text:
Q: C string array bubble sort returns the input as output in my function I am given a string array where it needs to be sorted via a specific ruleset which is also given - the main function works and the rule comparison ones work as well but the bubble sort keeps returning the input as output and I can't figure out why.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
void swap(char** s1, char** s2)
{
    char** temp = s1;
    s1 = s2;
    s2 = temp;
}
main()
{
    int i, j;
    char** arr_of_strings = malloc(3 * sizeof(char*));//I allocated the array
    arr_of_strings[0] ="wonder_woman";//with malloc and loops originally.
    arr_of_strings[1] ="batman";
    arr_of_strings[2] ="superman";
    for (i = 0; i <2; i++)//the bubble array process:
    {
        for (j = 0; j < 3 - i - 1; j++)
        {
            if (strcmp(arr_of_strings[i], arr_of_strings[j]) > 0)
            {
                swap(&arr_of_strings[j], &arr_of_strings[j + 1]);
            }
        }
    }
     printf("The sorted strings are:\n"); //printing the function
    for (int k = 0; k < 3; k++) {
        printf("%s\n", arr_of_strings[k]);
    }

}

output example:
The sorted strings are:
wonder_woman
batman
superman

A: check this lines, compairing i with j , but swapping j and j+1
if (arr_of_strings[i]> arr_of_strings[j]) //simplification
  {
    swap(&str_arr[j], &str_arr[j + 1]);
  }

A: I think you have a problem with your swap function' or the way you call it.
anyway, this implementation works:
#include <stdio.h>
#include <malloc.h>
#include <string.h>

#define SIZE 3

int main()
{
    int i, j; int n=SIZE; //n is a user input in the original program.
    char temporary_string[32];
    char* arr_of_strings[SIZE];
char* temp = NULL;

//input data
for (int l = 0; l < 3; l++)
{
    scanf("%s", temporary_string);
    arr_of_strings[l] = malloc(((strlen(temporary_string) + 1) *sizeof(char)));
    strcpy(arr_of_strings[l], temporary_string);
    temporary_string[0] = '\0';
}

//the actual sort
for (i = 0; i < n - 1; i++)
{
    for (j = 0; j < SIZE - i - 1; j++)
    {
        if (strcmp(arr_of_strings[j], arr_of_strings[j + 1]) > 0) //simplification
        {
           //swap
           temp = arr_of_strings[j];
           arr_of_strings[j] = arr_of_strings[j + 1];
           arr_of_strings[j + 1] = temp;
        }
    }
}

printf("The sorted strings are:\n");
for (int i = 0; i < n; i++) {
    printf("%s\n" , arr_of_strings[i]);
}
 // free allocated memory
 for (int i = 0; i < n; i++) {
     free(arr_of_strings[i]);
 }
}

I hope it helps, if you have quastions I would be happy to answer =)

A: Your swap function doesn't actually swap the items pointed to by its parameters. Change it to:
void swap(char** s1, char** s2)
{
    char* temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

Also, your main function is comparing non-adjacent items but swapping adjacent items, so it doesn't sort properly.  Change the relevant part of the code to:
            if (strcmp(arr_of_strings[j], arr_of_strings[j + 1]) > 0)
            {
                swap(&arr_of_strings[j], &arr_of_strings[j + 1]);
            }

to sort in ascending order.
The bubble sort can be optimized by keeping track of the position of the last swapped item and finishing the sort after a pass that does not swap any items:
    i = 3; // sorting first 3 items
    while (i > 1)
    {
        int last = 0;
        for (j = 0; j < i - 1; j++)
        {
            if (strcmp(arr_of_strings[j], arr_of_strings[j + 1]) > 0)
            {
                swap(&arr_of_strings[j], &arr_of_strings[j + 1]);
                last = j + 1;
            }
        }
        i = last;
    }

A: Your swap function doesn't do anything.
It is similar to this function supposed to swap two ints:
void swap(int a, int b)
{
  int temp = a;
  a = b;
  b = temp;
}

If you call it like this:
int a = 2, b = 3;
swap(a,b);

a and b still contain the same values.
This is the correct code for your swap:
void swap(char** s1, char** s2)
{
  char *temp = *s1;
  *s1 = *s2;
  *s2 = temp;
}


text:
Q: Operation is not valid due to the current state of the object - HASP HL dongle I am trying to add reference to my Delphi Prism project for HASP HL. So, I can communicate with the USB HASP HL dongle.
After the initial set up, I couldn't get my program to communicate with the USB HASP HL dongle. So, I watched a youtube tutorial video by SafeNet or Alladdin and followed their instruction to the teeth exactly, but I ran into another problem, which I can't seem to figure out.
As part of the HASP HL dongle setup, I am supposed to add reference for hasp_net_demo.dll to my project. Everytime I try to do that, I keep getting this error, Operation is not valid due to the current state of the object, and it won't let me add the reference. I learned that along with hasp_net_window.dll reference you also need to add reference to hasp_net_demo.dll, because it has the actual namespace and class to communicate with your HASP HL dongle.
So, what can I do at this point? or What options do I have?
Please, help. I have been looking at this problem for the last 3 months on and off and still can't find a solution.
Thanks in advance,

A: I was able to resolve my issue. First, you need to make sure that you are writing application for framework 4.0. If you are, then you need to download their latest Runtime API for .NET dll files.
Sentinel HASP DotNET Runtime API
apidsp_windows.dll
apidsp_windowsx64.dll
hasp_net_windows.dll
hasp_windows_xxxxx.dll

Put them all in your project folder. Then, add reference to hasp_net_windows.dll file to your project file.
Then, you are done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass multiple args in Ember JS prop I have a function that lives in a component and I want to pass multiple arguments to it from the parent. I realise I can pass them individually but I'd like to pass them as one arg if possible.
I'd like this to work but the syntax in actionArgs isnt correct
<MyComponent @actionName={{myAction}} @actionArgs={{myValue, myOptions}} />

<button {{on "click" (action @actionName @actionArgs)}}></button>

I've tried wrapping in parenthesis but that didnt work either.

A: Amazingly this can be done by passing in the fn arguments with the fn helper
<MyComponent @actionName={{fn myAction myValue myOptions}} />

<button {{on "click" (action @actionName)}}></button>


text:
Q: Chrome maximized window bug Xubuntu (Xfce) Since last Google-Chrome update to version 95.0.4638.54, Chrome is not respecting screeen size when maximizing the window.

A: It's been identified as a bug in Chrome. The bug that seems the most active is https://bugs.chromium.org/p/chromium/issues/detail?id=1260821
But there are also what appears to be a few duplicates:

*

*https://bugs.chromium.org/p/chromium/issues/detail?id=1257119

*https://bugs.chromium.org/p/chromium/issues/detail?id=1261797

*https://bugs.chromium.org/p/chromium/issues/detail?id=1264432
Your best bet is to wait for the next Chrome update.

A: I have a workaround for this: enable "Use system title bar and borders" in settings of Google Chrome. (You can search the setting by the name.)

A: Previous version of chrome did not have such a problem. This is a bug of chrome and I already reported my instances to google. I believe a newer version will fix this soon.

A: I had the same issue and the solution to it was to "Use system title bar and borders" under the settings on the "System Menu" on the upper-right hand corner in Chrome.
Navigate to settings -> appearance and the setting is in there.
As shown in this picture:

A: This behavior is observed in the Chrome 95 and higher (unfortunately, the same happens in Chrome Beta 96. at least for me.)
As a workaround I downgraded the Chrome version to 94.
If you have the same problem you can use this workaround:

*

*uninstall the google-chrome-stable package:
sudo apt remove google-chrome-stable

*download Chrome 94 from Google repository and install it.

*hold the google-chrome-stable package to prevent its updating:
sudo apt-mark hold google-chrome-stable
You will still receive Chrome update lists and see a new version for the package:
/$ apt list --upgradable
Listing... Done
code-insiders/stable 1.63.0-1636719582 amd64 [upgradable from: 1.63.0-1636472235]
code/stable 1.62.2-1636665017 amd64 [upgradable from: 1.62.1-1636111026]
google-chrome-stable/stable 95.0.4638.69-1 amd64 [upgradable from: 94.0.4606.81-1]

but it won't install by sudo apt upgrade:
/$ sudo apt upgrade
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
The following packages have been kept back:
  google-chrome-stable
The following packages will be upgraded:
  code code-insiders
2 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
Need to get 163 MB of archives.
After this operation, 26,6 kB of additional disk space will be used.
Do you want to continue? [Y/n]

until you unhold the google-chrome-stable package:
sudo apt-mark unhold google-chrome-stable

A: For those offering up "Use system title bar and borders" as a solution, be aware that this seems to remove the Minimize, Maximize and Close buttons from the title bar, i.e. you'll move from this:

... to this:

(Yes, that's the top-right edge of the window in both images).
You can still manipulate the window by double-clicking on the title bar, of course, along with right-clicking the Chrome tile on the window buttons (i.e. where you get the list of running applications alongside the main Whisker menu button).
You can always take the nuclear option of closing Chrome and then re-opening it, but a more convenient workaround appears to be to simply right-click an item in that main panel (Panel 0 - so, the Whisker Menu, Window Buttons, Workspace Switcher, Notification Area...) , and select "Panel Preferences". Chrome will immediately resize correctly, and then you just close the resultant Preferences dialog.
Note that this doesn't work if you try anything other than Panel 0.

A: I have found that reloading the xfce panel temporarily resolves this. I did a keybind of "xfce4-panel -r" to an F-key. This will get you by until the Chrome bug is fixed.


text:
Q: How to emit an item from first observable then 4 items from second observable? Let's say I have two array lists, I want to emit an item from the first list then 4 items from the second list and combine them into a third observable which emits the result of this operator. If the second list has less than 4 items, then emit all items remaining from this list.
O1: A, B, C, D
O2: 1,2,3,4,5,6,7,8,9,10,11,12,13,14
So the result will be : A1234    B5678   C9101112   D1314

A: Haven't checked by a compiler, it's just something I can think of:
Observable<T> o1 = ...
Observable<T> o2 = ...

Observable<T> o3 = o1.zip(o2.buffer(4), (a, b) -> {
  List<T> contents = new ArrayList<>();
  contents.add(a);
  contents.addAll(b);
  return contents;
}).flatMap(list -> Observable.from(list));

*

*buffer the second Observable (the one that you want to take chunks of 4 of)

*zip it with the first Observable, and create a single List<T> from the 2

*flatMap the Observable<List<T>> into Observable<T>

*Also mind that I assume that both of your Observables are of the same type.


text:
Q: Массив данных одного класса в другом классе Есть классы
class Voucher {
string date;
int visitors;

};

class Balance {};

Как сделать что бы в классе Balance выводился список (массив) данных класса Voucher например
1) "24.12.2018", 6 visitors
2) "13.11.2019", 10 visitors и т.д

A: Видимо где то так
class Voucher {
public: // иначе будет сложно
int date;
int visitors;

};

