text:
Q: How to make a bot kick someone if i say a certain keyword So if I say for example 'abracadraba' I want the bot to kick a certain member.
I know the player I want to kick for example 'example#1234'
The bot has all permisions necessary.
This is the code by now:
import discord
import time
from discord.ext import commands

client = discord.Client()

@client.event
async def on_ready():
    print("Botu e gata")

@client.event
async def on_message(message):
    if message.content.startswith("ba"):
        await member.kick(userName = "FluXon#5183",reason=None)

    if "matei" in message.content:
        await message.channel.send("Suge carasu")
    if "Matei" in message.content:
        await message.channel.send("El e ceo nostru")
        time.sleep(2)
        await message.channel.send("Unul dintre cei mai respectati cetateni ai acestui server")
        time.sleep(2)
        await message.channel.send("El se ocupa de chestii ca voi sa nu trebuiasca sa va ocupati")
        time.sleep(2)
        await message.channel.send("Asa ca respecta           ti-l")
        time.sleep(2)
        await message.channel.send("MATEI CEO")
        await message.channel.send("MATEI CEO")
        await message.channel.send("MATEI CEO")

client.run(token)

A: Below is some code which will achieve what you want, make sure to replace 123456789 with the ID of the user you want to be kicked. You can find a users id by following this tutorial.
@client.event
async def on_message(message):
    if "abracadraba" in message.content:
        member = await message.guild.fetch_member(123456789)
        await member.kick()

Note:
Anyone could kick this member by saying the word, not just you. If you want to limit it to only yourself, you can check the message.author is equal to you. This function will also raise a discord.Forbidden if the bot doesn't have the permission to kick someone.
Relevant Documentation:

*

*discord.Guild.fetch_member

*discord.Member.kick


text:
Q: How can i detect that the activity has been started I am working on a Java Testing Controller Application that runs on a PC.
It does:
Install app on the android phone:

adb install xxx.apk

Start the activity:

adb shell am start -n com.package.name/com.package.name.ActivityName

When activity has been started, send a broadcast:

send a broadcast to start the test function on the activity

Our app needs about a half minute to start, so, how can I detect if the app is ready?
I was thinking reading the logcat, but we have to test several devices at the same time.
Any ideas on how to do it?

A: Android Debug Bridge (adb.exe) supports -s to issue/filter commands by device, e.g.
adb -s emulator-5554 logcat -c
will clear logcat for the device called emulator-5554.
Use:
adb devices
to list all devices running.
Maybe use "adb pull" and "adb push" to read/write a file. E.g. install app starts and writes some text to a file called flag.txt on the sd scard:
adb -s emulator-5554 pull /sdcard/flag.txt flag.txt
PC clears text and clears file for next run:
adb -s emulator-5554 push flag.txt /sdcard/flag.txt
Other ways may be possible, see adb docs: https://developer.android.com/studio/command-line/adb

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i remove the posts category class names from body_class I have 2 categories, just to make an easy example, Cars and Bikes.
I have a post that fits both of the category.
If i visit the Cars category, the body_class looks like this:
"archive category category-cars category-1 category-cars category-bikes"
The problem is that somehow the post category is visible in the body_class after the category-1 classname. How can i avoid this? I need to use different colors for different categories, but right now the category-bikes class overwrites the category-cars class.

