text:
Q: Multipart form-data posting using Apache HttpClient not working I'm trying to post to my website using a java desktop application. I used Apache HttpClient to make the post request and Jsoup to do some parsing after.
This is the form on my website:
<form name="item" action="http://example.com/index.php" method="post" enctype="multipart/form-data">
   <input type="hidden" name="CSRFName" value="CSRF1142289289_807321318">
   <input type="hidden" name="CSRFToken" value="2db57fc741cdb8c1b02a2f485508def7796162f5eebdd9f7d0ce9fd9aabb39ecd5df8c63a46560ae540ed9f26c40fdd33f0285e7b1f2ef18bc4b760ad3da4ae8">
   <fieldset>
      <input type="hidden" name="action" value="item_add_post">
      <input type="hidden" name="page" value="item">
      <input id="catId" type="hidden" name="catId" value="">
      <select id="select_1" name="select_1" depth="1" class="valid">
         <option value="0">Selectează categoria</option>
         <option value="108">Cazare si Pensiuni</option>
         <option value="105">Transport si Turism</option>
      </select>
      <input id="titlero_RO" type="text" name="title[ro_RO]" value="">
      <textarea id="descriptionro_RO" name="description[ro_RO]" rows="10" class="uniform"></textarea>
      <input id="price" type="text" name="price" value="">
      <select name="currency" id="currency">
      <option value="EUR">euro</option>
         <option value="RON" selected="selected">lei</option>
         <option value="USD">dollar</option>
      </select>
      <input type="file" name="photos[]">
      <select name="regionId" id="regionId">
         <option value="">Regiunea</option>
         <option value="782153">Alba</option>
      </select>
      <select name="cityId" id="cityId" disabled="disabled">
         <option value="">Orasul</option>
         <option value="462667">Abrud</option>
      </select>
      <input id="cityArea" type="text" name="cityArea" value="">
      <input id="cityAreaId" type="hidden" name="cityAreaId" value="">
      <input id="contactName" type="text" name="contactName" value="">
      <input id="contactEmail" type="text" name="contactEmail" value="">

Publică<button type="submit">Publică</button>

   </fieldset>
</form>

Of course i've removed some stuff from it such as divs, css for this, I kept the minimum.
If I submit the form through my browser the actual data sent is this one:
Remote Address:xx.xxx.xx.xxx:80
Request URL:http://example.com.ro/index.php
Request Method:POST
Status Code:302 Moved Temporarily
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,lzma,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:2398
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarybWBRwGAP2qS2vOYX
Cookie:_ugtopperm=1; b620f=last_submit_item%261406384018; _ugtopsecure=1;         osclass=f8e8a642a5d853ef3ca332a44604b975
Host:example.com.ro
Origin:http://example.com.ro
Referer:http://example.com.ro/adauga
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)     Chrome/36.0.1985.125 Safari/537.36 OPR/23.0.1522.60
Request Payload
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="CSRFName"

CSRF1142289289_807321318
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="CSRFToken"

2db57fc741cdb8c1b02a2f485508def7796162f5eebdd9f7d0ce9fd9aabb39ecd5df8c63a46560ae540ed9f26c40fdd33f0285e7b1f2ef18bc4b760ad3da4ae8
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="action"

item_add_post
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="page"

item
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="catId"

98
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="select_1"

98
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="title[ro_RO]"

This is the ad title
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="description[ro_RO]"

This is the ad description lots of text etc...
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="price"

5
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="currency"

RON
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="photos[]"; filename=""
Content-Type: application/octet-stream

------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="regionId"

782162
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="cityId"

463357
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="cityArea"

0123457617
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="cityAreaId"

------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="contactName"

nic
------WebKitFormBoundarybWBRwGAP2qS2vOYX
Content-Disposition: form-data; name="contactEmail"

nicolae_aldea@yahoo.com
------WebKitFormBoundarybWBRwGAP2qS2vOYX--
Response Headersview source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Wed, 30 Jul 2014 13:41:38 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=3, max=100
Location:http://example.com.ro/prestari-servicii
Pragma:no-cache
Server:Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
Set-Cookie:b620f=last_submit_item%261406727698; expires=Thu, 30-Jul-2015 13:41:38 GMT;     path=/
X-Powered-By:PHP/5.3.28

And it works ok. After I click the Publish button (in the browser) I get redirected from /adauga to /prestari-servicii where I can see that ad I just typed.
Now I tried to mimic the same thing in java using Apache HttpClient
package abcd;

import java.io.File;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class Test {
    public static void main(String[] args) throws Exception {
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient client = HttpClients.custom()
            .setDefaultCookieStore(cookieStore).build();

        //trying to get the cookies if any?!
        HttpGet get = new HttpGet("http://example.com.ro/adauga");
        get.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        get.setHeader("Accept-Encoding", "gzip,deflate,lzma,sdch");
        get.setHeader("Accept-Language", "en-US,en;q=0.8");
        get.setHeader("Cache-Control", "max-age=0");
        get.setHeader("Connection", "keep-alive");
    /* HERE IS THE PART I THINK IT MESSES UP
        get.setHeader("Cookies", what should i set here? is the job done by client
    having the cookieStore set??
    */
        get.setHeader("Host", "example.com.ro");
        get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36 OPR/23.0.1522.60");
        CloseableHttpResponse response1 = client.execute(get);

        List<Cookie> cookies = cookieStore.getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        response1.close();

        //my site uses CSRF protection in the form so first I take these using Jsoup
        Document html = Jsoup.connect("http://example.com.ro/adauga").get();
        String CSRFName = html.getElementsByAttributeValue("name", "CSRFName").get(0).val();
        String CSRFToken = html.getElementsByAttributeValue("name", "CSRFToken").get(0).val();

        File image = new File("C:\\Users\\DESKTOP\\Desktop\\Capture.PNG");
        FileBody photos = new FileBody(image, ContentType.APPLICATION_OCTET_STREAM);

        StringBody csrfName = new StringBody(CSRFName, ContentType.MULTIPART_FORM_DATA);
        StringBody csrfToken = new StringBody(CSRFToken, ContentType.MULTIPART_FORM_DATA);
        StringBody action = new StringBody("item_add_post", ContentType.MULTIPART_FORM_DATA);
        StringBody page = new StringBody("item", ContentType.MULTIPART_FORM_DATA);
        StringBody catId = new StringBody("98", ContentType.MULTIPART_FORM_DATA);
        StringBody select_1 = new StringBody("98", ContentType.MULTIPART_FORM_DATA);
        StringBody title = new StringBody("Sample title text etc", ContentType.MULTIPART_FORM_DATA);
        StringBody description = new StringBody("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", ContentType.MULTIPART_FORM_DATA);
        StringBody price = new StringBody("2", ContentType.MULTIPART_FORM_DATA);
        StringBody currency = new StringBody("RON", ContentType.MULTIPART_FORM_DATA);
        StringBody regionId = new StringBody("782162", ContentType.MULTIPART_FORM_DATA);
        StringBody cityId = new StringBody("463357", ContentType.MULTIPART_FORM_DATA);
        StringBody cityArea = new StringBody("0123577617", ContentType.MULTIPART_FORM_DATA);
        StringBody cityAreaId = new StringBody("", ContentType.MULTIPART_FORM_DATA);
        StringBody contactName = new StringBody("Garry", ContentType.MULTIPART_FORM_DATA);
        StringBody contactEmail = new StringBody("bogus@email.abc", ContentType.MULTIPART_FORM_DATA);

        HttpPost post = new HttpPost("http://example.com.ro/index.php");
        post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        post.setHeader("Accept-Encoding", "gzip,deflate,lzma,sdch");
        post.setHeader("Accept-Language", "en-US,en;q=0.8");
        post.setHeader("Cache-Control", "max-age=0");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "multipart/form-data");
    //again, I think i'm doing something wrong here. Am I supposed to set
    //boundary as this??
        post.setHeader("boundary", generateBoundary());
    //should i set cookies after? if so, how?!
        post.setHeader("Host", "example.com.ro");
        post.setHeader("Origin", "http://example.com.ro");
        post.setHeader("Referer", "http://example.com.ro/adauga");
        post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36 OPR/23.0.1522.60");

        HttpEntity entity = MultipartEntityBuilder.create()
                .addPart("CSRFName", csrfName)
                .addPart("CSRFToken", csrfToken)
                .addPart("action", action)
                .addPart("page", page)
                .addPart("catId", catId)
                .addPart("select_1", select_1)
                .addPart("title[ro_RO]", title)
                .addPart("description[ro_RO]", description)
                .addPart("price", price)
                .addPart("currency", currency)
                .addPart("photos[]", photos)
                .addPart("regionId", regionId)
                .addPart("cityId", cityId)
                .addPart("cityArea", cityArea)
                .addPart("cityAreaId", cityAreaId)
                .addPart("contactName", contactName)
                .addPart("contactEmail", contactEmail)
                .build();

        post.setEntity(entity);

        CloseableHttpResponse response = client.execute(post);
        System.out.println("After executing the post request... :" + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine());

        String htmlPageResponse = EntityUtils.toString(response.getEntity());
        System.out.println();
        System.out.println(htmlPageResponse);
        response.close();
        client.close();
    }

    protected static String generateBoundary() {
        StringBuilder buffer = new StringBuilder();
        Random rand = new Random();
        int count = rand.nextInt(11) + 30; // a random size from 30 to 40
        for (int i = 0; i < count; i++) {
        buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }
        return buffer.toString();
   }

    private final static char[] MULTIPART_CHARS =
        "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
         .toCharArray();
}

After I run this I get
    200 - HTTP/1.1 200 OK
Instead of 302 as I get when I use the browser. I also checked the html response and it was the original index.php page instead of the redirect where I was supposed to view my just entered message.
So did I set the cookies right? Or I messed something in the request headers? Like the boundary etc. I had this problem for a week almost. I tried every single httpclient multipart example but they don't seem to work with a "real world" website.
Thank you!

A: Have you tried to compare the request you created using Apache HttpClient with the one you posted above? Doing so, you could easily check if the two are really the same, and whether you did something wrong or not in setting the cookies.
To view the request before executing it you can print it before executing it.
Try System.out.println(get.toString()); or alternatively, you can use HttpMessage's method -getFirstHeader("cookie") to look into the Header you set.
But in order to mimic the actual request, I guess you should create a Cookie object and then use methods from SetCookie Interface to set it accordingly to Cookie:_ugtopperm=1; b620f=last_submit_item%261406384018; _ugtopsecure=1;. At that point, you can use cookieStore.addCookie(Cookie cookie) method just after BasicCookieStore cookieStore = new BasicCookieStore();
I haven't never done this myself. But this is what I understood by taking a look to the APIs. I hope this might be of some help.


text:
Q: How do I add a Watch or Inspect in Xcode? as in the title is there a way in Xcode to Add Watch or Inspect a code segment in Xcode
for example how can I see the result of [myObject aMethod] with actually stepping over or Stepping in.

