text:
Q: Running User Sql Commands On Dynamic Databases I am trying to do something with dynamic databases. My requirement is as follows:
-- Need to generate and dynamic databases on the fly.
=> These databases are for users to do whatever they want. However, every database is created with restricted permissions and users cannot go beyond their own database.
-- Need to execute any random user query (or a set of user queries) on that database
=> Given that the users can write any query, I do not know whether the query is going to be a "select" query or a "non-select" query. affected". This is equivalent to "running a mysql script file"
Now, I have written a DatabaseManager class, which does "1" for me, but I am still facing issues in implementing "2". The key problem lies in the following things:

*

*I do not know the query executed by the user.

*I need to handle the query and revert back with appropriate result to the user (this is very important), i.e.
-- for a select query, it should return the data requested by the user
-- for a non-select query, it should return "no. of rows affected"
-- for a composite query (which contains both select and non-select queries), it can return the "no. of rows affected"

*The user can change the delimiters and write complex stuff such as procedures etc., so I cannot do command level split using semicolon ";" and execute them one by one.
What I tried with Yii is following:

*

*I created a transaction for every query (or bunch of queries that I get).

*Not knowing what the query is, I always execute the "queryAll" on that. If it is a "select based query", then I hope to get the correct result from it. If it succeeds, then I commit the transaction

*If it is a "non-select" query, I will get an exception here, and I will roll back the transaction. In this case, I will next create a new transaction and then call the "execute" command. Given that this is a non-sql or composite query, I expect the command to run. It should only throw an exception in case of a syntax error or in case of some constraint violation

*In case "execute" also throws an exception, I roll back this transaction as well, and show the result to the user.
I was expecting my approach 2 to work in this case. However, I see that the transactions are not working properly in case of "create table command". Here, the "queryAll" command gives and exception, but still goes ahead and creates the user table. Now, when I try to run the same command again with "execute", it again gives the exception, because the table already exists. I am surprised that the transaction rollback did not make any difference.
Now, my above approach may be grossly incorrect, and I'll be happy to hear some feedback on what is the right way to approach this problem. For now, here are some key questions that I have:

*

*Is it possible to execute a bunch of random sql queries in Yii? More importantly, is it possible to break the queries into individual queries? (I know this is tough problem and a big topic of discussion in stackoverflow itself, but asking the same question none the less)

*Why is transaction rollback not working?

*What are the holes in my approach and how can anyone screw up this system?
My apologies for such a long post. However, it was a little difficult to explain the problem in brief. I am attaching the source code for my DatabaseManager class with this post for a detailed reference.
<?php
class DatabaseManager
{
public $db_name;
public $username;
public $password;
const HOST = "localhost";
const ROOT = "dummy_root";
const ROOT_PASSWORD = "dummy_root_password";
const DB_PASSWORD_SALT = 'dummy_password_salt';

public function getDbComponent($db_name) {
    //if the component already exists then create it
    if(Yii::app()->hasComponent($db_name)) {
        $component = Yii::app()->getComponent($db_name);
        return $component;
    }

    //if the db component doesn't exist, then create it and return the
    //new component
    try {
        $this->db_name = $db_name;
        $this->username = "dummy_user";
        $this->password = "dummy_password";

        $component = $this->createDbComponent();
        Yii::app()->setComponent($db_name, $component);
    } catch (PDOException $e) {
        die("DB ERROR: ". $e->getMessage());
    }
    return $component;
}

private function createDbComponent() {
    $pdo = new PDO("mysql:host=".self::HOST, self::ROOT, self::ROOT_PASSWORD, array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,));

    $pdo->exec("CREATE DATABASE IF NOT EXISTS `$this->db_name`;
                GRANT ALL PRIVILEGES ON ".$this->db_name.".* TO '".$this->username."'@'localhost' IDENTIFIED BY '".$this->password."';
                FLUSH PRIVILEGES;")
        or die(print_r($pdo->errorInfo(), true));

    $component = Yii::createComponent(array(
                'class'=>'CDbConnection',
                'connectionString'=>'mysql:host=localhost;dbname='.$this->db_name,
                'emulatePrepare' => true,
                'password'=> $this->password,
                'username'=> $this->username,
                'charset' => 'utf8',
                'enableParamLogging' => true,
                )
            );
    return $component;
}

private function formatErrorMessage($msg) {
    $check_for_prefix = "CDbCommand failed to execute the SQL statement:";
    $result = str_replace($check_for_prefix, "", $msg);
    return $result;
}

private function executeSelectQuery($query, $db_name) {
    //Get the db component on which the query should be executed
    $db = $this->getDbComponent($db_name);
    $command = $db->createCommand($query);

    $transaction = $db->beginTransaction();
    try {
        $command = $db->createCommand($query);
        $output = $command->queryAll();
        $output = $command->queryAll();
        $transaction->commit();
    } catch (exception $e) {
        $transaction->rollback();
        //throw back this exception
        //as it should be handled by the higher level code
        throw new Exception($e->getMessage());
    }
    return $output;
}

private function executeNonSelectQuery($query, $db_name) {
    //Get the db component on which the query should be executed
    $db = $this->getDbComponent($db_name);
    $transaction = $db->beginTransaction();
    try {
        $command = $db->createCommand($query);
        $command->prepare();
        $output = $command->execute();
        $transaction->commit();
    } catch (exception $e) {
        $transaction->rollback();
        //throw back this exception
        //as it should be handled by the higher level code
        throw new Exception($e->getMessage());
    }
    return $output;
}

public function runQuery($code, $db_name) {
    try {
        //we can have two kind of queries -- select or non-select
        //since we don't know the type of query, we should by default try to make a select query
        //if this gives an exception, then there is a possibility that this is a non-select query
        //so now we try doing an "execute" on this
        //if that goes fine, it means that the query was a non-sql query
        //else we show the exception to user
        $db = $this->getDbComponent($db_name);
        try {
            $output = $this->executeSelectQuery($code, $db_name);
            $result['status'] = "success";
            $result['output'] = $output;
        } catch (exception $e) {
            try {
                $output = $this->executeNonSelectQuery($code, $db_name);
                $result['status'] = "success";
                $result['output'] = "Query OK, ".$output." row(s) affected";
            } catch (exception $e) {
                $error = $this->formatErrorMessage($e->getMessage());
                $result['status'] = "failure";
                $result['error'] = $error;
            }
        }
    } catch (exception $e) {
        $result = $e->getMessage();
    }

    return $result;
}

//resets the db
public function resetDbComponent($db_name) {
    //in case of reset simply delete the database
    $result = $this->deleteDbComponent($db_name);
    if(!$this->getDbComponent($db_name)) {
        throw new Exception("Could not create database -- ".$db_name);
    } else {
        $result['status'] = "success";
        $result['output'] = "Database reset to inital state";
    }
}

public function deleteDbComponent($db_name) {
    $pdo = new PDO("mysql:host=".self::HOST, self::ROOT, self::ROOT_PASSWORD);
    try {
        $pdo->exec("DROP DATABASE IF EXISTS `$db_name`;");
        Yii::app()->setComponent($db_name, null);
        $result['status'] = 'failure';
        $result['output'] = "Database ".$db_name." deleted";
    } catch (exception $e) {
        $result['status'] = 'failure';
        $result['output'] = "Database ".$db_name." could not be deleted";
    }
}
}

Regards,
Kapil

A: I understood from your question you need to build API to your database :
1- users can access it
2- can do some basic and complex sql queries
So you need Restful Api
This article will help you  , and you can search more about it on google
http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html

A: There are a couple questions here, so let me just summarize what I think you are asking:

*

*Why do create table transactions not roll back?

*Which active record function is correct to process either select or non-select queries?

*How do I deal with multi-statement queries?

So here are my answers:

*

*MySQL does not protect DDL sttatements with transactions.  Those are the create, alter, grant, etc. statements.  PostgreSQL does, so either you switch to PostgreSQL, or you don't try to protect your DDL with transactions.  Given that you don't know, without parsing the user's SQL, it may be that switching to PostgreSQL is you best choice here, but reserve that until you read further answers.

*It is my opinion that Active Record is not meant for doing what you are asking, and trying to pound your square peg into the round ActiveRecord hole may be very difficult. Instead I would use Yii and ActiveRecord to manage your list of users and databases, but use plain old PHP to manage the user's nteraction with those databases.  That would mean that you have two connections, one to your admin database that contains user and database information, and another to the user's database.  You could just use the mysql functions to connect, query, and disconnect from the user database.

*I suggest that it is inherantly insecure to allow multiple statements to be executed in a single query.  It may even be that the mysql functions will not allow it.  In any case you should not allow it because that gives hackers the ability to perform some of the more insidius SQL injection attacks like changing the statement by sticking a ; delete from table into a field that is used to build an sql statement.  Except for defining procedures you should not allow this.  That means you need to build at least a rudimentary parser.  At least enough to know what statement you are executing.  Given that, you could even dynamically know whether transaction support is available, and commit or rollback based on that.
Hope this helps.


text:
Q: grep search on subdirectories I'm trying to search for a text in a directory among all files. Its expected to access the subfolders too. There are folder & files with whitespace characters in their name. I'm using the following command to search.
find . -type f | xargs grep -rls 'my text'

This doesn't access the folder and files with white space characters. Any suggestion on what to change on the command?

A: That should handle files with whitespace just fine I think (though not newlines) but you can use find -print0 and xargs -0 to be safer.
That being said your current use of the -r argument to grep is pointless since it will only ever be given directories to operate on. And additionally your use of find here is pointless since grep -r does what you want here directly.
Just use grep -rls 'my text' ..

A: Any version of grep that I personally layed hands on supports the -r switch, recursive.
Just hand it the top directory and grep will do its thing:
grep -r myregex /home/marcus/bunchoffilesindirectories

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to select a text block when soft keyboard shows up I am displaying an alert box with edit text for user to change the name of a file.
However, I want to auto select the name of the file expect for the suffix (for example: ".jpg").
I use EditText.setSelection(0, name.length()-4) and the name block is selected as I wished.
But, when I click on the edit text to bring on the soft keyboard, the selection is gone.
How to keep the selection from disappearing? Or, how can I automatically set the selection when the soft keyboard is displayed?
Following is my code of showing the alert dialog:
private void updateItemFileName(final long ID, final String oldName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Enter new name");
        final EditText input = new EditText(this);
        input.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        input.setText(oldName);
        /* Select the "name" block except for the suffix*/
        input.setSelection(0, oldName.length() - 4);
        builder.setView(input);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //TODO: change the name and refresh list view
            }
        });
        builder.setNegativeButton("Cancel", null);
        builder.create().show();
}

