text:
Q: Mapping error in Elasticsearch? I have an index named againagain-* which was created by logstash. I did the
curl command

before I ran the config file into logstash. However after all these steps, I went into Discover tab in Kibana but all the strings are still deemed as True under the "Analzyed Fields". Is there something wrong with my mapping?
P.S I did it before and after I ran my config file too.
    curl –XPUT http://localhost:5601/againagain -d '
{
 "mappings" : {
  "_default_" : {
   "properties" : {
"service" : { "type" : "integer" },
"rule" : { "type" : "integer" },
"ICMP Type" : { "type" : "integer" },
"ICMP Code" : { "type" : "integer" },
"ip_offset" : { "type" : "integer" },
"ip_id" : { "type" : "integer" },
"ip_len" : { "type" : "integer" },
"Confidence Level" : { "type" : "integer" },
"fragments_dropped" : { "type" : "integer" },
"Severity" : { "type" : "integer" },
"serial_num" : { "type" : "integer" },
"during_sec" : { "type" : "integer" },
"Attack info" : {"type": "string", "index" : "not_analyzed" },
"peer gateway" : {"type": "string", "index" : "not_analyzed" },
"SmartDefense Profile" : {"type": "string", "index" : "not_analyzed" },
"FollowUp" : {"type": "string", "index" : "not_analyzed" },
"attack" : {"type": "string", "index" : "not_analyzed" },
"type" : {"type": "string", "index" : "not_analyzed" },
"Performance Impact" : {"type": "string", "index" : "not_analyzed" },
"reject_category" : {"type": "string", "index" : "not_analyzed" },
"action" : {"type": "string", "index" : "not_analyzed" },
"ICMP" : {"type": "string", "index" : "not_analyzed" },
"inzone" : {"type": "string", "index" : "not_analyzed" },
"dn" : {"type": "string", "index" : "not_analyzed" },
"proto" : {"type": "string", "index" : "not_analyzed" },
"dst" : {"type": "string", "index" : "not_analyzed" },
"message_info" : {"type": "string", "index" : "not_analyzed" },
"ICMP" : {"type": "string", "index" : "not_analyzed" },
"Severity" : {"type": "string", "index" : "not_analyzed" },
"rule_uid" : {"type": "string", "index" : "not_analyzed" },
"CookieI" : {"type": "string", "index" : "not_analyzed" },
"interface" : {"type": "string", "index" : "not_analyzed" },
"IKE" : {"type": "string", "index" : "not_analyzed" },
"TCP packet out of state" : {"type": "string", "index" : "not_analyzed" },
"service_id" : {"type": "string", "index" : "not_analyzed" },
"vpn_feature_name" : {"type": "string", "index" : "not_analyzed" },
"Protection Type" : {"type": "string", "index" : "not_analyzed" },
"src" : {"type": "string", "index" : "not_analyzed" },
"ip_len" : {"type": "string", "index" : "not_analyzed" },
"fw_subproduct" : {"type": "string", "index" : "not_analyzed" },
"protection_id" : {"type": "string", "index" : "not_analyzed" },
"Protection Name" : {"type": "string", "index" : "not_analyzed" },
"tcp_flags" : {"type": "string", "index" : "not_analyzed" },
"Internal_CA" : {"type": "string", "index" : "not_analyzed" },
"outzone" : {"type": "string", "index" : "not_analyzed" },
"scheme" : {"type": "string", "index" : "not_analyzed" },
"Reason" : {"type": "string", "index" : "not_analyzed" },
"message" : {"type": "string", "index" : "not_analyzed" },
"product" : {"type": "string", "index" : "not_analyzed" },
"Industry Reference" : {"type": "string", "index" : "not_analyzed" }
   }
  }
 }
}
';

The output they gave me in Terminal after this command is  <.!DOCTYPE html.><.html.><.head.><.title.><.link rel="stylesheet" href="/styles/main.css".><./head.><.body.><.h1>Not Found<./h1><./body.><./html.">kibana"

A: Like i said in the comment, you are trying put your mapping on the kibana port (5601) instead of the elasticsearch port (9200, by the default).
curl -XPUT "http://localhost:9200/againagain/" -d'
{
  "mappings": {
    "_default_": {
      "properties": {
        "service": {
          "type": "integer"
        },
        "rule": {
          "type": "integer"
        },
        "ICMP Type": {
          "type": "integer"
        },
        "ICMP Code": {
          "type": "integer"
        },
        "ip_offset": {
          "type": "integer"
        },
        "ip_id": {
          "type": "integer"
        },
        "ip_len": {
          "type": "string",
          "index": "not_analyzed"
        },
        "Confidence Level": {
          "type": "integer"
        },
        "fragments_dropped": {
          "type": "integer"
        },
        "Severity": {
          "type": "string",
          "index": "not_analyzed"
        },
        "serial_num": {
          "type": "integer"
        },
        "during_sec": {
          "type": "integer"
        },
        "Attack info": {
          "type": "string",
          "index": "not_analyzed"
        },
        "peer gateway": {
          "type": "string",
          "index": "not_analyzed"
        },
        "SmartDefense Profile": {
          "type": "string",
          "index": "not_analyzed"
        },
        "FollowUp": {
          "type": "string",
          "index": "not_analyzed"
        },
        "attack": {
          "type": "string",
          "index": "not_analyzed"
        },
        "type": {
          "type": "string",
          "index": "not_analyzed"
        },
        "Performance Impact": {
          "type": "string",
          "index": "not_analyzed"
        },
        "reject_category": {
          "type": "string",
          "index": "not_analyzed"
        },
        "action": {
          "type": "string",
          "index": "not_analyzed"
        },
        "ICMP": {
          "type": "string",
          "index": "not_analyzed"
        },
        "inzone": {
          "type": "string",
          "index": "not_analyzed"
        },
        "dn": {
          "type": "string",
          "index": "not_analyzed"
        },
        "proto": {
          "type": "string",
          "index": "not_analyzed"
        },
        "dst": {
          "type": "string",
          "index": "not_analyzed"
        },
        "message_info": {
          "type": "string",
          "index": "not_analyzed"
        },
        "rule_uid": {
          "type": "string",
          "index": "not_analyzed"
        },
        "CookieI": {
          "type": "string",
          "index": "not_analyzed"
        },
        "interface": {
          "type": "string",
          "index": "not_analyzed"
        },
        "IKE": {
          "type": "string",
          "index": "not_analyzed"
        },
        "TCP packet out of state": {
          "type": "string",
          "index": "not_analyzed"
        },
        "service_id": {
          "type": "string",
          "index": "not_analyzed"
        },
        "vpn_feature_name": {
          "type": "string",
          "index": "not_analyzed"
        },
        "Protection Type": {
          "type": "string",
          "index": "not_analyzed"
        },
        "src": {
          "type": "string",
          "index": "not_analyzed"
        },
        "fw_subproduct": {
          "type": "string",
          "index": "not_analyzed"
        },
        "protection_id": {
          "type": "string",
          "index": "not_analyzed"
        },
        "Protection Name": {
          "type": "string",
          "index": "not_analyzed"
        },
        "tcp_flags": {
          "type": "string",
          "index": "not_analyzed"
        },
        "Internal_CA": {
          "type": "string",
          "index": "not_analyzed"
        },
        "outzone": {
          "type": "string",
          "index": "not_analyzed"
        },
        "scheme": {
          "type": "string",
          "index": "not_analyzed"
        },
        "Reason": {
          "type": "string",
          "index": "not_analyzed"
        },
        "message": {
          "type": "string",
          "index": "not_analyzed"
        },
        "product": {
          "type": "string",
          "index": "not_analyzed"
        },
        "Industry Reference": {
          "type": "string",
          "index": "not_analyzed"
        }
      }
    }
  }
}'

A: So your question earlier is spot on.  You need your index to be empty first.  So curl your mapping and THEN send your data in using logstash.  I'm not sure if it's required but you might want to clear your mappings in elasticsearch when you delete your index.  I've run into the same issue before.  There might be easier methods but I just delete everything, put in my mapping, then import data and I've always been good to go.


text:
Q: how to add an json object as an element to another json i create a json object by a script with jq.
jq -n --arg date "$DATE" --arg script "$SCRIPT" --arg log_level "$LOG_LEVEL" --arg ppid "$PPID" --arg message "$MESSAGE" '{"t":$date, "service":$script, "level":$log_level, "pid":$ppid, "message":$message}'

The Variable log_level and message are provided by another script and in message there can be stored a plain string or a json string.
Example Json String:
{"text":"value", "text2":"value2"}

Output if a a plain string is provided:
{
  "t": "2017-10-12 16:52:26",
  "service": "import.sh",
  "level": "INFO",
  "pid": "23425",
  "message": "START"
}

Output if a json object is provided:
{
    "t": "2017-10-12 17:01:16",
    "service": "import.sh",
    "level": "INFO",
    "pid": "13069",
    "message": "{\"text\":\"value\", \"text2\":\"value2\"}"
}

What i expected if i provide the json object:
{
    "t": "2017-10-12 17:01:16",
    "service": "cis_import.sh",
    "level": "INFO",
    "pid": "13069",
    "message": {
        "text": "value",
        "text2": "value2"
    }
}

Am i right that jq add the \ for each " because it gets added to the json object like it would be a simple string?
How can i get my expected json?

A: Got it finally. Thanks for the hints chepner
and blusky
To validate if $MESSAGEis a json i use jq -n $MESSAGE see jq manual instead of jq . /path/to/file.json
To use the mentioned --argjson i will add " around $MESSAGEif the $MESSAGE is a plain string MESSAGE="\"$MESSAGE\"". I do this with DATE, SCRIPT, LOG_LEVEL, PPID too.
Command to create the json object looks like this:
jq -cn --argjson date "$DATE" --argjson script "$SCRIPT" --argjson log_level "$LOG_LEVEL" --argjson  ppid "$PPID" --argjson message "$MESSAGE" '{"t":$date, "service":$script, "level":$log_level, "pid":$ppid, "message":$message}'

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP echo the html tag is not at the corresponding place There is two php file
The first php is header.php

    <?php
    function setLink($link,$title){
        echo "$title";
    }
    ?>

The second is index.php

<?php
    require_once ('header.php');
    setLink("#goal","title1");
    setLink("#history","title2");
?>

<?php require_once ('footer.php'); ?>

The setLink() is to echo the html tag, I thought the result will be :

title1....

However, it actually turn out to be:

..
title1