A: To actually see the value change while you step through, you can right click the watch list of the debug area and choose "Add Expression..."

A: In the debugger console, if you stop at a breakpoint you can type po [myObject aMethod] to see the return value (if it's not an id type return value, use p ([return type here])[myObject aMethod]).
You can also set a breakpoint action to print something out without pausing, just right click to edit the breakpoint:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I overlay the coordinates of variables of one PCA over the coordinates of individuals from a second PCA and still interprete the results? I do have two sets of data: Abundance data and environmental data and need to "link" them or "overlay" them in a PCA:
I want to conduct a PCA in R which gives me the individuals Ciliate species as Individuals and the environmental parameters as variables.
What I do have are two different dataframes.
"abundance"  where the abundance of the different species at the sampled sites are given and
"environment" where the environmental parameters of the sampled sites are given. So I have one parameter in common in eacht dataframe: the sites!
If i conduct PCAs I either get a plot with the sites as individuals and the environmental parameters as variables or a plot with the species as individuals and the sites as variables. What I need, would be to link the datasets by the parameter site so that I can conduct a PCA with the ciliate species as individuals ans the environmental parameters as variables. So i would somehow need to link the two PCAs/dataframes over the common parameter site.
What I did so far- i did two different PCAs and rememberd the coordinates of the individuals (ciliate species) of PCA1 and the coordinates of the variables of PCA2 (environmental parameters) and biploted them-> The graph is exactly what I would need, but is it still interpretable as a PCA, so the dataframes really linked by the site parameter?
Or did simply trick with the data and loose the interpretability?
Another option I tried is to calculate the environmental paramteres of each ciliate species by weighted mean (weighted by the abundance of the ciliates at the site) and conduct a PCA on a dataframe with ciliate species and the weighted mean of the environmental parameters...Which works but I think I loose a lot of information on this way...What do you think?
#Create random dataframe of abundance data, I am sure this can be done simpler and more elegant than this ;)
    species<-c("spec1", "spec2", "spec3", "spec 4", "spec 5", "spec 6", "spec7")
    site1<-c(2,4,19,34,3,6,9)
    site2<-c(5,8,9,12,0,1,1)
    site3<-c(23,56,7,1,1,1,2)
    site4<-c(4,6,2,8,5,1,7)
    abundance<-data.frame(species,site1,site2,site3,site4)
    rownames(abundance)<-abundance$species
    abundance<-abundance[,-1]
    #Create random dataframe of abundance data
    #environmental parameters of the sites
    X<-c("site1","site2","site3","site4")
    Temp<-c(24,24.5,23.5,25)
    Chla<-c(2.2,1.5,2.0,3.4)
    Plo<-c(1000,2000,1500,200)
    Plo2<-c(200,400,600,200)
    environment<-data.frame(X,Temp,Chla,Plo,Plo2)
    rownames(environment)<-environment$X
    environment<-environment[,-1]
    ###PCA on abundance data
    #hellinger pre-transformation of abundance data
    library(vegan)
    abu.h<-decostand(abundance,"hellinger")
    abu.h.pca<-prcomp(abu.h)
    envir.pca<-prcomp(environment,scale=TRUE)
    biplot(abu.h.pca)
    ##and now I would need to discard the sites vectors and overlay it with
    #the environmental sites factors, due to my prof?
    #Graph of individuals
    fviz_pca_ind(abu.h.pca)
    ##get coordinates
    library(factoextra)
    ind<-get_pca_ind(abu.h.pca)
    head(ind$coord)
    #x in biplot
    ind<-ind$coord
    ind<-ind[,1:2]
    ind
    #y variables
    # Extract the results for variables only

    vari<-get_pca_var(abu.h.pca)
    var<-vari$coord
    var<-var[,1:2]
    var
    biplot(ind, var, var.axes = TRUE)

A: I've never done what you're describing, but I know you can do a relate to the environmental (abiotic) data with vector overlays on top of an nMDS. If you can do that with a PCA, I'm not sure, but at least my PRIMER manual mentions that a PCA of abiotic data using Euclidean distance is a good fit with an nMDS of the biotic data, and is how PRIMER's BEST function works. But this isn't PRIMER.
See the vegan::envfit function. The intro vignette covers it briefly. Vegan tutor covers it a bit more.
I transposed the species data and did it using an nMDS of the species data.
library(vegan)

species <-c ("spec1", "spec2", "spec3", "spec 4", "spec 5", "spec 6", "spec7")
site1 <- c(2,4,19,34,3,6,9)
site2 <- c(5,8,9,12,0,1,1)
site3 <- c(23,56,7,1,1,1,2)
site4 <- c(4,6,2,8,5,1,7)
abundance <- data.frame(species,site1,site2,site3,site4)
rownames(abundance) <- abundance$species
abundance <- abundance[,-1]
abundance <- t(abundance)

X <- c ("site1","site2","site3","site4")
Temp <- c(24,24.5,23.5,25)
Chla <- c(2.2,1.5,2.0,3.4)
Plo <- c(1000,2000,1500,200)
Plo2 <- c(200,400,600,200)
environment <- data.frame(X,Temp,Chla,Plo,Plo2)
rownames(environment) <- environment$X
environment <- environment[,-1]

AbEnvMDS <- metaMDS(abundance, k = 2)
AbEnvFit <- envfit(AbEnvMDS, environment)

plt <- plot(AbEnvMDS) # displays both sites (empty circles) and species (red +)
plt <- plot(AbEnvMDS, display = "species") # displays only species (red +)
plt
identify(plt, what = "species") # choose your points
plot(AbEnvFit) # overlays your environment


text:
Q: Using Nant to build and deploy asp.net, vb.net , framework 1.1 How can I use properly Nant to build and deploy an asp.net project developed using asp.net , vb.net and .net framework 1.1?
I tried with this build file:
<?xml version="1.0" ?>
<project name="MyWebProj" default="build" basedir=".">
    <description>...</description>
    <property name="debug" value="true" overwrite="false"
    />
    <property name="basename" value="MyWebProj" />
    <target name="build">
        <mkdir dir="NantBIN" />
        <vbc target="library" output="NantBIN/${basename}.dll" debug="${debug}">
            <sources>
                <include name="*.vb" />
            </sources>
        </vbc>
    </target>
</project>

And I run this bat file:
@echo off bin\nant -t:net-1.1 -buildfile:.MyWebProjPath pause

A: You can refer below links which explain step by step process for you.
http://www.codeproject.com/Articles/123713/Automate-Publishing-a-WebSite-into-IIS-using-MSDep
https://web.archive.org/web/20211020150759/https://www.4guysfromrolla.com/articles/120104-1.aspx

A: First of all, thank you for all the answers and advices.
This is how I finally resolved the problem.I use this as the build file:
<?xml version="1.0"?><project name="..." default="rebuild" basedir=".">
<target name="rebuild" depends="build">
    <call target="build.copy"/>
</target>
<target name="build" description="Build all targets.">
    <call target="build.project"/>
</target>
<target name="build.project">
    <solution configuration="${configuration}" solutionfile="${solutionName}" outputdir="${expected.output}">
        <webmap>
            <map url="${webproj.url}" path="${webproj.name}" />
        </webmap>
    </solution>
</target>
<target name="build.copy">
    <copy  todir="${path.to.deploy}" overwrite="true">
        <fileset basedir=".">
            ...
            <include name="**\*.asp" />
            <include name="**\*.aspx" />
            <include name="**\*.css" />
            <include name="**\*.js" />
            ...
        </fileset>
    </copy>
</target>

And I run this bat file (is important to set -t:net-1.1 to specify the .net framework version ):
bin\nant -t:net-1.1 -buildfile:.MyWebProjPath


text:
Q: Modelling best practices with Grakn I've looked at how to do data modelling and have some questions in regards to the use of roles specifically in Grakn.
Let's take a simple case. I have a Company, and that Company can be a Distributor, Supplier, Customer, or any such combination. Company A could be a distributor and a customer at the same time.
If I use a relational database, I would have a table for CompanyS and then tables for SupplierS, CustomerS, etc, which then would reference the Company table.
However, I want to start with a Company and know what roles it is playing without having to create these extra tables. So that in my application I can know that a company is both a distributor and a supplier in a single query.
There's a few ways I can think how to do it, but as I feel this problem domain is so common there must be some best practices for modelling these concepts.
So I am looking for common patterns or strategies to model and name certain entity roles. I am using Grakn. Any help is appreciated.

A: If I understand right, you mean to ask for general rules of thumb for choosing roles. Choosing roles is also caught up in choosing the naming for your relations, entities and attributes. In the case given, company is ubiquitously modelled as an entity, but there are plenty of examples where you may realise that you had the naming for an entity/relation/role mixed up.
Try this for general guidance:
Entity: Should be capable of its own existence in the world. Can be an abstract concept. Use abstract nouns (company, religion), collective nouns, common nouns.
Relation: Should have existence dependent upon the existence of its role players. Use abstract nouns (marriage, membership, hierarchy) and verbal nouns (authorship, ownership, ).
Role: Should describe a behaviour within the context of a relation. You can try using this sentence: A [entity] behaves like a [role] in a [relation]. For example a station behaves like a stop in a train-route. Should use nouns.
Attributes: Should describe a quantity only e.g. name (string), age (long), colour (string), is-green (boolean), verbose (boolean), is-running (boolean), score (double). Typically nouns or verbs. Anything goes if it describes a value well.
If you struggle to find a noun, use a name that ends with a noun, but prepend with a descriptive term, like authored-book.

A: At times it may be easier to think of relations in terms of verbs too -- as long as they are gerund tense. For example:

faceting sub relation,
   relates facet-assignment,
   relates assigned-facet.

listing sub relation,
   relates list-assignment,
   relates assigned-list.


text:
Q: How to compute Pricing of Product & Options based on User Option Selection and Pricing per Option I am building a service for pricing options of a product and for pricing the product itself when product has various options.
Example
User selects some X options out of Y options available, where X <= Y.  The service then computes the pricing from selected options using cost for those options.
Using Pseudocode, it goes something like this:
$totalPrice = 0;

//number of modules comes from user input OR can be derived from it
//price per module comes from database
$productPrice = [PRICE FOR A MODULE] * [NUMBER OF MODULES];

$totalPrice += $ProductPrice;

//option 1 selection comes from user input
if ([OPTION ONE IS SELECTED])
     $totalPrice += [PRICE FOR OPTION ONE]

Question:
How can I decide who deals with options and who deals with pricing?
For example, I can inject selected options into a Pricing class but that complicates Pricing, since now business logic inside Pricing class needs to be aware of selected options and how to use them to compute the price.
Perhaps I can have a class for just options, and another class for just pricing, and then some kind of a third "Combiner" class that knows how to combine options and pricing to come up with final totals.  But won't that be too complicated?
Is there a model for this sort of thing?
General Problem Statement
A more general problem is --
Given

*

*A) User Input (i.e. Add-on Options)

*B) Product Specifications (i.e. number of product sub-parts) which can be derived elsewhere from user input and its own service

