text:
Q: centos 8 in the docker build net core 5.0 error message NET SDK is not installed I Project MVCVue add a folder build path home/paul/Downloads/MVCVue/App/bin/De

#Dokerfile#
ROM mcr.microsoft.com/dotnet/aspnet:5.0-focal AS base
WORKDIR /app
EXPOSE 5000

ENV ASPNETCORE_URLS=http://+:5000
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app

USER appuser

FROM mcr.microsoft.com/dotnet/sdk:5.0-focal AS build
WORKDIR /src
COPY ["MVCVue.csproj", "./"]
COPY . .

FROM base AS final
WORKDIR /app
ENTRYPOINT ["dotnet", "MVCVue.dll"]

my docker images

#docker images#
Step 13/13 : ENTRYPOINT ["dotnet", "MVCVue.dll"]
 ---> Running in cc2865b2290a
Removing intermediate container cc2865b2290a
 ---> 2f79dc5fec19
Successfully built 2f79dc5fec19
Successfully tagged netcore:v
[root@localhost De]# docker images
REPOSITORY                        TAG         IMAGE ID       CREATED              SIZE
netcore                           v           2f79dc5fec19   About a minute ago   215MB
<none>                            <none>      83feaa33c847   About a minute ago   646MB
mcr.microsoft.com/dotnet/sdk      5.0-focal   939156dd4acc   12 days ago          646MB
mcr.microsoft.com/dotnet/aspnet   5.0-focal   063dc45e41e8   12 days ago          213MB

I have SDK 5.0
I don't know what was missed but Tell me to err NET SDK is not installed
#error message#
[root@localhost De]# docker run netcore:v
Could not execute because the application was not found or a compatible .NET SDK is not installed.
Possible reasons for this include:
  * You intended to execute a .NET program:
      The application 'MVCVue.dll' does not exist.
  * You intended to execute a .NET SDK command:
      It was not possible to find any installed .NET SDKs.
      Install a .NET SDK from:
        https://aka.ms/dotnet-download

A: You don't build your application in your Dockerfile, so that's why there's nothing to execute.
Try changing your Dockerfile to
FROM mcr.microsoft.com/dotnet/aspnet:5.0-focal AS base
WORKDIR /app
EXPOSE 5000

ENV ASPNETCORE_URLS=http://+:5000
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app

USER appuser

FROM mcr.microsoft.com/dotnet/sdk:5.0-focal AS build
WORKDIR /src
COPY ["MVCVue.csproj", "./"]
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o out

FROM base AS final
WORKDIR /app
COPY --from=build /src/out .
ENTRYPOINT ["dotnet", "MVCVue.dll"]


text:
Q: Why getting exception when trying to create a folder name based on date time? In the screenshot on the left, what do I get on the textBox Text, and on the right is the exception when clicking on the continue button.

The code of the method to create the folder/s :
private void CreateDownloadFolders()
        {
            string locationToCreateFolderRadar = textBoxRadarPath.Text;
            string locationToCreateFolderSatellite = textBoxSatellitePath.Text;
            string folderName = "";
            string date = DateTime.Now.ToString("ddd MM.dd.yyyy");
            string time = DateTime.Now.ToString("HH.mm tt");
            string format = "{0} on {1} At {2}";
            folderName = string.Format(format, date, time);
            Directory.CreateDirectory(locationToCreateFolderRadar + folderName);
            Directory.CreateDirectory(locationToCreateFolderSatellite + folderName);
        }

The button click event that calls the CreateDownloadFolders method :
private async void btnStart_Click(object sender, EventArgs e)
        {
            CreateDownloadFolders();

            urls = new List<string>();

            lblStatus.Text = "Downloading...";

            rad.GetRadarImages();
            await Task.Delay(5000);
            foreach (string link in rad.links)
            {
                urls.Add(link);
            }

            await sat.DownloadSatelliteAsync();
            foreach (string link in sat.SatelliteUrls())
            {
                urls.Add(link);
            }

            urlsCounter = urls.Count;

            await DownloadAsync();
        }

Maybe because the button click event is type async?

A: your issue is on this line:
  folderName = string.Format(format, date, time);

you are sending only  two parameters and the format  is  expecting 3:
 string format = "{0} on {1} At {2}";

you have two ways to solve this:
1:
 string format = "{0} on {1} At X"; // expect only 2 parameters

or
2:
   folderName = string.Format(format, date, time, "something else"); // send all 3 parameters

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stiles doesn't apply to algolia search box in react Im trying to style Algolia's SearchBox in CRA app, with pure CSS
.ais-SearchBox-submitIcon path,
.ais-SearchBox-resetIcon path {
    fill: red,
}

.ais-SearchBox-input {
    width: '130px';
}

button.ais-SearchBar-submit {
    display: none;
}

None of these class selectors is working.
Im sure Im missing something, but cant figure it out.


text:
Q: JPA: multiple select statements while fetching a single record @OneToOne and @PrimaryKeyJoinColumn Considering my entities as CPU and PROCESSOR having relationship one to one with shared Primary Key.
One CPU has One Processor.
CPU.java
@Entity
@Table(name = "PKJoin_CPUt")
public class CPU {

    private int id;
    private String name;
    private Processor processor;

    @OneToOne(cascade = CascadeType.PERSIST, mappedBy = "cpu", optional = true,fetch=FetchType.LAZY)
    public Processor getProcessor() {
        return processor;
    }
    public void setProcessor(Processor processor) {
        this.processor = processor;
        if (null != processor) {
            processor.setCpu(this);
        }
    }
    private Processor2 processor2;

    @OneToOne(cascade = CascadeType.PERSIST, mappedBy = "cpu", optional = true,fetch=FetchType.LAZY)
    public Processor2 getProcessor2() {
        return processor2;
    }

    public void setProcessor2(Processor2 processor2) {
        this.processor2 = processor2;
        if (null != processor2) {
            processor2.setCpu(this);
        }
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
        if (null != processor) {
            processor.setId(id);
        }
        if (null != processor2) {
            processor2.setId(id);
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String deptName) {
        this.name = deptName;
    }

}

Processor.java
@Entity
@Table(name = "PKJoin_Processor")
public class Processor {

    private int id;
    private String name;

    private CPU cpu;

    @OneToOne(fetch=FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public CPU getCpu() {
        return cpu;
    }

    public void setCpu(CPU cpu) {
        this.cpu = cpu;
    }
    @Id
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Main.java
public class Main {
  static EntityManagerFactory emf = Persistence.createEntityManagerFactory("Hello");
  static EntityManager em = emf.createEntityManager();

  public static void main(String[] a) throws Exception {
    em.getTransaction().begin();

    new Main().findData();
   // new Main().persistData();

    em.getTransaction().commit();
    em.close();
    emf.close();

  }

 public void findData(){

    CPU cpu = em.find(CPU.class, 449);
    System.out.println(cpu.getProcessor().getName());

  }
}

This is executing like this::
    Hibernate: select cpu0_.id as id11_0_, cpu0_.name as name11_0_ from PKJoin_CPUt cpu0_ where cpu0_.id=?
    Hibernate: select processor0_.id as id38_0_, processor0_.name as name38_0_ from  PKJoin_Processor processor0_ where processor0_.id=?
    Hibernate: select processor2x0_.id as id19_0_, processor2x0_.name as name19_0_ from PKJoin_Processor222 processor2x0_ where processor2x0_.id=?

Joe
I don't want these three queries to get executed while I am fetching only the CPUName attribute.I don't want join also.
I want only the first query to get executed for whenever i try to fetch CPU attributes.
Need a solution?

A: The problem is that since the associatio is optional, Hibernate has no way to know, just by loading a CPU, if it has an associated processor or not. So, in order to either set the processor field to null, or to set it to an instance of Processor, it has to chck if a processor exists with the primary key of the CPU.
To avoid that, the easiest way is to map the association using a join column in CPU pointing to the processor. That way, if the join column is null, Hibernate knows there is no associated CPU. And if it's not null, it can set the procssor field to a lazy proxy.
Another way, AFAIK, is to use @LazyToOne(NO_PROXY), and to instrument the bytecode. But I've had bad experiences with this setting in the past. Maybe it has improved.

A: In your findData(), you do cpu.getProcessor().getName(), so it's logical you get a query for the first processor.
You do weird things in the CPU.setId() function, maybe that's why the processors are loaded.
You shouldn't do this, you should let hibernate take care of this. For bidirectional one-to-one relations based on primary key, I think you need the following:
public class CPU {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "cpu", fetch=FetchType.LAZY)
    private Processor processor;

    ...
}

public class Processor {
    @Id @OneToOne
    @JoinColumn("id")
    private CPU cpu;  //combine @Id and @OneToOne, no int id needed.

    protected Processor(){}