Why is that and how to fix? Thanks for helping
Update:
Also , The setLink should be able to call in different php
e.g. for the product.php , I can call setLink("#product","product");
Thanks

A: You are defining setlink in the header, but where you define the function is irrelevant to where the link appears.
You are calling setlink in a location that is where the link is appearing.
Modify your code as follows:
header.php
<?php
    function setLink($link,$title){
        echo "$title";
    }
?>

    <?php setLink("#goal","title1");
          setLink("#history","title2"); ?>

index.php

<?php
    require_once ('header.php');
    // Do not call setLink here, it's called in the header include....
?>

<?php require_once ('footer.php'); ?>

A: You should call the function to the place at which you want to print the data. You can define the function wherever you want in the document.
I have rewritten your code.
<?php
    function setLink($link,$title){
        echo "$title";
    }
?>

    <?php
        setLink("#goal","title1");
        setLink("#history","title2");
    ?>

The second is index.php

<?php
    require_once ('header.php');
?>

<?php require_once ('footer.php'); ?>

A: You defined function instead of calling it.
Change the code as below for header.php:

    <?php
     setLink("#goal","title1");
     setLink("#history","title2");
    ?>

You can define function setlink in index.php. Place the function definition anywhere in the file, for example at the bottom of the index.php

<?php
    require_once ('header.php');
?>

<?php require_once ('footer.php'); ?>

<?php
 function setLink($link,$title){
      echo "$title";
 }
?>


text:
Q: Updating timestamps on attaching/detaching Eloquent relations I'm using Laravel 4, and have 2 models:
class Asset extends \Eloquent {
    public function products() {
        return $this->belongsToMany('Product');
    }
}

class Product extends \Eloquent {
    public function assets() {
        return $this->belongsToMany('Asset');
    }
}

Product has the standard timestamps on it (created_at, updated_at) and I'd like to update the updated_at field of the Product when I attach/detach an Asset.
I tried this on the Asset model:
class Asset extends \Eloquent {
    public function products() {
        return $this->belongsToMany('Product')->withTimestamps();
    }
}

...but that did nothing at all (apparently). Edit: apparently this is for updating timestamps on the pivot table, not for updating them on the relation's own table (ie. updates assets_products.updated_at, not products.updated_at).
I then tried this on the Asset model:
class Asset extends \Eloquent {
    protected $touches = [ 'products' ];

    public function products() {
        return $this->belongsToMany('Product');
    }
}

...which works, but then breaks my seed which calls Asset::create([ ... ]); because apparently Laravel tries to call ->touchOwners() on the relation without checking if it's null:

PHP Fatal error:  Call to undefined method Illuminate\Database\Eloquent\Collection::touchOwners() in /projectdir/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 1583

The code I'm using to add/remove Assets is this:
Product::find( $validId )->assets()->attach( $anotherValidId );
Product::find( $validId )->assets()->detach( $anotherValidId );

Where am I going wrong?

A: You can do it manually using touch method:
$product = Product::find($validId);
$product->assets()->attach($anotherValidId);
$product->touch();

But if you don't want to do it manually each time you can simplify this creating method in your Product model this way:
public function attachAsset($id)
{
    $this->assets()->attach($id);
    $this->touch();
}

And now you can use it this way:
Product::find($validId)->attachAsset($anotherValidId);

The same you can of course do for detach action.
And I noticed you have one relation belongsToMany and the other hasMany - it should be rather belongsToMany in both because it's many to many relationship
EDIT
If you would like to use it in many models, you could create trait or create another base class that extends Eloquent with the following method:
public function attach($id, $relationship =  null)
{
    $relationship = $relationship ?: $this->relationship;
    $this->{$relationship}()->attach($id);
    $this->touch();
}

Now, if you need this functionality you just need to extend from another base class (or use trait), and now you can add to your Product class one extra property:
private $relationship = 'assets';

Now you could use:
Product::find($validId)->attach($anotherValidId);

or
Product::find($validId)->attach($anotherValidId, 'assets');

if you need to attach data with updating updated_at field. The same of course you need to repeat for detaching.

A: From the code source, you need to set $touch to false when creating a new instance of the related model:
Asset::create(array(),array(),false);

or use:
$asset = new Asset;
// ...
$asset->setTouchedRelations([]);
$asset->save();

A: Solution:
Create a BaseModel that extends Eloquent, making a simple adjustment to the create method:
BaseModel.php:
class BaseModel extends Eloquent {
    /**
     * Save a new model and return the instance, passing along the
     * $options array to specify the behavior of 'timestamps' and 'touch'
     *
     * @param  array  $attributes
     * @param  array  $options
     * @return static
     */
    public static function create(array $attributes, array $options = array())
    {
        $model = new static($attributes);
        $model->save($options);
        return $model;
    }
}

Have your Asset and Product models (and others, if desired) extend BaseModel rather than Eloquent, and set the $touches attribute:
Asset.php (and other models):
class Asset extends BaseModel {
    protected $touches = [ 'products' ];
    ...

In your seeders, set the 2nd parameter of create to an array which specifies 'touch' as false:
Asset::create([...],['touch' => false])

Explanation:
Eloquent's save() method accepts an (optional) array of options, in which you can specify two flags: 'timestamps' and 'touch'. If touch is set to false, then Eloquent will do no touching of related models, regardless of any $touches attributes you've specified on your models. This is all built-in behavior for Eloquent's save() method.
The problem is that Eloquent's create() method doesn't accept any options to pass along to save(). By extending Eloquent (with a BaseModel) to accept the $options array as the 2nd attribute, and pass it along to save(), you can now use those two options when you call create() on all your models which extend BaseModel.
Note that the $options array is optional, so doing this won't break any other calls to create() you might have in your code.


text:
Q: Оптимизация запроса sql / кода java Доброго времени суток.
Есть проблема, которую не могу решить уже второй день. Написал приложение, которое парсирует из XML файла данные и записывает их в БД. Все как бы работает, но время записи одного файла XML (размером 15 килобайт) занимает около 3 минут. А файлы будут и по 10 мегабайт и по 20.
Всего в коде у меня 3 метода, в которых я записываю данные в БД. Вот пример одного метода:
public void insertToPhoto(String id_photo, int id_phototype , int maxzoomlevel, int width, int height, int angle, String id_stage) throws SQLException {

          Connection conn = null;
          PreparedStatement pstmt = null;
            try {
              conn = getConnection();
              String query = "insert into photos(id_photo, id_phototype, maxzoomlevel, width, height, angle, id_stage) values(?,?,?,?,?,?,?)";
              pstmt = conn.prepareStatement(query); // create a statement
              pstmt.setString(1, id_photo); // set input parameter
              pstmt.setInt(2, id_phototype); // set input parameter
              pstmt.setInt(3, maxzoomlevel); // set input parameter
              pstmt.setInt(4, width); // set input parameter
              pstmt.setInt(5, height); // set input parameter
              pstmt.setInt(6, angle); // set input parameter
              pstmt.setString(7, id_stage); // set input parameter

              pstmt.executeUpdate();
              conn.commit();
            }
            catch (Exception e) {
                if(conn != null){
                    try{
                        conn.rollback();
                    }
                    catch(SQLException ex){

                    }
                }

            } finally {

                conn.setAutoCommit(true);
            }
      }

И таких их 3. Данные их XML файла я записываю в List<>. После всего этого я при помощи for(obj x: list) вытягиваю данные и записываю их в БД.  Вот кусочек кода:
for(Datenstrom x: datList){
                for(WGS y: x.getWgs()){
                    for(Bilder bil: x.getBilder()){
                        idUUIDStage = mq.getUUID();
                        con.insertToStage(idUUIDStage, bil.getNr(), todayq, todayq, Integer.parseInt(con.getIDSection(Integer.toString(x.asb.getVnk()), Integer.toString(x.asb.getNnk()))), y.getStation(), 0.0, 0.0, 0, x.zuordnung.getFS());

                    }
                }

                for(Bilder bilder: x.getBilder()) {

                    idUUIDPhoto = mq.getUUID();

                    Image im = new Image(bilder.getD());

                    con.insertToPhoto(idUUIDPhoto, bilder.getNr(), im.getCountZoom(), Image.widthImage(), Image.heightImage(), 50, con.getIDStage(bilder.getStation()));

            }

Как мне оптимизировать все это, что бы процесс записи в БД проходил быстрее ? Где я сделал не правильно и что можно было бы изменить ?

A: Ну примерно так:
conn = getConnection();
conn.setAutoCommit(false);
try {
    ...
    stmt1.execute();
    ...
    stmt2.execute();
    conn.commit();
} catch (Exception e) {
    conn.rollback();
}

Неплохо было бы ещё стейтменты закрыть.

A: Главная идея — это убрать conn.commit();
Для этого желательно взять одно подключение к базе, поставить у него setAutoCommit(false);, навставлять строк в базу.
При этом учтите, что если вы сделаете rollback, то откатятся все вставки: тут надо понять, что плохого в том, что какая-то запись не вставилась.
Ну и в конце только commit();
А еще меня смущают два цикла по getBilder,
Имхо, с этим можно что-то сделать, и con.getIDStage, я думаю, тоже можно убрать.

A: Лучше всего писать в базу не построчно, а балково. Как это делается на plain JDBC - честно, не помню.
Как вариант, использовать спринговые JdbcTemplate и его API (пример: класс SimpleJdbcInsert#executeBatch). Ну и тогда без проблем можно коммитить, например, каждые N-записей


text:
Q: Преобразование кода в символы Как преобразовать код в символы, уже только какие костыли не приделал все равно что то да не работает
Пробовал так..
namespace test
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            //1 вариант
            string[] arrayCode = {"6c", "52"};
            Console.WriteLine (Encoding.GetString(BitConverter.GetBytes(Convert.ToInt32(arrayCode[0]))));
            //2 вариант
            Encoder.ToChar(arrayCode[i]);
         }
    }
}

Выдает ошибку
1) an object reference is required to access non-static member
2) коды русских символов не помещаются в char, тут ошибка превышения размера

