text:
Q: Python Parsing with a Variable Name and Square Brackets I have a file named item.dat containing bracketed keywords:
[ITEM1]
banana
peach
apple
orange
grapes
[END]
[ITEM3]
tennis
bowling
[END]
........

I want to the lines between the bracketed keywords to be processed.  The variable wil contain the bracketed lines I want to extract.  The problem is how do I perform a line comparison for "[ItemName]"?
del item[:]
ItemName = "ITEM3"
with open('item.dat') as input_data:
    for line in input_data:
        if line.strip() == "\[ItemName\]":   # the problematic line
            break
    for line in input_data:  # This keeps reading the file
        if line.strip() == '[END]':
            break
        print line
        item.append(line)

A: Try this regex:
^\[(?!END).*]

Regex live here.
Explaining:
^\[          # starts with a '[' character
(?!END)      # don't match 'END'
.*]$         # take all till the end ']' character

Hope it helps.

A: I believe that the question that you have asked can be answered using the solution provided here with only slight modifications. As the linked answer is so thorough, I will not repeat the answer, but if for some reason that does not work, let me know and I can provide some alternatives.

A: Don't know if I really understand the question, but a simple way of extracting the bracketed values is this:
items = []
variables = []

with open('item.dat') as input_data:
    for line in input_data:
        line = line.strip()
        if line and line[0] == '[' and line[-1] == ']':
            variables.append(line)
        else:
            items.append(line)

Printing the two lists using the data provided results in:
variables = ['[ITEM1]', '[END]', '[ITEM3]', '[END]']
items = ['banana', 'peach', 'apple', 'orange', 'grapes', 'tennis', 'bowling']


text:
Q: What is the difference between jobs and services?
Possible Duplicate:
What's the difference between "Service" and "/etc/init.d/"?

So what are the differences between jobs that are located in /etc/init/, which I call by writing start myJob, versus a service which I call by sudo service aservice reload?
Thanks

A: A service is a type of job (Jobs are either tasks or services).
From the upstart cookbook:
4.1 Job
A "unit of work" - generally either a "Task" or a "Service". Each Job is defined in a Job configuration file.
4.1.1   Job Types
4.1.1.1   Task Job
A Task Job is one which runs a short-running process, that is, a program which might still take a long time to run, but which has a definite lifetime and end state.
For example, deleting a file could be a Task Job since the command starts, deletes the file in question (which might take some time if the file is huge) and then the delete command ends.
4.1.1.2   Service Job
A Service Job is a long-running (or daemon(3) process). It is the opposite of a Task Job since a Service Job might never end of its own accord.
Examples of Service Jobs are entities such as databases, webservers or ftp servers.
4.1.1.3   Abstract Job
There is one other type of job which has no script sections or exec stanzas. Such abstract jobs can still be started and stopped, but will have no corresponding child process (PID). In fact, starting such a job will result in it "running" perpetually if not stopped by an Administrator. Abstract jobs exist only within Upstart itself but can be very useful. See for example:
Jobs that "Run Forever"
Synchronisation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt на windows10, некорректная работа В общем потребовалось запустить проект на другом компьютере , я взял тот же установочный файл и установил на другом компьютере.

мой компьютер - виндовс 7 разрядка 64, другой компьютер - виндовс 10 разрядка 64, установочный файл - qt-opensource-windows-x86-5.10.1.exe

QtCreator прекрасно работает на обоих компьютерах. Компилятор в обоих случаях mingw53_32 "из коробки".
Но при компиляции проекта которой прекрасно компилиться на моём компьютере, он не скомпилировался на другом компьютере, выкинув ошибку на то что не может найти файл, стороннюю .dll (которую на самом деле прекрасно видит).
По правде говоря даже примеры он не запускает.
Я проверил связи Dependency Walker-ом и получил удручающий результат
Множество библиотек не было , я докачал часть руками и установил Windows 10 SDK но всё равно все библиотеки не установились.
Вот связи рабочего Qt

Вот не рабочий Qt

Не знаю что я делаю не так и чего не хватает.
Сам не рабочий qt (на windows 10) пустой проект собирает но при запуске сразу аварийно завершается.


text:
Q: How to use modal to create a new object in rails? This is the current situation, a general rails  app with index.html.erb related to index action, and a new.html.erb with new action to create a new object.
My request is that I want to use modal to replace the index.html.erb to create a new object. In detail, when user click a New Button in the index.html page, a dialog display with a form of creating object, instead of opening the new.html page.
Is there a possible way to realise this ignoring copying the code in new.html.erb to index.html.erb? Because it would also move the code in new action to index action.
I have tried an approach below, but it didn't meet my requirement:
<%= link_to "New sites", new_site_path, :class => "btn btn-primary", "data-toggle" => "modal", "data-target" => ".bs-example-modal-lg" %>
It would open a modal dialog including the components in application.html.erb, such as navigation bar ,side bar and so on, not only the creating form.

A: you can set "layout false" in action


text:
Q: Suggest command not working because "TypeError: can't read property 'execute' undefined" Hello I have been trying to make a Discord bot to create a submit command and for some reason it always comes out as saying "TypeError: can't read property 'execute' undefined" in the console which I have checked and is not working for some reason.
//submit.js

module.exports = {
    name: 'sumbit',
    aliases: ['submission', 'suggest'],
    description: 'Submits your article for The Monthly Grind',
    execute(message, args, cmd, client, Discord){
        const channel = message.guild.channels.cache.find(c => c.name === 'submitarticles');
        if(!channel) return message.channel.send('suggestions channel does not exist!');

        let messageArgs = args.join(' ');
        const embed = new Discord.MessageEmbed()
        .setColor('FADF2E')
        .setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true }))
        .setDescription(messageArgs);

        channel.send(embed).then((msg) =>{
            msg.react('');
            msg.react('');
            message.delete();
        }).catch((err)=>{
            throw err;
        });
    }
}

// command_handler.js
const fs = require('fs');

module.exports = (client, Discord) =>{
    const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));

    for(const file of command_files){
        const command = require(`../commands/${file}`);
        if(command.name){
            client.commands.set(command.name, command);
        } else {
            continue
        }
    }
}

// message.js

const command_handler = require('../../handlers/command_handler');

require('dotenv').config();

module.exports = (Discord, client, message) =>{
    const prefix = process.env.PREFIX;

    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const cmd = args.shift().toLowerCase();

    const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));

    try {
        command.execute(message, args, cmd, client, Discord);
    } catch (err) {
        message.reply("Sorry there was an error running this command!")
        console.log(err);
    }
}

Console error: "TypeError: can't read property 'execute' undefined"
I have been unable to find the cause of this error and I am still continuing to look.
-JFS

A: It means command is undefined. Try to check it first and if there is no command found, just ignore it:
const command = client.commands.get(cmd)
    || client.commands.find(a => a.aliases && a.aliases.includes(cmd));

if (!command) return;

try {
    command.execute(message, args, cmd, client, Discord);
} catch (err) {
    message.reply("Sorry there was an error running this command!")
    console.log(err);
}