*C) Pricing for sub-parts, Pricing for Options

Compute total Product price.
How can I do this in OO?

A: Code is C# pseudocode.
A Word about MVC
The domain model is unconcerned with trasformations at the seams of MVC. That is we don't care how the data is going to get from the UI to the business classes to the data store (and back). A good domain model is the fixed reference around which all the doing-stuff and MVC transmuting code evolves.

Summary
Looks like a lot? No. Appropriate classes makes coding easy and the resulting code simple. How? Single Responsibility Principle and encapsulation.

*

*Big Ideas

*

*Structure

*

*A domain model is the central focus

*Coherent objects get created from UI selections

*Coherent objects get created from data-source

*Custom Collections

*

*Single Responsibility Principle at play, i.e. A place to put collective functionality

*Pricing API

*

*"Price" is calculated dynamically.

*

*sales, promotions, option packages

*"Cost" is fixed. MSRP essentially.

*Easy, idiot-proof for the client

*Fanatically hide all details from the API clients.

*Patterns, at least conceptually

*

*Visitor

*

*A PriceRule knows what Product properties to use.

Domain Data Structures
Design a model that makes sense so that it is easy to access and is stable as the cost/pricing algorithm and code evolves.
public class Product {
    var Id;
    var Cost;  // MSRP. Before the kibitzing begins.
    // No Price property. Will dynamically calc.
    // My design decision. You can do otherwise.
    var Options;

    // MSRP. No price adjusting.
    public Decimal GetCost { return this.Cost + this.Options.GetCost(); }

    // The visitor pattern.
    public void GetPrice ( PricingCollection adjustments) {
        if(adjustments == null) return this.GetCost();

        return adjustments.Apply(this);
    }
}

public class Option {
    var Id;
    var Cost;  // MSRP
    bool Discontinued;  // don't show it on the UI if it is.
}

public class OptionCollection {
    var Options;  // Add() method not shown

    public decimal GetCost() {
        var total = 0;

        foreach (var option in Options)
            total += option.Cost;

        return total;
    }
}

Product-Options
    public ProductOptions : Dictionary<Product, OptionCollection>

Populated from a data-store at program initialization time.
The complete set of product-options and can be used in the UI. Change the data-store of course changes the available options for the user.
Removing options after being selected for a product is a requirements issue. I would think you fill existing product orders with now discontinued options.

Pricing

Perhaps I can have a class for just options, and another class for just pricing,

Built into a separate set of classes. We inject the "pricing model" into the Product and the "pricing model" knows how to adjust costs to come up w/ a final, total price.
For example "Buy option X and get option Y at half price." Or "$3,OOO off of our Texas Tough truck, San Jacinto Day only."
I'm not going to argue "interface" vs "abstract class". Client code cares about API, not its implementation.
public abstract class PriceRule {
    // Sub classes must implement this method
    // As complex as your sales gimmic demands.
    public abstract Decimal Apply (Product thisProduct);
}

PriceRule must know the domain model structure. That's OK. That is the idea of the Visitor design pattern.
The PriceRule API implies (for the domain model) that an OptionCollection can exist only w/in a Product object. I like that because it keeps our structure(s) consistant - it always belongs to some Product object. Unless requirements dictate otherwise of course.
 public class PriceRuleCollection {
    var PriceRules; // Add() method not shown

    public Decimal Apply (Product thisProduct) {
        var total = 0;
        foreach (var rule in PriceRules)
            total = rule.Apply(thisProduct);

        return total;
    }
  }

and then some kind of a third "Combiner" class that knows how to combine options and pricing to come up with final totals. ...  But won't that be too complicated?

Just the opposite! You may think it too trivial, but it has 2 important purposes.

*

*It declares the concept of a "pricing model" explicitly. The term is part of the business we're coding for. We can talk and code in our customers' terms.

*A place to add code at the "pricing model" level of abstraction. We can manipulate the order of price rule application. We can add new concepts like financing.

.
public class PricingModel{
    public PricingModel( PriceRuleCollection pricing, Product product, ProductOptions allOptions ) {
        this.Pricing = pricing;
        this.Product = product;
        this.ProductOptions = allOptions;   // might be handy. We everything in one place.
    }

    public Decimal TotalPrice() {
        return this.pricing.Apply(this.product);
    }
  }

A: Personally I would go with your idea of a third class. To me, this seems most consistent with an MVC (Model, View, Controller) pattern. If I understand correctly, an option (or Module) has a price property. This is part of your model.  A user makes selections -- this is something that happens in your view. When it comes time to calculate a total based on a user's selection, this should be the job of your controller. In other words, the controller asks the view, "what has the user selected?" and gets a list of selections; the controller then queries the database/model and asks "what does each of these selected options cost?" and maps these selections to prices. It then has all the information it needs to perform the calculation, in which it asks itself "what is the total cost of all these options?" -- and then sends that information back to the view to be displayed to the user. To extend this whole use case to completion, if the user then interacts with the view and agrees to go ahead with their purchase, then the controller can go back to the model and have it create an order entity, and update the "number sold" property on each option/module, and whatever else you might want to do as part of your business logic.
As a rule, business logic lives in the controller. Entities, and information about entities, lives in the model. Raw user input, and what is displayed back to the user, belongs in the view. This isn't more complicated - you might have more 'parts', but each part has a clearly defined role, and it's much simpler to make changes to any of these parts while the rest remain the same. You could, for example, change the way everything is presented to the user as much as you like, and not even have to look at/touch/have access to the model or controller components. Likewise, if you wanted to rewrite the whole app, but keep the same data regarding available modules/options, all you need to do is keep in mind how your data is structured when designing the new controller and view however you like.
It can seem a little counter-intuitive at first, but creating more components can make an application a lot easier to write, debug, and modify later. You already seem to understand this intuitively, in that you're thinking about what should be responsible for what - but luckily you don't need to make all these decisions for yourself in a vacuum, as there are already established patterns like 'MVC' which answer most of these questions for you.
A good rule of thumb is to keep all your business logic separate from everything else. A product on a shelf needs a price tag, it doesn't need its own cash register to ring up a sale. Make the module that handles your business logic independent, and you can do anything you like with it - reuse it to sell different products by plugging in a new model, or create a whole new method of interaction, e.g. API calls from another application, instead of your dedicated user interface.


text:
Q: Linux file inaccessible and has "?" permission I have a file that has some strange permissions on it:
[root@host var]# ls -la
total 248
drwxr-xr-x  32 root     root      4096 Nov 24 07:59 .
drwxr-xr-x  27 root     root      4096 Nov 23 20:13 ..
drwxr-xr-x   2 root     root      4096 Jun 17  2008 account
drwxr-xr-x   3 root     root      4096 Jun 17  2008 antiword
drwxr-xr-x   2 pcap     pcap      4096 Jun 17  2008 arpwatch
?---------   ? ?        ?            ?            ? backup
drwxr-xr-x  10 root     root      4096 Jun 17  2008 cache
drwxr-xr-x   2 root     root      4096 Nov 18 20:37 cpq
drwxr-xr-x   5 netdump  netdump   4096 Jun 17  2008 crash
drwxr-xr-x   3 root     root      4096 Jun 17  2008 db

The file in question is "backup". I have tried searching for some information on what could be causing this but unfortunately finding it hard to find relevant information. Running any commands against this file results in "Permission denied"
Anyone come across a file like this before? Any commands I could run to remove it or restore it?
Cheers,
Andy

A: maybe also this folder contains a mounted filesystem which suddenly became inaccessible.

A: I've seen silly things like this when there's filesystem corruption.  A fsck should sort that out in fairly short order.

A: above all I would suspect filesystem damage and do a fsck of the filesystem (in case of /var it first needs reboot into rescue mode).
If that won't help, please write what filesystem it is (as seen from mount command).


text:
Q: visibility and existence of an element in javascript I need to know if this is a good practice to check the visibility and existence of an element in javascript
if(document.getelementbyid("id") && document.getelementbyid("id").style.visibility=="visible")){}

A: Checking existence of element using document.getElementById is good practice since JavaScript will not throw an error if element does not exists on the page.
However, checking visibility is entirely dependent on the coding conditions.
Correct syntax:
if(document.getElementById("id") && document.getElementById("id").style.visibility == "visible"){}


text:
Q: Push forward is smooth for jet bundle I was reading M,Golubitsky & V.Guillemin's book Stable Mappings and Their Singularities ,in theorem 2.7 (page 40),needs to prove  the following fact:
If $h: Y \rightarrow Z$ is smooth, then $h_{*}: J^{k}(X, Y) \rightarrow J^{k}(X, Z)$ is smooth. If $g: X \rightarrow Y$ is a diffeomorphism, then $g^{*}: J^{k}(Y, Z) \rightarrow J^{k}(X, Z)$ is a diffeomorphism.
The book says it follows from the construction of a smooth structure on $J^k(X,Y)$.I try to prove it in detail taking the push forward for example,that is to show under the coordinate chart,The push forward is smooth.I don't know how to write it clear.


text:
Q: How to fix "pgadmin4-apache2" error in Ubuntu 18.04 command line installation When installing on Ubuntu 18.04 (bionic beaver), majority of packages I encounter an error involving "pgadmin4-apache2" that causes the installation to fail. What is causing this error and if it requires the re-installation of "pgadmin4-apache2" how do I go about this?
I tried installing the following packages, of which all failed:
pip3 install python-mysql
sudo apt install mysql-client-core-5.7
sudo apt-get install python3.7-dev libmysqlclient-dev

The error I am getting is the following:
Setting up pgadmin4-apache2 (4.5-1.pgdg18.04+1) ...
Traceback (most recent call last):
  File "setup.py", line 17, in <module>
    from pgadmin.model import db, User, Version, ServerGroup, Server, \
  File "/usr/share/pgadmin4/web/pgadmin/__init__.py", line 38, in <module>
    from pgadmin.setup import get_version, set_version
  File "/usr/share/pgadmin4/web/pgadmin/setup/__init__.py", line 12, in <module>
    from .db_upgrade import db_upgrade
  File "/usr/share/pgadmin4/web/pgadmin/setup/db_upgrade.py", line 11, in <module>
    import flask_migrate
  File "/usr/lib/python3/dist-packages/flask_migrate/__init__.py", line 8, in <module>
    from alembic import __version__ as __alembic_version__
  File "/usr/lib/python3/dist-packages/alembic/__init__.py", line 9, in <module>
    from . import context  # noqa
  File "/usr/lib/python3/dist-packages/alembic/context.py", line 1, in <module>
    from .runtime.environment import EnvironmentContext
  File "/usr/lib/python3/dist-packages/alembic/runtime/environment.py", line 2, in <module>
    from .migration import MigrationContext
  File "/usr/lib/python3/dist-packages/alembic/runtime/migration.py", line 12, in <module>
    from .. import ddl, util
  File "/usr/lib/python3/dist-packages/alembic/ddl/__init__.py", line 1, in <module>
    from . import postgresql, mysql, sqlite, mssql, oracle  # pragma: no cover