class Balance {
private:
  std::vector<Voucher> m_voucher;
public:
void show() {
  for (int i = 0; i < m_voucher.size(); i++) {
    std::cout << (i+1) << ") " << int2strdate(m_voucher[i].date) << ", " << m_voucher[i].visitors << " visitors" << std::endl;
  }
};

std::string int2strdate(int date) {
   // тут как то самостоятельно напишите, я не знаю, как дату сохраняете
   return ...;
}


text:
Q: How to make PHP CodeSniffer standard PHPCS validate the ternary operator? I've been using PHP_CodeSniffer for a few days but I still can't validate some codes. When I use ternary operator, even a very simple like this:
$name = (strlen($name) > 0) ? $name : 'nameless';

The Code Sniffer says:

ERROR | Inline IF statements are not allowed

But if I write an invalid code using ternary, like this:
$name = strlen($name) > 0? $name: 'nameless';

Code Sniffer says "FOUND 4 ERRO(S)...":

ERROR | The value of a comparison must not be assigned to a variable
  ERROR | Inline shorthand IF statement requires brackets around comparison
  ERROR | Inline IF statements are not allowed
  ERROR | Expected 1 space before "?"; 0 found
  ERROR | Expected 1 space before ":"; 0 found

Why it validate all ternary expressions but, when I fix all, PHPCS says it is invalid? Am I writing it wrong or it simply does not allow ternary at all?

A: The sniff is failing, not syntax errors.  You have rules defined that you are not following.  You either need to correct your code or remove the rules from the ruleset.
Inline IF statements will be the ternary option you wrote. By your ruleset, you need to write:
if (strlen($name) > 0)
{
    $name = $name;
}
else
{
    $name = 'nameless';
}

Likely better to remove the sniff from the rules.
In the edited code, the sniffs are complaining that
> 0?

should be
> 0 ?

and
$name: 'nameless';

should be
$name : 'nameless';


text:
Q: Play Java validation fail for Set and Map I use Play 2.5.12 to provide a web service to create an object and validate its attributes. Here is a simplified code of what I want to do:
public class Example {

    private String lastName;

    private List<String> firstNames;

    private Map<String, Integer> vehicles;

    public Example() {}

    public String validate() {
        if (vehicles.get("Ferrari") != null)
            return "Liar!";
        return null;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).append(lastName).append(firstNames).append(vehicles).toString();
    }

    // getters and setters
}

public class ExampleController extends Controller {

    private FormFactory formFactory;

    @Inject
    public ExampleController(FormFactory formFactory) {
        this.formFactory = formFactory;
    }

    @BodyParser.Of(BodyParser.Json.class)
    public Result createExample() {
        Example exampleFromJackson = Json.fromJson(request().body().asJson(), Example.class);
        System.out.println(exampleFromJackson.toString());
        Example exampleFromForm = formFactory.form(Example.class).bindFromRequest().get();
        System.out.println(exampleFromForm.toString());
        // etc
        return created();
    }
}

If I call the web service with a body like this:
{
    "lastName": "Martin",
    "firstNames": ["Robert", "Cecil"],
    "vehicles": {
        "BMW": 1,
        "Seat": 1
    }
}

The deserialized object by jackson prints correctly then this error occurs:
org.springframework.beans.InvalidPropertyException: Invalid property 'firstNames[0]' of bean class [models.Example]: Property referenced in indexed property path 'firstNames[0]' is neither an array nor a List nor a Map; returned value was [[]]

If I replace the Set by a List, I can avoid this error and then I obtain the following:
models.Example@68d2162a[Martin,[Robert, Cecil],{BMW=1, Seat=1}]
models.Example@29ef1c11[Martin,[Robert, Cecil],{}]

The deserialized object by jackson is correct but the one obtained by the request isn't so I can't do a correct validation.
So my questions are:
- Why Play doesn't let me use a Set?
- Why is the Map not retrieved?


text:
Q: Navigation bar for angular2 not properly displayed

            <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>
                Toggle navigation

            </button>
            Angular

                         Home

                         Counter

                         Fetch data

                         MarginReport

    import { Component } from '@angular/core';
    import { MarginServcies } from '../../services/MarginService';
    import { Response } from '@angular/http';
    import { Http } from '@angular/http';

    @Component({
        selector: 'margin',
        template: require('./margin.component.html')
    })
    export class MarginComponent {
        //public MarginList = [];
        //public constructor(private marginService: MarginServcies) {
        //    this.marginService.getMargin()
        //        .subscribe(
        //        (data: Response) => (this.MarginList = data.json())
        //        );
        public margin : Margin;

        constructor(http: Http) {
            http.get('http://localhost:2213/api/margin').subscribe(result => {
                this.margin = result.json();
            });
        }
    }

    interface Margin {
        AccountID: string;
        AsOfDate: Date;
        MarginType: string;
        DelivType: string;
        FedCall: number;
        MaintenanceCall: number;
        DayTradingCall: number;
        HouseCall: number;
        RegT_CallBalance: number;
        Equity: number;
        CashAvailable: number;
        DayTradingBuyingPower: number;
        PMA_Excess: number;
        AccountStatus: string;
        Company: string;

    }

Margin

    <margin>

    </margin>

Hi, above is my navigation bar code. And the MarginReport section just doesnot show up.I do not know why. i also have a margin.component.ts for my angular app.
I am not sure if it is the routing problem. i want the nav bar to show home, fetchdata, counter and margin report.
could anyone help me with that?


text:
Q: Перенаправление вывода терминала в переменную Помогите разобраться с перенаправлением вывода cmd в переменную, т.к. переменной присваивается только exit_code процесса. Для наглядности есть пара примеров:
Пример
import sys, os
command = "tasklist"
result1 = os.system(command)
print(result1) # на выходе получим 0

Пример 2
command = "tasklist>temp.txt"
result2 = os.system(command)
print(result2) # на выходе получим 0
with open('temp.txt', 'r') as f:
    result2 = f.read()
    print(result2) # выведет результат выполнения tasklist

Вопрос: можно ли перенаправить вывод терминала windows не используя temp.txt файл, тобиш сразу выгружать значение в переменную.? sys.stdout пробовал.
sys.stdout = open('temp.txt', 'w') #запишет 0 в файлик
os.system('tasklist') #сам резульат выполнения будет выведен в интеретаторе

file = open('temp.txt', 'r').read()
print(file)# выведет 0

A: Самый простой способ перенаправить вывод из системной оболочки - это подключиться к каналу команды, вот таким образом:
import os

command = 'dir'
pipe = os.popen(command)

print(pipe.read())

Здесь мы открыли канал и получили объект открытого файла из которого можно читать или писать в него в зависимости от режима (r по умолчанию) открытия, используя стандартный интерфейс работы с файлами.

A: subprocess.check_output()
— это самый простой способ получить вывод внешней команды:
import subprocess

output = subprocess.check_output(['программа', 'аргумент 1', '2'])

Всё что программа выводит в стандартный вывод, сохраняется в output. Если программа завершится с ненулевым статусом возврата (как правило на ошибку указывает), то check_output() выбросит исключение (не следует неявно ошибки игнорировать).
Начиная с простого случая существует множество вариаций. К примеру, чтобы получить объединённый вывод как из стандартного потока команды (stdout) так и из потока ошибок (stderr), можно передать stderr=subprocess.STDOUT параметр в check_output(). Дочерний процесс может вообще напрямую в терминал писать в обход своих stdout/stderr, в этом случае на POSIX системах можно pty создать, чтобы перехватить вывод (в таких случаях удобно pexpect модуль использовать).
По умолчанию вывод возвращается в виде байт, чтобы получить текст необходимо указать кодировку символов, которая может зависеть от выбранной команды:
text = subprocess.check_output(['программа', 'аргумент 1', '2'], encoding=encoding)

Подробнее см. Byte при печати вывода внешней команды.
Стоит упомянуть, что в отличии от старых интерфейсов, унаследованных из Си (таких как system(), popen()), функции в subprocess модуле никогда не запускают командную оболочку, если явно об этом не попросить. Что позволяет избежать shell injection и делает вызов более переносимым (если сама программа переносима).

A: При накоплении целой кучи батников, для записи разных стримов, пришла в голову идея, автоматизировать процесс контроля за работой этих батников. Скрипт, который будет контролировать запуск и перезапуск в случае краша, мониторинг работоспособности, добавления новых стримов и оповещать в случае изменений, либо ошибок в любом из батников. Теперь собственно для чего был задан вопрос. ffmpeg иногда ругается на прямые ссылки на стримы, поэтому предварительно их нужно обрабатывать с помощью youtube-dl. Можно конечно писать все стримы youtube-dl, а потом разбивать готовые файлы на части, но они будут недоступны для просмотра во время записи.
# _*_coding: utf-8 _*_
import os, time, subprocess, re
from mylib import get_current_date_time, get_file_name, send_mail
from config import EXIT_CODES, STREAMS_LIST

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FFMPEG_PATH = os.path.join(BASE_DIR, 'ffmpeg\\bin', 'ffmpeg.exe')
YOUTDL_PATH = os.path.join(BASE_DIR, 'youtube-dl', 'youtube-dl.exe')
DEST_DIR = r'D:\test_dir'

if __name__ =='__main__':

    video_link = 'https://www.youtube.com/watch?v=GiBK0z6Zdf4'
    dirty_link= subprocess.check_output('{0} -f "bestvideo[height<=480]+bestaudio/best[height<=480]" -i "{1}" -g'.format(YOUTDL_PATH, video_link))
    flink_compr = re.compile(r'http.*\\n')
    FILE_NAME = get_file_name()
    out_file = os.path.join(DEST_DIR, FILE_NAME)
    dl_link = link_pattern.findall(str(dirty_link))[0].rstrip()
    command = '{0} -i "{1}" -c:v copy -vsync 1 -acodec mp2 -ac 2 -ab 128k -ar 44100 "{2}.ts"'.format(FFMPEG_PATH, dl_link, out_file)
    os.system(command)

UPD. Это кусочек тестового примера, через subprocess. Пример с os.popen, также работает. Но я решил уйти от батников, буду пытаться запустить несколько потоков. Удачи мне, вам всем огромнейшая благодарность )))

A: Вот так можно довольно просто получить результат выполнения как кортеж, код завершения и потоки вывода (стандартный и ошибок):
import subprocess

out = subprocess.getstatusoutput('xxx')
print(out)
(127, '/bin/sh: xxx: command not found')

A: Можно так
>>> from subprocess import Popen, PIPE
>>> stdout = Popen('echo abc', shell=True, stdout=PIPE).stdout
>>> output = stdout.read()
>>> output
b'abc\n'


text:
Q: How to return a value in asyncronous xhr request? How would I return loadFile.responseText as the return value in xhr() function where loadFile.Open is set to true (async)... When I set the request as synchronous (false), the value is returned. I do understand why this happens but I am wondering if there is a way to accomplish this with asynchronous settings.
loadFile.open("GET", url, true); // no response

Whole function:
function xhr(url, async){

    var data = '';

    var loadFile = new XMLHttpRequest();

        loadFile.overrideMimeType("application/json");

        loadFile.open("GET", url, false); // when true, no value is returned (of course)

        loadFile.onreadystatechange = function() {

            if (loadFile.readyState === 4 && loadFile.status == "200")
            {
                data = JSON.parse( loadFile.responseText );

                return data;
            }
        }

        loadFile.send(null);

    return loadFile.onreadystatechange();
}

I was looking for an answer to this and found this How do I return the response from an asynchronous call? and it is NOT a duplicate.
I don't mind entirely changing the direction if it is required. Can you help with an actual basic example or a solid suggestion of which way to go to accomplish that?

A: I am going to answer this then close this as a duplicate. This answer is purely a clarification for your SPECIFIC problem. The real answer is to read and understand the duplicate.
Here I'm going to copy and paste the relevant portion from the duplicate answer:

 var result = foo();
 // Code that depends on 'result'

becomes
 foo(function(result) {
     // Code that depends on 'result'
 });

So your code should be restructured as:
function xhr(url, callback){

    var data = '';

    var loadFile = new XMLHttpRequest();

        loadFile.overrideMimeType("application/json");

        loadFile.open("GET", url, false); // when true, no value is returned (of course)

        loadFile.onreadystatechange = function() {

            if (loadFile.readyState === 4 && loadFile.status == "200")
            {
                data = JSON.parse( loadFile.responseText );

                callback(data); //// NOTE: this is how you return the value
            }
        }

        loadFile.send(null);

    loadFile.onreadystatechange();
}

