Q:

Tensorflow input pipeline using text

in the last weeks I tried to get the input pipeline running with tf.records under tensorflow (tf 2.0.1). From a CSV sentences are loaded and a record is generated:
import tensorflow as tf
import pathlib
import sys
import csv

PATH_PARENT = str(pathlib.Path(__file__).parent.absolute())
if PATH_PARENT.endswith('models'):
    PATH_PARENT = PATH_PARENT[:-len('models')]

PATH_PARENT = PATH_PARENT.replace("\\", '/')

sys.path.append(PATH_PARENT)

def create_tf_example(features, label):
    tf_example = tf.train.Example(features=tf.train.Features(feature={
        'Sentence': tf.train.Feature(bytes_list=tf.train.BytesList(value=[features.encode('utf-8')])),
        'Class': tf.train.Feature(bytes_list=tf.train.BytesList(value=[label.encode('utf-8')])),
    }))
    return tf_example

intent_load_list = ["training_data_intent_Music_controler_0.csv"]   # Example: musik,<slot_0>,play,<slot_music_controle>

for load_intent in intent_load_list:
    start = 14
    end = load_intent.rfind("_")
    label = load_intent[start : end]
    print("loading intent " + label)
    csv_data = []

    with open(PATH_PARENT + "models/" + load_intent, 'r') as csv_file:
            csv_reader = csv.reader(csv_file)
            for row in csv_reader:
                clean_output = ''
                for word in row:
                    if '<' not in word:
                        clean_output = clean_output + word + ' '
                csv_data.append(clean_output)

    with tf.io.TFRecordWriter(PATH_PARENT + "models/dataset.tfrecords") as writer:
        for row in csv_data:
            features = row

            example = create_tf_example(features, label)
            writer.write(example.SerializeToString())
    writer.close()

This works so far. This record should be loaded later, edited with a tf-hub model and then trained with the record. However, I either get an IndexEror or it fails completely:
import numpy as np
import tensorflow as tf
from tensorflow import keras
import tensorflow_hub as hub
import sys
import pathlib

PATH_PARENT = str(pathlib.Path(__file__).parent.absolute())
if PATH_PARENT.endswith('models'):
    PATH_PARENT = PATH_PARENT[:-len('models')]

PATH_PARENT = PATH_PARENT.replace("\\", '/')

sys.path.append(PATH_PARENT)

embed = hub.load("https://tfhub.dev/google/nnlm-de-dim50-with-normalization/2")

dataset = tf.data.TFRecordDataset(filenames = [PATH_PARENT + "models/dataset.tfrecords"])

def prepare_for_training(ds, shuffle_buffer_size=1024, batch_size=2):
    ds = ds.map(lambda x: embed([x]))

    ds = ds.shuffle(buffer_size=shuffle_buffer_size).batch(batch_size)

    print(ds)

    return ds

def convert_data(data):
    data_np = embed(data)
    data_list = data_np.tolist()
    return data_list

batch_size = 64
n_intents = 2

train_ds = prepare_for_training(dataset, batch_size=batch_size)

build_model = keras.Sequential()
build_model.add(keras.layers.Input(shape=(None, 50)))
build_model.add(keras.layers.Dense(50, activation='relu'))
build_model.add(keras.layers.Dropout(0.2))
build_model.add(keras.layers.Dense(20, activation='relu'))
build_model.add(keras.layers.Dropout(0.2))
build_model.add(keras.layers.Dense(n_intents, activation='softmax'))

build_model.summary()
build_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

build_model.fit(train_ds, epochs=5)     # IndexError - list index out of range
print("done")

Has anyone perhaps tried something similar or an idea? Unfortunately the documentation didn't help much. Thanks in advance

A:

You get this error in tensorflow version 2.0.1 when you don't pass the labels in your data. In the below example, I am writing dummy Input values using TFRecordWriter and later reading it using TFRecordDataset and passing it to the model.
If you run the same code in tensorflow version 2.1.0, the error statement changes as IndexError: tuple index out of range.
Also, if you run the same code in tensorflow version 2.2.0, the error statement changes as ValueError: No gradients provided for any variable: ['dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0', 'dense_2/kernel:0', 'dense_2/bias:0'].
Code to reproduce the error -
%tensorflow_version 2.x
import tensorflow as tf
import numpy as np
print(tf.__version__)

def write_date_tfrecord():
    #writes 10 dummy values to replicate the issue
    Input = [20191221.123 + x for x in range(0,10)]
    print("Writing Input - ", Input)

    example = tf.train.Example(
            features = tf.train.Features(
                feature = {
                    'Input':tf.train.Feature(float_list=tf.train.FloatList(value=Input))
                     }
                ))

    writer = tf.io.TFRecordWriter("Data.tf_record")
    writer.write(example.SerializeToString())

def parse_function(serialized_example):
        features = {
            'Input': tf.io.FixedLenSequenceFeature([], tf.float32,allow_missing=True)
             }
        features = tf.io.parse_single_example(serialized=serialized_example, features=features)
        Input = features['Input']
        return Input

def dataset_generator():
    trRecordDataset = tf.data.TFRecordDataset("Data.tf_record")
    trRecordDataset = trRecordDataset.map(parse_function, num_parallel_calls = tf.data.experimental.AUTOTUNE)
    return trRecordDataset

write_date_tfrecord()
generator = dataset_generator()

build_model = tf.keras.Sequential()
build_model.add(tf.keras.layers.Input(shape=(1,)))
build_model.add(tf.keras.layers.Dense(50, activation='relu'))
build_model.add(tf.keras.layers.Dropout(0.2))
build_model.add(tf.keras.layers.Dense(20, activation='relu'))
build_model.add(tf.keras.layers.Dropout(0.2))
build_model.add(tf.keras.layers.Dense(3, activation='softmax'))

build_model.summary()
build_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

build_model.fit(dataset_generator(), epochs=5)     # IndexError - list index out of range
print("done")

Output -
2.0.1
Writing Input -  [20191221.123, 20191222.123, 20191223.123, 20191224.123, 20191225.123, 20191226.123, 20191227.123, 20191228.123, 20191229.123, 20191230.123]
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense (Dense)                (None, 50)                100
_________________________________________________________________
dropout (Dropout)            (None, 50)                0
_________________________________________________________________
dense_1 (Dense)              (None, 20)                1020
_________________________________________________________________
dropout_1 (Dropout)          (None, 20)                0
_________________________________________________________________
dense_2 (Dense)              (None, 3)                 63
=================================================================
Total params: 1,183
Trainable params: 1,183
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
      1/Unknown - 0s 60ms/step
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-1-d1c5c463cdc2> in <module>()
     47 build_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
     48
---> 49 build_model.fit(dataset_generator(), epochs=5)     # IndexError - list index out of range
     50 print("done")

20 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training_eager.py in _model_loss(model, inputs, targets, output_loss_metrics, sample_weights, training)
    164
    165         if hasattr(loss_fn, 'reduction'):