ImportError: cannot import name 'mysql'
dpkg: error processing package pgadmin4-apache2 (--configure):
 installed pgadmin4-apache2 package post-installation script subprocess returned error exit status 1
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Setting up libpython3.7:amd64 (3.7.1-1~18.04) ...
Setting up libpython3.7-dev:amd64 (3.7.1-1~18.04) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
Setting up zlib1g-dev:amd64 (1:1.2.11.dfsg-0ubuntu2) ...
Setting up libmysqlclient-dev (5.7.25-0ubuntu0.18.04.2) ...
Setting up python3.7-dev (3.7.1-1~18.04) ...
Processing triggers for libc-bin (2.27-3ubuntu1) ...
Errors were encountered while processing:
 pgadmin4-apache2

I'm not entirely sure why the installation of "pgadmin4-apache2" happenings every time as well.
In an attempt to solve this issue I did the following:
sudo apt-get purge pgadmin4-apache2

This failed to complete, but despite it's failure I attempted to reinstall "pgadmin4-apache2", but again encountered the error.
sudo apt-get install pgadmin4-apache2

...

ImportError: cannot import name 'mysql'
dpkg: error processing package pgadmin4-apache2 (--configure):
 installed pgadmin4-apache2 package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 pgadmin4-apache2
E: Sub-process /usr/bin/dpkg returned an error code (1)

This error is hindering me from installing any additional packages.


text:
Q: How to get a property used in a jquery plugin? Is that possible to get back a property that I pass as a paramter to a jQuery plugin.
Sample:
$("selector").pluginFunction({ prop1: "test"});

Then I want to further get this property value back.
something like
var x = $("selector").pluginFunction().giveMyValueBack().prop1;

Thanks!

A: As of i dont know what this plugin does you could append that value as data to the element itself.
Write:
$('selector').data('prop1', 'test');

Read:
$('selector').data('prop1');

Eventually this is overhead. But without knowing how and if the plugin stores that value its not that easy possible to answer.
Assuming your using jquery.

A: Try creating your plugin properties as a separate object, and then passing that object to the pluginFunction. For example.
var pluginData = { prop1: "test"};
$("selector").pluginFunction(pluginData);

Then you can always just refer to the pluginData object.
var prop1 = pluginData.prop1;


text:
Q: How do I fix the responsive css for iframes I am trying to embed two iframes side-by-side and have them resize with screen width. On screens smaller than 500px, I want the second iframe to "wrap" below the first, and both expand to nearly full width. What actually happens is on screens less than about 488px, the second iframe drops down but both stay the same width and stay in the same relative position (the second iframe stays to the right)
Here is my code so far:

.vimeo-wrapper {
        max-width: 1200px;
        position: relative;
        margin: 0 auto;
    }

    .vimeo-standard {
        float: left;
        height: 470px;
        width: 75%;
        border: 1px solid #000;
        margin: 1px;
    }
    .vimeo-chatbox {
        float: right;
        height: 470px;
        width: 24%;
        border: 1px solid #000;
        margin: 1px;
    }
    iframe {
        width: 100%;
        height: 100%;
    }

    *@media (max-width:750px) and (min-width:700px){
        .vimeo-standard {
            float: left;
            height: 294px;
            width: 74%;
            border: 1px solid #000;
            margin: 0 auto;
       }
       .vimeo-chatbox {
           float: right;
           height: 294px;
           width: 24%;
           border: 1px solid #000;
           margin: 0 auto;
       }
       iframe {
        width: 90%;
        height: 100%;
        }
    }

    *@media (max-width:699px) and (min-width:600px){
        .vimeo-standard {
            float: left;
            height: 252px;
            width: 74%;
            border: 1px solid #000;
            margin: 0 auto;
       }
       .vimeo-chatbox {
           float: right;
           height: 252px;
           width: 24%;
           border: 1px solid #000;
           margin: 0 auto;
       }
       iframe {
        width: 90%;
        height: 100%;
        }
    }
    *@media (max-width:599px) and (min-width:500px){
        .vimeo-standard {
            float: left;
            height: 210px;
            width: 74%;
            border: 1px solid #000;
            margin: 0 auto;
       }
       .vimeo-chatbox {
           float: right;
           height: 210px;
           width: 24%;
           border: 1px solid #000;
           margin: 0 auto;
       }
       iframe {
        width: 90%;
        height: 100%;
        }
    }
    *@media (max-width:499px) {
        .vimeo-standard {
            float: none;
            height: 200px;
            width: 100%;
            border: 1px solid #000;
            margin: 2px auto;
            padding-bottom: 10px;
       }
       .vimeo-chatbox {
           float: none;
           width: 100%;
           height: 200px;
           border: 1px solid #000;
           margin: 2px auto;
           padding-top: 5px;
       }
       iframe {
        width: 90%;
        height: 100%;
        }
    }

    .clearfix:before,
    .clearfix:after {
        content: " "; /* 1 */
        display: table; /* 2 */
    }

    .clearfix:after {
        clear: both;
    }

A: Your code actually looks fine, the problem is the * characters you've put before your @media queries (this isn't valid CSS). Removing them makes everything work for me:

.vimeo-wrapper {
  max-width: 1200px;
  position: relative;
  margin: 0 auto;
}

.vimeo-standard {
  float: left;
  height: 470px;
  width: 75%;
  border: 1px solid #000;
  margin: 1px;
}

.vimeo-chatbox {
  float: right;
  height: 470px;
  width: 24%;
  border: 1px solid #000;
  margin: 1px;
}

iframe {
  width: 100%;
  height: 100%;
}

@media (max-width:750px) and (min-width:700px) {
  .vimeo-standard {
    float: left;
    height: 294px;
    width: 74%;
    border: 1px solid #000;
    margin: 0 auto;
  }
  .vimeo-chatbox {
    float: right;
    height: 294px;
    width: 24%;
    border: 1px solid #000;
    margin: 0 auto;
  }
  iframe {
    width: 90%;
    height: 100%;
  }
}

@media (max-width:699px) and (min-width:600px) {
  .vimeo-standard {
    float: left;
    height: 252px;
    width: 74%;
    border: 1px solid #000;
    margin: 0 auto;
  }
  .vimeo-chatbox {
    float: right;
    height: 252px;
    width: 24%;
    border: 1px solid #000;
    margin: 0 auto;
  }
  iframe {
    width: 90%;
    height: 100%;
  }
}

@media (max-width:599px) and (min-width:500px) {
  .vimeo-standard {
    float: left;
    height: 210px;
    width: 74%;
    border: 1px solid #000;
    margin: 0 auto;
  }
  .vimeo-chatbox {
    float: right;
    height: 210px;
    width: 24%;
    border: 1px solid #000;
    margin: 0 auto;
  }
  iframe {
    width: 90%;
    height: 100%;
  }
}

@media (max-width:499px) {
  .vimeo-standard {
    float: none;
    height: 200px;
    width: 100%;
    border: 1px solid #000;
    margin: 2px auto;
    padding-bottom: 10px;
  }
  .vimeo-chatbox {
    float: none;
    width: 100%;
    height: 200px;
    border: 1px solid #000;
    margin: 2px auto;
    padding-top: 5px;
  }
  iframe {
    width: 90%;
    height: 100%;
  }
}

.clearfix:before,
.clearfix:after {
  content: " ";
  /* 1 */
  display: table;
  /* 2 */
}

.clearfix:after {
  clear: both;
}


text:
Q: great ancestor & great great ancestor 1/ I have rule checker that forbid elements depending on a xpath expression.
2/ Every "test" element can contain a "test" element recursivly
3/ I want to forbid the "non usage" of an attibute for the firsts 3 "test" elements
Exemple:
<test targetAttribute="level 1">
   <test targetAttribute="level 2">
      <test targetAttribute="level 3">
         <test targetAttribute="level 4">
            <test targetAttribute="level 5">
            </test>
         </test>
      </test>
   </test>
</test>

targetAttribute attribute is mandatory for the firsts 3 levels only all other descendant element from level3 have their targetAttribute optionnal.
Here are my xpath:
//test[not(targetAttribute)]/ancestor[1]::test (level1)
//test[not(targetAttribute)]/ancestor[2]::test (level2)
//test[not(targetAttribute)]/ancestor[3]::test (level3)

But it doesn't work ! I also tried without success:
//test/ancestor[1]::test[not(targetAttribute)]

I'm becoming crazy @_@ can someone help me plz ?

A: In order to select an attribute you need to use @ before the attribute name. So
//test[not(targetAttribute)]
should be changed to
//test[not(@targetAttribute)]
and it will get all the test elements that do not contain this @targetAttribute.
Second thing.
When you want to select the first closest ancestor test you should use index after the test, like so:
/ancestor::test[1]

this will select the closes ancestor that is test (immediate parent in this case).
/ancestor::test[2]

will give you the grandparent and 3 will produce grand-grand parent.
Also you should probably filter out ancestors that don't have @targetAttribute
Not sure what exactly you are trying to accomplish, but just a try:
//test[not(@targetAttribute)]/ancestor::test[@targetAttribute][3] (level1)
//test[not(@targetAttribute)]/ancestor::test[@targetAttribute][2] (level2)
//test[not(@targetAttribute)]/ancestor::test[@targetAttribute][1] (level3)


text:
Q: How does string theory relate superposition and general relativity? So I know that in general relativity, superposition cannot be true. However, since string theory supposedly connects quantum mechanics and gravity, how does it relate superposition and gravity?

A: Theories that allow for superpositions of space being curved in different ways have all of their inconsistencies show up at high energies. The new degrees of freedom which come to the rescue in string theory become less important at low energies thereby leading to a theory which looks like a supersymmetric analogue of general relativity. A large research area focuses on building models where the same can be said about ordinary general relativity.
The situation should be morally similar to Fermi's theory of beta decay. Even though it was useful for many things, it could not be formally reconciled with the idea of superpositions due to a UV catastrophe. This changed with the discovery of the W boson leading to a much nicer theory whose IR behaviour still matched that of Fermi.

A:
So I know that in general relativity, superposition cannot be true.

General Relativity is a classical theory, and is not  quantized yet, its quantization is a  matter of current research, and string theories are part of this research.

However, since string theory supposedly connects quantum mechanics and gravity, how does it relate superposition and gravity?

String theories are quantum mechanical theories and all the concepts of quantum mechanics are within those models.If a string theory is successful in modeling the data and observations  it will be also including a quantization of general relativity, which will follow the rules of superposition in quantum mechanics.

A: Unlike what you may hear in many places, we have a perfectly good theory of quantum gravity: you just treat general relativity as a quantum field theory! Now, it's true that the result is non-renormalizable. But that just means that it only gives useful predictions below a certain energy scale $\Lambda$, or for distance scales longer than some length $\Lambda^{-1}\sim \sqrt{\hbar G_N}$. We call this an "effective theory".
That theory deals perfectly well with superposition. The result is much the same as any other quantum theory: the dynamical variables can be in a superposition of different states. In gravity, the dynamics describes the geometry of spacetime. So spacetime can be in a superposition of different geometries!
String theory is more complete (it gives predictions even at the very short distances where the above description fails), but for the purposes of this question all you need to know is that at long distances or low energies it gives the quantum theory of GR described above. So in string theory too, spacetime can be in a state with a superposition of different geometries.