1 - Не понимаю что он хочет(
2 - Может это можно решить через char?

A: Например, так:
string[] arrayCode = {"6c", "52"};
var bytes = arrayCode.Select(s => Convert.ToByte(s, 16));
var result = Encoding.UTF8.GetString(bytes.ToArray());

(для UTF-8).

Если в строках не байты, а целые символы, по идее пойдёт такой код:
static void Main(string[] args)
{
    string[] arrayCode = {"6c", "52", "90d0"};
    var chars = arrayCode.Select(s => ExtractChar(s, Encoding.UTF8));
    var result = new string(chars.ToArray());
}

static char ExtractChar(string s, Encoding enc)
{
    var code = Convert.ToInt32(s, 16);
    var bytes = BitConverter.GetBytes(code);
    var nbytes = (s.Length + 1) / 2;
    var result = enc.GetString(bytes, 0, nbytes);
    if (result.Length != 1)
        throw new ArgumentException("В строке не один символ");
    return result[0];
}


text:
Q: Typescript type inference on dynamically accessed object properties interface CustomResponse {
    data: string;
    status: number;
    [key: string]: string | number;
}

const RESPONSE_PROPS = {
  DATA: "data",
  STATUS: "status",
};

const response: CustomResponse = {
    data: "test",
    status: 200,
};

let dataWrong: string = response[RESPONSE_PROPS.DATA];
let dataRight: string = response.data;

dataWrong gets the error
Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'

In cases like above, how to get dataWrong infer right type in typescript? Is type assertion (better type guards) the only way?

A: RESPONSE_PROPS.DATA is typed as string if you use an as const assertion (which will make the compiler keep the string literal type "data" for RESPONSE_PROPS.DATA) it works as expected:
interface CustomResponse {
    data: string;
    status: number;
    // [key: string]: string | number; not necessary for the code to work
}

const RESPONSE_PROPS = {
    DATA: "data",
    STATUS: "status",
} as const;

const response: CustomResponse = {
    data: "test",
    status: 200,
};

let dataWrong: string = response[RESPONSE_PROPS.DATA];
let dataRight: string = response.data;

Note: If the string literal type is used to index you don't really need the index signature.


text:
Q: Light attenuation strange behaviour I'm trying to implement a simple viewer and I was trying to implement light attenuation for point light.
The problem I have is the following:

I have that unnatural line going over the sphere.
The relevant code in shader is:
....
vec3 Ldist = uLightPosition-vPosition.xyz;
vec3 L = normalize(Ldist);
....
float NdotL = max(dot(N,L),0.0);

float attenuation = 1.0/ (Ldist*Ldist);

vec3 light = uAmbientColor;

if(NdotL>0.0){
    specularWeighting = rho_s * computeBRDF(roughness, Didx, Gidx, Fidx, L,  N,  V);
    light = light + NdotL*uLightColor*attenuation*(specularWeighting*specularColor*envColor.rgb + diffuseColor);
}

Being new to slightly more advanced lighting,  I really can't see what could be wrong.
(I know that maybe should be a different question, but being so small I was wondering if I could ask this here as well: is there are any rule of thumb to select the light and intensity position to have a nice result on a single object like the sphere up there?)

A: The following doesn't really make sense:
vec3 Ldist = uLightPosition-vPosition.xyz;
[...]
float attenuation = 1.0/ (Ldist*Ldist);

First of all, this shouldn't even compile, as Ldist is a vec3 and the * operator will do a component wise multiplication, leaving you whit a scalar divided by a vector. But apart from the syntax issues, and assuming that just len(LDist) was meant (which I will call d in the following), the attenuation term still does not make sense. Typically, the attenuation term used is
1.0/(a + b*d + c * d*d)

with a, b and c being the constant, linear and quadratric light attenuation coefficients, respectively. What is important to note here is that if the denominator of that equation becomes < 1, the "attenuation" will be aobve 1 - so the opposite effect is achieved. Since in a general scene, the distance can be as low as 0, the only way to  make sure that this will never happen is by setting a >= 1, which is typically done. So I recommend that you use at least 1.0/(1.0+d) as attenuation term, or add some constant attenuation coefficient in general.


text:
Q: In Java, get the style property used value or computed value of an element Is there any Java API which would take a html document and a css document as input and allow me to ask: give me the used value for property x for element with id y?
(Computed value would also be fine but used value even better).
(I would like to use a small subset of CSS2.1 as input to style an excel sheet).

A: I am not sure if there is any library like that but in order to achieve solution to your problem you can use a CSS Parser Simple API For CSS has many implementation, then you can do a query the parsed content for query. If you want to parse HTML also in Java then you can use apache HTML parser. Hope this helps.


text:
Q: Tap event testing with protractor and appium I have html with on-tap= doThis(). When going to test it with protractor and appium the .click event does not fire it off. It seems like a really simple thing to do, but yet I can not find any documentation on touch events for iOS appium. Does this have to do with the driver I am using?
// javascript
// assuming we have an initialized `driver` object for an app

driver.contexts().then(function (contexts) {

  return driver.context(contexts[1]); // choose the webview context
})

// do some web testing
.elementsByCss('.green_button').click()

.context('NATIVE_APP') // leave webview context

// do more native stuff here if we want

.quit() // stop webdrivage


text:
Q: Multiple NSObject Initialization Causes code to stop executing So I have a custom TVShow object that has some base fields like id, showName, airDate etc. which are all either NSStrings or NSIntegers and I am attempting to create a bunch of these objects via some data I have gotten from an API online.
So I loop through my NSArray of JSON data and create a TVShow object for each response:
TVShow *show = [[TVShow alloc] initWithData:[NSJSONSerialization JSONObjectWithData:data options:0 error:&error]];
[self.showArray addObject:show];

However, only 7 of these ever get created and then any code below this just ceases to run. I have a NSLog(@"Added"); printing after I create the show and it only gets called 6 times. If I add breakpoints after any of this code, they never get called. I'm not sure what's going on but it must be something to do with how I have set up my TVShow object?
It currently looks like:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface TVShow : NSObject

@property NSInteger showID;
@property NSString *showName;
@property NSString *airDate;
@property double rating;
@property NSString *imageUrl;
@property NSString *showSummary;
@property NSString *episodeSummary;
@property NSInteger season;
@property NSInteger episode;

- (id)initWithData:(NSDictionary *)data;

@end

and the .m file:
#import <UIKit/UIKit.h>
#import "TVShow.h"

@implementation TVShow

- (id)initWithData:(NSDictionary*)data {
    self = [super init];
    if(self) {

        [self buildObjectFromData:data];
    }
    return self;
}
-(void)buildObjectFromData:(NSDictionary*)data {
    NSDictionary *dict = [data objectForKey:@"_embedded"];
    NSDictionary *dict2 = [dict objectForKey:@"nextepisode"];
    NSDictionary *dict3 = [data objectForKey:@"image"];

    NSString *airDate = [dict2 valueForKey:@"airstamp"];
    NSInteger season = [[dict2 valueForKey:@"season"] integerValue];
    NSInteger episode = [[dict2 valueForKey:@"episode"] integerValue];
    NSString *episodeSummary = [dict2 valueForKey:@"summary"];
    NSString *showName = [data valueForKey:@"name"];
    NSString *showSummary = [data valueForKey:@"summary"];
    NSString *imageUrl = [dict3 valueForKey:@"medium"];
    NSInteger showID = [[data valueForKey:@"id"] integerValue];

    self.airDate = airDate;
    self.showName = showName;
    self.season = season;
    self.episode = episode;
    self.showSummary = [self stringByStrippingHTML:showSummary];
    self.episodeSummary = [self stringByStrippingHTML:episodeSummary];
    self.imageUrl = imageUrl;
    self.showID = showID;
}

-(NSString *) stringByStrippingHTML:(NSString*)string {
    NSRange r;
    NSString *s = string;
    while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        s = [s stringByReplacingCharactersInRange:r withString:@""];
    return s;
}

@end

If I create the object as just: [[TVShow alloc] init]; everything works fine, so it must be something wrong with this model is what I'm thinking. I'm unsure of what to try next, but any help would be greatly appreciated here.

A: Turns out there were cases that casued:
-(NSString *) stringByStrippingHTML:(NSString*)string {
    NSRange r;
    NSString *s = string;
    while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
        s = [s stringByReplacingCharactersInRange:r withString:@""];
    return s;
}

to go into infinite loops. Removing this snippet fixed the freeze.


text:
Q: SELinux prevents an android app from reading a serial device file I am using a Galaxy S5 (G900H) and I am connecting a serial device to it via USB using cdc-acm driver and trying to read it from my android application.
It works fine on other devices (older and newer).
When connecting the device, the device file /dev/ttyACM0 is created but when trying to read from it I receive an error Permission denied.
When running setenforce 0 and setting SELinux to Permissive mode - everything works fine and the app reads the device file successfully.
The dmesg says:
cdc_acm 2-1:1.0: usb_probe_interface
cdc_acm 2-1:1.0: usb_probe_interface
cdc_acm 2-1:1.0: This device cannot do calls on its own. It is not a modem.
cdc_acm 2-1:1.0: ttyACM0: USB ACM device

I tried making a new policy using audit2allow but couldn't find any "denied" message to use in order to create an "allow" rule.
Is there any way to use the device file via my app without setting SELinux to permissive? I can edit the kernel and make a new one if needed, but I really prefer not to.
Thanks!


text:
Q: Codeigniter Sessions not showing data I have the following error in my code:
1) the data i am storing over session is not showing up in view
2) the form validation set rules is not working.. The required is not working. Whenever i press login without entering any field it prints a.
I have auto loaded session and form validation.
Should I use php sessions or ci sessions?
Controller:
public function loginFormValidation()
      {
          $this->form_validation->set_rules('email','Username','required'); //not working
          $this->form_validation->set_rules('pass','Password','required');
          $this->form_validation->set_error_delimiters('
', '
');

          if($this->form_validation->run())
          {
              $email = $this->input->post('email');
              $pass = $this->input->post('pass');

              $this->load->model('loginModel');
              $result = $this->loginModel->loginValidation($email,$pass);

              $user_id = $result->user_id;
              $user_name = $result->user_name;
              $password = $result->password;

              $arrayDb = array(
                  'user_id' => $user_id,
                  'user_name' => $user_name,
                  'password' => $password,
              );

              $this->session->set_userdata('row', $arrayDb);

              header("location:".base_url()."/Users/dashboard");

          }
          else
          {
              echo "a";
          }
      }

Model:
class loginModel extends CI_Model
{
    public function loginValidation($email,$pass)
    {
        $q = $this->db->where(['email' => $email, 'password' => $pass])
            ->get('users');

        if($q->num_rows())
        {
            return $q->row();
        }
        else
        {
            return false;
        }
    }
}

Controller where i am printing it for testing:
class Users extends CI_Controller
{
    public function dashboard()
    {
        echo $this->session->userdata('user_name');  // Empty no data showing
        exit;
    }
}

A: Your code has a few errors and oversights.

*

*You should NEVER store plaintext passwords, let alone add them to a session variable. There is no need for that. Check out: http://php.net/manual/en/function.password-verify.php

*You need to check whether or not the login function actually returned data, otherwise just anyone can "login" as long as they pass form validation.

*You are setting session data with an array incorrectly according to the way you want to access the variables.

Controller:
public function loginFormValidation() {
    $this->form_validation->set_rules('email', 'Username', 'required');
    $this->form_validation->set_rules('pass', 'Password', 'required');
    $this->form_validation->set_error_delimiters('
', '
');

    if ($this->form_validation->run()) {
        $email = $this->input->post('email');
        $pass = $this->input->post('pass'); // do not store plaintext!!!

        $this->load->model('loginModel');
        $result = $this->loginModel->loginValidation($email, $pass);

        if ($result) {
            $user_id = $result->user_id;
            $user_name = $result->user_name;
            $password = $result->password;
            //https://www.codeigniter.com/user_guide/libraries/sessions.html#adding-session-data
            $arrayDb = array(
                'user_id' => $user_id,
                'user_name' => $user_name,
                'password' => $password, // why are you storing their PLAINTEXT password in a session?!
            );
            $this->session->set_userdata($arrayDb);
            header("location:" . base_url() . "/Users/dashboard");
        } else {
            echo 'login failed; bad username/password.';
        }
    } else {
        echo validation_errors();
    }
}

Model:
public function loginValidation($email, $pass) {
    $q = $this->db->where(['email' => $email, 'password' => $pass])
            ->get('users');
    if ($q->num_rows() == 1) {
        return $q->row();
    }
    return false;
}

Rather than reinventing the wheel check out: https://github.com/benedmunds/CodeIgniter-Ion-Auth
I personally use it an recommend it.


text:
Q: How/Where to optimise SSIS Package that causes sql queries to take extremely long to execute? I currently have a parent SSIS package that executes 4 child packages. Each child package transfers a table between source SQL server to a destination SQL server and executes the following SQL queries in the destination SQL server:

*

*Creation of Table

*Renaming of Tables

*Dropping of Table

I frequently encounter the following error "timeout expired.the timeout period elapsed prior to completion of the operation" and the SQL server becomes extremely slow and unresponsive in SSMS. However, this does not happen much if I execute only 2 child packages in parallel. How can I prevent this while executing more tasks in parallel? Where should I be looking to fix?

A: Does the parent package execute the childs simultaneously or one after another?
I think in a case where the childs are executed simultaneously, you can have issues with resource lock since you perform DDL queries.


text:
Q: Is there any way to parse and fetch color text data from JSON in kotlin? I am trying to parse and fetch data from JSON. But, I want at the place of color name respective color should be displayed.
e.g.
  {
        "id": 1,
        "name": rose,
        "color": "Red"
    },
    {
        "id": 2,
        "name": lily,
        "color": "White"
    }

So, at the place of text red: Red color and for white: White color and so on.

A: Try Color class method:
public static int parseColor (String colorString)

in android.

A: Add one more field in json which would contain hex color code.
{ "id": 1, "name": rose, "color": "Red" , "code" :"#ff0000" }, { "id": 2, "name": lily, "color": "White" , "code" :"#ffffff" }

Then parce this hex code using Color function parseColor.


text:
Q: React Native Gifted Chat on Expo on Android input is covered by keyboard I'm using a react-native gifted chat for my application chat. But the text input is covered by the keyboard so I can't see what I'm typing.
I'm using react-native version 0.60.10. Expo version 32.0.13. Android-based phone for testing. I tried solutions with keyboardAvoidingView and KeyboardSpacer but it still not working.
Looking forward hearing any advice.
Any advice would be very great.
This is screenshot
Source Code
render() {
    const {navigation} = this.props;
    return (
        <>
            <HeaderBack headerWrapper={{height: 80}} headerSubWrapper={{marginTop: 30}} navigation={navigation}/>
                <GiftedChat
                    style={{paddingHorizontal: 20}}
                    isTyping={true}
                    messages={this.state.messages}
                    onSend={messages => this.onSend(messages)}
                    user={{
                        _id: 1,
                    }}
                />
        </>
    );
}

A: Try this updated code
componentWillMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow',
                      this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide',
                      this._keyboardDidHide);

}