And how to use the returned result:
xhr(some_url, function (result) {
    // use result here

    // NO, it's not possible to get result outside this function
    // If you really want you can pass it further to other functions:

    do_something_with(result);

    // but you can NEVER return it
});

Basically you need to restructure your code and get used to callbacks.
There are fancier ways to do callbacks like promises and with newer versions of js async/await (which returns promises) but they're all callbacks nonetheless.


text:
Q: Object locks instance member to synchronize access to it Is it neccessary to create a placeholder lock object to for thread-safety (and correctness) or is it sufficient to lock on the resource itself (assuming no other code will need it).
locking a System.Random
private static readonly Random rnd = new Random();
public static int Rand(int min, int max) {
    lock(rnd) {
        return rnd.Next(min, max);
    }
}

using a separate placeholder/dummy lock object
private static readonly Random rnd = new Random();
private static readonly object rndLock = new object()
public static int Rand(int min, int max) {
    lock(rndLock) {
        return rnd.Next(min, max);
    }
}

this may seem trivial but i'm concerned with if the first code-block is susceptible to deadlock or other issues

A: The reason we avoid locking the object itself, is to avoid the situation where a lock is taken inadvertently, if the "object itself" is publicly exposed.  If you are only using the "object itself" inside a private class or method, there is no harm in using the method you propose.


text:
Q: QTP fails to recognize Java-applet Jtree object when used with Regular Expression I am using QTP for automating an application. QTP recognizes Java applet- JTree as a html tag. In the html tag we have a number which is dynamic.
Hence we used Regular Expression so that QTP  recognizes the object even if the number changes. But QTP is failing to do so. We have tested the regular expression in the evaluator and it works highlights the correct number as expected.
The expression in Obj Repository matches with the one in the Expert view.
Reg expressions do not work with html tags/applets is it??
Is there any other way to deal with dynamic elements in html tags??
Thanks in advance.

A: Try using descriptive programming it may help you. If you could provide more details of the issue then i could send you code snippet.

A: You should try UFT that is the next generation of QTP.
If you have a QTP-Licence you can update to UFT and I guess it will work well.
On the other hand how long will QTP will be supported


text:
Q: how to use custom pointers in osmdroid? I am using OSMDroid and this code gives default markers to point my location. How do i put custom markers in place of the default markers? How do i import a new drawable?
anotherOverlayItemArray = new ArrayList<OverlayItem>();
anotherOverlayItemArray.add(new OverlayItem("KTM2", "KTM2", myLocation));
 ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = new
          ItemizedIconOverlay<OverlayItem>( this, anotherOverlayItemArray,myOnItemGestureListener);

      mapView.getOverlays().clear();
      mapView.getOverlays().add(anotherItemizedIconOverlay);
      mapView.invalidate();

A: You can set a specific marker to each OverlayItem:
OverlayItem item = new OverlayItem("KTM2", "KTM2", myLocation);
Drawable myMarker = getResources().getDrawable(markerResId);
item.setMarker(myMarker);
anotherOverlayItemArray.add(item);

You can also get rid of the ItemizedIconOverlay/OverlayItem approach by using the OSMBonusPack Marker.


text:
Q: Owl Carousel - Auto Height mobile issue This is the page in question: http://k2ld.91dev.com.au/project/balwyn-residence/
The carousel uses autoheight:true.
On certain mobile browsers including Dolphin, iPhone, Google Nexus 4 (when viewed in Chrome Dev Tools), the .owl-wrapper-outer container will have a small inline height applied which crops the first image.
Once you swipe to the left and back the height is recalculated and all is fine.
My Owl code looks like this (inside a document.ready):
// Owl Slider
$(".owl-carousel").owlCarousel({
    items: 1,
    loop: true,
    autoHeight: true
});

I originally used Owl Carousel 1 and then switched to version 2 to see if the issue went away... it didn't.
How can I get the carousel to calculate it's height once the images are fully loaded?

A: I created a script manually using some owl properties, make the creation of a function to create the carousel, it takes the individual height of each element, and arrow for the element of each item. With this we can adjust the height of the carousel at any resolution.
In your case, you would do the following:
$(".owl-carousel").owlCarousel({
    items: 1,
    loop: true,
    afterAction : afterAction
});

function afterAction() {
    var elem = this.owl.owlItems;
    var index = this.owl.visibleItems;

    var height = elem.eq(index).height();

    //.owl-wrapper is the element that we are high.
    elem.parents('.owl-wrapper, .owl-carousel').css('height', height);
}

I hope this helps!

A: I've ended up changing sliders to BX Slider which offers similar functionality.

A: use imagesLoaded
jQuery(document).ready(function () {
        jQuery('#div_id').imagesLoaded(function () {
            jQuery('#div_id .scroll-box').owlCarousel({
                items: 1,
                nav: false,
                pagination: false,
                autoHeight: true,
                loop: true,
                lazyLoad: true,
                animateOut: 'slideOutRight',
                animateIn: 'pulse'
            });
        });
    });


text:
Q: Periodically edit a Rails database from a gem I have been working with and learning Rails for a few months and have recently taken up a project that calls for a gem that will periodically pull data from another site and compile it into a database friendly format.
I have the ruby code to do the pulling, editing, and formatting. My question is how to get the gem to edit the database for the Rails app that will be built by inserting the data. What I want is to have a few models based off the data being mined by the gem.
Some background info on the app. The app will be a stats reporting app for sports. So the models that are based on the data mined will be Stats, Players, Teams, and Games. There will be other models in the application as well, such as Devise users and others.
Once again, I have made the ruby code that will pull the data using 'json' and 'nokogiri' gems and will put them into (a lot of) hashes. I just have no idea how to store them in a database usable by a Rails app. Or any database for that matter. The only information I could turn up had to do with Engines and Railtie but there were no thorough explanations.
Thanks for the help.


text:
Q: Cannot add Style to Resourcedictionary I'm getting following error when try to add style to Resourcedictionary.
cannot add content of type 'system.windows.style' to an object of type 'system.windows.resourcedictionary'

A: This is due duplicate keys. Finaly found another style added with same key.


text:
Q: TVP vs loop for each parameter I am in a situation where I need to do some comparison for some products that are in a shopping cart. The cart can have as many items as the user desires but the average over time is roughly 5-15 items per cart.
My question is one about optimization/overhead. I need to check what department each product is in and determine the shipping charge. The department for each product isn't directly related to the product (i.e. there isn't a department id column in the product definition table) but I can query and get the department id based on the product id.
This is where my question is. Would it be better (less overhead/faster) to pass in a list of id's to a stored procedure and use the list in the stored procedure with something like table valued parameter to query the existing table? Or would it be faster to just query the products 1 at a time (assuming the aver cart size is on the high end of 5-15), get the department id, and then go onto the next item?
I have never used TVP and I am trying to learn from some other questions posted on stack overflow and the msdn site. So before I spend to much time trying to get the results I want I am posing this question.

A: Generally the TVP should be faster (and easer to make it faster if you need it).  The larger the list, the more favorable TVP's should be versus one query per ID.
It's a bit more development work to set things up to use a TVP, so if you'll never have more than a small list (say 3 or less), then it may not be worth it, but otherwise it's definitely a better approach.


text:
Q: concurrencyLevel in ConcurrentHashMap What will be the concurrencyLevel if ConcurrentHashMap size increased?
Suppose initial capacity of ConcurrentHashMap  is 16. and default concurrencyLevel will 16. If capacity increased by load factor after some time and now increased capacity is 28. What will be the concurrencyLevel in this case?
Gone through with these links as well
Segmentation in ConcurrentHashMap and Modifying values in ConcurrentHashMap but still not clear.
Thanks in advance.

A: There is no reason to think upon reading the documentation that concurrency level can ever change.  It remains what it is set to during object creation.
When in doubt, browse the source code:
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/43cb25339b55/src/share/classes/java/util/concurrent/ConcurrentHashMap.java
it seems that currently all it does is raises the number of bins if initial capacity is less than specified concurrency level.


text:
Q: Writing to a file then trying to open it again for parsing I'm trying to save the xml feed of a twitter user to a file and then try to read it again for parsing onto the screen.
This s what I see hen I try to run it..
    Wrote to file #<File:0x000001019257c8>
Now parsing user info..
twitter_stats.rb:20:in `<main>': undefined method `read' for "keva161.txt":String (NoMethodError)

Here's my code...
require "open-uri"
require "rubygems"
require "crack"

twitter_url = "http://api.twitter.com/1/statuses/user_timeline.xml?cout=100&screen_name="
username = "keva161"
full_page = twitter_url + username
local_file = username + ".txt"

tweets = open(full_page).read

my_local_file = open(local_file, "w")
  my_local_file.write(tweets)

puts "Wrote to file " + my_local_file.to_s
sleep(1)
puts "Now parsing user info.."
sleep(1)

parsed_xml = Crack::XML.parse(local_file.read)

tweets = parsed_xml["statuses"]

first_tweet = tweets[0]
user = first_tweets["user"]

puts user["screen_name"]
puts user ["name"]
puts users ["created_at"]
puts users ["statuses_count"]

A: You are calling read on local_file, which is the string containing the filename.  You meant to type my_local_file.read, I guess, to use the IO object you got from open.  (...or File.read local_file.)
Not that this is the best form: why are you writing to a temporary file anyhow?  You have the data in memory, so just pass it directly.
If you do want to write to a local file, I commend the block from of open:
open(local_file, 'w') do |fh|
  fh.print ...
end

That way Ruby will take care of closing the file for you and all that.


text:
Q: Issue with RDD of Custom Objects in Spark I am passing a type into a flatmap like so;
 val customData: RDD[(Text/String, Custom)] = origRDD.flatMap { case(x) => parse(x)}

this returns a key value pair of String and Custom(I have used Text in place on String as well to no avail, that is the explanation of 'Text/String'). This class extends Serializable and is registered in Kryo.
When I try to run the program it just runs and never ends. By never ends I mean I have left it running for 18 hrs and it did not finish. If I change it to Text(hadoop io) with an Int (counter) instead of the custom object it finishes very quickly. When I say quickly I mean 30 mins. The data it is running through is the same data and parse(as well as flatmap) method is used in both so it is running through the exact same logic. The method it uses in the flatmap is the same parse method. The behavior declines when I change it to (Text/String, Custom) from (Text, Int).
I would like to know what do I need to add to make this work. Does it need to be a Writable?
Example of Custom object class implementation(obviously not the exact but mimics it very well);
class Custom(dateAsLong: java.lang.Long, typeOfTransaction: util.HashSet[java.lang.Long], isCustomer: Boolean, amount: String, customerMatch: ObjectMatch) extends Serializable {
//has getters and setters here

 val startDate = dateAsLong
 val transType = typeOfTransaction
 val customer = isCustomer
 val cost = amount
 val matchedData = customerMatch

 def getStartDate(): java.lang.Long = startDate
 def getTransType(): util.HashSet[java.lang.Long] = transType
 def getCustomer(): Boolean = customer
 def getCost(): String = amount
 def getMatchedData(): ObjectMatch = matchedData
}