--> 166           per_sample_losses = loss_fn.call(targets[i], outs[i])
    167           weighted_losses = losses_utils.compute_weighted_loss(
    168               per_sample_losses,

IndexError: list index out of range

Solution - I created the dummy labels variable and wrote the dummy labels using TFRecordWriter and later reading it using TFRecordDataset and passing it to the model. Now we are passing both Input and labels to the model and it works fine.
Fixed Code -
%tensorflow_version 2.x
import tensorflow as tf
import numpy as np
print(tf.__version__)

def write_date_tfrecord():
    #writes 10 dummy values to replicate the issue
    Input = [20191221.123 + x for x in range(0,9)]
    labels = [1, 1, 0, 0, 0, 1, 1, 2, 2]

    example = tf.train.Example(
            features = tf.train.Features(
                feature = {
                    'Input':tf.train.Feature(float_list=tf.train.FloatList(value=Input)),
                    'labels':tf.train.Feature(float_list=tf.train.FloatList(value=labels))
                     }
                ))

    writer = tf.io.TFRecordWriter("Data.tf_record")
    writer.write(example.SerializeToString())

def parse_function(serialized_example):
        features = {
            'Input': tf.io.FixedLenSequenceFeature([], tf.float32,allow_missing=True),
            'labels': tf.io.FixedLenSequenceFeature([], tf.float32,allow_missing=True)
             }
        features = tf.io.parse_single_example(serialized=serialized_example, features=features)
        Input = features['Input']
        labels = features['labels']
        return Input, labels

def dataset_generator():
    trRecordDataset = tf.data.TFRecordDataset("Data.tf_record")
    trRecordDataset = trRecordDataset.map(parse_function, num_parallel_calls = tf.data.experimental.AUTOTUNE)
    return trRecordDataset

write_date_tfrecord()
generator = dataset_generator()

build_model = tf.keras.Sequential()
build_model.add(tf.keras.layers.Input(shape=(1,)))
build_model.add(tf.keras.layers.Dense(50, activation='relu'))
build_model.add(tf.keras.layers.Dropout(0.2))
build_model.add(tf.keras.layers.Dense(20, activation='relu'))
build_model.add(tf.keras.layers.Dropout(0.2))
build_model.add(tf.keras.layers.Dense(3, activation='softmax'))

build_model.summary()
build_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

build_model.fit(dataset_generator(), epochs=5)     # IndexError - list index out of range
print("done")

Output -
2.1.0
Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_12 (Dense)             (None, 50)                100
_________________________________________________________________
dropout_8 (Dropout)          (None, 50)                0
_________________________________________________________________
dense_13 (Dense)             (None, 20)                1020
_________________________________________________________________
dropout_9 (Dropout)          (None, 20)                0
_________________________________________________________________
dense_14 (Dense)             (None, 3)                 63
=================================================================
Total params: 1,183
Trainable params: 1,183
Non-trainable params: 0
_________________________________________________________________
Epoch 1/5
1/1 [==============================] - 0s 362ms/step - loss: 8705754.0000 - accuracy: 0.0000e+00
Epoch 2/5
1/1 [==============================] - 0s 14ms/step - loss: 4458477.5000 - accuracy: 0.2222
Epoch 3/5
1/1 [==============================] - 0s 16ms/step - loss: 5933292.5000 - accuracy: 0.2222
Epoch 4/5
1/1 [==============================] - 0s 16ms/step - loss: 4305070.0000 - accuracy: 0.1111
Epoch 5/5
1/1 [==============================] - 0s 14ms/step - loss: 5578528.5000 - accuracy: 0.1111
done

Would also recommend to go through this link that explains "How to feed TFRecord to train Keras model".
Hope this answers your question. Happy Learning.


Q:

How do I reference Entity Framework 6 from a .NET core class library in RC2?

I have a .NET core class library from which I want to reference Entity Framework 6.1.3. Here is my project.json:
{
  "version": "1.0.0-*",

  "dependencies": {
    "NETStandard.Library": "1.5.0-rc2-24027",
    "EntityFramework": "6.1.3"
  },

  "frameworks": {
    "netstandard1.5": {
      "imports": "dnxcore50"
    }
  }
}

I'm getting this compilation error:

The dependency EntityFramework 6.1.3 does not support framework
  .NETStandard,Version=v1.5.

So I tried switching the NetStandard.Library dependency to Microsoft.NETCore.App like so:
{
  "version": "1.0.0-*",

  "dependencies": {
    "Microsoft.NETCore.App": {
    "version": "1.0.0-rc2-3002702",
    "type": "platform"
    },
    "EntityFramework": "6.1.3"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  }
}

I'm getting a smilar compilation error as earlier:

The dependency EntityFramework 6.1.3 does not support framework
  .NETCoreApp,Version=v1.0

Basically, this leaves me with no option to reference Entity Framework 6.1.3 from .NET core.
I can refer EF Core from .NET core class libraries, but it is not something I wish to do right now.
Is there a solution to this?

A:

Entity Framework 6.1.3 does not support .NET Core. This was part of the motivation for creating Entity Framework Core. EF 6 has deep ties to APIs in .NET Framework that may not be ported to exist in .NET Core.
You can still use EF6 with "project.json" projects but you need to target .NET Framework instead of .NET Core.
{
    "dependencies": {
        "EntityFramework": "6.1.3"
    },
    "frameworks": {
        "net461": { }
    }
}


Q:

How do I remove newline from the last argument in bash?

I'm working on wsl bash and I have the following function defined in my ~/.bashrc file:
function clip { /mnt/c/Windows/System32/clip.exe "${@%\n}"; }

However this does not remove the trailing \n from the arugument.
How can I improve this to meet my specific needs?
Many thanks
EDIT:
With the help of Kamil's answer, I was able to figure out what was actually going on. turns out that the spawned subprocess (cmd.exe) is adding the carriage return which is being inserted into clip.exe (because I was using pipes. ex. pwd | clip).
I was able to get the desired result with the following:
function clip { /mnt/c/Windows/System32/WindowsPowershell/v1.0/powershell.exe Set-Clipboard "${@:-$(cat)}"; }

It's a bit slow as it relies on

powershell
cat (external binary which should be replaced with read builtin)

But not a problem for my needs :)

A:

"${@%\n}" removes a trailing n. "${@%\\n}" would remove trailing \n (literal string, not a newline).
To remove a newline character you need to pass a newline character. In Bash this syntax should work:
"${@%$'\n'}"

where $'\n' is responsible for generating an actual newline character. A literal newline will work as well:
"${@%
}"

Notes:

The solution removes trailing newline from each argument, not only from the last (because this is how $@ works).
In Linux its unusual to have a trailing newline in a command line argument. I don't know WSL, I don't know your usage case; I hope you know what you want*.

Example:
$ set a $'b\n' c
$ printf '<%s>\n' "$@"

<c>
$ printf '<%s>\n' "${@%$'\n'}"

<c>
$ printf '<%s>\n' "${@%
}"

<c>

* If "removing the trailing \n from the argument" is not what you want, then maybe you call the function in a (sourced?) script and the script suffers from DOS line ending(s). Check this question.


Q:

Combine multiple rows to one after group by

UPDATE:
https://www.db-fiddle.com/f/5fGUTSsAhGRPYPk33wDSzz/0
Sorry for asking the question very similar to the previous one, but I am really stuck here.
There are multiple tables:

items → items_roles → roles
items → zones →  roles_zones → roles

Structure:

items: id, zone_id
items_roles: role_id, item_id
zones: id
roles_zones: role_id, zone_id
roles: id, role_type_id,

I am trying to add role fields to items, it should take role_type and it is value from items_zones and if it is NULL fetch fallback value from zone (roles_zones).
I started with:
SELECT
    items.id,
    (z_roles.role_type_id) as z_role_type_id,
    (z_roles.id) as z_role_id,
    MAX(i_roles.role_type_id) as i_role_type_id,
    MAX(i_roles.id) as i_role_id
FROM
    items
LEFT JOIN
    zones as j_zones ON j_zones.id = items.zone_id
LEFT JOIN
    roles_zones ON roles_zones.zone_id = j_zones.id
LEFT JOIN
    roles as z_roles ON (z_roles.id = roles_zones.role_id)
LEFT JOIN
    items_roles ON items_roles.item_id = items.id
LEFT JOIN
    roles as i_roles ON items_roles.role_id = i_roles.id
                     AND (z_roles.role_type_id = i_roles.role_type_id)
WHERE
    items.id = 834
GROUP BY
    items.id, z_roles.role_type_id, z_roles.id
ORDER BY
    i_role_id;

Looks right:
id  |z_role_type_id |z_role_id |i_role_type_id |i_role_id |
----+---------------+----------+---------------+----------+
834 |5              |111       |5              |68        |
834 |11             |120       |11             |120       |
834 |7              |77        |               |          |
834 |2              |2         |               |          |
834 |12             |91        |               |          |
834 |4              |78        |               |          |
834 |8              |36        |               |          |

And now this query:
SELECT
    items.id,
    z_roles.role_type_id as z_role_type_id,
    z_roles.id as z_role_id,
    MAX(i_roles.role_type_id) AS i_role_type_id,
    MAX(i_roles.id) AS i_role_id,
    MAX(CASE
           WHEN (i_roles.role_type_id = 5) THEN i_roles.id
           WHEN (z_roles.role_type_id = 5) THEN z_roles.id
        END) AS role_type_5_value,
    MAX(CASE
           WHEN (i_roles.role_type_id = 11) THEN i_roles.id
           WHEN (z_roles.role_type_id = 11) THEN z_roles.id
        END) AS role_type_11_value,
    MAX(CASE
           WHEN (i_roles.role_type_id = 7) THEN i_roles.id
           WHEN (z_roles.role_type_id = 7) THEN z_roles.id
        END) AS role_type_7_value
FROM
    items
LEFT JOIN
    zones AS j_zones ON j_zones.id = items.zone_id
LEFT JOIN
    roles_zones ON roles_zones.zone_id = j_zones.id
LEFT JOIN
    roles AS z_roles ON (z_roles.id = roles_zones.role_id)
LEFT JOIN
    items_roles ON items_roles.item_id = items.id
LEFT JOIN
    roles AS i_roles ON items_roles.role_id = i_roles.id
                     AND (z_roles.role_type_id = i_roles.role_type_id)
WHERE
    items.id = 834
GROUP BY
    items.id,
    z_roles.role_type_id,
    z_roles.id
ORDER BY
    items.id, i_role_id;

Generates this:
 id  | z_role_type_id | z_role_id | i_role_type_id | i_role_id | role_type_5_value | role_type_11_value | role_type_7_value
-----+----------------+-----------+----------------+-----------+-------------------+--------------------+-------------------
 834 |              5 |       111 |              5 |        68 |               111 |                    |
 834 |             11 |       120 |             11 |       120 |                   |                120 |
 834 |              7 |        77 |                |           |                   |                    |                77
 834 |              2 |         2 |                |           |                   |                    |
 834 |             12 |        91 |                |           |                   |                    |
 834 |              4 |        78 |                |           |                   |                    |
 834 |              8 |        36 |                |           |                   |                    |
(7 rows)

Multiple rows and wrong value for role_type_5_value. Probably because of MAX aggregator. Is it possible to use something like first aggregator (because rows ordered by i_role_id and first results are right)?
I want this:
 id  | role_type_5_value | role_type_11_value | role_type_7_value
-----+-------------------+--------------------+-------------------
 834 |                68 |                120 |                77

I tried to group by by aggregated fields, (role_type_5_value, role_type_11_value, role_type_7_value) but this is simply not working.

A:

First: removing the unneeded bridge-tables from the main query and squeeze them into EXISTS() terms will simplify your query.(you only need three tables, the rest is glue)
Second: don't put all your terms in the GROUP BY clause.

SELECT
  i0.id
   , MAX(CASE
    WHEN (r1.role_type_id = 5) THEN r1.id
    WHEN (r0.role_type_id = 5) THEN r0.id
  END) AS role_type_5_value
  , MAX(CASE
    WHEN (r1.role_type_id = 11) THEN r1.id
    WHEN (r0.role_type_id = 11) THEN r0.id
  END) AS role_type_11_value
  , MAX(CASE
    WHEN (r1.role_type_id = 7) THEN r1.id
    WHEN (r0.role_type_id = 7) THEN r0.id
  END) AS role_type_7_value

FROM items i0
LEFT JOIN roles AS r0
  ON EXISTS ( SELECT*
        FROM zones AS z0
        JOIN roles_zones rz ON rz.zone_id = z0.id
        WHERE z0.id = i0.zone_id
        AND r0.id = rz.role_id)

LEFT JOIN roles AS r1
  ON EXISTS ( SELECT*
        FROM items_roles ir
        WHERE ir.item_id = i0.id
        AND ir.role_id = r1.id
        AND r0.role_type_id = r1.role_type_id
        )