A: Are you setting focus and specifically instructing Android to provide the keyboard? Try this on for size:
if(myEditText.requestFocus()) {
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}

This should give the focus to the EditText and open up the keyboard while your selection is still selected. From your question, I'm interpreting that while the filename is selected, the EditText is not focused and touching the EditText then unselects the filename.


text:
Q: How to exclude results not associated to a specific value WorkQueueItem contains unique requests, some have failed with an exception and others did not fail.
The Tag table returns all tags related to a request. A request can have multiple tags or none.
I'm trying to get all the count of failed requests grouped by type of exception that do not have the "Forwarded" tag.
I did get 'Duplicate Request' and 'Dummy Request' which don't have the "Forwarded" tag but 'Could no Complete' does have the 'Forwarded' tag but it also has this 'Deferred' tag as well which is returned.
I do not want to get 'Could not Complete' at all since it is associated to 'Forwarded' somewhere.
How could I get requests that don't have a Forwarded tag associated to them ?
Wanted result:
WorkQueueItem contains unique requests, some have failed with an exception and others did not fail.
The Tag table returns all tags related to a request. A request can have multiple tags or none.
I'm trying to get all the count of failed requests grouped by type of exception that do not have the "Forwarded" tag. I did get 'Duplicate Request' and 'Dummy Request' which don't have the "Forwarded" tag but 'Could no Complete' does have the 'Forwarded' tag but it also has this 'Deferred' tag as well which is returned.
I do not want to get 'Could not Complete' at all since it is associated to 'Forwarded' somewhere.
How could I get requests that don't have a Forwarded tag associated to them ?
Wanted result: (I previously added the tag column just to help understanding what is going on, I don't want it)
+---+--------------------+-------+
|   | Exception          | Count |
+---+--------------------+-------+
| 1 | Duplicate Request  | 1     |
+---+--------------------+-------+
| 2 | Dummy Request      | 1     |
+---+--------------------+-------+

Current result:
+---+--------------------+-------+----------+
|   | Exception          | Count | tag      |
+---+--------------------+-------+----------+
| 1 | Duplicate Request  | 1     | NULL     |
+---+--------------------+-------+----------+
| 2 | Dummy Request      | 1     | Deferred |
+---+--------------------+-------+----------+
| 3 | Could not Complete | 1     | Deferred |
+---+--------------------+-------+----------+

Current Query:
SELECT  exceptionreason as Exception,
        COUNT(exceptionreason) as Count,
        tag

FROM [myDB].[dbo].[WorkQueueItem]
JOIN myDB.dbo.WorkQueue
ON WorkQueue.ident = WorkQueueItem.queueident
LEFT JOIN myDB.dbo.WorkQueueItemTag
ON WorkQueueItem.ident = WorkQueueItemTag.queueitemident
LEFT JOIN myDB.dbo.Tag
ON WorkQueueItemTag.tagid = Tag.id

WHERE name='TestQueue'
AND exception is not null
AND (NOT Tag.tag LIKE '%Forwarded%' OR Tag.tag is null)
Group by exceptionreason, tag

I hope there is enough info here.
Any help is appreciated, thanks.
EDIT:
Adding Datasets
WorkQueueItem
+---+--------+------------+--------------------+------------+
|   | ident  | exception  | exceptionreason    | completed  |
+---+--------+------------+--------------------+------------+
| 1 | 192947 | 2017-05-25 | Dummy Request      | NULL       |
+---+--------+------------+--------------------+------------+
| 2 | 194990 | NULL       | NULL               | 2017-05-25 |
+---+--------+------------+--------------------+------------+
| 3 | 194994 | 2017-05-25 | Duplicate Request  | NULL       |
+---+--------+------------+--------------------+------------+
| 4 | 194995 | 2017-05-25 | Could not Complete | NULL       |
+---+--------+------------+--------------------+------------+

WorkQueueItemTag
+---+----------------+-------+
|   | queueitemident | tagid |
+---+----------------+-------+
| 1 | 192947         | 14904 |
+---+----------------+-------+
| 2 | 194995         | 14905 |
+---+----------------+-------+
| 3 | 194995         | 14906 |
+---+----------------+-------+

TAG
+---+-------+-----------+
|   | id    | tag       |
+---+-------+-----------+
| 1 | 14904 | Deferred  |
+---+-------+-----------+
| 2 | 14905 | Forwarded |
+---+-------+-----------+
| 3 | 14906 | Deferred  |
+---+-------+-----------+

A: This could be close to what you want.
SELECT
    WQI.exceptionreason,
    COUNT(*) [Total]
FROM
    myDB.dbo.WorkQueueItem WQI
WHERE
    WQI.exception IS NOT NULL
    AND EXISTS(SELECT 1 FROM myDB.dbo.WorkQueue WHERE ident = WQI.queueident AND name = 'TestQueue')
    AND NOT EXISTS(
        SELECT
            1
        FROM
            myDB.dbo.WorkQueueItemTag WQIT
        WHERE
            WQIT.queueitemident = WQI.ident
            AND EXISTS(SELECT 1 FROM myDB.dbo.Tag WHERE id = WQIT.tagid AND tag LIKE '%Forwarded%')
    )
GROUP BY
    WQI.exceptionreason;

A: One easy way is with a correlated sub-query and NOT IN
declare @WorkQueueItem table (ident int, exception datetime, exceptionreasion varchar(128), completed datetime)
insert into @WorkQueueItem
values
(192947,'2017-05-25','Dummy Request',NULL),
(194990,NULL,NULL,'2017-05-25'),
(194994,'2017-05-25','Duplicate Request',NULL),
(194995,'2017-05-25','Could not Complete',NULL)

declare @WorkQueueItemTag table (queueitemindent int, tagid int)
insert into @WorkQueueItemTag
values
(192947,14904),
(194995,14905),
(194995,14906)

declare @TAG table (id int, tag varchar(64))
insert into @TAG
values
(14904,'Deferred'),
(14905,'Forwarded'),
(14906,'Deferred')

select
    i.exceptionreasion
    ,count(*)
from @WorkQueueItem i
where i.ident not in (select i.ident
                    from @WorkQueueItem i
                    left join @WorkQueueItemTag it on it.queueitemindent = i.ident
                    left join @TAG t on t.id = it.tagid
                    where t.tag = 'Forwarded' )
and i.exceptionreasion is not null
group by
    i.exceptionreasion

A: Looks like you are looking for conditional aggregation as below:
 SELECT  exceptionreason as Exception,
        SUM(case when Tag.tag LIKE '%Forwarded%' or Tag.tag is null then 0 else 1 end) as Count,
        tag

FROM [myDB].[dbo].[WorkQueueItem]
JOIN myDB.dbo.WorkQueue
ON WorkQueue.ident = WorkQueueItem.queueident
LEFT JOIN myDB.dbo.WorkQueueItemTag
ON WorkQueueItem.ident = WorkQueueItemTag.queueitemident
LEFT JOIN myDB.dbo.Tag
ON WorkQueueItemTag.tagid = Tag.id

WHERE name='TestQueue'
AND exception is not null
----AND (NOT Tag.tag LIKE '%Forwarded%' OR Tag.tag is null)
Group by exceptionreason, tag


text:
Q: bencode и его особенности Прочитал протокол от корки до корки несколько раз но так и не смог понять , почему некоторые спецификаторов формата дублируются,например 'll' вместо 'l', в спецификации ни слова про дублирования. Может кто то даст ссылку или вкратце обьяснит с чем связанно. Так же иногда дублируется символ конца 'e' и выглядит так 'ee'

A: Давайте посмотрим, как должно в таком кодировании выглядеть число 10. Это будет i10e.
Как кодируется массив? l<содержимое>e.
А как же будет выглядеть массив на 2 элемента 1 и 2? (то есть, массив [1,2])? Это будет так  l i1e i2e e (пробелы добавлены для читаемости). Вот и получается в конце две буквы e. Но одна - это конец записи числа, а вторая - конец списка.
А теперь сложнее. А как будет выглядеть список(массив), внутри которого находится вышеуказанный массив? l l i1e i2e e e (пробелы снова для читаемости). Да у нас тут две l и три(!!!) e
Еще раз, если это не очевидно, в виде дерева (# - это начало комментария)
l       # [
  l     #   [
    i1e #     1,
    i2e #     2
  e     #   ]
e       # ]


text:
Q: npm installs two versions of a module with different patch versions whilst I'm using caret My projects package.json
dependencies: {
    A: "^0.0.2",
    B: "^0.0.1"
}

module B package.json
dependencies: {
    A: "^0.0.1",
}

When I run nmp install for my project it installs module A twice. Once in the top level (version 0.0.2) and one time nested in module B (version 0.0.1):
project/node_modules/A                   <--0.0.2
project/node_modules/B/node_modules/A    <--0.0.1

But I'm using ^ in both package.json files. So why, even when I reinstall module B does it not use the top level installation of module A instead of getting a nested version of module A?
After all, A@^0.0.1 should match A@0.0.2 right?

A: This is as per design. See this answer
npm install with ^ dependency instead of exact match

That happens because ^0.0.1 is considered to be equivalent to 0.0.1.
When the version of a package starts with 0 it's considered to be in development, and the semantic versioning rules are different. An increase in either of the numbers can be expected to have breaking changes when the version is 0.0.X. You can see the rules here.
Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4
Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple. In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for versions 0.X >=0.1.0, and no updates for versions 0.0.X.
You'll probably see the caret when you increment the minor version, but it will also have the special rules that are mentioned over. "Normal" rules start applying when you increment the major version.

You can also look at the below page with more details
https://docs.npmjs.com/misc/semver#caret-ranges-123-025-004
It clearly shows ^0.0.3 := >=0.0.3 <0.0.4, which means ^0.0.X is same as 0.0.X


text:
Q: Class D Amp headphones grounding circuit I am having a problem with some of the class d amps I've played with (PAM8302A), and it seems like this article here describes my problem:
https://www.edn.com/design/analog/4313726/Add-headphones-to-a-Class-D-amplifier
essentially the audio circuit turns off because of the headphone plug sharing a common ground or something. I am making a pi zero pwm to analog amplifier circuit and some suggestions would be appreciated.
Edit: How is this? 220uF cap highlighted

A: Insert a 470uF capacitor into the VO_P output with the capacitor + lead going to the IC. Now you are no longer shorting out the DC bias voltage at the output pins. Use small cell-phone type headphones or earbuds to get enough volume. You need 2 of these ICs for stereo sound. This IC cannot drive studio grade headphones, at least not to any useful volume.


text:
Q: What's the difference between LAY and LIE? This has been confusing for me.
Some say:

"I'm laying on/in my bed."

Others say:

"I'm lying on/in my bed."

Which is correct?
Do the sentences have any difference?
I'm not sure which preposition to use either.
Can ON and IN be used with these verbs?


text:
Q: Problem reading SAS data file into Spark Dataframe and loading to S3 I'm having real fun with a local installation of Spark on a Windows 10 machine. I'm trying to read a SAS data file into a Spark dataframe from where I want to write it to a parquet file on an S3 bucket.
The code from my Jupyter Notebook is below.
The error that I get is below the code. It's related to the saurfang package.
The code worked until I added in the SparkContext() stuff (bookended with '<here---' and '>here----' in the code) which I believe I need in order to work with S3 on my local machine (lots of resolved problems got me to this point). This was when I added in the 'df.write.mode...' line too.
I have assumed that create_spark_session() will use the context details built prior to its definition. I'm wondering if some part of the SparkContext() configurations are preventing this line from working correctly:
.config("spark.jars.packages", "saurfang:spark-sas7bdat:2.0.0-s_2.11") \
I am new to Spark and any help will be appreciated.
import configparser # to work with the configuration file
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format
from pyspark.sql.types import (StructType, StructField, StringType, DoubleType, IntegerType, TimestampType,FloatType)
import pandas as pd
import findspark
import pyspark

config = configparser.ConfigParser()
config.read('dl.cfg') # edit this file to include your own values.

os.environ['AWS_ACCESS_KEY_ID']=config['AWS']['AWS_ACCESS_KEY_ID']
os.environ['AWS_SECRET_ACCESS_KEY']=config['AWS']['AWS_SECRET_ACCESS_KEY']
os.environ['AWS_DEFAULT_REGION']=config['AWS']['AWS_DEFAULT_REGION']

SAS_DATA_LOCATION=config['OTHER']['SAS_DATA_LOCATION']

BUCKET_NAME = config.get("OTHER","BUCKET_NAME")

#<HERE-------------
# see: https://gist.github.com/asmaier/5768c7cda3620901440a62248614bbd0
sc=pyspark.SparkContext()

# see https://github.com/databricks/spark-redshift/issues/298#issuecomment-271834485
sc.setSystemProperty("com.amazonaws.services.s3.enableV4", "true")

# see https://stackoverflow.com/questions/28844631/how-to-set-hadoop-configuration-values-from-pyspark
hadoop_conf=sc._jsc.hadoopConfiguration()

# see https://stackoverflow.com/questions/43454117/how-do-you-use-s3a-with-spark-2-1-0-on-aws-us-east-2
hadoop_conf.set("fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
hadoop_conf.set("com.amazonaws.services.s3.enableV4", "true")
hadoop_conf.set("fs.s3a.access.key", os.environ['AWS_ACCESS_KEY_ID'])
hadoop_conf.set("fs.s3a.secret.key", os.environ['AWS_SECRET_ACCESS_KEY'])

# see http://blog.encomiabile.it/2015/10/29/apache-spark-amazon-s3-and-apache-mesos/
hadoop_conf.set("fs.s3a.connection.maximum", "100000")

# see https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region
hadoop_conf.set("fs.s3a.endpoint", "s3." + os.environ['AWS_DEFAULT_REGION'] + ".amazonaws.com")

#>HERE-----------

def create_spark_session():
    """Create a spark session in which to work on the data."""
    spark = SparkSession \
        .builder \
        .config("spark.jars.packages", "saurfang:spark-sas7bdat:2.0.0-s_2.11") \
        .config("spark.driver.extraClassPath", "C:/Progra~1/Java/jdk1.8.0_251/postgresql-42.2.14.jar")\
        .getOrCreate()
    return spark

def spark_to_s3(read_format,fpath,tname,delimiter=','):
    """
    Create a Spark dataframe from an input file.

    Args:

    read_format: E.g. csv.
    fpath: Full path for your input file, e.g. 'c:\your_file.csv'.
    tname: The name of the file to write
    delimiter: E.g. ','
    """
    spark = create_spark_session()
    df =spark.read.format(read_format) \
                  .option("header","true") \
                  .option("delimiter",delimiter) \
                  .load(fpath)
    print(df.printSchema())
    df.write.mode("overwrite").parquet('s3a://' + BUCKET_NAME + f'/parquet/{tname}.parquet')

# build a dictionary of arguments for the four input files
parameters_dict = {'immigration': {'read_format':'com.github.saurfang.sas.spark',\
                                   'fpath':SAS_DATA_LOCATION + 'i94_apr16_sub.sas7bdat','delimiter':','}
      }

# iterate through the dictionary, writing each dataframe to a parquet file
for k in parameters_dict.keys():
    spark_to_s3(parameters_dict[k]['read_format'],parameters_dict[k]['fpath'],k,parameters_dict[k]['delimiter'])

This is the error:
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-4-9aaee5b3167c> in <module>
      9 # iterate through the dictionary, writing each dataframe to a parquet file
     10 for k in parameters_dict.keys():
---> 11     spark_to_s3(parameters_dict[k]['read_format'],parameters_dict[k]['fpath'],k,parameters_dict[k]['delimiter'])

<ipython-input-3-04778a385a6a> in spark_to_s3(read_format, fpath, tname, delimiter)
     14                   .option("header","true") \
     15                   .option("delimiter",delimiter) \
---> 16                   .load(fpath)
     17     print(df.printSchema())
     18     df.write.mode("overwrite").parquet('s3a://' + BUCKET_NAME + f'/parquet/{tname}.parquet')

~\Anaconda3\lib\site-packages\pyspark\sql\readwriter.py in load(self, path, format, schema, **options)
    164         self.options(**options)
    165         if isinstance(path, basestring):
--> 166             return self._df(self._jreader.load(path))
    167         elif path is not None:
    168             if type(path) != list:

~\Anaconda3\lib\site-packages\py4j\java_gateway.py in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

~\Anaconda3\lib\site-packages\pyspark\sql\utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

~\Anaconda3\lib\site-packages\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o37.load.
: java.lang.ClassNotFoundException: Failed to find data source: com.github.saurfang.sas.spark. Please find packages at http://spark.apache.org/third-party-projects.html
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:657)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:194)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:178)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: com.github.saurfang.sas.spark.DefaultSource
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$20$$anonfun$apply$12.apply(DataSource.scala:634)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$20$$anonfun$apply$12.apply(DataSource.scala:634)
    at scala.util.Try$.apply(Try.scala:192)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$20.apply(DataSource.scala:634)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$20.apply(DataSource.scala:634)
    at scala.util.Try.orElse(Try.scala:84)
    at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:634)
    ... 13 more