text:
Q: Coding cmd.exe from a windows shortcut file I'm running cmd.exe code directly from within a windows shortcut .lnk file rather than in .bat text file; example:
%COMSPEC% /Q /V:ON /C "SET QUERY=StackOverflow && ECHO Hello !QUERY!"

Noting, the reason I'm running code like this is due to group policy restrictions.  So I've been learning the joys of single-line coding with only 260 available characters! :)
And I'm looking for an equivalent to %0 in batch files that can return me the source file of the shortcut itself? Or at least the folder it started in?
Noting I can't just simply just set the shortcut's 'Start In' directory, because I want to retain the original %CD% that called the shortcut.
I don't think it's even possible.  But if anyone at least has any good general tips for single-line coding then please share!

A: This is only a partial answer.  But I was able to get the equivalent to %~n0 (i.e the name of the shortcut)
This works because when you call cmd.exe from a shortcut, the window title is equal to the shortcut's filename
Create a new shortcut file called 'getWinTitle' with the following command
%COMSPEC% /Q /C FOR /F "delims=: tokens=2" %G IN ('TASKLIST /FI "IMAGENAME eq cmd.exe" /FO "LIST" /V^|FIND "Window Title"') DO IF NOT "%G"==" N/A" IF NOT "%G"==" getWinTitle" ECHO %G

Then in your main shortcut code, you call the 'getWinTitle.lnk' file and store it's output as follows:
%COMSPEC% /Q /V:ON /C "(FOR /F "tokens=*" %G IN ('getWinTitle.lnk') DO SET _WT=%G)&ECHO !_WT!"

You could do this all in one shortcut, but it eats up a lot of the 260 character limit.  I found this article which describes how to increase the 260 character limit to 1096.  But I was unable to use this method, as it was also blocked under the group policy of my machine.

"The maximum target length can be extended though by creating the shortcut via a jscript making use of the 'WScript Shell' object. The GUI properties window will still clip the target field at two hundred sixty characters, but the 'WScript Shell' object will only clip the target parameter at one thousand ninety-six (1096) characters."
https://www.uperesia.com/booby-trapped-shortcut-generator


text:
Q: how to remove duplicates from string elements within a list? ['tthhee', 'zzeenn', 'ooff', 'ppyytthhoonn', 'bbyy', 'ttiimm', 'ppeetteerrss', 'bbeeaauuttiiffuull', 'iiss', 'bbeetttteerr', 'tthhaann', 'uuggllyy..', 'eexxpplliicciitt', 'iiss', 'bbeetttteerr', 'tthhaann', 'iimmpplliicciitt..', 'ssiimmppllee', 'iiss', 'bbeetttteerr', 'tthhaann', 'ccoommpplleexx..', 'ccoommpplleexx', 'iiss', 'bbeetttteerr', 'tthhaann', 'ccoommpplliiccaatteedd..', 'ffllaatt', 'iiss', 'bbeetttteerr', 'tthhaann', 'nneesstteedd..', 'ssppaarrssee', 'iiss', 'bbeetttteerr', 'tthhaann', 'ddeennssee..', 'rreeaaddaabbiilliittyy', 'ccoouunnttss..', 'ssppeecciiaall', 'ccaasseess', "aarreenn''tt", 'ssppeecciiaall', 'eennoouugghh', 'ttoo', 'bbrreeaakk', 'tthhee', 'rruulleess..', 'aalltthhoouugghh', 'pprraaccttiiccaalliittyy', 'bbeeaattss', 'ppuurriittyy..', 'eerrrroorrss', 'sshhoouulldd', 'nneevveerr', 'ppaassss', 'ssiilleennttllyy..', 'uunnlleessss', 'eexxpplliicciittllyy', 'ssiilleenncceedd..', 'iinn', 'tthhee', 'ffaaccee', 'ooff', 'aammbbiigguuiittyy,,', 'rreeffuussee', 'tthhee', 'tteemmppttaattiioonn', 'ttoo', 'gguueessss..', 'tthheerree', 'sshhoouulldd', 'bbee', 'oonnee----', 'aanndd', 'pprreeffeerraabbllyy', 'oonnllyy', 'oonnee', '----oobbvviioouuss', 'wwaayy', 'ttoo', 'ddoo', 'iitt..', 'aalltthhoouugghh', 'tthhaatt', 'wwaayy', 'mmaayy', 'nnoott', 'bbee', 'oobbvviioouuss', 'aatt', 'ffiirrsstt', 'uunnlleessss', "yyoouu''rree", 'dduuttcchh..', 'nnooww', 'iiss', 'bbeetttteerr', 'tthhaann', 'nneevveerr..', 'aalltthhoouugghh', 'nneevveerr', 'iiss', 'oofftteenn', 'bbeetttteerr', 'tthhaann', '*rriigghhtt*', 'nnooww..', 'iiff', 'tthhee', 'iimmpplleemmeennttaattiioonn', 'iiss', 'hhaarrdd', 'ttoo', 'eexxppllaaiinn,,', "iitt''ss", 'aa', 'bbaadd', 'iiddeeaa..', 'iiff', 'tthhee', 'iimmpplleemmeennttaattiioonn', 'iiss', 'eeaassyy', 'ttoo', 'eexxppllaaiinn,,', 'iitt', 'mmaayy', 'bbee', 'aa', 'ggoooodd', 'iiddeeaa..', 'nnaammeessppaacceess', 'aarree', 'oonnee', 'hhoonnkkiinngg', 'ggrreeaatt', 'iiddeeaa', '----', "lleett''ss", 'ddoo', 'mmoorree', 'ooff', 'tthhoossee!!']

How can we remove the duplicate letters from each string in the list ?

A: Assuming that the name of your list is words. Which defined like below for example:
words = ['tthhee', 'zzeenn', 'ooff', 'ppyytthhoonn', 'bbyy', 'ttiimm']

If order important for you, you can use following, It keeps the first of the repeating letters and deletes the next ones.:
new_list = [''.join(dict.fromkeys(word)) for word in words]

['the', 'zen', 'of', 'python', 'by', 'tim']

A: You can use dict.from_keys to ensure keeping unique letters while maintaining the order, and str.join to generate again a string:
[''.join(dict.fromkeys(x)) for x in input_list]

output:
['the', 'zen', 'of', 'python', 'by', 'tim', 'petrs',
 'beautifl', 'is', 'betr', 'than', 'ugly.',
 'explict', 'is', 'betr', 'than', 'implct.',
...
]

A: If I assume that you want to keep one letter and remove the following one, you can only take the "even index" of the word:
words = ['tthhee', 'zzeenn', 'ooff', 'ppyytthhoonn', 'bbyy']

corrected = [word[::2] for word in words]
print(corrected)

>> ['the', 'zen', 'of', 'python', 'by']

A: I have this solution:
your_list= ["".join(set(x)) for x in your_list]

output:
['eht',
'nez',
'of',
'toynhp',
'by',
'mti',
'rstep',
'atibeluf']


