text:
Q: Efficiency and delayed execution of OrderBy I have a list of objects which contain a date and value. There is one object per date, and an object for every date for the past several months. I am looking for the date where the value was changed to the most recent value.
Here is an example of what I mean:
<datevalue>
    <date>8-9</date>
    <value>5</value>
</datevalue>
<datevalue>
    <date>8-10</date>
    <value>6</value>
</datevalue>
<datevalue>
    <date>8-11</date>
    <value>5</value>
</datevalue>
<datevalue>
    <date>8-12</date>
    <value>5</value>
</datevalue>
<datevalue>
    <date>8-13</date>
    <value>5</value>
</datevalue>

In the above example, the current value is 5 because it is the value on 8-13, the most recent date. I want to return the 8-11 datevalue object because it is the day on which the value was changed to the most recent value. I don't want the 8-9 value because even though its the earliest day with the current value, the value was changed after that date.
Here was my first attempt to solve this:
DateValue FindMostRecentValueChange(List<DateValue> dateValues)
{
    var currentValue = dateValues
                        .OrderByDesc(d => d.date)
                        .Select(d => d.value)
                        .First();
    var mostRecentChange = dateValues
                            .OrderByDesc(d => d.date)
                            .TakeWhile(d => d.value = currentValue)
                            .Last();
    return mostRecentChange;
}

This works. However, it was pointed out to me that I was repeating the OrderByDesc for both operations. Considering that OrderByDesc could be an expensive operation, I wanted to not have to do it twice. Therefore I made a change:
DateValue FindMostRecentValueChange(List<DateValue> dateValues)
{
    var orderedDateValues = dateValues.OrderByDesc(d => d.date);
    var currentValue = orderedDateValues;
                        .Select(d => d.value)
                        .First();
    var mostRecentChange = orderedDateValues
                            .TakeWhile(d => d.value = currentValue)
                            .Last();
    return mostRecentChange;
}

Now I only call OrderByDesc once. It's an improvement, right? Well, maybe not. OrderByDesc is a delayed execution.
From what I understand, that means that the actual ordering isn't done until you ask for a value from it. So when you call First() while looking for the currentValue you perform the OrderByDesc, and then it's executed again when you call Last() while looking for the mostRecentChange. So does that mean that I'm still executing OrderByDesc twice?
Am I correctly interpreting how delayed execution operates? I would hope that the compiler would recognize this scenario and optimize it behind the scenes so that the execution is only called once, but I cannot find any information to support this theory. Can you help me wrap my head around the best way to optimize this solution?

A:
So does that mean that I'm still executing OrderByDesc twice?

Yes, that is correct.

I would hope that the compiler would recognize this scenario and optimize it behind the scenes so that the execution is only called once, but I cannot find any information to support this theory.

It cannot, because that would change the intended functionality in several key ways.

*

*If the underlying data changes, those changes should be reflected when iterating the sequence again.  If you added a new item to dateValues between the first query and the second, it should be there in the second query.  If you removed an item, it shouldn't be there, etc.

*To get what you're asking for it would need to store all of the items in some sort of collection, even after the first consumer was "done" with them.  That is undesirable.  The idea here is that you can stream the data, and that once you've finished processing an item you're "done" with it, and don't need to hold it in memory.  What if you don't have enough memory to hold onto all of the items in the query for subsequent runs?

Can you help me wrap my head around the best way to optimize this solution?

It's quite trivial.  Just populate a data structure with the results of the query.  The easiest way to do this, just put them all in a list.  Add a ToList call to the end of the query and it will evaluate it once, and then the resulting list can be iterated many times without negative consequences.  Since this solution, when such semantics are desired, is so easy to get, whereas the semantics of deferred execution are much harder to get, despite being more powerful, they chose not to base LINQ on materialized collections.

A: No, your queries will be executed right if you use First() or Last() and some others. That means you call the OrderBy twice (including OrderByDescending).
You can try this:
var mostRecentChange = dateValues.OrderBy(d=>d.Date)
                                 .SkipWhile((x,i)=>i==dateValues.Count-1||x.Value == dateValues[i+1].Value)
                                 .Take(1);


text:
Q: Syntax Error occurred when try to build the react-native android application in genymotion I create an android application using react-native when I try to load that application into Genymotion it shows an error as
399/400Error while persisting cache: SyntaxError /home/samantha/AwesomeProject/index.android.js: "React" is read-only

A: I done a mistake in my index.android.js
render() {
    var movie = MOCKED_MOVIES_DATA[0];
    var React = require("react-native");
    var Image = React.Image;
    return (
        <View style={styles.container}>
            <Text>{movie.title}</Text>
            <Text>{movie.year}</Text>
            <Image source={{uri: movie.posters.thumbnail}}
                   style={style.thumbnail}/>
            <View style={style.rightContainer}>
                <Text style={style.title}>{movie.title}</Text>
                <Text style={style.year}>{movie.year}</Text>
            </View>
        </View>
    );
}

this is my react render() function this one works fine
previously I wrote as
var React = require("react-native");
var Image = React.Image;
render() {
    var movie = MOCKED_MOVIES_DATA[0];
    return (
        <View style={styles.container}>
            <Text>{movie.title}</Text>
            <Text>{movie.year}</Text>
            <Image source={{uri: movie.posters.thumbnail}}
                   style={style.thumbnail}/>
            <View style={style.rightContainer}>
                <Text style={style.title}>{movie.title}</Text>
                <Text style={style.year}>{movie.year}</Text>
            </View>
        </View>
       );
    }

because of that it is showed as "React" is read-only

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java шифрование помогите пожалуйста что я нет так делаю ?
String[] arg = new String[] { "0051FEAC52DB40394261", "FBD84AE57499E4400414E2831CF98D1E" };

if (arg.length == 0) {
    System.out.println ("ERROR 0x01 ARGS");
    System.in.read();
    return;
}

String hex_str = String.valueOf(arg [0]);
byte[] snDEC = hex_string_to_byte_array (hex_str.substring (0, 4));
byte[] snHEX = Helper.toPrimitives(dec_string_to_byte_array(hex_str.substring(0, 4)));
binary_hex = Helper.toObjects(hex_string_to_byte_array (hex_str.substring (4, hex_str.length()-4)));
byte [] key16 = hex_string_to_byte_array (String.valueOf(arg [1]));

    System.out.println(key16);
// Расшифровываем
TDES_ECB _tdes = new TDES_ECB();
byte[] dec_result = _tdes.TripleDesDecryptOneBlock (Helper.toPrimitives(binary_hex), key16);

//foreach (byte b in dec_result)
//{
//    Console.Write("{0:X2}", b);
//}
//Console.WriteLine();

short sn1 = (short) Integer.parseInt(hex_str.substring (0, 4));//BitConverter.ToInt16 (snDEC);
short sn2 = (short) BitConverter.toInt16 (Helper.toPrimitives(swap_bytes(dec_result)),0);

//Console.WriteLine("SN1: {0:X2}", sn1);
//Console.WriteLine("SN1: {0:X2}", sn2);

// Сверка серийных номеров
    if (String.valueOf(sn1) != String.valueOf(sn2))
{
    System.out.println("ERROR 0x02 SN");
    System.in.read();
    return;
}

// Проверяем контрольную сумму
    if (!compare_crc16(Helper.toObjects(dec_result)))
{
    System.out.println("ERROR 0x03 CRC16");
    System.in.read();
    return;
}

// Получаем дату - тут надо подумать.
Calendar dt = Calendar.getInstance();
    dt.add(Calendar.YEAR, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd0000");
//Console.WriteLine ("new date: "+dt.ToString("yy MM dd hh mm"));

int current_time = Integer.parseInt(sdf.format(dt));
    System.out.println("a1:" + current_time);

int current_time2 = Integer.parseInt(sdf.format(dt));
    System.out.println("a2:" + current_time2);

// добавляем серйиник
ArrayList<Byte> l = new ArrayList<> ();
    l.add (snHEX[0]);
    l.add (snHEX[1]);

byte[] time_arr = Helper.toPrimitives(BitConverter.GetBytes (current_time2));
ArrayList<Byte> tmp = new ArrayList<Byte>(Arrays.asList(Helper.toObjects(time_arr)));
    Collections.reverse(tmp);

// добавляем дату
    for (byte b : tmp)
        l.add(b);

// считаем контрольную сумму с новыми данными
ArrayList<Byte> last_pack = calc_crc16 (l.toArray(new Byte[0]));

byte[] en_result = _tdes.TripleDesEncryptOneBlock(Helper.toPrimitives(last_pack.toArray(new Byte[0])), key16);

    System.out.println(hex_str.substring (0, 4));

    for (byte b: en_result)
        System.out.println("{0:X2} " + b);

    System.in.read();
}

private static Byte [] swap_bytes(byte [] bb)
{
    List<Byte> res = new ArrayList<> ();
    res.add (bb [1]);
    res.add (bb [0]);
    return res.toArray(new Byte[0]);
}

private static ArrayList<Byte> calc_crc16(Byte[] byteIn)
{
    int crc = 0x0000;
    crc = calc_cycle(byteIn);
    ArrayList<Byte> l = new ArrayList<Byte>(Arrays.asList(byteIn));

    l.add((byte) (crc >> 8));
    l.add((byte) (crc&255));
    return l;
}

private static Boolean compare_crc16(Byte[] byteIn)
{
    int crc = calc_cycle(byteIn);
    int crc2 = (int) (byteIn [7] | (int)(byteIn [6] << 8));
    return (crc == crc2) ? true : false;
}

private static int calc_cycle(Byte[] byteIn)
{
    int crc = 0xFFFF;

    for (int i=0; i<6; i++)
    {
        byte tmp = byteIn[i];
        tmp ^= (byte)(crc & 0xFF);
        tmp ^= (byte)(tmp << 4);

        crc = (int)((int)(tmp << 8) | ((crc >> 8) & 255));
        crc ^= (byte)(tmp >> 4);
        crc ^= (int)((int)tmp << 3);
    }
    return crc;
}

private static Byte[] dec_string_to_byte_array(String str)
{
    ArrayList<Byte> lb = new ArrayList<Byte>(Arrays.asList(BitConverter.GetBytes(Integer.parseInt(str))));
    Collections.reverse(lb);
    return lb.toArray(new Byte[0]);
}