A: Download:spark-sas7bdat-2.1.0-s_2.11.jar and keep it in HDFS temp location.Please find below code to help read SAS file from s3 to pyspark data frame.
from pyspark.sql import *
import pyspark
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
import os
import boto3
import json
from datetime import date
import time
import sys
from pyspark.sql.functions import col,lit
from pyspark.sql.functions import *
from pyspark.sql.types import *
import pyspark.sql.functions as F

list ={
    'spark.yarn.queue': 'default',
    'spark.jars.packages': 'saurfang:spark-sas7bdat:2.1.0-s_2.11',
    'spark.jars':'hdfs:///tmp/spark-sas7bdat-2.1.0-s_2.11.jar',
    'spark.driver,memory': '2g',
    'spark.executor.memory': '2g',
    'spark.dynamicAllocation.maxExecutors': '10'}
spark = SparkSession.builder.master("local").appName("app_name").enableHiveSupport()
for k,v in list.items():
    spark = spark.config(k, v)

spark = spark.getOrCreate()
print(spark.version)

aws_access_key="src_accesskey"
aws_secret_access_key="src_secretkey"
endpoint="s3 endpoint"
bucket="bucketname"

spark._jsc.hadoopConfiguration().set('fs.s3a.impl', 'org.apache.hadoop.fs.s3a.S3AFileSystem')
spark._jsc.hadoopConfiguration().set('fs.s3a.access.key', aws_access_key)
spark._jsc.hadoopConfiguration().set('fs.s3a.secret.key', aws_secret_access_key)
spark._jsc.hadoopConfiguration().set('fs.s3a.endpoint', endpoint)
spark._jsc.hadoopConfiguration().set('fs.s3a.connection.ssl.enable', 'false')
spark._jsc.hadoopConfiguration().set('fs.s3a.path.style.access', 'true')

inputdf=spark.read.format("com.github.saurfang.sas.spark")
             .load("s3a://<bucketname>/<path>.sas7bdat")
inputdf.printSchema()
inputdf.show()