text:
Q: How does Scala's (2.8) Manifest work? I have some Scala code that makes fairly heavy use of generics, and I have gleaned from the docs that using a manifest in the parametrization constraints can help me work around the type erasure issues (e.g. I want to instantiate a new object of the generic type). Only, I'd like to understand more about how this works. It almost feels like some sort of hashmap that's getting an entry for every invocation site... Can anyone here elaborate?
class Image[T <: Pixel[T] : Manifest](fun() => T, size: Array[Int], data: Array[T]) {
    def this(fun: () => T, size: Array[T]) {
        this(fun, size, new Array[T](size(0) * size(1));
    }
}

This is something that doesn't seem to be covered in any of the documentation that I found on the site, and on Google I mostly get older posts that have very different syntax, and since 2.8 seems to have a lot of things changed, I'm not sure those are still accurate.

A: The "context bound" T ... : Manifest is syntactic sugar for an implicit argument: (implicit man: Manifest[T]). Thus at the point of instantiation of the type constructor specified by class Image, the compiler finds / supplies the Manifest for the actual type used for the type parameter T and that value "sticks with" the resulting class instance throughout its existence and "anchors" each particular instance of Image[Something] to the Manifest for its T.

A: It's been awhile since I dug through the source code for Scala in a quest to answer the same question... but the short answer, as I recall -
Manifest is a cheat code to allow the COMPILER to get around Type erasure (it isn't being used at runtime).  It causes multiple code paths to be generated at compile time for the possible input types matching the manifest.
The Manifest is resolved implicitly, but if there is any ambiguity at compile time about what the Manifest type is, the compiler WILL stop.
With a copy of a Manifest you have a few things available.  The main things you typically want is either the java.lang.Class that was erased via erasure:
class BoundedManifest[T <: Any : Manifest](value: T) {
  val m = manifest[T]
  m.erasure.toString match {
    case "class java.lang.String" => println("String")
    case "double" | "int"  => println("Numeric value.")
    case x => println("WTF is a '%s'?".format(x))
    }
}

class ImplicitManifest[T <: Any](value: T)(implicit m: Manifest[T]) {
  m.erasure.toString match {
    case "class java.lang.String" => println("String")
    case "double" | "int" => println("Numeric value.")
    case x => println("WTF is a '%s'?".format(x))
  }
}

new BoundedManifest("Foo Bar!")
// String
new BoundedManifest(5)
// Numeric value.
new BoundedManifest(5.2)
// Numeric value.
new BoundedManifest(BigDecimal("8.62234525"))
// WTF is a 'class scala.math.BigDecimal'?
new ImplicitManifest("Foo Bar!")
// String
new ImplicitManifest(5)
// Numeric value.
new ImplicitManifest(5.2)
// Numeric value.
new ImplicitManifest(BigDecimal("8.62234525"))
// WTF is a 'class scala.math.BigDecimal'?

This is a rather wonky example but shows what is going on.  I ran that for the output as well FWIW on Scala 2.8.
The [T ... : Manifest] boundary is new in Scala 2.8... you used to have to grab the manifest implicitly as shown in ImplicitManifest.  You don't actually GET a copy of the Manifest.  But you can fetch one inside your code by saying val m = manifest[T] ... manifest[_] is defined on Predef and demonstrably will find the proper manifest type inside a boundaried block.
The other two major items you get from a Manifest is <:< and >:> which test subtype/supertype of one manifest versus another.  If I recall correctly these are VERY naive implementation wise and don't always match but I have a bunch of production code using them to test against a few possible erased inputs.  A simple example of checking against another manifest:
class BoundedManifestCheck[T <: Any : Manifest](value: T) {
  val m = manifest[T]
  if (m <:< manifest[AnyVal]) {
    println("AnyVal (primitive)")
  } else if (m <:< manifest[AnyRef]) {
    println("AnyRef")
  } else {
    println("Not sure what the base type of manifest '%s' is.".format(m.erasure))
  }
}

new BoundedManifestCheck("Foo Bar!")
// AnyRef
new BoundedManifestCheck(5)
// AnyVal (primitive)
new BoundedManifestCheck(5.2)
// AnyVal (primitive)
new BoundedManifestCheck(BigDecimal("8.62234525"))
// AnyRef

Jorge Ortiz has a great blog post (albeit old) on this: http://www.scala-blogs.org/2008/10/manifests-reified-types.html
EDIT:
You can actually see what Scala is doing by asking it to print out the results of the erasure compiler phase.
Running, on my last example above scala -Xprint:erasure test.scala produces the following result:
final class Main extends java.lang.Object with ScalaObject {
  def this(): object Main = {
    Main.super.this();
    ()
  };
  def main(argv: Array[java.lang.String]): Unit = {
    val args: Array[java.lang.String] = argv;
    {
      final class $anon extends java.lang.Object {
        def this(): anonymous class $anon = {
          $anon.super.this();
          ()
        };
        class BoundedManifestCheck extends java.lang.Object with ScalaObject {
          <paramaccessor> private[this] val value: java.lang.Object = _;
          implicit <paramaccessor> private[this] val evidence$1: scala.reflect.Manifest = _;
          def this($outer: anonymous class $anon, value: java.lang.Object, evidence$1: scala.reflect.Manifest): BoundedManifestCheck = {
            BoundedManifestCheck.super.this();
            ()
          };
          private[this] val m: scala.reflect.Manifest = scala.this.Predef.manifest(BoundedManifestCheck.this.evidence$1);
          <stable> <accessor> def m(): scala.reflect.Manifest = BoundedManifestCheck.this.m;
          if (BoundedManifestCheck.this.m().<:<(scala.this.Predef.manifest(reflect.this.Manifest.AnyVal())))
            scala.this.Predef.println("AnyVal (primitive)")
          else
            if (BoundedManifestCheck.this.m().<:<(scala.this.Predef.manifest(reflect.this.Manifest.Object())))
              scala.this.Predef.println("AnyRef")
            else
              scala.this.Predef.println(scala.this.Predef.augmentString("Not sure what the base type of manifest '%s' is.").format(scala.this.Predef.genericWrapArray(Array[java.lang.Object]{BoundedManifestCheck.this.m().erasure()})));
          protected <synthetic> <paramaccessor> val $outer: anonymous class $anon = _;
          <synthetic> <stable> def Main$$anon$BoundedManifestCheck$$$outer(): anonymous class $anon = BoundedManifestCheck.this.$outer
        };
        new BoundedManifestCheck($anon.this, "Foo Bar!", reflect.this.Manifest.classType(classOf[java.lang.String]));
        new BoundedManifestCheck($anon.this, scala.Int.box(5), reflect.this.Manifest.Int());
        new BoundedManifestCheck($anon.this, scala.Double.box(5.2), reflect.this.Manifest.Double());
        new BoundedManifestCheck($anon.this, scala.package.BigDecimal().apply("8.62234525"), reflect.this.Manifest.classType(classOf[scala.math.BigDecimal]))
      };
      {
        new anonymous class $anon();
        ()
      }
    }
  }
}


text:
Q: selenium RC ruby, wait for hidden element to appear? How can I wait for a hidden element to appear on the page?
I tried seleum.is_element_present but it dosent seem to be working.

A: What you want is the is_visible method. Below will wait for 30 seconds to become visible
!30.times{ break if (@selenium.is_visible("locator") rescue false); sleep 1 }

A: wait_for_element(locator, options={})
Wait for an element to be present (the wait in happenning browser side).

A: Came across the same problem using Watir, present? only works if element is visible. To wait for an invisible element to appear you can do this in Watir
Watir::Wait.until { browser.div(:class => "loaded").exists? }

exists? returns true if element is in the DOM, doesn't care about visibility


text:
Q: Hive external tables map to azure blob storage Is there a way to create a Hive external table using  with location pointing to Azure Storage? We actually want to connect SAP HANA (SDA) to blob storage, so it seems the only way is to  create an external hive table first which points to Azure blob storage and then use Hive ODBC connector/spark connectorto connect  it toHANA SAP`. Does anyone have any idea how to achieve that?

A: You can create external tables in Hive or Spark on Azure. There are several options available:

*

*Azure HDInsight

*Azure Databricks (via Spark)

*Hadoop distros supporting Azure Blob Storage (e. g. HDP)

External table creation would reference the data in the Blob storage account. See the following example for a Hive table created in HDInsight (wasb is used in the location):
CREATE EXTERNAL TABLE IF NOT EXISTS <database name>.<external textfile table name>
    (
        field1 string,
        field2 int,
        ...
        fieldN date
    )
    ROW FORMAT DELIMITED FIELDS TERMINATED BY '<field separator>'
        lines terminated by '<line separator>' STORED AS TEXTFILE
        LOCATION 'wasb:///<directory in Azure blob>'
TBLPROPERTIES("skip.header.line.count"="1");

or in Azure Databricks:
CREATE EXTERNAL TABLE IF NOT EXISTS my_table (name STRING, age INT)
   COMMENT 'This table is created with existing data'
   LOCATION 'wasbs://<storage-account@<containername>.blob.core.windows.net/<directory>'

See also:

*

*HDInsight Documentation

*Azure Databricks Documentation
I don' t know what SAP supports. ODBC-Access is possible to all of the solutions.


text:
Q: I am confused with the const keyword in react I have code that passes data through a react component from a form to a backend. The backend processes it and sends a response. However I am confused with the const keyword, I am seeing in the code.
axios{
  .post('/api/users/register', newUser)
  .then(res => console.log(res.data))
  .catch(err => this.setState({ errors: err.response.data }));

}
render() {
    const { errors } = this.state;
     <div className="form-group">
              <input
                type="text"
                className={classnames('form-control form-control-lg', {
                  'is-invalid': errors.name
                })}
                placeholder="Name"
                name="name"
                value={this.state.name}
                onChange={this.onChange}
      />

You can assume that the code works. However, why is const {errors} defined like this, and how come it can access the errors list from the backend is-invalid': errors.name.
Thank you.

A: This is called object destructuring.  const {errors} = this.state; is a cleaner way of accessing the errors key in your local state than typing this.state.errors everywhere.  So now when you need to use errors you can just pass it in somewhere like this

const {errors} = this.state;

<YourComponent
  errors={errors}
/>


text:
Q: Test passes in Test Explorer, fails in NUnit GUI I have a special test written in NUnit which passes in Visual Studio Test Explorer but does not pass when it is ran in the NUnit gui. The unit test uses an Interceptor class which swaps two methods so that I can use the second method as a fake for the first which is used in the unit under test. This is done with the C# unsafe (unmanaged) code:
  public static void Inject( MethodInfo replacedMethod, MethodInfo injectionMethod )
  {
     RuntimeHelpers.PrepareMethod( replacedMethod.MethodHandle );
     RuntimeHelpers.PrepareMethod( injectionMethod.MethodHandle );

     unsafe {
        if( IntPtr.Size == 4 ) {

           int* inj = (int*) replacedMethod.MethodHandle.Value.ToPointer() + 2;
           int* tar = (int*) injectionMethod.MethodHandle.Value.ToPointer() + 2;

           if( System.Diagnostics.Debugger.IsAttached ) {
              //Version x86 Debug
              byte* injInst = (byte*) *inj;
              byte* tarInst = (byte*) *tar;

              int* injSrc = (int*) (injInst + 1);
              int* tarSrc = (int*) (tarInst + 1);

              Replaced = (((int) tarInst + 5) + *tarSrc) - ((int) injInst + 5);

              *tarSrc = (((int) injInst + 5) + *injSrc) - ((int) tarInst + 5);
              *injSrc = Replaced;
           }
           else {
              //Version x86 Release
              Replaced = *tar;
              *tar = *inj;
              *inj = Replaced;
           }
        }
     }
  }

I call the Inject method from my unit test:
  public static void SecondMethod( double[] e, out double var1, out double var2, out double var3 )
  {
     var1 = new Double();
     var2= new Double();
     var3 = new Double();
     var1 = 0.0;
     var2 = 0.0;
     var3 = 0.0;
  }

  [Test]
  public void Utilites_Tanks_ApproximateApogee_ReturnsTrue(){
     double val = 10;
     double[] ecr = { 1.2, 3.4, 5.6, 4.5, 6.7, 8.9 };
     MethodInfo x = typeof( FirstMethodClass ).GetMethods().Single(m => m.Name == "FirstMethod" && m.GetParameters().Length == 4);
     MethodInfo z = typeof( TestClass ).GetMethod( "SecondMethod" );
     Interceptor.Inject( x,z );
     bool stageValue = UnitUnderTestMethodClass.Method( ecr, val, out double[] apogeeInfo2 );
     Assert.That( stageValue, Is.True );
  }

This test works as planned; it passed in the Visual Studio test explorer and it does show up in the NUnit gui. The hang up is that it doesn't pass when ran in the NUnit gui. I have run the test in NUnit gui versions 2.6.# and 3.# with the same result. There is another test that I have written that does close to the same thing and it passes. That test is swapping methods with no arguments to pass so the GetMethod portion is done within the Interceptor unlike this test.
I was wondering if the NUnit gui does not play well with unsafe (unmanaged) code. I am referencing the correct build in the NUnit gui as well so I do not believe that this is the issue.
Thanx


text:
Q: How to pass in part of object(json) by restful api Now, I have a user object which has three required attributes:
{FirstName,
 LastName,
 CreatedTime
}.
Now I developed an API to create a user. I want to use POST /api/users.
I should pass in Jason data and it contains the data I want to post.
If I pass in {FirstName=abc, LastName=abc, CreatedTime=sometime}, it works, but if i miss any attribute, such like only passing in {firstname=abc}, it will throw exception.
I pasted my method below.
    [Route("api/users")]
    public User CreateUser(User user)
    {
        if (!ModelState.IsValid)
            throw  new HttpResponseException(HttpStatusCode.BadRequest);

        user.FirstName = String.IsNullOrEmpty(user.FirstName) ? "Undefined" : user.FirstName;
        user.LastName = String.IsNullOrEmpty(user.LastName) ? "Undefined" : user.LastName;
        user.UserName = String.IsNullOrEmpty(user.UserName) ? "Undefined" : user.UserName;
        user.ModifiedAt = DateTime.Now;
        user.CreatedAt = DateTime.Now;
        _context.Users.Add(user);
        _context.SaveChanges();

        return user;
    }

My question is: Is there any way that I can pass in partial properties of user? Such like {firstname=abc}.
This technique can also be used as PUT (update user method).
Thanks in advance.

A: 1) When inserting your record just mark your CreatedAt and ModifiedAt property to [JsonIgnore] attribute
[Required]
[JsonIgnore]
public DateTime CreatedAt { get; set; }

[Required]
[JsonIgnore]
public DateTime ModifiedAt { get; set; }

2) When you try to get your data your api method will be
[HttpGet]
[Route("ById/{id=id}")]
public IHttpActionResult GetUser(int? id)
{
    if (id == null)
        return NotFound();

    User user = _context.Users.SingleOrDefault(c => c.UserId == id.Value);

    if (user == null)
        return BadRequest("User not exist in our database");

    var returnedData = new { FirstName = user.FirstName, LastName = user.LastName, UserName = user.UserName, CreatedAt = DateTime.Now, ModifiedAt = DateTime.Now };
    return Ok(returnedData);
}

We just use to return Anonymous Type that is customizable to return data.
Try once may it help you

A: It depends to your properties datatype, if they are nullable so you can just leave them empty or null in your sending message but if they are not nullable you have to provide value otherwise you will get noting in the destination (your wep-api action).
So now if you want to avoid passing value even for non-nullable properties you can use [JsonIgnore] attribute (Belongs to Newtonsoft.Json) on your properties. Like this:
using Newtonsoft.Json;

public class User
{
   //...
   [JsonIgnore]
   public DateTime CreatedAt  { get; set; }
   //...
}


text:
Q: I'm making a chatbot translated into Portuguese but when the bot will send the answer instead of returning the translation it returns [object Object] I'm making a chatbot and I'm trying to understand why it's returning [object Object], I'm trying to translate the answer o from en to pt.
client.on("message", async message => {
  if (message.channel.name == "chatbot") /*name channel*/ {
    if (message.author.bot) return;
    message.content = message.content.replace(/@(everyone)/gi, "everyone").replace(/@(here)/gi, "here");

    if (message.content.includes(`@`)) {
      return message.channel.send(`**❌ Please dont mention anyone**`);
    }

    message.channel.startTyping();
    if (!message.content) return

    const translate = require("@iamtraction/google-translate"); //api

    const translated = await translate(message.content, {
      to: 'en'
    }); //translating

    /*message.channel.send("Please say something.");*/
    fetch(`https://api.affiliateplus.xyz/api/chatbot?message=${encodeURIComponent(translated)}&botname=${client.user.username}&ownername=DEVELOPER_NAME`)
      .then(res => res.json())
      .then(async data => {
        const translat = await translate(data.message, {
          to: 'pt'
        }); //translating
        message.inlineReply(`${translat}`); //here is where it returns [object Object]
      });
    message.channel.stopTyping();
  }
});