A: This could be solved via CSS as well.  Just set up declarations for the special cases where there is overlap between categories:
.category-cars { background-color: #f00; }
.category-bikes,
.category-cars.category-bikes { background-color: #0f0; }

This will give any posts that are in both bikes and cars the same background color as those used in the bikes category.


text:
Q: how to solve "the type parameter ListNode is hiding the type ListNode"? I have got some problems of java type parameter. Here is the code. I have a class ListNode, and a class MyComparator implementing Comparator interface.
class ListNode {
    int val;
    ListNode next;
}

class MyComparator<ListNode> implements Comparator<ListNode> {
    @Override
    public int compare(ListNode n1, ListNode n2) {
        if (n1.val < n2.val)
            return -1;
        else if(n1.val == n2.val)
            return 0;
        else
            return 1;
    }
}

However the compiler reports that "the type parameter ListNode is hiding the type ListNode" at the declaration line of MyComparator, and it leads to "val can not be resolved" error in the overriding implementation of compare().
I am quite confused about the type parameter here, could anyone give me some tips please?

A: Use
class MyComparator implements Comparator<ListNode> {

instead of
class MyComparator<ListNode> implements Comparator<ListNode> {


text:
Q: Information: Unable to bind to http://localhost:80 on the IPv4 loopback interface: 'Permission denied'. in MAC We are getting below  error message in MAC while adding Kestrel in app settings.json in .net 6 Rest api.
"Kestrel": {
        "Endpoints": {
            "Http": {
                "Url": "http://localhost:80"
            },
            "Https": {
                "Url": "http://localhost:443"
            }
        }
    }

Error Message:
Microsoft.AspNetCore.Server.Kestrel: Warning: Overriding address(es) 'http://localhost:80'. Binding to endpoints defined via IConfiguration and/or UseKestrel() instead.
      Unable to bind to http://localhost:80 on the IPv4 loopback interface: 'Permission denied'.
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Server.Kestrel[0]
Microsoft.AspNetCore.Server.Kestrel: Information: Unable to bind to http://localhost:80 on the IPv4 loopback interface: 'Permission denied'.
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to bind to http://localhost:80 on the IPv6 loopback interface: 'Permission denied'.
Microsoft.AspNetCore.Server.Kestrel: Information: Unable to bind to http://localhost:80 on the IPv6 loopback interface: 'Permission denied'.


text:
Q: How to prove Vector Angles?
Any vector $\mathbf{v}$ is a unit vector if $\|\mathbf{v}\| = 1$.
Let $\mathbf{x}$, $\mathbf{y}$, and $\mathbf{z}$ be unit vectors, such
  that $\mathbf{x} + \mathbf{y} + \mathbf{z} = \mathbf{0}$. Show that
  the angle between any two of these vectors is $120^\circ$.

I know how to prove this using geometry, but the problem instructs me not to. How should I start to/prove this?
Thanks in advance!

A: Consider the dot product between $\vec x$ and $\vec y$. Then $\vec x\cdot \vec y=\cos (\alpha)$, where $\alpha$ is the angle between the vectors $\vec x$ and $\vec y$. But $\vec y=-(\vec x+\vec z)$ and so $\vec x\cdot (-\vec x-\vec z)=\cos(\alpha).$ This implies that $$-|x|^2-\vec x\cdot \vec z=\cos(\alpha)$$
$$\Rightarrow -1-\cos (\beta)=\cos (\alpha)$$
$$\Rightarrow \cos(\alpha)+\cos(\beta)=-1$$
Use a similar argument by considering $\vec y \cdot \vec z$ and $\vec z\cdot \vec x$ and you will get $$\cos(\beta)+\cos(\gamma)=-1$$
And $$\cos(\gamma)+\cos(\alpha)=-1$$
Add all these three equations to get $2(\cos(\alpha)+\cos(\beta)+\cos(\gamma))=-3$ or $$\cos(\alpha)+\cos(\beta)+\cos(\gamma)=\frac{-3}{2}.$$
Now we know that $$\frac{-3}{2}\leq \cos(\alpha)+\cos(\beta)+\cos(\gamma)\leq 3$$ so clearly $\alpha, \beta \text{ and }\gamma$ are at their minimum values, which is $$\alpha= \beta= \gamma=\frac{2\pi}{3}.$$ For a rigorous justification of this claimm, check out this link.

A: We have that $$(\mathbf{x} + \mathbf {y} + \mathbf {z})^2 =0$$ $$\Rightarrow \mathbf {x}^2 + \mathbf {y}^2 + \mathbf {z}^2 +2 (\mathbf {x}\cdot \mathbf {y} + \mathbf {y}\cdot \mathbf {z} + \mathbf {z}\cdot \mathbf {x}) =0$$ $$\Rightarrow (\mathbf {x}\cdot \mathbf {y} + \mathbf {y}\cdot \mathbf {z} + \mathbf {z}\cdot \mathbf {x}) = -\frac {3}{2} $$ $$(|\mathbf {x}||\mathbf {y}|\cos \theta_{xy} + |\mathbf {y}||\mathbf {z}|\cos \theta_{yz} + |\mathbf {z}||\mathbf {x}|\cos \theta_{zx}) = -\frac {3}{2} $$ $$=\cos \theta_{xy} + \cos \theta_{yz} + \cos \theta_{zx} = -\frac {3}{2}$$
Can you conclude using this? Hope it helps.


text:
Q: Put Link into json using hook (React) i have a question, i want to add this command line:
Cell: ({ row }) => {row.original.lastName}

into 'lastName',using hook in reactjs, for example:
Before:
const [columns, setColumns] = useState(
[
  {
    id:'firstName',
    Header: 'First Name',
    accessor: 'firstName',
  },

  {
    Header: 'Last Name',
    accessor: 'lastName',
   },
]
);

setColumns(???)

Result:
[
   {
     id:'firstName',
     Header: 'First Name',
     accessor: 'firstName',
   },

   {
     Header: 'Last Name',
     accessor: 'lastName',
     Cell: ({ row }) => {row.original.lastName}
    },
 ]

Best regards
Giuseppe

A: Please find a small working solution as below. Please feel free to replace the button click with your side effect which can be an API call or any action side effect. Just for simplicity, I have used a button.
import React, { useState } from "react";
import ReactDOM from "react-dom";

const Row = ({ row }) => (
  {row.original.lastName}
);

function App() {
  const [columns, setColumns] = useState([
    {
      id: "firstName",
      Header: "First Name",
      accessor: "firstName"
    },

    {
      Header: "Last Name",
      accessor: "lastName"
    }
  ]);

  const createRowsForLastName = () => {
    const replaceColumnForLastName = columns.map(column => {
      if (column.accessor === "lastName") {
        return {
          ...column,
          Cell: <Row row={{ original: { lastName: "some name" } }} />
        };
      }

      return { ...column };
    });

    setColumns(replaceColumnForLastName);
  };

  console.log(columns);
  return (

      <button onClick={createRowsForLastName}>Create Row!</button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


text:
Q: In need of a link to open an iOS app if installed or else go to the iTunes store My app (iOS and Android) wants to post in behalf of the user to Facebook, but I don't find an api in FBWebDialog class (FB iOS SDK) to set the message to post. So my first question is: is there any api in FB iOS/Android SDK to edit the post message (feed dialog)?
With this failure I hope to do this by posting a FB message with a links. So here is what my title suggests. Is it possible to have a link (URL) which, when clicked by the user, leads to an iOS app if this app is installed or to iTunes store if the app is not installed? If this URL exists, will it work well on computers (PCs and macs) and other terminals?
I think if I set up a web server myself, I could use JavaScript to check whether the target app is installed on the client device, but I don't want to do so if there is already a way to do this.
Thanks in advance.

A: Seems you cannot change the FB post message, or check whether a specific app is installed on your device using native code.
Therefore, I just take use of the URL to the iTunes store (See How to link to apps on the app store). When clicking the link, the behaviour depends on the OS version (seemingly). Sometimes, you're led to your app (if installed) and sometimes to the app store.


text:
Q: Processes are running slow in Docker container on Ubuntu 18.04 Processes are taking time when running them in a Docker container on an Ubuntu 18 machine. But the same process with the same Docker version is running fine on an Ubuntu 16 machine.
I have a node application listening on some port. Accepting get requests on the path "/" and "/docker" which simply runs a command "whoami" in the host machine and in a Docker container respectively and returns the result. The same node application with the same Docker container is running on both the machines (Ubuntu 16 and Ubuntu 18).
Firstly, I tried sending 20 concurrent get requests with path "/" to both the machines. And both the machines executed the command in an average of
35-40ms.
Secondly, I tried sending 20 concurrent get requests with path "/docker" to both the machines. Here, the Ubuntu 16 machine took a maximum of 4.3 seconds and an average of 3 seconds. But the Ubuntu 18 machine takes a maximum of 10 seconds and an average of 9 seconds.
I tried the above test multiple times and concluded that when running the process inside Docker, the time taken to execute is almost double in the Ubuntu 18 machine compared to Ubuntu 16.
I checked the following:

*

*I tried monitoring through top and htop while hitting 20 requests. But everything seems the same there.

*Also tried monitoring using perf command. But unable to find any unusual difference there. But I am not very used to perf command and so unable to understand clearly.

*While these 20 requests were in processing. I run the same Docker command manually with strace. And found random results i.e. sometimes time taken in clock_gettime or futex (FUTEX_WAIT) or sometimes in +++ exited with 0 +++ message on Ubuntu 18, but it took less time on Ubuntu 16.
Below are the different configurations and code snippets I am using and running:

Machine1: Giving better performance.
node    v10.16.0
npm     6.9.0
docker  18.09.8
ubuntu  16.04.3 LTS, xenial

Machine2: Giving poor performance.
node    v10.16.0
npm     6.9.0
docker  18.09.8
ubuntu  18.04.2 LTS, bionic

Node application code snippet:
// for path "/docker"
var excuteInDocker = function() {
    var cmd = "docker";
    var args = ["exec", "ubuntu", "whoami"];
    return executeCmd(cmd, args);
}

// for path "/"
var execute = function(){
    var cmd = 'whoami';
    var args = [];
    return executeCmd(cmd, args);
}

Output of docker info which are common to both ubuntu 16 and 18:
Containers: 1
 Running: 1
 Paused: 0
 Stopped: 0
Images: 2
Server Version: 18.09.8
Storage Driver: overlay2
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 894b81a4b802e4eb2a91d1ce216b8817763c29fb
runc version: 425e105d5a03fabd737a126ad93d62a9eeede87f
init version: fec3683
Security Options:
 apparmor
 seccomp
  Profile: default
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 7.296GiB
Name: myhostname
ID: LLLO:OMTS:PNNM:T3MP:AD2F:UMDG:IIZK:OGBO:3ZLL:YDBX:ONAO:AY5G
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 27
 Goroutines: 42
 System Time: 2019-07-25T15:25:54.991694211+05:30
 EventsListeners: 0
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false
Product License: Community Engine

WARNING: No swap limit support

docker info specific to Ubuntu 16:
Kernel Version: 4.4.0-112-generic
Operating System: Ubuntu 16.04.3 LTS
Total Memory: 7.303GiB
ID: FOFI:RW7N:RZSP:HHKH:BKS3:LMWL:TC2J:W7V2:222Y:Q2AU:XMU3:KLU7

docker info specific to Ubuntu 18:
Kernel Version: 4.15.0-1040-aws
Operating System: Ubuntu 18.04.2 LTS
Total Memory: 7.296GiB
ID: LLLO:OMTS:PNNM:T3MP:AD2F:UMDG:IIZK:OGBO:3ZLL:YDBX:ONAO:AY5G

Ubuntu 16 machine Data:
1. Data of time taken in execution
2019-07-25 14:06:42.851 INFO  uid: 540ae880-aeb7-11e9-919d-dd32b3cf84d5 time: 475 result: {"success":true,"data":"root"}
2019-07-25 14:06:43.183 INFO  uid: 54145e60-aeb7-11e9-919d-dd32b3cf84d5 time: 745 result: {"success":true,"data":"root"}
2019-07-25 14:06:45.711 INFO  uid: 540c4810-aeb7-11e9-919d-dd32b3cf84d5 time: 3326 result: {"success":true,"data":"root"}
.
.
.
2019-07-25 14:06:46.835 INFO  uid: 541d5f10-aeb7-11e9-919d-dd32b3cf84d5 time: 4338 result: {"success":true,"data":"root"}

*Logs of command strace -t docker exec ubuntu whoami:

*Result of perf top --sort comm,dso:

Ubuntu 18 machine Data:
1. Data of time taken in execution:
2019-07-25 14:07:32.559 INFO  uid: 715a6af0-aeb7-11e9-a5a9-2fffd4e800d1 time: 1008 result: {"success":true,"data":"root"}
2019-07-25 14:07:32.941 INFO  uid: 7178c860-aeb7-11e9-a5a9-2fffd4e800d1 time: 1191 result: {"success":true,"data":"root"}
2019-07-25 14:07:40.363 INFO  uid: 71767e70-aeb7-11e9-a5a9-2fffd4e800d1 time: 8628 result: {"success":true,"data":"root"}
.
.
.
2019-07-25 14:07:41.970 INFO  uid: 718af0d0-aeb7-11e9-a5a9-2fffd4e800d1 time: 10101 result: {"success":true,"data":"root"}

*Logs of command strace -t docker exec ubuntu whoami:

*result of perf top --sort comm,dso:

So, I need help in debugging what is wrong with Docker on the Ubuntu 18 machine. Or if there is any limitation with Docker on Ubuntu 18 or maybe some machine or Docker configuration issue.

A: I did not encounter such a problem on my desktop, but mysql container was running very slowly in a way that I could not understand on my ubuntu laptop. This solution solved my problem.


text:
Q: SonarQube code smell does not work for a constructor, but does work for another constructor in an inner class in the same file I have a rule that methods should not have too many parameters (maximum 5), code smells code does not appears in a class for a constructor with more than 5 parameters.
But appears for methods that have more than 5 parameters in the same class, and for inner static class with more than 5 parameters.
What the problem?

A: I think you are talking about the rule java:S107.
You can edit the rule in SonarQube to have different thresholds for methods and for constructors:
Parameter for max number of method parameters:

max - (Default Value: 7)

Parameter for max number of constructor parameters:

constructorMax - (Default Value: 7)

So please check if you have different values set for the parameters of this rule.
As for why it is not checked for constructors of an inner class, maybe SonarQube uses the parameter max instead of constructorMax for a constructor of an inner class. But I could not find anything related to inner classes in the description of the rule.


text:
Q: Why does LaTeX mix up the order of my algorithms and other output?
Possible Duplicate:
How to avoid splitting tables between sections

I did something like this:
\documentclass{article}

\usepackage[T1]{fontenc}

\usepackage{algorithm}

\usepackage{algorithmic}

\usepackage{array}

\usepackage{eqparbox}

\usepackage[pdftex]{graphicx}

\pagestyle{headings}

\begin{document}
\begin{algorithm}

  \begin{algorithmic}

    algorithm goes here

  \end{algorithmic}

\end{algorithm}

\begin{algorithm}

  \begin{algorithmic}

    algorithm goes here

  \end{algorithmic}

\end{algorithm}

\section{test}

section contents.

\end{document}

When I render the PDF, the test section appears before the second algorithm, instead of after it.
Isn't LaTeX supposed to render them in the above order?

A: Algorithm is a floating environment. So, you need to put a [!h] next to it if you want it to appear exactly where you're putting it. Like so:
\begin{algorithm}[!h]


text:
Q: Breaking a row into multiple records with LOAD DATA INFILE I would like to load a csv file that has the following format:
ID | Names
1  | John, Jim
2  | Ralph
3  | Conrad, Alex, Sam

and the data in my SQL table should be like that:
ID | Name
1  | John
1  | Jim
2  | Ralph
3  | Conrad
3  | Alex
3  | Sam

1) Is there a way to do this directly using LOAD DATA INFILE?
2) If not I assume I will have to load the csv file to a temporary table and then populate the final table from it. Any performance tips on how to do this fast?
Thank you.

A: Suggestion 1
It can be achieved one way to do this is to create a CSV in the format you want. So you would need a loop to through each row. First separate the ID and then the Names. Then you insert that into a new CSV, and upload that csv to the database.
So your query should look something like this after:
string query;

query = `"LOAD DATA LOCAL INFILE INTO TABLE xxx FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (ID, Names)"`

Please note this wont work if your ID is a primary key because you can't have two same ID's as you have described in your OP.
Suggestion 2
You can try other method suggested by @sahrash shah.


text:
Q: How to remove filter components row from an extendedDataTable in richfaces I have an extendedDataTable with a column like this
<rich:column id="exampleId"
             filter="#{exampleFilterBean.exampleFilterMethod}"
             filterValue="#{exampleFilterBean.exampleFilterValue">
             <f:facet name="header" >
                  <h:outputText value="Header" />
             </f:facet>
             <h:outputText value="#{exampleFilterBean.example.exampleAttribute}" />

I don't want to display the control bar with the filter box because I'm using external filters and JavaScript API.

A: You can easily hide them by adding a css-command:
.rf-edt-flt-c { display:none; }

Also the input boxes will be removed when you remove the filter/filterattribute - attributes
A third way is to remove them via javascript using extended data tables onready-attribute
onready="$('.rf-edt-flt-c', this).each(
                function(n){
                    this.parentNode.removeChild(this);
                 });"

Hope it helps...


text:
Q: Android Studio - Error Module not specified i'm a newbie to Android/Java development and purchased a book Java Programming for Android Developers For Dummies, 2nd Edition.
This comes with a code samples section http://users.drew.edu/bburd/Java4Android/ (chapter 02_01) I understand the book is a few years old hence so the code samples will be. However, i'm having massive problems getting the code samples to run on Android Studio 4.1.2.
I can import the project and sync the Gradle files. When I do it appears with a green tick at the bottom. Oddly it says failed next to that with the following message.
Gradle sync failed: Unsupported method: SyncIssue.getMultiLineMessage().
            The version of Gradle you connect to does not support that method.
            To resolve the problem you can change/upgrade the target version of Gradle you connect to.
            Alternatively, you can ignore this exception and read other information from the model.
            Consult IDE log for more details (Help | Show Log) (1 s 443 ms)

My build.gradle file is as follows
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Also if I try and run the project I see this screen

I've read many posts with similar issues and worked through various fixes. None seemed to work so can anyone shed any light on what's happening please? I've also downloaded android studio on 3 different PC's incase its a bug of some sort.
Thank you

A: I should say the files in there are very outdated, and you will have very hard time, with every project. But if you still want to build the project here are a few things you can do.
look for the file gradle-wrapper.properties and update it with this
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip

Then move to project level build.gradle file (there are two one inside app directory and one on the root directory, use the root directory)
buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Then move to app level build.gradle and update it with this
apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    defaultConfig {
        applicationId "com.allyourcode.a02_01"
        minSdkVersion 15
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:2.0.4'
    testImplementation 'junit:junit:4.13.1'
}

And then sync the project and let Android studio do its magic.

A: As the stack traces say, you should upgrade your Gradle version. You are using an "old" book where the samples have been build with an old version of Android Studio that supports well that old version of Gradle. But 4.1 is a recent version and does not support well many old Gradle features.


text:
Q: How to use Doctrine2 from Symfony2 in an existing future-Symfony application? I don't find any solution through Symfony's docs and google. I find only stuff about starting an application from scratch.
I have a big own-framework application and i want slowly migrate to Symfony2. I have not the convenience to build a new application from scratch.
Until now i cloned the entire symfony folder into my own-framework application's root folder.
I was using Doctrine by directly implementing it, whitout touching Symfony, like following.
<?php
namespace QueryBuild\Helpers;

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

class Listing
{
protected $appConfig;
protected $doctrineEntityManager;

public function __construct(\cConfig $app_config)
{
    $this->setAppConfig($app_config);
    $this->setDoctrineEntityManager();
}

public function setAppConfig($app_config)
{
    $this->appConfig = $app_config;
}

public function setDoctrineEntityManager()
{
    $paths = array(
        $this->getAppConfig()->BasePath() . "/symfony/src/El/Entity/"
    );
    $isDevMode = true;

    // the connection configuration
    $dbParams = array(
        'driver' => 'sqlsrv', // pdo_sqlsrv for mssql
        'host' => $this->getAppConfig()->db->Host,
        'user' => $this->getAppConfig()->db->User,
        'password' => $this->getAppConfig()->db->Password,
        'dbname' => $this->getAppConfig()->db->Database
    );

    // 5th param on false, to NOT use the simple annotation reader. Otherwise annotations are going to be readed wrong. Can be due to server configurations.
    $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, null, null, false);
    $doctrineEntityManager = EntityManager::create($dbParams, $config);

    $this->doctrineEntityManager = $doctrineEntityManager;
}

public function getAppConfig()
{
    return $this->appConfig;
}

public function getDoctrineEntityManager()
{
    return $this->doctrineEntityManager;
}

}

Dont be confused on my namespace, my actual task is to create a query building feature.
Now i don't want anymore to connect to the db by passing the login datas into setDoctrineEntityManager().
I already wrote those informations in /symfony/app/config/parameters.yml .
Now my idea was to instanciate symfony to be able to read the configuration, and howewer from symfony to instanciate doctrine.
How can i accomplish this?
Many thanks in advice.

A: Finally my solution was the contrary as i thinked before. Symfony2 is now the wrapping base application, and the legacy application is (at the moment) encapsulated as a LegacyBundle. Now i can pass e.g. the Entity-Manager or even the Controller-Container to the legacy application.


text:
Q: Elasticsearch NEST API, Searching Multiple Indices If one is seraching several indexes at the same time, is there any way to say that if searching index A, then add this filter and if searching index B then add a different filter.
For example:
var filters = new List<Func<QueryContainerDescriptor<PropertySearchResult>, QueryContainer>>();
filters.Add(fq => fq.Term(t => t.Field(f => f.PromoterId).Value(user.Id)));
filters.Add(fq => fq.Term(t => t.Field(f => f.SubscriptionId).Value(subscriptionId)));
string indicies = String.Join(",", Utils.SupportedCountries.Select(c => c.Key.ToLower()).ToArray());
var result = await ElasticSearchConfig.GetClient().DeleteByQueryAsync<PropertySearchResult>(u => u
               .Index(indicies)
               .Query(q => q
               .Bool(bq => bq.Filter(filters))));

at the moment, all indices will be subject to the same filters but I would like to vary the filters based on which index is being searched.

A: Add(with &&) a term query to each of your filters
.Term("_index", A)

Check this link
https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-index-field.html


text:
Q: Phabricator error: unpack failed: unable to create temporary object directory when Git push? I was installed Phabricator on my VM, all settings are working correctly. I made git repo on there, and I can clone, fetch, pull successfully.
But I got an error when I try to push with this description:
error: unpack failed: unable to create a temporary object directory
To http://xxx.yyy.co.id/source/phabricator_docs.git
 ! [remote rejected] master -> master (unpacker error)
error: failed to push some refs to 'http://xxx.yyy.co.id/source/phabricator_docs.git'

Here's some Phabricator setting :
"diffusion.allow-http-auth": true,
"repository.default-local-path": "/opt/phab/repo"
I try to change permission and change the owner of repository dir, but it still got an error.
I'm so depressed about how to solve this error. Because this Phabricator will be used by our employee soon. Hope this question will get an answer and solve my problem.


text:
Q: Create a "regular expressions" that accepts only int and float values As the title suggests I would need a "regular expressions" that accepts only integer values and/or float and more with these conditions

*

*The value must be between 10 and 40

*If it is a float value, accept only one digit after the decimal point

*Example of acceptable values: 10 / 20 / 10.5 / 22.6 / 39.9 / 40

*Example of values not acceptable : 10.55566 / 10.10.10 / 10..

i try this , but accepts values that do not follow my conditions described above (unfortunately with regular expressions are not very clever)
var regex = /^(?=.*\d)\d*(?:\.\d*)?$/;

A: The regex would be:
\b(?:40(:?\.0)?|[1-3][0-9](?:\.[0-9])?)\b

Where:

*

*\b matches a word start/end

*[1-3] limits the first digit to the range 1-3

*[0-9] a compulsory digit must follow, thus adhering to the rule 10 <= n < 40

*(?:..)? ? makes the group optionalwithout ?: disables the capturing of the group

*\.  matches a dot literal

*[0-9] and exactly one digit

Your check method should be something like
var check = function (str) {
    str = str.trim();
    var re = /\b[1-3][0-9](\.[0-9])?\b/;
    match = re.exec(str);
    return match !== null && match[0] === str;
}

Alternative:
/$\s*(:?40(:?\.0)?|[1-3][0-9](\.[0-9])?)\s*^/

Use the latter if you have one string containing the number in question

*

*\s* matches any whitespace characters

*$ represents the beginning of the string

*^ represents the end of the string

A: To match 10<= number <= 40:
\b(?:40|[1-3]\d(?:\.\d)?)\b


text:
Q: Grid trading bot - auto parameters calculation I'm trying to figure out how the Binance Grid Trading Bot calculates its auto parameters. I found the following link which tells us the formula.
How are auto parameters calculated?

*

*Upper Band = MA + BBM * Standard Deviation

*Lower Band = MA - BBM * Standard Deviation

*Grid Number = (grid_upper_limit - grid_lower_limit)/ATR

Average True Range (ATR) for the past pre-defined hours of the selected symbol
https://www.binance.com/en/support/faq/76bd4effa3c4456c971a1c6835762742
I created a small pinescript snippet to test with. However, I'm getting completely different values than what Binance gets.
//@version=5
indicator("Grid Bot - Auto parameters", overlay = true)

src = close
length = 30
mult = 2
resolution = 'D'

// Simple Moving Average
sma = ta.sma(src, length)
smaHTF = request.security(syminfo.tickerid, resolution, sma)

// Bollinger bands
[middle, upper, lower] = ta.bb(src, length, mult)

middleHTF = request.security(syminfo.tickerid, resolution, middle)
upperHTF = request.security(syminfo.tickerid, resolution, upper)
lowerHTF = request.security(syminfo.tickerid, resolution, lower)

// p1 = plot(upperHTF, "Upper", color = #2962FF)
// p2 = plot(lowerHTF, "Lower", color = #2962FF)
// fill(p1, p2, title = "Background", color = color.rgb(33, 150, 243, 95))

// Standard deviation
stdev = ta.stdev(src, length)
stdevHTF = request.security(syminfo.tickerid, resolution, stdev)

//===============================
// Upper price & Lower price
upperPrice = smaHTF + middleHTF * stdevHTF
lowerPrice = smaHTF - middleHTF * stdevHTF

plot(upperPrice)
plot(lowerPrice)

atrHTF = request.security(syminfo.tickerid, resolution, ta.atr(length))
gridNumber = (upperPrice - lowerPrice) / atrHTF
// plot(gridNumber)

Moving average will be the day range you've selected for the grid.
BBM will be as per the standard deviation as stated in the article
https://www.binance.com/en/support/faq/76bd4effa3c4456c971a1c6835762742

A: ta.bb already calculates sma and stdev.
Here you can see in detail:
https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}bb
On the other hand, you are using "request.security" in the wrong way because it repaints
https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html#repainting-request-security-calls
Try this:
//@version=5
indicator("Grid Bot - Auto parameters", overlay = true)

src = close
length = 30
mult = 2
resolution = 'D'

// Bollinger bands
[middle, upper, lower] = ta.bb(src, length, mult)

middleHTF = request.security(syminfo.tickerid, resolution, middle[1], lookahead = barmerge.lookahead_on)
upperHTF  = request.security(syminfo.tickerid, resolution, upper[1],  lookahead = barmerge.lookahead_on)
lowerHTF  = request.security(syminfo.tickerid, resolution, lower[1],  lookahead = barmerge.lookahead_on)

plot(upperHTF)
plot(middleHTF)
plot(lowerHTF)


text:
Q: File.Delete fails on attempting to delete an opened file but deletes on process exit? While calling File.Delete(file_path) for a file which is opened in another process, the attempt fails with cannot access error, but on exiting the app (from where the attempt was made) the file gets deleted automatically. After File.Delete attempt, the path gets inaccessible for any other operation.
I need to either fail on delete and let the path be accessible through the app or delete the file completely, not on app exit.
Well my code is this :
 private bool DeleteFilesAsync(string FileToDelete)
 {
    try
    {
            //Set file's attribute to normal if it is ReadOnly file
            File.SetAttributes(FileToDelete, FileAttributes.Normal);

            File.Delete(FileToDelete);
           //Some bussiness logic to update file's status in database

        return true;
    }
    catch (Exception ex)
    {
        //log the error
         return false;
    }
}

Something wrong here?

A: Windows does have a delete-on-last-close feature. All deletes are handled that way. The only reason that this almost never occurs in practice is because most apps do not open the file with FILE_SHARE_DELETE so it is not possible to delete a used file. But at the Kernel level all deletes are delete-on-close.
There might be a way to clear the delete flag by calling NtSetInformationFile to set the FileDispositionInfo class. This assumes that it is possible to clear the delete flag. It might well be.
Anyway, a more sane approach would be to open the file before deleting it to ensure that exclusive access is available:
using(new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { }

After this line passes without exception, we know that the file was unused at the point of opening it. Of course, it might be opened by someone else immediately after this line, but maybe this solution is enough for you.


text:
Q: Converting a scraped unicode string into regular Python strings this issue has been driving me crazy. I am scraping a webpage using the requests module. The string I get in return is this:
x = "\nM\\u00fcnster - Melbourne - New York\n\\ud83d\\udc7b kaptenandson"

I can't seem to be able to get it to output normally, neither on terminal, nor anywhere else (output files, etc.). The text contains an umlaut and two emojis but I am just not able to work with it – drives me crazy.
Further, I have read through the resources on unicode but they haven't been of any help in this case. Are there any other unicode / encoding tutorials in Python I can read?

A: Figured it out! The string I got was javascript escaped. Pointing to the right answer here:
How do I decode escaped unicode javascript code in Python?


text:
Q: To ensure "Date Modified" doesn't change, want to open all Word and Excel in Read-Only or Protected Mode - how? In order to avoid OneDrive Office documents' "Date Modified" field changing whenever I open and navigate a doc, I want all OneDrive and OneDrive for Business documents to open in Read-Only or Protected Mode by default. This way I can still open and browse/read the file (and ideally, I could also print it), without accidentally changing its modified date. If I do want to edit it, I don't mind hitting the "Enable Editing" button (or taking some other simple action) shown for Protected Mode to make changes. I don't like the extra step before I can start editing, but that seems a much lesser problem than the date mangling that occurs otherwise (with no apparent solutions according to the Internet).
Yes, it is possible to open a OneDrive file and close it without changing the Modified date, but it is easy to accidentally navigate in a way that triggers a save and date change on the file. My core goal is to ensure that CANNOT happen. I don't want to the file's Modified date to change without consciously choosing to make changes to the file. Those dates are critical to me for file searching and navigation.
I also do NOT want to disable AutoSave nor turn off the OneDrive Office Sync. These are essential features for collaboration and even for a single person working on the same document across multiple computers at the same time. I see disabling these is often suggested as the solution (and it would work for that, because they are the reason the Modified date changes). That's just not viable in my case, because I value and need the benefits of OneDrive's live file access, both personal and business versions.
I also want this to be the default for all files, not just a few specific files. I know I can change this per file via File -> Protect Document -> Always Open Read Only. But that only affects one file at a time, and I need this to apply to many hundreds or thousands of files across over a hundred directories. Plus, that's too late, because then I need to re-save the document to apply that change, which changes the modified date -- the very problem I'm trying to solve.
Example of Excel showing manually set to Read Only when saving under File -> Info:

Example of Word showing a file opened from an email is in Protected Mode:

Is there a way to:

*

*Reliably open and freely navigate Office documents on OneDrive without changing the Date Modified value?

*Assuming the answer to #1 is 'no', which is my conclusion following much Internet research and attempts, how can I tell Word, Excel, and PowerPoint to always open every document (at least every OneDrive personal and OneDrive for Business document) in Protected Mode or Read-Only Mode, like in the screen shots above?

*Is there a way to force this across all users on a tenant, preferably via a SharePoint or OneDrive setting (so it applies even to BYOD systems that wouldn't be affected by a Group Policy setting)?


text:
Q: read csv is concating last colum of first row with first column of second row in php I have a csv file like this

i have used the following code.
     $filename=$_FILES['file']['tmp_name'];
    //$err_upTmpName = 'testfile.csv';

        if(!file_exists($filename) || !is_readable($filename))
            return FALSE;

        $header = array('id','name','qty','rate');
        $data = array();

$r = 1;
$r1=0;
$rw=0;
if (($handle = fopen($filename, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);

           for ($c = 0; $c < $num; $c++) {
               if ($r <= 4) {

               } else {
                   $r = 1;

                   $a[$r1] = $s;
                   $r1++;
               }
               $s[] = $data[$c];
               $r++;
           }

       $rw++;
    }
    fclose($handle);
}

var_dump($a);

am getting the output as

array(2) { [0]=> array(4) { [0]=> string(4) "pppp" 1=> string(3)
  "kjj" [2]=> string(3) "rrr" [3]=> string(7) "sss a33" } 1=> array(8)
  { [0]=> string(4) "pppp" 1=> string(3) "kjj" [2]=> string(3) "rrr"
  [3]=> string(7) "sss a33" [4]=> string(3) "200" [5]=> string(2) "50"
  [6]=> string(6) "555 zz" [7]=> string(2) "33" } }

Here am getting first row 3rd column value as sss 333.
But i need as ss.
Also 2nd row in the array is again the first row.
I need the output like

[{ppp,kjj,rrr,sss},{a33,200,50,555},{zz,33,44,44}]

Please help me.


text:
Q: Individual slopes for many zip codes over time I have a dataset where I am interested in calculating a slope for each observation / row.
I have dependent variable $Y$ that is continuous. Every $Y$ is unique to a zipcode.
and my independent / predictor variables are measured over time for every $Y$,
say $x_1$ to $x_{20}$. I am looking for a slope for each $Y$ for each zip code for each row. I am not sure if I can do this by linear regression because I only have one observation for $y$.
I cannot average $x_1$ to $x_{20}$, because I will lose the information on the slope.
The goal here is to measure change in $x$ ($x_1$ to $x_{20}$) on $Y$, and since $x_1$ to $x_{20}$ is measured over time I like to retain the slope information and not simply take the average. I am trying to answer the question 'how severe is the change in $x$ on a zipcode which has a value $Y$'.

A: You will want to use a mixed effects model / multi-level model (these are ultimately the same thing, but they have different terminology and historical development, and constitute different ways of thinking about the situation).
The idea behind these is that you are sampling your zip codes from a population, and you can fit distributions of slopes and intercepts associated with your zip codes over time.  The primary output of such analyses is a population mean slope and intercept, but you can get predicted slopes for each zip code as well.
Your question is rather vague, but I'm guessing you will actually want to take your $x$'s as the dependent variable and $Y$ as the predictor variable. ${\rm Time}$ will also be a predictor variable and your data will be nested within zipcodes.
If you want to explore the threads on CV related to this topic, you can search under the mixed-effect, mixed-model, and multilevel-analysis tags.  In my opinion, the best overall book is:

*

*Fitzmaurice, G.M., Laird, N.M., & Ware J.H. (2011).  Applied Longitudinal Analysis.  Wiley.
For a practical guide to fitting them with different software, you can pair that with:

*West, B.T., Welch, K.B., & Galecki, A.T. (2006).  Linear Mixed Models: A Practical Guide Using Statistical Software.  Chapman and Hall / CRC.


text:
Q: Mapping 3D Scatter Points with Unique, Interpolated Colors So I'm trying to create a 3dscatter plot using matplotlib and have had issues trying to map each individual point to a heat map value. My end goal is to have a 4d graph that visualizes my data. The issue is that some of my data points are repeated and overlap, and that's not something I can change.
I tried:
X, Y = np.meshgrid(np.linspace(min(x), max(x)), np.linspace(min(y), max(y)))
Z = griddata((x, y), z, (X, Y), method='cubic')
W = griddata((x,z), w,(X,Z),method='cubic')
#all array sizes at this point 2500

fig, ax = plt.subplots(subplot_kw={'projection': '3d'})
scamap = plt.cm.ScalarMappable(cmap='inferno')

ax.scatter3D(X,Y,Z,c=W,sparse=True)
#throws a value error where W size != Y or X size

fig.colorbar(scamap)

I expected to see all my points with an associated heat map value but that did not work as the sizes of the arrays became different during plotting. It seems that due to overlapping data, it may be removing it. Here is the table data I am using. How would I properly plot interpolate this into a 4d graph?

Index
Model
x
y
z
w

0
Model 1
63
38
4
5.683333333

1
Model 1
66
34
4
4.85

2
Model 1
71
31
4
3.966666667

3
Model 1
88
32
4
5.683333333

4
Model 1
93
37
4
5.683333333

5
Model 1
77
28
4
3.033333333

6
Model 1
99
42
4
5.683333333

7
Model 1
104
48
4
5.683333333

8
Model 1
110
53
4
5.683333333

9
Model 1
82
26
4
2.4

10
Model 1
116
59
4
5.683333333

11
Model 1
121
64
4
5.683333333

12
Model 1
63
40
10
5.683333333

13
Model 1
66
36
10
5.166666667

14
Model 1
88
37
10
5.683333333

15
Model 1
71
33
10
3.283333333

16
Model 1
82
32
10
4.283333333

17
Model 1
93
43
10
5.683333333

18
Model 1
99
48
10
5.683333333

19
Model 1
77
31
10
2.516666667

20
Model 1
104
53
10
5.683333333

21
Model 1
110
59
10
5.683333333

22
Model 1
116
64
10
5.683333333

23
Model 1
121
70
10
5.683333333

24
Model 1
63
42
16
5.683333333

25
Model 1
66
39
16
4.55

26
Model 1
82
37
16
5.55

27
Model 1
71
35
16
3.4

28
Model 1
88
43
16
5.683333333

29
Model 1
93
48
16
5.683333333

30
Model 1
77
33
16
2.65

31
Model 1
99
54
16
5.683333333

32
Model 1
104
59
16
5.683333333

33
Model 1
110
64
16
5.683333333

34
Model 1
116
70
16
5.683333333

35
Model 1
121
75
16
5.683333333


text:
Q: ArrayList  Understanding I am doing a project on ArrayLists and mathematic methods such as sum, standard deviation and variance etc and I have come across this ArrayList<Double>.
public static double Sum(ArrayList<Double> list) {
    double sum = 0;
    for (int i = 0; i < list.size(); i++) {
        sum = sum + list.get(i);
    }
    return sum;
}

I understand how ArrayList works but I am not exactly sure what is going on in this method, can anyone help me understand it a little better?

A: These are called Generics. Oracle has a great tutorial on it
Long story short, if you write List list = new ArrayList it would mean anything can be put in that list: toys, food, books. Kinda chaotic, huh? I bet what you'd rather have are boxes that contain only certain types of objects: a box for toys, another one for food and one more for books. That's generally what generics allow you to do. By writing List<Book> list = new ArrayList<>(), you're saying that this list can contain only books. If you try to put something else in there, you will get an error.
To sum up, in your case, method sum takes ArrayList<Double> - a list that can contain only Double objects. You can be sure that all of the elements are of that type, so you needn't check.

A: Look at this: ArrayList<Double> list = new ArrayList<Double>(); it creates a list that can only contain double values. A double is a variable type that can contain whole numbers and decimal numbers. So creating a list like this only allows the program to add numbers to the list: list.add(4.3);
When you call this method, you must pass an ArrayList<Double> object to it: Sum(List); Then it takes the list and adds every element of that list together into a variable called sum. After it has done that, it will return that sum. return sum;.
Here's how it does that:
  for (int i = 0; i < list.size(); i++) {
            sum = sum + list.get(i);
        }

Its basic syntax is for(initialization; condition; iteration). When first called it will execute the initialization, then it will continue to repeat as long as the condition is true, and every time it repeats it will execute the iteration.
This specific one creates a variable called i and assigns it the value 0 for its initialization. Then for its condition it does i < list.size(), meaning that it will repeat as long as the integer value contained in i is less then the number of elements in the ArrayList. Finally, for its iteration it does i++, which will make the integer contained in i one value larger every time the thread loops.
So our i will get one value larger every time the loop iterates. Inside the loop we have sum = sum + list.get(i);. This takes the double (decimal) variable sum and adds to its current value whatever value is contained in the i (remember i has a number value) element of the ArrayList.
Click this link to learn more about for loops: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
So if the ArrayList contained the values {2, 4, 1, 5} and i contained the value 1, then calling sum = sum + list.get(i); would add the value 4 to the the value contained in sum. If i equaled 0 and we called sum = sum + list.get(i), than sum's value would be increased by 2, and it goes on like that.
These are called indexes. Indexes are numbers used to access objects in arrays or array lists. If I had an array that looked like this: int array[] = {4, 2, 5, 3}; then 4's index would be 0, 2's index would be 1, 5's index would be 2, and 3's index would be 3.
This image can give you a better understanding of indexes:


text:
Q: Group of deck transformations cyclic Given a pointed topological space $(X,x_0)$, let $p\colon (\tilde{X}, \tilde{x}_0)\to (X,x_0)$ be a covering of that space. Write $p^{-1}(x_0)= \{\tilde{x}_0, \tilde{x}_1,\ldots,\tilde{x}_n\}$. I'd like to show that there is a deck transformation $T$ s.t. $T\tilde{x}_k=\tilde{x}_{k+1}$ if and only if $p_*(\pi_1(X,x_0))$ is normal and the group of deck transformations is cyclic.
If $p_*(\pi_1(\tilde{X},\tilde{x}_0))$ is normal and the group of deck transformations is cyclic, must we have $p_*(\tilde{X},\tilde{x}_0)=deck(X,p)$?

A: Let us denote $G=\pi_1(X,x_0)$ and $H=p_*(\pi_1(\bar{X},\bar{x}_0)$.
The first statement, about the cyclicity of the group $\text{deck}(X,p)$ of deck transformations, follows when you observe that $\text{deck}(X,p)$ acts transitively on $p^{-1}(x_0)$ if and only if $H$ is normal in $G$. (It is important to note where a subgroup is normal, as we will see!)
As for your second question, note that $\text{deck}(X,p)$ is isomorphic to $N(H)/H$, where $N(H)$ is the normalizer of $H$ in $G$, defined as the largest intermediate subgroup $H\subseteq N(H)\subseteq G$ such that $H$ is normal in $N(H)$. There is an explicit formula for $N(H)$ here. Therefore, if $H$ is already normal in $G$, we have $N(H)=G$, and $\text{deck}(X,p)(\bar{X})=G/H$. You can see that your second statement is false in general. For example, let $G=S_3$, the symmetric group on 3 variables, and let $H$ be $\mathbb{Z}/3\mathbb{Z}$. $H$ is then a normal subgroup, and the group of deck transoformations is $G/H=\mathbb{Z}/2\mathbb{Z}$ which is cyclic.
If order for the condition $H\simeq \text{deck}(X,p)$ to happen, you need $N(H)/H\simeq H$, which can happen, for example when $G$ is either a product $G\simeq H\times H$, or a semidirect product $G\simeq H \rtimes H$.


text:
Q: Realm, Swift and App Sandbox not working? I can't get Realm (lastest version), Swift and Sandboxing to work.
I created a Hello Word app with RealmSwift / Realm embedded binaries included correctly.
import RealmSwift

..add one class and only the line:
let realm = try! Realm ()

Then I got this error when I run the app:
*2016-08-17 21:04:05.404 testprosjekt1[37407:21624950] ***storageTaskManagerExistsWithIdentifier:withIdentifier failed: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.nsurlstorage-cache was invalidated." UserInfo={NSDebugDescription=The connection to service named com.apple.nsurlstorage-cache was invalidated.}; {
    NSDebugDescription = "The connection to service named com.apple.nsurlstorage-cache was invalidated.";
}
2016-08-17 21:04:05.412 testprosjekt1[37407:21624950] ***cachedResponseDictionaryForRequest:key:handler failed: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.nsurlstorage-cache was invalidated." UserInfo={NSDebugDescription=The connection to service named com.apple.nsurlstorage-cache was invalidated.}; {
    NSDebugDescription = "The connection to service named com.apple.nsurlstorage-cache was invalidated.";*
}

If I turn off sandboxing - I got NO error at all.
So, my question is: Is the latest version of Realm NOT working with sandboxed apps?

*

*I have tried set Read / write on to all the directories in sandboxing, but this does not help.

*I use xCode 7.3

A: Realm works well with sandboxing (until you try to reader or write to a directory you don't have access to).
Realm collects anonymous analytics and checks for updates when your app is run with a debugger attached, or when it runs in a simulator. This call does not run when your app is in production, or running on your user's devices. See more at FAQ.
Also if you perform any network calls in your app add com.apple.security.network.client to your entitlement (or simply enable Outgoing connection (Client) in Capabilities tab of your project's settings).


text:
Q: Update ctx.textAlign with js function Hi I have this js function:
function ChangeTextAlign(selectTag) {
    // Returns the index of the selected option
    var whichSelected = selectTag.selectedIndex;

    // Returns the text of the selected option
    var alignValue = selectTag.options[whichSelected].text;

    var div = document.getElementById("first-text");
    div.style.textAlign = alignValue;
}

This function updates text alignement perfectly in the input field right there:
<input type='text' value='Pirma eilutė' id='first-text' />

But how to make it work with ctx.textAlign ? Here's how it is set right now:
 ctx.font = '12pt sans-serif';
 ctx.strokeStyle = '#929292';
 ctx.fillStyle = '#929292';
 ctx.textAlign = 'center';
 ctx.textBaseline = 'top';

I want to update the ctx.textAlign value everytime I press one of these options:
Change textAlign value:
 <select onchange="ChangeTextAlign (this);" size="4">
     <option />left
     <option />right
     <option selected="selected" />center
     <option />justify
 </select>

This works only with my input field, but I want to update the value of the ctx.textAlign. How can I do this ?

A: Given this html:
<select id='align' size="4">
    <option value='left'/>left
    <option value='right'/>right
    <option value='center' selected="selected" />center
    <option value='justify' />justify
</select>

Listen for change events on your select element:
var selection=document.getElementById('align');
selection.onchange=function(e){ChangeTextAlign(e);};

On selection change:

*

*Fetch the user's chosen alignment value

*Set context.textAlign to that value

*Clear the canvas

*Redraw the text to display it with the chosen alignment

The javascript change handler:
function ChangeTextAlign(event){
    var newAlignment=selection.value;
    if(newAlignment=='justify'){alert('Justify is not supported'); return;}
    ctx.textAlign=newAlignment;
    redraw(text);
}

Example code and a Demo:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;

var text = 'Hello, World!'
ctx.textAlign = 'center';

redraw(text);

var selection = document.getElementById('align');
selection.onchange = function(e) {
  ChangeTextAlign(e);
};

function ChangeTextAlign(event) {
  var newAlignment = selection.value;
  if (newAlignment == 'justify') {
    alert('Justify is not supported');
    return;
  }
  ctx.textAlign = newAlignment;
  redraw(text);
}

function redraw(text) {
  // clear the canvas
  ctx.clearRect(0, 0, cw, ch);
  // demo only, show the fillText x,y
  ctx.fillRect(cw / 2, 0, 1, ch);
  // draw the text
  ctx.fillText(text, cw / 2, ch / 2);
}
body {
  background-color: ivory;
}
#canvas {
  border: 1px solid red;
  margin: 0 auto;
}
<canvas id="canvas" width=200 height=100></canvas>
<select id='align' size="4">
  <option value='left' />left
  <option value='right' />right
  <option value='center' selected="selected" />center
  <option value='justify' />justify
</select>


text:
Q: AMPL: variable is already defined first time coding for class and im getting this error that my variable is already defined. i've tried "reset;" already and it still appears. here is my code.
var p11 integer >= 0; # p11 describes the designer
var p12 integer >= 0; # then the project the designer
var p13 integer >= 0; # is working on
var p14 integer >= 0;
var p21 integer >= 0;
var p22 integer >= 0;
var p23 integer >= 0;
var p24 integer >= 0;
var p31 integer >= 0;
var p32 integer >= 0;
var p33 integer >= 0;
var p34 integer >= 0;

maximize scores:
    90 * p11 + 80 * p12 + 10 * p13 + 50 * p14 + 60 * p21 + 70 * p22 + 50 * p23 + 65 * p24 + 70 * p31 + 40 * p32 + 80 * p33 + 85 * p34;

subject to hours_required:
    p11 + p21 + p31 >= 70;
    p12 + p22 + p32 >= 50;
    p13 + p23 + p33 >= 85;
    p14 + p24 + p34 >= 35;

subject to hours_split:
    p11 + p12 + p13 + p14 <= 80;
    p21 + p22 + p23 + p24 <= 80;
    p31 + p32 + p33 + p34 <= 80;


text:
Q: Is it safe to use Unicode characters in Java GUI? For a play button in a Java GUI I currently use a button with the label set to ' ▻ ' (found this symbol in a Unicode symbol table). As I understand, it is better to not use such symbols directly in source code but rather use the explicit unicode representation like \u25BB in this example, because some tools (editor, ...) might not be able to handle files with non-ASCII content (is that correct?).
Assuming the compiled class contains the correct character, under which circumstances would the GUI not show the intended symbol on a current PC operating system? Linux, Windows, Mac should all support UTF-16, right? Do available fonts or font settings cause problems to this approach?
(Of course I could add an icon, but why add extra resources if a symbol should already be available... given that this is a portable solution)

A:
Do available fonts or font settings cause problems to this approach?

Unfortunately they do. You can use unicode in the source code of course, but the problem is that currently unicode has 246,943 code points assigned so obviously no font has even a fraction of those defined. You'll get squares or some other weird rendering when the glyph isn't available. I've had cases where relatively simple symbols such as ³ render fine on one Windows computer and show up as squares in the next, almost identical computer. All sort of language and locale settings and minor version changes affect this, so it's quite fragile.
AFAIK there are few, if any, characters guaranteed to be always available. Java's Font class has some methods such as canDisplay and canDisplayUpTo, which can be useful to check this at runtime.
Instead of using icons, you could bundle some good TrueType font that has the special characters you need, and then use that font everywhere in your app.

A: I currently use a button with the label set to ' ▻ '

rather than I always use JButton(String text, Icon icon), and Icon doesn't matter if is there this Font or another Font, UTF-16 or Unicode

A: Most of editors have support for unicode, so go on.
Look at this post: Eclipse French support
If you are using simple editor like notepad then when you save type name and below it choose UTF encoding ( http://www.sevenforums.com/software/72727-how-make-notepad-save-txt-files-unicode.html )


text:
Q: Newtonsoft.Json - Dynamic object property access I'm trying to go through every property on a dynamic object contained in a JArray:
Newtonsoft.Json.Linq.JArray feeds = Newtonsoft.Json.Linq.JArray.Parse(response.Content);
if (feeds.Any())
{
    PropertyDescriptorCollection dynamicProperties = TypeDescriptor.GetProperties(feeds.First());
    foreach (dynamic feed in feeds)
    {
        object[] args = new object[dynamicProperties.Count];
        int i = 0;
        foreach (PropertyDescriptor prop in dynamicProperties)
        {
             args[i++] = feed.GetType().GetProperty(prop.Name).GetValue(feed, null);
        }
        yield return (T)Activator.CreateInstance(typeof(T), args);
    }
}

When i triy to accessfeed.GetType().GetProperty(prop.Name).GetValue(feed, null); it tells me that feed.GetType().GetProperty(prop.Name); is null.
JSON structure looks like:
[
    {
        "digitalInput.field.channel":"tv",
        "digitalInput.field.comment":"archive",
        "count(digitalInput.field.comment)":130
    }
]

Can someone help me?

A: Try to change your foreach to
foreach (PropertyDescriptor prop in dynamicProperties)
{
    args[i++] = prop.GetValue(feed);
}

UPDATE
args[i++] = feed.GetType().GetProperty(prop.Name).GetValue(feed, null);

So, lets see on it step by step:

*

*feed.GetType():  will return type JArray

*feed.GetType().GetProperty(prop.Name): the problem is here, because
You tried to get propery of type JArray by name, but
prop.Name in your case will be "digitalInput.field.channel", "digitalInput.field.comment" and "count(digitalInput.field.comment)"
So, in a result it will return null because type JArray doesn't have such properties.


text:
Q: Will these two coherent electromagnetic waves be in phase? My question is how will I know if two coherent electromagnetic waves are in phase based on their phase difference.
I just solved a problem which stated...

Two coherent sources A & B send electromagnetic waves with wavelength = 2.4 cm. Find the phase difference when A is 2.52m from a point and B is 3.60m away from the same point.

I used the equation $\phi = 2\pi(R_2-R_1)/\lambda$ and I got $90\pi$.
So these two wavelengths have a phase difference of $90\pi$ degrees , are these two wavelengths in phase? How would I know?

A: Coherency has to be over a period of time. Instantaneously any two waves (or signals) at the same freq will have at at one time or point a phase difference. If their freqs stay exactly what they had at one time, they will stay coherent with each other, i.e. The phase differences won't change over the same period of time for the two. Over a period of time the oscillator or clock that determines the freq of a wave, will drift and have random fluctuations. If the drift of two such oscillators or clocks, is zero and their instantaneous fluctuations also zero (impossible unless at zero Kelvin) they stay coherent. Small drifts and small amount of random fluctuations will make them coherent to some extent. So drifts increase over a longer time range, and random fluctuations also affects it - the probability density function of the so called phase noise which causes those random fluctuations (in freq and in phase) is highest at the oscillator center freq, and goes down as you go away, so one must calculate.
Usually coherence can be calculated/analyzed by knowing (somebody measured it and specified it, or you go measure it) the stability of the transmitter (usually set by the oscillator), and is denotes
D as eg, 10^(-6) over 100 msec. Means that over 100 msec the difference in freq (and from that you can compute phase differences) is 1 part in 10^6, eg 1 KHz at a freq of 1 GHz. Clearly ok for pulsed Non-coherent detection, but not so good for non-coherent detection (eg, in radar, one would use a signal at that freq and look for Doppler changes, and 1 KHz would be a Doppler you would look for, so this coherency (or stability) would not be good enough in a Doppler radar).
You can estimate the coherency of two signals using standard signal processing techniques. First you must digitize, with a x100 (or dependent on the sigma you can tolerate) time better stability in your oscillator than whatever you want to estimate. Then you do a cross coherency estimate, it is very similar to a cross correlation, both of which done with correlators or Fast Fourier Transforms.

A: Coherent sources- Two sources of light are said to be coherent if the waves emitted from them have the same frequency and are 'phase-linked'; that is, they have a zero or constant phase difference.
The calculation yielded 90.pi ; We know that 2.pi denotes a phase change of zero as the waves will come back to initial phase relation of the coherent sources.The waves advance by one wavelength when the phase change is 2.pi.
Your result to be correct ; its a multiple of 2.pi therefore their phase relations are same as the initial condition  that either they are in phase or having the constant phase difference as in the beginning.


text:
Q: My NIntegrate expression returns a wildly inaccurate value I am trying to integrate a function using NIntegrate:
a1 = 0.00221856
b = 0.0990293
h = 100.0
a1 NIntegrate[Exp[-b * (z-h)^2]* z, {z, 0, Infinity}, AccuracyGoal -> 4]

(* Out: 6.202e-25 *)

I have also computed the same integral analytically and the answer is 1.25.
In Mathematica, if I replace the limits of integration as {z, 0, 200} in place of {z, 0, Infinity}, then I get the right answer. I am confused as to what is going on.

A: Here is the function you are integrating:
Plot[Exp[-b*(z - h)^2]*z, {z, 0, 200}, PlotRange -> All]

Again for reference, your integral can be calculated analytically, as you mentioned yourself:
a1 = Rationalize[0.00221856, 0];
b = Rationalize[0.0990293, 0];
h = 100;
a1 Integrate[Exp[-b*(z - h)^2]*z, {z, 0, Infinity}]
N[%]

(* Out:
-(13866/25) Sqrt[(2 Pi)/4951465] (-2 + GammaRegularized[-(1/2), 990293/1000])
1.24958
*)

Numerically, once you remove the AccuracyGoal option you have in your code, NIntegrate works, but returns a warning:
a1 = 0.00221856;
b = 0.0990293;
h = 100.0;
a1 NIntegrate[Exp[-b*(z - h)^2]*z, {z, 0, Infinity}]

(* Out: 1.24958 *)

The warning suggests that the routine needs to perform more bisections than the default value of MaxRecursion will allow.
The natural approach will then be to increase the value of MaxRecursion. The following, for example, executes immediately and without warnings to yield the correct value:
a1 NIntegrate[Exp[-b*(z - h)^2]*z, {z, 0, Infinity}, MaxRecursion -> 20]

(* Out: 1.24958 *)

Notice that AccuracyGoal can be difficult to use; for instance, the "Details and Options" section of the documentation for AccuracyGoal mentions that "In most cases, you must set WorkingPrecision to be at least as large as AccuracyGoal." In this case, even setting a much higher working precision does not solve the problem.


text:
Q: SSRS Line Chart how displaying Fiscal Month and Year on the Horizontal Axis The sql I used to generate month and year is as below:
left(CONVERT(VARCHAR(10), CLOSED_DT, 112), 6) AS MONTH
The fomat of the Month and year is '201507'. How can I show fiscal year and month on horizontal axis? For example, 'Dec 2015' comes before 'Jan 2016'.

A: you have created a string, so it will be sorted alphabetically.
Instead convert to the first day of the month:
DATEADD(month, DATEDIFF(month, '2000-01-01', CLOSED_DT), '2000-01-01') as MONTH
That can still be used for grouping, and it will be treated and sorted as a date.
You can then format the Date as appropriate within the axis


text:
Q: Defining Variable Variables using LESS CSS Say I have three separate color schemes that are used on various pages in a site. Each color has a a light, medium and dark tint defined, and the color scheme is defined by a class in the body. Assume that the "red" color scheme is the default. Like this:
Color Definitions:
@red-lt:   #121;
@red-md:   #232;
@red-dk:   #343;
@green-lt: #454;
@green-md: #565;
@green-dk: #676;
@blue-lt:  #787;
@blue-md:  #898;
@blue-dk:  #909;

Basic Default Style Example
body { background-color: @red-dk;
  #container { background-color: @red-md;
     p { color: @red-dk; }
  }
}

Different Color Scheme Style Example
body.green { background-color: @green-dk;
  #container { background-color: @green-md;
     p { color: @green-dk; }
  }
}

I'd like to use variables so that I don't have to re-write all of the color variations for each scheme, so that I can just write something like this:
body.[color-var] { background-color: @[color-var]-dk;
  #container { background-color: @[color-var]-md;
     p { color: @[color-var]-dk; }
  }
}

…but I can't quite wrap my head around how to accomplish that. Help…?

A: Use interpolation and escaping, parentheses in the selector and parametric mixins to get the desired effect:

*

*Dynamic variables by interpolation: In a string, "@{variable}" is replaced with the value of the variable. They can also be nested: Given @{@{var}-foo} and @var: bar;, the result is "barfoo".
The resulting value is quoted. To remove these quotes, prefix ~.

*Dynamic selectors by Selector interpolation: body.@{var} turns into body.bar.

Example:
@red-md:   #232;
@red-dk:   #343;

.setColor(@color) {
    body.@{color} { background-color: ~"@{@{color}-dk}";
        #container { background-color: ~"@{@{color}-md}";
         p { color: ~"@{@{color}-md}"; }
      }
    }
}
.setColor(~"red"); // Escape to prevent "red" turning "#FF0000"
//.setColor(~"blue"); etc..