text:
Q: Classifying components by similar tag values Background
I'm trying to analyse source code to look for ways of improving modularity. To that end I have constructed a directed graph of identifiers (functions, types etc) with edges indicating a reference relationship. So if function foo calls bar then there will be a corresponding edge in the graph from foo to bar.
I've identified the strongly connected components (i.e. mutually recursive functions and types) in this graph, which yields a DAG of components.
I want to try to cluster these components according to the modules that use them. For instance if function foo is called from code in Module_A and Module_B then its module user list will be those two modules. (Note that this is distinct from any import lists: I'm tracking actual use, not importation).
My theory is that in a well-designed module all the components will have similar lists of user modules. But in a badly designed module the user module lists will be very different.
I'm hoping that it will be possible to cluster components according to user lists, so that components with similar lists can then be refactored into modules with higher cohesion.
The Question
Given a set of components, each with a set of associated discrete tag values (user modules in this case), is there a good algorithm for identifying clusters of components that share similar sets of tags?
I've googled clustering algorithms, but all the ones I have seen seem to be about clustering by ordinal or real values (e.g. k-means).


text:
Q: Agenda (nodejs) schedule I've been playing with https://github.com/rschmukler/agenda, which is nice way to queue / schedule things in node app, but I have a question.
What is the right syntax to schedule beerRun to run at exact time of exact day? The way written below does not really do the trick.
agenda.schedule('2017-01-07 7:27', 'beerRun', []);

In the agenda's documentation they have 'tomorrow at 7:30pm', which is good, but I need something else (exact day / time).


text:
Q: BackUp Dockerized PostreSQL Database I have a docker-compose based Postgresql container, together with Pgadmin
I want to make a backup for my database to prevent data loss.
So I thought to create the backup from the Pgadmin interface, but this would create a backup file inside the container itself.
What I tried to figure out is,
how I can create a backup in case of running by mistake docker-compose down? which will erase all the volumes that are attached to the docker-compose file.
Thanks

A: First, for production use, you don't use docker-compose but docker swarm or kubernetes. docker-compose is made for testing and you should not manage your production or even a equivalent test system that must have SLA (like no data loss) using docker-compose.
Then docker-compose down do not remove the volumes, to do that, you would need to add the "-v" option like:
docker-compose down -v

Third if you want to use a persistant volume not managed by the docker-compose but that is long lived, declare it as external, as per the documentation (https://docs.docker.com/compose/reference/down/):

Stops containers and removes containers, networks, volumes, and images
created by up.
By default, the only things removed are:
Containers for services defined in the Compose file Networks defined
in the networks section of the Compose file
The default network, if one is used
Networks and volumes defined as external are never removed.

This way you decouple you volume lifecycle from your containers. The documentation on volumes also explains how you can use volume drivers to get access to distant file systems and backup volumes if necessary: https://docs.docker.com/storage/volumes/
So if you want backup, do that by a shell command to a specific folder mapped to a volume that is potentially behind the scene a distant file system and is itself considered safe (backuped & replicated).

A: You can mount a folder inside the container to a host folder and use pgadmin to create a backup that will be persisted outside the container (docker-compose down has no effect on it):
services:
  db:
    volumes:
      - /folder/in/host:/folder/in/container

For example: If you create a backupfile say in /folder/in/container/pg.dump, it will also be available on the host as /folder/in/host/pg.dump

Or you can create a volume with docker volume create --name somename that will be stored in /var/lib/docker/volumes that even docker-compose down -v will not remove:
services:
  db:
    volumes:
      - somename:/folder/in/container

volumes:
  somename:
    external: true

More about volumes:

*

*https://docs.docker.com/engine/reference/commandline/volume_create/

*https://docs.docker.com/compose/compose-file/#volumes


text:
Q: Return single SELECT row in BEFORE UPDATE trigger From 41.9.1. Triggers on Data Changes:

To alter the row to be stored, it is possible to replace single values directly in NEW and return the modified NEW, or to build a complete new record/row to return.

I'd like to do the latter. I have a SELECT which is guaranteed to return a single row. How do I use it?

A: Here is a sample:
CREATE TABLE sample (
   id integer PRIMARY KEY,
   sthg text NOT NULL,
   ip inet
);

CREATE FUNCTION sample_trig() RETURNS trigger
   LANGUAGE plpgsql AS
$$BEGIN
   SELECT 42, 'yes!', '127.0.0.1'::inet INTO NEW;
   RETURN NEW;
END;$$;

CREATE TRIGGER sample_trig
   BEFORE INSERT ON sample FOR EACH ROW
   EXECUTE PROCEDURE sample_trig();

INSERT INTO sample VALUES (1, 'new', NULL);

TABLE sample;

 id | sthg |    ip
----+------+-----------
 42 | yes! | 127.0.0.1
(1 row)


text:
Q: Brackets Emmet Custom Snippet Configuration Issue Here are the steps I took:
 1. Install emmet via extensions manager
 2. Click Emmet menu > preferences
 3. Enter path for extensions. (Tried both custom and actual brackets extensions folder)
4. Add a snippets.json file to the specified folder in step #3.
{
"variables": {
    "lang": "en",
    "locale": "en-US",
    "charset": "UTF-8",
    "indentation": "\t",
    "newline": "\n"
},

"txt": {
    "filters": "txt",
    "profile": "txt",
    "abbreviations": {
        "@i": "@import url(|);"
}
}

I am editing a txt file and it is not working when I press @i<tab> or Meta+E, what am I missing?


text:
Q: Nonlinear (quadratic) matrix differential equation Let $X_0, A \in \mathbf R^{n \times n}$ be symmetric positive semidefinite matrices, and consider the equation
$$
\dot X = - X A X, \qquad X(0) = X_0.
$$
Does this equation admit an explicit solution (possibly in terms of the eigenvalues and eigenvectors of $A$ or $X_0$)? If not, is there a standard way of approaching it, in order to for example deduce convergence rates to equilibrium?
Edit: diagonalizing $A$ as $V D V^T$ and introducing $Y = V^TXV$, we can write the following equation for $Y$:
$$ \dot Y = - YDY, \qquad Y(0) = Y_0:= V^T X_0V.$$

A: There was a silly typo in my original comment but after a discussion with a friend I think there's a way to arrive at an answer for some cases which includes the original comment.
Given $\dot{X}=-XAX$, we can try to write the solution $X$ as a power series. $X(0)=X_0$,
$$\dot{X}(0)=-X_0AX_0=(-1)^1 (X_0A)^1X_0$$
$$\ddot{X}(0)=+2X_0AX_0AX_0=(-1)^2\cdot 2\cdot (X_0A)^2X_0$$
$$\dddot{X}(0)=(-1)^3\cdot 6\cdot (X_0A)^3X_0$$
$$X^{(n)}(0)=(-1)^n\cdot n!\cdot (X_0A)^nX_0 $$
So without taking into account questions of convergence or invertibility for the moment, it seems like
$$X=\sum_{n=0}^{\infty}(-1)^n (X_0A)^nX_0t^n=(\mathbb{1}+X_0At)^{-1}X_0$$
You could also choose to factor out each of the derivatives as $X^{(n)}(0)=(-1)^n\cdot n!\cdot X_0 (AX_0)^n$ so that
$$X=\sum_{n=0}^{\infty}(-1)^n X_0(AX_0)^nt^n=X_0(\mathbb{1}+AX_0t)^{-1}$$
This answer by Robert Israel points out something to be wary of for non-hermitian positive semi-definite matrices, but it looks like from the last part of the answer $AX_0$ or $X_0A$ should have non negative eigenvalues and so it looks like it could be ok for something like $0\leq t \leq \rho(AX_0)^{-1}$ where $\rho(AX_0)$ is its spectral radius. I'm not very familiar with these things so maybe someone can correct me on this.
Although I think by using $\frac{d}{dt}U^{-1}=-U^{-1}\frac{dU}{dt}U^{-1}$, then it could be true in general that the solution is $X(t)=(\mathbb{1}+X_0At)^{-1}X_0$ or $X(t)=X_0(\mathbb{1}+AX_0t)^{-1}$.


text:
Q: Differences between node.js and Tornado Besides the fact that node.js is written in JS and Tornado in Python, what are some of the differences between the two?  They're both non-blocking asynchronous web servers, right?  Why choose one over the other besides the language?

A: Nodejs also has a seamless integration / implementation of websockets called Socket.io. It handles browsers supporting sockets - events and also has backward polling compatibility for older browsers. It is quite quick on development requiring a notification framework or some similar event based programming.

A: I would suggested you go with NodeJS, if there is no personal pref to python. I like Python a lot, but for async I choose Tornado over node, and later had to struggle finding way to do a thing, or libraries with async support (like Cassandra has async in tests, but nowhere could I find way to use cqlengine with async. Had to choose Mongo since I already surpassed the deadline).
In terms of performance and async, Node far better than tornado.

A: As Rich Bradshaw points out Node.js is written in JS, which means you can keep the front end and the back end in the same language and possibly share some codebase. To me that is a huge potential benefit of Node.js.
Node also comes with more asynchronous libraries out of the box it seems.
V8 should make JS faster than Python at least that's what benchmarks seem to suggest, but it may not matter much, because both Node.js and Tornado (and most other web frameworks for that matter) use wrappers for native libraries. A lot of the Python standard library is written in C or can be replaced by a faster alternative, which mitigates potential differences even more.
Web services are usually I/O bound, so that means we're spending the time waiting for the data store and not processing the data. That makes the synthetic speed difference between JS and Python irrelevant in many applications.

A: The main advantage of node.js is that all its libraries are async so you don't have to worry much about blocking. There are async libraries for mysql, postgres, redis, etc. All is async by default.
Python have a library for anything - but most of these libraries are not asynchronous. In order to take advantage of tornado (and not to block the process) special libraries for are necessary (e.g. you can't just 'pip install redis' and use it, you'll need something like brukva), and there are much less tornado libraries than node.js libraries. There is no async mysql tornado driver available at the moment, for example (or at least I'm not aware of it).
But you can still use many python libraries with tornado (ones that doesn't do i/o), and tornado community is raising and filling the gaps.
It is easier to write an app using node.js than using tornado in my experience. I personally switched to tornado from node.js because it fits into existing infrastructure of my python project better (integration between django site serving html pages and tornado server providing realtime features was quite painless).

A: node.js uses V8 which compiles into assembly code, tornado doesn't do that yet.
Other than that (which doesn't actually seem to make much difference to the speed), it's the ecosystem. Do you prefer the event model of JS, or the way Python works? Are you happier using Python or JS libraries?


text:
Q: Cannot See Directories on Ubuntu 19.10 from Windows 10 I have a desktop running 19.10.  I would like to use it as a file server on my LAN.  I have set up Open SSH and I am able to access through Putty on my Windows 10 laptop.  Also, I have installed Samba through the terminal.  My laptop sees it on the Network in the file explorer but it says "This folder is empty."
Do I need to set up access to my directories?  I have removed the monitor from this desktop so I would like to make these changes via terminal in Putty.

A: For starters, you need to actually create a smb share. It is done by editing configuration file. Most cases, it is fairly tedious job for some reason and often results in frustration and failure.
As a recommendation if you run your desktop headless, is to install a tool called Cockpit. It also has a plugin for Samba(also docker and others).
sudo apt install cockpit cockpit-storaged

Then install Samba plugin for Cockpit by running
wget -O - https://raw.githubusercontent.com/enira/cockpit-smb-plugin/master/install.sh | sudo bash

After that, open browser, enter your desktops local IP adress and add port 9090(for example, 192.168.0.110:9090), then log in with your desktop's credentials(and tick "Reuse my password for privileged tasks" if you want to adjust the settings there). Then you can fairly simply manage and create your SMB shares.
As I am running a headless too, I am not going back to ssh after having Cockpit for sure. You can set a static IP, SMB shares, manage docker, manage Tuned powersaving settings, even virtual machines, if you want and the best part - it has a terminal right there as well.


text:
Q: Ionic nav main attribute. What does it do? I was looking at<ion-nav> that goes by the class name Nav:

*

*API docs

*Navigation in Component docs

*Source code
I noticed there is a method called initPane(), that makes reference to an attribute main.
So I presume you can have this code:
<ion-nav main>
</ion-nav>

What is the significance of this?
I see no mention of it in the documentation.
How does it impact the behaviour of your app?
I'm wondering if it's some sort of mechanism to automate setting the RootPage.
Can someone please clarify?
Thanks.

A: Found it here SplitPane

Here, SplitPane will look for the element with the main attribute and
  make that the central component on larger screens. The main component
  can be any Ionic component (ion-nav or ion-tabs) except ion-menu.


text:
Q: How to remove HTML tags, but preserve text, and then later replace the tags? <ruby><rb>自分</rb><rp>(</rp><rt>じぶん</rt><rp>)</rp></ruby>

I want to remove <ruby> tags, but I want to keep the contents. I want to do it with all <ruby> tags on the page.
I don't even know how to try, I had the idea to keep the HTML content in a variable, remove the <ruby> tags with hide(), and splash the text again, but I don't know how to re-insert it in a specific section of text. Also, I'm struggling with each.
I'd also like to remember where the tags were removed, so I can get them back later with a click.

A: Use the unwrap function:
$('ruby').unwrap();
http://api.jquery.com/unwrap/
EDIT:
How about similarly following the tutorial example in the above link?
pTags = $('ruby');

if ( pTags.parent().is("span") ) {
  pTags.unwrap();
  pTags.wrap("<ruby></ruby>");
} else {
  pTags.unwrap();
  pTags.wrap("");
}

Unwrap the <ruby> tag and wrap it with a placeholder  tag.
Update 1:
Well, my previous code had the right "pseudocode", but I tested it and it wasn't working properly. Instead I had to do something like this:
pTags = $('ruby');
var content = pTags.contents();

$("button").click(function () {
    if (content.parent().is("span")) {
        content.unwrap().wrapAll("<ruby></ruby>");
    } else {
        content.unwrap().wrapAll("");
    }
});

Update 2:
Update 1 didn't take into consider multiple <ruby> tags. I have updated the code so that it works for multiple ruby tags as well as nested <ruby> tags!
var wrapper = $('ruby');
var content;

$("button").click(function () {
    wrapper.each(function () {
        content = $(this).contents();
        if (content.parent().is("span")) {
            content.unwrap().wrapAll("<ruby></ruby>");
            wrapper = $('ruby');
        } else {
            content.unwrap().wrapAll("");
            wrapper = $('span.unwrapped_ruby');
        }
    });

});

Try the jsfiddle

A: If you are just trying to remove the ruby tags, you can do something like this:
$(document).ready(function(){
    var cont = $('ruby').contents().unwrap();
    $('html').append(cont)
});

DEMO


text:
Q: Installing package on R, need C++11 support for OSX I'm trying to install library(Boom) for Bayesian Object Oriented Modeling and its dependencies BoomSpikeSlab, bsts. However, I always get the same response from R:
In file included from Models/Glm/MultinomialLogitModel.cpp:31:
In file included from     ../inst/include/Models/Glm/PosteriorSamplers/MLVS.hpp:25:
In file included from     ../inst/include/Models/Glm/PosteriorSamplers/MLVS_data_imputer.hpp:25:
../inst/include/Models/PosteriorSamplers/Imputer.hpp:30:10: fatal     error: 'future' file not found
#include <future>
     ^
 1 error generated.
 make: *** [Models/Glm/MultinomialLogitModel.o] Error 1
ERROR: compilation failed for package 'Boom'
* removing '/usr/local/lib/R/3.2/site-library/Boom'
Warning in install.packages :
installation of package 'Boom' had non-zero exit status
 ERROR: dependency 'Boom' is not available for package 'BoomSpikeSlab'
 * removing '/usr/local/lib/R/3.2/site-library/BoomSpikeSlab'
Warning in install.packages :
 installation of package 'BoomSpikeSlab' had non-zero exit status
 ERROR: dependencies 'BoomSpikeSlab', 'Boom' are not available for     package 'bsts'
* removing '/usr/local/lib/R/3.2/site-library/bsts'
  Warning in install.packages :
installation of package 'bsts' had non-zero exit status

The downloaded source packages are in
'/private/var/folders/s2/9wz53mrj0vqcpj9v3zjwx6q80000gn/T/RtmpvMmIug/downloaded_packages'

I thought that might be related to my problem
pip cffi package installation failed on osx
so I tried :
xcode-select --install

which resulted in:
xcode-select: Error: unknown command option '--install'.

xcode-select: Report or change the path to the active
          Xcode installation for this machine.

Usage: xcode-select --print-path
       Prints the path of the active Xcode folder
  or: xcode-select --switch <xcode_path>
       Sets the path for the active Xcode folder
  or: xcode-select --version
       Prints the version of xcode-select

How can I install the Boompackage?
I'm using Mac OSX 10.8.5 with Xcode version: 5.1.0
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin12.6.0

A: Well, Boom is on CRAN so it by that very construction must work with the default toolchain.
Do you have BH installed?   The corresponding clang version worked for years as we added optional C++11 support in Rcpp at least as early as March 2013 (when we added support for Rcpp::plugin(cpp11).


text:
Q: A blank bar appear at bottom when using translucent status bar in non-actionbar activity? I want to use a Toolbar instead of an Actionbar with translucent status bar, but a thin bar(the same as the status bar in width) appears at bottom of the screen only if I'm using the NoAcitionbar theme.
And the color of the bar is the same as the 'windowBackgroud' I set. So I guess there's a margin or something.
I tried to reset all the margins but it didn't work.
And when I use the 'Android Device Monitor' in Android Studio to check the hierarchy of the UI the bar disappears, but re-disapear when I restart the app.
I'm using AppCompat v22 support lib and my Activity is AppCompat Activity.
I override this function in MainAcitivity:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            // translucent status bar
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // translucent navigation bar
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }
}

In MainAcitvity there's only a fragment :
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_fragment"
android:name="org.bitoo.abit.ui.MainActivityFragment"
tools:layout="@layout/fragment_mission_list" android:layout_width="match_parent"
android:layout_height="match_parent" />

and the layout of fragment is here:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         xmlns:materialdesign="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
            android:background="@color/light_primary_color"
         tools:context="org.bitoo.abit.ui.DetailedMissionActivityFragment">

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_mission_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"/>

<com.gc.materialdesign.views.ButtonFloat
    android:id="@+id/bt_add"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_margin="15dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentBottom="true"
    android:background="@color/accent_color"
    materialdesign:animate="false"
    materialdesign:iconDrawable="@drawable/ic_action_new" />
 </RelativeLayout>

Style of theme :
  <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarStyle">@style/my_actionbar_style</item>
    <item name="colorPrimary">@color/primary_color</item>
    <item name="colorPrimaryDark">@color/dark_primary_color</item>
  </style>

<style name="my_actionbar_style" parent="Widget.AppCompat.ActionBar">
    <item name="background">@color/dark_primary_color</item>
    <item name="backgroundStacked">@color/dark_primary_color</item>
    <item name="backgroundSplit">@color/dark_primary_color</item>
    <item name="titleTextStyle">@style/my_actionbar_text_style</item>
</style>
<style name="my_actionbar_text_style" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/title_text_color</item>
</style>


text:
Q: iPod UISlider images for retina display - objective-c I want to make my default UISlider like iPod UISlider (volume or tracking), but I can't find UISlider images for Retina display. I found only this. But this is not for Retina display. Where I can find this images?

A: Somewhere on your hard disk you can find the app "Springboard.app". on my installation it is here:

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk/System/Library/CoreServices/SpringBoard.app/

if you open it via right click and "Show Package Contents", you will find apple's artwork. if you can't find the knob inside (didn't check), it is probably drawn directly viv core graphics.
Note: I have no idea, if you can use this legally
edit
Maybe I misunderstood your question.
If you are targeting only iOS 5, I strongly recommend watching Session 114 - Customizing the Appearance of UIKit Controlsdeveloper login required of the WWDC 2011 Session Videos. It show how to change iOS controls appearance app-wide.


text:
Q: TypeError: Missing 1 required positional argument: 'self' Anybody? I keep on getting issues with a part of my code. Anybody has some idea how to tackle it?
Python - Selenium
I added the full code. The purpose is to auto open Instagram Stories.
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
import random
import string

#Chromedriver path. Make sure to have the same Chromedriver version as your Google Chrome browser
browser = webdriver.Chrome(executable_path= r"")  # <----- ENTER PATH HERE

browser.get(('https://www.instagram.com/accounts/login/?source=auth_switcher'))
sleep(2)

def start():
    acceptCookies = browser.find_element_by_xpath('/html/body/div[4]/div/div/button[1]');
    acceptCookies.click();
    sleep(4);
    #browser.implicitly_wait(3)  #this is another wait function.If you would like to run the script faster, change all sleep() to this
    username = browser.find_element_by_name('username')
    username.send_keys('') # <- INSERT YOUR INSTAGRAM USERNAME HERE -------------------------------------------------------------------------------------------------------------------------
    password = browser.find_element_by_name('password')
    password.send_keys('') # <- INSERT YOUR INSTAGRAM PASSWORD HERE -----------------------------------------------------------------------------------------------------------------------
    nextButton = browser.find_element_by_xpath('/html/body/div[1]/section/main/div/div/div[1]/div/form/div/div[3]/button')
    nextButton.click()
    #browser.quit()
    sleep(5)
    notification = browser.find_element_by_xpath("//button[contains(text(), 'Niet nu')]")
    notification.click()
    sleep(5)
    notification = browser.find_element_by_xpath("//button[contains(text(), 'Niet nu')]")
    notification.click()
    sleep(5)

def openStories(self):
    bot=self.bot
    bot.find_element_by_xpath('OE30K').click()

#Start the programm
start()
openStories()

A: In Python self is used this way:
class MyClass:
    def __init__(self, name: str, age: int) -> None: # constructor
        self.age = age # self is the object that the constructor is initializing
        self.myMethod(name) # You can call methods passing the instance itself as argument, the argument 'self' is the instance
    def myMethod(self, name: str) -> None:
        self.name = name

The self variable represents the instance itself.
>>> my_object = MyClass()
>>> my_object.myMethod('myName')
>>> print(my_object.name)
'myName'

The self argument is the instance on which the method is called.

A: Hope you understand the difference between defining a method within a class and a function outside a class.
class MyClass:
    foo = "HELLO!"

    def openStories1(self):
        # Here self is an instance of MyClass
        print(self.foo)

def openStories2(self):
    # Here self is just an object.
    print(self.foo)

# Can be called without explicitly passing an argument, since self refers to the instance1
instance1 = MyClass()
instance1.openStories1()

# When defining outside a class you will need to pass the instance explicitly.
openStories2(instance1)

# Raises error since this function cannot be accessed through the instance because it's not defined in the class.
instance1.openStories2()

Outputs:
HELLO!
HELLO!
Traceback (most recent call last):
  File "scratch_6.py", line 18, in <module>
    instance1.openStories2()
AttributeError: 'MyClass' object has no attribute 'openStories2'


text:
Q: Difference between ExecuteAsync and StartAsync methods in BackgroundService .net core Migrating from the legacy .NET Framework I need to create a long time background process worker.
Looking at the documentation I found a BackgroundService class, which is used for this kind of purpose. But I stumbled across two the same (for my point of view) methods ExecuteAsync() and StartAsync()
Can somebody explain to me what the main difference between them?
Is it some kind of segregation principle - we have a method for setting up data as the "constructor" and we have a method for actually doing things?

A: The default behavior of the BackgroundService is that  StartAsync calls ExecuteAsync, see code. It's a default, the StartAsync is virtual so you could override it.
Please note that only StartAsync is public and ExecuteAsync
protected (and abstract). So from the outside StartAsync is called
If you create a subclass of BackgroundService, you must implement ExecuteAsync (because it's abstract). That should do your work.  Also you could override StartAsync (as it's virtual), but that's only needed for special cases.
So why is there a StartAsync and ExecuteAsync?
You could create a service by implementing IHostedService. That interface has StartAsync and StopAsync.
BackgroundService is an (base) implementation of IHostedService, and could be used for long running tasks. This one defines the abstract ExecuteAsync.
In summary

*

*When inheriting from BackgroundService, implement ExecuteAsync

*When implementing IHostedService, implement StartAsync and StopAsync
Read more

*

*Background tasks with hosted services in ASP.NET Core

*BackgroundService in .NET Core for long running tasks - also other implementations of IHostedService are shown here, like a TimedHostedService

A: To add to Julian's answer, I have noticed if you do override StartAsync when using the BackgroundWorker, ExecuteAsync will not get called. I am not sure if you are supposed call ExecuteAsync from StartAsync, but my impression was StartAsync runs before ExecuteAsync and before the backgroundservice runs. But the behavior I am seeing is that if you override StartAsync, ExecuteAsync will not automatically get called. Remove the override to StartAsync, and ExecuteAsync gets called automatically.


text:
Q: how to prove working of RS 232 full modem,RS 422 working PC to PC and LOOP BACK Hello there I am a newbie trying to prove the working of RS 232 Full modem and also one RS 422( RX,TX,RTS,CTS)
These 2 ports are on a custom designed board and I need to prove they are working.
I am able to confirm the working at register level but I need to prove the working using softwares like Minicom or any other custom program.
How can I prove the working of these ports from one PC to a different PC using DB 9 connections and LOOP BACK too
Can someone help me with this? Do I need to use any extra hardware to prove the working of this in Linux?

A: The most common type of serial port test is probably a loopback test.  Create a test fixture that connects output pins of the port to the input pins (TX->RX, RTS->CTS, etc).  If you do not have matching input pins for every output pin, you will need to do a three-way connection.
After you create the loopback, you will need to write software that exercises the pins.  If TX and RX are connected, you can send a byte and verify that it was echoed back.  For the control pins, toggle them and make sure the other side of the connection saw the transition.  Make sure you exercise every pin of the serial port.
Note that you should run a TX->RX data loopback at multiple baud rates.  It is possible for there to be a signal integrity issue in the design that only shows up at higher bauds rates.  It is also possible for there to be a bad signal connection on the board that is masked by inductance and capacitance at higher baud rates.  Therefore, it is a good idea to run a data loopback at the slowest baud rate, the fastest baud rate, and 1-2 in the middle.
Another thing you should do is a baud rate accuracy test.  This will prove the clock driving the UART is running at the right frequency, and being divided properly.  Transmit X amount of bytes at a certain baud rate and verify they arrived in the expected amount of time.  To get an accurate number, you will need to bypass any buffering in the OS serial port driver (e.g. use direct register I/O), and make sure to accommodate for any start/stop bit overhead (see comments below).
However, a loopback test is not exhaustive.  It only proves the device can talk to itself.  The device may still have some flaw (e.g. voltage levels) that cannot be detected locally.  So, you should also run some tests with external hardware.  Cable your board to another system and run a test (e.g. with minicom).  Make sure they can talk to each other.
Even an external communication test can miss something.  You can still have poor signal quality from your board, but it happens to be good enough for the other device.  To accurately verify the signal quality/timing, you need an oscilloscope.
While you are running communication tests, connect the scope probes to the various signals and verify the signal integrity.  Make sure that voltage levels are valid, that you see clean low/high bit transitions, and that the timing of the data pin appears correct for the specified baud rate.  (A scope can be a more accurate way to measure baud rate than the software-based method described earlier.)


text:
Q: Format Y axis of Chart.JS as Time I have this chart below, I want to scale the Y axis using the TIME (the time isn't time of day it is total hours,mins, seconds so could be over 24 hours) just can't seem to get it to work, all I get is a blank screen, sure it's a syntax error but can't spot it! Thanks
var ctx = document.getElementById("myChart3").getContext('2d');
var myChart3 = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"],
        datasets: [
            {
                label: "Time",
                backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#565452", "#321456", "#129864", "#326812", "#215984"],
                data: ["11:46:07", "11:41:14", "11:55:26", "12:14:58", "11:54:55", "11:54:04", "12:28:29", "12:35:18"]
            }
  ]
    },
    options: {
        scales: {
            yAxes: [{
                type: 'time',
                time: {
                    displayFormats: {
                        minutes: 'h:mm:ss a'
                    }
                }
        }]
        }
    }
});

A: Time scale works only for X axis.

It can only be placed on the X axis.

But for Y you can use a linear scale and express each time as date in milliseconds since 1970-01-01 (how the usual Date object does).
PLUNKER or use the following example:

$(function(){
  const ctx = document.getElementById('myChart').getContext('2d');

  let years = ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"];
  let times = ["11:46:07", "11:41:14", "11:55:26", "12:14:58", "11:54:55", "11:54:04", "12:28:29", "12:35:18"];

  let data = years.map((year, index) => ({
    x: moment(`${year}-01-01`),
    y: moment(`1970-02-01 ${times[index]}`).valueOf()
  }));

  let bckColors = ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#565452", "#321456", "#129864", "#326812", "#215984"];

  let myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [
            {
                label: "Time",
                backgroundColor: 'rgba(188, 229, 214, 0.7)',
                pointBackgroundColor: bckColors,
                data: data,
                pointBorderWidth: 2,
                pointRadius: 5,
                pointHoverRadius: 7
            }
        ]
    },
    options: {
        scales: {
            xAxes: [
              {
                type: 'time',
                position: 'bottom',
                time: {
                  displayFormats: {
                    years: 'YYYY'
                  },
                  unit: 'year'
                }
              }
            ],
            yAxes: [
              {
                type: 'linear',
                position: 'left',
                ticks: {
                  min: moment('1970-02-01 00:00:00').valueOf(),
                  max: moment('1970-02-01 23:59:59').valueOf(),
                  stepSize: 3.6e+6,
                  beginAtZero: false,
                  callback: value => {
                    let date = moment(value);
                    if(date.diff(moment('1970-02-01 23:59:59'), 'minutes') === 0) {
                      return null;
                    }

                    return date.format('h A');
                  }
                }
              }
            ]
        }
    }
  });
});
<html>
  <head>
      <script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      <script src="https://npmcdn.com/moment@2.14.1"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
  </head>
  <body>
    <canvas id="myChart" width="500" height="300"></canvas>
  </body>
</html>

Explanation
You can have the years on X axis which can be a linear, time or category scale.
In this example X axis is a time scale.
The following code is used to generate values for X and Y axis:
  let data = years.map((year, index) => ({
    x: moment(`${year}-01-01`),
    y: moment(`1970-02-01 ${times[index]}`).valueOf()
  }));

For X axis I used moment js to create a date on the first day of the corresponding year.
For Y axis I used moment js to create the date in milliseconds since 1970-01-01. In this case all hours are combined with a day to form a date. 1970-02-01 in order to prevent an edge cases that may happen for 1970-01-01. Then these milliseconds, since 1970-01-01, are used with the Y axis linear scale.
Y axis tick.callback is used to format the corresponding milliseconds to an hour. Thus using the format h A to obtain for example 1 AM, 1 PM, 12 AM, 12 PM, ....


text:
Q: Magento admin not working (too many redirects) This morning i changed the System Config Custom Admin URL in magento witch resulted in a 404.
I used this: https://stackoverflow.com/questions/7202950/magento-admin-url-not-working-404-after-changing-it-cant-go-back to revert the change i've made.
I got my www.mystore.com/admin back, but when i log in i get this:

The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for
  this address in a way that will never complete.

An the URL looks like this:
https://mystore.com/index.php/admin/index/index/key/d27c0da27b776b799fb5f7aa4ebbbda0/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/index.php/admin/dashboard/index/key/57c8085a9d1a09359fc39e478c9588e8/?SID=boks2ippnh47oq87dvt910q4n1

When i then remove the URL and put in: mystore.com/admin, i get the admin dashboard only in HTML
My MySQL tables look like this:
admin/url/custom = NULL
admin/url/use_custom = 0
admin/url/use_custom_path = 0

web/unsecure/base_url = http://mystore.com/
web/secure/base_url = https://mystore.com/

Any fix for this problem?

A: *

*It seems like you are using https for secure url so make sure you have installed SSL properly.

*Also before changing the base secure url,did you checked the media and skin url, is it was a static url there, if yes so you need to change this from core_config_data.

Did you changed admin url from admin panel?

A: it is due to Session Validation is set to remote url
So, please go to phpmyadmin
search Core_config_data
delete the configration table
look like
Validate REMOTE_ADDR

Validate HTTP_VIA

Validate HTTP_X_FORWARDED_FOR

Validate HTTP_USER_AGENT

i sure it can save your time but sir, do it on your risk thanks @Martvent Developer


text:
Q: Zing Chart Y-scale data out of frame I added data formatting to my zingchart Y-scale to use $ "," and 2 decimals, and now the text is out of frame. I tried changing the width of the chart to no avail. Any ideas here?
jsfiddle.net/Rodmunera/j1ddL5k6/7

A: Try adding the plotarea object to your JSON and add the margin attribute to that object. I tried it with a margin of 100px and it made everything fit in--

var chartJSON =
        {
            "legend":{
                "border-color":"#bbbbbb",
                "margin-top":10,
                "margin-left":0,
                "drag-handler":"header",
                "item":{
                    "toggle":true,
                    "margin-top":5,
                    "margin-left":5,
                    "margin-right":5,
                    "margin-bottom":5
                },
                "shadow":false,
                "margin-right":0,
                "background-color-2":"#e1e1e1",
                "border-width":1,
                "background-color":"#e1e1e1",
                "draggable":true,
                "minimize":false,
                "header":{
                    "":0,
                    "background-color":"#bbbbbb",
                    "text-align":"center",
                    "font-size":16,
                    "text":"Legend",
                    "font-family":"Lato",
                    "color":"#ffffff",
                    "background-color-2":"#bbbbbb",
                    "font-weight":300
                },
                "layout":"x4",
                "position":"50% 0%",
                "margin-bottom":0
            },
            "tooltip":{
                "visible":true,
                "decimals":2,
                "thousands-separator":",",
                "format":"$%v",
                "text":"$%v"
            },
            "stacked":false,
            "series":[
                {
                    "background-color":"#7fb2f0",
                    "line-color":"#7fb2f0",
                    "text":"Checkout Total",
                    "marker":{
                        "border-color":"#7fb2f0",
                        "background-color":"#7fb2f0",
                        "alpha":1
                    },
                    "background-color-2":"#7fb2f0",
                    "values":[227.04,141.90,56.76,56.76,56.76,141.90,113.52,56.76,28.38,56.76,56.76,28.38,28.38,56.76,141.90,198.66,56.76,56.76,141.90,397.32,85.14,198.66,85.14,255.42,317.82,783.15,646.95,1770.60,3745.50]
                },
                {
                    "background-color":"#bf5a9a",
                    "line-color":"#bf5a9a",
                    "text":"Refunds",
                    "marker":{
                        "border-color":"#bf5a9a",
                        "background-color":"#bf5a9a",
                        "alpha":1
                    },
                    "background-color-2":"#bf5a9a",
                    "values":[0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,56.76,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,272.40,817.20]
                },
                {
                    "background-color":"#efae69",
                    "line-color":"#efae69",
                    "text":"Revenue",
                    "marker":{
                        "border-color":"#efae69",
                        "background-color":"#efae69",
                        "alpha":1
                    },
                    "background-color-2":"#efae69",
                    "values":[200.00,125.00,50.00,50.00,50.00,125.00,100.00,50.00,25.00,50.00,50.00,25.00,25.00,50.00,125.00,175.00,50.00,50.00,125.00,350.00,75.00,175.00,75.00,225.00,280.00,690.00,570.00,1560.00,3300.00]
                }
            ],
            "guide":{
                "line-gap-size":0,
                "visible":true,
                "line-color":"#000000",
                "format":"$%v",
                "line-width":1,
                "tooltip-visible":false,
                "alpha":0,
                "tooltip-text":"%v"
            },
            "alpha":1,
            "scale-y":{
                "zooming":false,
                "decimals":2,
                "thousands-separator":",",
                "negation":"currency",
                "format":"$%v",
                "text":""
            },
            "plotarea":{
                "margin":"100px"
            },
            "plot":{
                "spline":true,
                "negation":"currency",
                "format":"$%v"
            },
            "scale-x":{
                "zooming":false,
                "transform":{
                    "guide":{
                        "visible":false
                    },
                    "item":{
                        "visible":false
                    },
                    "all":"%M %d, %Y",
                    "type":"date"
                },
                "decimals":0,
                "format":"%v",
                "mirrored":0,
                "text":"Shows",
                "values":[1398729600000,1398816000000,1398902400000,1399248000000,1399334400000,1399420800000,1399593600000,1399680000000,1400025600000,1400112000000,1400716800000,1400976000000,1401062400000,1401235200000,1401321600000,1401494400000,1401580800000,1401667200000,1401753600000,1401840000000,1401926400000,1402012800000,1402099200000,1402185600000,1402272000000,1402358400000,1402444800000,1402531200000,1402617600000]
            },
            "type":"area"
        }
zingchart.render({
  id: "myChart",
  height: 300,
  width: 500,
  data: chartJSON
});

I'm on the ZingChart team so please feel free to reach out if you have any questions about this answer or other ZingChart features.


text:
Q: encode data in get request <!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<body onload="searchForPrograms.submit();">
<form id="searchForPrograms" name="searchForPrograms" enctype="application/x-www-form-urlencoded" method="get" action="searchingEngine.php">
<input type="text" id="query" name="query" value="MyProgram"  /><br>
<input type="submit" value="Search" />
</form>
</body>

The get request should have the form like "searchingEngine.php?query=%22MyProgram%22".
How can I encode the value of the query input correctly?


text:
Q: The hierarchy of single pages with custom post types in WordPress I have a custom post type named cities.
For this custom post type I will have N cities related.
I'm trying to create the files for theses pages and I thought this would work:
single.php - the generic one
single-cities.php - To list the cities
single-cities-{city-slug}.php - To bring the information for THE city

When I try:
/cities - It's showing the single.php content, not the single-cities content with the list.
/cities/sao-paulo - It's working. It shows the information about Sao Paulo.

Test:
If I delete the single-cities-{city-slug}.php, and try to access /cities/sao-paulo, it will bring the single-cities.php

What am I doing wrong in this hierarchy?
My code to register the custom post type:
$city_args = array(
  'labels'              => $labels,
  'public'              => true,
  'has_archive'         => true,
  'publicly_queryable'  => true,
  'query_var'           => true,
  'capability_type'     => 'post',
  'hierarchical'        => false,
  'supports'             => array(
    'title'
  ),
  'exclude_from_search' => false,
  'menu_icon'           => 'dashicons-building'
);

register_post_type('cities', $city_args);

Thanks!

UPDATE
I think I misunderstood the concept of a single page.
The single.php is just to render a single post, not to list the posts for a custom post type.
Reading more about this hierarchy, I'm trying to understand how my structure of listing cities and then bring the city information would fit.
Maybe I should create a page for cities, and then inside this page (page-cities.php), create the code to bring all the cities.
Clicking on each city, it should go to the single.php, is that it??

A: You'll want archive-cities.php to list all cities, single-cities for one post. Use this as a reference: https://codex.wordpress.org/Post_Type_Templates

A: The page listing all your posts is called an Archive, which lives at the slug declared in the register_post_type arguments.
/cities - This is your archive page, so it will call archive-cities.php
/cities/sao-paulo - This is a single post. It will first look for single-cities-{city-slug}.php, then for single-cities.php.
In most cases, you would only use single-cities-{city-slug}.php to make a unique template file for a specific city. Assuming every city post uses an identical layout, you only need single-cities.php.


text:
Q: How to remove a string from the list, by looking at a certain letter? var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
            foreach(string country in countries)
            {
                if (country.StartsWith("A"))
                {
                    countries.Remove(country);
                }
            }
            foreach (string country in countries)
            {
                Console.WriteLine(country);
            }

For instance I would like to get rid of countries starting with the letter A

A: I would suggest you to use RemoveAll() (link to documentation) which requires a condition to know if the element has to be removed or not
You could do :
// The List declaration you provided
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };

// Replace your first `foreach(string country in countries)` with this line
countries.RemoveAll(country => country.StartsWith("A"));

// The way of displaying data you provided
foreach (string country in countries)
{
    Console.WriteLine(country);
}

Edit : As Johnathan Barclay said in the comments, "if you want to perform a case-insensitive search, you should provide a StringComparison rather than using ToUpper()", as I did in the uneditted answer.
The code would be :
// The List declaration you provided
var countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };

// Replace your first `foreach(string country in countries)` with this line
countries.RemoveAll(country => country.StartsWith("a", StringComparison.InvariantCultureIgnoreCase));

// The way of displaying data you provided
foreach (string country in countries)
{
    Console.WriteLine(country);
}

A: Approach with   RemoveAll()
List<string> countries = new List<string>() { "India", "Australia", "Austria", "Canada", "Mexico", "Japan" };
countries.RemoveAll(country => country.StartsWith("A"));
countries.ForEach(Console.WriteLine);

A: Yes you can use the RemoveAll() property to get the result you want.
var countries = new List<string>() { "India", "Australia", "Austria"};

countries.RemoveAll(Country=>country.StartsWith("A"))


text:
Q: How ejabberd 13.10 server is better than ejabberd previous versions in terms of performance? I am working in android application development using ejabberd-2.1.13 as a server for my android application. I heard that ejabberd-13.10 is better in performance compare to previous versions.So I installed ejabberd-13.10 in my ubuntu machine.To ensure performance of ejabberd-13.10 I did performance test for different ejabberd servers(ejabberd-2.1.13 & ejabberd-13.10) using fprof tool as described in following link.(http://carbonshaft.blogspot.in/2011/11/erlang-using-fprof-profiler-to-drive.html) .But I  get latest ejabberd server (ejabberd-13.10) show slow performance compare to ejabberd-2.1.13.Could you please advice how the ejabberd-13.10 server is better in performance?

A: 13.10 is better by the simple fact 2.1.x branch is officially deprecated and abandoned.
This means two simple things:

*

*No new version in the 2.1.x will be released.

*Bugs found in 2.1.13 might not get fixed.

Also I would suggest not profiling but rather measuring the real-life performance using a suitable tool, such as tsung.  The problem with profiling two different code bases is that you're comparing apples to oranges.  Things like memory consumption (declared to be greatly reduced in 13.x due to switching from strings to binaries) do count in real-world scenarios when you intend to host thousands of concurrent connections.  Also note that programs like ejabbed do really tend to be memory- and I/O-bound, not CPU-bound (the latter usually indicates you've managed to trigger a bug in the program or runtime) so mere profiling might not be indicative, only stress testing the staging or production server would.