A: Based on the packages documentation in npm the translate method returns Promise<Object> with text property. It means that if you want to get the text after translation then you must use it as: translat.text


text:
Q: Using generic function does not work for loading YAML list with jackson I just recently started trying out Kotlin and I'm mostly amazed with it so far. However, I can't quite wrap my head around how the generics work here.
I want to read a YAML file that looks like this:
- id: acrobatics
  name: Akrobatik
  description:
  ...

A simple data class to map this to:
data class Skill (
    val id: String,
    val name: String,
    val description: String
)

Now, on to the interesting part. Apparently, it does work with generics!
I started with this function, which does its job as intended:
fun loadSkills(): List<Skill> {

    val resource: URL = classLoader.getResource("rulebook/skills.yml")!!

    val items: List<Skill> = resource.openStream()
        .bufferedReader().use() { reader ->
            objectMapper.readValue<List<Skill>>(reader)
        }

    return items
}

However, I want to reuse this, so I tried creating a generic function:
protected fun <R: Any> loadList(path: String): List<R> {

    val resource: URL = classLoader.getResource(path)!!

    val items: List<R> = resource.openStream()
        .bufferedReader().use() { reader ->
            objectMapper.readValue<List<R>>(reader)
        }

    return items
}

And my original function just calls:
return loadList<Skill>("rulebook/skills.yml")

And now my tests fail because I get a List of LinkedHashMaps, which seems to be the default datatype used by the YAML parser to map objects.
I read a little more and tried changing my method signature to an inline function with a reified type parameter:
protected inline fun <reified R: Any> loadList(path: String): List<R>

But that doesn't seem to change anything.
Is there any way to make this work elegantly?

A: Since all generic type information does not exist at runtime, you need to provide it to Jackson somehow. Reified type keeps that information, but AFAIK Jackson does not use it so you have to do it manually. For example, like this:
inline fun <reified T> loadSkills(path: String): List<T> {

    val resource: URL = javaClass.classLoader.getResource(path)
    val type = objectMapper.typeFactory.constructParametricType(List::class.java, T::class.java)
    val items: List<T> = resource.openStream()
                .bufferedReader().use { reader ->
                    objectMapper.readValue(reader, type)
                }

    return items
}

EDIT: It turns out that there is a restriction in jackson-kotlin-module for automatic calculation of nested generic types.
If you try to parse yaml (or whatever else) for single Skill (without list) it will work properly even inside generic function, but once you want to have nesting like List< Skill >, it fails to recognise type properly and produces List of HashMaps


text:
Q: How to be navigated to the page of the profile details when the user's name is clicked Hello so I created a fake data in Mockaroo to display the users and its profile details. My goal here is to display the names and when clicked it will redirect to the profile details.
So far here is my code. I would really appreciate your help since I'm very new to this.
Future<List<Users>> _getUsers() async {
    var data =
        await http.get("https://my.api.mockaroo.com/users.json?key=8f9261404");

    var jsonData = json.decode(data.body);

    List<Users> users = [];

    for (var u in jsonData) {
      Users user = Users(
          u["user_id"],
          u["name"],
          u["email"],
          u["mobile"],
          u["address"]);

      users.add(user);
    }
    return users;
  }

I made a class
class Users {
  Users(
      {this.id,
      this.name,
      this.email,
      this.mobile,
      this.address});

  final int id;
  final String name;
  final String email;
  final String mobile;
  final String address;

}

This is my UI
body: SingleChildScrollView(
          child: Column(
        children: <Widget>[
          FutureBuilder(
            future: _getUsers(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.data == null) {
                return Container(child: Center(child: Text("Loading...")));
              } else {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return ListTile(
                      key: Key("$index"),
                      title: Text(snapshot.data[index].name),);
                  },
                );
              }
            },
          ),
        ],
      )),

Again, my goal here is to be navigated to the page of the profile details when the user's name is clicked.

A: You can wrap your ListTile with an GestureDetector and then use Navigator, like this:
GestureDetector(
    child: ListTile(
            key: Key("$index"),
            title: Text(snapshot.data[index].name),
    onPressed: (){
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) {
              return DetailScreen(data: snapshot.data.documents[index]);
            }),
    },
)

Inside onPressed you navigate to your detail screen and you pass your data to your detail screen. This is done by passing the data as parameter to your detail screen: return DetailScreen(data: snapshot.data.documents[index]);. You can then access your data in your new detail screen using the data parameter.
You have to create your detail screen at first, like this:
class DetailScreen extends StatelessWidget {

final DocumentSnapshot data;

  DetailScreen({this.data})

  @override
  Widget build(BuildContext context) {
    return Container(
      //Do something with data
    );
  }
}


text:
Q: add_custom_command doesn't rebuild when dependencies change I run a python script over each of my source files in order to generte additional code. The generated code can then be included in the source file and its content be used.
#include <Main.cpp.generated.hpp>