private static byte[] hex_string_to_byte_array(String str) throws Exception
{
    if (str.length() % 2 == 1)
        throw new Exception("he binary key cannot have an odd number of digits");

    byte[] arr = new byte[str.length() >> 1];

    for (int i=0; i< str.length() >>1; i++)
    {
        arr[i] = (byte)((GetHexVal(str.charAt(i << 1)) << 4) + (GetHexVal(str.charAt((i << 1) + 1))));
    }

    return arr;
}

private static int GetHexVal(char hex) {
    int val = (int)hex;
    return val - (val < 58 ?48 : 55);
}
static class TDES_ECB
{

    private KeyGenerator keyGenerator;

    //Encriptor
    public byte[] TripleDesEncryptOneBlock(byte[] plainText, byte [] key16) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
            BadPaddingException, IllegalBlockSizeException

    {

        Security.addProvider(new BouncyCastlePQCProvider());
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key16, "DESede"));

        byte[] encrypted = cipher.doFinal(plainText);

        return encrypted;
    }

    //Decrryptor
    public byte[] TripleDesDecryptOneBlock(byte[] data, byte[]key16) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
            IllegalBlockSizeException

    {

        Security.addProvider(new BouncyCastlePQCProvider());
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key16, "DESede"));

        byte[] decrypted = cipher.doFinal(data);

        return decrypted;
    }
}

static class BitConverter
{
    public static Byte[] GetBytes(int value)
    {
        ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder());
        buffer.putInt(value);
        return Helper.toObjects(buffer.array());
    }

    public static short toInt16(byte[] bytes, int index) //throws Exception
    {
        return (short)((bytes[index + 1] & 0xFF) | ((bytes[index] & 0xFF) << 0));
        //return (short)(
        //        (0xff & bytes[index]) << 8 |
        //                (0xff & bytes[index + 1]) << 0
        //);
    }
}

static class Helper
{
    public static byte[] toPrimitives(Byte[] oBytes)
    {
        byte[] bytes = new byte[oBytes.length];

        for(int i = 0; i < oBytes.length; i++) {
            bytes[i] = oBytes[i];
        }

        return bytes;
    }

    public static Byte[] toObjects(byte[] bytesPrim) {
        Byte[] bytes = new Byte[bytesPrim.length];

        int i = 0;
        for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing

        return bytes;
    }
}

Получаю
Exception in thread "main" java.security.InvalidKeyException: Wrong key size
at com.sun.crypto.provider.DESedeCrypt.init(DESedeCrypt.java:69)
at com.sun.crypto.provider.ElectronicCodeBook.init(ElectronicCodeBook.java:94)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:591)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:467)
at com.sun.crypto.provider.DESedeCipher.engineInit(DESedeCipher.java:166)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:863)
at javax.crypto.Cipher.init(Cipher.java:1248)
at javax.crypto.Cipher.init(Cipher.java:1185)
at MainClass$TDES_ECB.TripleDesDecryptOneBlock(MainClass.java:246)
at MainClass.main(MainClass.java:75)

A: Длина материала ключа (в вашем случае key16) - должна быть 192 бит, то есть 24 байта.
P.S. Научитесь в конце-концов читать диагностику сообщений:

java.security.InvalidKeyException: Wrong key size

Неверная длина ключа...
Update
Я обычно не занимаюсь рефлексированием, почему именно 192 бита, а не 112 или 168. Оставляю это на усмотрение узких специалистов:

So sometimes the (triple) DES key lengths are referred to as 56 bit, 112 bit or 168 bits instead of 64, 128 or 192 bits respectively. Usually cryptographic API's still require you to enter 8, 16 or 24 bytes despite of this.

Полагаюсь на рабочую длину и все. Работает и ладно.


text:
Q: How to effectively handle removal of objects with Corona SDK? I have a button that creates and apply force every time the the button is touched.
How do I prevent this from leaking memory?
I am using director class to change from scene to scene.
Here is the code:
-- Fire the rocket from the jet position
local function fireTheRocket(event)
    if event.phase == "ended" then
      local fireBall = display.newImage( "rocket.png")
      fireBall.x = jet.x;
      fireBall.y = jet.y;

      GUI:insert(fireBall);

      physics.addBody(fireBall, "dynamic")
      fireBall:applyForce( 1000, 0, fireBall.x, fireBall.y )
    end
end
fireBtn:addEventListener("touch", fireTheRocket)

A: You could try to do something like that:
(insert it after aplayng a force)
local function DestroyRocket()
  fireBall:removeSelf()
  fireball = nil
end
timer.performWithDelay( 1000, DestroyRocket)

It destroy your rocket after 1 sec. Or you can do in onCollision if you want to destroy it when it collide with some other objects.


text:
Q: Цветные символы в строке как можно с помощью C# сделать отдельные символы в строке консоли цветными?

A: using System;

namespace CSrharpApplicationTest
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Random rnd = new Random();
            string s = "Hello world!";
            foreach (var item in s)
            {
                // Используем 16, а не 15, так как rnd.Next не включает 16
                // в диапазон случайных чисел. Максимальное значение ConsoleColor
                // - это 15.
                Console.ForegroundColor = (ConsoleColor)rnd.Next(16);
                Console.Write(item);
            }
            Console.WriteLine();
        }
    }
}

Вывод строки случайными цветами посимвольно. Используется явное приведение int -> ConsoleColor. Обращаю внимания на то, что перечисление обычно базируется на типе целочисленном типе (хотя средствами рефлексиями, можно вытворять что угодно, но это плохая идея).


text:
Q: Tests that verify the calling of remove function of the Python os module fail I am trying to mock Python os module but my mocking steps are not working.
The code in the file os_mock.py:
import os

class MyTestMock:

    def rm(self):
        # some reason file is always hardcoded
        file_path = "/tmp/file1"
        if os.path.exists(file_path):
            os.remove(file_path)
            print(file_path, 'removed successfully')
        else:
            print(file_path, 'Does not exist')

The code in the test case file test_os_mock.py
import os
import unittest
from unittest.mock import patch
from os_mock import MyTestMock

class TestMyTestMock(unittest.TestCase):
    @patch('os.path')
    @patch('os.remove')
    def test_rm(self, mock_remove, mock_path):
        my_test_mock = MyTestMock()
        mock_path.exists.return_vallue = False
        my_test_mock.rm()
        self.assertFalse(mock_remove.called)

        mock_path.exists.return_vallue = True
        my_test_mock.rm()
        self.assertTrue(mock_remove.called)

I am getting below error when I execute test cases
F
======================================================================
FAIL: test_rm (__main__.TestMyTestMock)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py", line 1336, in patched
    return func(*newargs, **newkeywargs)
  File "/Users/vuser/code/MP-KT/mock/test_os_mock.py", line 15, in test_rm
    self.assertFalse(mock_remove.called)
AssertionError: True is not false

----------------------------------------------------------------------
Ran 1 test in 0.008s

FAILED (failures=1)

I know I am doing something wrong while mocking, But I could not able to figure it out, I got couple of stack overflow links, I followed it, but no help.

A: I have made some change only to your test file, while the file os_mock.py remains unchanged.
Change return_vallue to return_value is enough
If you change return_vallue to return_value your test passes successfully so these changes (in the 2 points where the errors are present) are sufficient.
In particular the changes are the followings:

*

*mock_path.exists.return_vallue=False --> mock_path.exists.return_value=False (return_vallue is not correct)

*mock_path.exists.return_vallue=True --> mock_path.exists.return_value=True (return_vallue is not correct)

Improving tests by assert_not_called() and assert_called_once()
The most important change is return_vallue --> return_value, but in my opinion the package unittest.mock provides methods assert_not_called() and assert_called_once() which can improve your tests.
For example self.assertTrue(mock_remove.called) ensures you called the mocked method, instead mock_remove.assert_called_once() checks that you called the method exactly one time.
So I recommend the followings changes:

*

*self.assertFalse(mock_remove.called) --> mock_remove.assert_not_called()

*self.assertTrue(mock_remove.called) --> mock_remove.assert_called_once()
The new file test_os_mock.py
With the changes showed, the file test_os_mock.py becomes:
import os
import unittest
from unittest.mock import patch
from os_mock import MyTestMock

class TestMyTestMock(unittest.TestCase):

    @patch('os.path')
    @patch('os.remove')
    def test_rm(self, mock_remove, mock_path):
        my_test_mock = MyTestMock()

        # return_vallue --> return_value
        mock_path.exists.return_value = False
        my_test_mock.rm()
        mock_remove.assert_not_called()
        #self.assertFalse(mock_remove.called)

        # return_vallue --> return_value
        mock_path.exists.return_value = True
        my_test_mock.rm()
        mock_remove.assert_called_once()
        #self.assertTrue(mock_remove.called)

if __name__ == "__main__":
    unittest.main()

assert_called_once_with()
In your test case better than assert_called_once() is the method assert_called_once_with() and with this other method  your test becomes as follow:
@patch('os.path')
@patch('os.remove')
def test_rm(self, mock_remove, mock_path):
    my_test_mock = MyTestMock()
    mock_path.exists.return_value = False
    my_test_mock.rm()
    mock_remove.assert_not_called()

    mock_path.exists.return_value = True
    my_test_mock.rm()
    # here is the NEW CHANGE
    mock_remove.assert_called_once_with("/tmp/file1")

This link is very useful for understand Mocking object in Python.


text:
Q: Why does NOT adding a '+ ""' after a mathematical operation in javascript make the counting of the new variables length undefined? I'm counting the number of hours and then subtracting it by 12 if it goes above 12 (so that 1pm doesn't appear as 13pm). Below is part of my javascript code.
else if (hours[0] >= 13) {
    hours[0] = hours[0] - 12 + "";
}

Later in the code, when I'm trying count the length of the array variable 'hours[0]', it appears as unknown if I have this code instead:
else if (hours[0] >= 13) {
    hours[0] = hours[0] - 12;
}

and I don't understand why. Could someone help me out please?