A: Starting with ejabberd 13.x, several optimisations have been performed:

*

*Optimization of the memory consumption.

*Optimization of the performance of some important modules, like pubsub.

*Better Multi User Chat performance and lower latency.

*Multicast routing optimization.

In term of performance, ejabberd 15.07 for example is 2 to 3 time more efficient on all the parameters: Memory, latency, CPU.


text:
Q: Opencart 2.3 Events and Triggers for editOrder Is there a list of available event triggers, because I am searching for one that does trigger when an order status is updated. I tried registering like this:
$this->model_extension_event->addEvent('editOrderEvent','catalog/model/checkout/order/editOrder/after','extension/module/newpay/editOrderHandler');
but it does not work.
However, I managed to make it work when a new order is created with this one:
$this->model_extension_event->addEvent('newOrderEvent','catalog/model/checkout/order/addOrder/after','extension/module/newpay/newOrderHandler');
but that is not what I'm looking for.
It seems not to register the editOrder part.
This is the structure of the extension:
In admin/controller/extension/module there are the install() and uninstall() methods.
In catalog/controller/extension/module there are the handler methods.


text:
Q: Angular2 springboot mysql My question can be stupid still I want help, as I am totally new to Angular2 specially.
I have hero-list.component.html file:

Tour of Heroes ({{mode}})