    public Processor(CPU cpu){
       this.cpu = cpu;
       cpu.setProcessor(this);
    }
    ...
}

Now if you save a Processor with a CPU, its id is magically filled in with the CPU's id.
Make sure you save them in the correct order:
CPU cpu = new CPU();
em.save(cpu);
Processor p = new Processor(cpu);
em.save(p);


text:
Q: Using "Matrix" package methods in a custom R package Following code is a function in a custom R package.
#' @import Matrix
#' @export
asdf <- function(){
    u <- Matrix(0,5,5)
    rowSums(u)
}

When I load the package and execute it, I get the following output.
> library(devtools); document(clean=TRUE); load_all()
Loading required package: roxygen2
Updating gm documentation
Loading gm
Loading required namespace: Matrix
Loading required package: Matrix
Writing gm.generate.Rd
Loading gm
> asdf
function(){
    u <- Matrix(0,5,5)
    rowSums(u)
}
<environment: namespace:gm>
>
> asdf()
Error in rowSums(u) (from tmp.R#5) : 'x' must be an array of at least two dimensions

So, even though the Matrix package is loaded, rowSums in the Matrix package is not getting dispatched even though Matrix package is imported in the NAMESPACE:
export(asdf)
import(Matrix)

In the global environment, the Matrix package is indeed loaded, and rowSums function is available.
> showMethods(rowSums)
Function: rowSums (package base)
x="ANY"
x="CsparseMatrix"
x="ddenseMatrix"
x="denseMatrix"
x="dgCMatrix"
x="dgeMatrix"
x="diagonalMatrix"
x="dsCMatrix"
    (inherited from: x="CsparseMatrix")
x="igCMatrix"
x="indMatrix"
x="lgCMatrix"
x="ngCMatrix"
x="RsparseMatrix"
x="TsparseMatrix"

However, if I define the same function in the global environment, everything works properly:
> qwer <- function(){
    u <- Matrix(0,5,5)
    rowSums(u)
}

qwer <- function(){
+     u <- Matrix(0,5,5)
+     rowSums(u)
+ }
> qwer()
[1] 0 0 0 0 0

I am puzzled by this. What am I doing wrong?
================================================================
In NAMESPACE file:
Package: hola
Type: Package
Title: What the package does (short line)
Version: 1.0
Date: 2014-01-03
Author: Who wrote it
Maintainer: Who to complain to <yourfault@somewhere.net>
Description: More about what it does (maybe more than one line)
License: What license is it under?

In DESCRIPTION file:
export(asdf)
import(Matrix)
importFrom(Matrix,Matrix)
importFrom(Matrix,rowSums)

In R/asdf.R file:
#' @import Matrix
#' @importFrom Matrix Matrix
#' @importFrom Matrix rowSums
#' @export
asdf <- function(){
    u <- Matrix(0,5,5)
    rowSums(u)
}

A: You should read 1.5.6 Namespaces with S4 classes and methods
Add this to your NAMESPACE file:
import(Matrix)

or better:
importFrom(Matrix, rowSums)

Also, Imports: Matrix in DESCRIPTION file is needed.
Bare minimum package is as follows:

DESCRIPTION file:
Package: hola
Type: Package
Title: What the package does (short line)
    Version: 1.0
    Date: 2014-01-03
Author: Who wrote it
Maintainer: Who to complain to <yourfault@somewhere.net>
Description: More about what it does (maybe more than one line)
License: What license is it under?
Imports:
    Matrix

NAMESPACE file:
export(asdf)
importFrom(Matrix,Matrix)
importFrom(Matrix,rowSums)

R/asdf.R file:
#' @importFrom Matrix Matrix
#' @importFrom Matrix rowSums
#' @export
asdf <- function(){
    u <- Matrix(0,5,5)
    rowSums(u)
}


text:
Q: Does not point to a Valid .jar Not Sure why I am getting this wrong path. Appreciate if anyone can help. On Windows 10 Enterprise Edition. Java Adopt JDK 11.06
2020-01-29 21:53:18,527 INFO  [org.kie.server.controller.websocket.client.WebSocketKieServerControllerImpl] (KieServer-ControllerConnect) Kie Server points to non Web Socket controller 'http://localhost:8080/business-central/rest/controller', using default REST mechanism
2020-01-29 21:53:23,794 WARN  [org.kie.server.services.impl.controller.DefaultRestControllerImpl] (KieServer-ControllerConnect) Exception encountered while syncing with controller at http://localhost:8080/business-central/rest/controller/server/sample-server error Read timed out
2020-01-29 21:53:28,421 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0059: Class Path entry jaxb-api.jar in **/C:/Windows/System32**/content/business-central.war/WEB-INF/lib/jaxb-core-2.3.0.jar  does not point to a valid jar for a Class-Path reference.
2020-01-29 21:53:28,421 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0059: Class Path entry jaxb-core.jar in /C:/Windows/System32/content/business-central.war/WEB-INF/lib/jaxb-impl-2.3.0.jar  does not point to a valid jar for a Class-Path reference.
2020-01-29 21:53:28,706 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0059: Class Path entry xml-apis.jar in **/C:/Windows/System32/**content/business-central.war/WEB-INF/lib/serializer-2.7.1.jar  does not point to a valid jar for a Class-Path reference.
2020-01-29 21:53:28,753 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0059: Class Path entry xercesImpl.jar in /C:/Windows/System32/content/business-central.war/WEB-INF/lib/xalan-2.7.1.jar  does not point to a valid jar for a Class-Path reference.
2020-01-29 21:53:28,753 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0059: Class Path entry xml-apis.jar in **/C:/Windows/System32/content/business-central.war/WEB-INF/lib/xalan-2.7.1.jar  does not point to a valid jar for a Class-Path reference.**
2020-01-29 21:53:28,753 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) WFLYSRV0059: Class Path entry serializer.jar in **/C:/Windows/System32/content/business-central.war/WEB-INF/lib/xalan-2.7.1.jar  does not point to a valid jar for a Class-Path reference.**
2020-01-29 21:53:31,482 WARN  [org.jboss.as.dependency.private] (MSC service thread 1-2) WFLYSRV0018: Deployment "deployment.business-central.war" is using a private module ("org.jboss.as.domain-management") which may be changed or removed in future versions without notice.
2020-01-29 21:53:31,629 INFO  [org.jboss.weld.deployer] (MSC service thread 1-4) WFLYWELD0003: Processing weld deployment business-central.war

A: Those are just warning messages. In your MANIFEST.MF you likely have the Class-Path attribute configured.
On a side note you probably shouldn't be using the internal org.jboss.as.domain-management module.


text:
Q: Access my web applications in PHP/APACHE without change host files I work with Apache that is installed in a Windows Server(Windows Server 2012 R2) , so i have my web applications in the htdocs folder (in the server ofc) if i want to access the applications via other computers connected to the server i have to change each host file in each pc...
If you work with 2, 3 pc that is ok, however when you have at least 40 pc's it can be very tiring.
That's way i'm asking this question.
I mean,it's possible to simply put the url in the browser and the computers connected to the server enter in my web application?

A: This isn't maybe the best solution, but here it is
in file C:\xampp\apache\conf\extra\httpd-xampp.conf
Inside <IfModule alias_module> write following lines
Alias / "C:\xampp\htdocs"
<Directory "C:\xampp\htdocs">
    AllowOverride all
    Order deny,allow
    Require all granted
</Directory>

Later restart apache and try to access you applications with inside the same intranet network:
computer-name/app-folder/

In general this isn't the best solution because you are exposing entire root folder htdocs, also I would suggest to you to move you application from htdocs and define application in httpd-vhosts.conf file. You can create aliases for application outside htdocs folder which are defined in httpd-vhosts.conf


text:
Q: Realm - Migration error Error: Realm on disc is newer than the one specified: v1 vs. v0
I have tried to add migration code for my project. I see the following error but not sure how to resolve it. I noticed the documentation needs to be updated for RealmMigration. Also I don't want to delete my data, I need to keep it stored. I may not be setting this up right but I was trying to follow the documentation which to me is a bit confusing for migration. Here is my code:
    visnetawrap.realmConfiguration = new RealmConfiguration.Builder(this).build();

    Realm.setDefaultConfiguration(visnetawrap.realmConfiguration);