WHERE i0.id = 834
GROUP BY i0.id
         -- r0.role_type_id,
         -- r0.id
ORDER BY i0.id;


Q:

What was Dolcetto combined with?

Dolcetto was a human chimera, a creature synthesized by alchemically combining two or more living beings. What was the other living beings that Dolcetto was combined with?

A:

I don't recall any of his gang having green hair. But in Brotherhood (and the manga), there were four gang members of Greed's:

Roa: Created by being mixed with an ox or possibly a bull.

Dolcetto: Created by being mixed with a dog.

Martel: Created by being mixed with a snake.

Bido: Created by being mixed with a gecko.

Later, after Greed "changed bodies", he got two new "partners":

Heinkel: Created by being mixed with a lion.
Darius: Created by being mixed with some kind of ape.


Q:

Android emulator hangs forever at boot time

Emulator started, but not booting further "android" flashing text.
Started by
Android/Sdk/emulator/emulator @Nexus_5X_API_25 -verbose

In logs only repeating records
emulator: MemoryReport: Epoch: 140737476643856, Res/ResMax/Virt/VirtMax: 737525760 737525760 5164826624 5302894592

How to fix/debug it?..
Was working fine with KVM end virtualization, but suddenly stopped after updating to emulator to 26.1.2-4077558.
Update
Thanks to albodelu for information about update to 26.1.3. After Update I having:
KVM is required to run this AVD.
Unknown Error

Please file a bug against Android Studio.