A: The subtraction hours[0] - 12 returns a number, no matter if hours[0] contains a number or a string containing a number, e.g. "13". Adding the + "" converts the result of the subtraction to a string. A number has no length in javascript, and therefore invoking the length member of a number will return undefined.

A: If you add "" to an expression you're converting the resulto to a string and strings have a .length property. Numbers instead do not have a .length so what you're experiencing is normal...
var x = 42;         // this is a number
var y = x + "";     // y is a string ("42")
var z1 = x.length;  // this is undefined (numbers have no length)
var z2 = y.length;  // this is the lenght of a string (2 in this case)


text:
Q: How close can I be to a bomb without getting blown up? For some reason, bomb damage tends to be somewhat erratic in this game.  For example, on dust2, if I'm at mid double doors when the bomb explodes, I end up dying (around 25 hp left or so), whereas if I'm in the situations sometimes, I can by on lower cat and end up surviving with a minimal amount hp.
Question is, how far must I be away from a bomb to be safe from any potential injuries? I'd personally like to not get blown up over and over, and would like to also be consistently far away enough to not die so I wouldn't have to rebuy the next round.

A: Go into a private game and use the following command:

map_showbombradius

If you don't want to explore it yourself, there is an in depth, useful video guide here:


text:
Q: Active: active (exited) Service plexconnect starts exited I have installed a python script called "plexconnect" which is basicly a script to trick my apple tv3 in to looking elsewhere for its trailers.
Source: https://github.com/iBaa/PlexConnect
Then i made an init script.
Source: https://forums.plex.tv/discussion/156534/install-on-ubuntu-server
The (minor) problem i have with this deamon is after a reboot the service allways start as active (exited):
● plexconnect.service - LSB: This is the Plex Connect daemon
   Loaded: loaded (/etc/init.d/plexconnect; bad; vendor preset: enabled)
   Active: active (exited) since sø. 2016-03-27 14:29:27 CEST; 1min 14s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 1043 ExecStart=/etc/init.d/plexconnect start (code=exited, status=0/SUCCESS)
    Tasks: 0 (limit: 512)

mars 27 14:29:26 lenox2 systemd[1]: Starting LSB: This is the Plex Connect daemon...
mars 27 14:29:27 lenox2 plexconnect[1043]:  * Starting the process PlexConnect
mars 27 14:29:27 lenox2 systemd[1]: Started LSB: This is the Plex Connect daemon.

After i restart the service it works fine active (running):
● plexconnect.service - LSB: This is the Plex Connect daemon
   Loaded: loaded (/etc/init.d/plexconnect; bad; vendor preset: enabled)
   Active: active (running) since sø. 2016-03-27 14:31:09 CEST; 1s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 1911 ExecStop=/etc/init.d/plexconnect stop (code=exited, status=0/SUCCESS)
  Process: 1921 ExecStart=/etc/init.d/plexconnect start (code=exited, status=0/SUCCESS)
    Tasks: 6 (limit: 512)
   CGroup: /system.slice/plexconnect.service
           ├─1930 /usr/bin/SCREEN -S PlexConnect -d -m /usr/local/lib/PlexConnect/PlexConnect.py
           ├─1933 python /usr/local/lib/PlexConnect/PlexConnect.py
           ├─1936 python /usr/local/lib/PlexConnect/PlexConnect.py
           ├─1940 python /usr/local/lib/PlexConnect/PlexConnect.py
           ├─1942 python /usr/local/lib/PlexConnect/PlexConnect.py
           └─1944 python /usr/local/lib/PlexConnect/PlexConnect.py

mars 27 14:31:09 lenox2 systemd[1]: Starting LSB: This is the Plex Connect daemon...
mars 27 14:31:09 lenox2 plexconnect[1921]:  * Starting the process PlexConnect
mars 27 14:31:09 lenox2 systemd[1]: Started LSB: This is the Plex Connect daemon.

I have tried to stop the plexmediaserver and restart the plexconnect to se if theres a problem with dependencies but it runs fine without plexmediaserver.
I have also tried to add plexmediaserver as a Required-Start to the init script:
#Required-Start:  networking plexmediaserver

then:
sudo update-rc.d plexconnect defaults
insserv: Service plexmediaserver has to be enabled to start service plexconnect
insserv: exiting now!

Its clear Im in over my head here and need help. The only clue i have now is the extra python lines at the bottom service status after a restart. Could it be python need to be a Required-Start?
Complete code for init script:
#!/bin/bash
### BEGIN INIT INFO
# Provides:          plexconnect
# Required-Start:    networking
# Required-Stop:     networking
# Default-Start:     3 4 5
# Default-Stop:      0 1 6
# Short-Description: This is the Plex Connect daemon
# Description:       This script starts the Plex Connect
#                    Python scripts in a detached screen.
### END INIT INFO

# Using the lsb functions to perform the operations.
./lib/lsb/init-functions

# Process name ( For display )
NAME=PlexConnect

# Daemon name, where is the actual executable
DAEMON="/usr/bin/screen"
DAEMON_OPTS="-S PlexConnect -d -m /usr/local/lib/PlexConnect/PlexConnect.py"
DAEMON_USER="root"

# pid file for the daemon
PIDFILE=/var/run/PlexConnect.pid

# If the daemon is not there, then exit.
test -x "$DAEMON"||exit5

case $1 in
 start)
  # Checked the PID file exists and check the actual status of process
  if[-e $PIDFILE ];then
   status_of_proc -p $PIDFILE "$DAEMON $DAEMON_OPTS""$NAME process"&& status="0"|| status="$?"
   # If the status is SUCCESS then don't need to start again.
   if[ $?="0"];then
    log_success_msg "Starting the process $NAME"
    exit# Exit
   fi
  fi
  # Start the daemon.
  # Start the daemon with the help of start-stop-daemon
  # Log the message appropriately
  if start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE --startas $DAEMON -p $PIDFILE -- ${DAEMON_OPTS};then
   while read line ;do[[ $line =~([0-9]*).PlexConnect]]&& echo ${BASH_REMATCH[1]};done<<(screen -ls)> $PIDFILE
   log_success_msg "Starting the process $NAME"
  else
   log_failure_msg "Starting the process $NAME"
  fi
  ;;
 stop)

  # Stop the daemon.
  if[-e $PIDFILE ];then
   status_of_proc -p $PIDFILE "$DAEMON DAEMON_OPTS""Stoppping the $NAME process"&& status="0"|| status="$?"
   if["$?"=0];then
    start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
    /bin/rm -rf $PIDFILE
    log_success_msg ""Stopping the $NAME process""
   fi
  else
   log_failure_msg "$NAME process is not running"
  fi
  ;;
 restart)
  # Restart the daemon.
  $0 stop && sleep 2&& $0 start
  ;;
 status)
  # Check the status of the process.
  if[-e $PIDFILE ];then
   status_of_proc -p $PIDFILE "$DAEMON $DAEMON_OPTS""$NAME process"&&exit0||exit $?
   log_success_msg "$NAME process is running"
  else
   log_failure_msg "$NAME process is not running"
  fi
  ;;
 reload)
  $0 restart
  ;;
 *)
  # For invalid arguments, print the usage message.
  echo "Usage: $0 {start|stop|restart|reload|status}"
  exit2
  ;;
esac

EDIT:
I´ve been looking at converting the sysvinit (plexconnect) to an Upstart.conf since plexconnect is an Upstart.conf but then i found out that ubuntu now uses systemd.
The problem i have now is that for some reason plexmediaserver runs as an Upstart and when i try to make an Upstart plexconnect.conf this happens:
initctl: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart: Connection refused

So now i´m even more confused... How could plexmediaplayer get to be an Upstart service if 16.04 does not allow me to update Upstart? (Installed via the Ubuntu package).

A: The main issue was Plexmediaserver was using Upstart/systemD so the init script failes.
More info in this guide I made: http://forums.plex.tv/discussion/213637/ubuntu-15-debian-8-raspbian-jessie-arch-or-based-autostart


text:
Q: Prevent or detect reading of daemon in memory Is it possible to prevent the memory being used by a daemon to be read by anything else?
If not, is it possible to detect an attempt to read?
If so, is it possible to get in front of the actual read and execute commands that can act first?

A: On Unixy systems, root is all-powerful and can certainly read (and even write) into your daemons' memory without it even being able to find out. Ditto for the user as which the daemon runs. If you are trying to protect against non-root/non-daemon-user access, the system itself should provide protection (modulo bugs or stupid configuration, that is).


text:
Q: Connecting a Linux-client to MacOS-server with C I study sockets and try to write a very simple application. The client sends the string "Hello there!", the server accepts it, displays at itself and sends back. Wrote the client (Linux Ubuntu 18.04), and the server (macOS 10.14.2, IP: 217.144.173.149):
server:
int main()
{
    int sock, listener;
    struct sockaddr_in addr;
    char buf[1024];
    int bytes_read;

    listener = socket(AF_INET, SOCK_STREAM, 0);
    if(listener < 0)
    {
        perror("socket");
        exit(1);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(3425);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("bind");
        exit(2);
    }

    listen(listener, 1);

    while(1)
    {
        sock = accept(listener, 0, 0);
        if(sock < 0)
        {
            perror("accept");
            exit(3);
        }

        while(1)
        {
            bytes_read = recv(sock, buf, 1024, 0);
            if (bytes_read <= 0) break;
            printf(buf);
            send(sock, buf, bytes_read, 0);
        }

        close(sock);
    }

    return 0;
}

client:
int main()
{
    char message[] = "Hello there!\n";
    char buf[sizeof(message)];

    int sock;
    struct sockaddr_in addr;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        perror("socket");
        exit(1);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(3425);
    addr.sin_addr.s_addr = inet_addr("217.144.173.149");
    if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("connect");
        exit(2);
    }

    send(sock, message, sizeof(message), 0);
    recv(sock, buf, sizeof(message), 0);

    printf(buf);
    close(sock);

    return 0;
}

However, after starting the client, it just hangs and after a while gives an error: connect: Connection timed out. The server at the same time, of course, works. Google search gave no results (maybe I was looking for). What I did wrong?

A: *

*Check server's ipfw IP Firewall. (Open port 3425 , which is the server port listen on)