    try {
        Realm tempRealmThread = Realm.getDefaultInstance();
        tempRealmThread.close();
    }
    catch (RealmMigrationNeededException e) {
        Realm.migrateRealm(visnetawrap.realmConfiguration, new RealmMigration() {
            @Override
            public long execute(Realm realm, long l) {
                return 1;
            }
        });
        Realm.setDefaultConfiguration(visnetawrap.realmConfiguration);
        Log.d("RealmMigration", "Schema has been upgraded.");
    }

A: You need to reflect your changes in the migration. Check this example, hope it helps.


text:
Q: How to stop wp_postmeta from being called on archive and search pages? Currently, when I load a search or result page, it queries the wp_postmeta table which is leading to the page taking ages to load. I realise this is a result of this table being huge (70k rows), and because of how much data is loaded into the cache.
Is there a way to stop update_post_caches from being called when these pages are loaded, and then send custom (and more efficient) queries to the database once the template has been loaded?

A: add_filter('pre_get_posts', 'customize_query');
function customize_query($query) {
    if($query->is_main_query() && ($query->is_search() || $query->is_archive()) {
        $query->set('update_post_meta_cache', false);
        $query->set('update_post_term_cache', false);
    }
}

Then wordpress will make 2 less queries for those pages & then you can use the $wpdb object to write custom queries.


text:
Q: How to setup clj-webdriver 0.7.2 with phantomjs I keep trying to set up phantomjs to create a web scraper, but I can't get the driver to work. I have added the lein dependencies like so:
  [org.seleniumhq.selenium/selenium-server  "2.47.1"]
  [com.codeborne/phantomjsdriver  "1.2.1"
    :exclusions [org.seleniumhq.selenium/selenium-java
    org.seleniumhq.selenium/selenium-server
    org.seleniumhq.selenium/selenium-remote-driver]]

Then in my script:
   (ns vendors-api.routes.scrapers.resource
     (:require [clj-webdriver.core :refer [new-webdriver]])
     (:import
       (org.openqa.selenium.phantomjs PhantomJSDriver)
       (org.openqa.selenium.remote DesiredCapabilities)))

   (def driver
    (new-webdriver
      {:browser (PhantomJSDriver. (DesiredCapabilities. ))}))

I keep getting the following error:
CompilerException java.lang.reflect.InvocationTargetException, compiling

What am I missing?

A: I expect your dependencies are incorrect/incomplete.
The following dependency list worked for me:
[clj-webdriver "0.7.2"]
[org.seleniumhq.selenium/selenium-java "2.51.0"]
[com.codeborne/phantomjsdriver "1.2.1" :exclusions [org.seleniumhq.selenium/selenium-java]]

And then
(require ' [clj-webdriver.core :as driver])
(def my-driver (driver/new-driver {:browser :phantomjs}))

A: The dependencies as stated in the question are correct.
The final setup that got it to work in the script is as the following:
(:require [clj-webdriver.taxi :as taxi])

(System/setProperty  "phantomjs.binary.path"  "/path/to/binary")

(taxi/with-driver {:browser :phantomjs} (forms-to-evaluate)...)

Hope this helps someone else out there


text:
Q: DataTable select won't fire for second time I have 2 tables in my view where I select a row from table1 and data return in table2
The problem is when i select second row it won't send ajax request while i can see click being triggered .
Screenshots
view

results

Code
script

Question
Why can't I get my next clicks to send request to back-end? what should I do to fix this?
Update
Sample code

A: Solved
I shouldn't have add retrieve:true, using destroy: true, is enough.


text:
Q: Can I update Nexus Maven "LATEST" metadata without a scheduled task? I'm running Nexus and I have a snapshots Maven repository. When I publish artifacts to that repository I also run a "Rebuild Maven Metadata Files" type task that runs for about 5 minutes and updates "LATEST" to actually point to the newest artifacts. Can I update that LATEST reference some other way? I publish with Gradle. Can Gradle just update that specific groups metadata?
Thanks

A: The maven metadata file is NOT managed by Nexus but by the client side tool. By default that is Maven and it downloads the metadata file as part of the deployment, updates it with the new snapshot data and uploads it again.
Potentially Gradle does not do that correctly and that is the reason you have to use the workaround of using the Nexus scheduled task. I don't think Gradle has any further tools to fix it up better. The only thing I can think of you could do is to kick off the scheduled task from Gradle automatically. But you would still have the timing problem.
Best would be to file a bug against Gradle and get it fixed.


text:
Q: Do version control systems use diffs to store binary files? How do popular version control systems (svn, git) handle storing revisions to a binary document?  I have projects with binary sources that are periodically updated and need to be checked in (mostly Photoshop documents, custom data format and a few word processing documents).  I've always been worried about checking in the binaries because I thought that the VCS might take a simple route of simply uploading a new copy of the binary each time - and hence my repository would get huge quickly.
If I have several data blocks (let's call them A, B, C, D, etc) and I have a binary file that on first check in looks like ABC, but then on the second check in has been modified to ADBE, will my VCS be smart enough to only store the changed bits or will it create an entirely new image of the file?

A: tl;dr
Git can store just diffs of binary files, but it's not very efficient, so you probably should use some external tools like lfs.
Slightly longer explanation
By default, git doesn't store diffs between commits. When you change some file and make a new commit, git stores object with a content of the whole file. It doesn't matter if you change just one line, or rewrite whole file - git doesn't store diffs, at least at first place. There is a piece of git called git-gc (garbage collector) responsible for tasks such removing dangling commits and optimization, it runs another git command - git-repack which does exactly what you ask for. It takes the whole bunch of objects and stores them inside one pack using delta compression.
Unfortunately packing with git-repack is not especially efficient when comes to compressing binary files. You can always tweak it, but if your files change a lot, or if they are really big, you should probably use some external tool like lfs.

A: We use CollabNet SubVersion Edge.
I just had occasion to commit a 50 megabyte Photoshop .psd file within which I had updated Smart Filter parameters.
09/18/2016  05:15 PM        53,015,186 StarSpikesPro4RealismTest.psd

My SVN repository size grew from:
 Total Files Listed:
       19157 File(s) 26,148,088,902 bytes

to
 Total Files Listed:
       19159 File(s) 26,152,019,035 bytes

That's less than 10% of the size of the .psd file, so quite clearly the entire 50 megabyte file wasn't stored, but a delta was calculated.
Keep in mind that some files, e.g., Photoshop images, may be themselves compressed by their associated application, so the binary contents of the stored file may be entirely different from edit to edit, and thus won't yield good delta performance on any system.  But you could choose to disable that compression in Photoshop.  This one was actually compressed on save, but even with such compression enabled we saw only a small growth in the repository size.
In my experience in general, an SVN repository used primarily for code development and storage of some associated binary files doesn't seem to grow quickly at all.  It's hard to compare specifics, but the above repository, 8 years old and worked on actively by 2 people full-time, containing Visual Studio solutions and mix of downloaded libraries, non-source-code development files such as graphics, build results, documentation, etc., has only grown to 26 gigabytes.  The server has a RAID 5 array of three 120 GB SSDs and I don't anticipate it needing an upgrade for years.
-Noel

A:
How do popular version control systems (svn, git) handle storing revisions to a binary document?

Rather smart, some are just smarter (but all store changes, not full new version of artifacts)
In my dirty fast tests some time ago (at the time of Git 1.7.*)  for the same test-case (same changes in MBs of binaries)  the same sequence produced slightly less (a few percents) SVN-repo, compared to Git.
But, on the other hand:
Git-LFS or Mercurial+LargeFiles Extension allow to store binaries (mostly LARGE) outside repository (repo have only pointers to objects in external location) and have the best from both worlds: fast small repo and versioning binaries


text:
Q: How do I override DrawItem for BS_SPLITBUTTON buttons If I make a new button class inheriting from CButton, specifying the BS_OWNERDRAW style , and overriding the DrawItem method I can control the rendering of the button, like this:
void CMyButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) {
    CDC dc;
    dc.Attach(lpDrawItemStruct->hDC);
    RECT rect = lpDrawItemStruct->rcItem;
    dc.FillSolidRect(&rect, RGB(0, 0xFF, 0));
    dc.Detach();
}

m_button.Create(L"Foo", WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, CRect(0, 150, 100, 200), this, IDC_FOO);

I get the following result:

which is what I hoped for. However if I instead inherit my button from CSplitButton, which adds the BS_SPLITBUTTON style, I get the following result:

which is not the result I had hoped for (I had hoped it would look exactly the same as the CButton). The DrawItem method isn't being called in this case so I guess BS_SPLITBUTTONS are treated differently by the system.
How can I get the result I want, a button with split button behaviour with customized drawing?

A: As it says in MSDN for BS_OWNERDRAW:

Creates an owner-drawn button. The owner window receives a WM_DRAWITEM
  message when a visual aspect of the button has changed. Do not
  combine the BS_OWNERDRAW style with any other button styles.

(My emphasis).
If you're doing your own drawing, you have to do all of it yourself.


text:
Q: How to get SQLite db values in Arraylist to Listview I need to set adapter values in a listview. In it, I created an ArrayList to get data from SQLite DB and I need to pass it to a listView with 3 columns. Here I mentioned my codes.
Where do I need to call my data Stored in local Db?
DBHelper.java
 public ArrayList<SQLPojo.UserDetails> getUserDetails() {

    ArrayList<SQLPojo.UserDetails> aUserDetailList = new ArrayList<SQLPojo.UserDetails>();

    try {

      String aQuery = "SELECT * FROM " + TABLE_NAME;

      Cursor aCursor = mySqliteDataBase.rawQuery(aQuery, null);

      aCursor.moveToFirst();
      if(aCursor.getCount() > 0) {
        SQLPojo.UserDetails aUserDetails = myReturnValues.getUserDetailInstance();
        aUserDetails.setId(aCursor.getString(aCursor
                .getColumnIndex("ID")));
        aUserDetails.setUsername(aCursor.getString(aCursor
                .getColumnIndex("USERNAME")));
        aUserDetails.setPlace(aCursor.getString(aCursor
                .getColumnIndex("PLACE")));
        aUserDetailList.add( aUserDetails );
      }
      aCursor.close();
    }
    catch(android.database.SQLException e)
    {
      e.printStackTrace();
    }
    return aUserDetailList;
  }

In this class, I am going to get all data and list it to the listview.
GetAllValues.java
public class SQLViewAllData extends Activity {

private SQLDbHelper myDbHelper;
private SQLCustomViewAllDataAdapter myAdapter;
private ListView myListView;
private ArrayList<SQLPojo> aList = new ArrayList<>();
private Activity myContext;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview_view_data);

    widgetInitialization();
    viewAllData();
}
//Initializing Widgets
public void widgetInitialization() {
    myDbHelper = new SQLDbHelper( myContext );
    myListView = (ListView)findViewById( R.id.listview_view_data_LV );
}

public ArrayList<SQLPojo.UserDetails> getUserInfo() {
    return myDbHelper.getUserDetails();
}

//view all data stored in DB
public void viewAllData( ) {
    myAdapter = new SQLCustomViewAllDataAdapter( SQLViewAllData.this,aList);
    myListView.setAdapter( myAdapter );
}}

This is my Adapter Class to get all values
CustomAdapter.java
 public View getView( int aPosition, View aConvertView, ViewGroup aParent ) {

LayoutInflater inflater = myActivity.getLayoutInflater();
ViewHolder aHolder;

if( aConvertView == null ) {
  aConvertView = inflater.inflate( R.layout.layout_inflate_custom_listview_view_data, null );

  aHolder = new ViewHolder();

  aHolder.aTextViewID = ( TextView )aConvertView.findViewById( R.id.custom_listview_view_data_ID );
  aHolder.aTextViewUN = ( TextView )aConvertView.findViewById( R.id.custom_listview_view_data_UN );
  aHolder.aTextViewPLC = ( TextView )aConvertView.findViewById( R.id.custom_listview_view_data_Place );
  aConvertView.setTag( aHolder );
}
else {
  aHolder = (ViewHolder) aConvertView.getTag();
}

aHolder.aTextViewID.setText(myData.get(aPosition).toString());
aHolder.aTextViewUN.setText(myData.get(aPosition).toString());
aHolder.aTextViewPLC.setText(myData.get(aPosition).toString());

return aConvertView;

}

A: It should be straight forward. Just do:
public void viewAllData( ) {
  aList = getUserInfo(); //this is where you call the local database.
  myAdapter = new SQLCustomViewAllDataAdapter( SQLViewAllData.this,aList);
  myListView.setAdapter( myAdapter );
}

Also, make sure you change aList from type SQLPojo to SQLPojo.UserDetails.


text:
Q: AsyncLocal values not correct with TPL Dataflow Consider this example:
class Program

{
    private static readonly ITargetBlock<string> Mesh = CreateMesh();
    private static readonly AsyncLocal<string> AsyncLocalContext
        = new AsyncLocal<string>();

    static async Task Main(string[] args)
    {
        var tasks = Enumerable.Range(1, 4)
            .Select(ProcessMessage);
        await Task.WhenAll(tasks);

        Mesh.Complete();
        await Mesh.Completion;

        Console.WriteLine();
        Console.WriteLine("Done");
    }

    private static async Task ProcessMessage(int number)
    {
        var param = number.ToString();
        using (SetScopedAsyncLocal(param))
        {
            Console.WriteLine($"Before send {param}");
            await Mesh.SendAsync(param);
            Console.WriteLine($"After send {param}");
        }
    }

    private static IDisposable SetScopedAsyncLocal(string value)
    {
        AsyncLocalContext.Value = value;

        return new Disposer(() => AsyncLocalContext.Value = null);
    }

    private static ITargetBlock<string> CreateMesh()
    {
        var blockOptions = new ExecutionDataflowBlockOptions
        {
            BoundedCapacity = DataflowBlockOptions.Unbounded,
            EnsureOrdered = false,
            MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
        };

        var block1 = new TransformBlock<string, string>(async input =>
        {
            await Task.Yield();
            Console.WriteLine(
                $"   Block1 [thread {Thread.CurrentThread.ManagedThreadId}]" +
                $" Input: {input} - Context: {AsyncLocalContext.Value}.");

            return input;
        }, blockOptions);

        var block2 = new TransformBlock<string, string>(async input =>
        {
            await Task.Yield();
            Console.WriteLine(
                $"   Block2 [thread {Thread.CurrentThread.ManagedThreadId}]" +
                $" Input: {input} - Context: {AsyncLocalContext.Value}.");

            return input;
        }, blockOptions);

        var block3 = new ActionBlock<string>(async input =>
        {
            await Task.Yield();
            Console.WriteLine(
                $"   Block3 [thread {Thread.CurrentThread.ManagedThreadId}]" +
                $" Input: {input} - Context: {AsyncLocalContext.Value}.");
        }, blockOptions);

        var linkOptions = new DataflowLinkOptions {PropagateCompletion = true};

        block1.LinkTo(block2, linkOptions);
        block2.LinkTo(block3, linkOptions);

        return new EncapsulatedActionBlock<string>(block1, block3.Completion);
    }
}

internal class EncapsulatedActionBlock<T> : ITargetBlock<T>
{
    private readonly ITargetBlock<T> _wrapped;

    public EncapsulatedActionBlock(ITargetBlock<T> wrapped, Task completion)
    {
        _wrapped = wrapped;
        Completion = completion;
    }

    public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader,
        T messageValue, ISourceBlock<T> source, bool consumeToAccept) =>
        _wrapped.OfferMessage(messageHeader, messageValue, source, consumeToAccept);

    public void Complete() => _wrapped.Complete();

    public void Fault(Exception exception) => _wrapped.Fault(exception);

    public Task Completion { get; }
}

internal class Disposer : IDisposable
{
    private readonly Action _disposeAction;

    public Disposer(Action disposeAction)
    {
        _disposeAction = disposeAction
            ?? throw new ArgumentNullException(nameof(disposeAction));
    }