Heroes:

{{hero.name}}

New hero name: <input #newHeroName />
<button (click)="addHero(newHeroName.value); newHeroName.value=''">Add Hero</button>

{{errorMessage}}

    {{newHeroName.value}}
    {{i}}
     {{hero.name}}

And I want to pass the heroes array to backend i.e. to my controller class in my spring boot application which will insert this data in mysql.
How can i achieve this ? I followed many tutorials and I got a lot more confused.
P.S: I want to achieve this in Angular2
Any help appreciated,
Thanks in advance.

A: You can use two ways. One is with spring-cors and another is 'decoupled application' way. CORS is suitable if you want to use cloud based solution. (Ok, I know u are beginner). If you want to use cors, please check the following github project.
https://github.com/borysn/spring-boot-angular2
Just don't panic, that's really easy, just go through and try to understand how that is being done.
Another way, is decoupled way. In the following url u can find the solution.
https://blog.jdriven.com/2016/12/angular2-spring-boot-getting-started/
Your question answer is little bit big, that's why I have used website link. Hope that will help.


text:
Q: Learning how to use ES6 import and modules getting Reference Error I am just beginning to learn ES6 imports, with the hopes to transition an application to modular ES6. My current project has the following directory structure:
index.html
-scripts\
   --function1.js
   --function2.js
   --globals.js
   --main.js