*Server's IP address must be public IP. Or the server and client in the same local area network.

If you just want to test your code. You can run server and client in the same computer. Open two terminal and the one run server , the other run client. And client change the connect ip 217.144.173.149 to 127.0.0.1
     127.0.0.1 mean localhost.

A: The problem is in the way you are converting the IP address from presentation type to network type.

*

*You should use the IP address if it is static instead of INADDR_ANY.

*If the problem stays try using a different function to convert the IP.

For further reference go here.

A: As other answers suggested , please check if your server is listening on properly using netstat command in server
From the server , check if firewalld or anyfirewall specific software is running
Try using different port to bind on server , may be 8080 or something else .
I also suggest you to read the excellent guide (beejs network programming guide)
https://beej.us/guide/bgnet/


text:
Q: Why do future_statements in Python need to be placed before everything? PEP 236 states clearly that all future_statements must appear near the top of a module, with only comments, docstrings and the like allowed before them.
I understand that this isn't debatable as a programming practice - it's the rules and they're clear. However, I can't google myself an answer as to why it was decided to be an error rather than just a violation of recommended practices when you fail to place your future_statement at the very top (aka, a warning).
Is it because this way, modules that import their own versions of names that the future_statement will import, will be able to override them, thus ensuring they'll work correctly? Is it to maintain some sort of strong code clarity so that proper coding practices aren't broken because of potential disasters if a __future__ import is accidentally ignored? The PEP isn't enlightening on this and I can't get any leads to finding out why.

A: __future__ statements potentially even have effects on parsing (example: unicode_literals, print_function), as they may modify (or rather switch to a different version of) the grammar. They thus must be known as early as possible. They also certainly have effects on code generation (division).
There are are thus good design reasons to force those statements to be at the start of the parsing and the compilation, in addition to the clarity concerns.
Other imported modules do not have any effect on what is going on in your module with respect to __future__. Which is a good thing, because otherwise other modules could break your module by importing print_function from __future__.

A: At a guess, it's to avoid the following kind of situation:
print "yo"
from __future__ import print_function

Is the print statement a syntax error or not? It depends if the future import applies to the whole file or just from that point on. Better to make it unequivocally an error not to be the import at the top.


text:
Q: currency symbol image in ionic i am trying to get the value of Total redemption to be on the same line with the word "Total Redemption" like the way Total Accrued Points looks, i am using an image for my currency symbol and the code for this display is

     Total Accrued Points :  {{reportData.accruedpoints}}

Total Redemption: {{reportData.redeemableamt | currency : ""}}

    <a  View {{reportData.submerchantId}} Details


text:
Q: how to combine SQL queries in columns I need rows of result set into columns. I currently have written the query :
SELECT COUNT(*) AS Male FROM add_faculty_override
WHERE gender='Male'
UNION
SELECT COUNT(*) AS Female FROM add_faculty_override
WHERE gender='Female';

This gives me the result as :
male
3          //total number of males
5          //total number of females

What I'd like to have instead as the result set is :
male   female
3        5

A: You can do this with a CASE statement:
SELECT COUNT(CASE WHEN gender='Male' THEN 1 END) AS Male
     , COUNT(CASE WHEN gender='Female' THEN 1 END) AS Female
FROM add_faculty_override

If you don't really need both results on one row then you can simply GROUP:
SELECT Gender, COUNT(*) AS Gender_Count
FROM add_faculty_override
GROUP BY Gender

A: You could use this:
SELECT (SELECT     COUNT(gender)
        FROM       add_faculty_override
        WHERE      gender='Male') AS 'Male',

       (SELECT     COUNT(gender)
        FROM       add_faculty_override
        WHERE      gender='Female') AS 'Female'

You can see this here->http://sqlfiddle.com/#!3/4ed9d/1
Hope this helps!!!


text:
Q: Magento 2: Override protected function getBackUrl in Magento\Checkout\Controller\Cart.php I just want to override below method but its not working anymore.
Magento 2: Override protected function getBackUrl From Magento\Checkout\Controller\Cart.php
Any idea please share
My php code is :
<?php

namespace Dynamic\Checkout\Controller\Magento\Checkout;

use Magento\Catalog\Controller\Product\View\ViewInterface;
use Magento\Checkout\Model\Cart as CustomerCart;

class Cart extends \Magento\Checkout\Controller\Cart
{
    protected function getBackUrl($defaultUrl = null)
        {
        echo "8888 ";exit;
    }
}

and di.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Controller\Cart" type="Dynamic\Checkout\Controller\Magento\Checkout\Cart" />
</config>


text:
Q: join two tables to get tomorrow's price (and the price two days from "now") I'm trying to do a JOIN query to analyze some stocks. In my first table called top10perday, I list 10 stocks per day that I have chosen to "buy" the next day and sell the following day:
date        symbol
07-Aug-08   PM
07-Aug-08   HNZ
07-Aug-08   KFT
07-Aug-08   MET
...
08-Aug-08   WYE
08-Aug-08   XOM
08-Aug-08   SGP
08-Aug-08   JNJ

For instance, for record #1:

*

*the date of the record is 07-Aug-08

*I want to buy a share of PM stock on the next trading day after 07-Aug-08 (which is 08-Aug-08)

*I want to sell that shar eof PM stock two trading days after 07-Aug-08), which turns out to be 11-Aug-08

My stock prices are in a table called prices, which looks like this:
date        symbol   price
07-Aug-08   PM       54.64
08-Aug-08   PM       55.21
11-Aug-08   PM       55.75
12-Aug-08   PM       55.95
... many more records with trading day, symbol, price

I want to do a JOIN so that my result set looks like this:
date        symbol  price-next-day  price-two-days
07-Aug-08   PM      55.21           55.75
...
list one record per date and symbol in table1.

I have tried doing something like:
SELECT top10perday.date, top10perday.symbol, Min(prices.date) AS MinOfdate
FROM prices INNER JOIN top10perday ON prices.symbol = top10perday.symbol
GROUP BY top10perday.date, top10perday.symbol
HAVING (((Min(prices.date))>[date]));

I have tried many variations of this, but I'm clearly not on the right path, because the result set just includes 10 rows as of the earliest date shown in my top10perday table.
I am using Microsoft Access. Thanks in advance for your help! :-)

A: This syntax worked in Access 2003:
SELECT t10.Date, t10.Symbol, p1.date, p1.price, p2.date, p2.price
FROM
(top10perday AS t10
  LEFT JOIN prices AS p1
  ON t10.Symbol = p1.symbol)
  INNER JOIN prices AS p2 ON t10.Symbol = p2.symbol
WHERE (
((p1.date)=((Select Min([date]) as md
             from prices
             where [date]>t10.[Date] and symbol = t10.symbol
            ))
) AND ((p2.date)=((Select Min([date]) as md
                   from prices
                   where [date]>p1.[Date] and symbol = t10.symbol)
                 ))
);

the idea is to get the first (min) date that is greater than the date in the previous table (top10perday and the prices as p1)

A: My guess is:
SELECT top10perday.date, top10perday.symbol, MIN(pnd.price) AS PriceNextDay, MIN(ptd.price) AS PriceTwoDays
FROM top10perday
LEFT OUTER JOIN prices AS pnd ON (pnd.symbol = top10perday.symbol AND pnd.date > top10perday.date)
LEFT OUTER JOIN prices AS ptd ON (ptd.symbol = top10perday.symbol AND ptd.date > pnd.date)
GROUP BY top10perday.date, top10perday.symbol
HAVING ((pnd.date = Min(pnd.date) AND ptd.date = Min(ptd.date));

It´s just a shoot in the dark but my reasoning is: List all stocks you want (top10perday) and for each stock get the price, if exists, with mininum date after its date to populate the PriceNextDay and the price with minimun date after the PriceNextDay to populate the PriceTwoDays. The performance may stinks. But test it and see if it works. Later we can try to improve it.
**EDIT**ed to include Rob Farley´s comment.

A: This should just be a join between three copies of the prices table. The problem is that you need to join to the next trading day, and that's a slightly trickier problem, since it's not always the next day. So we end up with a more complex situation (particularly as some days are skipped beacuse of holidays).
If it weren't Access you could use row_number() to order your prices by date (using a different sequence per stock code).
WITH OrderedPrices AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY symbol ORDER BY date) AS RowNum
FROM Prices
)
SELECT orig.*, next_day.price, two_days.price
FROM OrderedPrices orig
  JOIN
   OrderedPrices next_day
   ON next_day.symbol = orig.symbol AND next_day.RowNum = orig.RowNum + 1
   JOIN
   OrderedPrices two_days
   ON two_days.symbol = orig.symbol AND two_days.RowNum = orig.RowNum + 2
;

But you're using Access, so I don't think you have ROW_NUMBER().
Instead, you could have a table which lists the dates, having a TradingDayNumber... then use that to facilitate your join.
SELECT orig.*, next_day.price, two_days.price
FROM Prices orig
  JOIN
  TradingDays d0
   ON d1.date = orig.date
  JOIN
  TradingDays d1
   ON d1.TradingDayNum = d0.TradingDayNum + 1
  JOIN
  TradingDays d2
   ON d2.TradingDayNum = d0.TradingDayNum + 2
  JOIN
   Prices next_day
   ON next_day.symbol = orig.symbol AND next_day.date = d1.date
   JOIN
   Prices two_days
   ON two_days.symbol = orig.symbol AND two_days.date = d2.date

But obviously you'll need to construct your TradingDays table...
Rob

A: I'm not a guru on this transformation but I can point you at an idea.  Try using Pivot on the date column for each symbol in your query from a date to a date.  This should give you a table with many columns with the name of the date you're using, and the price on each day.  Indeed it should do this for every stock symbol you have over a given time.
Based on what you're trying to graph though, I think it would be interesting for you to look at the VWSP not just the spot price on your trades if you're trying to plot the stock performance.


text:
Q: Default zoom for eps file I have an EPS file that, for whatever reason, looks very small on the screen when I open it with an EPS viewer (gv, in my case... but it looks the same regardless of viewer).  I have to immediately zoom in to 8x magnification just to get the image to fill the screen.  Of course, since it is a vector graphic, the graphic looks fine when viewed at any magnification.
My question: Is there code I can add to the EPS file to change the default zoom (in other words, to make the file display on screen as 8 times larger by default, regardless of the viewer)?