KVM enabled.
This was initial error which I fixed by adding executable permissions to emulator binaries.
So done this again.
Forced emulators to work by:
chmod a+x ~/Android/Sdk/emulator/emulator*
chmod a+x ~/Android/Sdk/emulator/lib64/lib*
chmod a+x ~/Android/Sdk/emulator/qemu/linux-x86_64/*
chmod a+x ~/Android/Sdk/emulator/qemu-img
chmod a+x ~/Android/Sdk/tools/emulator*
chmod a+x ~/Android/Sdk/tools/android
chmod a+x ~/Android/Sdk/tools/bin/*

And now miracle :) both emulator devices are working.

A:

My answer is not exact solution to your problem but use Genymotion for simulation. It offers many devices from different brands and more robust AVDs. I only use AVD in Android Studio when i'm to test sensors virtually. That emulator is still cumbersome and very problematic.

A:

I've got this problem when I use hardware accelerated image.
The solution that works for me, and may work for you is to create a new Virtual Device, and select "Software" under "Emulated Performance":

A:

I've had this a number of times when the emulator gets updated.
The only solution I've found, if you can it a solution, is to delete the emulator and re-create it again and it should work OK after that.


Q:

LINQ GroupBy continuous time

Assuming I have a simple structure that looks like this:
public class Range
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }

    public Range(DateTime start, DateTime end)
    {
        this.Start = start;
        this.End = end;
    }
}

And I create an collection like so:
var dr1 = new Range(new DateTime(2011, 11, 1, 12, 0, 0),
    new DateTime(2011, 11, 1, 13, 0, 0));
var dr2 = new Range(new DateTime(2011, 11, 1, 13, 0, 0),
    new DateTime(2011, 11, 1, 14, 0, 0));
var dr3 = new Range(new DateTime(2011, 11, 1, 14, 0, 0),
    new DateTime(2011, 11, 1, 15, 0, 0));
var dr4 = new Range(new DateTime(2011, 11, 1, 16, 0, 0),
    new DateTime(2011, 11, 1, 17, 0, 0));

var ranges = new List<Range>() { dr1, dr2, dr3, dr4 };

What I want to do is group the ranges where they are continuous - i.e. they are continuous if the End value of the previous Range is the same as the Start of the next.
We can assume that there are no collisions/duplicates or overlaps in the Range values.
In the example posted, I would end up with two groups:
2011-11-1 12:00:00 - 2011-11-1 15:00:00

2011-11-1 16:00:00 - 2011-11-1 17:00:00

It's fairly easy to come up with an iterative solution for this. But is there some LINQ magic I can use to get this in a pretty one-liner?

A:

Your best bet is to use yield and an extension method:
static IEnumerable<Range> GroupContinuous(this IEnumerable<Range> ranges)
{
    // Validate parameters.

    // Can order by start date, no overlaps, no collisions
    ranges = ranges.OrderBy(r => r.Start);

    // Get the enumerator.
    using (IEnumerator<Range> enumerator = ranges.GetEnumerator();
    {
        // Move to the first item, if nothing, break.
        if (!enumerator.MoveNext()) yield break;

        // Set the previous range.
        Range previous = enumerator.Current;

        // Cycle while there are more items.
        while (enumerator.MoveNext())
        {
            // Get the current item.
            Range current = enumerator.Current;

            // If the start date is equal to the end date
            // then merge with the previous and continue.
            if (current.Start == previous.End)
            {
                // Merge.
                previous = new Range(previous.Start, current.End);

                // Continue.
                continue;
            }

            // Yield the previous item.
            yield return previous;

            // The previous item is the current item.
            previous = current;
        }

        // Yield the previous item.
        yield return previous;
    }
}

Granted, the call to OrderBy is going to cause a full iteration of the ranges sequence, but there's no avoiding that.  Once you have it ordered, you can prevent having to materialize your results before returning them; you simply yield the results if the conditions dictate.
If you know that the sequence is ordered, however, then you don't have to call OrderBy at all, and you can yield items as you traverse the list and break on different collapsed Range instances.
Ultimately, if the sequence is unordered, then you have two options:

Order the list and then process (remember, OrderBy is deferred as well, but will have to use one full iteration to order the sequence), using yield to return the item when you have one to process
Process the entire sequence at once and return as an entire materialized sequence

A:

A generic version of casperOne's extension method, used as such:
var items = new[]
    {
        // Range 1
        new { A = 0, B = 1 },
        new { A = 1, B = 2 },
        new { A = 2, B = 3 },
        new { A = 3, B = 4 },
        // Range 2
        new { A = 5, B = 6 },
        new { A = 6, B = 7 },
        new { A = 7, B = 8 },
        new { A = 8, B = 9 },
    };

var ranges = items.ContinousRange(
    x => x.A,
    x => x.B,
    (lower, upper) => new { A = lower, B = upper });

foreach(var range in ranges)
{
    Console.WriteLine("{0} - {1}", range.A, range.B);
}

Implementation of extension method
    /// <summary>
    /// Calculates continues ranges based on individual elements lower and upper selections. Cannot compensate for overlapping.
    /// </summary>
    /// <typeparam name="T">The type containing a range</typeparam>
    /// <typeparam name="T1">The type of range values</typeparam>
    /// <param name="source">The ranges to be combined</param>
    /// <param name="lowerSelector">The range's lower bound</param>
    /// <param name="upperSelector">The range's upper bound</param>
    /// <param name="factory">A factory to create a new range</param>
    /// <returns>An enumeration of continuous ranges</returns>
    public static IEnumerable<T> ContinousRange<T, T1>(this IEnumerable<T> source, Func<T, T1> lowerSelector, Func<T, T1> upperSelector, Func<T1, T1, T> factory)
    {
        //Validate parameters

        // Can order by start date, no overlaps, no collisions
        source = source.OrderBy(lowerSelector);

        // Get enumerator
        using(var enumerator = source.GetEnumerator())
        {
            // Move to the first item, if nothing, break.
            if (!enumerator.MoveNext()) yield break;

            // Set the previous range.
            var previous = enumerator.Current;

            // Cycle while there are more items
            while(enumerator.MoveNext())
            {
                // Get the current item.
                var current = enumerator.Current;

                // If the start date is equal to the end date
                // then merge with the previoud and continue
                if (lowerSelector(current).Equals(upperSelector(previous)))
                {
                    // Merge
                    previous = factory(lowerSelector(previous), upperSelector(current));

                    // Continue
                    continue;
                }

                // Yield the previous item.
                yield return previous;

                // The previous item is the current item.
                previous = current;
            }

            // Yield the previous item.
            yield return previous;
        }
    }

A:

You could use the Aggregate() method and a lambda to group them together.  This is, as you say, assuming no duplicates or overlaps:
// build your set of continuous ranges for results
List<Range> continuousRanges = new List<Range>();

ranges.Aggregate(continuousRanges, (con, next) => {
{
    // pull last item (or default if none) - O(1) for List<T>
    var last = continuousRanges.FirstOrDefault(r => r.End == next.Start);

    if (last != null)
        last.End = next.End;
    else
        con.Add(next);

    return con;
});

Now, if you know the ranges are ordered, you could get away with always comparing the next against the last one we processed, like so:
// build your set of continuous ranges for results
List<Range> continuousRanges = new List<Range>();

ranges.Aggregate(continuousRanges, (con, next) => {
{
    // pull last item (or default if none) - O(1) for List<T>
    var last = continuousRanges.LastOrDefault();

    if (last != null && last.End == next.Start)
        last.End = next.End;
    else
        con.Add(next);

    return con;
});


Q:

Didn't produce the JSON output in logcat

Hi I am developing a webservice based app in which I want to retrieve data from MySQL remote server and display it in logcat. But I receive an error:
Your content must have a ListView whose id attribute is 'android.R.id.list'.

The fact is I didn't mention ListView in my layout file. Herewith I've attached my java files and the logcat report. Response from server side was working well.
URL for JSON Response: vishwas.meximas.com/apps.php
MainActivity.java:
    public class MainActivity extends ListActivity {
        ProgressDialog progress;
        JSONParser parser = new JSONParser();
        JSONObject object;
        JSONArray array;
        ArrayList<HashMap<String, String>> info_list;

        String URL = "http://vishwa.meximas.com/apps.php";

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

            info_list = new ArrayList<HashMap<String, String>>();
            new loadinfo().execute();
        }

        class loadinfo extends AsyncTask<String, String, String> {

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                progress=new ProgressDialog(MainActivity.this);
                progress.setMessage("Loading User Info.....");
                progress.setIndeterminate(false);
                progress.setCancelable(false);
                progress.show();
            }

            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                List<NameValuePair>  list =new ArrayList<NameValuePair>();
            JSONObject json=parser.makeHttpRequest1(URL, "GET", list);
            Log.d("RECEIVED", json.toString());
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    }

And my Second java file is JSONParser.java:
    package com.example.webservice_call;

    public class JSONParser {
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";

        // constructor
        public JSONParser() {

        }

        public JSONObject makeHttpRequest1(String url, String method,
                List<NameValuePair> params) {

            // Making HTTP request
            try {

                // check for request method
                if(method == "POST"){
                    // request method is POST
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                }else if(method == "GET"){
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);

                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            // return JSON String
            return jObj;
        }
    }

The received Logcat error was:
    04-07 12:34:54.988: E/AndroidRuntime(1243): FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.webservice_call/com.example.webservice_call.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    at android.app.ActivityThread.access$600(ActivityThread.java:141)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
    at android.app.ListActivity.onContentChanged(ListActivity.java:243)
    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:273)
    at android.app.Activity.setContentView(Activity.java:1881)
    at com.example.webservice_call.MainActivity.onCreate(MainActivity.java:31)
    at android.app.Activity.performCreate(Activity.java:5104)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    ... 11 more

Please help me to solve this error.

A:

Here is the solution JSONParser.java...
Just put this class in your code and see the result..
package com.example.orientation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";

        // constructor
        public JSONParser() {

        }

        public JSONObject makeHttpRequest1(String url, String method,
                List<NameValuePair> params) {

            // Making HTTP request
            try {

                // check for request method
                if(method == "POST"){
                    // request method is POST
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                }else if(method == "GET"){
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);

                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
                JSONObject obj = new JSONObject();
                try {
                    obj.put("result", new JSONArray(json));
                    jObj=obj;
                } catch (JSONException e1) {
                 // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

            // return JSON String
            return jObj;
        }
    }

There is a problem actually the response from your webservice is JSONArray and you are receiving it in JSONObject.I modify your JSONParser class please the code...
 // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                    JSONObject obj = new JSONObject();
                    try {
                        obj.put("result", new JSONArray(json));
                        jObj=obj;
                    } catch (JSONException e1) {
                     // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }

                // return JSON String
                return jObj;
            }

[
{
Id: "1",
Name: "GST",
Address: "Alapakkam"
},
{
Id: "2",
Name: "GST1",
Address: "Chennai"
}
]


Q:

How meaningful is the Big-O time complexity of an algorithm?

Programmers often talk about the time complexity of an algorithm, e.g. O(log n) or O(n^2).
Time complexity classifications are made as the input size goes to infinity, but ironically infinite input size in computation is not used.
Put another way, the classification of an algorithm is based on a situation that algorithm will never be in: where n = infinity.
Also, consider that a polynomial time algorithm where the exponent is huge is just as useless as an exponential time algorithm with tiny base (e.g., 1.00000001^n) is useful.
Given this, how much can I rely on the Big-O time complexity to advise choice of an algorithm?

A:

With small n Big O it is just about useless and it's the hidden constants or even actual implementation that will more likely be the deciding factor for which algorithm is better. This is why most sorting functions in standard libraries will switch to a faster insertion sort for those last 5 elements. The only way to figure out which one will be better is benchmarking with realistic data sets.
Big O is good for large data sets and discussing on how an algorithm will scale, it's better to have a O(n log n) algorithm than a O(n^2) when you expect the data to grow in the future, but if the O(n^2) works fine the way it is and the input sizes will likely remain constant, just make note that you can upgrade it but leave it as is, there are likely other things you need to worry about right now.
(Note all "large" and "smalls" in the previous paragraphs are meant to be taken relatively; small can be a few million and big can be a hundred it all depends on each specific case)
Often times there will be a trade-off between time and space: for example quicksort requires O(log n) extra memory while heapsort can use O(1) extra memory, however the hidden constants in heapsort makes it less attractive (there's also the stability issue which make mergesort more attractive if you don't mind payign the extra memory costs).
Another thing to consider is database indexes, these are additional tables that require log(n) time to update when a record is added, removed or modified, but lets lookups happen much faster (O(log n) instead of O(n)). deciding on whether to add one is a constant headache for most database admins: will I have enough lookups on the index compared to the amount of time I spend updating the index?
One last thing to keep in mind: the more efficient algorithms are nearly always more complicated than the naive straight-forward one (otherwise it would be the one you would have used from the start). This means a larger surface area for bugs and code that is harder to follow, both are non-trivial issues to deal with.

A:

Very meaningful in my experience.
At the root of many performance problems I often find these causes...

Failure to consider the range of n for which the algorithm will be used.
Failure to consider time complexity of the algorithm used.
Failure to consider memory requirements of the alogrithm for the likely range of n.
Failure to consider latency differences between RAM, Disk, Network, etc.
(and not least) Failure to test with realistic sized data.

This comes up in routine places in development of business software. Such as...

Why does my SQL query run so slowly?
Why does my HTML+CSS+js UI run so slowly? I'm just doing a few jquery operations on the DOM?
Why is my .Net  app running so slowly? I'm just using datasets to massage some data and put it in a grid.

In most cases where n is known to be small it's not worth spending a lot of time on complexity.
Thinking about the expected range of n and evaluating complexity is a proven way to know when it is worthwhile to question algorithms and architectures. I use this primarily as an intuitive tool for 'in my head' or 'back of cocktail napkin' level calculation. It saves me a lot of time.
It's an essential tool for software design.

A:

What's important isn't the value that O bounds but the rate of growth of the value that O bounds. This is where Calculus comes in.
If you take the derivative of log(n) for instance, you get 1/n as the rate of change. This means that the time taken by a log(n) algorithm grows as a rate of 1/n meaning that as you add more and more values to the set, you get a smaller value for f(1/n). The same hold true over n'= 1, n^c' where c is some constant = cn and c^n' = c^n(log(c)). Thus you have a much, much slower rate of growth for time taken for the lower orders than for the higher ones. Once you hit exponential, the rate of growth begins to grow at a rate greater than the base function.
Thus understanding Big O allows you to easily compare algorithms time per input even if the input is never 'infinite'. Incidentally, infinite in software development or CS often means "Arbitrarily Large" rather than the technical, mathematical infinity since computers in practice are finite devices.


Q:

How to reorder Django-Graphene sub-query?

I am trying to reorder my ProductLandingPageImageNode according to a 'order' field on my ProductLandingpageImage Model.
If this would be a direct query I could write a resolve method, but I cannot find out how this is possible on a sub-query.
MAIN QUERY:
class Query(graphene.ObjectType):
  class Meta:
    interfaces = [relay.Node, ]

  product_oscar = graphene.List(ProductNode)
  productByID = DjangoFilterConnectionField(ProductNode)

  def resolve_product_oscar(self, info, **kwargs):
    return Product.objects.all()

PRODUCTNODE:
class ProductNode(DjangoObjectType):
  class Meta:
    model = Product
    interfaces = (relay.Node, )
    filter_fields = {
      "slug" : ['iexact']
    }

PRODUCTLANDINGPAGEIMAGENODE:
class ProductLandingpageImageNode(DjangoObjectType):
  class Meta:
    model = ProductLandingpageImage
    interfaces = (relay.Node, )

How to solve this?

LANDINGPAGEIMAGE MODEL on request:
class AbstractProductLandingpageImage(models.Model):
  """
    A landingpageimage of a product
  """
  product = models.ForeignKey(
    'catalogue.Product',
    on_delete=models.CASCADE,
    related_name='landingpage_image',
    verbose_name=_("Product landingpage"))
  date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  original = models.ImageField(
    _("Landingpage original"), upload_to=settings.OSCAR_IMAGE_FOLDER, max_length=255, blank=True)

  ORDER_CHOICES = (
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5),
    (6, 6),
  )

  order = models.PositiveIntegerField(default=1, choices=ORDER_CHOICES, blank=True)

class Meta:
    abstract = True
    app_label = 'catalogue'
    # Any custom models should ensure that this ordering is unchanged, or
    # your query count will explode. See AbstractProduct.primary_image.
    ordering = ["order"]
    verbose_name = _('Product landingpage image')
    verbose_name_plural = _('Product landingpage images')

The default ordering in the Meta does somehow not work. What is also strange when I Graphql query for the order value is not not return "1, 2, 3..." but "A_1, A_2..."

A:

Maybe something like this.  Since you don't list your Product model, I just made up the name of the field on Product that references the image, so you should rename that.  If there's a many-to-one relationship  relationship between product and image maybe you want a different field name.
import graphene
from graphene.django.types import DjangoObjectType

class ProductNode(DjangoObjectType):
    name_of_your_image_field = graphene.Field(ProductLandingpageImageNode)

    class Meta:
        model = Product
        ... other Meta data

    def resolve_name_of_your_image_field(self, info):  # rename to match field
        # Put the code that returns a single ProductLandingpageImage instance here
        # graphene-django will convert your ProductLandingPageImage instance into a ProductLandingpageImageNode

This is for returning a single ProductLandingPageIMage . If you want to return multiple instances, then change the field definition to a list
    name_of_your_image_field = graphene.List(ProductLandingpageImageNode)

and then in your resolver return multiple ProductLandingPageImage instances -- for example a queryset that is sorted the way that you want it.


Q:

question about the definition of the exterior square of a group

On groupprops, one definition they give of the exterior square of a group is as follows:
Let $G$ be a group, and let $F$ be the free group on the generating set $G\times G$. For any central extension $E$ of $G$, the commutator map $G\times G\rightarrow [E,E]$ given by sending $(g_1,g_2)\mapsto[\tilde{g_1},\tilde{g_2}]$, where $\tilde{g_1},\tilde{g_2}$ are lifts of $g_1,g_2$ to $E$, which is not well defined, but their commutator is, since the kernel of $E\rightarrow G$ is central. For every central extension $E$, this map induces a surjective homomorphism $\Omega_E : F\twoheadrightarrow [E,E]$. Then, they define the exterior square $G\wedge G$ of $G$ to be the quotient of $F$ by the intersection of all kernels of all maps $\Omega_E$.
My question is - For any central extension $E\rightarrow G$, isn't $[E,E]\cong [G,G]$, so really the maps $\Omega_E$ are all essentially the same map $F\twoheadrightarrow [G,G]$, so all the kernels are the same?
What am I missing?
EDIT: Okay, so given any commutator $[g_1,g_2]\in [G,G]$, this defines a unique commutator $[\tilde{g_1},\tilde{g_2}]\in [E,E]$. Does this map define an injective homomorphism $[G,G]\rightarrow [E,E]$?

A:

Your proposed map $[G,G] \to [E,E]$ isn't well defined.  It's possible that $[g_1, g_2] = [h_1, h_2]$, but the lifts $[\tilde{g_1}, \tilde{g_2}] \ne  [\tilde{h_1}, \tilde{h_2}]$.
Consider the case $E = Q_8$ (the quaternion group).  The center of $E$ is $\{1, -1\}$ and the quotient $G := E/Z(E) \cong C_2 \times C_2$.  The map $E \to G$ is the quotient map. Since $G$ is abelian, we have $[G,G] = 1$ i.e., no matter what we choose $g_1$ and $g_2$ to be, we get $[g_1, g_2] = 1$.  But when we lift we can get anything in $[E,E] = \{1, -1\}$, so the map $[G,G] \to [E,E]$ isn't well defined.


Q:

Importing Wavefront .obj files for android

What is the best way importing .obj files to android app created in Blender? I want the best and the easyest variant! How about a link to a tutorial?

A:

Personally I have implemented the OBJ reader long time ago in Android Native C and in that case the issue is quite more complicated than doing it in Java.
The easiest way is to open the file in text mode and parse the file following its logic.
The logic i very very simple and you can find the file format here:
http://www.martinreddy.net/gfx/3d/OBJ.spec
The writing of such a code won't take more than 2 days of an average skilled developer, i suggest you to do it your own to have a better control of your code.
In alternative, if you want it ready, you can find and adapt this Java loader:
http://www.java2s.com/Code/Java/3D/ObjectFileLoader.htm
Cheers


Q:

SSH keys in build environment when using multibranch pipeline Jenkinsfile

I have a project being built on Jenkins using the multibranch pipeline plugin. I am using the declarative pipeline syntax and my Jenkinsfile looks something like this:
pipeline {
    agent { label 'blah' }
    options {
        timeout(time: 2, unit: 'HOURS')
        buildDiscarder(logRotator(numToKeepStr: '5'))
    }
    triggers { pollSCM('H/5 * * * *') }
    stages {
        stage('Prepare') {
            steps {
                sh '''
                  echo "Building environment"
                  python3 -m venv venv && \
                  pip install git+ssh://git@my_private_repo.git
                '''
            }
        }
    }
}

When the build is run on the Jenkins box the build fails and when I check the console output it is failing on the pip install command with the error:
Permission denied (publickey).
fatal: Could not read from remote repository.

I am guessing that I need to set the required ssh key into jenkins build environment, but am not sure how to do this.

A:

You need to install the SSH Agent plugin and use it to wrap the actions in the steps directive in order to be able to pull from a private repository. You enable the SSH Agent with the sshagent directive, where you need to pass in an argument representing the hash for a valid key with read permissions to the git repository. The key needs to be available in the global credentials view of Jenkins (Jenkins -> Credentials [on the left-hand side menu], search for the ID field of the right key), e.g.:
    stage('Prepare') {
        steps {
            sshagent(['<hash_for_your_key>']) {
                echo "Building environment"
                sh "python3.5 -m venv venv"
                sh "venv/bin/python3.5 venv/bin/pip install git+ssh://git@my_private_repo.git
            }
        }

N.B.: Because the actions under the steps directive are executed as subprocesses, you'll need to call explicitly the executable files from the virtual environment, using long syntax.


Q:

Gatsby: Trying to get image path from front matter but getting this "TypeError: Cannot read property 'image' of undefined"

Im building a blog with Gatsby and I'm trying to display a hero image on each post page with the image path that is defined in each posts front matter. But, I'm getting this error from my hero component:
TypeError: Cannot read property 'image' of undefined
Here is my code:
Post front matter
---
path: /blog-post1
title: Blog Post 1
image: ../../images/blog-post-1.jpg
description: Blog post description
---

Hero.js
import React from 'react'
import Img from "gatsby-image";

const Hero = props => (

);

export default Hero

Post.js
import React from 'react';
import { graphql } from 'gatsby';

import Layout from '../components/layout';
import Hero from '../components/hero';

const PostTemplate = ({ data }) => {
  const { markdownRemark } = data;
  const { frontmatter, html } = markdownRemark;
  return (
    <Layout>

      <Hero headerImage={frontmatter.image} />

    </Layout>
  )
}

export default PostTemplate;

export const pageQuery = graphql`
  query($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
        date
        path
        title
        description
        image {
          childImageSharp {
            resize(width: 1500, height: 1500) {
              src
            }
            fluid(maxWidth: 786) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`;

Any ideas on what's happening? Thanks in advance.

A:

I figured out was the issue.
In my hero.js, I was calling the image using {props.frontmatter.image.childImageSharp.resize}
But in my post.js I was passing the data into the hero component like this <Hero headerImage={frontmatter.image} />
So, it was trying to find frontmatter.image.image, which doesn't exist. All I had to do was remove the .image like this


Q:

Why execvp accepts 2 arguments

Assume the following code in c:
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char * argv[]) {
  char *args[] = {"/bin/echo", "1", NULL};
  execvp(args[0], args);
}

Why does execvp accept 2 arguments? Why can't it be execvp(args) and internally it would automatically grab the executable to run from args[0] ?

A:

What if you want the "name" of the process (args[0] in your case) to be different from the actual executable program? That is a valid use-case, and the simplest solution to handle both the cases is the two-argument execvp we now have.


Q:

jQuery Ajax PHP POST method with response array[] instad sent data. How to get send values in response?

I am creating simple application which will insert log data into database table.
Going with jQuery Ajax POST method and JSON format for data.
My index.php has HTML and this code:
<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery.ajax({
        type: "POST",
        url: "http://www.example.com/ajax_model.php",
        data: {
            "log_session": "27738d7552b75ae395ae1138adf4fa60",
            "log_ip": "1.2.3.4",
            "log_vrijeme": "2018-11-23 01:22:47",
            "log_model": "12345"
        },
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function(response) {
            console.log(response);
            alert(response);
        },
        error: function(error) {
            console.log(error);
        }
    });
});
</script>

My ajax_model.php - which gives me response Array[] instad the data which is sent:
<?php
if(isset($_POST)){
    header('Content-Type: application/json');
    echo json_encode($_POST);
    exit;
}
?>

I am getting result in my console.log() and alert() - Array[].
How can I output my sent response to check if the data was correctly sent over Ajax?
Am I missing some brackets like [] or {}?
Or do I need to add something to my ajax_model.php file?
Thank you for suggestion and provided information.

A:

You aren't sending JSON so get rid of:
 contentType: 'application/json; charset=utf-8',

That will cause $_POST to be empty as the default contentType is:
application/x-www-form-urlencoded; charset=UTF-8


Q:

Delay "unhover" action

#login-panel-ghost {
  display: none;
  transition-delay: 2s;
}
.top-menu-login:hover #login-panel-ghost {
  display: block;
  position: fixed;
  width: 250px;
  height: 180px;
  transition-delay: 2s;
}
Login

Log in!

    <form>
      <input type="text" placeholder="Username">
    </form>

Now, let me explain what I would like to accomplish: I've a span .top-menu-login which will be displayed as a phrase, in this case "Login". Furthermore, the div #login-panel-ghost is originally hidden, but when the mouse passes over "Login" the div should appear.
I managed to do that, the problem is that I would like to delay the element disappearing after the mouse unhovers the "Login"!
I've tried this code so far, that I found on Stack Overflow, but I think the fact that the hover changes another div is causing trouble.
P.S. I know it should be easy with JavaScript, but I'd like to try without it!

A:

You are on the right lines using transition-delay: 2s;, however, there are a couple of factors that mean this won't work:

You cannot animate display, it is either there (display: block;) or not (display: none;)
You are not specifying a transition so there is nothing for transition-delay: 2s; to effect

To make this work using CSS you can do the following:

Add height: 0; to #login-panel-ghost to effectively hide the element
Add height: 180px; to .top-menu-login:hover #login-panel-ghost to effectively show the element
Transition on the height changing it from 0 to 180px by adding transition: height 0s; to #login-panel-ghost
Add overflow: hidden; to allow the content that exceeds the boundries of #login-panel-ghost to be hidden
Add transition-delay: 2s; to #login-panel-ghost to delay the transition when .top-menu-login is not hovered over
Add transition-delay: 0s; to #.top-menu-login:hover #login-panel-ghost to ensure there is no delay when the user hovers over the element

#login-panel-ghost {
  height: 0;
  overflow: hidden;
  transition: height 0s;
  transition-delay: 2s;
}
.top-menu-login:hover #login-panel-ghost {
  height: 180px;
  position: fixed;
  transition-delay: 0s;
  width: 250px;
}

Login

Log in!

    <form>
      <input type="text" placeholder="Username" />
    </form>


Q:

What is $f$? Finding where a function converges pointwise?

I have a question.

Let $f_n(x) = x^{4n} + \frac1{n^2}$. AS $n \to \infty$, $f_n$ converges pointwise to a function $f$ on $[0,1]$
What is $f$?

Now if I am understanding correctly, couldn't $f$ be many things? Since we have $[0,1]$ wouldn't it be correct to say that $f = 1$, since $f_n(x) = 1^{4n} + 0 = 1$ That gives point-wise convergence right? What about $f(x) = x$ this should give uniform convergence on $[0,1]$ to $0$ right? But I need pointwise convergence, so I suppose I need to choose some value $[0,1]$
Also, is there a way to disable the automatic rendering below(the one that shows my $LaTeX$ rendered? It is lagging this old laptop to a crawl.

A:

When $x<1$, the value for $x^{4n}+\frac1{n^2}$ as $n$ increases without bound is $0+0$. The first $0$ is because large powers of $x$ approach $0$.
When $x=1$, the value for $x^{4n}+\frac1{n^2}$ as $n$ increases without bound is $1+0$.
Thus, on $[0,1]$, $f_n$ approaches a step function: its pointwise limit is $0$ on $[0,1)$ and $1$ at $x=1$.


Q:

Django admin change plural model names

My Django (Grappelli theme) admin lists all my apps and then the model names are displayed in plural form. To convert the name to plural, Django adds an 's' to the name of the model, however some of these are incorrect.  For example, 'Product categories' becomes 'Product categorys'
How can I change the names displayed in the admin views for these?

A:

You need to specify a verbose_name_plural attribute in your model's Meta subclass.
Check: https://docs.djangoproject.com/en/1.10/ref/models/options/#django.db.models.Options.verbose_name_plural for more info.


Q:

Avoid crashing from shared drive

my program is located on a shared drive, but it can happen that the computer loses the connection to the shared drive, for whatever reason. the program would crash. is there a way to create a "cache" or something so that the program can still be used? i heard that there is a compiler setting in Delphi, but i found nothing about .net.

A:

You can try following
"C:\Program Files (x86)\Microsoft Visual Studio
14.0\VC\bin\editbin.exe" /swaprun:CD /swaprun:NET YourApp.exe


Q:

Prevent Caching in SQL Server

Having looked around the net using Uncle Google, I cannot find an answer to this question:
What is the best way to monitor the performance and responsiveness of production servers running IIS and MS SQL Server 2005?
I'm currently using Pingdom and would like it to point to a URL which basically mimics a 'real world query' but for obvious reasons do not want the query to run from cache. The URL will be called every 5 minutes.
I cannot clear out the cache, buffers, etc since this would impact negatively on the production server. I have tried using a random generated number within the SELECT statement in order to generate unique queries, but the cached query is still used.
Is there any way to simulate the NO_CACHE in MySQL?
Regards

A:

To clear the SQL buffer and plan cache:
DBCC DROPCLEANBUFFERS
GO
DBCC FREEPROCCACHE
GO

A little info about these commands from MSDN:

Use DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server. (source)
Use DBCC FREEPROCCACHE to clear the plan cache carefully. Freeing the plan cache causes, for example, a stored procedure to be recompiled instead of reused from the cache. (source)

A:

SQL Server does not have a results cache like MySQL or Oracle, so I am a bit confused about your question. If you want the server to recompile the plan cache for a stored procedure, you can execute it WITH RECOMPILE. You can drop your buffer cache, but that would affect all queries as you know.
At my company, we test availability and performance separately. I would suggest you use this query just to make sure you your system is working together from front-end to database, then write other tests that check the individual components to judge performance. SQL Server comes with an amazing amount of ways to check if you are experiencing bottlenecks and where they are. I use PerfMon and DMVs extensively. Using PerfMon, I check CPU and page life expectancy, as well as seeing how long my disk queue is. Using DMVs, I can find out if my queries are taking too long (sys.dm_exec_query_stats) or if wait times are long (sys.dm_os_wait_stats).
The two biggest bottlenecks with IIS tend to be CPU and memory, and IIS comes with its own suite of PerfMon objects to query, but I am not as familiar with those.


Q:

How can i handle negative value in reverse order in big decimal in java?

I have one problem in BigDecimal with handling negative value in reverse order. I got a NumberFormatException. How can I solve it?
This is my code:
import java.math.BigDecimal;

public class Java_bigdecimal_signum {
    public static void main(String args[]) {

        BigDecimal obj = new BigDecimal("20.15-");
        int i = obj.signum();
        System.out.println("\nobject value : " + obj
                         + "\nmethod generated value : " + i);
    }
}

Exception is:
Exception in thread "main" java.lang.NumberFormatException
at java.math.BigDecimal.<init>(Unknown Source)
at java.math.BigDecimal.<init>(Unknown Source)
at Java_bigdecimal_signum.main(Java_bigdecimal_signum.java:6)

I need output below:
object value : -20.15
method generated value : -1

Thanks in Advance.

A:

Well, I am assuming that your getting your number String with the minus on the end from somewhere else in your actual code, rather than passing a String literal to BigDecimal. If so, you can just process the String variable before passing it to BigDecimal, and move the - from the end to the beginning like so.
import java.math.BigDecimal;

public class Java_bigdecimal_signum {
    public static void main(String args[]) {
        String number = "20.15-";
        if(number.endsWith("-")){
            number = "-" + number.substring(0, number.length() -1);
        }
        BigDecimal obj = new BigDecimal(number);
        int i = obj.signum();
        System.out.println("\nobject value : " + obj
                     + "\nmethod generated value : " + i);
    }
}

And, to state the obvious, If you really are just passing a String literal to BigDecimal as in your example code, then just put the minus on the beginning. :)
Hope this helps.


Q:

Powershell silent / unattended install of Delphi Tokyo 10.2 - for CI use in win docker container

I'm attempting to create a powershell command that silently installs Delphi Tokyo 10.2 - to be used as an automated compiler in a Windows Docker container. I've not been able to find any recent documentation on how to implement an unattended/silent installation using the proper installer commands / switches.
I was able to determine that the Tokyo and Rio installers use Inno Setup  - and should be given Inno Setup installer commands/switches.
From the Tokyo installer about page:
https://photos.app.goo.gl/88jY7PF2mPAipwEA9
This is the command I've messed with thus far:
.\radstudio10_2_3_esd__93231.exe /sp- /verysilent /suppressmsgboxes /norestart/ /log="c:\somelocation\install.log"

However I am not able to get the install process to go past the first page or EULA checkbox. The failed silent install log shows:
Log opened. (Time zone: UTC-05:00)
Setup version: Inno Setup version 5.5.6 (u)
Original Setup EXE: C:\somelocation\radstudio10_2_3_esd__93231.exe
Setup command line: /SL5="$18051C,138809719,642048,C:\somelocation\radstudio10_2_3_esd__93231.exe" /sp- /verysilent /suppressmsgboxes /norestart/ /log=c:\somelocation\install.log
Windows version: 10.0.18363  (NT platform: Yes)
64-bit Windows: Yes
Processor architecture: x64
User privileges: Administrative
64-bit install mode: No
Created temporary directory: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\innocallback.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\UnlockFirewall.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\mOasisRuntime.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\topbanner96.bmp
Failed to proceed to next wizard page; aborting.
Got EAbort exception.
Deinitializing Setup.
Log closed.

Here's a portion of the logs from a non-silent install of the same installer package:
Log opened. (Time zone: UTC-05:00)
Setup version: Inno Setup version 5.5.6 (u)
Original Setup EXE: C:\somelocation\radstudio10_2_3_esd__93231.exe
Setup command line: /SL5="$405F0,138809719,642048,C:\somelocation\radstudio10_2_3_esd__93231.exe" /log=c:\somelocation\install.log /saveinf=c:\somelocation\install.inf
Windows version: 10.0.18363  (NT platform: Yes)
64-bit Windows: Yes
Processor architecture: x64
User privileges: Administrative
264-bit install mode: No
Created temporary directory: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\innocallback.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\UnlockFirewall.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\mOasisRuntime.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\topbanner96.bmp
Message box (OK):
Inno Setup version 5.5.6 (u)
Copyright © 1997-2015 Jordan Russell
Portions Copyright © 2000-2015 Martijn Laan
All rights reserved.

Inno Setup home page:
http://www.innosetup.com/

RemObjects Pascal Script home page:
http://www.remobjects.com/ps
User chose OK.
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Starting the installation process.
Creating directory: C:\Program Files (x86)\Embarcadero
Creating directory: C:\Program Files (x86)\Embarcadero\Studio
Creating directory: C:\Program Files (x86)\Embarcadero\Studio\19.0
Directory for uninstall files: C:\Program Files (x86)\Embarcadero\Studio\19.0\
...
...
...

So in the above successful non-silent install - notice the line in the logs that says Message box (OK) this occurs after I accept the EULA. So at present i'm not sure how to pass an installer switch to suffice the EULA page silently.
Has anyone had success with creating a silent / unattended install of Delphi Tokyo or Rio? Or has found documentation that helped them achieve something similar?
Any help is much appreciated!
Kind Regards,

A:

For Delphi 2007 and Delphi XE2 we were able to do a silent installation with setup.exe /s, see https://delphisorcery.blogspot.com/2011/07/unattended-delphi-installation-how.html for reference.
But this did not work for Delphi 10.2 Tokyo anymore. So our IT department called Embarcadero directly for more information on how to do a silent installation. But unfortunately they told us, the installation process can not be done silently!


Q:

Can "pouvoir" be translated/interpreted to meanings other than "can" ?

(I was not exactly certain on how to phrase this question, so bear with me.)
The majority of times when French learners encounter the verb pouvoir, they think of the word as its common English counterpart can; However, I was curious to know whether it should be thought as to have the ability; be able to perform an action
For example in this case:

Mon frère était ravi de pouvoir me parler encore !

To represent

My brother was ecstatic to be able to talk to me again !

Another example:

Il voulait pouvoir y participer ce soir, puisque sa femme l'avait empêché d'y participer hier.

For

He wanted to be able to participate in it tonight, since his wife had prevented him from participating yesterday.

There may be some instances, such as this:

I want to have the ability to make my own decisions.

Where you could use pouvoir in this instance ?

J'ai envie de pouvoir prendre mes propres décisions.

Can pouvoir presented as such, if so would it be more practical to think of it as such when translating/interpreting ?

A:

The primary meaning of 'pouvoir' is "to have the power to", but it is widely used in many different context (ability, possibility, permission) so that a translation out of context is quite difficult.
In your first example, it seems that the ability is stressed, but maybe he was expecting that I would not talk to him anymore because of some very disappointing behaviour.
In your second example, the permission is stressed. (his wife did not want him to go).
Your last sentence makes sense to me, but you need to remove the de

J'ai envie de pouvoir prendre mes propres décisions.

EDIT: Comme j'essaie de l'expliquer dans mon pauvre anglais, le verbe pouvoir s'utilise dans beaucoup de situations: c'est une valeur sûre! Cependant, cette diversité peut nuire à la bonne compréhension de la phrase hors contexte, donc il vaut parfois mieux utiliser un terme plus précis.
Si vous me dites "j'ai envie de pouvoir prendre mes propres décisions", la première interprétation qui me vient à l'esprit est qu'une autorité (parent, patron...) prend toutes les décisions à votre place (et vous devez toujours obéir).
Avec  "j'ai envie d'avoir l'occasion de prendre mes propres décisions", vous vous êtes émancipé de cette autorité mais les circonstance ne vous ont pas encore offert la possibilité (les événements se sont enchaînés trop vite pour qu'une décision puisse se prendre). Le verbe pouvoir s'utilise aussi dans ce sens-ci, et la construction est moins lourde, donc votre choix doit se baser sur le contexte (en privilégient la simplicité à l'orale et la clarté dans un texte officiel).


Q:

Why is the point of failure load lower than the peak load?

In a tensile test the peak load was 69kN, but the point of failure load was 60kN. Why is it lower?

A:

That is due to necking.
When a bar is under tension, two opposing mechanisms take place:

The bar loses cross-sectional area since it attempts to retain its volume while being stretched (see Poisson's ratio).
Once the bar begins to suffer plastic deformations, it undergoes stress hardening and it's elastic modulus rises.

So long as the increase in elastic modulus is greater than the loss of area, the stress (or force) measured will increase. At a certain point, however, the material starts to lose area faster than it hardens, which means that the force required to continue deforming the element starts to diminish, until the element reaches its ultimate deformation capacity and snaps.
Now, if you'd been measuring the force and dividing by the element's original cross-sectional area to get stress results, then these would have the same profile as the force results: increasing up to the peak load and then dropping to point of failure. This is known as engineering stress.
If, however, you use special equipment to measure the actual cross-sectional area as it changes during the test, then you'll see that the stress actually increased during the entire test due to stress hardening. This is known as true stress.
Here's a graph showing the difference between engineering and true stress. The red line represents engineering stress and the blue, true stress.

Source: Wikipedia
As the name implies, engineers tend to use engineering stress for the simple reason that it is infinitely easier to measure and design with. And as the diagram above demonstrates, the difference between engineering and true stress in the elastic range where we spend 95% of our time is very small.


Q:

Can “We would be happy if everyone is good, therefore we have no military force” and “Japan have military force” be congruent grammatically?

There was the two separate quotes from Shigeru Ishiba, secretary general of the LDP in the interview to TIME appearing in the article titled, “Return to the Samurai” (October 7):
http://content.time.com/time/magazine/article/0,9171,2153060,00.html

“The constitution says Japan doesn’t possess an army, navy or air
  force. Is it true? Japan does have an army, a navy, an air force. We have
  lots of warplanes and tanks. Let’s stop telling a lie."

And later, he says:

“We would be happy if everyone in the world is good, and therefore we
  have no military force.”

To me it appears as if he is admitting Japan have military force in the first quote and denying it in the second quote.
Though I think Ishiba is saying that we are happy not to have military force if everyone in the world is good, but we have military force as it is contrary, is the above two statements grammatically congruent? If no problem, the case is closed. If not, how should it be rephrased in order for avoiding a confusion that I was induced to?
Please understand that I have no intent to discuss political implications of the above quotes at all.
I’m only interested in the grammatical correctnessn of them.

A:

“We would be happy if everyone in the world is good, and therefore we have no military force.”

I would paraphrase it like this, If I understand it correctly:
"We would be happy if everyone in the world was good. Then, we wouldn't need to have a military force."
I don't think it was meant to be a contradiction to the earlier statement.


Q:

Closed laptop lid during installation, black screen

I tried to perform an installation of Ubuntu 14.04 in a dual boot setup with Windows 8.1 using a LiveUSB.
I selected a 17GB disk to install Ubuntu on. The disk was empty according to Windows, and formatted with FAT32. According to the Ubuntu installation, 33MB of the disk was used though.
Anyway, I selected the option 'something else', as the option to install alongside windows wasn't available (perhaps because the drive has more than four partitions?) and then selected only this 17GB disk, as mount point /, with FAT32.
Then the device needed a lot of time, over two hours, to write the changes to the disk. I hadn't expect it to take so long for just 17GB, and went to bed. I closed the lid of my laptop. When I woke up this morning, the device was still running. However, when I opened the lid, the screen stayed black.
I closed it again and opened it, and then saw some text, like when you start up or shutdown Ubuntu. The text was:
nouveau E[  PDISP] [0000:01:00.0][0xc000907c][ffff880222a2f400] fini: 0xc2061088
nouveau E[  PDISP] [0000:01:00.0][0xc000907c][ffff880222a2f400] failed suspend, -16
nouveau E[    DRM] 0xd1500000:0xd15c7c00 suspend failed with -16
nouveau E[    DRM] 0xdddddddd:0xd1500000 suspend failed with -16
nouveau E[    DRM] 0xffffffff:0xd1500000 suspend failed with -16
nouveau E[    DRM] 0xffffffff:0xffffffff suspend failed with -16
pci_pm_suspend(): nouveau_pmops_suspend+0x0/0xb0 [nouveau] returns -16
dpm_run_callback(): pci_pm_suspend+0x0/0x150 returns -16
PM: Device 0000:01:00.0 failed to suspend async: error -16
PM: Some devices failed to suspend, or early wake event detected

After a second, the screen goes black again. Any time I close and open the lid I see this text (added to the text that was already there from last time), but just for one second.
The special function key to enable/disable the built-in screen doesn't have any effect, nor does ctrl-alt-del or ctrl-shift-esc. I tried connecting an external display, again with no success.
I'm reluctant to power off the device as it was doing something with partitions and don't want to lose my data.
How to get out of this strange mode?
The laptop in question is a Lenovo U410.

A:

I am not sure that any damage has been done, but I don't see how powering off your device could make it worse at this point.
You will need to reinstall Ubuntu though. Install it in the 17G partition, which should be formatted as ext4 and with / as the mount point. The bootloader should also go on the disk (not the partition) to let you choose the OS. The guide you mentioned has good points on this in the troubleshooting section.
If properly done the installation should take less than two hours, or at least you should notice some progress or animation.
(compiled from the comments)


Q:

Изменить state React- компонента по кнопке которая не является частью React-компонента

Как изменить state React- компонента по нажатию кнопки , которая не является частью React-компонента - является простой HTML кнопкой ?
(можно ссылку на пример  кода)

A:

Просто в componentDidMount добавьте кнопке обработчик нажатия из своего компонента:

class ComponentForButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msgText: 'Nothing',
      clickCount: 0
    }
  }

  componentDidMount() {
    let button = document.getElementById("myButton");
    button.addEventListener("click", this.onButtonClick);
  }

  onButtonClick = () => {
    let next = this.state;
    this.setState({
      msgText: 'Click',
      clickCount: next.clickCount + 1
    });
  }

  render() {
    return(

{this.state.msgText} {this.state.clickCount} times

    );
  }
}

ReactDOM.render(
  <ComponentForButton/>,
  document.getElementById('root')
);

<button type="button" id="myButton">Click me</button>


Q:

How can I refactor the Switch Statements

I am trying to refactor the mother of all switches and am not really sure how to do it. Here is the existing code:
    private void SetPrepareFiles(
                  ObservableCollection<PrepareElement> prepareElements)
    {
        DateTime fileLoadDate = DateTime.Now;

        string availabilityRequestFile = string.Empty;
        string infrastructureFile = string.Empty;
        string gsQualityFile = string.Empty;
        string pvdnpProducedFile = string.Empty;
        string docFile = string.Empty;
        string actualCurrentStateFile = string.Empty;
        string actualIpPlanFile = string.Empty;

        foreach (var prepareElement in prepareElements)
        {
            switch (prepareElement.MappingName)
            {
                case "AvailabilityRequest":
                    availabilityRequestFile = prepareElement.FileName;
                    break;
                case "SystemInformation":
                    docFile = prepareElement.FileName;
                    break;
                case "ITStatus":
                    infrastructureFile = prepareElement.FileName;
                    break;
                case "ActualIPPlan":
                    actualIpPlanFile = prepareElement.FileName;
                    break;
                case "ActualCurrentState":
                    actualCurrentStateFile = prepareElement.FileName;
                    break;
                case "Produced":
                    pvdnpProducedFile = prepareElement.FileName;
                    break;
                case "Quality":
                    QualityFile = prepareElement.FileName;
                    break;
            }

        }

        var fc = new FilesConverter.FilesConverter();
        fc.SetCommonFiles(availabilityRequestFile, actualCurrentStateFile,
                               actualIpPlanFile, fileLoadDate);

    }

How would I refactor this Switch to a Dictionary

A:

What about
Dictionary<string, string> fileMappings =
   prepareElements.ToDictionary(e => e.MappingName, e => e.FileName);


Q:

jQuery UI Draggable - drag beyond absolute positioning

I am unable to see the elements that i am dragging once they leave a parent element that has absolute positioning. (Cant see the draggable helper as it moves)
Check out the example at http://nairobi.io/tests/jquery-ui-draggable
Kindly help me fix this problem.

A:

You've misspelled "appendTo" as "apendTo" in your draggable initialiser (line 138), which means the helper is not being added to the right place.


Q:

Css как сделать чтобы изображение было по центру

https://vk.com/im?sel=206691271&z=photo206691271_456240810%2Fmail155797
https://vk.com/im?sel=206691271&z=photo206691271_456240811%2Fmail155798
как мне сделать чтобы при увеличении масштаба .lol был по центру?
делаю сайт резиновым

  a:active {
  color: black;
}

a:hover {
  color: slategrey;
}

a {
  text-decoration: none;
  color: black;
}

ul li {
  list-style-type: none;
}

li {
  display: inline-block;
  margin-right: 5%;
  margin-left: 5%;
}

ul {
  background: #f6f9bf;
}

.nav {
  background: #f6f9bf;
  padding-top: 5px;
  text-align: center;
  padding-bottom: 1%;
}

.nav a {
  font-size: 240%;
}

html {
  font-family: Tahoma;
  margin: 0px auto;
}

header {
  background: #f6f9bf;
}

body {
  margin: 0px!important;
}

.screen {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url("masina.png") no-repeat;
  background-size: 100% 100%;
}

.lol {
  margin-top: 51%;
  box-sizing: border-box;
  margin-left: auto;
  display: block;
  top: 106%;
  background: #f6f9bf;
  padding: 0px 303px 0px 300px;
}

.lel {
  position: absolute;
  border: 10px solid black;
  box-sizing: border-box;
  padding-top: 50px;
  padding-bottom: 50px;
  padding-left: 7%;
  padding-right: 7%;
  left: 2%
}

th,
td {
  border-bottom: 2px solid black;
  color: black;
  font-size: 32px;
  padding-left: 200px;
  padding-bottom: 40px;
}

.lole {
  position: absolute;
  top: 2200px;
  left: 100px;
  padding: 100px 100px 10px 100px;
  border: 5px solid black;
  background: #f6f9bf;
  border-radius: 10px;
  font-size: 30px;
}

input,
textarea {
  margin-bottom: 100px;
  padding: 15px 15px 15px 100px;
  background: #f6f9bf;
  font-size: 25px;
  border: none;
}

input,
textarea:focus {
  outline: none;
}

input,
textarea {
  border-bottom: 3px solid black;
}

.lp {
  box-sizing: border-box;
  width: 1903px;
  height: 80px;
  background: darkgrey;
  position: absolute;
  top: 3500px;
}

.contact {
  border-bottom: 2px solid black;
  display: inline-block;
  margin-top: 3200px;
  margin-left: 100px;
<!DOCTYPE Html>

  <meta charset="utf-8">

  <link rel="stylesheet" href="class.css">

                    ЗАКАЗАТЬ

ЦЕНЫ

КОНТАКТНЫЕ ДАННЫЕ

О НАС

        Марка
        Цена самовывоза
        Цена с доставкой

        m100
        3000
        3500
        Заказать

        m200
        4500
        5000
        Заказать

          m400
          5509
          6000
          Заказать

    Обратная сзязь ,Оставте ваш номер
 телефона и мы вам перезвоним

    <form method="post" enctype="multipart/form-data" name="form">

<input type="text" class="form_name" pattern="^[А-Яа-яЁё\s]+${1,17}" required placeholder="Ваше имя" name="name">

<input type="tel" class="form tel" required pattern="[0-9+]{9,11}" placeholder="Ваш номер телефона" name="num">

<textarea type="text" class="form zak" required placeholder="Ваш заказ" name="text"></textarea>
      <button class="some-form__button" name="but">Отправить</button>
      <?php
        if (isset ($_POST['but']) ) {
            require_once 'sms.ru.php';
            $smsru = new SMSRU('C3A6B841-6B90-4FD6-4ED5-B4FFB841F914'); // Ваш уникальный программный ключ, который можно получить на главной странице
            $name = trim($_POST['name']);
            $num = trim($_POST['num']);
            $text = trim($_POST['text']);

            if(empty($name)){
                echo "Поле имя пусто. ";
                /*Выход или редирект*/
            }

            if(empty($num)){
                echo "Поле номер пусто. ";
                /*Выход или редирект*/
            }

            if(empty($text)){
                echo "Поле заказ  пусто. ";
                /*Выход или редирект*/
            }
            if(!empty($name) && !empty($num) && !empty($text) ){

                $data = new stdClass();
                $data->to = '89065906733';
                $data->text = $name . "-" . $num . "-" . $text; // Текст сообщения

                $sms = $smsru->send_one($data);// Отправка сообщения и возврат данных в переменную
                if ($sms->status == "OK") { // Запрос выполнен успешно
                    echo "Сообщение отправлено успешно. ";
                    echo "Ваш новый баланс: $sms->balance";
                    sleep(10);
                    header("Location: ".$_SERVER['REQUEST_URI']);
                } else {
                    echo "Сообщение не отправлено. ";
                    echo "Код ошибки: $sms->status_code. ";
                    echo "Текст ошибки: $sms->status_text.";
                    sleep(10);
                    header("Location: ".$_SERVER['REQUEST_URI']);

                }
            }

        }?>