Turns into:
body.red {
  background-color: #334433;
}
body.red #container {
  background-color: #223322;
}
body.red #container p {
  color: #223322;
}

Note: When the answer was originally written, selector interpolation did not exist. See the previous revision for the solution if you're working with an old LESS compiler (before LESS 1.3.1a). Support for the old method will be dropped in LESS 1.4.0.

A: If those values really follow a predictable format like that, seems like a perfect case for a parametric mixin:
Less:
@red:   #232;
@green: #565;
@blue:  #898;

.theme (@color) {
  background-color: @color - #111;
  #container {
    background-color: @color;
    p { color: @color + #111; }
  }
}

body.red {
  .theme(@red);
}

Compiled CSS:
body.red{background-color:#112211;}
body.red #container{background-color:#223322;}
body.red #container p{color:#334433;}

A: I know this question is pretty old, but for those that come to this post my answer maybe can help
I`m not really sure for what you want to use this, but one of my suggestion is based on @ScottS answer. On my real world, I need to create a web app, where it would show several brands and each brand have their own text color, background and so on... so I started to chase a way to accomplish this in LESS, what I could easily do on SASS and the result is below:
LESS
// Code from Seven Phase Max
// ............................................................
// .for
.for(@i, @n) {.-each(@i)}
.for(@n)     when (isnumber(@n)) {.for(1, @n)}
.for(@i, @n) when not (@i = @n)  {
    .for((@i + (@n - @i) / abs(@n - @i)), @n);
}

// ............................................................
// .for-each

.for(@array)   when (default()) {.for-impl_(length(@array))}
.for-impl_(@i) when (@i > 1)    {.for-impl_((@i - 1))}
.for-impl_(@i)                  {.-each(extract(@array, @i))}

// Brands
@dodge : "dodge";
@ford : "ford";
@chev : "chev";

// Colors
@dodge-color : "#fff";
@ford-color : "#000";
@chev-color : "#ff0";

// Setting variables and escaping than
@brands: ~"dodge" ~"ford" ~"chev";

// Define our variable
.define(@var) {
  @brand-color: '@{var}-color';
}

// Starting the mixin
.color() {
    // Generating the loop to each brand
    .for(@brands); .-each(@name) {
        // After loop happens, it checks what brand is being called
        .define(@name);
         // When the brand is found, match the selector and color
        .brand-@{name} & {
            color: @@brand-color;
        }
    }
}

.carColor {
    .color();
}

Te result will be:
CSS
.brand-dodge .carColor {
    color: "#fff";
}
.brand-ford .carColor {
    color: "#000";
}
.brand-chev .carColor {
    color: "#ff0";
}

This is very tricky and I had to use several elements to get what I needed, first used a set of mixins provided by Seven Phase Max and you can find it here and than, the @ScottS answer was the piece that was missing fro my puzzle... hope this helps you and others that need to create a set of Variables to be part of another variable and create a more dynamic less file.
You can copy my entire code and test at http://lesstester.com/

A: Try this
@red-lt:   #121;
@red-md:   #232;
@red-dk:   #343;
@green-lt: #454;
@green-md: #565;
@green-dk: #676;
@blue-lt:  #787;
@blue-md:  #898;
@blue-dk:  #909;

@color: 'red-lt';

div{
background: @@color;
border: 1px solid lighten(@@color,20%);
}

A: To my knowledge, variable variable names are not supported in LESS. You could however restructure your declarations in a more semantic manner:
/* declare palette */
@red-lt:   #121;
@red-md:   #232;
@red-dk:   #343;
@green-lt: #454;
@green-md: #565;
@green-dk: #676;
@blue-lt:  #787;
@blue-md:  #898;
@blue-dk:  #909;

/* declare variables based on palette colors */
@lt: @red-lt;
@md: @red-md;
@dk: @red-dk;

/* ...and only use them for main declarations */
body { background-color: @dk;
  #container { background-color: @md;
     p { color: @dk; }
  }
}

This should let you switch between palettes quite painlessly by avoiding explicit color references.


text:
Q: Jquery .load() function isn't working on Chrome? I tried to used the .load() function of Jquery. It seem to me that its not working on my Chrome but its working on Firefox and Safari...
I'm not sure what I did wrong?
Please help me....
Here's my code below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link rel="stylesheet" href="css/goldstyle.css" type="text/css" media="all"/>

A: I found out that if you're directly opening the file in the browser, i.e file:/// it will not work in Chrome, and you'll see something like:
Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin

You need to setup a web-server, like WAMP, and then run it from localhost instead

A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link rel="stylesheet" href="css/goldstyle.css" type="text/css" media="all"/>

I updated your code so the load is in the correct place as its bad practice to have it where it was.
Your also shouldnt have jQuery normal and min this will cause some issues to!
It works fine here on Chrome,IE and Firefox.
Have you tried pushing F12 for developer tools?
Then seeing what errors are displayed in the console?

A: I had an comparable problem and found out, that Chrome (in opposite to IE or FF) often needs an additional Ctrl+F5 to unload the cached content.
For me it seemed that my $().ready function doesn't work, but after Ctrl+F5 it does work.
I know it is not exactly an answer to the question, but I came here with this described behaviour - and perhaps others do.

A: I met the similar problem and I fix that with adding setTimeout() instead of only function() there, it works.


text:
Q: Regex for Kata.StringCalculator I'm trying to use a regexp in the StringCalculator kata with that I want to find out if the string contains the definition for the use delimiter or not.
My input string is
//[;]\n1;2;3

My regexp is
//\[(.)\]\\n(.+)

My regexp will be parse a that what I expect: http://www.myezapp.com/apps/dev/regexp/show.ws?regex=//%5C%5B%28.%29%5C%5D%5Cn%28.+%29&env=env_js
In this online tester I see the expected result: http://www.brain4.de/programmierecke/js/tools/regex.php
String.match(RegExp) returns: »//[;]\n1;2;3« »;« »1;2;3«
RegExp.exec(String) returns: //[;]\n1;2;3,;,1;2;3
RegExp.test(String) returns: true
String.search(RegExp) returns: 0

The following code in JavaScript returns null but I don't see why:
new RegExp('//\[(.)\]\n(.+)').exec('//[;]\n1;2;3')

A: Use this:
new RegExp('//\\[(.)\\]\n(.+)').exec('//[;]\n1;2;3')

Note that you have to escape the backslash itself in the regex otherwise it matches itself literally (the way it's matching in \n).


text:
Q: Powershell through CMD or VBS getting FileVersion Okeys, I'm at a loss of understanding something. It might be in here somewhere already, but I'm haveing some trouble explaining it to myself, so I'm also haveing trouble searching for it.
The thing isn't really complicated, just illogical to me. I'm trying to set up a script in Powershell that mainly goes into a folder and gets the versions of all the *.exe files. And that works quite well like this :
dir 'C:\Program Files (x86)\SPN'| Get-ChildItem -Recurse -Include '*.exe' |%{$_.VersionInfo} | select FileName, FileVersion | Format-Table -Autosize | Out-file c:\test.txt

It's pretty simple as all it does is go into the folder, recursivly searching for the exe files, taking out the VersionInfo and then selecting the FileNames and Versions before putting it into a file as to make a report of the versions installed. And it works too!
The problem is a bit more complicated. We use a htm\vbs application to run scripts. Mainly it means that all our scripts be it vbs, batch, or powershell is run through this platform. Sometimes we also run a powershell through a batch file started by a vbs script.
When I start powershell and run the script above a file is outputed with the information I'm after, when I start a cmd and run the powershell script I get a list of the applications without the versions. Same goes for vbs.
So I thought I'd go more deep. I started a cmd, and typed in start powershell to get a new window that way, but alas, I still only get the filenames and no versions! The only way I get the versions is to run the script through Powershell it self. ( meaning I have to manually open Powershell, as right clicking and selecting Run with Powershell gives names, and no versions )
Any suggestions and ideas would be welcome.
Thanks.

A: Some columns might not be displayed if you specify the widest columns first, so it is safest to specify the smallest data elements first. In the following example, we specify the extremely wide path element first, and even with wrapping, we still lose the final column.
Specify fileversion first fixes the problem.
dir 'C:\.....| Get-ChildItem -Recurse -Include '*.exe' | %{$_.VersionInfo} | select FileName, FileVersion | Format-Table -Wrap -Autosize -Property fileversion, filename | Out-File "C:\....\testing.txt"

http://technet.microsoft.com/en-us/library/dd347677.aspx


text:
Q: xslt mapping to find substring between I have my string as below
<Text>Pack:NA Lead:20 Dimension:235</Text>

And need to map
NA to outputfield1
20 to outputfield2
235 to outputfield3

How to do this correctly in xslt mapping where the values 'NA,20,235' could be different each time?
I could only see substring component which takes length as second parameter.
That leads requires several steps to achieve this.
Any better solution to just take the value between Lead: and Dimension for outputfield2?

A: To extract the Pack value, you can use:
<xsl:value-of select="substring-before(substring-after(Text, 'Pack:'), ' ')" />

To extract the Lead value, use:
<xsl:value-of select="substring-before(substring-after(Text, 'Lead:'), ' ')" />

To extract the Dimension:
<xsl:value-of select="substring-after(Text, 'Dimension:')" />


text:
Q: What is the way to represent factor variables in scikit-learn while using Random Forests? I am solving a classification problem using Random Forests. For that I have decided to use Python library scikit-learn. But I am new to both Random Forest algorithm and this tool. My data contains many factor variables. I googled for that and found out that it's not right to give numerical values to factor variables like we do in linear regression, as it will treat it as continuous variable and give wrong result. But I could not find anything about how to deal with factor variables in scikit-learn. Please tell me the options to use or point me to some document where I can get it.

A: You should use the sklearn's OneHotEncoder. What it does is create a new variable for each distinct value in your categorical integer feature.
So for example if you have variable var with values [10, 25, 30], it will create three new variables (i.e. matrix with 3 columns), essentially with variables var_10, var_25 and var_30 with values [1, 0, 0], [0, 1, 0] and [0, 0, 1] respectively.

A: If you are using a pandas data frame to you can easily use the get_dummies function to accomplish this. Here's an example:
import pandas as pd

my_data = [['a','b'],['b','a'],['c','b'],['d','a'],['a','c']]
df = pd.DataFrame(my_data, columns = ['var1','var2'])
dummy_ranks = pd.get_dummies(df['var1'], prefix = 'var1_')
print dummy_ranks

   var1__a  var1__b  var1__c  var1__d
0        1        0        0        0
1        0        1        0        0
2        0        0        1        0
3        0        0        0        1
4        1        0        0        0

[5 rows x 4 columns]


text:
Q: How push path to proper context in React Router from outside route context? I have some dynamically created components that are created outside the ReactRouter node/component, so ReactRouter considers them to not be inside a context and if I try to use ReactRouter.Link it throws the error:
Links rendered outside of a router context cannot handle clicks

I have found a work around by using this:
var routes = ReactDOM.render((
    <ReactRouter.Router history={ReactRouter.browserHistory}>
        <ReactRouter.Route  path="/" component={Main}>
          <ReactRouter.IndexRoute component={Homepage}/>
          <ReactRouter.Route path="about" component={About} />
        </ReactRouter.Route>
    </ReactRouter.Router>
), document.getElementById('routes'));

//So items outside routes can still use the router
routes.goTo = function(route)
{
    //Go to the route
    routes.history.push( route );
};

This works, but is there also a way to get/set the context and use that to navigate?


text:
Q: Java Multithreading - Producer Consumer with limits I am trying to write the solution for Producer/Consumer but with limits.
The producer(s) (there may be more than one) should terminate after producing a total of 5 values while the consumer(s) (there may be more than one consumer as well) should stop after all five values have been consumed.
I have tried to use AtomicInteger for this:
public class InternalQueue {

    private static final int MAX_QUEUE_SIZE = 10;

    private Queue<Integer> queue = new LinkedList<>();

    public AtomicInteger itemsProduced = new AtomicInteger(0);

    public AtomicInteger itemsConsumed = new AtomicInteger(0);

    public synchronized boolean put(int n) {
        if(itemsProduced.get() < MAX_QUEUE_SIZE) {
            queue.add(n);
            itemsProduced.addAndGet(1);
            return true;
        }
        return false;
    }

}

But the problem is how do I let the consumer thread to know when to stop ?
I want to avoid exceptions.
There may be also multiple producers and multiple consumers.
Any better way to do this ?

A: Maybe something like this wrapper over BlockingQueue?
public class MyQueue<T> {

    private final BlockingQueue<T> queue;
    private final AtomicInteger freeSpace;

    public MyQueue(int size) {
        this.freeSpace = new AtomicInteger(size);
        this.queue = new LinkedBlockingQueue<>(size);
    }

    public boolean produce(T t) {
        if(isDone()) {
            return false;
        }

        freeSpace.decrementAndGet();
        return queue.offer(t);
    }

    public boolean isDone() {
        return freeSpace.get() <= 0;
    }

    public Optional<T> consume() {
        return Optional.ofNullable(queue.poll());
    }
}

Consumers could use the isDone method or could stop when the Optional returned by consume is empty. Note that null values are not accepted

A: You need your queue class to keep track of the number of items posted to the queue, as well as when the queue is empty or full. You also need to queue the requests of the producers so that only one producer at a time is given access to the queue.
The following Ada example demonstrates this. The solution is straightforward in Ada because Ada queues calls to protected object entries, ensuring only one producer or consumer has access at any given time.
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   protected Limited_Buffer is
      entry Put(Item : in Integer);
      entry Get(Item : out Integer);
      function Is_New return Boolean;
      function At_Limit return Boolean;
   private
      Count : Natural := 0;
      Value : Integer;
      New_Value : Boolean := False;
   end Limited_Buffer;

   protected body Limited_Buffer is
      entry Put(Item : in Integer) when not New_Value and then not At_Limit is
      begin
         Value := Item;
         New_Value := True;
         Count := Count + 1;
      end Put;
      entry Get(Item : out Integer) when New_Value is
      begin
         Item := Value;
         New_Value := False;
      end Get;
      function Is_New return boolean is
      begin
         return New_Value;
      end Is_New;

      function At_Limit return Boolean is
      begin
         return Count >= 5;
      end At_Limit;

   end Limited_Buffer;

   task P1;

   task body P1 is
      Num : Integer := 1;
   begin
      loop
         select
            Limited_Buffer.Put(Num);
            Num := Num + 1;
         or
            delay 0.001;
         end select;
         exit when Limited_Buffer.At_Limit;
      end loop;
   end P1;

   task P2;

   task body P2 is
      Num : Integer := 10;
   begin
      loop
         select
            Limited_Buffer.Put(Num);
            Num := Num + 1;
         or
            delay 0.001;
         end select;
         exit when Limited_Buffer.At_Limit;
      end loop;
   end P2;

   task type C1;

   task body C1 is
      Num : Integer;
   begin
      loop
         select
         Limited_Buffer.Get(Num);
         Put_Line(Num'Image);
         or
            delay 0.001;
         end select;
         exit when Limited_Buffer.At_Limit;
      end loop;
   end C1;

   Con1, Con2 : C1;

begin
   null;
end Main;

Ada protected objects, such as Limited_Buffer in the example above, allow the definition of three kinds of methods: procedures, entries, and functions. Procedures provide an exclusive unconditional read-write lock on the protected object. Entries provide a conditional read-write lock on the protected object. Functions are read-only methods that provide a shared read lock on the protected object.
This example uses two entries named Put and Get as well as two functions named Is_New and At_Limit. The private portion of the protected object declaration defines the private data used by the protected object. In this example there are three data items within the protected object. Count is an instance of Natural, which is a pre-defined subtype of Integer with a minimum value of 0. Count is initialized to 0 in this example. Value is an instance of Integer. Value is the data element storing the value written to and read from the protected object by the Put and Get entries. New_Value is an instance of Boolean initialized to False. New_Value is used to ensure that each value written to the protected object is consumed exactly once.
The protected body Limited_Buffer implements the logic for the two entries and the two functions. Ada always separates the specifications and the implementations for protected objects and for tasks.
The first line of each entry mimics the protected object specification but also adds the boundary conditions. The entry is only evaluated when the boundary condition evaluates to TRUE. Each call by a task to an entry is queue. The default queuing policy is FIFO, ensuring that the calls are handled in the order the calls were made. The calling task is suspended while its call is in the entry queue. Each entry has its own queue.
The example goes on to create two producer tasks named P1 and P2. The only difference between the two tasks is the range of numbers they write to the queue.
We do not want the producers to be suspended in the Put entry queue forever when the Queue has processed it limit of values. Ada provides syntax for conditionally calling an entry queue. This syntax begins at the "select" reserved word. After the entry call completes the local variable Num is incremented. The conditional nature of the call begins at the "or" reserved word. The entry call is associated with a timer. If the time expires before the entry call completes the entry call is cancelled and the loop repeats. The loop is terminated when Limited_Buffer.At_Limit returns TRUE.
The two consumers are identical. I therefore created a task type for the consumers. Two instances of the task type are created later in the source code. The consumers repeatedly call Limited_Buffer.Get and print the value retrieved from the buffer. This activity is also done conditionally because we do not want the consumers to be suspended after all values have been read from the buffer.
Finally two instance of the consumer task type are create. All four tasks begin execution when the execution of the main procedure reaches the begin statement in the main procedure. The main procedure does nothing else, which is why its only executable statement is the null reserved word.

A: Look at ArrayBlockingQueue:

This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.


text:
Q: HTTP Status code for content unavailable without a redirect I'm trying to find the correct HTTP status code for a page where the content is temporary unavailable however there is no redirect, instead a message is displayed on the page informing the user the content is temporarily unavailable.
307 Temporary Redirect isn't applicable as there is no redirect.
404 Not Found might possibly be applicable, however I'm not sure if this is the correct response to give as the content is found, just not available.
410 Gone isn't applicable as the content will be available again some time in the future.
None of the other codes seemed even remotely applicable. Does anyone know the correct code to use and can explain why?

A: It sounds like the 4XX series of responses are appropriate here. From the RFC:

The 4xx class of status code is intended for cases in which the
client seems to have erred. Except when responding to a HEAD request,
the server SHOULD include an entity containing an explanation of the
error situation, and whether it is a temporary or permanent
condition.

With this in mind, I think 403 forbidden is the most appropriate:

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it.
Authorization will not help and the request SHOULD NOT be repeated.
If the request method was not HEAD and the server wishes to make
public why the request has not been fulfilled, it SHOULD describe the
reason for the refusal in the entity.  If the server does not wish to
make this information available to the client, the status code 404
(Not Found) can be used instead.

I suggest this for three reasons:

*It's not an exotic code, so it will work fine in the browser. This, to me, is the most important reason - you will be able to serve a page that explains why the content isn't available, and you can be fairly certain it will be displayed correctly.

*It's appropriate for the server to say "I understand your request, but I won't serve you that content at this time", and that's exactly what the first two lines of the description say.

*It doesn't explicity say "forget you ever knew about this content" to any robots (or for that matter, people).

For completeness, here's why I ruled out the other response code categories:

2XX Success: This class of status code indicates that the client's request was
successfully received, understood, and accepted.

*

*But, we're not accepting the request in this case. I don't think 2XX is right.

3XX  Redirection: This class of status code indicates that further action needs to be
taken by the user agent in order to fulfill the request.

*

*I suppose that you could argue "further action" to mean "please wait until the content is available before trying again", but reading the other 3XX codes, "further action" usually means "immediate redirect", which as you've already pointed out, isn't appropriate.

5XX Server error: Response status codes beginning with the digit "5" indicate cases in
which the server is aware that it has erred or is incapable of
performing the request.

*

*Nothing has gone wrong on the server, you just don't want to serve the content right now.

A: HTTP STATUS CODE 204
i.e. NO CONTENT
Read More about it here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
section 10.2.5
i.e.
The server successfully processed the request, but is not returning any content.


text:
Q: The final topology is finer than the initial If $T$ is a set of topologies on a (non-empty) set $X$, then the initial topology on $X$ can be defined as $\bigcup T$ while the final topology is $\bigcap T$. We see clearly that $\bigcap T \subset \bigcup T$ and thus the final topology is strictly coarser than the initial topology.
However, consider the next situation: let $X$ and $Y$ be two topological spaces with distinguished points $x_0\in X$ and $y_0\in Y$, as well as the following four maps: the ''inclusions''
$$
\begin{array}{rcl}
\iota_1: X & \longrightarrow & X\times Y\\
 x & \longmapsto & (x,y_0) \\
\end{array}
$$
and
$$
\begin{array}{rcl}
\iota_2: X & \longrightarrow & X\times Y\\
 y & \longmapsto & (x_0,y) \\
\end{array}
$$
and the projections
$$
\begin{array}{rcl}
\pi_1: X\times Y & \longrightarrow & X \\
 (x,y) & \longmapsto & x \\
\end{array}
$$
and
$$
\begin{array}{rcl}
\pi_2: X\times Y & \longrightarrow &  Y\\
 (x,y) & \longmapsto & y . \\
\end{array}
$$
We can define two topologies on $X\times Y$: the initial topology with respect to the maps $(\pi_1,\pi_2)$, with is the usual product topology and the final topology with respect to the maps $(\iota_1,\iota_2)$.
For the first, if $\mathscr B_1$ and $\mathscr B_2$ are basis of the topology of $X$ and $Y$ resp. then
$$
\mathscr B = \left\{\bigcap_{i=1}^n \pi^{-1}(U_i) : \mbox{each } U_i \mbox{ belongs to }  \mathscr B_1 \mbox{ or } \mathscr B_2 \mbox{ and } n\in\mathbb N \right\}
$$
is a base for such a topology.
For the second one, a bse could be
$$
\mathscr B' = \{ U\subseteq X\times Y : \iota_1^{-1}(U)\in\mathscr B_1 \mbox{ AND } \iota_2^{-1}(U)\in\mathscr B_2 \}
$$
(we need the ''AND'').
What is surprising for me? That the final topology is finer than the initial. For show that let me consider an easy example: pick $X=Y=\mathbb R$ and $x_0=y_0=0$. Then, a closed set in the usual topology
such as for example the square $S=[a,b]\times[a,b]$, with $0<a<b$, is open in $\mathbb R^2$ equipped with the initial topology, since $\iota_1^{-1}(S)=\iota_2^{-1}(S)=\emptyset$ which is open.

What I would like to do now? I want to show that every open set in $\mathbb R^2$ with the product topology is also open in $\mathbb R^2$ endowed with the final topology.

And I would like to do it in a smart (elegant, refined, any word sounds me good) way. For that I should consider an open set $U\subseteq\mathbb R^2$ which will be an arbitrary union of sets of the form $(a,b)\times(c,d)$ ($a<b$ and $c<d$ and may be $\infty$). And I'm not sure how to proceed here. I think my problem is that I'm not sure how to express an arbitrary open set as the union of sets belonging to $\mathscr B$.
Thanks a lot.

A: The condition on the second map is equivalent to a subset of $U$ being open if $U$ restricted to $(x_0, \mathbb{R})$ is open in $\mathbb{R}$, and the subset of $U$ restricted to $(\mathbb{R}, y_0)$ is open in $\mathbb{R}$.
In $\mathbb{R}^2$, a set is open iff it's sequentially open. So if a subset were not open in the restriction to subspaces above, then it would fail to be open in $\mathbb{R}^2$, since a sequence exhibiting non-openness would continue to exist.

A: The product topology $\mathcal{T}_p$ on $X \times Y$ is the minimal topology that makes $\pi_1$ an $\pi_2$ continuous. From this fact it follows that a function $F : Z \to X \to Y$, from any space $Z$ is continuous (in the product topology on $X \times Y$) iff $F \circ \pi_1$ and $F \circ \pi_2$ are continuous.
Now $\iota_1 \circ \pi_1 = \textrm{id}_X$ and $\iota_1 \circ \pi_2 = c_{y_0}$, where the right hand sides are the identity map and a constant map, which  are both continuous, so $\iota_1$ is continuous as a map into $(X \times Y, \mathcal{T}_p)$ and similar considerations show the same for $\iota_2$.
Now the final topology $\mathcal{T}_f$ you are considering is by definition the maximal topology on $X \times Y$ that makes $\iota_1$ and $\iota_2$ continuous, and $\mathcal{T}_p$ is just some topology that does that so by maximality: $\mathcal{T}_p \subseteq \mathcal{T}_f$