In order to make it work with CMake, I've added this python script as a custom cmake, because it seems to be the common way to make it work.
My CMake script looks like this (ignore the hardcoded paths, it's a proof of concept).
cmake_minimum_required (VERSION 3.20)
project(test)

add_executable(target Main.cpp test.h for_each.hpp ${CMAKE_CURRENT_BINARY_DIR}/gen/Main.cpp.generated.hpp)

add_custom_command(
    OUTPUT gen/Main.cpp.generated.hpp
    COMMAND python D:/Projects/clang-plugins/test-gen/test-gen.py ${CMAKE_CURRENT_SOURCE_DIR}/Main.cpp ${CMAKE_CURRENT_BINARY_DIR}/gen/Main.cpp.generated.hpp
    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/Main.cpp)

target_compile_features(target PRIVATE cxx_std_17)

target_include_directories(target PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/gen)

Everytime I modify my Main.cpp file, the generated file is rebuilt. Which is good. However, if a file included by Main.cpp changes, the generated file is not rebuilt. Which is a problem because then the generated code can be outdated. I can fix it by adding those headers into the DEPENDS arg, but I don't want to do this my hand.
I don't want to trigger my custom command everytime the file Main.cpp changes, but everytime the file Main.cpp is rebuilt.


text:
Q: React Native: Text and Growing TextInput in a responsive ScrollView Using RN 0.45, for iOS and Android:
I'm trying to create a view that is like the "reply" view of the reddit app, that I think would be as follows:

*

*A header (Text) that is static

*Below the header, an input (TextInput) that grows/shrinks to the size of the content

*Encapsulating both, a scrolling view (ScrollView) with a static height that is above above the top of the keyboard

When putting this view together, I'm having trouble
The simple version of my code looks more or less like this, though this doesn't accomplish what I want because the TextInput scrolls inside the scrollview rather than with the scrollview:
<ScrollView style={{height: 200}}>
  <Text>Header Text</Text>
  <TextInput
    multiline
    underlineColorAndroid={'transparent'}
    autoCapitalize='none'
    autoFocus
    editable
  />
</ScrollView>

I'm looking for a way to

*

*Dynamically size the TextInput within the scrollview

*When the cursor is within the TextInput at the bottom of the visible part of the scrollview and the user types something that makes a new line, the scrollview will shift to show the new text line

*When the cursor is in the middle of the TextInput and creates a new line, the scrollview does not move

I'm wondering if there are examples of this kind of view in another app, or a method that people have used to create this kind of view, especially if it is different than the method I'm trying out or uses a library made for this kind of thing!
EDIT: Another attempt using AutoGrowingTextInput, but the overall UX doesn't quite work as expected as creating a line in the middle of the of the textinput area causes the ScrollView to scroll all the way to the end --
    <ScrollView
      style={{ height: 240 }}
      ref={(scrollView) => { this.scrollView = scrollView; }}
      contentContainerStyle={{ flexGrow: 1 }}
      onContentSizeChange={() => {
        this.scrollView.scrollToEnd();
      }}
    >
      <Text>Header Text</Text>
      <AutoGrowingTextInput
        multiline
        underlineColorAndroid={'transparent'}
        autoCapitalize='none'
        autoFocus
        editable
      />
    </ScrollView>


text:
Q: Python - Only last line is saved to file I'm trying to output the result of my script into a text file. The script is working fine, the only problem is when results are saved into the text file (output.txt), only last line is being saved,not the whole thing? I'm not sure what I'm doing wrong here. any suggestions will be appreciated.
Cheer!
        try:

            if 'notavailable' not in requests.get('url' + str(service) + '&username=' + str(username), headers={'X-Requested-With': 'XMLHttpRequest'}).text:
                result = service + '\t' + " > " + username + " > " 'Available'
                print  result
                f = open("output.txt", "w")
                f.write(result + "\n")
                f.close()

            else:
                print service + '\t' + " > " + username + " > " 'Not Available'

        except Exception as e:
            print e

A: you need to write
f = open("output.txt", "a")

This will append the file, rather than write over whatever else you put in it.

A: In every iteration you are opening the file, erasing its content, writing and closing. It is much better to open it only once:
f = open('output.txt', 'w')
# do loop
    f.write(stuff)
f.close()

Or, much better:
with open('output.txt', 'w') as f:
    while loop:
       f.write(stuff)

This method is not only cleaner, but also performs much better, as you can cache the contents of the file, and use the minimal number of OS calls.

A: I'm going to take a wild guess and assume that all of this code happens inside a loop. Each time through the loop, you write one more line, but at the end, you only have the last line.
If that's the problem, here's the issue:
        f = open("output.txt", "w")

When you open a file in 'w' mode, that truncates any existing file.
To fix this, either open the file once, outside the loop, instead of over and over again, or open it in 'a' mode or 'r+' mode or some other mode that doesn't truncate the file.
The documentation for the open function, or the inline help in the interactive interpreter, explains what all the different modes mean.

A: Did you try with parameter 'a'
So:
f = open("output.txt", "a")
That will open the file with pointer at the end.
http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python


text:
Q: mirror in frequency domain Why is that in the frequency domain, I always see mirror images? What causes these mirror frequencies to appear? How do they pop in? Where do they come from?
Secondly, what is this concept of negative frequency? In normal life, most of the time I only hear people mention the positive frequency. What is the role of the negative frequency and why is it always a mirror image of the positive frequency.
The lowest figure shows the frequency domain of a cosine function (two impulses appearing, also a mirror image)

A: Both the signal and the Fourier transform can be complex functions, but some interesting and useful simplifications are possible when either of these functions are purely real or purely imaginary.
when the time signal is purely real the fourier transform is said to be obey Hermitian symmetry.
\$X(-f)=X^*(f)\$
\$|X(-f)| = |X(f)|\$
\$argX(-f)= -argX(f)\$
if the time signal is purely imaginary then the fourier transform is said to be skew hermitian.
\$X(-f)=-X^*(f)\$
which will manifest itself as not a reflection but an inverted reflection.
So in short commonly used transforms and modulations will have the properties that you mention.


text:
Q: is Windows phone's Launcher similar functionality available on iOS? I am developing an application using Xamarin Forms, targeting iOS, Android and Windows Phone.
Using Dependency Service, I implemented to open/preview file that can be an audio, video or text document.
On Android, I used Intent with Android.Content.Intent.ActionView.
On Windows Phone, I used Launchers.
Is there any similar simple way on iOS to view a file?


text:
Q: Exceeding SQL Server SP call nesting level of 32 I came accross a business case where I need nested SP calls beyond the level of 32, which is the SQL Server's limit. Can anybody say whether there is a possibility to increase this limit?

A: No, 32 is the limit: Maximum Capacity Specifications for SQL Server
Nesting Stored Procedures
32 is a deep call stack; I've never hit this limit before. It suggests you should look for an alternative approach.

A: If you hit this limit, then you should be using udfs or CTEs for your recursive code. If it isn't recursive, it's really poor design.
I've never been more than about 4 deep including a trigger

A: Recursive calling COULD be a really nice feature, especially when your output is XML and you need to get XML child nodes that are equal in format as the parent. The workaround is using stored procedures to handle the parent/child relationship, with the drawback of more complicated/redundant code. Say you have:
create table Users (UserID int, Name nvarchar(50), ManagerID int null)
insert into Users (1, 'Carl', null)
insert into Users (2, 'Tom', 1)
insert into Users (3, 'John', 1)

and
create function GetUser(@UserID int)
returns XML as
begin
    declare @xml XML
    SET @xml = (
        SELECT [UserID] "User/@UserID"
            , [Name] "User/@Name"
            FROM Users
            WHERE [UserID] = @UserID
        FOR XML PATH(''), TYPE
    )
    return @xml
end

To get all managers in an XML:
create proc GetAllManagers() as
begin
    set nocount on;
    SELECT dbo.GetUser([UserID])
    FROM Users
    WHERE [ManagerID] IS NULL
    FOR XML PATH(''), TYPE, root('Managers')
end

Now to the problem. What if for each manager, I want all the users belonging to the manager? I would like my function to be able to call itself:
alter function GetUser(@UserID int, @IsIncludeChildren bit)
returns XML as
begin
    declare @xml XML
    SET @xml = (
        SELECT [UserID] "User/@UserID"
            , [Name] "User/@Name"
            , (SELECT dbo.GetUser([UserID], 0)) "User/Children"
            FROM Users
            WHERE [ManagerID] = @UserID AND @IsIncludeChildren = 1
        FOR XML PATH(''), TYPE
    )
    return @xml
end

and calling this simply
alter proc GetAllManagers() as
begin
    set nocount on;
    SELECT dbo.GetUser([UserID], 1)
    FROM Users
    WHERE [ManagerID] IS NULL
    FOR XML PATH(''), TYPE, root('Managers')
end

But this is not possible because of the nesting limit. So workaround is (using the first function):
alter proc GetAllManagers() as
begin
    set nocount on;
    SELECT
      dbo.GetUser([UserID])
    , (
      SELECT dbo.GetUser([UserID])
          FROM Users
          WHERE [ManagerID] = [Users].[UserID]
          FOR XML PATH(''), TYPE
    ) "User/Children"

    FROM Users as [Users]
    WHERE [ManagerID] IS NULL
    FOR XML PATH(''), TYPE, root('Managers')
end

This is not too bad, but if you have lots of other procedures returning user data, you will have to build the parent/child relationship in all procs, instead of in a single function!
So there, Microsoft, fix it!


text:
Q: Log parser not reading the new fields included in IIS Log I use log parser 2.2 to read the IIS log and copy the log into a database. Initially IIS log was having the default fields and I was able to copy the log in to database. Now I included one more field in IIS log but the log parser does not return the details of new column. Can anyone help to make log parser to read the additional fields along with the old log files?
Following query is used to read IIS log.
select * from C:\inetpub\logs\LogFiles\W3SVC3\*.*

A: If it's newly added, then I think log parser stops checking the newly defined field after the first 50 entries it finds (perhaps total or per log) try using just the IIS log that has the new field in it to determine if it's working or not. Also, make sure that the first 3 lines reflect the # Fields: stuff entire you're looking for.
ie:
select * from C:\inetpub\logs\LogFiles\W3SVC3\todays.log


text:
Q: Is there any way I can call my shell script in Java and set values to the shell script variables via Java class I have a shell script file which has three variables defined in it. I need to set values for those variable in java class, which means, I need to get access of the shell script file in my Java class, then I need to get access of those three variables, and then I need to set values of those three variables from Java. I am not sure how to achieve this requirement. My shell script file is located in windows D:/.
Here is my shell script code:
path=`xxx`
echo "$path"

Src
Dest
Env

I need to set the value of Src, Dest and Env

A: A process inherits a copy of all environment variables from its parent process, which is the process that runs it.
So if you want to set environment variables in a Java program and use them in a shell script, you need the Java program to run the shell script.
That is possible using the java.lang.ProcessBuilder class, but quite unusual. Are you sure it's what you want?
If you need the java program to get the values of the variables, and then use them in the shell script, you could have the java program write the values to a file and then read them from the file in your script, which is likely to be simpler, easier and more portable.


text:
Q: My LTO-5 ultrium 3000 SAS external tape drive won't show up on my iMac OK, so here is my problem. I got a HP LTO-5 ultrium 3000 SAS external tape drive from my boss and he said to connect it to my new iMac but when I connect it, it doesn't show up on my computer.
I'm really not good at this but I have searched for an answer online and haven't found one. I don't have ant specific information about the LTO-5 I have or where he bought it but he said that I had to install some program to make it work and I don't know what that program is. I asked my boss but he didn't remember what program it was.
It is connected via a ATTO Thunder Link. Could that be a problem?

A: Ok, the solution to my problem was that I didn't have the software to use the LTO. I found that when I downloaded HP StoreOpen Standalone I could use the LTO without a problem.


text:
Q: Is there a CPAN module to extract the current level of content from an email I'm looking for a module to do a best-effort attempt to extract the immediate level of content (ie discarding any quoted content and the signature block) from the plain text component of an email.
We've already got some code that has a shot at it, so if there is no existing module that does it, ideas for a name for a new module would also be appreciated (Text::ExtractImmediateLevelOfContentFromEmail seems a bit unwieldy).

A: I believe there's no such module because that's very task oriented and there's a huge variety of message formatting styles. The minimal implementation is something you can do with a few lines of code:
use Email::MIME;
my $email = Email::MIME->new($message);
my $body;
$email->walk_parts(sub {
    my ($part) = @_;
    return unless $part->content_type =~ m[text/plain];
    $body .= $part->body;
});

# strip quoted lines and attribution line
$body =~ s/^.+ wrote:\n(?=\n* ?>)//m;
$body =~ s/^ ?>.*\n//gm;

# strip signature
$body =~ s/-- \R.+//;

Of course you may want to add other heuristic rules to remove attribution lines written in other languages, as well as removing Outlook-style quoted text.
I'd suggest some heuristics to avoid quoted text stripping if the message is recognized to use interleaved-style quoting. That's because interleaved replies may loose some meaning if you strip quoted text.
If you want to factor that out to a module, I'd call it Email::ExtractBody or Email::ExtractText. I'd stress in the POD that the module has a heuristic and best-effort approach.


text:
Q: Age from year and date column Netezza sql I have data elements like ID; start_date; Birth_year. I want to calculate Age based on the birth_year column and start_date as shown in the AGE column.

I could only think of padding the birth year with '-01-01' and then using that column to calculate Age.
Is there another efficient way to get Age from the birth year and start date in Netezza SQL?

A: Use the extract SQL function to get the year from start_date and do the age calcuation
E.g

select
    start_date,
    birth_year,
    -- assuming birth_year is an integer
    extract(year from start_date) - birth_year as age
from ...

will give
 START_DATE | BIRTH_YEAR | AGE
------------+------------+-----
 2000-01-15 |       1985 |  15
 2010-06-20 |       1990 |  20
 2005-12-15 |       1992 |  13
 2007-08-17 |       1998 |   9
 2020-09-15 |       1999 |  21
(5 rows)

An alternative method to get more detailed age would be to use the Netezza 'age' SQL function -
select
    start_date,
    birth_year,
    age(start_date, to_date(birth_year, 'YYYY'))
from...

which will result in
 START_DATE | BIRTH_YEAR |           AGE
------------+------------+--------------------------
 2000-01-15 |       1985 | 15 years 14 days
 2010-06-20 |       1990 | 20 years 5 mons 19 days
 2005-12-15 |       1992 | 13 years 11 mons 14 days
 2007-08-17 |       1998 | 9 years 7 mons 16 days
 2020-09-15 |       1999 | 21 years 8 mons 14 days
(5 rows)