Example of the parse method inside of a object that extends java Serializable;
object Paser extends Serializable {
    def parse(transaction: Transaction, customerList: util.HashMap[String, String], storeList: util.HashMap[String, String]): List[(Text, Custom)] ={ //list because flatmap emits 0, 1 or 2
//adds items to the list depending on conditions
    var list:List[(Text, Custom)] = List()
    val typeOfTransaction = getType(transaction)
    val dateAsLong = getDate(transaction)
    val amount = getAmount(transaction)
    val customerMatch = getCustomerMatch(transaction, customerList)
    val storeMatch = getStoreMatch(transaction, storeList)
     //more fields parsed

    if (customerMatch != Some(null)){
       isCustomer = true
       val transaction: Custom = getTransaction(dateAsLong, typeOfTransaction,      isCustomer, amount, customerMatch)
       val transactionId = hash(transaction.getCustomer(), transaction.getTransType(), transaction.getMatchedData().getItem())
       list = list :+ (new Text(transactionId), transaction)

    }
    if (storeMatch != Some(null)){
       isCustomer = false
       val transaction: Custom = getTransaction(dateAsLong, typeOfTransaction,      isCustomer, typeOfTransaction, storeMatch)
       val transactionId = hash(transaction.getCustomer(), transaction.getTransType(), transaction.getMatchedData().getItem())
       list = list :+ (new Text(transactionId), transaction)
    }
  }
 list
}

Kryo Serialization is like so;
 conf.registerKryoClasses(Array(classOf[Custom]))

Any help is appreciated with code examples or links to example.
Spark UI for (Text/String, Custom) run

Bottom progress with 1/11 task is the flatmap, Top is saveAsNewHadoopAPIFile
The flatmap stage 0 is saveAsNewHadoopAPIFile -> filter x7 -> flatmap

Run with (Text, Int)

The slow run (Text/String, Custom) run says 1.1h, however I have let it run 18hrs. When it runs for 18hrs it progresses slowly through, however it is not ideal to let it run a day. There is something wrong, very wrong. Again the parse method is used in both so it is running through the exact same logic even though the faster run is not outputting the custom value, instead it outputs the keys Text and int.
Not sure if this is helpful but whatever is wrong is causing the scanning in the Accumulo to appear different as well. The Text, Int run has a normal increase in scans stays at relatively the same scans/s for the 30 mins then drops. When I run with the custom it increase then immediately drops down. in a ^ like fashion then drags on at a lower scan rate for hours.
Spark Version: 1.6.2, Scala 2.11

A: You should not use var list:List[(Text, Custom)] = List().  Every execution of the code list = list :+ (new Text(transactionId), transaction) creates a new list (it is not just adding to the existing List).  List in Scala is immutable.  You should replace it with val myListBuffer = ListBuffer[(Text, Custom)]().  I am not sure if that is the only problem - but this change should help if your list is huge.
Also, a couple of comments on writing code in Scala - there is no need to have getters and setters in a Scala class.  All the members are immutable anyway.  You need to think really hard before you use a var in Scala.  The immutability will make your code resilient, improve readability, and easier to change.


text:
Q: selected item value from Bootstrap DropDown with specific ID I have a bootstrap dropdown generated on a page and javascript onclick to capture change and send a POST resuest to the server.
The value inside 'a' is the playlist id, which expected by server
my selectvalue inside JS is always 0. how to retrive the value inside a?

    <button class="btn btn-default dropdown-toggle" type="button" id="btnchanneldropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
      Select Playlist
    </button>

Play List 01

Play List 02

Play List 03

Jscript
$(document).ready(function(){
$('#ulchanneldropdown').on('click', 'li a',function(){

var selectvalue = $(this).data('value');

$.post('functions/playlist_table1.php', { value: inputValue },function(data,status){
  var targetDiv = document.getElementById('playlist_here');
  targetDiv.innerHTML = data;
      });
    });
   });

A: You have to use attr() instead of data() :
var inputValue = $(this).attr('value');

data("value") is used to get data-value="test" attribute.
And as pointed by @u_mulder, you have to change selectvalue to inputValue, or change into your { value: inputValue } to { value: selectvalue }.


text:
Q: IdentityServer 4 and TLS 1.2 I have disabled TLS 1.0 and TLS 1.1. in Identity Server (v4 running in a Service Fabric Cluster using WebHostBuilder, targeting .NET 4.6.2 using a self-signed cert). I have added the following in Startup.cs:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

And I receive the following error:
System.InvalidOperationException: IDX10803: Unable to create to obtain
configuration from: 'https://services.mytest.com:8443/oauth/.well-
known/openid-configuration'. ---> System.IO.IOException: Unable to get
document from: https://services.mytest.com:8443/oauth/.well-
known/openid-configuration ---> System.Net.Http.HttpRequestException: An
error occurred while sending the request. ---> System.Net.WebException: The
underlying connection was closed: An unexpected error occurred on a receive.
---> System.ComponentModel.Win32Exception: The client and server cannot
communicate, because they do not possess a common algorithm

I've looked at the questions here:
IDX10803: Unable to create to obtain configuration
Unable to obtain configuration from well-known/openid-configuration
I've tried the suggestions (including adding the cert to trusted root)

A: I don't know much about that particular piece of software but the problem here is not that the certificate is not trusted (according to the error message) but your server and client try to negotiate during TLS handshake which protocol version, cryptographic ciphers and keyexchange mechanism should be used. It would seem that the client and server have now become incompatible. Either change the client or the server.
See also for an related and post with a possible solution:
The client and server cannot communicate, because they do not possess a common algorithm


text:
Q: Matlab - Matching nominal values to numeric values for a bar plot? I have 2 variables, one is USA/Non-USA (origin of 35 cars), the second is horsepower (of 35 cars).
I need to create a bar and errorbar plot for the mean horsepower of each option of the first variable, so 2 bars of the mean horsepowes.
The bar function will not pair nominal values to numeric ones.
Thanks in advance for the help, I just started Matlab and am a bit lost!

A: Assuming your usa indicator is denoted by a binary (1 for usa, 0 for non-use), you can use the following. You can then aggregate the classes using accumarray. Then you can plot using bar.
% Initialize Toy Data
usa = [0 0 1 1]';
hp = [5 15 10 20]';

% Grab Unique Classes
[u,~,c] = unique( usa );

% Aggregate By Unique Classes, m is the mean for each class
m = accumarray( c, hp, size(u), @(x) mean(x) );

% Plot bar graph
bar(u,m)

I'm not sure what error plot you're referring to, please clarify. You can use this data for any plot.


text:
Q: Total number of strings constructed by a set of $N$ characters. Let $S=\{s_1,\ldots,s_N\}$ be a set of $N$ characters. What is the total number of strings that could be constructed using elements of the above set, granted that strings may be of length at least $1$ and each character is used only once?
For instance, for $N=2$, i.e., $S=\{s_1,s_2\}$, the number of all possible strings is equal to $4$. That is, these strings are the following: $s_1$, $s_2$, $s_1s_2$, and $s_2s_1$. If I am not mistaken, for $N=3$, this number is equal to $15$.
How could I compute this number analytically for an arbitrary choice of $N$? I am a bit stuck on this, so thank you very much for any help in advance!

A: Using the expression $\operatorname{T}(n)=\sum_{k=1}^n k!{n \choose k}$ provided by HowDoIMath above, we can rewrite it as a recursive function:
\begin{split}
\operatorname{T}(n+1) &= \sum_{k=1}^{n+1} k!{n+1 \choose k} = \sum_{k=0}^n (k+1)!{n+1 \choose k+1} =
\sum_{k=0}^n (k+1)!\frac{(n+1)!}{(k+1)!(n+1-k-1)!} \\
&= (n+1)\sum_{k=0}^n k!\frac{n!}{k!(n-k)!} = (n+1)\sum_{k=0}^n k!{n \choose k} = \\
&= (n+1)\sum_{k=1}^n k!{n \choose k} +(n+1) = (n+1)\operatorname{T}(n) + (n+1).
\end{split}
The recurrence equation $\operatorname{T}(n)=n \operatorname{T}(n-1)+n$, with $\operatorname{T}(1)=1$, has solution
$$
\operatorname{T}(n)=e\cdot n\cdot\Gamma(n,1),
$$
Where $\Gamma$ is the upper incomplete gamma function. I found this solution by messing around in Mathematica, but once you have it, it is easy enough to prove that is the solution, by showing that it satisfies the recurrence relation, using integration by parts, and testing the initial value.
Now
\begin{split}
\Gamma(n,1) &= \int_1^\infty t^{n-1}e^{-t}dt=\int_0^\infty t^{n-1}e^{-t}dt -\int_0^1 t^{n-1}e^{-t}dt \\
&= \Gamma(n,0)-\int_0^1 t^{n-1}e^{-t}dt = (n-1)!-\int_0^1 t^{n-1}e^{-t}dt,
\end{split}
using that $\Gamma(n,0)$ is the usual gamma function $\Gamma(n)$. So we arrive at
$$
\operatorname{T}(N)=e\cdot N!-e\cdot N\int_0^1 t^{N-1}e^{-t}dt.
$$
We still have to prove that this is equal to $\lfloor e\cdot N!-1 \rfloor$, as mentioned again by HowDoIMath, but at least it's part of the way!

A: I'll show that HowDoIMath's answer $T(n)$ is equivalent to $\lfloor e\cdot n!-1\rfloor$.
Rewrite $T(n)$ as $n!\binom{n}0+(n-1)!\binom{n}1+(n-2)!\binom{n}2+\ldots+(n-(n-1))!\binom{n}{n-1}$.
Divide by $n!$ to get: $$T(n)=n!(\tbinom{n}0+\tfrac1n\tbinom{n}1+\tfrac1{n(n-1)}\tbinom{n}2+\ldots+\tfrac1{n(n-1)\ldots2}\tbinom{n}{n-1})$$
$$\therefore\ T(n)=n!(1+1+\tfrac1{2!}+\tfrac1{3!}+\ldots+\tfrac1{(n-1)!})$$
Thus $T(n)=n!(e-\tfrac1{n!}-f(n))$ where $f(n)=\tfrac1{(n+1)!}+\tfrac1{(n+2)!}+\tfrac1{(n+3)!}+\ldots$
Expanding, $T(n)=e\cdot n!-1-n!f(n)$.
We already know that this is an integer, so all that remains is to show that $n!f(n)<1$.
$$n!f(n)=\tfrac1{n+1}+\tfrac1{(n+1)(n+2)}+\tfrac1{(n+1)(n+2)(n+3)}+\ldots$$
But $$e-2=\tfrac12+\tfrac1{2\cdot3}+\tfrac1{2\cdot3\cdot4}+\ldots<1$$
By the comparison test, for $n>1$ each term of $n!f(n)$ is smaller than the corresponding term in $e-2$. Therefore the series converges, and is less than $1$.

A: Sloane has the sequence: https://oeis.org/A007526
He provides this amazing looking closed form for the general expression:
$\lfloor e\cdot N!-1\rfloor$
I haven't checked it, and have no idea why it is true, but I believe I saw something similar for derangements at some point.


text:
Q: pdfjs in Android WebView crashes on scroll i've added pdf.js to my Android Project (Visual Studio 2015, Xamarin), to display a pdf in a WebView Component. With the following Cod loads an example pdf.
        WebView wv = FindViewById<WebView>(Resource.Id.webView1);
        wv.SetWebChromeClient(new WebChromeClient());
        wv.Settings.JavaScriptEnabled = true;
        wv.Settings.AllowUniversalAccessFromFileURLs = true;
        wv.LoadUrl("file:///android_asset/pdfviewer/viewer.html?file=http://www.orimi.com/pdf-test.pdf");

But as soon as i try to scroll down the pdf, the whole app crashes. The following lines are from the debug log.