My index.html file code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Modular JS Example</title>
</head>
<body>
  <button onclick="changevar1()">Change Var 1</button>
  <button onclick="changevar2()">Change Var 2</button>
  <script src="scripts/main.js" type="module"></script>

</body>
</html>

As you can see, I have two buttons which have onclick triggers assigned to them. These functions namely, changevar1() and changevar2() are found in files function1.js and function2.js respectively. And my entry point is main.js.
My main.js is as follows:
import {globalvar1 as globalvar1,
  globalvar2 as globalvar2} from "./globals.js";
import {changevar1 as changevar1} from "./function1.js";
import {changevar2 as changevar2} from "./function2.js";

console.log(globalvar1, globalvar2,changevar1,changevar2);

My globals.js is where I declare some global variables which will be used by functions in either functions1.js or functions2.js and is as follows:
export let globalvar1 = "I am globalvar1";
export let globalvar2 = "I am globalvar2";

My function1.js has the function for the first button and is as follows:
import { globalvar1 } from "./globals.js" //do I need to import here?

export function changevar1() {
  globalvar1 = "Now changed globalvar1"
  console.log(globalvar1);
}

In the case above, I am importing the globalvar1 from globals.js and I am not sure if that is required, or if it will all come together in main.js?
My function2.js has the function for the second button and is as follows:
export function changevar2() {
  globalvar2 = "Now changed globalvar2"
  console.log(globalvar2);
}

In this case, I was not importing the globalvar2, just to see if it was not required.
Now the question is simply when you press the button how can you trigger either changevar1() or changevar2() to change the globalvar1 or globalvar2? I keep getting "Reference errors".
I have read several online documents and watched a few video tutorials online too to try to understand modular js.
Please excuse my lack of knowledge about modules and any help even if very basic knowledge is helpful.


text:
Q: javascript auto submit to form without name (tumblr) I want to make auto submit code in JavaScript for Tumblr but the problem is that the form doesnt have name. I cant edit html I will put code in Tampermonkey in Chrome (same as Greasmonkey in Firefox).
<form id="post_form" style="" enctype="multipart/form-data" class="active" data-post-type="photo">

some photo

<button class="chrome blue txt " type="submit">Reblog post</button>

</form>

I tried a number of ways but nothing works.


text:
Q: Replacing values by values of a different dataframe in R I have this kind of dataframe (df1):
     Code    ID_CODE     value_1   value_2    value_3
     HA09U    98_ 10      57.80      NA          NA
     HA09U    98_ 11      57.80      NA          NA
     HA09U    98_ 12      57.80      NA          NA
     MB03L    99_ 10        NA      90.77        NA
     MB03L    99_ 11        NA      90.77        NA
     MB03L    99_ 12        NA      90.77        NA
     KE17P    100_ 10      68.44    76.05        72.01
     KE17P    100_ 11      68.44    76.05        72.01
     KE17P    100_ 12      68.44    76.05        72.01

I want to replace the value of ALL variables (value_1, value_2 and value_3) of the person that includes NAs by adding the values from my second dataframe (df2):
     Code    value_1   value_2    value_3
    HA09U     90.35     89.84      90.07
    MB03L     66.94     79.62      73.77

The result should be:
      Code    ID_CODE     value_1    value_2    value_3
     HA09U    98_ 10       90.35      89.84      90.07
     HA09U    98_ 11       90.35      89.84      90.07
     HA09U    98_ 12       90.35      89.84      90.07
     MB03L    99_ 10       66.94      79.62      73.77
     MB03L    99_ 11       66.94      79.62      73.77
     MB03L    99_ 12       66.94      79.62      73.77
     KE17P    100_ 10      68.44      76.05      72.01
     KE17P    100_ 11      68.44      76.05      72.01
     KE17P    100_ 12      68.44      76.05      72.01

I tried to use some merge and bind_rows function, this one took me the closest:
df1$value_1[df1$Code == df2$Code] <- df2$value_1

But it did not worked and somehow messed up the dataframe.
Using this code
d1 <- left_join(df1, df2, by = "Code" )

Adds three new colums with the values of df2, but the values of KE17P (the person that already has complete data) is missing. So I am really looking for a replacing function.

A: We can use a join in data.table (Here, we assume the NA columns are numeric class and not logical)
library(data.table)
nm1 <- grep('^value_\\d+$', names(df1), value = TRUE)
setDT(df1)[df2, (nm1) := mget(paste0('i.', nm1)), on = .(Code)]

-output
df1
#    Code ID_CODE value_1 value_2 value_3
#1: MB03L  99_ 10   66.94   79.62   73.77
#2: MB03L  99_ 11   66.94   79.62   73.77
#3: MB03L  99_ 12   66.94   79.62   73.77
#4: MB03L  99_ 13   66.94   79.62   73.77
#5: MB03L  99_ 14   66.94   79.62   73.77
#6: MB03L  99_ 15   66.94   79.62   73.77

Or using tidyverse
library(dplyr)
library(stringr)
left_join(df1, df2, by = 'Code') %>%
  transmute(Code, ID_CODE, across(ends_with('.x'), ~
     coalesce(get(str_replace(cur_column(),"\\.x", ".y")), .))) %>%
  rename_with(~ str_remove(., '\\.x'), starts_with('value_'))

-output
#    Code ID_CODE value_1 value_2 value_3
#1 MB03L  99_ 10   66.94   79.62   73.77
#2 MB03L  99_ 11   66.94   79.62   73.77
#3 MB03L  99_ 12   66.94   79.62   73.77
#4 MB03L  99_ 13   66.94   79.62   73.77
#5 MB03L  99_ 14   66.94   79.62   73.77
#6 MB03L  99_ 15   66.94   79.62   73.77

data
df1 <- structure(list(Code = c("MB03L", "MB03L", "MB03L", "MB03L", "MB03L",
"MB03L"), ID_CODE = c("99_ 10", "99_ 11", "99_ 12", "99_ 13",
"99_ 14", "99_ 15"), value_1 = c(NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_), value_2 = c(90.77, 90.77, 90.77,
90.77, 90.77, 90.77), value_3 = c(NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_)), row.names = c(NA, -6L), class = "data.frame")

df2 <- structure(list(Code = c("HA09U", "MB03L"), value_1 = c(90.35,
66.94), value_2 = c(89.84, 79.62), value_3 = c(90.07, 73.77)),
class = "data.frame", row.names = c(NA,
-2L))


text:
Q: How to draw an image directly to an ImageData array - HTML5/Javascript My problem:
I'm making an HTML5 game and am attempting to make it faster by drawing the background once instead of having it redrawn every frame.
To do this I drew the background on the canvas and then attempted to get an ImageData from it. Unfortunately I was stopped by a Security Error. Unable to, because the image is from an external source.
I've researched this and it seems that this is a "feature" to stop bad people from stealing content from the user's hard drive. Though these images I loaded aren't from the hard drive.
I would really love to be able to speed up my game. Is there a solution to go around the security error or maybe even to load the image directly into an image data so I can draw by looping through pixels?(Note: I do not want to have to mess with multiple canvases to get the job done)Thanks, Gan

A: There is no way around that, though you can draw an image from another domain the use of getImageData will always raise a security error in that situation. That is to prevent stealing of sensitive information since web sites can generate dynamic images containing private user information based on cookies or IP address. However, you could simply use a server side script to proxy the image.
But honestly getImageData and putImageData are fairly slow, I don't see how that could speed up your game. It seems to me that you think drawing an image data is faster than simply using drawImage, it's not.
You will have to redraw everything if you want your animation to look good anyway, that's the way animation works.