Also, make sure your command name is correct. The current one is misspelled sumbit, so maybe change the name to 'submit':
module.exports = {
    name: 'submit',


text:
Q: Не могу привести строку к валидному json (C#) У меня есть json ответ от сайта, но этот json очень специфически форматирован: все кавычки и слеши прописаны через слеш-кавычку и двойные слеши, как будто в коде C#. Я пытался заменить все слеш-символы оригинальными, но тогда пропадают некоторые лишний слеш-символы в атрибуте data и json не парсится.
Как я пытался сделать:
// метод расширения
public static async Task<string> GetContent(this HttpClient httpClient, string url)
{
    if (url is null)
        throw new ArgumentNullException(nameof(url));

    var response = await httpClient.GetAsync(url);
    response.EnsureSuccessStatusCode();

    var content = await response.Content.ReadAsStringAsync();

    return content;
}

var content = await httpClient.GetContent("https://nz.ua/ru/dashboard/getnextnews");
content     = content.Replace(@"\\", "");
content     = content.Replace("\\\"", "\"");
content     = content.Remove(0, 1);
content     = content.Remove(content.Length - 1, 1);

var json = JObject.Parse(content);

Фактическое содержание content: https://justpaste.it/76tqq
Оригинальный ответ сервера:
"{\"lastNews\":\"177286396\",\"newsId\":[null,null,null,null,null,null,null,null,null,null],\"data\":\"
\\n
\\n
<\\/a> \\n                    \\n                          \\u041c\\u0435\\u043b\\u044c\\u043d\\u0438\\u043a \\u042e\\u043b\\u0456\\u044f \\u041b\\u0435\\u043e\\u043d\\u0456\\u0434\\u0456\\u0432\\u043d\\u0430<\\/a><\\/a>\\n            <\\/div>\\n
56 \\u043c\\u0438\\u043d. \\u043d\\u0430\\u0437\\u0430\\u0434<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b \\u043f\\u043e\\u043b\\u0443\\u0447\\u0438\\u043b\\u0438 \\u043e\\u0446\\u0435\\u043d\\u043a\\u0443 10 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0423\\u043a\\u0440\\u0430\\u0457\\u043d\\u0441\\u044c\\u043a\\u0430 \\u043c\\u043e\\u0432\\u0430 , \\u041a\\u043e\\u043d\\u0442\\u0440\\u043e\\u043b\\u044c\\u043d\\u0430 \\u0440\\u043e\\u0431\\u043e\\u0442\\u0430                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041a\\u0443\\u0437\\u044c\\u043c\\u0438\\u0447\\u043e\\u0432 \\u0406\\u0433\\u043e\\u0440 \\u0406\\u0433\\u043e\\u0440\\u043e\\u0432\\u0438\\u0447<\\/a><\\/a>\\n            <\\/div>\\n
\\u0441\\u0435\\u0433\\u043e\\u0434\\u043d\\u044f \\u0432 20:32<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u041d\\u043e\\u0432\\u043e\\u0441\\u0442\\u044c \\u0438\\u0437 \\u0441\\u043e\\u043e\\u0431\\u0449\\u0435\\u0441\\u0442\\u0432\\u0430: \\u041c\\u043e\\u0439 \\u043a\\u043b\\u0430\\u0441\\u0441<\\/b>
\\u0410\\u043d\\u0443, \\u0442\\u0435\\u0441\\u0442 \\u0442\\u0430\\u043a\\u043e\\u0439 \\u0432\\u043e\\u0442
\\u043b\\u044f\\u043b\\u044f\\u043b\\u044f\\u043b\\u044f\\u043b\\u044f...
\\u041f\\u043e\\u0434\\u0440\\u043e\\u0431\\u043d\\u0435\\u0435<\\/a>\\u041a\\u0442\\u043e \\u043f\\u043e\\u0441\\u043c\\u043e\\u0442\\u0440\\u0435\\u043b \\u043d\\u043e\\u0432\\u043e\\u0441\\u0442\\u044c<\\/a>                <\\/div>\\n
\\n
\\n
\\n        \\u0410\\u043d\\u0434\\u0440\\u0456\\u0454\\u0432\\u0441\\u044c\\u043a\\u0438\\u0439 \\u0410\\u043d\\u0434\\u0440\\u0456\\u0439        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0411\\u0430\\u0445\\u0456\\u0440\\u043a\\u043e \\u0414\\u0430\\u043d\\u0438\\u043b\\u043e        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0413\\u043e\\u0433\\u043e\\u043b\\u044c \\u0412\\u0430\\u043b\\u0435\\u0440\\u0456\\u044f        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0404\\u0441\\u0438\\u043f\\u0435\\u043d\\u043a\\u043e \\u0412\\u0430\\u0441\\u0438\\u043b\\u044c        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0416\\u043e\\u043b\\u0443\\u0434\\u044c \\u0412\\u0456\\u043a\\u0442\\u043e\\u0440\\u0456\\u044f        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0406\\u0432\\u0430\\u0441\\u0438\\u043d\\u0430 \\u0412\\u0456\\u043a\\u0442\\u043e\\u0440\\u0456\\u044f        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041a\\u043e\\u0447\\u0435\\u0433\\u0430\\u0440\\u043e\\u0432\\u0430 \\u0412\\u0430\\u043b\\u0435\\u0440\\u0456\\u044f        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041a\\u0440\\u0443\\u0433\\u043b\\u0430 \\u0415\\u043b\\u0456\\u043d\\u0430        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041a\\u0443\\u0437\\u044c\\u043c\\u0438\\u0447\\u043e\\u0432 \\u0406\\u0433\\u043e\\u0440        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041b\\u043e\\u0436\\u043d\\u0456\\u043a\\u043e\\u0432\\u0430 \\u0414\\u0430\\u0440'\\u044f        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041c\\u0435\\u0440\\u043a\\u0443\\u043b\\u043e\\u0432 \\u0414\\u043c\\u0438\\u0442\\u0440\\u043e        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041c\\u0438\\u0445\\u0430\\u0439\\u043b\\u0438\\u043a \\u042e\\u0440\\u0456\\u0439        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041c\\u043e\\u0432\\u0447\\u0430\\u043d \\u0410\\u043d\\u0430\\u0441\\u0442\\u0430\\u0441\\u0456\\u044f        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041c\\u0443\\u0445\\u0430 \\u0412\\u0456\\u043a\\u0442\\u043e\\u0440        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041d\\u0435\\u043b\\u0456\\u043f\\u0430 \\u0414\\u0435\\u043d\\u0438\\u0441        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u041d\\u0435\\u0448\\u0442\\u0443\\u043d \\u0404\\u0433\\u043e\\u0440        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0420\\u0430\\u0441\\u044c\\u043a\\u043e \\u0412\\u0456\\u0442\\u0430\\u043b\\u0456\\u043d\\u0430        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0422\\u0435\\u0433\\u0456\\u043c\\u0431\\u0430\\u0454\\u0432\\u0430 \\u0413\\u0430\\u043d\\u043d\\u0430        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0423\\u0441\\u043e\\u0432\\u0430 \\u0414\\u0430\\u0440'\\u044f        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0427\\u0443\\u0433\\u0443\\u043d\\u043e\\u0432\\u0430 \\u0410\\u043d\\u0430\\u0441\\u0442\\u0430\\u0441\\u0456\\u044f        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0428\\u0432\\u0438\\u0434\\u0435\\u043d\\u043a\\u043e \\u0410\\u043b\\u0456\\u043d\\u0430        \\n         \\n            <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0428\\u0435\\u043b\\u0443\\u0434\\u044c\\u043a\\u043e \\u041d\\u0456\\u043a\\u0456\\u0442\\u0430        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n
\\n        \\u0428\\u043e\\u043a\\u0430\\u0440\\u0435\\u0432\\u0430 \\u041c\\u0430\\u0440\\u0456\\u044f        \\n                    <\\/i>\\n                <\\/span>\\n    <\\/li>\\n                            <\\/ul>\\n                                            <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u0413\\u0440\\u0438\\u0433\\u043e\\u0440\\u0435\\u043d\\u043a\\u043e \\u042f\\u043d\\u0456\\u043d\\u0430 \\u0412\\u0456\\u043a\\u0442\\u043e\\u0440\\u0456\\u0432\\u043d\\u0430<\\/a><\\/a>\\n            <\\/div>\\n
\\u0441\\u0435\\u0433\\u043e\\u0434\\u043d\\u044f \\u0432 17:22<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b\\u0434\\u0430\\u043d\\u043e \\u0434\\u0438\\u0441\\u0442\\u0430\\u043d\\u0446\\u0438\\u043e\\u043d\\u043d\\u043e\\u0435 \\u0437\\u0430\\u0434\\u0430\\u043d\\u0438\\u0435 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0425\\u0456\\u043c\\u0456\\u044f                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041d\\u0435\\u0448\\u0442\\u0443\\u043d \\u041e\\u043b\\u0435\\u0441\\u044f \\u0412\\u043e\\u043b\\u043e\\u0434\\u0438\\u043c\\u0438\\u0440\\u0456\\u0432\\u043d\\u0430<\\/a><\\/a>\\n            <\\/div>\\n
\\u0441\\u0435\\u0433\\u043e\\u0434\\u043d\\u044f \\u0432 11:34<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b \\u043f\\u043e\\u043b\\u0443\\u0447\\u0438\\u043b\\u0438 \\u043e\\u0446\\u0435\\u043d\\u043a\\u0443 12 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0406\\u043d\\u0444\\u043e\\u0440\\u043c\\u0430\\u0442\\u0438\\u043a\\u0430, \\u041f\\u043e\\u0442\\u043e\\u0447\\u043d\\u0430                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041c\\u0435\\u043b\\u0456\\u0442\\u043e\\u043f\\u043e\\u043b\\u044c\\u0441\\u044c\\u043a\\u0430 \\u0417\\u041e\\u0428 I-III \\u0441\\u0442\\u0443\\u043f\\u0435\\u043d\\u0456\\u0432  \\u2116 15 \\u041c\\u041c\\u0420 \\u0417\\u041e  <\\/a><\\/a>\\n            <\\/div>\\n
\\u0441\\u0435\\u0433\\u043e\\u0434\\u043d\\u044f \\u0432 9:22<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b\\u0434\\u0430\\u043d\\u043e \\u0434\\u0438\\u0441\\u0442\\u0430\\u043d\\u0446\\u0438\\u043e\\u043d\\u043d\\u043e\\u0435 \\u0437\\u0430\\u0434\\u0430\\u043d\\u0438\\u0435 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0406\\u0441\\u0442\\u043e\\u0440\\u0456\\u044f \\u0423\\u043a\\u0440\\u0430\\u0457\\u043d\\u0438                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041c\\u0435\\u043b\\u0456\\u0442\\u043e\\u043f\\u043e\\u043b\\u044c\\u0441\\u044c\\u043a\\u0430 \\u0417\\u041e\\u0428 I-III \\u0441\\u0442\\u0443\\u043f\\u0435\\u043d\\u0456\\u0432  \\u2116 15 \\u041c\\u041c\\u0420 \\u0417\\u041e  <\\/a><\\/a>\\n            <\\/div>\\n
\\u0441\\u0435\\u0433\\u043e\\u0434\\u043d\\u044f \\u0432 9:09<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b \\u043f\\u043e\\u043b\\u0443\\u0447\\u0438\\u043b\\u0438 \\u043e\\u0446\\u0435\\u043d\\u043a\\u0443 8 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0406\\u0441\\u0442\\u043e\\u0440\\u0456\\u044f \\u0423\\u043a\\u0440\\u0430\\u0457\\u043d\\u0438, \\u041f\\u043e\\u0442\\u043e\\u0447\\u043d\\u0430                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041c\\u0435\\u043b\\u044c\\u043d\\u0438\\u043a \\u042e\\u043b\\u0456\\u044f \\u041b\\u0435\\u043e\\u043d\\u0456\\u0434\\u0456\\u0432\\u043d\\u0430<\\/a><\\/a>\\n            <\\/div>\\n
 1 \\u0434.  \\u043d\\u0430\\u0437\\u0430\\u0434<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b\\u0434\\u0430\\u043d\\u043e \\u0434\\u0438\\u0441\\u0442\\u0430\\u043d\\u0446\\u0438\\u043e\\u043d\\u043d\\u043e\\u0435 \\u0437\\u0430\\u0434\\u0430\\u043d\\u0438\\u0435 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0423\\u043a\\u0440\\u0430\\u0457\\u043d\\u0441\\u044c\\u043a\\u0430  \\u043b\\u0456\\u0442\\u0435\\u0440\\u0430\\u0442\\u0443\\u0440\\u0430                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041c\\u0435\\u043b\\u0456\\u0442\\u043e\\u043f\\u043e\\u043b\\u044c\\u0441\\u044c\\u043a\\u0430 \\u0417\\u041e\\u0428 I-III \\u0441\\u0442\\u0443\\u043f\\u0435\\u043d\\u0456\\u0432  \\u2116 15 \\u041c\\u041c\\u0420 \\u0417\\u041e  <\\/a><\\/a>\\n            <\\/div>\\n
 1 \\u0434.  \\u043d\\u0430\\u0437\\u0430\\u0434<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b\\u0434\\u0430\\u043d\\u043e \\u0434\\u0438\\u0441\\u0442\\u0430\\u043d\\u0446\\u0438\\u043e\\u043d\\u043d\\u043e\\u0435 \\u0437\\u0430\\u0434\\u0430\\u043d\\u0438\\u0435 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0406\\u0441\\u0442\\u043e\\u0440\\u0456\\u044f \\u0423\\u043a\\u0440\\u0430\\u0457\\u043d\\u0438                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041a\\u0443\\u0440\\u0442\\u0432\\u0435\\u043b\\u0456\\u0454\\u0432\\u0430 \\u041e\\u043b\\u0435\\u043d\\u0430 \\u041c\\u0438\\u043a\\u043e\\u043b\\u0430\\u0457\\u0432\\u043d\\u0430<\\/a><\\/a>\\n            <\\/div>\\n
 1 \\u0434.  \\u043d\\u0430\\u0437\\u0430\\u0434<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b\\u0434\\u0430\\u043d\\u043e \\u0434\\u0438\\u0441\\u0442\\u0430\\u043d\\u0446\\u0438\\u043e\\u043d\\u043d\\u043e\\u0435 \\u0437\\u0430\\u0434\\u0430\\u043d\\u0438\\u0435 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u043c\\u0438\\u0441\\u0442\\u0435\\u0446\\u0442\\u0432\\u043e                <\\/div>\\n                    <\\/li>\\n
\\n
\\n
<\\/a> \\n                    \\n                          \\u041c\\u0435\\u043b\\u044c\\u043d\\u0438\\u043a \\u042e\\u043b\\u0456\\u044f \\u041b\\u0435\\u043e\\u043d\\u0456\\u0434\\u0456\\u0432\\u043d\\u0430<\\/a><\\/a>\\n            <\\/div>\\n
 1 \\u0434.  \\u043d\\u0430\\u0437\\u0430\\u0434<\\/div>\\n        <\\/div>\\n\\n
\\n                    \\u0412\\u044b\\u0434\\u0430\\u043d\\u043e \\u0434\\u0438\\u0441\\u0442\\u0430\\u043d\\u0446\\u0438\\u043e\\u043d\\u043d\\u043e\\u0435 \\u0437\\u0430\\u0434\\u0430\\u043d\\u0438\\u0435 \\u043f\\u043e \\u043f\\u0440\\u0435\\u0434\\u043c\\u0435\\u0442\\u0443: \\u0423\\u043a\\u0440\\u0430\\u0457\\u043d\\u0441\\u044c\\u043a\\u0430 \\u043c\\u043e\\u0432\\u0430                 <\\/div>\\n                    <\\/li>\\n\"}"

Гугл также его автоматически не парсит:

A: Судя по всему, у нас входящая строка есть JSON-представление некоторого объекта, закодированное ещё раз по правилам JS.
Чтобы «снять» кодирование верхнего уровня, можно применить JToken.Parse:
var jsonString = (string)JToken.Parse(content);

Далее JSON разбираем стандартным образом:
var obj = JObject.Parse(jsonString);

Итого:
var obj = JObject.Parse((string)JToken.Parse(content));

A: Финальный рабочий код:
content = Regex.Unescape(content);
content = content.Remove(0, 1); // удаляем кавычку в начале
content = content.Remove(content.Length - 1, 1); // удаляем кавычку в конце
var json = JObject.Parse(content);


text:
Q: Why is current flowing mostly through the base (NPN transistor) I am currently working to install an NPN photoelectric sensor (retro-reflective dark on: https://www.automationdirect.com/adc/shopping/catalog/sensors_-z-_encoders/photoelectric_sensors/18mm_round_-_nonmetal/polarized_retroreflective_(ss_-z-fa-z-_fb_series)/fbp-dn-0e) however it is not working as expected and was hoping someone here could clarify what is happening. To my understanding an NPN transistor works as so (RL is 9k ohms). Here the transistor is activated.
What is happening is the current Ib is 0.016A when the transistor(sensor) is on and 0.12A when the transistor is off. Ie is 0.018A when the transistor is on and 0.012 when off. Ic is essentially zero at all times. The impedance reading between the collector and emmiter is 38.5M ohms at all times, and the impedance reading when taken across RL (base and collector) is overload and then when the sensor is activated the resistance of 9k ohms is read.
My question is although the logic is working as expected, the currents (Ie, Ib and Ic) are not. I was under the impression the transistor acted essentially as a switch between emitter and collector, however most of the current flow is through the base and the emitter, and the impedance between the collector and emitter is not dropping below 38.5M ohms. Can anyone clarify anything for me? Or is it likely I have screwed up the circuit or am taking incorrect measurements. Thank you.

A:
Figure 1. From the datasheet on the linked site.
The diagram is telling us to power the sensor on 1 (+) and 3 (-) and connect the load between 1 and 4.

simulate this circuit – Schematic created using CircuitLab
Figure 2. The internals of the sensor.
These sensors are far more complex that you seem to have imagined.

*

*The type you have chosen is a retro-reflective type. That means that it has both a transmitter and a sensor.

*The sensor is digital. The output will be either on or off and not somewhere in between. That means it has to have some threshold logic to determine when to switch.

*The threshold logic will switch an NPN output transistor which will connect the output lead to ground when on. (Hence 'NPN' type.)

*There will also be some hysteresis built-in so that once the on threshold has been exceeded that the light level will have to fall significantly before it turns off.

*Several precautions will be taken to ensure that the sensor is not sensitive to ambient light so that it doesn't turn on and off when someone switches the lights or a cloud moves across the sun. These include:

*

*Using infra-red light for the transmitter (not always).

*Polarizing the transmitted light and using a polarizing filter on the receiver.

*Modulating the transmitted light (the simplest is pulsing it on and off at, say, 1 kHz) and monitoring the reflected light for the modulation and detecting the change from on to off.

Most industrial control systems now use PNP sensors which switch the positive rather than the negative. This makes trouble-shooting more intuitive.
Note also that we have a symbol for transistors. There is no need to draw a diagram of PN junctions!

A: NPN photo detectors usually leave the base open, or tied with a very large resistor to the emitter. Normally the light hitting the transistor excites the base-emitter, causing base current to flow. The collector draws more current, due to the transistors current gain. So then a resistor in the collector, biased positive (VCC) relative to the emitter allows the collector voltage to vary between VCC (no light) to VceSat (much light).
I don't exactly understand your circuit. I assume that the emitter is the left N and the collector is the right N. Perhaps the voltage source is what you think is happening when light hits the transistor? When light hits the transistor the model should be a current source connected across the B-E, injecting a current proportional to the light power. Then an external voltage source with neg to the emitter and a resistor between pos and the collector biases the transistor and allows the collector voltage to change with light intensity.
A resistor across the base-emitter makes the transistor less sensitive to light as the photo induced current gets shunted by the resistor.
Your drawing has no relationship to the specification drawing for these sensors. I don't think they have exposed the base for you to connect to. I believe that in this case normally open means no current flow when no light. Normally closed means current flows when no light. NPN means that the load is externally connected to a positive voltage, and the other side of the load connected to the collector of a transistor. Emitter to neg side of the supply. In diagram 1 of the data sheet collector would be black and emitter blue. Brown, which is connected to the VCC side of the load is probably there so the sensor vendor can place a snubber circuit (Probably a diode and a maybe a small capacitor) in parallel across the load so as to protect the device from inductive kick-back if the load is a inductive, such as a relay coil.
Usually these sensors have so much gain that almost any light saturates the detector and causes the load voltage to swing from VCC to nearly ground. Often the photo detector and another transistor are Darlington connected to get the product of two transistors current gain.


text:
Q: how to represent a bridge in eagle pcb schematics?
i'm trying to show that points 7,8,10,11 are connected to ground and point 9 is connected to R18 resistor. but the visuals is misleading. how to create that "jump"

(sorry i don't know the correct lingo for that operation, please edit if you know, thankyou)

A: Eagle wants you to put junction points where two lines connect each other. Otherwise gives a warning in ERC (Electrical Rule Check). I suggest you this notation;

This way Eagle becomes sure, if it's a connection or just a different net passing over. To put junction points you can use 'Junction' from toolbar. But if you draw your nets with 'Net' tool rather than 'Wire' tool junctions will be automatically put.


text:
Q: Using a numpy array in if condition cause problems, how to fix it? I would like to test every single element of "z", with the "if else" condition and return desired equation. My implementation is resulting with an error. I tried "z.all" and "z.any" functions but these two are converting "z" to a boolean array. I do not want z as boolean array. How can I do this, while z remain as a numpy array?
z is a numpy array and its shape is (10610, ))
    def function(z):
        alpha = 1
        if (z < 0):
            return -alpha * z
        elif (0 <= z <= 1):
            return (3 * z ** 3) - (4 * z ** 2) + (2 * z)
        else:
            return z

A: You can use numpy.where for the two conditions:
np.where(
    z < 0,
    -alpha * z,
    np.where(
        z <= 1,
        (3 * z ** 3) - (4 * z ** 2) + (2 * z),
        z))

A: If I understand correctly you want to apply your function to all elements in the array z right? If so you might want to look into numpys vectorize function.
For your code:
vfunc = np.vectorize(function)
z = vfunc(z)

If speed and efficiency are important you can refer to this other answer where different methods are compared.

A: Using boolean indexing:
def function(z):
    alpha = 1

    m = (z < 0)
    z[m] = -alpha * z[m]

    m = ((z >= 0) & (z <= 1))
    z[m] = (3 * z[m] ** 3) - (4 * z[m] ** 2) + (2 * z[m])

    return z


text:
Q: How to refresh from server based on updated package.xml? I am trying to compare metadata from 2 environments (SB and prod) so I have extracted the specific components for SB. Since I already have the package.xml, is it possible to copy the xml into the production project and refresh from server to get the metadata for the specific components (from prod), instead of going through the trouble to manually select and add the components again?
Thanks heaps!

A: yes that is correct. you can use same package.xml. The only thing to consider is there might be some component which are not available on PROD, in that case component not found error will occur but if you have identical orgs there is no issue.

A: If you want to compare the metadata in two orgs, try these sweet tools.  Originally built by Tquila, but the company was acquired by Accenture, and they've finally reposted their toolkit here:
http://sftoolkit.co/
The sf org compare tool might help you do this all more quickly:
https://sforgcompare.herokuapp.com/
Cheers!


text:
Q: Is it safe to use instance variables to store transient properties of ActiveRecord objects? I need to store an encoding-state value on a video while it's been encoded
I have a video object. While the video is being encoded it needs to lock edits on its comments.
The video therefore needs to store its current encoding state (is it happening yes/no?) and allow child comments to query that property.
Please note
I know that there are better ways to solve this particular problem. I actually need to solve a slightly different problem however I felt the nuances of it would confuse the question so I've chosen this one instead. My question is specifically around the nuances of isntance variables and not how to better-solve this encoding problem (which obviously needs a queue).
class Video

  has_many :comments

  after_initialize do
    @encoding_in_process = false
  end

  def encode
    @encoding_in_process = true
    ...
    @encoding_in_process = false
  end

  def encoding_in_process?
    @encoding_in_process
  end
end

class Comment
  belongs_to :video

  before_update
    raise "locked" if video.encoding_in_process?
  end

  ...
end

As you can see, each video instance is storing an instance variable @encoding_in_process which is used to determine whether a comment can be updated.
The problem
There is a danger there will be multiple in-memory instances of the same video each with different values for @encoding_in_process.
e.g.
bieber_video = Video.find_all_by_artist('Bieber').last
bieber_video.encode
# assume this takes a while...
bieber_video.encoding_in_process?
# => true

bieber_copy = Video.find_by_id bieber_video.id
bieber_copy.encoding_in_process?
# => false

# Each ActiveRecord objects refer to the same Bieber video
bieber_copy.id == bieber_video.id
# => true

# ...however they refer to different objects in memory:
puts bieber_video
#<Video:0x00000105a9e948>
puts bieber_copy
#<Video:0x00000105a11111>

# and hence each instance has a different version of commenting_locked?
# bieber_video.encoding_in_process? != bieber_copy.encoding_in_process?

The question
Given that the same database row might generate two different in-memory instances, what is a safe way to store transient non-database-backed information about those instances?
EDIT
The actual problem I'm trying to solve is setting a flag on an object when destroy is initiated such that its child objects can determine whether or not they're eligible to be destroyed themselves.
It's therefore a very instantaneous problem and not suitable for backing into the database. I used this video example because I thought it was a bit clearer however I may have simply muddied the waters.
THE SOLUTION (courtesy of one of the answers below
@Alex D's suggestion did solve the problem but to add further clarity to this for anyone wanting to repeat, the actual code was this:
class Video
  # set a class variable containing an array of all videos
  # which are currently being encoded
  @@ids_of_videos_being_encoded = []
  ...

  def encode
    store_encoding_state true
    begin
      encode()
    ensure
      # make sure we switch this off after
      # encoding finishes or fails
      store_encoding_state false
    end
  end

  private
    def store_encoding_state encoding_in_progress
      if encoding_in_progress
        @@ids_of_videos_being_encoded.push(id)
      else
        @@ids_of_videos_being_encoded.delete(id)
      end
    end

    def encoding_initiated?
      @@ids_of_videos_being_encoded.include? id
    end
end

A:
The video therefore needs to store its current encoding state (is it happening yes/no?) and allow child comments to query that property.

IMO, that's not a good way to do this because of all the synchronization issues that will ensue.
A much better strategy is to start off all videos in an unencoded state, which you store with the video record's metadata. When a video data stream is created, enqueue an encoding task for some worker to carry out. The worker thread will encode the videos, and when it's done, it should update the video's state to encoded.
Now there's no transient state issues; the next time someone tries to comment when the encoding is finished, it'll be done.

Given that the same database row might generate two different in-memory instances, what is a safe way to store transient non-database-backed information about those instances?

If they don't need to be synchronized, then there isn't an issue. If they do need to be synchronized, you run the risk of a race condition. You can also call .reload to refresh an object's state from the database.
And if the data needs to be synchronized like that, then you probably do need to store it. In the video encoding example, you should either store each video's encoded/unencoded state or provide an implicit, authoritative way of knowing whether the video is encoded or not.

Update from the original question:

The actual problem I'm trying to solve is setting a flag on an object when destroy is initiated such that its child objects can determine whether or not they're eligible to be destroyed themselves.

Just use the after_destroy callback to invoke an appropriate method on each child object, and let them determine whether they should be destroyed or not. That will look something like this:
class Video < ActiveRecord::Base
  after_destroy :purge_pending_comments!

  def purge_pending_comments!
    comments.map &:destroy_if_pending
  end
end

A: The answer to your question depends on whether you may use multiple server processes or not. If you may want to run multiple server processes (which is a good assumption), the problem is not just multiple in-memory ActiveRecord objects representing the same DB row, the problem is multiple objects in different memory spaces.
If you have multiple processes which are somehow collaboratively working with the same data, you must keep that data in a shared store (i.e. a database), and you must flush changes to the store, and refresh your in-memory data as needed. In this case, you cannot rely on transient in-memory data being kept in synchronization (because there is no way it possibly could be).
If constantly writing/reading your transient data to the DB sounds expensive, that's because it is. In general, whenever you have multiple processes (on the same or different servers) working together, you want to design things so each process can grab a chunk of data and work on it for a while without having to communicate with the others. Fine-grained data sharing in a distributed system = bad performance.
If you are sure that you will only ever use a single server process, and you want to simulate the effect of instance variables which are shared between multiple ActiveRecord objects representing the same DB row, keep the data in a hash, keyed by the record ID, and use getters/setters which read/write the hash. If you are doing a lot of this, you can do some metaprogramming "magic" to have the getters/setters automatically generated (a la "attr_accessor"). If you need help writing that metaprogramming code, post a question and I'll answer it.


text:
Q: Validate multiple file with same name validate in laravel below are my form inputs :
<input type="file" name="image[]" multiple="true"></input>
<input type="file" name="image[]" multiple="true"></input>

and validation rules which i have used is :
'image' => 'required',
'image.*' => 'required',

I want to validate both the image file required But by above code only first image type is validating.

A: instead of
'image' => 'required',
'image.*' => 'required',

you could use
'image.*' => 'required',

this might solve your problem


text:
Q: Python, loops and iteration Define the method below to return the lowest factor of an arbitrary integer. The lowest factor is the smallest number greater than 1 that will divide evenly into the parameter(which will be 2 or higher).And this is my code, I don't know why is incorrect.
def first_factor(n):
    for num in range(2,n):
        if n % num == 0 and sqrt(n):
            return num

A: You should be using the square root of the number in the range, not as one of the conditions.
def first_factor(n):
    for num in range(2, int(n**0.5)+1):
        if n % num == 0:
            return num

A: This is only the definition of the function - you have to call it and print the result to see it.
The full code may be:
def first_factor(n):
    for num in range(2, n + 1):
        if n % num == 0:
            return num

print(first_factor(3))

Note that I totally omitted square root as it is useless and it prevented to give a result for prime numbers.


text:
Q: Calculate days between two custom field value dates I'm trying to calculate the difference in days between two post custom field values that have been inputted via a front end date picker (gravity forms).
A simplified version of what I have to get my two dates is below:
 <?php $date1 = get_field('date_start', false, false);
 $date1 = new DateTime($date1); ?>

<?php echo $date1->format('j M'); ?>

 <?php $date2 = get_field('date_fin', false, false);
 $date2 = new DateTime($date2); ?>

<?php echo $date2->format('j M'); ?>

I need to calculate and output the day difference between the above outputted dates.
Say if I had an output like:
3 jun
10 jun
I would like to be able to create a variable or some type of php output that would say:
'7 days late'
Then to make things even more complicated if the difference is zero I would like to say:
'On time'

A: We can use something like human_time_diff() to give us a readable time difference. First we need to see if the days are the same:
$date1 = get_field( 'date_start', false, false );
$date1 = new DateTime( $date1 );
$unix1 = strtotime( $date1->format( 'Y-m-d' ) );

$date2 = get_field( 'date_fin', false, false );
$date2 = new DateTime( $date2 )
$unix2 = strtotime( $date2->format( 'Y-m-d' ) );

if( 0 === ( $unix1 - $unix2 ) ) {
    echo 'On Time!';
} elseif( $unix2 < $unix1 ) {
    echo human_time_diff( $unix1, $unix2 ) . ' Early';
} else {
    echo human_time_diff( $unix1, $unix2 ) . ' Late';
}

Some example with output:
Date 1 = June 3rd
Date 2 = June 3rd
Output: On Time!
Date 1 = June 10th
Date 2 = June 13th
Output: 3 Days Late
Date 1 = June 10th
Date 2 = June 3rd
Output: 1 Week Early

If we wanted to show the actual days instead of week or month as human_time_diff() does we can just subtract the largest from the smallest, divide by the WordPress constant variable DAY_IN_SECONDS. We'll then run it through the _n() function to display plural or singular.
if( 0 === ( $unix1 - $unix2 ) ) {
    echo 'On Time!';
} elseif( $unix2 < $unix1 ) {
    $days = ( intval( $unix1 - $unix2 ) / DAY_IN_SECONDS );
    printf( _n( '%s day early', '%s days early', $days ), $days );
} else {
    $days = ( intval( $unix2 - $unix1 ) / DAY_IN_SECONDS );
    printf( _n( '%s day late', '%s days late', $days ), $days );
}


text:
Q: How does the Elo rating system work in a situation like this? The Elo rating system is commonly used to rank chess players, giving some insight into the probably of one player defeating another, but how would it react in a situation where there are three players whose games consistently end in the following way:
Jenny defeats Phil
Phil defeats Andy
Andy defeats Jenny
If each player begins with an Elo score of 1200 (as is usual), what happens? How is the score affected if they play other "ranked" matches with people outside that circle?


text:
Q: Want to add search box for each column which will search in respective column I Want to add search box for each column which will search in respective column. For that I have written my code as below but its not working.
home.component.html

    Commit Date
    Commit Id
    Environment
    Jira Id's
    Upgrade Date

    <input [(ngModel)]="searchString1" placeholder="Search.." class="advancedSearchTextbox">
    <input [(ngModel)]="searchString2" placeholder="Search.." class="advancedSearchTextbox">
    <input [(ngModel)]="searchStrin3" placeholder="Search.." class="advancedSearchTextbox">
    <input [(ngModel)]="searchStrin4" placeholder="Search.." class="advancedSearchTextbox">
    <input [(ngModel)]="searchString5" placeholder="Search.." class="advancedSearchTextbox">

      {{data.commit_date}}

    {{data.commit_id}}
    {{data.env}}
    {{data.jira_ids}}
    {{data.upgrade_date}}

filter.pipe.ts
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
  name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
  transform(items: any, filter: any, defaultFilter: boolean): any {
    if (!filter){
      return items;
    }
    if (!Array.isArray(items)){
      return items;
    }
    if (filter && Array.isArray(items)) {
      let filterKeys = Object.keys(filter);
      if (defaultFilter) {
        return items.filter(item =>
            filterKeys.reduce((x, keyName) =>
                (x && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] == "", true));
      }
      else {
        return items.filter(item => {
          return filterKeys.some((keyName) => {
            return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] == "";
          });
        });
      }
    }
  }
}

It works fine if I add a single search box at top and change HTML file like below:
Search Data Here: <input [(ngModel)]="searchString" placeholder="Search.." class="advancedSearchTextbox">

    Commit Date
    Commit Id
    Environment
    Jira Id's
    Upgrade Date

      {{data.commit_date}}

    {{data.commit_id}}
    {{data.env}}
    {{data.jira_ids}}
    {{data.upgrade_date}}

What changes do I need to make the search box work for each individual column

A: Use one parameter for the search input and use function that get the key and the name of the column as below:
HTML:

    Commit Date
    Commit Id
    Environment
    Jira Id's
    Upgrade Date

    <input  placeholder="Search.." class="advancedSearchTextbox" [ngModel]="searchString" (ngModelChange)="search($event,'commit_date')" >
    <input placeholder="Search.." class="advancedSearchTextbox" [ngModel]="searchString" (ngModelChange)="search($event,'commit_id')">
    <input placeholder="Search.." class="advancedSearchTextbox" [ngModel]="searchString" (ngModelChange)="search($event,'env')">
    <input placeholder="Search.." class="advancedSearchTextbox" [ngModel]="searchString" (ngModelChange)="search($event,'jira_ids')">
    <input placeholder="Search.." class="advancedSearchTextbox" [ngModel]="searchString" (ngModelChange)="search($event,'upgrade_date')">

      {{data.commit_date}}

    {{data.commit_id}}
    {{data.env}}
    {{data.jira_ids}}
    {{data.upgrade_date}}

TS:
  history = [
    {
      commit_date: "20/02/2019",
      commit_id: "52",
      env: "log",
      jira_ids: "jira",
      upgrade_date: "02/03/2019"
    },
    {
      commit_date: "03/03/2019",
      commit_id: "53",
      env: "log",
      jira_ids: "jira",
      upgrade_date: "03/04/2019"
    }
  ];
  searchString="";
  filterData:any=[];

  constructor(){
    this.filterData = this.history;
  }

  search(term,columnName){
       if(!term) {
      this.filterData = this.history;
    } else {
      this.filterData = this.history.filter(x =>
         x[columnName].trim().toLowerCase().includes(term.trim().toLowerCase())
      );
    }
  }


text:
Q: Custom intellij plugin to trigger function like textChange() I am writing a custom plugin for intellij.
This plugin listens to port. When receiving specific information, it should trigger to scan text, like textChange().
When java file has been modified, Inspection plugin will inspect all file again to find some errors or warnings. But I want to trigger inspecting by my program, instead of modifying
How can I trigger this event?

A: To force rehighlighting of a file, use DaemonCodeAnalyzer.getInstance(project).restart(file).


text:
Q: google drive api change owner / transferowner I want to update the permission of some files in google drive using google drive api v2.
everything works fine, file list, permission insert, .... only with permission update i have a problem but only if i want to change the owner!
There is a parameter called "transferOwnership", if i set this on https://developers.google.com/drive/v2/reference/permissions/update "try it" to true everything works fine but i dont know / can finde any way how to set this parameter in my code!?
var permissionresult = UpdatePermission(service, "fileid", "permissionid", "owner");

public static Permission UpdatePermission(DriveService service, String fileId,
    String permissionId, String newRole)
{
    try
    {
        // First retrieve the permission from the API.
        Permission permission = service.Permissions.Get(fileId, permissionId).Execute();
        permission.Role = newRole;

        return service.Permissions.Update(permission, fileId, permissionId).Execute();
    }
    catch (Exception e)
    {
        Console.WriteLine("An error occurred: " + e.Message);
    }
    return null;
}

Hope someone can help me, thats the last thing i need to complete my app.
thanks
markus

A: You need to init a new Permission instance or use the existing to modify the Role, Type and Value fields:
Permission p = new Permission();
p.Role = "owner";
p.Type = "user";
p.Value = "jbd@google.com";
service.Permissions.Update(p, fileId, permissionId);

A: I think this is what you wanted:
var permissionresult = UpdatePermission(service, "fileid", "permissionid", "owner");

public static Permission UpdatePermission(DriveService service, String fileId,
    String permissionId, String newRole)
{
    try
    {
        // First retrieve the permission from the API.
        Permission permission = service.Permissions.Get(fileId, permissionId).Execute();
        permission.Role = newRole;

        //Call the TransferOwnership property
        var updatePermission = service.Permissions.Update(permission, fileId, permissionId);
        updatePermission.TransferOwnership = true;
        return updatePermission.Execute();
    }
    catch (Exception e)
    {
        Console.WriteLine("An error occurred: " + e.Message);
    }
    return null;
}

A: You only change owner the files or folders you own.
Permission permission = new Permission
            {
                Role = "owner",
                Type = "user",
                EmailAddress = "abcnewideal2020@gmail.com"
            };

            //Call the TransferOwnership property
            var updatePermission = service.Permissions.Update(permission, fileId, permissionId);
            updatePermission.TransferOwnership = true;
            return updatePermission.Execute();

Hope this help!


text:
Q: Exception: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure NULL Suddenly paypal got error on paypal which is working before. I use RESTFUL API library from paypal.
Exception: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure NULL

A: I am afraid this could be due to the SSL issue, which PayPal has disable the SSLv3 support completely on January 12th due to Poodle vulnerability.
All information on the POODLE vulnerability and the changes needed can be found here:
PayPal SSL 3.0 (POODLE) - Merchant Response Guide
You can check the status and update your SDK (If needed) here:
PayPal SSL 3.0 (POODLE) Microsite ACT NOW


text:
Q: DataGrid that can update its databind? I am looking for an out of the box way to have a GridView on a form bound to a BindList that gets updated often and maintain the current entries.
I want to show some client objects in the GridView. Every few seconds my form reads an xml file which has the up-to-date information on the client (Name, variableNumber, variableNumber, state). I want to be able to update the information in the grid without destroying selection.
Can this be done out of the box?

A: Credit will go to DJ KRAZE if he moves his comment to an answer. While I had researched how to accomplish this nothing I found directly said that it would maintain selection and such.
My current solution is
using (var reader = new StreamReader(new FileStream(clientFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                var ser = new XmlSerializer(typeof(ClientList));
                var temp = (ClientList)ser.Deserialize(reader);

                foreach (var client in temp.Items)
                {
                    if(clientWatchers.Any(c => c.Handle == client.Handle))
                    {
                        var c = clientWatchers.First(w => w.Handle == client.Handle);
                        c.SyncNumber = client.SyncNumber;
                        c.PsNumber = client.PsNumber;
                        c.IsHalted = client.IsHalted;
                    }
                    else
                    {
                        clientWatchers.Add(client);
                    }
                }

                var handles = clientWatchers.Select(c => c.Handle).ToArray();

                foreach (var handle in handles)
                {
                    if(temp.Items.All(c => c.Handle != handle))
                        clientWatchers.Remove(clientWatchers.First(c => c.Handle == handle));
                }

                //foreach (var client in temp.Items)
                    //clientWatchers.Add(client);
                dgClientView.DataSource = clientWatchers;

            }


text:
Q: Output only changed lines I'm trying to get diff to only output changed lines, not added or deleted files.
So if file 1 contains:
hello 1
my 2
name 3

and file 2 contains:
hello 2
my 2
earth

I would get output similar to:
< hello 1
> hello 2

I've searched both on Google and Stack Overflow, and found a perl script at Stack Overflow, but that doesn't output anything.
Any way this can easily be done?

A: According to your example, I guess your question is "get diff to only output changed lines, not added or deleted lines." (not files). Right ?
If so, I think it's difficult to distinguish "added or deleted lines" from "changed lines".
e.g.
line 1
line 2
line 3

vs
line 1
line 2
lane 3

The differences of the 3rd line, is a "changed" or a "added or deleted"


text:
Q: Требуется считать текстовый файл, посчитать количество элементов в строке, найти последний и определить его первые 4 символа Требуется считать текстовый файл, посчитать количество элементов в строке, найти последний и определить его первые 4 символа. С тем чтобы найти последнее слово проблем нет, но не получается сделать чтобы программа запоминала его, и далее выводила первые три символа из него.
    <?php

$files = file('country.txt');

foreach ($files as $string) {

echo str_word_count( $string, 0, "АаБбВвГ㥴ДдЕеЁёЄєЖжЗзИиІіЇїЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЬьЪъЫыЮюЬьЭэЯя" );

function myFunc($f) {
global $f
echo $f = substr($string,strrpos($string,' '),strlen($string));
return $f;
}
myFunc($f);

$NewFunc = "myFunc";
$NewFunc();
echo substr($NewFunc, 0, 3);

}

A: Для решения этой задачи не нужно использовать цикл:
$file = 'country.txt';
// считать текстовый файл
$arr = file_exists($file) ? file($file, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES) : [];
// посчитать количество элементов
$all = count($arr);
// найти последнее слово
$end = explode(' ', $arr[$all-1]);
// вывести первые три символа из него
echo mb_substr(end($end), 0, 3);


text:
Q: Handling addError(String) from Managed package There is an addError(String) executed from a managed package.
How should this be handled by the code of the installed org?
This is the flow:
VF page->Controller--> update --> Managed package trigger->Managed package trigger utility> addError(String).
This addError is not propagating to the installed org.
Any ideas, please?

A: By "Not Propogating to the installed org", do you mean that you are unable to see what the error is for these items?
If so i would suggest overriding the managed VF page with a replica of your own extending the same controller and displaying the pageMessages
<apex:pageMessages />

tag on your page.
If the code in the controller was not designed to catch the errors - you would need to patch that so that you could capture and relay that to your page either by overriding a managed controller and writing it to the error block on your page by adding the error you have caught in your error handler OR modify your managed code to write this out properly. Managed code should still display an error on an object - the code and debug lines are more of what is protected here and withheld from those without access to managed code.


text:
Q: STEP_COUNTER and STEP_DETECTOR works with SDK 28, but not SDK 29? I've made a service that regularly broadcasts counted steps from both the STEP_COUNTER and STEP_DETECTOR sensor. In one app I made it worked flawlessly, but after copying the exact same code to another project it stopped working. After hours of debugging, I figured out how to solve it. When I change the compileSdkVersion in the build.gradle to 28 it works fine, but changing it to 29 makes it stop working. Why is that?

A: As per the Privacy changes in Android 10 (which apply to apps that have a targetSdkVersion of 29 or higher):

Android 10 introduces the android.permission.ACTIVITY_RECOGNITION runtime permission for apps that need to detect the user's step count or classify the user's physical activity, such as walking, biking, or moving in a vehicle. This is designed to give users visibility of how device sensor data is used in Settings.

The only built-in sensors on the device that require you to declare this permission are the step counter and step detector sensors.

Therefore you must:

*

*Add the android.permission.ACTIVITY_RECOGNITION to your app's manifest.

*Request the permission at runtime and have the user grant that permission.


text:
Q: functions that has :: at the beginning what does :: means at the start of a functions like ::mesagebox, ::PostQuitMessage, ::DestroyWindow and etc? i was reading a book called Introduction to 3D Game Programming with DirectX 9.0 and when i look at the example source code, it has so many functions that has :: on it.
here is the example code:
LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch( msg )
    {
    case WM_DESTROY:
        ::PostQuitMessage(0);
        break;

    case WM_KEYDOWN:
        if( wParam == VK_ESCAPE )
            ::DestroyWindow(hwnd);
        break;
    }
    return ::DefWindowProc(hwnd, msg, wParam, lParam);
}


text:
Q: Why shared-memory approach is not well suited for massive data streams? As per this post, which says that [emphasis mine]: Modern applications often deal with streaming data, indeed, with massively large streams of data. Neither the shared-file nor the shared-memory approaches are well suited for massive data streams. Channels of one type or another are better suited. Part 2 thus introduces channels and message queues, again with code examples in C.
My question is that why shared-memory approach is not well suited for massive data streams.Could somebody please explain that in more details?

A: Shared memory can communicate whatever data that needs to be communicated more efficiently than can message queues.  Shared memory has basically no communications overhead.  However, shared memory is limited because it can only be used to communicate with processes running on the same host.
"Massive large streams of data" are usually processed on clusters of servers.  In this case, it is more desirable to be able to spin up new processes based on the load with processes running across many servers.
A scheme could be designed that would use shared memory on the local server and networking when crossing servers, but that adds complexity.  Furthermore, if the majority of the inter-process communication is crossing servers, the extra complexity of shared memory


text:
Q: Is a copy constructor needed for my OpenMP parallelization? I ran into errors while I was parallelizing my function below.
bool
CMolecule::computeForces_twobody(vector<CMolecule*> &mols,
                               vector<CPnt> & force, vector<CPnt> & torque)
{
  if(mols.size() == 1 ) return true;
  int nmol=mols.size();
  int M2=nmol*(nmol-1)/2;

  vector<CMolecule*> twomols;

  vector<CPnt> force2b(nmol),torque2b(nmol);

  vector<CSphereIDPair> dimer;

  CPnt forcetemp,torquetemp;

  for(int i=0;i<nmol;i++)
     for(int j=i+1;j<nmol;j++)
     {
      dimer.push_back(CSphereIDPair(i,j));
     }

#pragma omp parallel for private(twomols, forcetemp, torquetemp)
   for(int i=0;i<M2;i++)
      {
        twomols.push_back(new CMolecule(*mols[dimer[i].is]));
        twomols.push_back(new CMolecule(*mols[dimer[i].js]));
        bool bInterXFS =  CMolecule::generateInterXFormsForPolarize_LowMemory(twomols);
        if(! bInterXFS )
        cout <<"error in generateInterXFormsForPolarize_LowMemory"<<endl;
        CMolecule::polarize_mutual(twomols,false, 1000);

        twomols[0]->computeMol_Force_and_Torque(forcetemp,torquetemp);
        force2b[dimer[i].is]+=forcetemp;
        torque2b[dimer[i].is]+=torquetemp;

        twomols[1]->computeMol_Force_and_Torque(forcetemp,torquetemp);
        force2b[dimer[i].js]+=forcetemp;
        torque2b[dimer[i].js]+=torquetemp;

        twomols.clear();
       }

  for(int i=0;i<nmol;i++)
    {
     force[i]=force2b[i];
     torque[i]=torque2b[i];
    }

  return true;
}

The serial code could be run normally. However, when run in parallel the program crashed at the function 'polarize_mutual' and generate core dumped file (unfortunately I didn't find any useful information from the core dumped file).  So I suspect that there might be something wrong with my copy operation.
        twomols.push_back(new CMolecule(*mols[dimer[i].is]));
        twomols.push_back(new CMolecule(*mols[dimer[i].js]));

I didn't see anything wrong but I doubt that this copy operation might be a shallow copy. This is because objects of class 'CMolecule' are constructed using a constructor that contains lots of pointers.
  CMolecule::CMolecule(int moltype, CPnt rcen, const vector<CPnt> &cens, const vector<double> &radii,
                 const vector<double> &chg, const vector<CPnt> &cpos, double idiel,
                 const vector<REAL*> &iMats, REAL intraRcutoff,
                 const vector<vector<CPnt> > &SPxes, const vector<int> &nSPx,
                 const vector<vector<int> >&neighs,
                 const vector< vector<int> > &intraPolLists_near,
                 const vector<CMulExpan*> &Fself, const vector<CMulExpan*> &Hself,
                 const vector<CLocalExpan*> & LFs_intraSelf, const vector<CLocalExpan*>  &LHs_intraSelf,
                 const vector<CLocalExpan*> & LFs_intraSelf_far, const  vector<CLocalExpan*> &LHs_intraSelf_far,
                 const vector<vector<REAL> > &qSolvedFself,
                 const vector<vector<REAL> > &qSolvedHself,
                 const vector<double> &totalFself, const vector<double> &totalHself,
                 const vector<CMolCell> &molcell)
    : m_rot(false), m_p(N_POLES), m_idiel(idiel), m_bKappa(false),  m_bAggregateM(false), m_moltype(moltype),
      m_molcells(molcell)

Is it necessary to write a copy constructor for class 'CMolecule' to do a deep copy?

A: Do you really need the twomols STL vector just to hold references to 2 CMolecule's?  Your implementation seems quite wasteful of CPU cycles.  I guess something along these lines might be easier for the compiler to optimize:
#pragma omp parallel for private(twomols, forcetemp, torquetemp)
for(int i=0;i<M2;i++)
{
   const CMolecule& a = mols[dimer[i].is];
   const CMolecule& b = mols[dimer[i].js];
   CMolecule::polarize_mutual(a, b, false, 1000);
   // (...)
}


text:
Q: how to pass month and year (ex: Mar-19) in DATESBETWEEN function in power bi? I am following an example of building KPI matrix from YouTube.  https://www.youtube.com/watch?v=Sq4oRnCGUAE&t=66s
How they passing Calendar[Month & Year] column in DATESBETWEEN function??
DATESBETWEEN(<dates>,<start_date>,<end_date>)

Isn't it first parameter has to be always type date?

My goal is to create 6 months trend, but for some reason dax expression does not work:
WP 6M TrendTest =
VAR LastEffDate = LASTDATE(fact_Premium[EffectiveDate])
RETURN
AVERAGEX(
DATESBETWEEN(
        dim_Date[Date],
        DATEADD(LastEffDate, - 5, MONTH), //creates rolling 6 months window and then takes average on [Mom WP] which is  difference between [Ttl WP] and [PreviousMonthWP] and only using months with values.
        ENDOFMONTH(LastEffDate)
        ),
        [Ttl WP]
)

The result I expect is to take average on grouped Month Over Month column for the last 6 months


text:
Q: route to specified number of views in angularjs I am in the process of building a mobile web app with AngularJS. The app will allow the user to record the salary and other figures for employees.
On the first page the user will select the number of employees to be filled for instance 3. When the user clicks next, it will go to employee 1 then next to employee 2 and so on.
The problem is i am having these views do not exist. I will create an augular directive which will contain the elements to be captured for the employee. But then how to route to these views. It should allow to go back as well to edit for any employee.
Any advise is welcome.
Thanks,
Ashley

A: You can have one state with the form and another parameterised state with the employee ID.
$stateProvider .state('contacts.detail',
{
    url: "/contacts/:contactId",
    templateUrl: 'contacts.detail.html',
    controller: function ($stateParams) {
       // If we got here from a url of /contacts/42
       expect($stateParams).toBe({contactId: "42"});
    }
})

From one employee editing state you can navigate to the next employee editing state.
More info/examples: https://github.com/angular-ui/ui-router/wiki/URL-Routing


text:
Q: Creating a button in the maximum size when scrollbars are not visible yet I am trying to create very simple class. The goal is to create a button in the maximum size when scrollbars are not visible yet. My code doesn`t work. The condition pane.getVerticalScrollBar().isVisible() returns true even if the scrollbar is not visible. I wonder why and how can I fix it?
import java.awt.BorderLayout;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {

public static void main(String[] args) throws UnsupportedEncodingException {
    JFrame frame = new JFrame();
    final JButton button = new JButton("Hello");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    final JPanel buttons = new JPanel();
    buttons.add(button);
    buttons.revalidate();
    final JScrollPane pane = new JScrollPane(buttons);
    pane.getViewport().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            System.out.println("*******************************************************************");
            System.out.println("Vertical visible? " + pane.getVerticalScrollBar().isVisible());
            System.out.println("Horizontal visible? " + pane.getHorizontalScrollBar().isVisible());
            if (!pane.getVerticalScrollBar().isVisible() && !pane.getHorizontalScrollBar().isVisible()) {
                button.setSize(button.getWidth() + 1, button.getHeight() + 1);
                buttons.revalidate();
                pane.revalidate();
            } else {
                button.setSize(button.getWidth() - 1, button.getHeight() - 1);
                buttons.revalidate();
                pane.revalidate();
                pane.getViewport().removeChangeListener(this);
            }
        }
    });
    panel.add(pane);
    frame.setContentPane(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
}
}

A: Don't play with the set size method.
If you want the button to occupy all the space available then use either:
frame.add(button); // height/width will be max
frame.add(button, BorderLayout.SOUTH); // only width will be max

Let the layout managers do the job for you.
Edit:

I have another class which scale img in the label and I want to find the best value for scale to make it maximalized as possible

Create a custom panel and dynamically draw the image at the size of the panel. Then it will automatically scale based on the space available.
See Background Panel as an example of this approach.


text:
Q: Where do timers live in matplotlib I am using matplotlib timer objects to register my own update function for an animation.  I can't seem to stop the callbacks once they start though without keeping a reference to the timer object.
It has been my experience thus far that when I create an object in matplotlib I am given a reference to it but it is also added to a list inside some other object (axis in figures, lines in axis etc.) which can then be queried later.  I cannot find where timer objects live however.  My problem can be summarized by this code snippet
import matplotlib.pyplot as plt
import numpy as np

def update():
    plt.get_current_fig_manager().canvas.figure.patch.set_facecolor(str(np.random.random()))
    plt.draw()

def start_animation():
    timer = fig.canvas.new_timer(interval = 50)
    timer.add_callback(update)
    timer.start()

fig = plt.figure()
start_animation()

Run the above code snippet, then try to programmatically stop the flashing.  The function that needs to get called is
timer.remove_callback(update).

To be clear.  I know that I can just keep a reference to a timer object and this problem goes away.  I am looking for an explanation of where this object must be living in matplotlib.

A: how bout
 self.timer =  fig.canvas.new_timer(interval=100)
 ...
 self.timer.remove_callback(...)

to clarify the reference is in a callafter method.
there is no reference stored in your figure or your canvas
you can see this in the backend source
def new_timer(self, *args, **kwargs):
    """
    Creates a new backend-specific subclass of :class:`backend_bases.Timer`.
    This is useful for getting periodic events through the backend's native
    event loop. Implemented only for backends with GUIs.

    optional arguments:

    *interval*
      Timer interval in milliseconds
    *callbacks*
      Sequence of (func, args, kwargs) where func(*args, **kwargs) will
      be executed by the timer every *interval*.
    """
    return TimerTk(self._tkcanvas, *args, **kwargs)

which simply returns a TimerTK instance.  the reference continues to live because the in the TimerTk.start() method you see a callafter that continues to keep the timer from garbage collecting
 class TimerTK(TimerBase):
       ...
       def _timer_start(self):
           self._timer_stop()
           self._timer = self.parent.after(self._interval, self._on_timer)

and that is why every example shows saving your own reference to the timer


text:
Q: match with language R for getting the position I am using match for getting if an element is in a list. For example my list is:
  c("a","b","h","e"...) and so on

if I want to see if element h is in the list I am using match in this way:
  if ("h" %in% v){do something}

How I can get the position of where it finds the element in the list?
Thanks

A: If you want to know the position use which
l <- c("a","b","h","e")
which(l=='h')
[1] 3   # It'll give you the position, 'h' is the third element of 'l'

Note that l is a vector, not a list as you mentioned.

A: If you want to know the position, use match:
l <- c("a","b","h","e")
match("h", l)

It won't make any different here, but generally it will be much faster.

A: The which function would tell you where in a vector an item would "match". The %in% will return a logical vector of the same length as its first argument, and if will only look at the first logical value so will not work well by itself. You could do this:
if( any("h" %in& v) ) { do something }

The any function allows you to "collapse" the result of %in%


text:
Q: Which type of placeholder should I use for PDO for faster performance? From what I've read, the only difference between named placeholders (like :email) and positional placeholders (the ? placeholder) is that you don't need to worry about the order for named placeholders when binding your params later, while with positional, you need to be careful to order your params correctly.
However, I can't seem to find if one actually performs better than the other?
Which should I use for faster performance, or is there no difference?

A: There is no noticeable difference. I'd argue that using named placeholders is actually slightly faster, but that's my opinion. I haven't done any benchmarking on the subject.
Like you said. Named placeholders allow for extra flexibility by not forcing you to remember the order of the parameters.


text:
Q: Lubuntu & GT730 - no output on DVI I'm trying to setup an extended desktop layout: primary output on VGA, extended desktop on HDMI and a mirror of the extended desktop on DVI.
I'm running an 'out of the box' Lubuntu 16.04.4 LTS, the graphics card is an Nvidia GT730 DDR3 (64-bit) which supports three monitors. However I'm getting no joy on the DVI output. I've tested the DVI cable on another machine and there is no issue there.
Short of the DVI port itself being faulty (I need to wait a couple of days for a spare cable to try) what else can I test for?


text:
Q: Why is the need for MySQL database schema? What is the need for a database schema (embedded in the DB) if I can configure my MySQL DB structure and write CRUD statements to work with it directly? I've never worked with these, but I'm assuming they're only for performance optimization?
I know of schema diagrams that can be exported as .sql commands which generate the DB structure, for example with MySQL Workbench.

A: Your question is not totally clear to me. If you are asking about why have an editable graphical representation of the schema, then there is no need for a graphical representation of the structure of a database.
It certainly comes in handy when you have to learn at a glance how a database is laid out or communicate to other people your DB design. And it's sometimes easier to edit the graphical representation instead of using DDL sentences.
If you want to know where in the DB is the schema stored, it is exposed through the standard INFORMATION_SCHEMA tables. Of course the DDL is in the database (else how would the db know how to store the data)

A: Well, you could create every column in your database as VARCHAR(255), but the result will be incredibly slow.
Think about the way the database does the querying: it has an index (think of an index in a dictionary). It looks through the index and finds the right record (the right page in the dictionary). Then, it returns the record.
If the index is small, the lookup is fast - because more "pages" of the index can fit into memory at once (just think about it - isn't it easier to look through the dictionary index if it's 2 pages instead of 500?). So using an integer index for querying is dramatically faster than using a string index.


text:
Q: Difference between "bdo" element and other elements with "dir" attribute? What is the difference between using bdo
<bdo dir="rtl">CIBARA english EMOS</bdo>

and using most tags with dir attribute like
CIBARA english EMOS

I know this question is similar to should i always use bdo for text direction?, but I still do not understand why the use of the dir attribute is "adequate" and bdo is not needed.
Doesn't the dir attribute "override the inherent directionality of letters" anyway? In which instances must I use bdo?

A: Using -
CIBARA english EMOS

Styles applied in Chrome:
span[Attributes Style] {
    direction: rtl;
    unicode-bidi: isolate;
}

Using -
<bdo dir="rtl">CIBARA english EMOS</bdo>

Styles applied in Chrome:
bdo[Attributes Style] {
    direction: rtl;
}

bdo {
    unicode-bidi: bidi-override;
}

So, with the use of <bdo> element, the default value bidi-override is always applied in most browsers and it should work as intended. The use of attribute dir does not seem to be adequate. See below:

<!DOCTYPE html>

This paragraph will go left-to-right.

This paragraph will go right-to-left.

<bdo dir="rtl">This paragraph will go right-to-left.</bdo>


text:
Q: Parsing XML webservice in black berry I need to parse below xml file in black berry
<Vehicles>
    <Car>
        <ID>000001</ID>
        <Make>Audi</Make>
    </Car>
    <Car>
        <ID>000002</ID>
        <Make>Buick</Make>
    </Car>
    <Car>
        <ID>000015</ID>
        <Make>Chevrolet</Make>
    </Car>
    <Car>
        <ID>000003</ID>
        <Make>Chrysler</Make>
    </Car>
</Vehicles>

Can any one pleae tell me how to parse it.

A: Please look into the following posts in stackoverflow.com
Parse XML file on BlackBerry
BlackBerry/J2ME - SAX parse collection of objects with attributes
Note: Please search in stackoverflow.com before post an issue.

A: As a starting point check the "xmldemo" sample app. It is a part of the BB SDK placed on your PC. XMLDemoScreen has an example of a DOM-parser implementaion.


text:
Q: Display Message if num_rows = 0 in php from mysqli prepared-statement I am having an issue trying to get the number of rows from a prepared statement query in php, my query looks as follows:
$DBH = getDBH();
$stmt = $DBH->prepare("SELECT info FROM list WHERE tag = ?");
$stmt->bind_param("s",$tag);
$stmt->execute();
$stmt->bind_result($information);

and i basically just want to say if there is no result returned display "no result returned" can anyone please help?

A: You need to use $statement->store_result() first. Using your code:
$DBH = getDBH();
$stmt = $DBH->prepare("SELECT info FROM list WHERE tag = ?");
$stmt->bind_param("s",$tag);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
$stmt->bind_result($information);

A: I don't recognize the class you are using, but generally I do this:
$sql = "SELECT * FROM dummy WHERE category=13";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0) {
// execute for positive results
} else {
// execute for 0 rows returned.
}

A: $sql = "SELECT * FROM dummy WHERE category=13";
$result = mysqli_query($link, $sql);
$numrows=mysqli_num_rows($result)
if($numrows>0) {
// execute for positive results
} else {
// execute for 0 rows returned.
}


text:
Q: Why is iPhone mail much faster than Mail.app? It is noticeably faster to send and receive mail on my iPhone than on my MacBook, both through a Gmail IMAP account. (I'm still using Leopard, though.) I have a few rules set up in Mail, but it seems like the slowdown on the Mac is in the communication to Google's servers.
Any explanations?

A: From my experience, it seems like the iPhone downloads only headers by default over IMAP while Mail.app may download the full e-mail. This would make syncs appear faster on the iPhone, but take longer to appear when viewed in full.
The iPhone may also be doing more work in the background that you may not realize, and just not displaying progress bars for such work, while you should be able to see all such activity on the macbook app. Logically as long as the connection speed is comparable between the two devices, and both use IMAP, the speeds should be similar.
If you're experiencing an actual slowdown on your Macbook when IMAP is syncing, there may be issues with your setup, but just comparing progress bars to judge speed may be an unfair comparison.

A: I don't use a Mac (I have an iPhone though), so this is just a theory. The iPhone/iPod Touch Mail app is a very light program, because it's slimmed down to fit on the devices. If you compare it's feature list to that of Mail.app, it's very bare. So you have a device that is 33% as fast (3GS)/ 16% as fast (others) as an average computer running an app that does about 2% of the stuff.

A: They are two completely different apps for different OS's and different hardware sets with a different range of features.
They are simlilar, but they technically serve different purposes, so I think it is natural to have performance differences.
Mail on the iphone is meant to be quick and simple with all the basic email needs met. Mail for os x on a full computer has every feature we have available for email and is much more complex code wise. So depending how you use it, it can be a different experience.


text:
Q: Remove Hive partition Locks I have a hive table under a schema with 5 partitions

*

*Country Code (Filled Values KR, CP)

*Organization Code (Filled values GCB, PKR)

*Product Code (CRD,PCL)

*Data Unit (CKI)

*Report Period ()

There are about 9000 partition values, I am trying to unlock a table with the below command
unlock schema.Table-name PARTITION(country_code='KR');

Error that happens is:

Return code 1 from org.apache.hadoop.hive.q1.exec.DDLTask.partion spec {country_code=KR} doesnt contain all (5) partition columns

Can someone provide a query/solution by which I can unlock the table partitions based on a single partition value?

A: 2 years later, but it might still help somebody..
The query is missing the keyword table I think...
The following query is working fine for me:
unlock table database.cs_generator PARTITION(config_id = '247', d_date = '2019-01-25')


text:
Q: Getting content inside tags inside string Here is my string
var a ="
First
Second

";

I need to take the text that is inside render and render1
How can i do this ?
I tried
var a ="
First
Second

";
alert(a.getElementsByTagName("render")[0].innerHTML);

Here is my Fiddle
But i am getting error like

Uncaught TypeError: a.getElementsByTagName is not a function

How can i do this
Note :
This is not content from site, i am trying to get text from other statement, so i am assigning the response to a variable and processing it.
I need to do this only using javascript

A: Strings don't have getElementsByTagName. But you can readily use the browser to parse the string and then use it on the result:

var a = "
First
Second

";
// Create an element to use to parse it
var div = document.createElement('div');
// Parse it
div.innerHTML = a;
// Find all divs in the result and show their innerHTML
Array.from(div.querySelectorAll("div")).forEach(function(div) {
    console.log(div.innerHTML);
});

Naturally you can do more advanced processing within the forEach callback if you want to extract other information.

A: Uncaught TypeError: a.getElementsByTagName is not a function
Yeah, it's not a function in this case, because you're trying to invoke function on string not element. Look at mdn for more clarifications:
https://developer.mozilla.org/pl/docs/Web/API/Element/getElementsByTagName
What's more: 'render' is not a tag anyway. You should use getElementById function to get outer div.


text:
Q: Integrate EasyButton, Geoman with ngx-leaflet I am using raw leaflet.js in my Angular Application which depends on some leaflet plugins like EasyButton, Geoman, Distortable Image. ngx-leaflet looks cool and simple. So I've decided to migrate to ngx-leaflet. But I am sure if it is possible to integrate these plugins with the library. If so provide some guidance.

A: Answering my own question.
Here are the steps I followed to get geoman working with ngx-leaflet.

*

*Install geoman npm i @geoman-io/leaflet-geoman-free. refer geoman github page

*Import geoman css in styles.scss @import '../node_modules/@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css';

*Import geoman in the component import '@geoman-io/leaflet-geoman-free';
Done.
then use it like this
this.map.pm.addControls({
      position: 'topleft',
      drawCircle: false,
      drawCircleMarker: false,
      drawPolyline: true,
      drawRectangle: false,
      drawPolygon: true,
      editMode: false,
      dragMode: false,
      cutPolygon: false,
      removalMode: false,
      drawMarker: false
    });

A: I am trying this integration, but I cannot find any typifications for Geoman.
In my project, I use @asymmetrik/ngx-leaflet and follow the documentation to access the map reference.
I wrote a component and within the call onMapReady, map.pm stops the construction of my application.
I get this error: The property 'pm' does not exist in type 'Map'.
import { Component, OnInit } from '@angular/core';
import * as L from 'leaflet';
import '@geoman-io/leaflet-geoman-free';
@Component({
  selector: 'app-main-map',
  templateUrl: './main-map.component.html',
  styleUrls: ['./main-map.component.css']
})
export class MainMapComponent implements OnInit {

    aMarker = L.marker([ -23.95, -46.38 ], {
              icon: L.icon({
                  iconSize: [ 25, 41 ],
                  iconAnchor: [ 13, 41 ],
                  iconUrl: 'assets/marker-icon.png',
                  shadowUrl: 'assets/marker-shadow.png'
              })
          });
    constructor() { }

    ngOnInit(): void {
    }

    onMapReady(map: L.Map) {
        this.aMarker.addTo(map);
        map.pm.addControls({
          position: 'topleft',
          drawCircle: false,
          drawCircleMarker: false,
          drawPolyline: true,
          drawRectangle: false,
          drawPolygon: true,
          editMode: false,
          dragMode: false,
          cutPolygon: false,
          removalMode: false,
          drawMarker: false
        });
    }

}

I know it's not the best, but the temporary solution is to use bracket notation. It works on my Angular 10 project.
// The same code as above, but with bracket notation.
onMapReady(map: L.Map) {
    this.aMarker.addTo(map);

    map["pm"]["addControls"]({
      position: 'topleft',
      drawCircle: true,
      drawCircleMarker: true,
      drawPolyline: true,
      drawRectangle: true,
      drawPolygon: true,
      editMode: true,
      dragMode: true,
      cutPolygon: true,
      removalMode: true,
      drawMarker: true
    });
}

While I can't find a better solution or time to create typings for Geoman, I use it like this.
I hope it is useful to anyone.

A: This worked for me in Angular 8 project:

*

*npm i @geoman-io/leaflet-geoman-free

*In your component

*

*import '@geoman-io/leaflet-geoman-free';

*import 'style-loader!@geoman-io/leaflet-geoman-free/dist/leaflet-geoman.css';


text:
Q: Mavericks lock screen doesn't show screen saver Prior to upgrading to Mavericks, when I chose to lock my MacBook Pro's screen, it would do so with my screen saver options (rotate through images in a folder, and show a clock). However, when I go to lock my screen now, it's simply a black screen.
Is there a way to make Mavericks use my screen saver settings when I choose to lock my screen as with older versions of OS X?

A: Check system preference -> Security & Privacy -> General-> Require password XXX after sleep or screen saver begins

A: Set one of the hot corners to start the screen safer.
The lock sends the display to sleep in mavericks - there's no option to change it afaik


text:
Q: infinite precision integers: division by 2 In C, if I want to divide an int by 2, x%2 should run as fast as (x%10)% 2
because a good compiler will just look at the last bit. But what about in a language with infinite precision arithmetic?
In particular, in Haskell which would be faster (or would they be the same speed): even x or even (quot x 10)?

A: Okay, I'll bite:
import Control.DeepSeq
import Criterion.Main
import Data.Bits
import System.Random

lotsOfBigNumbers :: [Integer]
lotsOfBigNumbers = take 10000 $ randomRs (2^128, 2^132) (mkStdGen 42)

evenRem, evenBits :: Integer -> Bool
evenRem  x = even (x `rem` 10)
evenBits x = (x .&. 1) == 0
remRem   x = ((x `rem` 10) `rem` 2) == 0

main = do
    deepseq lotsOfBigNumbers (return ())
    defaultMain
        [ bench "even"     $ nf (map even    ) lotsOfBigNumbers
        , bench "evenRem"  $ nf (map evenRem ) lotsOfBigNumbers
        , bench "evenBits" $ nf (map evenBits) lotsOfBigNumbers
        , bench "remRem"   $ nf (map remRem  ) lotsOfBigNumbers
        ]

And the results:
sorghum:~/programming% ghc -O2 test && ./test
[1 of 1] Compiling Main             ( test.hs, test.o )
Linking test ...
warming up
estimating clock resolution...
mean is 1.920340 us (320001 iterations)
found 51108 outliers among 319999 samples (16.0%)
  46741 (14.6%) low severe
  4367 (1.4%) high severe
estimating cost of a clock call...
mean is 83.20445 ns (16 iterations)
found 4 outliers among 16 samples (25.0%)
  2 (12.5%) low mild
  2 (12.5%) high severe

benchmarking even
mean: 1.508542 ms, lb 1.503661 ms, ub 1.514950 ms, ci 0.950
std dev: 28.53574 us, lb 23.35796 us, ub 35.19769 us, ci 0.950
found 18 outliers among 100 samples (18.0%)
  17 (17.0%) high severe
variance introduced by outliers: 11.371%
variance is moderately inflated by outliers

benchmarking evenRem
mean: 1.937735 ms, lb 1.930118 ms, ub 1.949699 ms, ci 0.950
std dev: 48.17240 us, lb 34.95334 us, ub 71.22055 us, ci 0.950
found 14 outliers among 100 samples (14.0%)
  3 (3.0%) high mild
  11 (11.0%) high severe
variance introduced by outliers: 18.989%
variance is moderately inflated by outliers

benchmarking evenBits
mean: 996.3537 us, lb 992.2839 us, ub 1.003864 ms, ci 0.950
std dev: 27.37875 us, lb 17.51923 us, ub 43.98499 us, ci 0.950
found 15 outliers among 100 samples (15.0%)
  2 (2.0%) high mild
  13 (13.0%) high severe
variance introduced by outliers: 21.905%
variance is moderately inflated by outliers

benchmarking remRem
mean: 1.925495 ms, lb 1.918590 ms, ub 1.935869 ms, ci 0.950
std dev: 43.00092 us, lb 31.67173 us, ub 57.83841 us, ci 0.950
found 13 outliers among 100 samples (13.0%)
  13 (13.0%) high severe
variance introduced by outliers: 15.198%
variance is moderately inflated by outliers

Conclusion: an extra rem costs a bit more, and .&. costs a bit less.


text:
Q: SAP Business Objects Webi: same report but the output changes based on the username SAP Business Objects Webi:
Assume there is a report ABC.wid. Am trying to achieve the following: When a user x logins, he should get data in line chart in ABC.wid. When a user y logins, he should get data in horizontal table in ABC.wid. So its the same report but the output changes based on the username. Is there a possibility of getting this done in SAP BO 4.2.?

A: Create both Chart and Table in the report, then in table/chart properties configure it to hide based on the CurrentUser() value

A: I have not done this myself, but I think you should be able to do this using a "Publication". Check this out...
https://wiki.scn.sap.com/wiki/display/BOBJ/Personalization+in+SAP+Business+Intelligence+4.0+Web+Intelligence+Publications
Noel


text:
Q: IntelliJ IDEA 15 - How to migrate task history between projects? I have been using IntelliJ IDEA 15 for close to a year now, and using the same project this whole time, where I have created Tasks to basically act as workspaces for various work assignments so I can group files I've touched based on the assignment title. I've recently had an issue in my project workspace where I am basically being forced to create a new workspace, and thus a new project in IntelliJ. The problem is that this new project has none of my Task history in it.
Does anyone know if it's possible, and if so, how, to migrate this Task history from one project to another?
Thanks in advance!

A: Tasks are saved in YOUR_PROJECT/.idea/workspace.xml so you can backup this file and if needed you can just copy and paste these lines defining tasks to the other workspace.xml file. This is the example of one:
<configuration default="false" name="my-debug-task" type="JavascriptDebugType" factoryName="JavaScript Debug" uri="http://localhost:4200">
      <mapping url="webpack:////home/marcin/Sprawozdania/Inzynierka/sqap/sqap-ui/src" local-file="$PROJECT_DIR$/sqap-ui/src" />
      <mapping url="webpack:////home/marcin/Sprawozdania/Inzynierka/sqap/sqap-ui" local-file="$PROJECT_DIR$/sqap-ui" />
      <method />
    </configuration>

Addittionaly In workspace.xml you need to add reference of copied task to:
 <project>
     <component>
         <list>

like here :
<list size="3">
      <item index="0" class="java.lang.String" itemvalue="JavaScript Debug.my-debug-task" />
      <item index="1" class="java.lang.String" itemvalue="JavaScript Debug.Unnamed" />
      <item index="2" class="java.lang.String" itemvalue="Maven.config start -devs" />
</list>


text:
Q: water is a liquid vs water is liquid A little backstory here. Someone tried to school me on the internet when I made a comment about how something was a liquid. My direct quote was: "Cats are a liquid"
Now immediately someone replied with the following language lesson:
I get the point he makes with Air, Rice or Water, but if you want to specify an aggregation state of a substance, or in this particular case a creature, wouldn't that be correct usage?


text:
Q: How to simulate the Out Of memory : Requested array size exceeds VM limit I used the Out Of Memory help from sun's site. Where it is quoted as

Out Of Memory : Requested array size exceeds VM limit
This indicates that the application attempted to allocate an array that is larger than the heap size. For
example, if an application tries to allocate an array of 512MB but the maximum heap size is 256MB,
then this error will be thrown. In most cases the problem is likely to be either that the heap size is too
small or that a bug results in the application attempting to create an array whose size is calculated to
be incorrectly huge.

I tried to simulate this by
import java.util.ArrayList;
import java.util.List;

public class JavaTest {
    public static void main(String[] args){
        long[] ll = new long[64*1024*1024];
    }
}

on my machine with
javac *.java;java -Xmx256m JavaTest

But the above line is producing

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at JavaTest.main(JavaTest.java:7)

What am I missing?
Update :
My java version is

$java -version
java version "1.6.0_15"
Java(TM) SE Runtime Environment (build 1.6.0_15-b03)
Java HotSpot(TM) Server VM (build 14.1-b02, mixed mode)

A: For me
long[] l = new long[Integer.MAX_VALUE];

yields Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit

PS: if you need to produce the exception for the purpose of testing, you could also just throw new OutOfMemoryError("Requested array size exceeds VM limit") yourself.

A: The array is allocated as continous heap space and memory can get fragmented due to object allocaion and garbage collection. The out of memory error occurs due to lack of a solid block of memory to allocate the array. Did you sent the JVM memory explicitly with -Xmx flag ?

A: Try allocating, say, an ArrayList and to double its size run-time.

A: Just looking at example fo people have the problem it seems to occur when people are using the java native interface, bridge between C++ applications.
When running pure java application the standard procedure seems for allocating an array is calculate the bytes needed from the size variable passed in the array deceleration throwing an java.lang.OutOfMemoryError: Java heap space exception.
When the array is created outside the JVM it looks it generates this other exception. I'm sure there is some technical reason for this different behavior.
You could try replicating the problem this person describes on this other forum.


text:
Q: Right way to get ethereum ERC-20 tokens information Can somebody tell me the right way to get info (decimals count, name and symbol) of the ERC-20 token from the Ethereum blockchain?
I supposed that it could be done through the calls of the appropriate functions decimals(), name(), symbol() to the contract address of the exact token via ABI construction (if user web3js library). And in many cases it can be done such way. But unfortunatelly that's not for all cases. For example, there's a token with address:
0xb5a5f22694352c15b00323844ad545abb2b11028
If we read contract info about this token on etherscan's webpage, there's no any info written in the contract public variables name, symbol, and decimals:
https://etherscan.io/address/0xb5a5f22694352c15b00323844ad545abb2b11028#readContract
But etherscan knows the name and symbol of this token (ICON (ICX)). Moreover there's another website that can get info about decimals count for this token:
https://api.ethplorer.io/getTokenInfo/0xb5a5f22694352c15b00323844ad545abb2b11028?apiKey=freekey
So the question is: is there any universal way to get decimals, name and symbol for the exact token (e.g 0xb5a5f22694352c15b00323844ad545abb2b11028) via blockchain calls or not? And how etherscan and ethplorer.io website can handle such calculations?
Hope somebody can help with my question. Thanks in advance!

A: The token provider interface spec says that those 3 methods are optional. It means that you can't expect every token contract to implement those. I guess that you have to have workarounds for those contracts which are not compatible with the standard.
For the https://etherscan.io/address/0xb5a5f22694352c15b00323844ad545abb2b11028#readContract if you look at the source code, the contract name is contract IcxToken, that's at least one way to identify it.


text:
Q: Multiple random values between specific ranges in R? I want to pick up 50 samples from (TRUNCATED) Normal Distribution (Gaussian) in a range 15-85 with mean=35, and sd=30. For reproducibility:
num = 50 # number of samples
rng = c(15, 85) # the range to pick the samples from
mu = 35 # mean
std = 30 # standard deviation

The following code gives 50 samples:
rnorm(n = num, mean = mu, sd = std)

However, I want these numbers to be strictly between the range 15-85. How can I achieve this?
UPDATE: Some people made great points in the comment section that this problem can not be solved as this will no longer be Gaussian Distribution. I added the word TRUNCATED to the original post so it makes more sense (Truncated Normal Distribution).

A: As Limey said in the comments, by imposing a bounded region the distribution is no longer normal. There are several ways to achieve this.
library("MCMCglmm")
rtnorm(n = 50, mean = mu, sd = std, lower = 15, upper = 85)

is one method. If you want a more manual approach you could simulate using uniform distribution within the range and apply the normal distribution function
bounds <- c(pnorm(15, mu, std), pnorm(50, mu, std))
samples <- qnorm(runif(50, bounds[1], bounds[2]), mu, std)

The idea is very basic: Simulate the quantiles of the outcome, and then estimate the value of the specific quantive given the distribution. The value of this approach rather than the approach linked by GKi is that it ensures a "normal-ish" distribution, where simulating and bounding the resulting vector will cause the bounds to have additional mass compared to the normal distribution.
Note the outcome is not normal, as it is bounded.