Loaded assembly: System.dll [External]
  Der Thread 'Unknown' (0x2) hat mit Code 0 (0x0) geendet.
  01-08 11:41:48.763 W/cr.BindingManager( 5994): Cannot call determinedVisibility() - never saw a connection for the pid: 5994
  [INFO:CONSOLE(0)] "The provided value 'moz-chunked-arraybuffer' is not a valid enum value of type XMLHttpRequestResponseType.", source:  (0)
  01-08 11:41:49.359 I/chromium( 5994): [INFO:CONSOLE(0)] "The provided value 'moz-chunked-arraybuffer' is not a valid enum value of type XMLHttpRequestResponseType.", source:  (0)
  [INFO:CONSOLE(946)] "Uncaught (in promise) TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (946)
  01-08 11:41:49.540 I/chromium( 5994): [INFO:CONSOLE(946)] "Uncaught (in promise) TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (946)
  [INFO:CONSOLE(0)] "Handler added to rejected promise", source: file:///android_asset/pdfviewer/viewer.html?file=http://www.orimi.com/pdf-test.pdf (0)
  01-08 11:41:49.565 W/cr.BindingManager( 5994): Cannot call determinedVisibility() - never saw a connection for the pid: 5994
  01-08 11:41:49.565 I/chromium( 5994): [INFO:CONSOLE(0)] "Handler added to rejected promise", source: file:///android_asset/pdfviewer/viewer.html?file=http://www.orimi.com/pdf-test.pdf (0)
  [INFO:CONSOLE(7007)] "TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (7007)
  01-08 11:41:49.566 I/chromium( 5994): [INFO:CONSOLE(7007)] "TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (7007)
  [INFO:CONSOLE(946)] "Uncaught (in promise) TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (946)
  01-08 11:41:49.607 I/chromium( 5994): [INFO:CONSOLE(946)] "Uncaught (in promise) TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (946)
  [INFO:CONSOLE(7104)] "PDF c21f21ea44c1e2ed2581435fa5a2dcce [1.6 Acrobat Distiller 7.0.5 (Windows) / Acrobat PDFMaker 7.0.7 for Word] (PDF.js: 1.2.109)", source: file:///android_asset/pdfviewer/viewer.js (7104)
  01-08 11:41:49.607 I/chromium( 5994): [INFO:CONSOLE(7104)] "PDF c21f21ea44c1e2ed2581435fa5a2dcce [1.6 Acrobat Distiller 7.0.5 (Windows) / Acrobat PDFMaker 7.0.7 for Word] (PDF.js: 1.2.109)", source: file:///android_asset/pdfviewer/viewer.js (7104)
  [INFO:CONSOLE(946)] "Uncaught (in promise) TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (946)
  01-08 11:41:49.667 I/chromium( 5994): [INFO:CONSOLE(946)] "Uncaught (in promise) TypeError: Cannot read property 'getItem' of null", source: file:///android_asset/pdfviewer/viewer.js (946)

This is a snippet from the viewer.js function (Line 946)
    _readFromStorage: function ViewHistory_readFromStorage() {
  return new Promise(function (resolve) {
    resolve(localStorage.getItem('database')); (Line 946)
  });
},

Does anyone has an idea ?

A: This seems to be an Android issue.Try enabling the DOM storage.
wv.Settings.DomStorageEnabled = true;

https://developer.xamarin.com/api/property/Android.Webkit.WebSettings.DomStorageEnabled/


text:
Q: Followed instructions on php.net and still cannot get mysqli extension to work I uncommented this line in the php.ini file: extension=php_mysqli.dll
and my extension is "extension_dir = "ext"".
The php_mysqli.dll does exist in the ext folder.
I am using php 5.5+ so I should not have to manually set the path for libmysql.dll.
Running mysqli_connect yields a fatal error.
I do not understand why this does not work. When I did this with my php_sqlsrv_55_ts.dll file, I was able to connect to sql server immediately. I do not see anything I missed in these installation instructions:
http://www.php.net//manual/en/mysqli.installation.php
Where do I go from here?

Windows 7
apache 2.4
php 5.5.9
No instance of mysql in this machine.


text:
Q: MongoDB, NodeJS: updating an embedded document with new members Using: MongoDB and native nodeJS mongoDB driver.
I'm trying to parse all the data from fb graph api, send it to my API and then save it to my DB.
PUT handling in my server:
    //Update user's data
app.put('/api/users/:fbuser_id/:category', function(req, res) {
    var body = JSON.stringify(req.body);
    var rep = /"data":/;
    body = body.replace(rep, '"' + req.params.category + '"' + ':');
    req.body = JSON.parse(body);
    db.fbusers.update({
            id: req.params.fbuser_id
        }, {
            $set: req.body
        }, {
            safe: true,
            multi: false
        },
        function(e, result) {
            if (e) return next(e)
            res.send((result === 1) ? {
                msg: 'success'
            } : {
                msg: 'error'
            })
        });
});

I'm sending 25 elements at a time, and this code just overrides instead of updating the document.
Data I'm sending to the API:
    {
  "data": [
    {
      "category": "App page",
      "name": "SoundCloud",
      "id": "7919071058",
      "created_time": "2013-09-16T18:16:59+0000"
    },
    {
      ...and so on
    }
    ]
    }

Basically my API changes "data" key from sent json to the category name, f.e.:
PUT to /api/users/000/likes will change the "data" key to "likes":
    {
  "likes": [
    {
      "category": "App page",
      "name": "SoundCloud",
      "id": "7919071058",
      "created_time": "2013-09-16T18:16:59+0000"
    },
    {
      ...and so on
    }
    ]
    }

Then this JSON is put to the db.
Hierarchy in mongodb:
        {
        "_id": ObjectID("556584c8e908f0042836edce"),
        "id": "0000000000000",
        "email": "XXXX@gmail.com",
        "first_name": "XXXXXXXX",
        "gender": "male",
        "last_name": "XXXXXXXXXX",
        "link": "https://www.facebook.com/app_scoped_user_id/0000000000000/",
        "locale": "en_US",
        "name": "XXXXXXXXXX XXXXXXXXXX",
        "timezone": 3,
        "updated_time": "2015-05-26T18:11:59+0000",
        "verified": true,
        "likes": [
            {
                "category": "App page",
                "name": "SoundCloud",
                "id": "7919071058",
                "created_time": "2013-09-16T18:16:59+0000"
            },
            {
                "category": "App page",
                "name": "SoundCloud",
                "id": "7919071058",
                "created_time": "2013-09-16T18:16:59+0000"
            },
            {
               ....and so on
            }
            ]
        }

So the problem is that my api overrides the field (in this case "likes") with newly sent data, instead of appending it to already existing data document.
I am pretty sure that I should be using other parameter than "$put" in the update, however, I have no idea which one and how to pass parameters to it programatically.

A: Use $push with the $each modifier to append multiple values to the array field.
var newLikes = [
  {/* new item here */},
  {/* new item here */},
  {/* new item here */},
];

db.fbusers.update(
  { _id: req.params.fbuser_id },
  { $push: { likes: { $each: newLikes } } }
);

See also the $addToSet operator, it adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.


text:
Q: MVC - Identity in a separate project - web references needed - why? I am trying to decouple the Identity model logic from an MVC project, as it appears in the standard template with Individual Identity.
I have created a class library and copied over the IdentityModels.cs file.
But as I am adding NuGet packages such as Microsoft.AspNet.Identity.EntityFramework to solve the missing references problems, the references list gets filled up with dlls that sound like web libraries, e.g. MS.Owin.Security.Cookies, Newtonsoft.Json, etc. Also, the IdentityModels.cs uses IdentityDbContext, which is contained in MS.AspNet.Identity.EntityFramework.
My question is: is it possible to completely remove the web-related dlls from the models project to make it "pure" models and business logic, (i.e. to have no references to cookies or Json or aspnet) or is the Identity Framework so tightly integrated with UI and browsers that it is best to leave it inside the MVC project?


text:
Q: Save a result containing HoldForm to a file This is the workflow I have. Basically, I want the outputs of the polynomials I computed are in a specific order. (It is not the same one here, this is just an example.).
f[1] = 1;
f[2] = x;
f[3] = x + y;
f[n_] := Expand[f[n - 1]*(x + 2 y - 3)]

f[4]

-3 x + x^2 - 3 y + 3 x y + 2 y^2

monomials = MonomialList[f[4]]

{x^2, 3 x y, -3 x, 2 y^2, -3 y}

First /@ CoefficientRules[f[4]]

{{2, 0}, {1, 1}, {1, 0}, {0, 2}, {0, 1}}

Sort@(First /@ CoefficientRules[f[4]])

{{0, 1}, {0, 2}, {1, 0}, {1, 1}, {2, 0}}

permutation = Ordering[First /@ CoefficientRules[f[4]]]

{5, 4, 3, 2, 1}

SortedMonomials = monomials[[permutation]]

{-3 y, 2 y^2, -3 x, 3 x y, x^2}

result=Plus @@@ HoldForm[Evaluate[SortedMonomials]]

-3 y+2 y^2-3 x+3 x y+x^2

But when I use Save to save the last result above, it will be result = HoldForm[-3*y + 2*y^2 - 3*x + 3*x*y + x^2] in the saved .txt file.
I want the content in the file to be result = -3*y + 2*y^2 - 3*x + 3*x*y + x^2.
Is there any way to achieve my requirement, only use MMA?

A: Is there some reason you are avoiding SetDelayed?  That will work like this:
x = "Fail!";
test := y + x

Save["foo.m", test]
FilePrint["foo.m"]

test := y + x

x = "Fail!"

If for some reason that won't work you can use Unevaluated:
Remove[x, y, test]

y = "Fail!";
test = Unevaluated[y + x];

Save["bar.m", test]
FilePrint["bar.m"]

test = y + x

y = "Fail!"

A: Since you are saving to a text file, how about convert to string first, for example:
pl = ToString[#] &[HoldForm[test = x + y]]; Save["file.txt", pl]

A: One can use Block to prevent Plus from evaluating until after result is defined.
SortedMonomials = {-3 y, 2 y^2, -3 x, 3 x y, x^2};

Block[{Plus},
 result = Plus @@ SortedMonomials;
 ]

Save["/tmp/foo.txt", result]

FilePrint["/tmp/foo.txt"]

result = -3*y + 2*y^2 - 3*x + 3*x*y + x^2

A: Assuming you have values for x and y defined, hence the need for HoldForm:
x = 1;
y = 2;

Block[{x, y},
 test = y + x;
 Save["file.txt", test]]


text:
Q: Novel with solar sail technology and gorilla-like aliens This book had solar sail technology and gorilla-like aliens with one strong muscular arm and one weak arm.

A: "Mote In God's Eye" by Larry Niven and Jerry Pournelle.
What do I win? :)


text:
Q: Request returns hidden characters I am using requests.get to read a JSON object.  The string downloaded is just a URL to download.  I try to feed it in using requests.get(), but I get a 404 error.  However, when I hardcode the value and run a requests.get(), I get a 200 response.  Here is the pseudocode:
response = requests.get(repository, headers=headers, data=data)
pod_map = json.loads(response.text)['locationMap']
for key in pod_map.keys():
   url = pod_map["key"] #url should be something like http://mylink.com
   response = requests.get(url)
   print response.status_code

The problem is that I when I run the code like this, I get a 404.  However, when I just copy/paste url into a variable, I get a 200.  Is there something I am missing with regards to encoding/decoding the JSON?


text:
Q: Try to mock pure virtual class i' trying to mock a function in a pure virtual class with google mock. Here is my code:
class I_Circle

{

private :

public:

    virtual ~I_Circle() {}

    virtual void GetClone(I_Circle * k) = 0;
};

class Mock_I_Circle : public I_Circle
{
public:
    Mock_I_Circle() {}
    virtual ~Mock_I_Circle() {};