A: You can scale the the contents of an eps format file by adding the following:
<xscale> <yscale> scale

PostScript command to it before the other commands in the file.
So to make everything 8 times bigger you would use:
8 8 scale

This scales the following graphics with respect to an origin in the lower-right, so it may also be necessary to translate everything so the area where marks appear fall within the visible portion of the "page". Not surprisingly, that can be done with a:
<xoffset> <yoffset> translate

These operations will be applied in the order shown. In other words, it will first scale the output, then translate it. Doing it in the opposite order would give different results, so it's important to remember this when figuring-out what values to use.
It's been a long time since I used ghostview, but I seem to recall there was a way to tell it to prepend files being processed with a preamble of commands, so you wouldn't need to actually modify any of them.
Conforming eps files will contain header comments that contain bounding box information of their content which can be very useful when transforming them. See section 3.1 Displaying an EPS file in the Encapsulated PostScript File Format Specification PDF file.


text:
Q: How to connect to a remote Oracle 11g database using PHP I have tried to make oci_connect work, by following these directions, but I still get the error:

ora-24408 could not generate unique server group name in test.php

Here is my PHP snippet (with bogus IP):
   $tns2 = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 123.123.123.123)(PORT = 1521)) (CONNECT_DATA = (SID = foo)))";
   if ($conn = oci_connect("username","pwd", $tns2))
   {
       echo "Connected to foo";
       oci_close($conn);
   }
   else
   {
       die("could not connect to foo");
   }

I use SQL Developer and can connect to this database just fine from this Ubuntu server. I also have Java applications that connect from this Ubuntu server to the remote Oracle database without any problems.
What am I missing to make PHP work?
I even did the phpinfo() and it showed the oci8 information.

A: Take a closer look to oci_connect.
And try with this conection string: "123.123.123.123:1521/foo"
$conn = oci_connect("username","pwd", "123.123.123.123:1521/foo");

Hope it helps.

A: You can try something like this:
define ('DB_USER','username');
define ('DB_PASS','pwd');
define ('DB_HOST', '123.123.123.123');
define ('DB_NAME', 'YOUR_DATABASE_NAME');
define ('CONST_DB_CHARSET_FOR_CONNECT','WE8ISO8859P15');
define ('DB_CONNECTION_STRING','\\123.123.123.123/DBSCHEMA');//in localhost use ''

$conexion = oci_connect(DB_USER, DB_PASS,DB_CONNECTION_STRING,CONST_DB_CHARSET_FOR_CONNECT);

Just put the right value for: YOUR_DATABASE_NAME
that's how I connect to remote oracle 11.g database.
Hope this helps you.


text:
Q: How to use notification channels in android O I am a beginner in android and right now working on a music streaming app. I have taken a course on Udemy for beginners for that and
the instructor goes line by line showing each step of creation,and i do exactly what he does. Now that we have reached the step of creating a notification for the
app, he uses something called 'NotificationCompat.Builder(this)'. Now when I type the same exact code, I get an error saying that the
NotificationCompat.Builder(context) has been deprecated now in android O. Due to this I am not getting the notifications on my phone when I
run it. Also the music is not being streamed. Due to this I am not able to proceed with further lectures.
I tried to ask the instructor on the forum for some help regarding this, but he does not seem to reply back. Also I tried to research
about the notification channels in android O, but I am unable to understand the concepts due to the lack of knowledge on basic android.
So it would be great if I could get some help regarding my problem.
I am uploading my code along with this.
The error is in PlayerService.java

(1). activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.music.zirakmistry.musicstreamingapp.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_media_play" />

</android.support.design.widget.CoordinatorLayout>

(2). MainActivity.java

public class MainActivity extends AppCompatActivity {

    static FloatingActionButton playPauseButton;
    PlayerService mBoundService;
    boolean mServiceBound=false;