_keyboardDidShow = (e) => {
    let keyboardHeight = e.endCoordinates.height;
    this.setState({
        minInputToolbarHeight: keyboardHeight + 45,
    });
}

_keyboardDidHide = () => {
    this.setState({
        minInputToolbarHeight: 45,
    });
}

componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();

}

render() {
    const {navigation} = this.props;

    let platformConf = Platform.OS === 'android' ? {
        minInputToolbarHeight: this.state.minInputToolbarHeight,
        bottomOffset: 0,
    } : {};

    return (
        <GiftedChat
            style={{flex: 1}}
            messages={this.state.messages}
            onSend={messages => this.onSend(messages)}
            onInputTextChanged={(text) => this._checkForMentions(text)}
            keyboardShouldPersistTaps='never'
            {...platformConf}
            user={{
                        _id: 1,
                    }}/>
    );
}

If the above method does not working you can easily fix using react-native-keyboard-spacer Link
Also some users fix this by removing forceGetKeyboardHeight
More information


text:
Q: c++ namespace best practice dilemma I'm finding that what I've considered "best practice" for use namespace in c++ is hurting the readability of my code, and making me question how to use them well.
My program consists of a few different modules which are mostly built into libraries that the "main" application uses. Each library uses it's own namespace, and their namespaces are all "inside" a project namespace to help project against name conflicts with 3rd party code. So I end up with class names such as "myproject::logging::Logger" and "myproject::reporting::ReportType" (As made up examples).
So far so good. And in my .cpp files I have no problem. I use "using myproject::logging" at the top for example, and can cleanly refer to my Logging class. In the unlikely event of a conflict between two of my namespaces I can just explicitly say which one I want. This works well.
Header files are different though. It's considered bad practice to put using statements into header files as they will affect unrelated code that may not expect them. So I always fully qualify all the names in .hpp files. That was somewhat ugly but managable up to now so I've put up with it. But now I'm increasing using template code in my libraries which means that there is much more actual code in my .hpp files now. And having to fully qualify every name is making the code practically unreadable due to the length of type names.
I'm starting to feel that the benefits of namespaces and best practice for using them are beginning to be outweighed by the unreadablilty of the code I'm having to write. I'm starting to wonder if I would be better abandoning the use of namespaces to gain the benefit of more readable code and fixing any name conflicts if and when they appear.
An alternative is to use short, single layer namespaces so instead of "myproject::logging::Logger" I would merely have "log::Logger" which would help a lot but make the likelyhood of namespace conflicts much higher, and also have the namespaces convey less useful information.
As I've said, this only really affects code in .hpp files as I'm happily using "using namespace" in my implementation files to make this manageable, but it is becoming a problem as I look at my templated code in .hpp files now and think "eww...." which can't be good :P
Anyone got any practical advice?

A: Personally? I'd get rid of the "myproject" part. What is the chance that your library will use the exact same namespace name as another and have a symbol defined with the same name as another?
Also, I would suggest shorter names for namespaces you expect to be used in headers.

A: My experience have been that it is much more convenient to have one namespace for all your code for the reasons you mentioned in your original post. This namespace protects your identifiers from clashing with identifiers from 3rd-party libraries. Your namespace is your dominion and it is easy to keep it name-conflict-free.

A: Here's what I do.
In <mylibrary.h>:
namespace myproject {
  namespace mylibrary
  {
    namespace impl
    {
      using namespace otherlibrary;
      using namespace boost;
      using namespace std;
      using namespace whatever::floats::your::boat;

      class myclass;
      class myotherclass;
    };
    using impl::myclass;
    using impl::myotherclass;
  };
};

In the source:
#include <mylibrary.h>
using namespace myproject::mylibrary; //clean!

A: I have been in this situation before. It is often the case that a lot of template functions/classes in your headers are really "implementation", although by the nature of templates in C++ you are forced to put them in a header file. Thus, I just put everything in some "detail" or "implementation" namespace, where I can comfortably use "using namespace". At the end, I "drop" what people should use to the corresponding place. Like this:
namespace myproject { namespace somemodule {

namespace _implementation {

using namespace myproject::othermodule;
using namespace myproject::yetanothermodule;

template <...>
class some_internal_metafunction{
...
};

template <...>
class stuff_people_should_use_outside {
...
};

} // namespace implementation

using stuff_people_should_use_outside ;
}} // namespace myproject::somemodule

This approach might enlarge a bit the names on your compiler reports, though.
Alternatively, you can give up the modules namespaces. But it might not be a good idea for an extremely large project.

A: I use the following to get rid of enormous amounts of std:: in header file:
// mylibrary.h
namespace myproject {
  namespace mylibrary {
    namespace impl {

      using namespace std;

      namespace stripped_std {

        // Here goes normal structure of your program:
        // classes, nested namespaces etc.
        class myclass;
        namespace my_inner_namespace {
                ...
        }

       } // namespace stripped_std
    } // namespace impl

  using namespace impl::stripped_std;

  } // namespace mylibrary
} namespace myproject

// Usage in .cpp file
#include <mylibrary.h>
using namespace myproject::mylibrary;

It is similar to what was suggested by n.m., but with a modification:
there is one more auxiliary namespace stripped_std.
The overall effect is that line using namespace myproject::mylibrary; allows you to refer to the inner namespace structure, and at the same time it does not bring namespace std into library user's scope.

It's a pity though that the following syntax
using namespace std {
...
}

is not valid in C++ at the time when this post is written.

A: If your project isn't very very very huge (I mean, very huge), using only myproject should be sufficent. If you really want to divide your project into parts, you can use more generalized namespaces. For example, if I was building a game engine, I would go for namespaces like MyEngine::Core, MyEngine::Renderer, MyEngine::Input, MyEngine::Sound etc.


text:
Q: Issue with mustache template variables I have the following bit of json that is generated by the swagger codegen tool, this is the vendor extensions for a API operation:
  "vendorExtensions" : {
    "x-rate-limit" : [ {
      "name" : "max",
      "value" : 20,
      "description" : "The max amount of requests allowed within the period"
    }, {
      "name" : "period",
      "value" : 60,
      "description" : "The amount of seconds that we track the amount of requests made"
    } ]
  },