    MOCK_METHOD1(GetClone, void(I_Circle* k));

};

TEST(CircleTest, secondTest) {
    NiceMock<Mock_I_Circle> iCircle;
    Mock_I_Circle* pICircle = &iCircle;

    EXPECT_CALL(iCircle, GetClone(_))
        .WillOnce(
            SetArgPointee<0>(*pICircle)
        );

    iCircle.GetClone(pICircle);

    Mock::VerifyAndClear(&iCircle);
}

With this implementation i'm getting the following error:
Error   C2280   'testing::PolymorphicAction<testing::internal::SetArgumentPointeeAction<0,Mock_I_Circle,false>>::PolymorphicAction(const testing::PolymorphicAction<testing::internal::SetArgumentPointeeAction<0,Mock_I_Circle,false>> &)': attempting to reference a deleted function MockInterface   c:\source\googletest\googlemock\include\gmock\gmock-actions.h   1110

What function here is meant to be deletetd? The problem seems to be result from the EXPECT_CALL with SetArgPointee, but i don't know what's wrong with it.

A: From the Google Mock Cookbook:

SetArgPointee() conveniently makes an internal copy of the value you
  pass to it, removing the need to keep the value in scope and alive.
  The implication however is that the value must have a copy constructor
  and assignment operator.

In your case, the Mock_I_Circle class lacks a copy constructor and assignment operator.  Adding these would fix the compilation error.  That being said, I'm not clear as to the purpose of the test you've written.


text: Q: I downloaded Ubuntu server went through the steps and now it reboots but goes back to the same steps and wont load I downloaded the ubuntu server and went through all the questions. then it rebooted and went back to the same page. i tried again and it keeps doing the same thing. It wont boot into a main page or gui . what did i do wrong?


text:
Q: COM with ATL Versioning My Visual Studio 2008 ATL project has a control that defines a version number in several places.
The IDL file:
uuid(56CD4ADB-B72D-4BF8-B5AC-6CA320EAD27D),
version(1.0),
helpstring("MyProject 1.0 Type Library")

The control's header file:
    class ATL_NO_VTABLE CMyControl :
        public CComObjectRootEx<CComSingleThreadModel>,
        public IDispatchImpl<IMyControl,
             &IID_IMyControl, &LIBID_MyProjectLib,
             /*wMajor =*/ 1, /*wMinor =*/ 0>,
            ...

And an rgs file:
MyCompany.MyProject.MyControl.1 = s 'MyControl Class'

What's the relationship between these version numbers?  When I want to release version 2, do I increment all 3?  And why does the the version in the registry script only have a 1 and not a 1.0?

A: You should check out Larry Osterman's series on COM and the minimial registry.  It should shed a bit of light on what these numbers actually do

*

*http://blogs.msdn.com/larryosterman/archive/2006/01/11/511647.aspx

*http://blogs.msdn.com/larryosterman/archive/2006/01/10/511279.aspx

*http://blogs.msdn.com/larryosterman/archive/2006/01/05/509731.aspx


text:
Q: update facebook status with php/curl I have a page on facebook and i want to be able to update my page when someone post a classifieds ad on my website.
currently the website in on my localhost [wamp] and am testing it from there
i have tried the solutions provided in the following websites but none of them seems to work
http://360percents.com/posts/php-curl-status-update-working-example/
http://www.barattalo.it/2010/03/01/php-curl-bot-to-update-facebook-status/
All am looking for is simple function to update my facebook page as such
Update_status(email,password,status);

A: 1) You need a Facebook app.
2) You then need a long lived access token for your Facebook page.
3) Using that access token you can post to your page. [ You can have a cron job running that checks whether any user has posted any new content, if yes then use the access token to post to page ]


text:
Q: Problems with GStreamer compiled from sources in RHEL8 + GCC12 I'm getting strange results with GStreamer 1.20.3 compiled from sources.
Target platform is RHEL8 with GCC12 (official Docker image was used as the base one).
Python 3.8, Meson and Ninja were installed so compilation/linking passes without any errors.
But when I'm trying to check if all is Ok, I see this:
# ./gst-inspect-1.0

staticelements:  bin: Generic bin
staticelements:  pipeline: Pipeline object

Total count: 4 plugins (1 blacklist entry not shown), 2 features

So the tool does not see any plugins.
GStreamer is compiled like this (I plan to use static library):
...
ENV INSTALL_DIR_GSTREAMER=/app/install/gstreamer

RUN meson setup --prefix=$INSTALL_DIR_GSTREAMER --default-library=static ./build
RUN ninja -C ./build
RUN ninja -C ./build install
...

I saved full log and see only one fatal in it. Not sure that it's a reason of the problem but still:
#29 345.7 Cloning into 'pygobject'...
#29 349.9 HEAD is now at 63825d8e release
#29 350.0 Cloning into 'gobject-introspection'...
#29 351.0 warning: Could not find remote branch master to clone.
#29 351.0 fatal: Remote branch master not found in upstream origin

On checking https://gitlab.gnome.org/GNOME/gobject-introspection I found the main branch which is probably just the new name of master.
But this error is strange enough because I found only one dependency on gobject-introspection in pango and in the .wrap file the branch name for gobject-introspection is specified properly as revision=main.
Also I tried to stream WAV file from Docker with gst-launch-1.0 and it also fails with unable to create pipeline and multifile plugin not found.
On checking configuration summary in the log I see all base, good, bad plugins:
...
#29 356.1 gst-plugins-good 1.20.3
#29 356.1
#29 356.1     Plugins: alpha, alphacolor, apetag, audiofx, audioparsers, auparse,
#29 356.1              autodetect, avi, cutter, navigationtest, debug, deinterlace, dtmf,
#29 356.1              effectv, equalizer, flv, flxdec, goom, goom2k1, icydemux,
#29 356.1              id3demux, imagefreeze, interleave, isomp4, alaw, mulaw, level,
#29 356.1              matroska, monoscope, multifile, multipart, replaygain, rtp,
#29 356.1              rtpmanager, rtsp, shapewipe, smpte, spectrum, udp, videobox,
#29 367.6              videocrop, videofilter, videomixer, wavenc, wavparse, y4menc,
#29 367.6              ossaudio, oss4, video4linux2, ximagesrc, cairo, jpeg, lame, dv,
#29 367.6              png, soup
...