    private ServiceConnection mServiceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PlayerService.MyBinder myBinder=(PlayerService.MyBinder)service;
            mBoundService=myBinder.getService();
            mServiceBound=true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name){
            mServiceBound=false;
        }
    };

    private BroadcastReceiver mMessageReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isPlaying=intent.getBooleanExtra("isPlaying",false);
            flipPlayPauseButton(isPlaying);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        playPauseButton = (FloatingActionButton) findViewById(R.id.fab);
        playPauseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view){
                if(mServiceBound)
                    mBoundService.togglePlayer();
            }
        });
        startStreamingService("https://www.mymusicstreamingapp.com/music_app/cute.mp3");
    }

    private void startStreamingService(String url)
    {
        Intent i=new Intent(this,PlayerService.class);
        i.putExtra("url",url);
        i.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
        startService(i);
        bindService(i,mServiceConnection,Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mServiceBound){
            unbindService(mServiceConnection);
            mServiceBound=false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,new IntentFilter("changePlayButton"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    }

    public static void flipPlayPauseButton(boolean isPlaying){
        if(isPlaying){
            playPauseButton.setImageResource(android.R.drawable.ic_media_pause);
        }
        else{
            playPauseButton.setImageResource(android.R.drawable.ic_media_play);
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

(3). PlayerService.java

public class PlayerService extends Service {

    MediaPlayer mediaPlayer=new MediaPlayer();
    private final IBinder mBinder=new MyBinder();

    public class MyBinder extends Binder
    {
        PlayerService getService()
        {
            return PlayerService.this;
        }
    }

    public PlayerService()
    {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        if(intent.getStringArrayExtra("url")!=null)
            playStream(intent.getStringExtra("url"));

        if(intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION))
        {
            Log.i("info","Start foregroung service");
            showNotification();
        }
        else if(intent.getAction().equals(Constants.ACTION.PREV_ACTION))
        {
            Log.i("info","Prev pressed");
        }
        else if(intent.getAction().equals(Constants.ACTION.PLAY_ACTION))
        {
            Log.i("info","Play pressed");
        }
        else if(intent.getAction().equals(Constants.ACTION.NEXT_ACTION))
        {
            Log.i("info","Next pressed");
        }
        else if(intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION))
        {
            Log.i("info","Stop foreground received");
            stopForeground(true);
            stopSelf();
        }

        return START_REDELIVER_INTENT;
    }

    private void showNotification()
    {
        Intent notificationIntent=new Intent(this,MainActivity.class);
        notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
        notificationIntent.setFlags((Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);

        Intent previousIntent=new Intent(this,MainActivity.class);
        previousIntent.setAction(Constants.ACTION.PREV_ACTION);
        PendingIntent ppreviousIntent=PendingIntent.getActivity(this,0,previousIntent,0);

        Intent playIntent=new Intent(this,MainActivity.class);
        playIntent.setAction(Constants.ACTION.PLAY_ACTION);
        PendingIntent pplayIntent=PendingIntent.getActivity(this,0,playIntent,0);

        Intent nextIntent=new Intent(this,MainActivity.class);
        nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
        PendingIntent pnextIntent=PendingIntent.getActivity(this,0,nextIntent,0);

        Bitmap icon= BitmapFactory.decodeResource(getResources(),R.drawable.logo);

        Notification notification=new NotificationCompat.Builder(this)
                .setContentTitle("Music Player")
                .setTicker("Playing music")
                .setContentText("My Song")
                .setSmallIcon(R.drawable.logo)
                .setLargeIcon(Bitmap.createScaledBitmap(icon,128,128,false))
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .addAction(android.R.drawable.ic_media_previous,"Previous",ppreviousIntent)
                .addAction(android.R.drawable.ic_media_play,"Play",pplayIntent)
                .addAction(android.R.drawable.ic_media_next,"Next",pnextIntent)
                .build();
        startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,notification);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return mBinder;
    }

    public void playStream(String url)
    {
        if(mediaPlayer!=null)
        {
            try
            {
                mediaPlayer.stop();
            }
            catch(Exception e)
            {
            }
            mediaPlayer=null;
        }

        mediaPlayer=new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try
        {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
            {
                @Override
                public void onPrepared(MediaPlayer mp)
                {
                    playPlayer();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
            {
                @Override
                public void onCompletion(MediaPlayer mp)
                {
                    flipPlayPauseButton(false);
                }
            });
            mediaPlayer.prepareAsync();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    public void pausePlayer()
    {
        try
        {
            mediaPlayer.pause();
            flipPlayPauseButton(false);
        }
        catch(Exception e)
        {
            Log.d("EXCEPTION","failed to pause media player");
        }
    }

    public void playPlayer()
    {
        try
        {
            mediaPlayer.start();
            flipPlayPauseButton(true);
        }
        catch(Exception e)
        {
            Log.d("EXCEPTION","failed to pause media player");
        }
    }

    public void flipPlayPauseButton(boolean isPlaying)
    {
        // code to communicate with main thread
        Intent intent=new Intent("changePlayButton");
        //add data
        intent.putExtra("isPlaying",isPlaying);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    public void togglePlayer()
    {
        try
        {
            if(mediaPlayer.isPlaying())
                pausePlayer();
            else
                playPlayer();
        }
        catch(Exception e)
        {
            Log.d("Exception","failed to toggle media player");
        }
    }
}

(4). Player.java

public class Player {
    MediaPlayer mediaPlayer=new MediaPlayer();
    public static Player player;
    String url="";

    public Player()
    {
        this.player = this;
    }

    public void playStream(String url)
    {
        if(mediaPlayer!=null)
        {
            try
            {
                mediaPlayer.stop();
            }
            catch(Exception e)
            {
            }
            mediaPlayer=null;
        }

        mediaPlayer=new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try
        {
            mediaPlayer.setDataSource(url);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
            {
                @Override
                public void onPrepared(MediaPlayer mp)
                {
                    playPlayer();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
            {
                @Override
                public void onCompletion(MediaPlayer mp)
                {
                    MainActivity.flipPlayPauseButton(false);
                }
            });
            mediaPlayer.prepareAsync();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    public void pausePlayer()
    {
        try
        {
            mediaPlayer.pause();
            MainActivity.flipPlayPauseButton(false);
        }
        catch(Exception e)
        {
            Log.d("EXCEPTION","failed to pause media player");
        }
    }

    public void playPlayer()
    {
        try
        {
            mediaPlayer.start();
            MainActivity.flipPlayPauseButton(true);
        }
        catch(Exception e)
        {
            Log.d("EXCEPTION","failed to pause media player");
        }
    }

    public void togglePlayer()
    {
        try
        {
            if(mediaPlayer.isPlaying())
                pausePlayer();
            else
                playPlayer();
        }
        catch(Exception e)
        {
            Log.d("Exception","failed to toggle media player");
        }
    }
}

(5). Constants.java

public class Constants {
    public interface ACTION {
        public static String MAIN_ACTION="com.music.zirakmistry.musicstreamingapp.action.main";
        public static String PREV_ACTION="com.music.zirakmistry.musicstreamingapp.action.prev";
        public static String PLAY_ACTION="com.music.zirakmistry.musicstreamingapp.action.play";
        public static String NEXT_ACTION="com.music.zirakmistry.musicstreamingapp.action.next";
        public static String STARTFOREGROUND_ACTION="com.music.zirakmistry.musicstreamingapp.action.startforeground";
        public static String STOPFOREGROUND_ACTION="com.music.zirakmistry.musicstreamingapp.action.stopforeground";
    }

    public interface NOTIFICATION_ID
    {
        public static int FOREGROUND_SERVICE=101;
    }
}

(6). AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.music.zirakmistry.musicstreamingapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".PlayerService"
            android:enabled="true"
            android:exported="true" />
    </application>

</manifest>

A: In order to facilitate the new feature called Notification Channels in Android Oreo the previous method was deprecated.
Notification Channels allow us to group notifications based on their intended behavior. So whenever a user don't need to see a specific type of notification they can disable the corresponding channel.
So for example consider an e-commerce app. It shows notifications for promotions/offers, order status, etc. Promotion and offer notifications are grouped into a channel named "promotion". So if the user don't want to see only these notifications they can disable the "promotion" channel from the app settings.
If you use the deprecated method, the notification will fail silently in Oreo. To make it work, use the new Builder constructor. Change your code as below:
Notification notification=new NotificationCompat.Builder(this, CHANNEL_ID)
    // set title, message, etc.
    .build();

And create a notification channel like this for Oreo:
NotificationManager manager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // Support for Android Oreo: Notification Channels
    NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "Channel_name_to_be_displayed_in_Settings",
                NotificationManager.IMPORTANCE_DEFAULT);
    manager.createNotificationChannel(channel);
}


text:
Q: Selective message notifications Can you turn off all notifications (text, email, phone, etc) but a selective few senders at night?  I am on call after hours and the work computer sends out a text message. That is all I want to hear.

A: The Do not disturb tool of the iPhone may provide what you are asking.
If you turn Do not disturb you'll be able to receive only the call from Favourite list of contacts. The only problem is that this service doesn't work for messages and therefore if you need to receive only message from a particular number, what I'm suggesting doesn't work for you.


text:
Q: Attempting to call execvp to run programname supplied through stdin, but call fails each time Good evening
I have found a few similar questions, but nothing that suffices based on this specific question.
I am forking a child process, and attempting to call execvp to run a simple program which outputs 3 chars to stdout. The program name to be run comes from user input.
For some reason every call to execvp fails for simpleO:
I compile file simpleO.c into simpleO, and then compile and run fork.c. I type simpleO into the prompt when requested to attempt to run, but each time I get the error. Here is the code.
The error message printed by perror is "No such file or directory"
--
fork.c
#include <stdio.h>
#include <unistd.h>/*fork, exec*/
#include <errno.h>/*errno*/
#include <string.h> /*strerror*/
#include <stdlib.h>/*EXIT_FAILURE*/

#define BUFFERSIZE 100

int main(int argc, char *argv[]){
int i = 0;
pid_t pid;
int status;
char buffer[BUFFERSIZE];

fgets(buffer, BUFFERSIZE, stdin);

argv[0] = strtok(buffer, " ");
while (buffer[i] != '\0') {/*analyze each char*/
    if (buffer[i] == ' ')/*based on how many spaces there are*/
        argv[i] = strtok(NULL, " ");/*tokenize, populate argv*/
    i++;
}

if((pid = fork()) == -1){
    fprintf(stderr, "fork error: %s\n", strerror(errno));
    return EXIT_FAILURE;}
else if (pid==0) {
    int e = execvp(argv[0],argv);
    if (e==-1) {
        perror("Exec failed");
        printf("Process %s\n",argv[0]);
        perror("Process did not run");
        exit(1);
    }
}
else{
    wait(&status);}
return 0;
}

--
simpleO.c
#include <stdio.h>
int main(int argc, char **argv){
    printf("%c",'c');
    printf("%c",'2');
    printf("%c",'1');
return 0;
}

Addl ref: perror prints "No such file or directory"

A: Okay, look: a key lesson in programming is that when an error message tells you something, you should believe it.  So, your program is saying "no such file or directory", and it means the file you're trying to run doesn't exist at whatever path you're trying to use.
You now know that it's not at the default path, so the next thing to try is to use the absolute path of the executable. Now, given the rest of this, I'd suggest you write a very simple C program that does nothing whatsoever besides trying to fork/exec your child program. No argv vector or anything, just fork and then execvp in the child with the executable path an absolute parth.


text:
Q: know deployment target in index.js firebase functions I have two deployment targets in my Cloud Functions. I use the command line to determine which project I deploy too. firebase use myTestApp or firebase use myLiveApp
Can I tell which target I am using in my index.js code?
I am hoping for something like this
// change baseURLs and other keys
if (Target == live) {
    const baseURL = 'myLiveApp';
    const stripekey= 'secreteLivekey';
} else {
    const baseURL = 'myTestApp';
    const stripekey= 'secreteTestkey';
};

currently I get around this by commenting out the test or live keys and this is very annoying and easy to make a mistake.

A: You can set the necessary variables in each project's Functions config.
CLI:
firebase use <live_project>
firebase functions:config:set stripe.key="secreteLivekey"
firebase functions:config:set baseURL="myLiveApp"
firebase use <non_live_project>
firebase functions:config:set stripe.key="secreteTestkey"
firebase functions:config:set baseURL="myTestApp"

In code:
import * as functions from 'firebase-functions'
const baseURL = functions.config().baseURL
const stripekey = functions.config().stripe.key

EDIT:
Since your question technically was "Can you know your deployment target?", the answer is yes.
const config = JSON.parse(process.env.FIREBASE_CONFIG)
const projectId = config.projectId


text:
Q: On device iOS websocket server Looking to implement websockets communication between a UIWebView in iOS with javascript to a local on the device websockets server in objective-c. Anyone seen a sample code set for setting a local websocket server on device for iOS so that the web view half can easily talk to the native container and vice versa?

A: I have made a websocket server that runs on iOS. It is a wrapper around libwebsockets, the code is on github: https://github.com/benlodotcom/BLWebSocketsServer .

A: try this library https://github.com/robbiehanson/CocoaHTTPServer
it has a MAC and IOS example with websockets.


text:
Q: Apache disabled virtual host domains resolve an enabled virtual host I have three virtual hosts defined on apache on my Ubuntu server for three different domains. If I disable two of the virtual hosts (a2dissite) and try to resolve those two URL's in the browser, then the one remaining enabled site will resolve.
How can I configure apache so that the domains for the disabled virtual hosts do not resolve?
This is how all 3 virtual hosts are configured (info is masked):
# domain: myfirstdomain.com
# public: /home/me/public/myfirstdomain.com/

<VirtualHost *:80>
  # Admin email, Server Name (domain name), and any aliases
  ServerAdmin webmaster@myfirstdomain.com
  ServerName  www.myfirstdomain.com
  ServerAlias myfirstdomain.com

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html index.php
  DocumentRoot /home/me/public/myfirstdomain.com/public

  # Log file locations
  LogLevel warn
  ErrorLog  /home/me/public/myfirstdomain.com/log/error.log
  CustomLog /home/me/public/myfirstdomain.com/log/access.log combined
</VirtualHost>

A: You can remove the A record for the website from the DNS, then browsers cannot load the web site.
Alternatively you can make a default virtual host on your web server that serves just an empty page.


text:
Q: Decimal number with comma instead of point (php and sql) I'm doing a little application of adding prices and decimals. Points are normal to use with decimals, but how can I write decimal number with comma as input (543,35 instead of 543.35) and then maybe change it with point to the database (mysql)? Then print it back form the database with the comma. Reason is that comma (,) is more used in Finland than point (.) when write decimal numbers.
Thank you very much!
Samuel

A: you need not do anything in the sql end. you want to format the decimal value in php (this assumes php4/php5): Set the third parameter $dec_point to ','
// string number_format ( float $number , int $decimals , string $dec_point , string $thousands_sep )
<?php

$number = 1234.56;

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

source:
http://php.net/manual/en/function.number-format.php
Cheers!

A: $input  = '5,50';
$output = str_replace(',', '.', $input);
var_dump($output); // string(4) "5.50"
$number = (float)$output;
var_dump($number); // float(5.5)

A: the PHP number_format function is what you need :
number_format(5.50, 2, ',');

...should do the trick.

A: As it's been said, it's best to save the value as a float and then format for display. As an alternative to the previously suggested number_format(), you could try money_format() http://us.php.net/manual/en/function.money-format.php It doesn't work in a windows environment though if that is important to you.

A: No, using comma as a decimal separator for arithmetic operations is not supported. Filter your input and replace the comma with a period, then format your output as you wish.


text:
Q: Installing only new packages from composer.json I'm trying to make composer update only newly added packages to composer.json i.e when I manually add a package dependency to the composer.json file, it should update the composer.lock file only for the new package; the rest of the packages should be at the same version as before. I tried running composer update --lock but I don't think it does what I'm trying to achieve and it took a lot of time to finish. I checked the commands on composer's documentation but can't find one to achieve my wish. Any advice or workaround will be appreciated.
Note: I'm using Laravel Forge, so there is a 2 minutes deployment limit.

A: In order to install only new packages with composer you should run
composer install
Because composer update will install your new packages but will update and all the other already installed packages.

A: You can specify the name of the package as an argument to the update command. This will perform a partial update: composer update the-package/you-want-to-update

A: I think your question is related to your (guessed) current workflow: To add a new package you edit the composer.json file and then run composer update - wishing to only add/update that new file.
If that is true, here is the solution:
composer require new/package will add the newest possible version (taking into account the currently installed packages) of the new package. Benefits: Only one command line, and no fiddling with JSON content.
If you already know which version you want, you could also run composer require new/package:^2.1.25@beta (or whatever version and stability level you want - this example is exaggerating a bit). If this version is incompatible with existing packages, nothing will get installed, everything will get rolled back, and you get an error message.


text:
Q: RecyclerView: No adapter attached; skipping layout - recycleView error Its giving me "RecyclerView: No adapter attached; skipping layout" error but in my opinion adapter is correctly attached. Please help.
    public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private RecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
        layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        requestJsonObject();
    }

    private void requestJsonObject(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="https://api.myjson.com/bins/2t4j3";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response " + response);
                GsonBuilder builder = new GsonBuilder();
                Gson mGson = builder.create();
                List<ItemObject> posts = new ArrayList<ItemObject>();
                posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
                adapter = new RecyclerViewAdapter(MainActivity.this, posts);
                recyclerView.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error " + error.getMessage());
            }
        });
        queue.add(stringRequest);
    }
}

I was moving my methods, but its not working. I was looking here for answer but there was only problems with wrong implemented adapters. I dont't know whats wrong here.

A: Try to put this line:
adapter = new RecyclerViewAdapter(MainActivity.this, posts);

After adding a LayoutManager to the RecyclerView. Of course the list will be empty, but just init RecyclerAdapter and assign it to the RecyclerView
Then, when Volley completes it's request, use:
recyclerView.getAdapter().addAll(posts);
recyclerView.getAdapter().notifyDataSetChaged();

The last commands add elements to the RecyclerView's adapter and notify LayoutManager of the change.

A: You are calling setAdapter in a delay thread. When the view is created in the main thread, the Recyclerview do not have an adapter.
Put this two lines before setLayoutManager
List<ItemObject> posts = new ArrayList<ItemObject>();
adapter = new RecyclerViewAdapter(MainActivity.this, posts);

In onResponse, you can ethier set a new adpater or update the data in the adapter which depends on your implementation.


text:
Q: NumPy saving an object with arrays of different shape but same leading dimension I experienced some unexpected behavior of np.save().
Assume, you want to save two numpy arrays into one .npy file (as an object). As long both arrays have the same shape this works without any problem, but when the leading dimension is the same an error occurs.
The problem is caused by np.asanyarray(), which is called in np.save() prior saving.
It is clear that one could solve this problem by e.g. saving into different files, but I am not looking for another solution, I want to understand this behavior of np.save().
Here is the code:
import numpy as np
a = np.zeros((10, 5))
b = np.zeros((10, 2))
np.save('test', [a, b])

Causes this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3/lib/python3.6/site-packages/numpy/lib/npyio.py", line 509, in save
arr = np.asanyarray(arr)
File "/python3/lib/python3.6/site-packages/numpy/core/numeric.py", line 544, in asanyarray
return array(a, dtype, copy=False, order=order, subok=True)
ValueError: could not broadcast input array from shape (10,5) into shape (10)

When the leading dimension is different there is no problem:
a = np.zeros((9, 5))
b = np.zeros((10, 2))
np.save('test', [a, b])

For me this behavior of np.save is inconsistent and seems to be a bug.

A: After seeing the source of asanarray method here (save method calls it internally) I see it tries to make a ndarray of the list which is passed using the array method. Now if they have different dimensions, it is able to to make an ndarray with 2 different elements in it. However, if they have the same leading dimension it tries to broadcast them together into a same ndarray. This is because it by default tries to make a high dimensional output. To get around this you can first make use of the empty method to specify dimensions, then use that to substitute the values like:
a=np.zeros((10,5))
b=np.zeros((10,2))
c=[a,b]
finalc = np.empty(len(c),dtype=object)
finalc[:]=c
np.save("file",c)

A: Am I do something wrong, I saved "finalc" and not "c". When I tried to save "c" there are the same error.
a=np.zeros((10,5))
b=np.zeros((10,2))
c=[a,b]
finalc = np.empty(len(c),dtype=object)
finalc[:]=c
np.save("file", finalc)


text:
Q: Restrict jstree dragging from one tree to other tree I am using Two different trees

*

*Tree1

*

*A

*B

*C

*Tree2

*

*A1

*B1

*C1

I am using drag and drop for both within the tree and i want to restrict that dragging from Tree1 to Tree2

$('#tree1').on('move_node.jstree',function(event,data){
             });

How can I allow a tree to drag only within the tree
Pls help to solve this

A: I got the solution to restrict the DND Plugin in jstree get the Latest source from github
place this in check_callback
check_callback : function (o, n, p, pos, more) {
  if(more && more.dnd && more.is_multi) { return false; }
  return true;
}


text:
Q: Redirect full http-link to https-domain on another server I'm not sure if this even is possible to do, but I have two different domains on two different webservers. Both have a SSL-certificate. What I need is for all links on domain1 (both http and https) to be redirected to domain2 with https. Example:
http://domain1.com/customlink should be redirected to https://domain2.com/customlink
Also https://domain1.com/customlink should be redirected to the same as above.
Is this possible to achieve by having a .htaccess file with some rules on the webserver of domain1.com? It is important that whatever the user writes after domain1.com, also will be kept in the new redirected link.

A:
I'm not sure if this even is possible to do .... my host told me that you cannot redirect https://example.com/SOMETHING and keep the part after slash onto the new domain

I feel there must be something more to this question, as otherwise, this is just a standard domain redirect...

*

*two different domains on two different webservers

*Both have a SSL-certificate.

*Assuming there is only 1 domain (ie. domain1.com) hosted on the first server that you want to redirect.

Then, in your .htaccess file at domain1.com, use a mod_alias Redirect:
Redirect 302 / https://domain2.com/

You should remove all other directives in the .htaccess file at domain1.com in order to avoid potential conflicts (they aren't being used anyway, since you are redirecting everything).
The mod_alias Redirect directive is prefix-matching, and everything after the match is passed on to the target. eg. /foo/bar/baz is redirected to https://domain2.com/foo/bar/baz. Everything (HTTP and HTTPS) is redirected to domain2.com (HTTPS).
This is currently a 302 (temporary) redirect. Only change to a 301 (permanent) - if that is the intention - once you have confirmed this works as intended. This is to avoid any potential caching issues.


text:
Q: Node/Babel : Switching from babel-node or babel-register to babel-cli for production Setup
Babel 6 (^6.0.0),
Node 5.4.0,
Express 4.13.x,
Both babel-node and babel-register have a warning to not be used in production on the
babel.io website. Basically transpiling on the fly like that is too slow for production.
So I've set things up to be transpiled with babel-cli and running pre-transpiled code.
The Problem:
During development, it's too slow re-transpile all the code and re-start the program for
every single change. I also can't see how a change monitor(e.g. nodemon) can be set for automatic reloads since we are now running the transpiled code and not the source(where changes are happening).
Question:
How do we set-up an easy way to switch between on-the-fly transpiling during development, and pre-transpiling for production?
Most examples I see babel-node and babel-register being used for development and production so I'm not sure what's a good strategy for quick development with babel while also preparing the code-base for production shipping.

A: Watch out many highly popular Node boilerplate repositories on Github  are still using babel-node and babel-register for production code and that's probably because,not to long ago,they were much easier to use for setting up a fast reloading developing environment. BUT, it's just as simple to use babel-cli and I recommend using it for both development and production code right out of the gate.
With help from the comments, I got to my core question:
"When developing, how can I avoid the slow rebuilding of my source code when using babel-cli?"
Unlike the on-the-fly transpling that babel-node and babel-register offer, which is fast for restarting during changes in development, the babel-cli pre-transpiles your code to a build destination where your code can then be run separately in it's es5 format. During development, building code from source to build between each change is slow because you have to wait for every file to be transpiled before restarting your server.
The solution is simple -all you need is babel-cli's watch method out-of-the-box can watch all your source code and quickly update your build code by only rebuilding files that updated while it watches.
Sorry if the solution is painfully obvious as you read this but the babel docs only show code watching for single files and there currently there is a plethora of popular libraries on Github devoted specifically to watching entire folders for changes, and so I'm assuming the out-of-the-box solution is somewhat new, and makes using babel-cli an obvious choice over babel-node and babel-register.
So, all you have to do is use an npm script like so:
"watch-files" : "babel src --watch --out-dir build"

and restart your server in the build directory whenever an update is made(unless you set up an automatic reload that watches the build folder).
Credit to @FelixKling  and @aray12 comments that helped me see that babel-cli is really easy to use even during development.


text:
Q: Passing arrays in to the function in bash script I am new to a bash script and writing the bash script. I have declared an array and I have given the values. But When I pass the array in the loop values are not getting inside the loop. Below is my code
declare -a files=( "A1S0" "D1S0" "D2S0" "D3S0" "D4S0" "D5S0" "D6S0" )
command_to_get_filesizes() {
  for i in "${!files[@]}"; do
     echo Processing file "${i[${index}]}"
  done
}
command_to_get_filesizes

Expected Output
A1S0
D1s0
D2S0
D3S0
D5S0
D680

But am getting output as
Processing file 0
Processing file 1
Processing file 2
Processing file 3
Processing file 4
Processing file 5
Processing file 6

could anyone pls help me to print values in the array

A: As per your expected output,

*

*we don't require "Processing file" in that echo command.

*we don't need to pass the index value of array while looping it in for loop.

Try as
declare -a files=( "A1S0" "D1S0" "D2S0" "D3S0" "D4S0" "D5S0" "D6S0" )
command_to_get_filesizes()
{
  for i in "${files[@]}"; do
    echo "$i"
  done
}
command_to_get_filesizes

A: The variable 'index' is undefined. What you intended was
echo Processing file "${files[i]}"

What the original does is obscure. All variables are (potentially) arrays with a zeroth element. (Try echo "${PATH[$junk]}".) So that whole construct "${i[${index}]}" resolves as ${i[0]}, which just echoes $i.
Your title is slightly misleading: you do not pass the array into the function (as a parameter): it is merely a global array variable.
@Siva is correct in that you can iterate over the array values simply. However, if you need both the index and the value in the same iteration, this does it for me.
for n in "${!N[@]}"; do
    printf '%8d  %s\n' "${n}" "${N[n]}"
done


text:
Q: Tool to shows server workload status (ASP.NET + MS SQL) I want to provide our testers with tool to see live server load, like memory usage, processor usage, database etc via webpage.
There are a lot of tools which are installed on server for admin, But definitely I do not want to provide access to live remote desktop.
I am using Windows 2003, IIS, MS SQL Server, ASP.NET

A: SCOM (System Center Operations Manager), htough not really LIVE (live does not scale= - point.
Otherwise the normal performancecounters work - you can connect to them from a remote computer.


text:
Q: How to properly notify view layer to open a dialog? I have a WPF application and i'm trying to respect the MVVM pattern rules. One of my views contains button:
                <Button
                    Command="{Binding BrowseCommand}"
                    Margin="50, 0, 0, 0"
                    Style="{StaticResource CommonButtonStyle}"
                    Width="100"
                    Height="30">
                    <TextBlock
                        Text="Browse"/>
                </Button>

Button command calls a method:
private void Browse(object sender)
{

    DialogService.BrowseForDestinationPath(DestinationPath);

}

The main purpose of this method is to show "Select-directory-dialog", collect data and return it to the view model.
    public static class DialogService
    {

        public static event Action<string> FolderBrowseRequested;

        ...

        public static void BrowseForDestinationPath(string initialPath)
        {

            FolderBrowseRequested?.Invoke(initialPath);

        }

    }

Event defined in my DialogService class is invoked, and the subscriber method located in code-behind of the dialog fires:
        protected void OnFolderBrowseRequested(string initialPath)
        {

            string destinationPath = initialPath;
            var browsingDialog = new VistaFolderBrowserDialog();

            if(browsingDialog.ShowDialog(this).GetValueOrDefault())
            {

                destinationPath = browsingDialog.SelectedPath;
                var dataContext = DataContext as UnpackArchiveWindowViewModel;

                if (dataContext != null)
                    dataContext.DestinationPath = destinationPath;

            }

            DialogService.FolderBrowseRequested -= OnFolderBrowseRequested; //so dumb

        }

The problem is i really don't like this solution, I'm convinced it's unnecessarily complicated and inelegant. How to properly show a dialog on button click, collect some data and deliver it to our view model? I would like to keep View and ViewModel seperated and fully respect MVVM regime.

A: You could first start by describing the behavior your DialogService needs in an interface.
public interface IDialogService
{
    void BrowseForDestinationPath(string initialPath);

    event PathSelectedEvent PathSelected;
}
public delegate void PathSelectedEvent(string destinationPath);

Your ViewModel would contain a member of type IDialogService and subscribe to the PathSelectedEvent. The BrowseForDestinationPath method would be called using your Browse method which is called using the Command.
You could then create a user control which implements IDialogService. You could either inject this through your ViewModels constructor or if your ViewModel had a property like
public IDialogService FolderBorwser {get;set;}

the benefit of this approach is that all your view model knows about is an interface. You now delegate the responsibility of creating a concrete instance to something else. I would reccomend using an Injection Container like Unity or MEF as they handle the job of managing and resolving dependencies.

A: I encourage you to write your own logic because it helps you to understand the problem of opening dialogs in MVVM, but if you hit a brick wall or wan't to take the easy way out, there is a library called MVVM Dialogs that can help you with these problems.
Using this library you would write your code like this.
private void Browse(object sender)
{
  var settings = new FolderBrowserDialogSettings
  {
    Description = "This is a description"
  };

  bool? success = dialogService.ShowFolderBrowserDialog(this, settings);
  if (success == true)
  {
    // Do something with 'settings.SelectedPath'
  }
}


text:
Q: Any way to inject a provider with a dependency on another provider in AngularJS config Given the code:
angular
  .module('someApp', ['provider1Module, provider2Module'])
  .config(function (provider1ModuleProvider, provider2ModuleProvider){
     provider1ModuleProvider.getSomethingSpecific()
  })

Given also that provider1ModuleProvider.getSomethingSpecific() depends on a method of provider2ModuleProvider's getSomethingGeneric() method, how can I call this method from within the config?
Right now, when I try to run code similar to this, I get an error that essentially tells me the second provider is not instantiated.  Can I explicitly instantiate both providers in the config in some way so that one provider's dependency on the other is resolved?
Essentially, what I'm trying to do is get some data in an abstract view state for some views in UI-router so that I can use it in child views.  If my pattern above won't work, any other suggestions?


text:
Q: Filter hours in datetime using SQLAlchemy I need to filter objects with a datetime field in the following way.
I have a lower and upper limit for hours and a separate lower and upper limit for dates. For example, I want to get all the objects  between May 1, 2013 and April 12, 2014 with an hour anywhere between 7 and 17.
I know approximately how I would do this in Django, but I can't find any resources explaining how to do it with SQLAlchemy.


text:
Q: how to prevent user from submitting the same form twice I have the codes below in my views and models. But I want a situation in which a  user cannot submit the same form twice. once a user submits the form he or she can only see a preview of what has been submitted but is unable to submit the same form.
Any help would be highly appreciated. Thanks
#views.py
def index(request):
    form = MembershipForm()
    if request.method == 'POST':
       form = MembershipForm(request.POST)
       if form.is_valid():
          form.save()
          return redirect("home")
    return render(request, 'index.html', {'form': form)

#models.py
class Membership(models.Model):
    fullname = models.CharField(max_length=500, blank=True, null=True)
    location = models.IntegerField(default='0',blank=True, null=True)
    department = models.IntegerField(default='0',blank=True, null=True)
    last_update = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __str__(self):
        return  str(self.fullname)


text:
Q: Why is my Ubuntu 18.04 distribution asking me to upgrade to Pop!_OS 19.10? I have Ubuntu 18.04 and I just received a notification that I can upgrade to Pop!_OS 19.10. Why in the world would this happen? Did I break my system? Has anyone else had something similar happen?
The only thing I have installed from Pop!_OS is their icon theme. Could it be because I have their ppa on my system? How can I clear this notification and request to update?

A: By adding the Pop PPA, you've received the patched version of GNOME Control Center, which pulls in pop-upgrade, which will prompt to upgrade to Pop!_OS 19.10. It's a required dependency of the patched version of gnome-control-center, so removing it would also remove the control center. We don't recommend adding the Pop! ppa on top of Ubuntu. We apologize for the issues it caused!

A: So I figured out what the issue is after some detective work and some experimentation. I had the Pop! ppa on my system for some reason. I guess this was a side effect of using the Pop Icon theme. I was searching through folders in /var/lib/ and found an empty pop-upgrade folder. At first I was not certain what it was, but it was entirely too coincidental for me to have a Pop!_OS system upgrade message and run across this folder and not have them be connected.
I have TimeShift on a daily schedule (highly recommend this people) so I decided to just sudo apt-get remove pop-upgrade and see what happened. I did this and then used autoremove but I ran into issues. I no longer had an ability to get to my default Gnome Settings menu. There were probably a bunch of other issues.
So what I did was I used TimeShift to go back to the day before, and when I went to apt-get upgrade I realized that gnome-control-center was being held back from upgrading because it needed additional packages. Those packages were libpop-upgrade and something else. So now I had it cornered. I must have used dist-upgrade earlier that night without realizing it, and it just force installed those extra Pop! packages, which led to the message. After I removed the Pop! ppa from my sources list, gnome-control-center no longer wanted to update, and pop-upgrade was not requesting an install.
Basically, do not have Pop! ppa on your Ubuntu system, because it will cause problems. I should have seen this coming but I am still only an intermediate with Linux. If you have already run into this same problem I had above, roll back to a previous point in time before the gnome-control-center upgrade, and remove the Pop! ppa from your system. Then you should be able to use update and upgrade without contaminating your system.


text:
Q: Learning C++ Templates Can anyone recommend any good resources for learning C++ Templates?
Many thanks.

A: This is a more advanced, but very useful, book on templates and template use.
Modern C++ Design

A: Bruce Eckel's Thinking in C++ is how I learned about templates. The first volume has an introductory chapter and the second volume has an in-depth chapter on templates.
There's Bjarne Stroustrop's The C++ Programming Language which has a good chapter on them. And The C++ Standard Library: A Tutorial and Reference which is about the standard library, but would definitely help you get a better understanding of how templates could be used in the real world. .

A: Be sure to differentiate between generic programming and template metaprogramming (which is more like another paradigm)
Generic programming can be learnt from the C++ bible, but you can just as well take a look at the java generics etc...
one about metaprogramming: Josuttis' book C++ Templates: The Complete Guide

A: The 2 volumes of 'Thinking in C++' go over the basics of templates. They can either be bought in print, or downloaded for free (and legal) use here.

A: I recomned that you get C++ Templates - The Complete Guide it's an excellent resource and reference.

A: I've found cplusplus.com to be helpful on numerous occasions.  Looks like they've got a pretty good intro to templates.
If its an actual book you're looking for, Effective C++ is a classic with a great section on templates.

A: "The C++ Programming language" by Bjarne Stroustrop


text:
Q: Prevent sap.m.popover from closing on click How do I prevent sap.m.popover from closing when the user clicks somewhere else on the page? Is there any solution to this requirement? I was not able to finde anything regarding this in the documentation.
Can someone point me in the right direction, please?

A: Isnt the property modal what you are looking for?

The popover will not be closed when tapping outside the popover. It also blocks any interaction with the background. The default value is false.

Check the demo kit for the modal property. The Demo-kit is really something you should often use, it could help you a lot.
<Popover title="Test" class="sapUiContentPadding" placement="Bottom" modal="true">
    //whatever you want inside your popover
    <footer>
        <Toolbar>
            <ToolbarSpacer/>
            <Button
                id="close"
                text="Close"
                press="handlClosePress" />
        </Toolbar>
    </footer>
</Popover>