    public void Dispose()
    {
        _disposeAction();
    }
}

The result of the execution will be something like:

Before send 1
After send 1
Before send 2
After send 2
Before send 3
After send 3
Before send 4
After send 4
   Block1 [thread 9] Input: 3 - Context: 3.
   Block1 [thread 10] Input: 2 - Context: 1.
   Block1 [thread 8] Input: 4 - Context: 4.
   Block1 [thread 11] Input: 1 - Context: 2.
   Block2 [thread 9] Input: 2 - Context: 3.
   Block2 [thread 7] Input: 1 - Context: 2.
   Block2 [thread 10] Input: 3 - Context: 3.
   Block2 [thread 8] Input: 4 - Context: 4.
   Block3 [thread 11] Input: 4 - Context: 4.
   Block3 [thread 7] Input: 1 - Context: 2.
   Block3 [thread 9] Input: 3 - Context: 3.
   Block3 [thread 4] Input: 2 - Context: 3.

Done

As you can see the passed context value and stored one's are not always the same after moving to second TDF block. This behavior screws up multiple Logging frameworks' LogContext feature usages.

*

*Is it an expected behavior (please explain why)?

*Does the TPL Dataflow messes up the execution context somehow?

A: To understand what's going on you must understand how Dataflow blocks work. There are no blocked threads inside them, waiting for messages to arrive. The processing is done by worker tasks. Lets consider the simple (and default) case of MaxDegreeOfParallelism = 1. Initially there are zero worker tasks. When a message is posted asynchronously with SendAsync, the same task that posted the message becomes a worker task and starts processing the message. If another message is posted while the first is processed, something else will happen. The second message will be enqueued in the block's input queue, and the task that posted it will complete. The second message will be processed by the worker-task that processed the first message. As long as there are messages enqueued in the queue, the initial worker task will pick them and process them one by one. If at some moment there are no more buffered messages, the worker task will complete, and the block will return in it's initial state (zero worker tasks). The next SendAsync will become the new worker task, and so on. With MaxDegreeOfParallelism = 1, only one worker task can exist at any given moment.
Lets demonstrate this with an example. Below is an ActionBlock that is feeded with delay X, and processes each message with delay Y.
private static void ActionBlockTest(int sendDelay, int processDelay)
{
    Console.WriteLine($"SendDelay: {sendDelay}, ProcessDelay: {processDelay}");
    var asyncLocal = new AsyncLocal<int>();
    var actionBlock = new ActionBlock<int>(async i =>
    {
        await Task.Delay(processDelay);
        Console.WriteLine($"Processed {i}, Context: {asyncLocal.Value}");
    });
    Task.Run(async () =>
    {
        foreach (var i in Enumerable.Range(1, 5))
        {
            asyncLocal.Value = i;
            await actionBlock.SendAsync(i);
            await Task.Delay(sendDelay);
        }
    }).Wait();
    actionBlock.Complete();
    actionBlock.Completion.Wait();
}

Lets see what happens if we send the messages fast and process them slowly:
ActionBlockTest(100, 200); // .NET Core 3.0

SendDelay: 100, ProcessDelay: 200
  Processed 1, Context: 1
  Processed 2, Context: 1
  Processed 3, Context: 1
  Processed 4, Context: 1
  Processed 5, Context: 1

The AsyncLocal context remained the same, because the same worker task processed all the messages.
Now lets send the messages slowly and process them fast:
ActionBlockTest(200, 100); // .NET Core 3.0

SendDelay: 200, ProcessDelay: 100
  Processed 1, Context: 1
  Processed 2, Context: 2
  Processed 3, Context: 3
  Processed 4, Context: 4
  Processed 5, Context: 5

The AsyncLocal context is different for each message, because each message was processed by a different worker task.
The moral lesson of this story is that each SendAsync does not guarantee the creation of a single asynchronous workflow that follows the message until the end of its journey, to the end of the pipeline. So the AsyncLocal class cannot be used to hold ambient data for each message.


text:
Q: Client Side File Upload to S3 I have a NodeJS/Express webapp running on AWS Elastic Beanstalk and I want to allow my users to upload profile pictures to AWS S3.
I want the client to directly upload to S3 because I'm planning to implement bigger file uploads later. I'm fairly new to NodeJS and AWS, how can I achieve what I'm looking for?

A: It is not a good practice to upload to s3 from client side. If you want to upload to s3, you need to specify the AWS accessKeyId and secretAccessKey. If you do that on the client side, everybody can see that.
Check this: Amazon S3 direct file upload from client browser - private key disclosure
If you choose to go with Express, you can use the multer and multer-s3 packages with aws-sdk package.


text:
Q: Gradient boosting on Vowpal Wabbit Is there a way to use gradient boosting on regression using Vowpal Wabbit? I use various techniques that come with Vowpal Wabbit that are helpful. I want to try gradient boosting along with that, but I can't find a way to implement gradient boosting on VW.

A: The idea of gradient boosting is that an ensemble model is built from black-box weak models. You can surely use VW as the black box, but note that VW does not offer decision trees, which are the most popular choice for the black-box weak models in boosting. Boosting in general decreases bias (and increases variance), so you should make sure that the VW models have low variance (no overfitting). See bias-variance tradeoff.
There are some reductions related to boosting and bagging in VW:

*

*--autolink N adds a link function with polynomial N, which can be considered a simple way of boosting.

*--log_multi K is an online boosting algorithm for K-class classification. See the paper. You can use it even for binary classification (K=2), but not for regression.

*--bootstrap M M-way bootstrap by online importance resampling. Use --bs_type=vote for classification and --bs_type=mean for regression. Note that this is bagging, not boosting.

*--boosting N (added on 2015-06-17) online boosting with N weak learners, see a theoretic paper


text:
Q: How to add data to CSV columns, one by one using pandas I have a pandas script as follows. Where I am reading multiple csv files in a given folder. All the csv files have a similar format and columns.
For a given column(Area), I want to add all the rows. Then I want to save this data into a new CSV file.
This is the code so far.
import pandas as pd
import glob

path = r'C:\Users\kundemj\Desktop\Post_Processing\HEA517_2000' # path
all_files = glob.glob(path + "/*.csv")

for filename in all_files:
    df = pd.read_csv(filename)
    area_sum = df['Area'].sum()
    print(area_sum)

I could figure out, by using excel_write function, but I want to use 'to_csv', and also with mode = 'append', as I have bunch of folders with same filenames.
The CSV file format I am looking for is as follows:
filename1, filename2, filename3,.....
area_sum1, area_sum2, area_sum3,.....

A: You could try this:
import pandas as pd
import glob

path = r'C:\Users\kundemj\Desktop\Post_Processing\HEA517_2000' # path
all_files = glob.glob(path + "/*.csv")

# Create an empty dict
results = {"filename": [], "sum": []}

# Iterate on files and populate the newly created dict
for filename in all_files:
    results["filename"].append(filename)
    df = pd.read_csv(filename)
    results["sum"].append(df['Area'].sum())

# Save to csv file
results = pd.DataFrame(results)
results.to_csv(path="path_to_file.csv", index=False)


text:
Q: When to decide to use typedef's data types or C's built-in standard data types gcc 4.7.2
c89
Hello,
I am using the Apache Portable Runtime and looking at their typedef's
typedef short apr_int16_t
typedef int apr_int16_t
typedef size_t apr_size_t /* This is basically the same, so what's the point */

etc.

*

*So what is the point of all this?

*When should you decided to use C's built-in standard data types or typedef's data types?

I just gave a example using the APR. However, I am also speaking generally as well. There is also the stdint.h header file that typedef's data types.
Many thanks for any suggestions,

A: In my opinion, it is better to have custom defined data types for native data types of the system as it helps in clearly distingushing the size of the types.
For Ex: A long may be 32 bit or 64 bit depending on the machine in which your code runs and the way it has been built. But, if your code specifically needs a 64 bit variable, then naming it as uint_64_t or something similar will always help in associating the size clearly.
In such cases, the code be written as:
    #if _64BIT_
    typedef long uint_64_t
    #else
    typedef long long uint_64_t
    #endif

But as suggested by Mehrdad, don't use it "just for kicks". : )

A: Great question.

*

*So what is the point of all this?
It's meant to be for abstraction, but like anything else, it is sometimes misused/overused.
Sometimes it's necessary for backwards compatibility (e.g. typedef VOID void in Windows), sometimes it's necessary for proper abstraction (e.g. typedef unsigned int size_t), and sometimes it's completely pointless logically, but makes typing easier (e.g. typedef char const *LPCSTR in Windows).

*When should you decided to use C's built-in standard data types or typedef's data types?
If it makes something easier, or if it implements a proper abstraction barrier, use it.
What exactly that means is something you'll just have to learn over time.
But don't use it "just for kicks"!


text:
Q: How to time requestAnimationFrame() independent of refreshrates I have a situation where I want to animate the width of a 600px wide div to 0px in 1 second. I could use requestAnimationFrame() for this. But I wouldn't really be a 100% sure if the animation will take 1 second.
It would look something like this:
let width = 600;
let animation;
function animateWidth(){
  if(width <= 0){
    window.cancelAnimationFrame();
  }else{
    width -= 10; // (600px/60fps)
  }
  document.getElementById('id1').setAttribute('width', width);
  animation = window.requestAnimationFrame(animateWidth);
}
animation = window.requestAnimationFrame(animateWidth);

The thing is, when a device has a different fps it will affect the duration of the animation (at 30fps it will take 2 seconds and at 60 fps it will take one). I want to make sure this duration of the animation is always one second. If the fps-rate is different I would want to change the new values of the width based on the duration (so animating at 30 fps we would change the width by 20 each step(600px/30fps)).

*

*Is there any way I can achieve this while using requestAnimationFrame? If I could get the average interval between frames or the fps that would work I think.

*Am I perhaps worrying about something that isn't really a big issue?

*What fps can I expect on different devices (mobile, pc, tablet, etc.)?

documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame

A: requestAnimationFrame passes the time since the page loaded to the callback so for example

const startValue = 600;
const endValue = 0;

// return a value between start and end as l goes from 0 to 1
function lerp(start, end, l) {
  return start + (end - start) * l;
}

const startTime = performance.now();
const durationInSeconds = 1;
const element = document.getElementById('id1');

function animateWidth(now) {
  const timeSinceStartInSeconds = (now - startTime) * 0.001;

  // l goes from 0 to 1 over durationInSeconds;
  const l = Math.min(timeSinceStartInSeconds / durationInSeconds, 1);

  element.setAttribute('width', lerp(startValue, endValue, l));

  // if we haven't finished request another animation frame
  if (l < 1) {
    requestAnimationFrame(animateWidth);
  }
}
requestAnimationFrame(animateWidth);
#id1 { background: red; }
<canvas id="id1"></canvas>

If it was me I'd probably try to make it a function

// return a value between start and end as l goes from 0 to 1
function lerp(start, end, l) {
  return start + (end - start) * l;
}

function animateAttribute(element, attribute, startValue, endValue, duration) {
  const startTime = performance.now();

  function animate(now) {
    const timeSinceStart = (now - startTime) * 0.001;

    // l goes from 0 to 1 over durationInSeconds;
    const l = Math.min(timeSinceStart / duration, 1);

    element.setAttribute(attribute, lerp(startValue, endValue, l));

    // if we haven't finished request another animation frame
    if (l < 1) {
      requestAnimationFrame(animate);
    }
  }
  requestAnimationFrame(animate);
}

const element = document.getElementById('id1');
const attribute = 'width';
const start = 600;
const end= 0;
const duration = 1;

animateAttribute(element, attribute, start, end, duration);
#id1 { background: red; }
<canvas id="id1"></canvas>

Also by passing l to any of these functions and passing the result to lerp you can change how the animation happens to match any of these styles of motion.
As for your other questions

Is there any way I can achieve this while using requestAnimationFrame? If I could get the average interval between frames or the fps that would work I think.

You can compute the interval between frames. Example:
let then = performance.now();
function animate(now) {
  deltaTimeInMilliseconds = (now - then);
  then = now;

  ...
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

Am I perhaps worrying about something that isn't really a big issue?

Only you can answer that question

What fps can I expect on different devices (mobile, pc, tablet, etc.)?

Most devices are 60fps but there are gamer monitors that run at 120fps or 240fps as well as VR (and WebVR) which generally runs at 90fps or more and you can use browsers inside VR. Whether or not you care about any of those situations is up to you.

A: Measuring time since the animation start and using it as a reference in width calculation would be a common practice here.
Using this code the animation will last one second no matter what FPS the device has.
const el = document.getElementById('id1');
const start = Date.now();

function animateWidth() {
  const t = (Date.now() - start) / 1000; // 1000 - one second

  if(t >= 1) {
    el.setAttribute('width', 0);
  }
  else {
    el.setAttribute('width', 600 * (1 - t));
    window.requestAnimationFrame(animateWidth);
  }
}

animateWidth();


text:
Q: C# generic class contains list of  but I cannot access methods of the  class I have a Generic class,DisplayGrid ...
class DisplayGrid<T> where T : class

... which has a List of <T> as a property.
public List<T> allRows;

... within a property of DisplayGrid I want to iterate over allRows and access a method of <T> ...
foreach (T r in this.allRows)
{
  if (!(r.isAValidRow))
  {
    blnRowsValid = false;
    break;
  }
}

... however attempting to make use of the isAValidRow method defined on <T> generates a compiler error ...
error CS1061: 'T' does not contain a definition for 'isAValidRow' and no extension method 'isAValidRow' accepting a first argument of type 'T' could be found

Reading back through old questions it seems this area has changed over the years. It seems unlikely that such a basic requirement would still be impossible ?

EDIT 1 : In the original version of this question I perhaps went too far in trying to simplify the sample code. I only included a single Row class but what I meant to imply is that there were multiple classes which might be used as a 'Row' when instantiating the DisplayGrid class.
I have now adapted the classes below so that there are two different classes which might be used as the <T> of the DisplayGrid class.
In doing this I hope to address a number of comments which, correctly, suggested there wasn't any need to use Generics, or that the 'where' directive could be limited to the only class, Row, which I had supplied in the example.
In the changes to the example I have defined classes RowA and RowB and I do appreciate that as shown they are functionally identical but this is just to make a simple example - in actual use RowA and RowB would be sufficiently distinctive to justify their not being the same class.

Full Classes
All Both classes referenced above appear below :
class DisplayGrid<T> where T : class
{
    public List<T> allRows;

    public DisplayGrid()
    {
        this.allRows = new List<T>();
    }

    public bool hasRowMsgs
    {
        get
        {
            bool blnRowsValid = true;
            foreach (T r in this.allRows)
            {
                if (!(r.isAValidRow))
                {
                    blnRowsValid = false;
                    break;
                }
            }
            return blnRowsValid;
        }
    }
    public bool isAValidTable
    {
        get {
            if (this.hasRowMsgs == false)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
class RowA
{
    public List<string> rowMsgs;

    public RowA()
    {
        rowMsgs = new List<string>();
    }

    public bool isAValidRow
    {
        get {
            return (this.rowMsgs.Count == 0) ? true : false;
        }
    }
}
class RowB
{
    public List<string> rowMsgs;

    public RowB()
    {
        rowMsgs = new List<string>();
    }

    public bool isAValidRow
    {
        get {
            return (this.rowMsgs.Count == 0) ? true : false;
        }
    }
}

A: After having read, and understood the significance of, the comment by Lee I now have a working version. The key to making it work was defining an Interface, IRow and applying it to the 'Row' classes, RowA and RowB.
For the sake of future readers here are the classes which now work.
Two points

*

*I have changed the code a little from the previous example code within the properties/methods to make them more succinct and to resolve an unrelated defects;

*RowA and RowB are unrealistically similar, this is only to allow the issue to be illustrated simply and briefly, clearly in a real implementation they would be less similar.

class DisplayGrid<T> where T : IRow
{
    public List<T> allRows;

    public DisplayGrid()
    {
        this.allRows = new List<T>();
    }

    public bool hasRowMsgs
    {
        get
        {
            bool blnHasRowMsgs = false;
            foreach (T r in this.allRows)
            {
                if (!(r.isAValidRow))
                {
                    blnHasRowMsgs = true;
                    break;
                }
            }
            return blnHasRowMsgs;
        }
    }
    public bool isAValidTable
    {
        get {
            return (!(this.hasRowMsgs));
        }
    }
}
interface IRow
{
    bool isAValidRow { get; }
}
public class RowA : IRow
{
    public List<string> rowMsgs;

    public bool isAValidRow {
        get {
            return this.rowMsgs.Count > 0 ? false : true;
        }
    }

    public RowA()
    {
        rowMsgs = new List<string>();
    }
}
public class RowB : IRow
{
    public List<string> rowMsgs;

    public bool isAValidRow {
        get {
            return this.rowMsgs.Count > 0 ? false : true;
        }
    }

    public RowB()
    {
        rowMsgs = new List<string>();
    }
}

A: If you change the first line to
class DisplayGrid<T> where T : Row

then it should work.
Explanation: The method you are trying to use is a property of a Row; it is not a method of 'class' so it is not recognized.


text:
Q: Weak star convergence leads to weak convergence of derivative? Let $u_\epsilon \in W^{1,p}(\Omega)$ be a sequence with $\Omega \subset \mathbb{R}^n$ bounded. Let $u_\epsilon \rightharpoonup^* u$ weakly* in $L^\infty (\Omega)$ (for a subsequence) with $u \in W^{1,p}(\Omega)$ and assume $\sup_\epsilon \vert \nabla u_\epsilon\vert_{L^p (\Omega; \mathbb{R}^n)} < C$.
Proof that $\nabla u_\epsilon \rightharpoonup \nabla u$ weakly in $L^p (\Omega; \mathbb{R}^n)$ (for a subsequence).

My idea so far:
$\nabla u_\epsilon$ is bounded, therefore there exists a weak limit (for a subsequence).
$u_\epsilon \rightharpoonup^* u$ weakly* in $L^\infty (\Omega)$, therefore $u_\epsilon \rightharpoonup u$ weakly in $L^p (\Omega)$, which means that  $~\int_\Omega \phi \partial_x u_\epsilon \to \int_\Omega \phi \partial_x u ~$  for all $~\phi \in W^{1,p^*}(\Omega)$.
If I am correct, the weak convergence in $L^p (\Omega; \mathbb{R}^n)~$ is $~\int_\Omega \Phi \cdot \nabla u_\epsilon \to \int_\Omega \Phi \nabla u~$ for all $~\Phi \in L^{p^*} (\Omega; \mathbb{R}^n)$, but I can't seem to get that from the lines above.
Any help is appreciated.

A: You are on the right track. $u_\epsilon\rightharpoonup u$ in $L^p(\Omega)$ as you noted. Since the sequence is bounded in $W^{1,p}(\Omega)$, there is a subsequence (denoted by $u_{\epsilon'}$) such that
$$
u_{\epsilon'} \rightharpoonup \tilde u \quad \textrm{ in }W^{1,p}(\Omega).
$$
Since $W^{1,p}(\Omega)$ is continuously embedded into $L^p(\Omega)$ it follows that both weak limits are the same, $u=\tilde u$. Hence
$$
u_{\epsilon'} \rightharpoonup u\quad \textrm{ in }W^{1,p}(\Omega).
$$
The gradient mapping $\nabla: W^{1,p}(\Omega)\to L^p(\Omega)$ is linear and continuous, thus weakly continuous, implying
$$
\nabla u_{\epsilon'} \rightharpoonup \nabla u\quad \textrm{ in }L^{p}(\Omega).
$$


text:
Q: How do I calculate the most probable orbital an electron is in? If I saw a snapshot in time of an electron near a proton (Hydrogen), then the electron can be in any orbital as long as it doesn't lie on a node of the wave function. So how would I determine which orbital it is most likely occupying?
EDIT: To phrase this a different way, how can I find out which wave function has the highest probability at a location. According to this graph http://i.stack.imgur.com/UNelW.gif for any r I chose there is one orbital (except where they intersect where there are two) which has the highest probability value. This is what I mean. I guess as an added question, what is this quality that I seem to mistakenly be describing?

A: Quantum mechanics tells us the probability for an electron in a certain orbital to be in a certain position or momentum state. Inverting this to find the probability for the electron to be in a certain orbital given its position or momentum state requires some a priori idea of what orbitals are the most probable. This is stated succinctly by Bayes' theorem:
$$
P(n,k,m \mid \vec x) \propto P(\vec x \mid n,k,m) P(n,k,m)
$$
The coefficient in this proportionality is fixed by requiring the norm of the probability to be unity. Without some good model for these a priori probabilities, the problem is un-answerable.
Luckily, a good model for these might be taken from thermodynamics. If the atom is in a bath of temperature $T$, the a priori probability to be in the state $\mid n,k,m \rangle$ is
$$
P(n,k,m) \propto \exp \left( - \frac{E(n,k,m)}{k_B T}\right)
$$
Again, the coefficient in this proportionality is fixed by requiring the norm of the probability to be unity. Of course, this is very simplified and ignores the kinetic and vibrational states available to atoms and molecules, which could complicate matters.
Edit: John Rennie's answer made be realize that the position $\vec x$ must be specified with some resolution $d^3 x$, otherwise the probabilities $P(\vec x \mid n,k,m) = \langle \vec x \mid n, k, m \rangle d^3 x$ are strictly 0.

A: I think you may have confused two separate things.
By orbital we normally mean the distinct atomic orbitals like $1s$, $2s$, $2p$, etc. These actually only exist for hydrogen atoms (and single electron ions) so let's just consider hydrogen for now. In practice if we do an experiment with a sample of hydrogen its energy is well characterised and under normal conditions the atoms will be in their ground state. That means we know the electron is in the $1s$ orbital.
If there is some energy input of a few eV or more, e.g. if you're heating the hydrogen, then there will be a chance that electrons will be excited to higher orbitals. In this case, as jwimberley says in his answer, the probability of state occupation will be given by a Boltzmann distribution.
But what I'm guessing you mean is where actually is the electron? That is, if we took a photograph as you suggest where would we see the little dot?
The answer is that the question doesn't make sense because the electron doesn't have a position. It is a delocalised object, not a tiny ball, and you can't ask what its position is because it has no position. However what you could ask is if I fired a high energy particle at different points in the atom what would be the probability of it hitting the electron? This does make sense, because even for a delocalised object the interaction with another object can be localised to an approximate point. In that case the probability of hitting the electon at a point would simply be proportional to $\Psi^*(\vec{r})\Psi(\vec{r})$, where $\Psi(\vec{r})$ is the value of the wavefunction at the point $\vec{r}$.
Response to comment:
Just to get the conclusion from the comments into the answer, The quantity $\psi^*\psi dV$ gives the probability of finding the electron in the volume element $dV$. So for any given volume element the relative values of $\psi^*\psi dV$ for all the different values will give you the relative probabilities that an electron found in that volume element is in the different orbitals.
However this applies only if you can assume that all electron energies are equally likely i.e. there are no other factors that would make some energies more probable than others. In practice it doesn't seem likely this would be the case for any experiment I can think of.


text:
Q: Installing SQL Server 2014 using chef community cookbook (sql_server) I've had a look at the chef community cookbook for installing sql server and it appears that it's tailored for installing SQL express, but I can't seem to work out how to install a standard or developer edition.
The README on the GitHub page (https://github.com/chef-cookbooks/sql_server) says you can just point it to any installation package, however I can't see how you would do this for an ISO (or even the extracted contents of an ISO) given that there's no single EXE package on the ISO media.
Am I missing something obvious, or will I need to roll my own recipe for installing SQL from an ISO (or contents of ISO)?  Ideally I would like to host the installation media on a central package repository behind my firewall.

A: ISOs are intended for DVD images but if you have an ISO shredder (search online for free tools) you'll see a setup.exe in there. Run that and it'll bring you to the installation center where you can choose to install a new instance and do a bunch of other things. It's a wizard type interface so just read the instructions on each page and you should be able to provide the relevant info where needed to successfully complete the installation

A: Option 1:
Customized cookbook is the best option for you use case. Like you said, host .ISO on central repo and create a cookbook that mounts the .ISO drive to run the installation. You should leverage that cookbook template and re-write that windows_package block in the server.rb to install using keyword 'source' with path to the mounted installation files. However, this will be a major work (from past experience...) so if you have only one or two nodes that need to run the cookbook, go with Option 2.
Option 2:
If you have only one or two nodes that need to run the cookbook, I would suggest you to run the basic 'sql_server::server' then upgrade to the version you want using the GUI with the PID product key.
Note that this process can be automated as well using Powershell script. If you are familiar with Powershell, you can automate it using powershell_script block.


text:
Q: extract key value from json python I want help to extract "url" value from - https://www.udemy.com/api-2.0/channels/1640/courses?is_angular_app=true&p=2
import urllib2, json
response = urllib2.urlopen('https://www.udemy.com/api-2.0/channels/1640/courses?is_angular_app=true&p=2')
data = json.load(response)

for data["url"] in data.items():
    print data["url"]

It doesn't work above . Please help

A: Using this code you can get url of first array
import urllib2, json
response = urllib2.urlopen('https://www.udemy.com/api-2.0/channels/1640/courses?is_angular_app=true&p=2')
data = json.load(response)

print data['results'][0]['url']

Use for loop for getting all url from every array
import urllib2, json
response = urllib2.urlopen('https://www.udemy.com/api-2.0/channels/1640/courses?is_angular_app=true&p=2')
data = json.load(response)

i = 0;
for data["url"] in data['results']:
    print data['results'][i]['url']
    i+=1

A: Try this :
import urllib2, json
response = urllib2.urlopen('https://www.udemy.com/api-2.0/channels/1640/courses?is_angular_app=true&p=2')
data = json.load(response)
for i in range(len(data['results'])):
   print data['results'][i]['url']


text:
Q: Python/ Boto 3: How to retrieve/download files from AWS S3? In Python/Boto 3, Found out that to download a file individually from S3 to local can do the following:
        bucket = self._aws_connection.get_bucket(aws_bucketname)
        for s3_file in bucket.list():
            if filename == s3_file.name:
                self._downloadFile(s3_file, local_download_directory)
                break;

And to download all files under one chosen directory:
    else:
        bucket = self._aws_connection.get_bucket(aws_bucketname)
        for s3_file in bucket.list():
            self._downloadFile(s3_file, local_download_directory)

And helper function _downloadFile():
  def _downloadFile(self, s3_file, local_download_destination):
        full_local_path = os.path.expanduser(os.path.join(local_download_destination, s3_file.name))
        try:
            print "Downloaded: %s" % (full_local_path)
            s3_file.get_contents_to_filename(full_local_path)

But both don't seem to be working. Using Boto 3 and Python, would like to be able to download all files, as a zip preferably, under a defined directory on S3 to my local.
What could I be doing wrong, and what's the correct implementation of the parameters?
Thank you in advance, and will be sure to accept/upvote answer
UPDATE CODE: Getting an error: "AttributeError: 'S3' object has no attribute
import sys
import json
import os
import subprocess

import boto3
from boto.s3.connection import S3Connection

s3 = boto3.resource('s3')
s3client = boto3.client('s3')

#This works
for bucket in s3.buckets.all():
    print(bucket.name)

def main():
    #Getting an error: "AttributeError: 'S3' object has no attribute 'download'"
    s3client.download('testbucket', 'fileone.json', 'newfile')

if __name__ == "__main__": main()

A: To download files from S3 to Local FS, use the download_file() method
s3client = boto3.client('s3')
s3client.download_file(Bucket, Key, Filename)

If the S3 object is s3://mybucket/foo/bar/file.txt, then the arguments would be
Bucket   --> mybucket
Key      --> foo/bar/file.txt
Filename --> /local/path/file.txt

There aren't any methods to download the entire bucket. An alternative way would be to list all the objects in the bucket and download them individually as files.
for obj in s3client.list_objects(Bucket='mybucket')['Contents']:
    try:
        filename = obj['Key'].rsplit('/', 1)[1]
    except IndexError:
        filename = obj['Key']

    localfilename = os.path.join('/home/username/Downloads/', filename)  # The local directory must exist.
    s3client.download_file('mybucket', obj['Key'], localfilename)

Note: The response of list_objects() is truncated to 1000 objects. Use the markers in the response to retrieve the remainder of objects in the bucket.


text:
Q: How to get base url with tenant in orchard? How to get the base url with tenant prefix in Orchard? I have a tenant root url, for example domain.com/tenant.
var httpContextAccessor = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IHttpContextAccessor)) as IHttpContextAccessor;
var workContext = WorkContextExtensions.GetWorkContext(httpContextAccessor.Current().Request.RequestContext);
return workContext.CurrentSite.BaseUrl;

When I use this code, I get only http:\domain.com, without tenant prefix.
Thanks a lot for answer.

A: Use ShellSettings. This object contains all the tenant information defined in Settings.txt file.
var settings = workContext.Resolve<ShellSettings>();
var host = settings.RequestUrlHost;
var prefix = settings.RequestUrlPrefix;

Now you need to combine the base URL you already got with tenant prefix above.
If you want to get a relative path that takes into account the current tenant, use Request.AppRelativeCurrentExecutionFilePath. Eg. If your tenant is example.com/tenant and you are requesting page example.com/tenant/mypage it will return ~/mypage. Depending on your scenario, this might also become useful.


text:
Q: env.password is set in fab file but process is still asking sudo password multiple times I have a fabfile.py for my django project that I'm using for auto-deploy.  I use getpass to prompt the user for sudo password on the server, then set env.password, however, when I run other commands, like run('sudo mkdir foo/bar') I get prompted for sudo password with each time a sudo command is run.
Here is the code (sorry for the horrible code block, still a new poster to the site):
 def initial_deploy(*args, **kwargs):
        args = dict([(x, True) for x in args] + kwargs.items())
        env.user = args.get('user','webiken')
        password = getpass('Please provide sudo password for user %(user)s ' %               dict(user=env.user))
        if password:
          env['password'] = password
          env['sudo_prompt'] = 'sending sudo password...'
         app_name = args.get('app','webiken-demo')
         now = datetime.now()
            year = now.year
        dt = now.strftime('%Y-%m-%d_%H:%M:%S')
        cmd = 'sudo rm -rf /opt/%(app_name)s' % dict(app_name=app_name)
        run(cmd)
        cmd = 'sudo mkdir -p /opt/%(app_name)s/%(year)s/' % dict(
    app_name = app_name,
    year = year
    )
        run(cmd)
        cmd = '/opt/%(app_name)s/%(year)s' % dict(
        app_name = app_name,
        year = year
    )
        with cd(cmd):
    run('sudo git clone git@localhost:%(app_name)s.git %(now)s' % dict(
        app_name = app_name,
        now = dt
    ))
        run('sudo ln -s /opt/%(app_name)s/%(year)s/%(now)s /opt/%(app_name)s/current' % dict(
    app_name = app_name,
    year = year,
    now = dt
    ))

A: Don't write your own code to request a password; try using Fabric's sudo command instead.

A: I think your problem probably cause by the newlines,try this:
f = open("../pass.txt", 'r')
password=str(f.read()).strip()
f.close()

print password
env.user = 'user'
env.password = password


text:
Q: How to encrypt json data in to JWE Token with jose I want to encrypt my JSON object into a JWE token. I am using the JOSE NuGet SDK with C# language. I am using A256KW JweAlgorithm for secret key and A256GCM for JweEncryption. Could anyone please help me find out what I am doing wrong?
string key = "Some Key";

// Create Security key  using private key above:
// not that latest version of JWT using Microsoft namespace instead of System

var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

//Some PayLoad that contain information about the  customer
var payload = new JwtPayload
                   {
                     { "page ", "2 "},
                     { "sc", "http://dummy.com/"},
                   };

var payload1 = Newtonsoft.Json.JsonConvert.SerializeObject(anyPayJson);

string token_1 = JWE.Encrypt(payload1, new[] { new JweRecipient(JweAlgorithm.A256KW, key, null) }, JweEncryption.A256GCM);

I am new in JOSE JWT and have no idea how to use JWE algo to the wrap secret key. I am getting error while processing it:

AesKeyWrap management algorithm expects key to be byte[] array.


text:
Q: Django autocomplete in Eclipse I want to use the autocomplete of PyDev with Django in Eclipse. I've followed these two threads
Autocompletion in Django + pydev
PyDev and Django: Autocomplete not detecting Django?
so I went to
Windows -> Preferences -> PyDev -> Interpreters -> Python Interpreter
selected the libraries tab and added path\to\Django\Django-1.6.1\django
and then right-clicked on Project's name then Preferences -> PyDev - PYTHONPATH
clicked on the external libraries and added the project folder and
C:\Python27\Lib\site-packages
finally I went to
Window->Preferences->PyDev->Editor->Code Completion
and checked that the autocomplete was on and it was so. But still don't have the auto-complete on. But it doesn't even autocomplete the variables that I have defined in the same class. Could anyone help me on this?

A: I fixed this myself. The problem wasn't related to PYTHONPATH or anything like that I had said above. The problem was with Aptana! I also noticed that Aptana that is now available for Windows x86 was 3.4.2 rather than 3.5 that was installed before. I think they had noticed that there are bugs in 3.5 and are now providing the 3.4.2 version.
To fix this simply reinstall Aptana.
Note: if you are getting "Port not bound (found port -1). Is there an enabled firewall?" after you enter some text and try [Ctrl + Space] you likely have the same problem.
Hope that helps for you.


text:
Q: Matplotlib - How to plot lines of minimum and maximum gradient through error bars? My code:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

def bestfit(x, m, c):
    return m * x + c

x = [2.8672E-02, 2.2199E-02, 1.8180E-02, 1.5410E-02, 1.3325E-02]
y = [8.64622E-03, 7.07473E-03, 6.13109E-03, 5.46607E-03, 4.90341E-03]
xerror =[8.2209E-07, 4.9280E-07, 3.3052E-07, 2.3748E-07, 1.7756E-07]
yerror = [1.62083E-04, 1.45726E-04, 1.38127E-04, 1.26587E-04, 1.22042E-04]

mod = Model(bestfit)
params = mod.make_params(m = 0.2421, c = 0.0017)
result = mod.fit(y, params, x = x)
print(result.fit_report())
print(1 - result.residual.var() / np.var(y))

matplotlib.rcParams['font.serif'] = "Times New Roman"
matplotlib.rcParams['font.family'] = "serif"
plt.plot(x, y, 'bo', markersize = 1.5)
plt.plot(x, result.best_fit, color = 'red', linewidth = 0.5)
plt.xlabel(r'Inverse Mass $g^{-1}$')
plt.ylabel('Damping Coefficient $s^{-1}$')

plt.errorbar(x, y, xerror, yerror)
plt.show()

I'm hoping to create lines of minimum and maximum gradient, along with their equations like so:

I was able to do it in Excel, but that required manual input of the 4 extreme data points.
How do I do this automatically?

A: It's not clear to me what the curves the other program is showing.  It sort of looks like it may be just drawing a line through the points
  (x[0], y[0]-yerror[0]), (x[-1], y[-1]+yerror[-1])
  (x[0], y[0]+yerror[0]), (x[-1], y[-1]-yerror[-1])

That should be easy for you to plot with matplotlib.  But that doesn't seem particularly meaningful to me.
On the other hand, if you want to include in your plot some measure of the uncertainty in the result of the fit, then there are a couple of options. First, you could evaluate the model using values for the parameters that are taken from the best_fit values and the uncertainties in those values.  For example, you might do (once you have result):
pars = result.params

curve1 = bestfit(x, pars['m'].value+pars['m'].stderr, pars['c'].value)
curve2 = bestfit(x, pars['m'].value-pars['m'].stderr, pars['c'].value)
curve3 = bestfit(x, pars['m'].value, pars['c'].value+pars['c'].stderr)
curve4 = bestfit(x, pars['m'].value, pars['c'].value-pars['c'].stderr)
curve5 = bestfit(x, pars['m'].value+pars['m'].stderr, pars['c'].value+pars['c'].stderr)
curve6 = bestfit(x, pars['m'].value+pars['m'].stderr, pars['c'].value-pars['c'].stderr)
curve7 = bestfit(x, pars['m'].value-pars['m'].stderr, pars['c'].value+pars['c'].stderr)
curve8 = bestfit(x, pars['m'].value-pars['m'].stderr, pars['c'].value-pars['c'].stderr)

and then plot some of those.
A simpler and possibly more informative plot to make would be to use the eval_uncertainties method of the ModelResult.  See
https://lmfit.github.io/lmfit-py/model.html#calculating-uncertainties-in-the-model-function  A simple use would be:
dely = result.eval_uncertainty()
plt.fill_between(x, result.best_fit-dely, result.best_fit+dely, color="#ABABAB")

Also, since you have uncertainties in y, you can use these in the fit itself.   To do this with lmfit.Model, you would pass in 1.0/yerror as a weight to the fit method:
result = mod.fit(y, params, x=x, weights=1.0/np.array(yerror))

(note: the data and uncertainties should really be numpy arrays, not lists).  I think for your data (where the uncertainties are similar in size) it will not make much of a difference to the best fit values and uncertainties, but it will make a difference in the reported statistics such as chi-square.
Finally, for a simple linear model (that is, a model that is linear in the parameters, like this one is), you don't really need to use an iterative approach like lmfit.Model but could use linear regression methods.


text:
Q: How does one make Windows XP auto-reconnect network drives upon reboot? I have a few network drive mappings that I want to be available to various programs upon reboot. However, they remain disconnected until I visit them manually.
If a program, such as OneNote which reads notes shared on a network drive, tries to connect, it does not see the share and does not cause auto-reconnect.
I am looking for a fully automated solution, preferably just a setting to make Windows natively reconnect on machine boot.
For example, right now drive Y and Z are disconnected and X is connected because I accessed it manually:

Edit: I have to change my question slightly but with quite a significant impact on the answers. The drives are indeed NOT available at logon. They only become reachable after I open an ssh tunnel.
Therefore, the main question is - how do you make applications force the drive alive when they try to access it?
I guess another approach would be to automatically run a script when the tunnel gets established. It's probably my best bet if the above is not possible.

A: Well, first of all, while mapping the drive you could tick the checkbox saying XP should reconnect the drives. It's not perfect. The other option is to write a script and place it in user's Startup folder:
net use * /d /y
net use <DriveLetter> <Path> (i.e. G: \\server\folder)
<repeat as many times as needed...>

A: Read this thread: https://web.archive.org/web/1/http://techrepublic%2ecom%2ecom/5208-11184-0.html?forumID=47&threadID=178558&messageID=1818197. The guy basically says to change this:
Try [HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters]

"KeepAliveTime"=dword:00300000
"KeepAliveInterval"=dword:00001000

We used to have a similar issue at my last place and this seemed to help.
Hope this helps.

A: Are they accessible if you try to open them? AKA, is this the age old issue of a mapped drive appearing to be disconnected, but when trying to open it, you find that it actually is connected?
But to answer the question as i read it:
To map a drive from a command prompt, and have it remain after a reboot, is to make it persistent.
NET USE <driveletter:> \\computername\share -p

Or, right click on My Computer, click map network drive, choose the location, and make sure "Reconnect at logon"

A: We encountered issues with this where we had a 2003 file share mounted in a Unix filesystem.  The "disconnect" would happen, and jobs that used it would potentially end up having to be run twice - the first time to wake up the share, the second time to actually do the job for real.
This wasn't satisfactory as - of course - sometimes the first run worked, so in the end one of our developers ended up writing a job to regularly poll the share and keep it warm.  Note that in this case changing keepalive times on the server wasn't an option as the share was mounted in the filesystem, and jobs could potentially have gaps of up to a week or so between them.
Why they didn't just connect at the start of each job and disconnect when done, or wake up the share via another method before running the actual job, I can't say.
Anyway, I'm not certain of the implementation details, but I expect that a scheduled task that just retrieves a directory listing would have the same end result for a Windows client if you were going to go down that route.  It's one way of doing it, but I'm sure there are better.
The moral of the story anyway is that Unix/Windows interoperability sure ain't as seamless as some folks would have you believe.  But that's digressing from the question.


text:
Q: google sheets: extract all decimals from a single row and find the average I have a google sheet( link: https://docs.google.com/spreadsheets/d/1eilz0uOhAnXkc7dpvSktcXv1-S7BWRGw3MZj9kOZGoI/edit?usp=sharing) I need help with. I want to be able to put the average of the scores for topic 1 (eventually I will add more topics but am keeping it simple for the question) in B3. I need to be able to only take the decimal values of scores and count how many instances to get the average. I am new to google sheets. Any hints would be appreciated, thanks.
I have tried to use the average function but it seems to work for columns and doesn't account for only calculating based on integers.

A: Use average(filter()), like this:
=iferror( average( filter(C2:K2, C$1:K$1 = "scores") ) )


text:
Q: Is it safe to fire and forget Task.add_async() on AppEngine? The issue isn't documented
I did some basic testing before converting all Task insertions to utilize add_async, all tasks that I inserted with add_async(), but didn't wait or get_result ended up executing and I assumed it was safe
However while investigating an issue, I found an instance where the task is added async, but it didn't execute, which led me to believe that it's unsafe to fire and forget about the async task rpcs, and they should be manually wait'ed, is this the case?


text:
Q: SQL Server: From 2008 To 2014 :-The data types datetime and time are incompatible in the add operator. Any other solution? I am migrating from SQL Server 2008 To 2014 and I get an error

The data types datetime and time are incompatible in the add operator.

I figured out the solution convert time to DateTime, but I have changes in many stored procedures and views.
Is there any other solution for above problem?

A: There is no other solution than re-factoring your code if you wish to upgrade to SQL2014. The example below demonstrates that setting the compatibility level to 2008 does not resolve this error. You  will have to modify all your stored procedures and views.
ALTER DATABASE database_name SET COMPATIBILITY_LEVEL = 100
GO
--DOESNOT WORK IN 2012
DECLARE @ESTRecords TABLE
    (
     ESTime TIME(7) NOT NULL ,
     ESTDate DATE NOT NULL ,
     ESTDateTime AS ( CONVERT(DATETIME, ESTDate, ( 108 )) + ESTime )
       PERSISTED
    )

INSERT  INTO @ESTRecords
       ( ESTime, ESTDate )
VALUES  ( '12:00 PM', '12/31/2012' )

SELECT  *
FROM       @ESTRecords


text:
Q: Clearing Wicket "Cache"/"Context" - Reloading Spring Context in Wicket I have a wicket web application which mounts a page, allowing users to choose what "mode" the application should start in, i.e. mock for development purposes and production for testing/QA/prod environments. Obviously this is only a feature that will be used for development purposes. Anyways, the mounted page simply presents the users with 2 choices in the form of a radio button. The back-end code reloads the Spring Application Context completely, allowing us to choose a different set of beans as per our needs. For example, when choosing the mock spring profile, we lack a lot of security and cache beans.
This seems to work fine, however the problem seems to be that, while Spring reloads without any issues, Wicket does not. It caches the old beans somehow so that the following happens. First, consider this piece of testcode:
public class MyPage extends Page {
  @Inject
  MyBean myBean;

public MyPage() {
  super("id");
  myBean.getData();
}

The two available sets of Springbeans both declare MyBean: mock returns static data when getData is called whereas production forwards the call to a WebService endpoint, does some filtering etc.
What happens is as follows: if the application starts and you choose mock profile from the radio-button-page, the mock data is read. However, going back to the radio-button-page and choosing the production profile shows us the problem:
WebApplication.get().getApplicationContext().getBean("myBean"); //returns the production instance
//Debugging the myBean instance in myPage shows it to be the mock instance

So, despite Spring refreshing fine, deleting old beans and creating a new set, Wicket uses the old bean version. How do we work around this? The two options we`ve considered are as follows:

*

*Refresh "everything in wicket". Unsure about how we'd go about this as I don't understand its magic all that well. In principle, what we'd want to do is WebApplication.get().refreshApplicationContext() or Session.clean() or something like that but nothing we've tried so far seems to work.

*Restarting the entire WebApplication, for example using an environment propery as a work-around. The problem with this approach is restarting the application programmatically without knowing what server we`re running on, i.e. we want it to work locally where we run Jetty and in development environments where the application runs on JBoss.
Any and all ideas are very welcome :)


text:
Q: Javascript - How to compare the element value inside event listener to the the array element? Once again, I need your input on the problem that I am having now.
I am creating a MCQ trivia where I encounter a logic problem.
Although for this example, I purposely set the answer are B, C or D, the result div will always show the result is correct – although I only set an event listener on button A but no answer.
Based on my code below, am I comparing the element value with the array answer value the right way?

var exam=[{
  "question": "Q1?",
  "option": ["A","B","C","D"],
  "answer": "B"
},{
  "question": "Q2?",
  "option": ["A","B","C","D"],
  "answer": "C"
},{
  "question": "Q3?",
  "option": ["A","B","C","D"],
  "answer": "D"
},{
  "question": "Q4?",
  "option": ["A","B","C","D"],
  "answer": "B"
},{
  "question": "Q5?",
  "option": ["A","B","C","D"],
  "answer": "C"
}]

//dom selector
var container = document.getElementById('container');
var questionEl = document.getElementById('question');
//for the answer display
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
//for the input button click
var opta = document.getElementById('opta');
var optb = document.getElementById('optb');
var optc = document.getElementById('optc');
var optd = document.getElementById('optd');
//
var button = document.querySelectorAll('button');
var nextButton = document.getElementById('help1Button');
var resultCont = document.getElementById('result');
//display question and answer
function displayQues() {
  //select one question randomly from the quiz array
  var i = Math.floor(Math.random() * exam.length);
  questionEl.textContent=exam[i].question;
  opt1.textContent = exam[i].option[0];
  opt2.textContent = exam[i].option[1];
  opt3.textContent = exam[i].option[2];
  opt4.textContent = exam[i].option[3];
};
//load this when page load
displayQues();
opta.addEventListener("click", function() {
  if (opt1.value === exam.answer) {
    displayQues();
    resultCont.textContent = "Correct!";
  } else {
    resultCont.textContent = "Incorrect!";
  }
});

 Alan Koh Exam Question

    <button id="opta"> A:   </button>
    <button id="optb"> B:   </button>
    <button id="optc"> C:   </button>
    <button id="optd"> D:   </button>

A: The problem with your current code is opt1.value === exam.answer. Both these properties are undefined. opt1.value because it's not set (I believe you want opt1.textContent) and exam.answer because exam is an array. You get Correct! always since undefined === undefined is true
Your issue can be solved by returning the current displayed question and using it for comparison.

var exam = [{
  "question": "Q1?",
  "option": ["A", "B", "C", "D"],
  "answer": "B"
}, {
  "question": "Q2?",
  "option": ["A", "B", "C", "D"],
  "answer": "C"
}, {
  "question": "Q3?",
  "option": ["A", "B", "C", "D"],
  "answer": "D"
}, {
  "question": "Q4?",
  "option": ["A", "B", "C", "D"],
  "answer": "B"
}, {
  "question": "Q5?",
  "option": ["A", "B", "C", "D"],
  "answer": "C"
}]
//

//dom selector
var container = document.getElementById('container');
var questionEl = document.getElementById('question');
//for the answer display
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
//for the input button click
var opta = document.getElementById('opta');
var optb = document.getElementById('optb');
var optc = document.getElementById('optc');
var optd = document.getElementById('optd');
//
var button = document.querySelectorAll('button');
//

var nextButton = document.getElementById('help1Button');
var resultCont = document.getElementById('result');

//display question and answer
function displayQues() {

  //select one question randomly from the quiz array
  var i = Math.floor(Math.random() * exam.length);

  questionEl.textContent = exam[i].question;
  opt1.textContent = exam[i].option[0];
  opt2.textContent = exam[i].option[1];
  opt3.textContent = exam[i].option[2];
  opt4.textContent = exam[i].option[3];
  return exam[i]; // Return the chosen exam variable
};

//load this when page load
var currentExam = displayQues(); // Store the chosen exam

opta.addEventListener("click", function() {
  if (opt1.textContent === currentExam.answer) {
    currentExam = displayQues(); // Store the new question
    resultCont.textContent = "Correct!";
  } else {
    resultCont.textContent = "Incorrect!";
  }

});

 Alan Koh Exam Question

  <button id="opta"> A:   </button>
  <button id="optb"> B:   </button>
  <button id="optc"> C:   </button>
  <button id="optd"> D:   </button>

A: Here is the jsfiddle link with the corrected code.
You have to loop through exam and compare the correct question and answer.


text:
Q: jQuery duplicate only works on one click I have found this code on the web and looking to retrofit it for my needs. In the original fiddle it used jQuery 1.7 but I am using 1.10 which they deprecated the live() feature I switch the values to on() but now it will only work one time (I can duplicate a lot but I can not remove or duplicate after) I included the fiddle. Another thing I have tried doing with the old code but could not get it to work was removing the need to click the duplicate button and instead have it inside of a for loop that gets it duplicate value from a variable. I was not getting errors which makes it hard to troubleshoot.
var regex = /^(.*)(\d)+$/i;
var cloneIndex = $(".clonedInput").length;
var locations = 3;
    for(var i = 0; i < locations; i++){
        $(this).parents(".clonedInput").clone()
            .appendTo("body")
            .attr("id", "clonedInput" +  cloneIndex)
            .find("*").each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex);
                }
        });
        cloneIndex++;
    };

A: After creating a cloned element, you've introduced a new DOM element into the document, thus you'd have to make your .click() hander to listen to the $(document) or $('body') to delegate to it. Thus if you rewrote your .click() handlers like below:
$("button.clone").on("click", function(){
    //.clone() etc
});

to:
$(document).on("click", "button.clone", function(){
    //.clone() etc
});

Demo Fiddle: http://jsfiddle.net/XcbsP/
In the second example, I swapped the HTML ID's in favour of numbered Indexes jQuery's .attr()/.data() to help keep track of the index. So in the future if you need to re-select an element, you can:
   $(".clonedInput[data-index='2']");

Also when creating many new clones your clicked object, pre-increment the counter as you create it:
/**
 *  Where $(this).val() is the <option value="2">
**/
for( var x = 0; x < $(this).val(); x++ )
    $('body').append( $(this).parents('.clonedInput')
                             .clone( true )
                             .attr('data-index', ++cloneIndex ));

Which makes a cleaner HTML and less dependency on id=""s, especially as you're using many of something, which .classes are intended for.
Demo Fiddle: http://jsfiddle.net/n6a7e/


text:
Q: Grok filtering in logstash for multiple defined patterns I am trying to filter my logs matching few patterns I have. e.g:
E/vincinity/dholland_view_sql_global/IN/Cluster_Node/SSL-CACHE/Dsal1
F/vincinity/dholland_view_sql_local/IN/Cluster_Node3/SSL-CACHE/Dsal4

R/vincinity/dholland_view_sql_bran/IN/Cluster_Node/Sample/vr1.log
Now I want to grep these 3 paths from a bunch of logs: basically the pattern that I want to extract is logs containing "vincinity" "sql" and "IN" so with regex it would be simply *vincinity*sql*IN*
I tried this grok filter:
grok {

    match => { "Vinc" => "%{URIPATHPARAM:*vincinity*sql*IN*}" }

  }

Then I get _grokparsefailure in kibana - I'm brand new to grok, so perhaps I'm not approaching this correctly.

A: From the grok filter documentation

The syntax for a grok pattern is %{SYNTAX:SEMANTIC}

The way the grok filter should work is
grok {
  match => {
    "message" => "%{PATTERN:named_capture}"
  }
}

Where message is the field that you want to parse, this is the default field that most inputs place your unparsed loglines in.
The URIPATHPARAM pattern is one predefined in logstash through a regex language called Onigurama. It may match your whole log message, but it will not capture certain chunks of it for you.
For help constructing a grok pattern, check out the docs, they link to a couple useful pattern construction tools.

A: The correct format for using a custom pattern in your grok block is:
(?<field_name>the pattern here)

or you can define your own custom pattern (using regular expression) in seperate file (my-pattern.txt) like this :
MYPATH_MUST_BE_UPPERCASE Regex_Pattern

save it in ./patterns directory and then use it this way:
grok {
     patterns_dir => "./patterns"
     match => ["message" , "%{MYPATH_MUST_BE_UPPERCAS:path}"]
}

in your case :
(?<vincinity>(?>/\s*.*?vincinity.*?\s*)+)
(?<sql>(?>/\s*.*?sql.*?/\s*)+)
(?<in>(?>\s*.*?(IN).*?\s*)+)


text:
Q: Android reload ListView data from SQLite I had a ListView that loads data from the SQLite database and onClickListener for each list that opens up to a new activity. My problem now is that when I press "Back" to go back to the previous activity with the ListView, it doesn't show.
How do I reload the list from database again? How do I go about it?
Does it have anything to do with notifyDataSetChanged()?
Please help.
Thank you.
EDITED:
Below are my codes to load the ListView under onCreate():
        ListView listContent = (ListView) findViewById(R.id.contentlist);
        mySQLiteAdapter = new SQLiteAdapter(this);
        mySQLiteAdapter.openToRead();

        Cursor cursor = mySQLiteAdapter.queueAll();
        startManagingCursor(cursor);

        String[] from = new String[] { SQLiteAdapter.KEY_CONTENT };
        int[] to = new int[] { R.id.text };

        SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor, from, to);

        listContent.setAdapter(cursorAdapter);

        mySQLiteAdapter.close();

        //Onclick ListView setlistener
        listContent.setTextFilterEnabled(true);
        listContent.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
                listTopic = ((TextView) view).getText().toString();

                summaryIntent.putExtra("SummTopic", listTopic);
                startActivity(summaryIntent);
            }
        });

So what to add in the Resume()?

A: You can put your code to fetch data from database and adding it to ListView inside onResume(). So when you jump back to your previous Activity its onResume() will be called and your ListView will be loaded with the data from database.


text:
Q: Animation speed depends on FPS Im making a simple game and im wanting to link the animation/movement of characters to the time between frames so that in one second the character moves the same distance no matter what the FPS. this is the code I have to try to do this.
public void getVels()
{
    if (isAirbourne && accely < terminalVel)
    {
        accely += gravity;
    }

    vely = accely;
    vely = vely * getFrameTime();

    System.out.println(getFrameRate() + "  " + getFrameTime() + "  " + vely);
}

.
public static long getTime()
{
    return Sys.getTime() * 1000 / Sys.getTimerResolution();
}

public static float getTimeSinceLast()
{
    if (first)
    {
        currentFrame = getTime();
        first = false;
        timeSinceLast = 1;
    }

    else
    {
        lastFrame = currentFrame;
        currentFrame = getTime();
        timeSinceLast = currentFrame - lastFrame;
    }

    return timeSinceLast;
}

public static float getFrameTime()
{
    return timeSinceLast * multiplier;
}

public static void updateClock()
{
    getTimeSinceLast();
}

however the game still runs 10x as fast at 100FPS compared to 10FPS even though it shouldn't. Any help/tips?
at 1000 fps getframetime would be 0.01,
if accely = 1 then vely * getframetime would be 0.01.
at 100fps getframetime is 0.1, so with accely at 1, vely * getframetime should be 0.1
which is 10x larger than 0.01 at a 10x smaller fps so the distance it travels per second should be the same right?
SOLUTION:
if (isAirbourne && accely < terminalVel)
{
    accely += gravity * getFrameTime;
}

instead of
if (isAirbourne && accely < terminalVel)
{
    accely += gravity;
}

acceleration from gravity was not adjusted.