So there are 2 main questions:
How to fix the gobject-introspection problem (I suspect somewhere in the sub-project there's a .wrap file with revision=master, but where it is)?
What else to check to understand why GStreamer tools are not working?
Any help is appreciated.


text:
Q: Why isn't "this" equal to the object that called the function? I have a function that I attach to a dom object. I want to be able to reference the dom object from within the function, but when I call it from an event, this isn't equal to the right thing.
var main = document.getElementById('main');

main.testFunction = () => {
  console.log('this',this);
}

main.addEventListener('click', main.testFunction);

Instead it's equal to window. Why is this? How do I reference the object that the method is part of?

A: This is because you are using arrow function. Arrow function doesnot have their own this. Use normal function it will work. According to MDN

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this

var main = document.getElementById('main');
main.testFunction = function() {
  console.log('this',this);
}
main.addEventListener('click', main.testFunction);
<button id="main"> main</button>

Secondly when you use addEventListener and pass the function then the element to which event is attached is automatically binded to given function.See the snippet

var main = document.getElementById('main');
function testFunction(){
  console.log('this',this);
}
main.addEventListener('click', testFunction);
<button id="main"> main</button>

If you want to access the element inside arrow function use event.target instead of this

var main = document.getElementById('main');
main.testFunction = (e) => {
  console.log('this',e.target);
}
main.addEventListener('click', main.testFunction);
<button id="main"> main</button>


text:
Q: Hindi text extraction from pdf in android studios Hey I'm a bit new to Android studio and I'm having some trouble in extraction non-English (hindi) text from pdf and displaying it in text view.
The English letters are correctly extracted from pdf but when it comes to non-English (hindi) letter, I always get garbage value
Can anyone please give a sample code as to how to extract the non-English letter from a pdf ?


text:
Q: Dev stack/ media wiki on Apache server I have devstack which is the development environment for Openstack on my Ubuntu machine 12.04 LTS. I recently installed mediawiki on my laptop. The problem now seems to be that every time I run /etc/init/apache2 start, the server starts and points to Openstack login. I want to instantiate the mediawiki server.
Is this possible? Can a single piece of hardware run two servers? Do I have to virtualization here?
The solution that I could think of on top of my head is that, there must be a file which points which server to instantiate. If this is the case, I am not able to think which file has to be changed.

A: You probably want to look at LXC.  And create a linux container for the devstack environment.
Alternatively something akin to cowbuilder may work well.


text:
Q: Windows Command Prompts 'systeminfo' command equivalent on Ubuntu With Windows' command prompt, I can get a simplified system hardware overview through systeminfo command. On Ubuntu I can get a lot of non GUI commands with lots of info plus verbose details. There are some GUI tools like sysinfo. But I can't find a non-GUI one. So, can I get a simplified non-verbose non-GUI system information summary through terminal on Ubuntu?

A: Try inxi:
$ inxi
CPU: 6-Core Intel Core i7-8700K (-MT MCP-) speed/min/max: 800/800/4700 MHz
Kernel: 5.4.0-52-generic x86_64 Up: 7h 17m Mem: 12886.2/32061.5 MiB (40.2%)
Storage: 6.37 TiB (35.2% used) Procs: 374 Shell: bash 5.0.17 inxi: 3.0.38

For more verbose output
inxi -F

Alternative: neofetch;
$ neofetch
            .-/+oossssoo+/-.               user@PC
        `:+ssssssssssssssssss+:`           ----------------
      -+ssssssssssssssssssyyssss+-         OS: Ubuntu 20.04.1 LTS x86_64
    .ossssssssssssssssssdMMMNysssso.       Host: MS-7B45 2.0
   /ssssssssssshdmmNNmmyNMMMMhssssss/      Kernel: 5.4.0-52-generic
  +ssssssssshmydMMMMMMMNddddyssssssss+     Uptime: 7 hours, 20 mins
 /sssssssshNMMMyhhyyyyhmNMMMNhssssssss/    Packages: 3626 (dpkg), 15 (snap)
.ssssssssdMMMNhsssssssssshNMMMdssssssss.   Shell: bash 5.0.17
+sssshhhyNMMNyssssssssssssyNMMMysssssss+   Resolution: 2560x1440
ossyNMMMNyMMhsssssssssssssshmmmhssssssso   DE: GNOME
ossyNMMMNyMMhsssssssssssssshmmmhssssssso   WM: Mutter
+sssshhhyNMMNyssssssssssssyNMMMysssssss+   WM Theme: Adwaita
.ssssssssdMMMNhsssssssssshNMMMdssssssss.   Theme: Yaru [GTK2/3]
 /sssssssshNMMMyhhyyyyhdNMMMNhssssssss/    Icons: Yaru [GTK2/3]
  +sssssssssdmydMMMMMMMMddddyssssssss+     Terminal: tilix
   /ssssssssssshdmNNNNmyNMMMMhssssss/      CPU: Intel i7-8700K (12) @ 4.700GHz
    .ossssssssssssssssssdMMMNysssso.       GPU: NVIDIA GeForce GTX 1080
      -+sssssssssssssssssyyyssss+-         Memory: 10264MiB / 32061MiB
        `:+ssssssssssssssssss+:`
            .-/+oossssoo+/-.

Both installable via apt.

A: I'm not using Windows, so I'm not sure what can systeminfo do, but here are few commands based on screenshots I googled.
Basic system information: hostnamectl
$ hostnamectl
   Static hostname: vtrefny-Standard-PC-Q35-ICH9-2009
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 07bb5131d4b54404aedd3c859da18c05
           Boot ID: 6bf5dda3c6f3434ea4a249bd34cb0b30
    Virtualization: kvm
  Operating System: Ubuntu 20.04.1 LTS
            Kernel: Linux 5.4.0-48-generic
      Architecture: x86-64

CPU information: lscpu
$ lscpu
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   40 bits physical, 48 bits virtual
CPU(s):                          2
On-line CPU(s) list:             0,1
Thread(s) per core:              1
Core(s) per socket:              1
Socket(s):                       2
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           94
Model name:                      Intel Core Processor (Skylake, IBRS)
Stepping:                        3
CPU MHz:                         2111.996
BogoMIPS:                        4223.99
Virtualization:                  VT-x
Hypervisor vendor:               KVM

Memory information: lsmem
$ lsmem
RANGE                                 SIZE  STATE REMOVABLE BLOCK
0x0000000000000000-0x000000007fffffff   2G online       yes  0-15
0x0000000100000000-0x000000017fffffff   2G online       yes 32-47

Memory block size:       128M
Total online memory:       4G
Total offline memory:      0B

Other tools:

*

*lsusb: devices connected to USB

*lspci: PCI devices

*lshw: detailed hardware info

*/proc/cpuinfo (file): detailed CPU information

*lsblk: list of block devices

*df -h: mounted filesystem with size and free space

There is of course more. Not sure if there is a one tool that can print all the information, but the tools I mentioned are installed by default and in Linux/Unix we usually have one tool for one thing (see Unix Philosophy).


text:
Q: Handling a download url results in 404 I have a single page web app using React and React-router v4 that is being served and consuming API from a golang backend.
The issue is: the client is requesting a download link for a file in the form hostname:port/download/file_name, however since the backend is running on the same hostname:port (served statically), react-router is handling the download link as an in-app navigation so it results in the frontend's 404
<Router>
    <Switch>
        <Route exact path='/' component={WelcomeScreen} />
        <Route path='/grades' component={LevelYearScreen} />
        <Route path='/grade/:gradeId' component={SubjectScreen} />
        <Route path='/subject-:subjectId/term-:termIndex' component={LessonSectionsScreen} />
        <Route path='*' component={NotFoundPage} />
    </Switch>
</Router>

Once the URL has been fetched, I'm navigating to the URL in order to download the file
window.location.href = response.fileUrl;

I have also tried to use <a href="fileUrl"/> and react-router's <Redirect> nothing seems to work. If the link is copied and pasted manually to the browser's address bar, the same thing happens. But if the js bundle is not present in the cache (Private window for example) the file is downloaded normally.
Is there any way to exclude the "/download" route from react-router ?


text:
Q: Calling function from within Knockout Observable Array I have a Knockout observable array that I wish to edit from within Javascript and from the HTML as well. Here is my code:
var ListModel = function(formula) {
  var self = this;
  self.formula = ko.observableArray(formula);

  this.mergeEquation = function(op) {
    if (op.type == "ins") {
      self.formula.splice(op.position, 0, op.value);
    } else if (op.type == "del") {
      self.formula.splice(op.position, 1);
    } else {
      console.info("No match: " + op.value + op.position);
    }
  };
};

My variable op is a JSON string. I know how to call the mergeEquation function using HTML data-bind, but how do I do so from within the same JS file? My current code goes something like this:
ko.applyBindings(new ListModel(formula));
//...
//initializing of JSON object called op
//...
if (something) {
  mergeEquation(op);
}

but it doesn't work. Am I missing out some step here? I've read up on functions and extenders but both seems too overkill for what I'm trying to do here.
PS: Here's a sample of the JSON structure I'm working with:
{"type":"ins", "clientID":1223, "version":0, "value":"hi", "position":0, "id":2736}

A: change :-
ko.applyBindings(new ListModel(formula));

to
  var vm = new ListModel(formula);
   ko.applyBindings(vm);

so, now vm is the thing you can call the mergeequation on
vm.mergeEquation(op)


text:
Q: Using YEAR and SUM CASE WHEN I have a query where I am adding all the hours of courses together for the past 3 years and I am having trouble getting the year and sum case when figured out.
THe Code is
SELECT TNG_MDA_TYP_CD, SUM(LEN_HRS_ST) AS Expr1, REC_EFF_STT_DT
FROM  dbo.COL_TBL_VCOURSE_NEW
GROUP BY TNG_MDA_TYP_CD, REC_EFF_STT_DT

REC_EFF_STT_DT is the date the course was made available and the LEN_HRS_ST is the total number of hours. I cannot figure out how to incorporate the YEAR function with SUM CASE WHEN. I need a column for each year so a column for 2010, 2011, and 2012 with the total hours.

A: Editing after question was clarified:
SELECT
 TNG_MDA_TYP_CD,
 Sum2010 = SUM(CASE WHEN DATEPART(YEAR, REC_EFF_STT_DT) = 2010 THEN LEN_HRS_ST ELSE 0 END),
 Sum2011 = SUM(CASE WHEN DATEPART(YEAR, REC_EFF_STT_DT) = 2011 THEN LEN_HRS_ST ELSE 0 END),
 Sum2012 = SUM(CASE WHEN DATEPART(YEAR, REC_EFF_STT_DT) = 2012 THEN LEN_HRS_ST ELSE 0 END)
FROM  dbo.COL_TBL_VCOURSE_NEW
GROUP BY TNG_MDA_TYP_CD

That's assuming that you literally wanted sums for 2010, 2011, and 2012 as you stated. For something more dynamic, take a look at the PIVOT function.


text:
Q: j2objc /usr/local/lib//libprotobuf.a(strutil.o) ld: 55 duplicate symbols for architecture x86_64 I am unable to get beyond the make protobuf step due to the error below. I read up some blogs, they recommended installing brew install protobuf. Did that. Still not able to build.
I am building on a Mac 10.11.6
make protobuf_dist
c++ -MD -c -o /Users/jsiddharth/Desktop/workspace/test/j2objc-master/protobuf/compiler/build_result/google/protobuf/compiler/j2objc/j2objc_enum.o -x c++ -stdlib=libc++ -Isrc -I../google/src src/google/protobuf/compiler/j2objc/j2objc_enum.cc
In file included from src/google/protobuf/compiler/j2objc/j2objc_enum.cc:35:
In file included from src/google/protobuf/compiler/j2objc/j2objc_enum.h:41:
src/google/protobuf/compiler/j2objc/common.h:44:10: fatal error:
      'google/protobuf/compiler/code_generator.h' file not found
#include <google/protobuf/compiler/code_generator.h>
         ^
1 error generated.
make[1]: *** [/Users/jsiddharth/Desktop/workspace/test/j2objc-master/protobuf/compiler/build_result/google/protobuf/compiler/j2objc/j2objc_enum.o] Error 1
make: *** [protobuf_compiler_dist] Error 2

Edit
I tried to export to

export PROTOBUF_ROOT_DIR=~/Downloads/protobuf-3.0.0/src/

Since I found the code_generator.h in

/Users/jsiddharth/Downloads/protobuf-3.0.0/src/google/protobuf/compiler/code_generator.h

Still the same error. Am I not exporting the correct variable ?
Edit

*

*For a Mac system, Unix tools are not available by default. You will first need to install Xcode from the Mac AppStore and then run the following command from a terminal:

*$ sudo xcode-select --install

*To install Unix tools, you can install "port" following the instructions at https://www.macports.org . This will reside in /opt/local/bin/port for most Mac installations.

*$ sudo /opt/local/bin/port install autoconf automake libtool
Now I am facing the following error

/Users/jsiddharth/Desktop/workspace/test/j2objc-master/protobuf/compiler/build_result/google/protobuf/stubs/strutil.o
     /usr/local/lib//libprotobuf.a(strutil.o)
  ld: 55 duplicate symbols for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)
  make[1]: * [/Users/jsiddharth/Desktop/workspace/test/j2objc-master/protobuf/compiler/build_result/j2objc_protoc] Error 1
  make: * [protobuf_compiler_dist] Error 2

A: The Optional Setup for Protocol Buffers in the Building J2ObjC doc should work. I think the missing step is to define a PROTOBUF_ROOT_DIR environment variable to brew's include directory root (it's /usr/local/include by default):
$ export PROTOBUF_ROOT_DIR=/usr/local/include
$ make protobuf_dist


text:
Q: Celery beat sends the same task twice to the worker on every interval I have the following scheduled task in example_app -> tasks.py:
@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):

    sender.add_periodic_task(
        crontab(minute='*/1'),
        test.s(),
    )

@app.task
def test():
    print('test')

However this scheduled task is executed twice every minute:
celery_1       | [2022-02-08 16:53:00,044: INFO/MainProcess] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] received
celery_1       | [2022-02-08 16:53:00,046: INFO/MainProcess] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] received
celery_1       | [2022-02-08 16:53:00,046: WARNING/ForkPoolWorker-6] test
celery_1       | [2022-02-08 16:53:00,047: WARNING/ForkPoolWorker-7] test
celery_1       | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-6] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] succeeded in 0.0014668999938294291s: None
celery_1       | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-7] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] succeeded in 0.001373599996441044s: None

I read that this can be caused when you change django timezone from UTC, which I have done on this project.  I tried this solution from another question but it doesn't stop the duplication:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.base')

class MyCeleryApp(Celery):
    def now(self):
        """Return the current time and date as a datetime."""
        from datetime import datetime
        return datetime.now(self.timezone)

app = MyCeleryApp('tasks')

app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

settings:
CELERY_BROKER_URL = "redis://redis:6379/0"
CELERY_RESULT_BACKEND = "redis://redis:6379/0"

running in docker:

    celery:
        restart: always
        build:
          context: .
        command: celery --app=config.celery worker -l info
        depends_on:
          - db
          - redis
          - django

    celery-beat:
        restart: always
        build:
          context: .
        command: celery --app=config.celery beat -l info
        depends_on:
          - db
          - redis
          - django

have also tried docker like this:
    celery:
        restart: always
        build:
          context: .
        command: celery --app=config.celery worker -B -l info
        depends_on:
          - db
          - redis
          - django

with same result.
Not sure what is causing this.

A: In case it helps anyone else, I solved the problem by removing the periodic task from tasks.py and defining it in settings.  So the files look like this:
tasks.py
@app.task
def test():
    print('test')

settings.py
CELERY_BEAT_SCHEDULE = {
    "test-task": {
        "task": "example_app.tasks.test",
        "args": (),
        "schedule": crontab(),
    }
}

Not sure what was wrong with my previous setup as I thought it was inline with the docs.


text:
Q: Невозможна установка canvas nodejs Команда npm install canvas
Ошибка:
> canvas@2.5.0 install D:\0000\Hikka-R\node_modules\canvas
> node-pre-gyp install --fallback-to-build