Контактные данные:

    <q>89023425523 </q> <q>5zcvxz@mail.ru</q> <q>5xhsxry@gmail.com</q>

 2018 Все права защищены. Bet.inc

A:

Оказывается можно применить text-align:center
и это действует если даже там нету текста жест кароче


Q:

Why does this Javascript DOM code only working FF, but not IE?

//create an instance of the XML parser
if (window.ActiveXObject)
{
    //Checking if the browser is IE
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false"; //make sure doc is fully loaded
    xmlDoc.load(strPath) //load the file in the parser
    if (xmlDoc.parseError.errorCode != 0)
    {
        alert("Error #: " + xmlDoc.parseError.errorCode;
    }
}

//for mozilla based browsers
else if (document.implementation && document.implementation.createDocument)
{
    xmlDoc= document.implementation.createDocument("","doc",null);
    xmlDoc.async=false; //make sure doc is fully loaded
    loaded = xmlDoc.load(strPath);
    if(!loaded)
    {
       alert("Error in XML File");
    }
}

//Parse the XML
var root = xmlDoc.documentElement;
level1Nodes = root.children;
for(var index1 = 0; index1 < level1Nodes.length; index1++)
{
    //Extract the markup content from XML
    var level1Node = level1Nodes[index1];
    var strName = level1Node.children[0].textContent;
    var strHeader1 = level1Node.children[1].tagName;
    var strHeader1Content = level1Node.children[1].textContent;
}

Is the "children" property available in the IE DOM Parser?

A:

In IE, an XML document does not implement the same document object model as an HTML document; in particular, XML Node objects don't have the children property, which is non-standard.
You should use the childNodes collection instead. However be aware that in Firefox and other browsers - and, IIRC, under very specific circumstances in IE - this collection will also include text nodes that contain only whitespace, such as line breaks in the original XML file. So you will need to check the nodeType property: if it has the value 1, it is an Element, and will have properties such as tagName.
Furthermore, as MSXML implements DOM Level 1, whereas Firefox implements DOM Level 3, you won't be able to use the textContent property, which was introduced in Level 3. Instead, you will have to iterate over the childNodes of nodeType === 3 and concatenate their nodeValue properties, and probably then will want to trim any leading or trailing whitespace. Alternatively, if you know that there will only ever be textNodes in there, call the normalize method of the element first to make sure it only has one text node child.
Nobody ever said this stuff was supposed to be easy :-(


Q:

For loop pauses, but prints out the Array all at once

I'm having trouble Grok'ing a simple JavaScript for loop.
Here is an example:

var arr = ["Banana", "Orange", "Apple", "Mango"];
for (i = 1; i <= 5; ++i) {
  setDelay(i);
}

function setDelay(i) {
  setTimeout(function(){
    for(const value of arr) {
    document.write(value);
    document.write("<br />");
    }
  }, i * 1000);
}

What I'm trying to do is pause after it prints the first value, but instead it runs the entire For loop then pauses. I think I'm trying to do something with for loops that just won't work, but I would like to know why.
Any help would be appreciated.
Plunkr here: https://plnkr.co/edit/tnmFrIRTDJI8T294Qh4z?p=preview
The example Javascript, setTimeout loops? didn't help me figure it out. I still got the concept wrong as George Pantazes points out.

A:

Inside setTimeout - instead of printing entire array just print current element.

var arr = ["Banana", "Orange", "Apple", "Mango"];
for (let i = 1; i < 5; ++i) {
  setDelay(i);
}

function setDelay(i) {
  setTimeout(function(){
    console.log(arr[i-1])
  }, i * 1000);
}


Q:

What does it mean to "know Shas"?

I've seen many sefarim that talk about finishing Shas, simply put, going through the sugyos and understanding them, even if you forget it. But what does it mean to "know Shas"? Does that mean I know word for word by heart? Is it the Concepts you know really well? Is it the tosfosim you've got down pat. What does it mean when one says, he "knows Shas". Sources Please

A:

Yeshivish has many ambiguous terms. This is one of them. I've heard this used by yeshiva students as well as rabbis / teachers and from what I can tell, there's no consistency in its meaning.
It could mean:

You've memorized all of Sha"s. Not necessarily word for word (though, I met one person years ago who, as far as about 50 people could tell, he really did do that.), but you know where things are. I.e., if someone mentioned a topic, you know exactly which page of which masechta (tractate) to find it.
You know and understand the various sugyot ("topics" out of lack of a better term) in sha"s. This includes all the arguments and discussions as well as all or most of the "major" commentaries explanations (Rash"i, Tosfot and perhaps a few of the other notable ones such as Ras"h, Ri"f, etc.) I've heard this idea used to mean every masechta or most of them.

There are probably other explanations of this term, and others are free to add or edit this list. However, the above are the main two that I can think of, now.
Incidentally, there is a book called "Yeshivish". I don't know if this term is mentioned there; I have the book home, and I'll try to find it. But, in general, there is no official "source" for yeshivish terminology. Also, the language (according to the book it is considered a "language" as it is a form of communication mainly within Jewish learning circles and mainly in U.S. and a few other English-speaking countries.)