When trying to access these variables name and value in my mustache template is coming up blank:
    {{#vendorExtensions}}
    {{#x-rate-limit}}
    $values['{{name}}'] = {{value}};
    {{/x-rate-limit}}
    {{^x-rate-limit}}
    $values['max'] = RateLimiting::MAX_LIMIT;
    $values['period'] = RateLimiting::TIMEOUT;
    {{/x-rate-limit}}
    {{/vendorExtensions}}

On a path that doesn't have the x-rate-limit defined, it correctly prints the following
    $values['max'] = RateLimiting::MAX_LIMIT;
    $values['period'] = RateLimiting::TIMEOUT;

On a path that does have, it prints the following
    $values[''] = ;
    $values[''] = ;

If I print {{.}} inside the {{#x-rate-limit}} and {{/x-rate-limit}}, I get the following:
{"name":"max","value":20,"description":"The max amount of requests allowed within the period"}}

So it's correctly iterating over the array of objects, I'm able to print them out, but I can't access the items inside those objects.
Is there something that I'm missing here? Everything seems correct to me?

A: Try using this template:
{{#vendorExtensions.x-rate-limit}}
$values['{{name}}'] = {{value}};
{{/vendorExtensions.x-rate-limit}}
{{^vendorExtensions.x-rate-limit}}
$values['max'] = RateLimiting::MAX_LIMIT;
$values['period'] = RateLimiting::TIMEOUT;
{{/vendorExtensions.x-rate-limit}}


text:
Q: warning signs of a power supply going bad We recently have a computer with 3 out of 5 HD going bad (excessive bad sectors) within 1 week.  This got me to start thinking that maybe it's the power supply.  What are some warning signs / tricks to tell when the power supply is about to go?  before it completely stop working.
I read on another thread on SF about power supply tester.  It looks helpful if the PSU has a faulty rail, but will those catch intermittent errors that might happen before a supply goes bad?

A: What you need to catch are voltage drops and spikes, some less than 100ms long, and that over a period of serveral hours. That power supply tester won't catch those, and I don't know of any device that does.
You can hook up a sensitive voltmeter, if you can see the voltage vary there's definitely a problem, but it won't catch all problems.
There is also another possibility: you could have drives all from the same bad batch.
In this case I would take no chances. Replace the PSU and start transferring data to fresh drives.

A: If it's a "proper" server, monitor it! Most real servers have a Lights Out Management interface which is basically a small "computer"(TM) in your server, capable of monitoring sensors, voltages, power supplies, physical intrusion detection etc.

A: I hook my multimeter up to it (5 and 12V) it then records surges and brown outs if any.

A: Just to start, every time I have personally seen a a series of HDDs fail in rapid succession in one machine it has turned out to be caused by a bad power supply. So, I'd say don't stuff around: replace the PSU and all the HDDs (including the ones that are currently "fine") immediately.
One exception to this rule would be if all the HDDs are new(-ish) - in which case it could be a bad batch - but I'd still go ahead and replace the PSU (and of course HDDs) anyway.
Re the warning signs of a bad PSU, in my experience:

*

*failing component(s), often multiple components in a short space of time (like your HDDs)

*instability (most noticable if the system has been rock solid historically) - apps crashing, strange errors, hard-freezes, BSODs, etc.

*strange smells or sounds coming from the PSU

A: smell the exhaust coming out of the power supply.  If it smells like burnt coffee, one or more of the capacitors has blown.  Make sure the fan on the power supply is still running.  If it is reasonably old, replacing it with a new one is relatively cheap insurance.


text:
Q: Accessing the code section of a C++ program Based upon my understanding, a C/C++ program looks something like this in the memory:

I wanted to know the following :

*

*Can I access the "text section" of the running program? By accessing I mean printing
the start and end addresses and examining the contents.

*Can I relocate the "text section" to some other address in the memory at runtime?

Thanks,

A: It is operating system specific; I am answering for Linux only.
First your figure is grossly incorrect in practice, since most programs are dynamically linked to several shared object libraries (including libc6.so...). See also ld.so(8), elf(5), execve(2). There is no single text section (but many "text" like segments). Read about the pmap and objdump commands.
Then, you can understand the address space of a process of pid 1234 with cat /proc/1234/maps ; read more about proc(5)... From inside the program, read /proc/self/maps; for instance try cat /proc/$$/maps in a shell to show the address space of the shell process, and cat /proc/self/maps for the address space of the process running that cat command. See also mmap(2).
You cannot really "relocate" (you actually mean "move") the text section. Some addresses are built inside the code. However, read about the -fPIE option of gcc (for position independent executable ....).
Of course, you can access the symbols of a program (from inside) if you link it with the -rdynamic flag and if you use dlopen(3) (and dlsym and even perhaps dladdr....) with a NULL first filename argument.
See also wikipages about address space, virtual memory, ASLR, position independent code, relocation, ABI, JIT compilation, name mangling and the x86-64 ABI spec and the Advanced Linux Programming book.


text:
Q: Adminer denied acces for user sorry about my English, my knowledge about server is very small...
I have on my computer to install Mysql, Adminer, php-7.3 and Apache2. I to try a data bank to build, but to come to this warning,

Access denied for user 'me'@'localhost' to database 'mela'

mela is the new data bank which I to try to build, me is my username on
Adminer.
When login on Mysql with sudo mysql -u root,
in SELECT User,Host FROM mysql.user; I to come this,
SELECT User,Host FROM mysql.user;
    +------------------+-----------+
    | User             | Host      |
    +------------------+-----------+
    | root             | %         |
    | me               | localhost |
    | mysql.infoschema | localhost |
    | mysql.session    | localhost |
    | mysql.sys        | localhost |
    +------------------+-----------+

With sudo sudo journalctl -xe to come,

pam_unix(sudo:session): session opened for user root by (uid=0)

and with sudo systemctl -l status apache2.service

Jan 31 17:24:00 debian systemd1: Starting The Apache HTTP Server...
  Jan 31 17:24:00 debian systemd1: Started The Apache HTTP Server.

With sudo systemctl status mysql to come this image,
The image to show how started mysql
with Show grants; to come this image
what to come with this command
Can Please anyone explains me with easy words, where is my mistake?

A: As the error suggests the user "me" does not have permission on the database "mela"
To confirm this run the below command as the mysql user "me"
Show grants;
If the user has permission on the database it will be shown

A: With a new installation of Mysql and login as root, now can open a data bank on Adminer..., I to say my steps..., I am with Debian.
1 - Stopping Apache2
sudo systemctl stop apache2.service

2 - Remove all from Mysql on my computer
CAUTION: this may remove a bunch of other packages that any link to MySQL, read carefully what will be removed.
sudo apt-get remove --purge *mysql\*
sudo apt-get autoremove
sudo apt-get autoclean

3 - Because I delele all from MySQL, now install they...
sudo apt-get install mysql-server

4 - Also, install Mysqli, because I have php7.3 on my computer, I install Mysql with php7.3.
sudo apt-get install php7.3-mysqli

5 - Sometimes and I don know why..later to installed Mysql, to come this warning,

Connect Error: SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client

and as here to say, By default and for some reason, mysql 8 default plugin is auth_socket. Applications will most times expect to log in to your database using a password.
I do it, I login to Mysql, I give the root password which I wrote on my installation...
~$ mysql -u root -p

and write the command which him to say,
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';

6 - Restart Mysql,
sudo systemctl restart mysql

7 - Restart Apache2
sudo systemctl restart apache2.service

8 - On Adminer login window, login as root, and how the window to show, I can build the mela data bank...
window to show my mela data bank
@Abhijith, Thanks for your Answer, I wish your a nice day!


text:
Q: Typesetting poems I have ~250 poems to typeset, consisting of ~40 verses each. 99% are in this form:
line 1
line 2
line 3
line 4

line 5
line 6
line 7
line 8

...

The "source" of each poem is a PDF file which I use to copy / paste into a plain text file.
Now the task is to format these poems while avoiding too much markup. I could do this:
\begin{verse}
line 1 \\
line 2 \\
line 3 \\
line 4 \\
\end{verse}

\begin{verse}
line 5 \\
line 6 \\
line 7 \\
line 8 \\
\end{verse}

But I much prefer not adding \begin{verse} and \end{verse} around each verse and I would like to avoid the double backslash at the end of each line. What can I do?
Some "rules"

*

*No page break is allowed inside a 4 line verse

*I want to avoid markup, but if it's not possible, its OK to add markup

*All exceptions are handeld manually

*No other special formatting is required (each of the four lines are flush left and ragged right, no automatic line breaking

*Some poems should be mulitcolumn, if feasible

*Each poem is in its own file, having a \title{...} and a \date{...} before it starts (I could put this somewhere else though).

A: Add the following to your preamble and you don't need to type any mark-up:
\documentclass{article}
\makeatletter
\newdimen\allttindent \allttindent=0pt % set this to change the indent

\def\docspecials{\do\ \do\$\do\&%
  \do\#\do\^\do\^^K\do\_\do\^^A\do\%\do\~}

\def\alltt{\trivlist \item[]\if@minipage\else\vskip\parskip\fi
\leftskip\@totalleftmargin  \advance\leftskip\allttindent \rightskip\z@
\parindent\z@\parfillskip\@flushglue\parskip\z@
\@tempswafalse \def\par{\if@tempswa\hbox{}\fi\@tempswatrue\@@par}
\obeylines \tt \catcode``=13 \@noligs
\let\do\@makeother \docspecials
 \frenchspacing\@vobeyspaces}

\let\endalltt=\endtrivlist
\AtBeginDocument{\alltt}
\AtEndDocument{\endalltt}
\makeatother

\begin{document}
There was an old woman of 92
Parlez-vous
There was an old woman of 92
Parlez-vous
There was an old woman of 92
Did a fart and away it flew
Inky pinky parlez-vous

The fart went rolling down the street
Knocked a copper off his feet

The copper got out his rusty pistol
Blew the fart right on to Bristol

The people of Bristol were having a dance
The fart went rolling on to France

The people of France were not at home
The fart went rolling on to Rome
\end{document}

It does not do the multicolumn but it maybe possible to trigger a multicolumn based on a word of the poem. Let me know the word and maybe egreg can come up with a macro for that! The preamble is borrowed from alltt2.

A:
\documentclass[twocolumn]{article}

\textheight.5\textheight

\begingroup
\makeatletter
\catcode13\active%
\gdef\verseinput#1{%
{%
\interlinepenalty\@M%
\def^^M{\@ifnextchar^^M\par{\ifhmode\break\fi}}%
\rightskip\fill%
\parindent\z@%
\parskip\baselineskip%
\raggedbottom%
\catcode13\active\input{#1}%
\par%
}}%
\endgroup%
\begin{document}

\verseinput{v1.txt}

\end{document}

line 1
line 2
line 3
line 4

line 5
line 6
line 7
line 8

line 9
line 10
line 11
line 12

line a9
line a10
line a11
line a12

line b9
line b10
line b11
line b12

line a9
line a10
line a11
line a12

line b9
line b10
line b11
line b12

line a9
line a10
line a11
line a12

line b9
line b10
line b11
line b12

line a9
line a10
line a11
line a12

line b9
line b10
line b11
line b12

line a9
line a10
line a11
line a12

line b9
line b10
line b11
line b12

A: An alternative option is to convert the plain text poems to the verse environment using another program. This method has the advantage that you could use it to automate the processing of poems from different files or from a database.
To prevent page breaks inside verses the following answer may be relevant: https://tex.stackexchange.com/a/21985/7092
As an example of the conversion, here's a simple tool using JavaScript with that performs this task. Here I consider a verse as any number of lines separated by a single line breaks. Save the code below as an html file to use it.

<html>
<head>
<title>Verses!</title>

<script>
function convertVerses()
{
    var input = document.getElementById('input').value
    var lines = input.split(/\r?\n/);
    var env = "verse"
    var output = "";
    for (var i = 0;i < lines.length;i++)
    {
        if (!lines[i].match(/^[ \t\n]*$/))
        {
         //   alert(lines[i])
        // no empty line
            if (lines.length==1 ||
              (i==0 && lines[i+1].match(/^[ \t\n]*$/)) ||
                (i==lines.length && lines[i-1].match(/^[ \t\n]*$/)) ||
                (lines[i-1].match(/^[ \t\n]*$/) && lines[i+1].match(/^[ \t\n]*$/))) {
                // only line of verse
                output += '\\begin\{'+env+'\}\n' + lines[i] + '\n\\end\{'+env+'\}\n\n';
            } else  if (i==0 || lines[i-1].match(/^[ \t\n]*$/)) {
                // first line of verse
                output += '\\begin\{'+env+'\}\n' +lines[i] + '\\\\\n';
            } else if (i==lines.length || lines[i+1].match(/^[ \t\n]*$/))  {
                // last line of verse
                output += lines[i] + '\n\\end\{'+env+'\}\n\n';
            } else {
                // any other line of the verse
                output += lines[i] + '\\\\\n';
            }
        }
    }
    document.getElementById('output').value = output;
}

</script>

<style>
textarea {width:700px;height:330px;display:block;margin:10px}
button {width:700px;height:50px;margin:10px}
</style>
</head>

<body>
<textarea id="input">
p0

p1
p2
p3

p5
p6

p9
</textarea>
<button onclick="convertVerses()"> Convert!</button>
<textarea id="output">
</textarea>
</body>
</html>


text:
Q: Record and replay input using list of timestamps i'm trying to record player input and play it back. i'm doing this by making a list in which i add the current frame every time the player clicks. when i play it back, i compare the list to the current frame. when the frame the player clicked is equal to the current playback frame, an action will happen.
public float recordingFrames;
public float playbackFrames;
public List<float> clickFrames;
public bool recording;
public bool playing;

if (recording)
{
    recordingFrames += Time.deltaTime;
    if (Input.GetMouseButton(0))
    {
        clickFrames.Add(recordingFrames);
    }
}

if (playback)
{
    playbackFrames += Time.deltaTime;
    for (int i = 0; i < clickFrames.Count; i++)
    {
        if (clickFrames[i] == playbackFrames)
        {
            Debug.Log("hello!")
        }
    }
}

the debug log is never received. how can i fix this? thank you!

A: There's no reason to expect Time.deltaTime to be constant. You are probably never going to get the same cumulative amount of time this way. You are better off clicking as long as the next timestamp is less than or equal to the current timestamp, and keeping track of where you are in the list of clickFrames accordingly.
This also lets you avoid iterating through the while clickFrames list every frame:
public float recordingFrames;
public float playbackFrames;
public List<float> clickFrames;
public bool recording;
public bool playing;
public int nextClickFrameIndex;

public void BeginPlayback()
{
    nextClickFrameIndex = 0;
    playback = true;
}

public void InputRecordPlayback()
{
    if (recording)
    {
        recordingFrames += Time.deltaTime;
        if (Input.GetMouseButton(0))
        {
            clickFrames.Add(recordingFrames);
        }
    }

    if (playback)
    {
        playbackFrames += Time.deltaTime;

        // loop while you have clicks left in the replay
        // AND you have clicks to playback since the last frame
        while (
                nextClickFrameIndex < playBackFrames.Count
                && clickFrames[nextClickFrameIndex] <= playbackFrames
                )
        {
            nextClickFrameIndex++;
            Debug.Log("hello!");
        }
    }
}


text:
Q: Trouble with AJAX, JS, and Select2 I apologize if I am doing something stupid, but I am brand new to Select2 and Ajax and am having a hell of a time trying to get this work.  I am attempting to create my own json file (link removed) to use with a form (link removed) I am building.  Using Firefox Lite in Chrome, I am able to get a response from my server (200 OK), but the select box does not display the search results. My json file appears to validate correctly using http://jsonformatter.curiousconcept.com.  You can also see it at
Any thoughts or tips?
json.php source:
<?
    $myArray = array(
            array( "id" => "id1", "text" => "title1" ),
            array( "id" => "id2", "text" => "title2" )
            );

    echo json_encode($myArray);

?>

select.php source:

    <link href="select2/select2.css" rel="stylesheet"/>

original example (works)

    <input type="hidden" class="bigdrop" id="e6" style="width: 600px; display: none;">

my version (does not work)

    <input type="hidden" class="bigdrop" id="e6a" style="width: 600px; display: none;">

A: You are calling your url (willwelch.net) as a jsonp call. In your php, you must capture the param callback passed by the ajax call, and wrap the result in a function call, with the function name = the contents of the callback parameter.
So the call to your php might be:
 http://willwelch.net/play/nhs/pstudents/json.php?callback=myfunc

And what you should return is:
 myfunc([{"id":"id1","text":"title1"},{"id":"id2","text":"title2"}])

Note the ajax call will add the callback param automatically.
Edit
Also you need to change your return method to add data as an input parameter:
         results: function (data) { // parse the results into the format expected by Select2.
               return {results: data};
         }


text:
Q: How to justify to create sub-models by slice of population? I'm in charge of a scoring project and I'm getting average results with my binary classification model.
A large number of reasons could explain this, but I think one of them is the heterogeneity of the population in my training dataset. I think that giving up on this global model for more specific sub-models could help improving the results.
For example : If we were in a retail company trying to find the best advertizing chanel, we could try to build a model for people shopping on stores and another one for people shopping online.
My question then is : What would you do to justify such sub-models approach ? I have a panel of 4/5 variables being regurlaly used for business strategies potentially with a good discriminatory power. My idea would be to use them to prove that somehow clients shopping only online are so different from the others that they should have their own model.
I read about some technics like T-SNE or Mapper Algorithm (I know of course about the more traditional ones). These technics are well documented online, but I hardly find their implementation for my use case.
I also thought about
Thank you for your help !

A: If there exists a subgroup that differs from the rest of the data, you should be able to identify it using exploratory data analysis. Create plots and calculate descriptive statistics per each subgroup. Are there any visible differences? How do they compare to the same plots and statistics calculated on the whole dataset? If there is a clear subgroup, in many cases it would be also detected if you used some clustering algorithm on the data.
However, you seem to be interested in predictive performance, so why not just train a model on the whole data, and models for subgroups, and compare their performance? For the subgroups, you would simply have a model per subgroup and use it for making predictions for the subgroup, and then concatenate all the predictions, so that they can be compared as a whole to the global model.
Finally, there are models that can account for the clustering in the data. In the case of some models, this can be handled by using a dummy variable for the subgroups, so that the model can figure out how to account for the differences. There are models designed for such nesting like mixed-model. If you don't know the exact groups and you need to cluster the data, there are models that can cluster your data and find a sub-model for each cluster.


text:
Q: ASP.Net 2012 Unobtrusive Validation with jQuery: What now? the first thing that you would like to answer is : refer to this post:
ASP.Net 2012 Unobtrusive Validation with jQuery
Now, I have the same problem and I have used the fix which works for me:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

Noting that I know very little about ASP and .NET, how safe/advised is it to disable Unobtrusive Validation ?
Will it break anything? Is it a weak fix for the problem?
Thank you

A: I think your answer is in:
What's New in ASP.NET 4.5 and Visual Studio 2012
I am copying the relevant text below:

Unobtrusive Validation
You can now configure the built-in validator controls to use
  unobtrusive JavaScript for client-side validation logic. This
  significantly reduces the amount of JavaScript rendered inline in the
  page markup and reduces the overall page size. You can configure
  unobtrusive JavaScript for validator controls in any of these ways:

*

*Globally by adding the following setting to the <appSettings> element in the Web.config file:

*Globally by setting the static System.Web.UI.ValidationSettings.UnobtrusiveValidationMode property
  to UnobtrusiveValidationMode.WebForms (typically in the
  Application_Start method in the Global.asax file).

*Individually for a page by setting the new UnobtrusiveValidationMode property of the Page class to
  UnobtrusiveValidationMode.WebForms.

In this blog: Jupaol's coding adventures. I found:
In order to fix the previous exception, we need to install the following Nuget packages:

*

*jQuery

*ASPNET.ScriptManager.jQuery

*Microsoft.AspNet.ScriptManager.MSAjax

*Microsoft.AspNet.ScriptManager.WebForms

Also there is a detail of the code added by these Nuget packages.


text:
Q: Guardar fichero en el escritorio FPDF Estoy intentando que FPDF me guarde el archivo directamente en el escritorio pero no lo consigo, me lo sigue guardando en la carpeta descargas y me pone como nombre del fichero la ruta. ¿Alguien me puede ayudar?
$pdf->Output('/C:/Users/Desktop/Fichas/ficha.pdf','D');

A: Si realizas la la descarga mediante el navegador, quien decide donde guardarlo es el navegador en caso que uses chrome. Cuando realizas la llamada con el parámetro 'D' lo que indicas es que fuerzas al navegador a realizar la descarga y dado que el nombre incluye una ruta, así es como es nombrado el fichero.
$pdf->Output('/C:/Users/Desktop/Fichas/ficha.pdf','D');

Es probable que la configuración que buscas es
$pdf->Output('F', 'C:/Users/Desktop/Fichas/ficha.pdf');

Lo cual guardara posiblemente el fichero en la ruta que quieras, siempre y cuando sea el equipo que ejecuta el servidor.
Nota que el parametro 'F' va en la primera posición dado que la documentación indica que ese parametro debería ir primero, aunque al hacer el llamado Output el código internamente cambia los parametros para que el primero sea I o D o F o S y el segundo el nombre del archivo.
Por lo que el valor F  indica guardar el archivo en local(refiriendose al servidor donde se ejecuta).


text:
Q: FILE MS-DOS Encoding C++ How to write some text into a txt file with MS-DOS encoding ?
I'm using class FILE. May be I must use another class?
CString text;
 CString file_name;
 text = "My text must be in txt file in MS-DOS encoding.";
 file_name = "MyFile.txt";
 FILE *fp;
 fp = fopen(file_name, "w+");
 fprintf(fp, text + "\n");
 fclose(fp);

A: There's nothing special about MS-DOS encoding other than end-of-line is represented by a \r\n two character sequence. If you open the file in text mode as you have done then this should happen automatically.

A: CharToOem (src, dst);
must be used to transform into MS-DOS encoding.


text:
Q: Local Storage wont clear in IE I am saving my login token to local storage and in IE when I go to logout it hits the landing page but immediately logs me back in again.
Is there anyway of clearing this out of IE?
Currently using this line of code on logout function:
window.localStorage.clear();

A: You can try to post your sample code to reproduce the issue with IE.
We will try to make a test with IE and try to check the result.
LocalStorage.clear() will clear all the data in localStorage. Which may not be suitable for your customers. You can try to use storage.removeItem(keyName); to remove any specific data from local storage.
Reference:
Storage.removeItem()


text:
Q: how to make webdriver threadsafe in c#? I have searched in Google but did not find a solution. Could someone please help me in it as I am able to find the solution in java but not in C#.
private static final ThreadLocal < WebDriver > webDriver =
    new ThreadLocal < WebDriver > () {
        @Override protected WebDriver initialValue() {
            return BrowserType.getBrowserType().getInstance();
        }
};

A: Using C# ThreadLocal, something like this?
public static ThreadLocal<IWebDriver> webDriver =
    new ThreadLocal<WebDriver>(() =>
    {
        return new InternetExplorerDriver();
    });

Hopefully you have the correct imports:
using OpenQA.Selenium;
using OpenQA.Selenium.IE;

Note, I barely code in C#, unless required.

A: Thread safety of Selenium is never guaranteed and strictly speaking it's not thread safe. Please refer to this

A: Java solution:

Multithreaded client code should use this to assert that it accesses
  webdriver in a thread-safe manner. Wrap WebDriver instances as
  follows:

WebDriver driver = ThreadGuard.protect(new FirefoxDriver());

Threading issues related to incorrect client threading may have
  mysterious and hard to diagnose errors. Using this wrapper prevents
  this category of errors. It is recommended for all multithreaded
  usage. This class has no overhead of any importance.

Reference


text:
Q: Mysql/Tomcat/MobileFirst Openjpa error no persistance metadata Trying to upgrade worklight 6.1 to mobilefirst 7.1 through Ibm installer and configuration tool. Tomcat server 7.0.30 starts but I never have runtimes in my console. The server log produces this error.
     appcenterdb-mysql  INFO   [localhost-startStop-1] openjpa.Runtime - Starting OpenJPA 1.2.2
0  appcenterdb-mysql  INFO   [localhost-startStop-1] openjpa.jdbc.JDBC - Using dictionary class "org.apache.openjpa.jdbc.sql.MySQLDictionary" (MySQL 5.6.19 ,MySQL Connector Java mysql-connector-java-5.1.25 ( Revision: ${bzr.revision-id} )).
<openjpa-1.2.2-r422266:898935 fatal user error> org.apache.openjpa.persistence.ArgumentException: Type "class com.ibm.puremeap.jpa.entity.OneTimeUrlEntity" does not have persistence metadata.
    at org.apache.openjpa.jdbc.meta.MappingTool.getMapping(MappingTool.java:682)
    at org.apache.openjpa.jdbc.meta.MappingTool.buildSchema(MappingTool.java:748)
    at org.apache.openjpa.jdbc.meta.MappingTool.run(MappingTool.java:646)
    at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDBCBrokerFactory.java:153)
    at org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.newBrokerImpl(JDBCBrokerFactory.java:119)
    at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:189)
    at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:142)
    at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:192)
    at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:145)
    at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:56)
    at com.ibm.puremeap.resources.data.impl.PrincipalHelper.createAndMakeSpecialPrincipalUnique(PrincipalHelper.java:393)
    at com.ibm.puremeap.resources.data.impl.PrincipalHelper.initializeSpecialPrincipals(PrincipalHelper.java:174)
    at com.ibm.puremeap.resources.data.impl.PureMeapData.<init>(PureMeapData.java:201)
    at com.ibm.puremeap.resources.data.impl.PureMeapData.fromDataSource(PureMeapData.java:102)
    at com.ibm.puremeap.resources.data.DataStoreFactory.getJPADBStore(DataStoreFactory.java:46)
    at com.ibm.puremeap.resources.data.DataStoreFactory.getDataStore(DataStoreFactory.java:34)
    at com.ibm.puremeap.util.DataUtil.getData(DataUtil.java:453)
    at com.ibm.puremeap.listeners.AppCenterServletContextListener.checkAndUpgradeTo60(AppCenterServletContextListener.java:171)
    at com.ibm.puremeap.listeners.AppCenterServletContextListener.contextInitialized(AppCenterServletContextListener.java:88)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)


text:
Q: chartValueSelected never gets called I utilize https://github.com/danielgindi/Charts in my project.
Here is my code, this is how I declare my ViewController class:
class ViewController: UIViewController, ChartViewDelegate

declaration of chartView
@IBOutlet weak var chartView: LineChartView!

inside viewDidLoad()
self.chartView.delegate = self

and this is how I implement delegate method
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: Highlight)
{
    print(dataSetIndex)
}

For some reason, when I swipe across the chart, this method never gets called. Any ideas why this might happen?
Thanks in advance

A: As I may have expected, the problem was Swift 3 difference in method signature.
Swift 3
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { ... }

A: Check with a breakpoint if chatView is initialized in viewDidLoad and check its delegate, then check if the method which call the delegate has ever been called.
You can use po chartView.delegate in the terminal screen
Maybe you are not selecting the chart, this is not a touch up inside button, to call the selected method you have to set selected, if you want this to work like a button maybe there are an action called setHighlighted...


text:
Q: Where do I find documentation for the NSAccessibility protocol The client side documentation for the protocol is found https://developer.apple.com/documentation/appkit/nsaccessibility#relationships (more precisely, the Swift API that must be implemented) but I can't seem to find any information on how one would interact with a client that implements this protocol.
Am I missing something? (obviously I am). Where do I find documentation on how, say, a screen reader, gets the information a client exposes.


text:
Q: Makefile compiling C files on Windows8 and files with no file extension/s I have gcc in my Win8 path and can compile C files from the Windows command prompt which is great and I have been compiling regularly in this way but just now I have been looking at creating a makefile to use and compile with.
My first makefile failed as I created makefile.txt but when I removed the file .txt extension the compile worked successfully with the make command at the cursor in cmd console.
The makefile then has no file extension and my query is how the xxxx does this work? Windows obviously knows what this file is and uses it with gcc to compile but how/why? This leads on to another question ...are there other files made with no file extension that do stuff on Windows (or other OS)? I'm perplexed and intrigued and would appreciate a technical explanation if possible.
Thanks.
EDIT...Sat 291114
I am working through Learning C the hard way by Zed Shaw and this image shows Ex2 creating a makefile on my Win8 PC..

A: It works because the make program is written to look for files named makefile, not files named makefile.txt.
Extensions are important on Windows so that Windows can guess what "type" of file it is, so if you tried to open that file Windows could guess at what program should be used to open it.
However, this is really a problematic solution.  First, just because two files have an extension of "foo" doesn't mean both are the same type of file; there's no central authority of file extensions (that I'm aware of) to guarantee there are no conflicts.  Second, just because a file has an extension "foo" doesn't mean the contents are of that type: I'm sure you're familiar with viruses and scams where a file of one type is created with a different extension to trick Windows into running an unexpected program.
On traditional UNIX-based systems the "type" of a file is usually derived from the contents of the file, not the extension.  There are some obvious exceptions, for example source files are all plain text files so they have the type of code it is (C, C++, Java, Python, etc.) marked by the extension.  But on UNIX systems, for example, programs do not have .exe extensions: for example it's just make, not make.exe.  Also a shell script doesn't have to end in .bat or .com: it can be just named foo as well if you want.  For executable files the operating system looks at the first two bytes of the file to tell what kind of executable it is.  For scripts the first two bytes must be #!: then the operating system knows it needs to run an interpreter (like the shell, or Python, or whatever) for the script.
For non-executable files like JPG or whatever, programs can determine their type by examining the contents.  Most file types have some format to their content that can be used to say "this is a JPG file", "this is a MP3 music file", etc.


text:
Q: Reverting a commit that's been accepted to GitHub, then making a small modifiation and trying again I committed some code on a local branch and opened a pull request on our GitHub repo, which was accepted.  Only then did we realize that we shouldn't have made change X, so we need to revert and try again.
I haven't reverted an accepted PR and wondered how best to go about it here.  I know GitHub has a revert button on closed pull requests but subsequent steps are...?
Do I revert, then pull from the 'master' branch (the one that had the PR accepted) into my local branch?  Won't I lose my work then?  Or should I open a new branch, pull into that one, and then cherry pick my original commits, then modify from there and open a new PR?
This is revert 101 stuff I know but I just haven't had to do it often.

A: Just revert the pull request, then pull from the master branch as you suggest. Reverting in git does not delete your original commits. It simply creates additional commits that undo the originals.
This means your commits will still be in master, so you can cherry-pick them and rebase them however you like.


text:
Q: Android HTTPClient "No Peer Certificate" over HTTP I'm building an Android app that accesses an openshift URL over HTTP. And I keep getting an error "No peer certificate".
When I run... openssl s_client -connect mySubDomain.rhcloud.com:80 -showcerts
I get... CONNECTED(00000003) 11940:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_cl nt.c:567:
Which is odd. I don't know too much about this stuff, but why is there a certificate over HTTP?
I've tried a lot of the things other people have mentioned on here and nothing seems to work.  Most of the questions here are also for HTTPS too.
John


text:
Q: DOM touch events on IE/EDGE instead of mousedown I'm implementing the following js code for adding events on a Canvas:
c.addEventListener("touchstart",function(e){console.log('touch')},true);
c.addEventListener("mousedown",function(e) {console.log("mouse")},true);

My computer is a hybrid Windows 10 tablet.
On IE/EDGE, when I perform a mouse click I get 'mouse' log.
On IE/EDGE, when I perform a touch on screen, I get 'mouse' log too.
However, when on IE/EDGE mobile (Windows phone)  or Chrome, I get the 'touch' log when I touch the screen.
I'm convinced that shomehow IE/EDGE, when executed on a laptop, translates "touch" events to 'mouse' events.
Is there any javascript, meta-tag or any option to disable this "translation"?
Note. I'm using touch and mouse events due PIXIJS framework.

A: I am working on touchevents on EDGE on a laptop, you can stop the translation by changing some settings of the flags. Put about:flags in the browser URL.
There under the field
"Enable touch events" choose "Only on when touchscreen is detected" and under
"Fire compatible mouse events in response to the tap gesture"
choose "Always Off"
As shown in pic

This will disable your automatic translation. Restart the browser and you will start getting touchevents.

A: Staring EdgeHTML 17, Microsoft supports Pointer Events to solve the issue:
https://stackoverflow.com/a/51159745/9598077


text:
Q: Strip special characters from text file but keep new lines (Python) I have a text file that looks like the following:
Don't
Can't
Won't
Shouldn't
My aim is to remove all special characters from the text file, whilst preserving the new line for each word. Output should look like:
Dont
Cant
Wont
Shouldnt
I'm currently using the following code:
import re

class TextCleaner:
    uncleanText = open("words.txt").read()
    cleanText = re.sub('[^A-Za-z0-9]+', '', uncleanText)
    open('words.txt', 'w').write(cleanText)

However, this outputs the following:
DontCantWontShouldnt
Can I achieve my primary aim whilst preserving the new lines using regex?

A: You can add \n to preserve new lines or \s to preserve any white spaces. For \s it's this code:
import re

class TextCleaner:
    uncleanText = open("words.txt").read()
    cleanText = re.sub('[^A-Za-z0-9\s]+', '', uncleanText)
    open('words.txt', 'w').write(cleanText)


text:
Q: How to embed lstlisting in table without much space I want to embed code in table like the below photo.

Firstly, I tried code 1.
\begin{tabular}{p{8cm}}
\hline
\begin{lstlisting}
code here ......
\end{lstlisting}
\\ \hline
\begin{lstlisting}
code here ......
\end{lstlisting}
\\ \hline
\end{tabular}

However, there is too much space between hline and code.
Then, I tried answer in Remove top space from lstlisting inside tabular.
The space became less than first step. However, there is still much space.
If I want the effect just like picture above, how can I do?
Great thanks!!

A: You have options aboveskip and belowskip. If we set these values to zero, there is still a small space. We can get rid of it by setting negative values.
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{tabular}{p{8cm}}
\hline
\begin{lstlisting}[aboveskip=-8pt,belowskip=-12pt]
code here ......
\end{lstlisting}
\\ \hline
\begin{lstlisting}[aboveskip=-8pt,belowskip=-12pt]
code here ......
\end{lstlisting}
\\ \hline
\end{tabular}
\end{document}


text:
Q: socket.error: port/proto not found I'm trying to get the service name of port number 1521 using socket package.
This is the code I'm trying to execute in shell
import socket
portname = socket.getservbyport(1521)
print portname

The error I'm getting is as below

portname = socket.getservbyport(i)
socket.error: port/proto not found

If I'm using any other port such as 22,80,1433,3306 their isn't any problem in retrieving the port/service name.
I've tried similar code on two other Linux Machine but their isn't any response.


text:
Q: I am wondering if my query would work because it is different from the solutions and it is just a theoretical task without a Database I've got the following task: Find each company hat is located in every city in which 'FBC' is located.
Follwoing entities:
employee(ID, person_name, street, city)
works(ID, company_name, salary)
company(company_name, city)
manages(ID, manager_id)

I wrote the following query:
select company_name
from company
where city in
(select city
from company
where company_name = 'FBC')

They used a nested query with not exists and exept but I found that too complicated.
What do you mean?
Thanks and best regards!


text:
Q: Ionic sticky element inside scrollable content I am trying to make a sticky element in ionic but not sure how to achieve this.
I have a back arrow that I would like to have in a fixed position. This is my html:
<ion-content>

...rest of the code...

</ion-content>

And this is my css:
.back-arrow {
  width: 100%;
  height: 48px;
  position: absolute;
  top:0;
  z-index: 1;
}

To make it clearer. When I have:

<ion-content>
  ...rest of the code...
</ion-content>

Then it is working, but when it is inside ion-content it is not sticky, and I need it inside of content.

A: I just learn that you can not set a fixed element relative to it's parent, unless its the body. You can however solve this with javascript in two ways. One way is to get your offset of the container and then calculate where your fixed element has to be set in your document to show up over your countainer. This can however be a little bit tricky with the scroll that I'm not sure is same width in all browsers.
The other solution is to have your fixed element to be positioned absolute in your countainer and then via javascript find out the scroll position. From that you update your absolute element on scroll event to be your set px from top of the countainer. The container needs to be set as position relative. With this the scrollbar is not a problem.
The first solution I find best if you dont need a sticky header as you dont need to run code on every scroll event. I would set the position on resize event and trigger that event from document ready event. Also you might wanna consider using a smart resize function, but that is another topic.
Here is the first solution using jquery:
https://jsfiddle.net/y842v5j8/3/
html

  sticky

    Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here

css
html,body{
  margin:0;
}

div{
  position:relative;
  width:200px;
  height:200px;
  display:block;
  padding:40px 5px;
  margin:50px auto;
  overflow-y:scroll;
  background:#ddd;
  border:1px solid #000;
}
div span{
  position:fixed;
  top:-100px;
  left:-100px;
  background:#fff;
  background:#ccc;
  padding:5px;
  border:1px solid #000;
  margin:20px 0 0 -20px; /* set this to get it from top right */
}

jquery
$(document).ready(function(){
    $(window).resize(function(){
    $('[data-sticky]').css({
        left: ($('[data-container]').offset().left + $('[data-container]').outerWidth()) - $('[data-sticky]').outerWidth()+'px',
      top: $('[data-container]').offset().top+'px'
    });
  });
  $(window).resize();
});

Here is the second solution using jquery:
https://jsfiddle.net/y842v5j8/5/
html

  sticky

    Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here
Endless content goes here

css
html,body{
  margin:0;
}

div{
  position:relative;
  width:200px;
  height:200px;
  display:block;
  padding:40px 5px;
  margin:50px auto;
  overflow-y:scroll;
  background:#ddd;
  border:1px solid #000;
}
div span{
  position:absolute;
  top:0;
  right:0;
  background:#fff;
  background:#ccc;
  padding:5px;
  border:1px solid #000;
  margin:20px 20px 0 0; /* set this to get it from top right */
}

jquery
$(document).ready(function(){
    $('[data-container]').scroll(function(){
    $('[data-sticky]').css(
        'top', $(this).scrollTop()+'px'
    );
  });
  $('[data-container]').scroll();
});

A: Override display: block in ion-item-sliding
ion-item-sliding {
    display: initial;
}


text:
Q: How do I add lists from objects to other objects (connected with id) I have two JSON files and I need to get the program to log the names from the other and under each name I need to log a list of titles that belong to that name from another JSON file. They are connected with an id but on the other file the correct id is named "id" and on the other, it's "userId" (and there is a key-id also but refers to something else.
The data is from here: https://jsonplaceholder.typicode.com/posts and here https://jsonplaceholder.typicode.com/users
What I need is something like this:
name1

-title1

-title2

-title3

-title4

name2

-title5

-title6

-title7

-title8

A: One solution is to use a nested for-loop:
for (let user of users) {
  console.log(user.name);
  for (let title of titles) {
    if (user.id == title.userId) {
      console.log(`\t- ${title.title}`);
    }
  }
}

Results in something like:
Leanne Graham
    - sunt aut facere repellat provident occaecati excepturi optio reprehenderit
    - qui est esse
    - ea molestias quasi exercitationem repellat qui ipsa sit aut
    - eum et est occaecati
    - nesciunt quas odio
    # ...
Ervin Howell
    - et ea vero quia laudantium autem
    - in quibusdam tempore odit est dolorem
    # ...


text:
Q: How to react to keypress events in Go? I have a REPL app in Go that should react to keyboard press events (distinct action for each key pressed key) but ReadString expects for return key to be pressed before reading os.Stdin:
import (
    "bufio"
    "os"
)

for {
    reader := bufio.NewReader(os.Stdin)
    key, _ := reader.ReadString('\n')
    deferKey(key)
}

How can I react to key press events in Go?

A: Game engines commonly implement this kind of functionality. They are usually also pretty much platform agnostic (usually at least Windows, Linux, Mac OS X). Try for instance Azul3D's keyboard library.
The logic is off the top of my head something like
watcher := keyboard.NewWatcher()
// Query for the map containing information about all keys
status := watcher.States()
left := status[keyboard.ArrowLeft]
if left == keyboard.Down {
    // The arrow to left is being held down
    // Do something!
}

Getting a list of what keys are currently being pressed down is a matter of iterating the map through and listing the keys where value was Down.

A: This answer for a similar question points to few options depending on which platform you need to implement this in.
I've personally used https://github.com/MarinX/keylogger.
It's well written and easy to understand. At the time, I had to write my own version of this library to listen to multiple keyboards, It was easy to adapt this code for that.
Note that this library is written for Linux only.
Example code:

import (
    "github.com/MarinX/keylogger"
    "github.com/sirupsen/logrus"
)

func main() {

    // find keyboard device, does not require a root permission
    keyboard := keylogger.FindKeyboardDevice()

    logrus.Println("Found a keyboard at", keyboard)
    // init keylogger with keyboard
    k, err := keylogger.New(keyboard)
    if err != nil {
        logrus.Error(err)
        return
    }
    defer k.Close()

    events := k.Read()

    // range of events
    for e := range events {
        switch e.Type {
        // EvKey is used to describe state changes of keyboards, buttons, or other key-like devices.
        // check the input_event.go for more events
        case keylogger.EvKey:

            // if the state of key is pressed
            if e.KeyPress() {
                logrus.Println("[event] press key ", e.KeyString())
            }

            // if the state of key is released
            if e.KeyRelease() {
                logrus.Println("[event] release key ", e.KeyString())
            }

            break
        }
    }
}