node-pre-gyp WARN Using request for node-pre-gyp https download
node-pre-gyp WARN Tried to download(404): https://github.com/node-gfx/node-canvas-prebuilt/releases/download/v2.5.0/canvas-v2.5.0-node-v72-win32-unknown-x64.tar.gz
node-pre-gyp WARN Pre-built binaries not found for canvas@2.5.0 and node@12.2.0 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)
Warning: unrecognized setting VCCLCompilerTool/MultiProcessorCompilation
Warning: unrecognized setting VCCLCompilerTool/MultiProcessorCompilation
Warning: unrecognized setting VCCLCompilerTool/MultiProcessorCompilation
Warning: unrecognized setting VCCLCompilerTool/MultiProcessorCompilation
Построение проектов в этом решении по одному. Чтобы включить параллельное построение, добавьте параметр "/m".
MSBUILD : error MSB3428: Загрузка компонента Visual C++ "VCBuild.exe" невозможна. Способы решения проблемы: 1) установка .NET Framework 2.0 SDK, 2) установка Microsoft Visual Studio 2005 или 3) указа
ние адреса компонента в системном пути, если компонент установлен в другом месте.  [D:\0000\Hikka-R\node_modules\canvas\build\binding.sln]
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (D:\soft\nodejs\node_modules\node-gyp\lib\build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:196:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:257:12)
gyp ERR! System Windows_NT 10.0.17763
gyp ERR! command "D:\\soft\\nodejs\\node.exe" "D:\\soft\\nodejs\\node_modules\\node-gyp\\bin\\node-gyp.js" "build" "--fallback-to-build" "--module=D:\\0000\\Hikka-R\\node_modules\\canvas\\build\\Release\\canvas.node" "--module_name=canvas" "--module_path=D:\\0000\\Hikka-R\\node_modules\\canvas\\build\\Release" "--napi_version=4" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v72"
gyp ERR! cwd D:\0000\Hikka-R\node_modules\canvas
gyp ERR! node -v v12.2.0
gyp ERR! node-gyp -v v4.0.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute 'D:\soft\nodejs\node.exe D:\soft\nodejs\node_modules\node-gyp\bin\node-gyp.js build --fallback-to-build --module=D:\0000\Hikka-R\node_modules\canvas\build\Release\canvas.node --module_name=canvas --module_path=D:\0000\Hikka-R\node_modules\canvas\build\Release --napi_version=4 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v72' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (D:\0000\Hikka-R\node_modules\canvas\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:196:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1011:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:268:5)
node-pre-gyp ERR! System Windows_NT 10.0.17763
node-pre-gyp ERR! command "D:\\soft\\nodejs\\node.exe" "D:\\0000\\Hikka-R\\node_modules\\canvas\\node_modules\\node-pre-gyp\\bin\\node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd D:\0000\Hikka-R\node_modules\canvas
node-pre-gyp ERR! node -v v12.2.0
node-pre-gyp ERR! node-pre-gyp -v v0.11.0
node-pre-gyp ERR! not ok

Пробовал установить sdk framework 2.0 - Не смог, установщик попросту не запускался.
Установить visual studio 2005 я так и не смог.
Собственно, компонент, я не знаю про какой компонент идёт речь.
Если будет какая-либо информация, прошу сообщить, возможно она натолкнёт меня на путь решения проблемы.


text:
Q: UIDatePickerView as FirstResponder for UITextField is missing Month Component I'm implementing a table view where for one particular table view cell, there is a textfield whose first responder needs to be a UIDatePicker.  I've been able to implement most of it, but for some reason the view is not appearing completely correct. I've been stuck on this problem for a while and I've been looking at this answer for help.
UIDatepicker in UItextfield in UItableView
As of now, I have the data picker appearing and disappearing properly, the delegate for the text field is working properly, and the textfield can be updated.  My problem is that for some reason the Month component of the date picker is missing (I have a picture, but since I have less than 10 rep, I can't post it).  What it looks like is a typically UIDatePicker but the first component that has the months, is completely empty and can't scroll.  The day and year components operate normally.
This is how I create the picker view
    cell = [tableView dequeueReusableCellWithIdentifier:InfoIdentifier];
    UILabel *textLabel = (UILabel *)[cell viewWithTag:kInfoLabelTag];
    UITextFieldWithIndex *cellText = (UITextFieldWithIndex *)[cell viewWithTag:kInfoTextboxTag];
    cellText.indexPath = indexPath;

    textLabel.text = @"Birthday";

    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    [datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    datePicker.tag = indexPath.row;

    cellText.inputView = datePicker;

And here is the callback method
-(void)datePickerValueChanged:(id)sender {
NSLog(@"Date Changing");
currentTextField.text = @"new date";
}

Resigning the first responder works, and if I print the date, the month is present, so the only problem is that the month labels are missing.
I created this project using Storyboards, and I am also using core date in this project.  However, the core data part of this view controller hasn't been implemented yet.
Any ideas?

A: So after looking through my code more I figured out that the problem was a category I created for a UIPickerView.
In another file, I created a custom picker view by using a category to override the drawrect: method of UIPickerView.  In the overrided method, I actually set some of the views as hidden for a UIPickerView.  Although the category was only imported in the other file, the category overrided method was being used for UIDatePickerView, and thus setting the first component as hidden.
My quick fix was to simply subclass UIPickerView for my special picker in the other file, thus isolating the custom drawRect override there.  After I did this, my UIDatePicker displayed properly!


text:
Q: Alter sequence using jdbctemplate I need to execute the below alter command using jdbc template(not sure if alter statement can be used in jdbctemplate).
ALTER SEQUENCE MY_SEQ INCREMENT BY <>;
The number will be passed dynamically.
Please help.
Thanks

A: This is my function.
int incremento= 10;
String sql="ALTER SEQUENCE esquema.scuencia INCREMENT BY ";
String update=sql+incrmento;
jdbcTemplate.update(update);
The user needs to have special privileges to modify the sequence.


text:
Q: creating an inline update field using jquery I've gotten stuck(again)
I have a table and one of the columns is a value that I want to be able to click, turn into an input field, then click again to change it back to just text.
I've gotten the first step done. It turns into an input field with a link to click and it uses the value that was previously in the td.
However, in writing the function to update the value and remove the input, I can't get it to fire at all. I've tried copying out the input field and hard coding that first step into the page and when I do that it does actually fire the click function. (I haven't finished writing this step as I wanted to get the function to fire first. Below is my code. Any help is overwhelmingly appreciated!
HTML:

2

2

2

JQUERY:
$(".qty").click(function(){
    var value = $(this).text();
    var set =$(this).attr('set');
    if (set==0){
        $(this).html('<input type="text" name="quantity" value="'+value+'">update ');
        $(this).attr('set', '1');
    }
});

$(".update_qty").click(function(){
    alert("using this to check if it's firing");
});

A: you need to use the live() function, otherwise the event won't be added to newly created elements.
$(".update_qty").live('click',function() {
   alert("check if firing");
});

A: demo
http://jsfiddle.net/JEBaN/1/

    some value

    To Edit Mode
    To View Mode

jQuery(function(){
        jQuery('#toEdit').click(_toEditMode);
        jQuery('#toView').click(_toViewMode);
});

function _toEditMode()
{
    var _elm=jQuery('.converter');
    var _val= _elm.html();
    _elm.html('<input type="text" value="'+_val+'" />');
}

function _toViewMode()
{
    var _elm=jQuery('.converter');
    var _val= _elm.find('input').val();
    _elm.html(_val);
}

A: $(".update_qty").click(function(){
    $("qty").html("
whatever text you want
");
});


text:
Q: Casting an string to float javascript I have an string defining the lattitude of an event with this format "p002.155" and "n003.196" being "p" and "n" the form the system define if the number is positive or negative.
I need to parse the string to float, tried with parseFloat but keeps getting NaN value because of the char inside the string
how can I do it?? Thanks.

A: You can replace the char and then convert to float:

var str = "n002.155";
str = +str.replace("p","").replace("n","-"); //here the leading `+` is casting to number
console.log(str);

A: You can use substring and look at the first char

function getFloat(str) {
  var sign = str.charAt(0)=="n"?-1:1;
  return parseFloat(str.substring(1))*sign;
}

var latPStr = "p002.155", latNStr = "n003.196";
console.log(getFloat(latPStr),getFloat(latNStr));

A: You can convert a string to float like this:
var str = '3.8';
var fl= +(str);  //fl is a variable converted to float
console.log( +(str) );
console.log("TYPE OF FL IS THIS "+typeof fl);

+(string) will cast string into float.


text:
Q: SQL Server 2019 with Docker Desktop - Restore Database error I have installed Docker Desktop and I have successfully got my 2019 SQL Server container running. It is pretty basic, here is my docker run command:
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=<Strong Password>" --name "sql1" -h "sql1" -e "MSSQL_PID=Developer" -p 1433:1433 -v D:\2019DBs\data:/var/opt/mssql/data -v D:\2019DBs\log:/var/opt/mssql/log -d mcr.microsoft.com/mssql/server:2019-latest

But when I go to restore a backup that that I placed in D:\2019DBs\data. I get the below error:
System.Data.SqlClient.SqlError: The operating system returned the error '1(Incorrect function.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on '/var/opt/mssql/data/Test.mdf'. (Microsoft.SqlServer.SmoExtended)

I can create an empty database without a problem. I am not sure what else to do.

A: A way to get this to work was manually create the .mdf, .ndf, and .ldf files in the directory then the restore worked. Not sure if this is ideal or why this would be the case but that is how I got it to work.


text:
Q: Follow user and tags system User can follow by another user or tag.
My database:
POSTS (id, user_id, name, content)
USERS (id, username)
TAGS (id, name)
TAGS_ASSIGNMENTS (post_id, tag_id)
USERS_FOLLOW (user_id, follow_user_id)
TAGS_FOLLOW (user_id, follow_tag_id)

I need one request to get all the post, where I follow users and tags...
Can someone hale me with that?
I can create on request for users and one for tags, but not together

A: You have to use both JOIN and UNION in this case, Try below:
select a.name, a.content from POSTS a where user_id in (
    select follow_user_id from USERS_FOLLOW where user_id = @userid)
UNION DISTINCT
select a.name, a.content from POSTS a where id in (
    select post_id from TAGS_ASSIGNMENTS a, TAGS_FOLLOW b where
        a.tag_id = b.follow_tag_id and b.user_id = @userid)

Here @userid is the input User Id


text:
Q: Using AWS CP command can we upload local zip file to s3? aws s3 --region cp XXX.zip s3://XXX --recursive --acl public-read

I am using above command to upload my local zip to s3 but not working

A: --recursive flag is the problem. It is causing the filename to be interpreted as directory which is not, it is a file. This sounds like a bug/annoyance of the AWS command.
From the Docs (docs.aws.amazon.com/cli/latest/reference/s3/cp.html)
--recursive (boolean) Command is performed on all files or objects under the specified directory or prefix.
Remove --recursive and the file is copied
aws s3 --region us-east-1 cp XXX.zip s3://XXX --acl public-read


text:
Q: Read name and values of node using value of attribute in PHP XPATH I am using PHP DOM XPATH. I have XML structure as below
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:rank="http://www.w3.org/2001/XMLSchema">
    <rank:one year = "2015">99</<rank:one>
    <rank:two year = "2014">128</rank:two>
    <rank:three year = "2015">27</rank:three>
</root>

where I want to get name and value of node where year is 2015
expected output is rank:one -- 99 and rank:three -- 27
I tried to write xpath query as
$xpath->query('//root/[@year="2015"]');

I am not getting what should be xpath expression in this case

A: The XPath expression should be
$xpath->query('//root/*[@year="2015"]');

Then you can use name() and text() to get its name and value, respectively.


text:
Q: how to send two models includes data to ajax success call I have two models called User and post. now am calling controller action through ajax. Now i want to send User.includes(:posts) data to ajax success function. Am successfully sending data also. But in ajax success function am able to see only users data but not posts data.
            $.each(data,function(k,v) {
                $('#testDataTable tbody').append('
'+v.id+'	'+v.name+'
');
            });

Am trying v.posts but its saying undfined . How to achieve this. Thanks in advance.
In Controller My code is
@e = Master.find(params[:id])
@data = @e.users.includes(:posts)
respond_to do |format|
    format.json { render :json => @data}
end

A: Just using includes on your association will not load the association data in the json.
You will have to do
@e.users.as_json(include: :posts)

This will render the posts in the json data