text:
Q: how to access a variable from a class using php extension? I am working in c++ under ubuntu. I have the following example:
[car.h]
#ifndef VEHICLES_CAR_H
#define VEHICLES_CAR_H

// A very simple car class
class Car {
public:
    Car();
    void shift(int gear);
    bool accelerate();
    void brake();
    int getCurrentSpeed();
    int getCurrentGear();
public:
    int maxGear;
    int currentGear;
    int speed;
};

#endif /* VEHICLES_CAR_H *

/
[car.cc]
#include "car.hpp"
#include "car2.hpp"
#include "car2.cc"
#include "car3.h"
#include "car3.cc"
#include <stdio.h>
#include <iostream>
using namespace std;

Car::Car() {

}

void Car::shift(int gear) {
    if (gear < 1 || gear > maxGear) {
        return;
    }
    currentGear = gear;
}
bool Car::accelerate() {
    speed = 10;
    if (speed == 10) return true;
    else return false;
}

void Car::brake() {
    speed -= (5 *5);
}

int Car::getCurrentSpeed() {
    Hello h; //this is in another class...it's working ok
    h.say_hello();
    speed=5;
    return speed;
}

int Car::getCurrentGear() {
    return currentGear;
}

[vehicles.cc]
#include "php_vehicles.h"
#include "car.hpp"

zend_object_handlers car_object_handlers;

struct car_object {
    zend_object std;
    Car *car;
};

zend_class_entry *car_ce;

void car_free_storage(void *object TSRMLS_DC)
{
    car_object *obj = (car_object *)object;
    delete obj->car;

    zend_hash_destroy(obj->std.properties);
    FREE_HASHTABLE(obj->std.properties);

    efree(obj);
}

zend_object_value car_create_handler(zend_class_entry *type TSRMLS_DC)
{
    zval *tmp;
    zend_object_value retval;

    car_object *obj = (car_object *)emalloc(sizeof(car_object));
    memset(obj, 0, sizeof(car_object));
    obj->std.ce = type;

    ALLOC_HASHTABLE(obj->std.properties);
    zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
    zend_hash_copy(obj->std.properties, &type->default_properties,
        (copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));

    retval.handle = zend_objects_store_put(obj, NULL,
        car_free_storage, NULL TSRMLS_CC);
    retval.handlers = &car_object_handlers;

    return retval;
}

PHP_METHOD(Car, __construct)
{
    long maxGear;
    Car *car = NULL;
    zval *object = getThis();

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "", NULL) == FAILURE) {
        RETURN_NULL();
    }

    car = new Car();
    car_object *obj = (car_object *)zend_object_store_get_object(object TSRMLS_CC);
    obj->car = car;

}
PHP_METHOD(Car, shift)
{
}
PHP_METHOD(Car, accelerate)
{
    Car *car;
    car_object *obj = (car_object *)zend_object_store_get_object(
        getThis() TSRMLS_CC);
    car = obj->car;
    if (car != NULL) {
       RETURN_BOOL( car->accelerate());
       RETURN_LONG(car->speed);
    }

}
PHP_METHOD(Car, brake)
{
}
PHP_METHOD(Car, getCurrentSpeed)
{
    Car *car;
    car_object *obj = (car_object *)zend_object_store_get_object(
        getThis() TSRMLS_CC);
    car = obj->car;
    if (car != NULL) {
        RETURN_LONG(car->getCurrentSpeed());
    }
    RETURN_NULL();

}
PHP_METHOD(Car, getCurrentGear)
{
}

function_entry car_methods[] = {
    PHP_ME(Car,  __construct,     NULL, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR)
    PHP_ME(Car,  shift,           NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Car,  accelerate,      NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Car,  brake,           NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Car,  getCurrentSpeed, NULL, ZEND_ACC_PUBLIC)
    PHP_ME(Car,  getCurrentGear,  NULL, ZEND_ACC_PUBLIC)
    {NULL, NULL, NULL}
};

PHP_MINIT_FUNCTION(vehicles)
{
   zend_class_entry ce;
    INIT_CLASS_ENTRY(ce, "Car", car_methods);
    car_ce = zend_register_internal_class(&ce TSRMLS_CC);
    car_ce->create_object = car_create_handler;
    memcpy(&car_object_handlers,
        zend_get_std_object_handlers(), sizeof(zend_object_handlers));
    car_object_handlers.clone_obj = NULL;
    return SUCCESS;

}

zend_module_entry vehicles_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
    STANDARD_MODULE_HEADER,
#endif
    PHP_VEHICLES_EXTNAME,
    NULL,        /* Functions */
    PHP_MINIT(vehicles),        /* MINIT */
    NULL,        /* MSHUTDOWN */
    NULL,        /* RINIT */
    NULL,        /* RSHUTDOWN */
    NULL,        /* MINFO */
#if ZEND_MODULE_API_NO >= 20010901
    PHP_VEHICLES_EXTVER,
#endif
    STANDARD_MODULE_PROPERTIES
};

#ifdef COMPILE_DL_VEHICLES
extern "C" {
ZEND_GET_MODULE(vehicles)
}
#endif

[php_vehicles.h]
  #ifndef PHP_VEHICLES_H
#define PHP_VEHICLES_H

#define PHP_VEHICLES_EXTNAME  "vehicles"
#define PHP_VEHICLES_EXTVER   "0.1"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef __cplusplus
extern "C" {
    #endif
#ifdef ZTS
#include "TSRM.h"
#endif
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
    #endif
#include "php.h"

#ifdef __cplusplus
}
#endif

extern zend_module_entry vehicles_module_entry;
#define phpext_vehicles_ptr &vehicles_module_entry;

#endif /* PHP_VEHICLES_H */

[config.m4]
    PHP_ARG_ENABLE(vehicles,
    [Whether to enable the "vehicles" extension],
    [  --enable-vehicles      Enable "vehicles" extension support])

if test $PHP_VEHICLES != "no"; then
    PHP_REQUIRE_CXX()
    PHP_SUBST(VEHICLES_SHARED_LIBADD)
    PHP_ADD_LIBRARY(stdc++, 1, VEHICLES_SHARED_LIBADD)
    PHP_NEW_EXTENSION(vehicles, vehicles.cc car.cc, $ext_shared)
fi

[test.php]
<html>
    <head>
        <title>MY FIRST PHP EXTENSION</title>
    </head>
    <body>
<?php

$car = new Car();
echo "FIRST RESULT: ".$car->getCurrentSpeed()." ";  // prints '0'
//echo "CAR IS: ".$car->accelerate();
if ($car->accelerate() == True) { echo "IT IS TRUE AND SPEED IS: ". $car->$speed;}

//echo "SECOND RESULT: ". $car->getCurrentSpeed()." "; // prints '5'
?>

    </body>
</html>

I have the following error at line $car->$speed:  Undefined variable: speed in /home/test.php on line 13
PHP Fatal error:  Cannot access empty property

WHY? How to solve this? thx ! appreciate

A: Change $car->$speed to $car->getCurrentSpeed():
if ($car->accelerate() == True) { echo "IT IS TRUE AND SPEED IS: ". $car->getCurrentSpeed();}

A: Calling $car->$speed property you should firs define $speed variable.
$speed = 'speed'; // You should define this in PHP code before calling $car->$speed
Calling $car->$speed assumes that you call $car->speed because $speed defined as 'speed'.
It's PHP part of the code.
Or you can simply call $car->speed if you need to access the 'speed' property of $car object


text:
Q: Config key not found : Where does typesafe ConfigFactory.load look for config files in a scala multi-project? When I run sbt test on the complete multi-project, I keep getting config key not found when it is clearly there in the resource folder corresponding to the test. Everything works fine when I run the tests with intellij.
I followed this to setup the project : https://www.scala-sbt.org/0.13/docs/Multi-Project.html
The following is the structure :
root(main project)
- util
- api(depends on util)
- consumer(depends on util)

*

*There are no tests in root project. All its config is in 'main' folder resources.

*'api' and 'consumer' modules have their own tests and their own resources containing config files.

*Some of these tests have objects which needs to read config and are not able to find them.

A: It will first look into the module from where you are running the test and there is finding conf which doesn't contains your config key. When you run from intellij that time you are in same module so it can pick the configuration. You can provide the path of the configuration file while loading the configuration and it can solve your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Правильное условие для RegExp. (vk чат бот) Пишу чат бота для вк. Библиотека - node-vk-bot-api
Есть проблема, например у бота есть "команда", или он "слушает" определенное слово:
bot.event(/^(помощь)/i, function(ctx) {
 блаблабла
})

Из регулярки следует - что важно, чтобы слово "помощь" было первым и не имеет значения регистр.
Но если у меня есть другая команда "помощь 2", то она игнорируется, т.к. бот уже
нацелен на функцию выше.
Пробовал сделать через
 bot.command(/^(помощь)/i, function(ctx) {
     блаблабла
    })
bot.command(/^(помощь 2)/i, function(ctx) {
     блаблабла
    })

результат аналогичен
Вопрос: Можно ли в регулярном выражении задать такой параметр, чтобы метод реагировал только в том случае, если это вообще единственное слово в строке?
Думал над вариантом, что если бот находит слово помощь, то дальше определяет есть ли в строке дополнительные слова которые могут перенаправить на другую функцию. Но решил что метод грязноват.
Есть ли другие способы это обойти?
Заранее спасибо!

A: Попробуйте со знаком конца строки: /^(помощь)$/i


text:
Q: CTAN package does not appear in TexLive utility I want to install this package from CTAN, but I can't find it through the TexLive Utility. Why would it not appear, and what can I do about it?
(If it's relevant, I'm using MacTex.)


text:
Q: How to expose a function in svelte that can accept parameters to render? I'm pretty new to svelte, and for my use case I would like to export the svelte app as a bundle.js which exposes a function let's say startApp(positionInject, appConfiguration) that can accept 2 parameters (positionInject is the app injection position eg: .app, appConfiguration is the initial configuration of the app to start), based on those parameters svelte app start renders.
I am wondering, this is possible in svelte?
Appreciate any help.

A: Every Svelte component takes a target element and props as constructor parameters. You can wrap the construction in a function:
import App from './App.svelte';

export function startApp(selector, props) {
  const target = document.querySelector(selector)

  return new App({
    target,
    props
  })
}

And you can call it like this:
import {startApp} from "./bundle.js"

startApp(".my-app", {config: ...})


text:
Q: Requested registry access is not allowed #2 I've recently been writing an application that needs access to the following registry key :

HKLM\SOFTWARE\Wow6432Node\Classes\CLSID

For some odd reason, I'm not allowed access to this key on any system I've tested on. I'm using administrative rights and everything in between to attempt to accomplish this. I've searched through the first 5 Google result pages and still turned up empty.
Things to note :
1. The keys I'm attemping to delete may or may not contain subkeys, I've thoroughly tested "DeleteSubKey" and "DeleteSubKeyTree".
2. I've tried OpenSubKey("Key",True), both false and true values still disallowed me access.
3. I'm also not allowed access to the non-64 bit location (HKLM\Software\Classes\CLSID).
4. I've tested this on XP, 7 & 8. XP didn't give me an issue.

5. The exact error I'm receiving can be found below :

Requested registry access is not allowed.   at
  Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)

PLEASE help me..this has been killing me for a few days now. Any help is greatly appreciated.

A:    Microsoft.Win32.RegistryKey m_RegEntry = Microsoft.Win32.Registry.LocalMachine;
   m_RegEntry = m_RegEntry.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4D36E96D-E325-11CE-BFC1-08002BE10318}");
        //string
        int i = 0;
        string[] m_szModemEntries = m_RegEntry.GetSubKeyNames();

This return many entries connected Devices to COM port . and an entry of "Properties" that we don't need to access.
below I am attaching a simple code to work with it.
            string[] m_szModem;
            Microsoft.Win32.RegistryKey m_RegEntry = Microsoft.Win32.Registry.LocalMachine;
            m_RegEntry = m_RegEntry.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4D36E96D-E325-11CE-BFC1-08002BE10318}");
            //string
            int i = 0;
            string[] m_szModemEntries = m_RegEntry.GetSubKeyNames();
            m_szModem = new string[m_szModemEntries.Length];
            string m_szModemPort = null;
            string m_szModemName = null;
            foreach (string m_szModemEntry in m_szModemEntries)
            {
                if (!IsNumber(m_szModemEntry))
                {
                }
                else
                {
                    m_RegEntry.Close();
                    m_RegEntry = Microsoft.Win32.Registry.LocalMachine;
                    string m_szKeyName = @"SYSTEM\CurrentControlSet\Control\Class\{4D36E96D-E325-11CE-BFC1-08002BE10318}\" + m_szModemEntry;
                    m_RegEntry = m_RegEntry.OpenSubKey(m_szKeyName);
                    m_szModemPort = m_RegEntry.GetValue("AttachedTo").ToString();
                    m_szModemName = m_RegEntry.GetValue("Model").ToString();
                    if (m_szModemName.Contains("<device name>"))
                    {
                        CommPort = m_szModemPort;
                        lbldevicename.Text = "Device connected!";
                        lbldevicename.ForeColor = Color.Green;
                        cmdProgram.Enabled = true;
                        DeviceConnected = true;
                        break;
                    }
                    CommPort = "";
                    cmdProgram.Enabled = false;
                    lbldevicename.Text = "Device not connected!";
                    lbldevicename.ForeColor = Color.Red;
                    DeviceConnected = false;
                }
            }

//and IsNumber Function
public Boolean IsNumber(String s)
    {
        foreach (Char ch in s)
        {
            if (!Char.IsDigit(ch)) return false;
        }
        return true;
    }

A: You may need to modify the access control security. Use GetAccessControl to get the ACL for the registry key, modify it, and then save it with SetAccessControl.

A: Here's a solution I've found which works without Admin rights: just leave out the 'true' paramter, and it will read it all. Worked for me!

A: First login with Local Admin account. Then run regedit.exe and click on the registry key to be edited. From the Edit menu select premissions. Check the permissions of the related user.
I guess related accounts do not have permission to modify the registry key.

A: in vb.net you can use this to get access of the key before doing any operation on it
x.GetAccessControl(System.Security.AccessControl.AccessControlSections.All)

where x is any reg. key
after seeing your code i tried this and it works
  Dim r As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\test", Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree)
           r.DeleteSubKey("subkey", True)

A: Add an app.manifest in Visual studio

add item then search for application manifest file

then Replace the start of it until   with this
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
</requestedPrivileges>
</security>
</trustInfo>


text:
Q: Time, space complexity for my JS anagram map solution The current setup, A and B could be larger anagrams but I chose a simple example here.
The goal is to find an index mapping P, from A to B. A mapping P[i] = j means the [n]th element in A appears in B at index j.
const A = [12, 28, 46, 32, 50]
const B = [50, 12, 32, 46, 28]

const hash = B.reduce((acc,cur,idx) => ({ ...acc, [cur]: idx }), {});

const result = A.reduce((acc,cur) => [...acc, hash[cur]], []);

return result

The result should be
[1, 4, 3, 2, 0]

What I think the time/space complexity for my solution is:
hash: time = O(a), space = O(c)
result: time = O(b), space = O(d)
Final answer is time = O(a + b), space = O(c + d)
Final final answer for time and space is O(n)?
Even though the result is being generated using time O(1) because of the hash, overall I think the time is O(n) cause n is the numbers. Am I correct in thinking this?
What is everyone thought on this? (If I'm right or wrong, not sure).
I figured some of you would ask why not use indexOf(), from my research, it looks like under the hood its a loop so I would be running O(2n). So medium to large size anagrams would be fatal.

A: The spread operator (...acc) is an O(n) operation over the object being spread. This hits your time complexity quite a bit.
Also, since A and B are anagrams you can use the same symbol n for both as they will have the same length.
I'm not sure about space complexity but I think the time complexity will be:
hash: time = O(n^2)
result: time = O(n^2)
Final answer is time = O(2n^2) which is ~O(n^2).

Suggested improvements:

*

*Don't use spread operator, it's unnecessary and slow.

*Array.map instead of Array.reduce for the result is much cleaner

*hash isn't hashing anything so the name is unclear, it's more of a mapping of numbers to indices - map is more clear

const A = [12, 28, 46, 32, 50]
const B = [50, 12, 32, 46, 28]

const map = B.reduce((acc,cur,idx) => { acc[cur] = idx; return acc; }, {});
const result = A.map(cur => map[cur]);

console.log(result);

This version is a pretty straightforward O(2n) -> ~O(n).


text:
Q: How do I add a new page from a NextJS app to an AWS Amplify application? I added a new page in src/pages/foo.tsx in my NextJS app
I can load the page fine if i go to http://localhost:3000/foo
However, when I push it to my Amplify app, the page doesn't load.
I have tried updating my routes in the Amplify console but can't get it to load
I see a directory for this page in my out directory:
out/foo/index.html
but if i try to go to that path it still doesn't load
This is my next.config.js
/* eslint-disable import/no-extraneous-dependencies */
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({
  poweredByHeader: false,
  trailingSlash: true,
  basePath: '',
  // The starter code load resources from `public` folder with `router.basePath` in React components.
  // So, the source code is "basePath-ready".
  // You can remove `basePath` if you don't need it.
  reactStrictMode: true,
});

Can anyone help please?
Thank you

A: Did you use getStaticProps function inside foo.tsx? It looks like your page is already there but it is not revalidated yet. Try changing the time of revalidate property inside getStaticProps. You can check documentation over here https://nextjs.org/docs/api-reference/data-fetching/get-static-props#revalidate


text:
Q: Переключение между интерфейсами Появилась необходимость "изменять" содержимое моего GUI окна на PtQt5.
from PyQt5 import QtCore, QtGui, QtWidgets
import sys, res, datetime, time

weekend = ["Empty", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресенье"]
month = ["Empty", "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"]

class mainWindow(object):
    def Ui_Form(self, Form):
        self.show_current_time()
        Form.setObjectName("Form")
        Form.resize(960, 616)
        Form.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        Form.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.widget = QtWidgets.QWidget(Form)
        self.widget.setGeometry(QtCore.QRect(20, 30, 910, 560))
        self.widget.setObjectName("widget")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setGeometry(QtCore.QRect(10, 10, 890, 540))
        self.label.setStyleSheet("border-image: url(:/images/kpk.png);\n"
"border-radius: 20px;")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setGeometry(QtCore.QRect(120, 115, 670, 61))
        font = QtGui.QFont()
        font.setPointSize(48)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.widget)
        self.label_3.setGeometry(QtCore.QRect(120, 173, 671, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.widget)
        self.pushButton.setGeometry(QtCore.QRect(148, 277, 50, 50))
        self.pushButton.setStyleSheet("border-image: url(:/images/protokolico.png);\n"
"border-radius: 10px;")
        self.pushButton.setText("")
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.protokol)
        self.label_4 = QtWidgets.QLabel(self.widget)
        self.label_4.setGeometry(QtCore.QRect(138, 326, 61, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        font.setStyleStrategy(QtGui.QFont.PreferDefault)
        self.label_4.setFont(font)
        self.label_4.setMouseTracking(False)
        self.label_4.setTabletTracking(False)
        self.label_4.setAcceptDrops(False)
        self.label_4.setAutoFillBackground(False)
        self.label_4.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_4.setScaledContents(False)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setWordWrap(True)
        self.label_4.setObjectName("label_4")
        self.pushButton_2 = QtWidgets.QPushButton(self.widget)
        self.pushButton_2.setGeometry(QtCore.QRect(819, 264, 40, 40))
        self.pushButton_2.setStyleSheet("border-image: url(:/images/zero.png);")
        self.pushButton_2.setText("")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.setMainWindow)
        self.pushButton_3 = QtWidgets.QPushButton(self.widget)
        self.pushButton_3.setGeometry(QtCore.QRect(224, 277, 50, 50))
        self.pushButton_3.setStyleSheet("border-image: url(:/images/database.png);")
        self.pushButton_3.setText("")
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.clicked.connect(self.DataBase)
        self.label_5 = QtWidgets.QLabel(self.widget)
        self.label_5.setGeometry(QtCore.QRect(219, 326, 61, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        font.setStyleStrategy(QtGui.QFont.PreferDefault)
        self.label_5.setFont(font)
        self.label_5.setMouseTracking(False)
        self.label_5.setTabletTracking(False)
        self.label_5.setAcceptDrops(False)
        self.label_5.setAutoFillBackground(False)
        self.label_5.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_5.setScaledContents(False)
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setWordWrap(True)
        self.label_5.setObjectName("label_5")
        self.pushButton_4 = QtWidgets.QPushButton(self.widget)
        self.pushButton_4.setGeometry(QtCore.QRect(306, 277, 50, 50))
        self.pushButton_4.setStyleSheet("border-image: url(:/images/koap.png);\n"
"border-radius: 10px;")
        self.pushButton_4.setText("")
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.Koap)
        self.label_6 = QtWidgets.QLabel(self.widget)
        self.label_6.setGeometry(QtCore.QRect(300, 324, 61, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        font.setStyleStrategy(QtGui.QFont.PreferDefault)
        self.label_6.setFont(font)
        self.label_6.setMouseTracking(False)
        self.label_6.setTabletTracking(False)
        self.label_6.setAcceptDrops(False)
        self.label_6.setAutoFillBackground(False)
        self.label_6.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_6.setScaledContents(False)
        self.label_6.setAlignment(QtCore.Qt.AlignCenter)
        self.label_6.setWordWrap(True)
        self.label_6.setObjectName("label_6")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_2.setText(_translate("Form", ""))
        self.label_3.setText(_translate("Form", ""))
        self.label_4.setText(_translate("Form", "Составить протокол"))
        self.label_5.setText(_translate("Form", "База данных"))
        self.label_6.setText(_translate("Form", "КоАП"))

    def protokol(self):
            print("Составить протокол")

    def setMainWindow(self):
            print("MainWindow")

    def DataBase(self):
            print("База данных")

    def Koap(self):
            print("КоАП РФ")

    def show_current_time(self):
        current_datetime = datetime.datetime.now()
        daynow = weekend[datetime.datetime.today().isoweekday()]
        monthnow = month[current_datetime.month]
        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(lambda: self.label_2.setText(QtCore.QTime.currentTime().toString("hh:mm")))
        self.timer.timeout.connect(lambda: self.label_3.setText(f"{daynow}, {current_datetime.day} {monthnow}"))
        self.timer.start()

if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        Form = QtWidgets.QWidget()
        ui = mainWindow()
        ui.Ui_Form(Form)
        Form.show()
        sys.exit(app.exec_())

Нужно, чтобы при нажатии на кнопку с функцией protokol открывался новый интерфейс с кодом:
class Protokol(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(960, 616)
        self.widget = QtWidgets.QWidget(Form)
        self.widget.setGeometry(QtCore.QRect(20, 30, 910, 560))
        self.widget.setObjectName("widget")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setGeometry(QtCore.QRect(10, 10, 890, 540))
        self.label.setStyleSheet("border-image: url(:/images/kpk.png);\n"
"border-radius: 20px;")
        self.label.setText("")
        self.label.setObjectName("label")
        self.pushButton_2 = QtWidgets.QPushButton(self.widget)
        self.pushButton_2.setGeometry(QtCore.QRect(819, 264, 40, 40))
        self.pushButton_2.setStyleSheet("border-image: url(:/images/zero.png);")
        self.pushButton_2.setText("")
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.setMainWindow)
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setGeometry(QtCore.QRect(116, 80, 681, 402))
        self.label_2.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-radius: 7px;")
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.widget)
        self.label_3.setGeometry(QtCore.QRect(120, 100, 671, 131))
        font = QtGui.QFont()
        font.setPointSize(35)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def setMainWindow(self):
            print("MainWindow")

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_3.setText(_translate("Form", "Составить протокол"))

А так же, при нажатии на кнопку с функцией mainWindow интерфейс переходил на первую главную страницу.

A: НИКОГДА НЕ ИЗМЕНЯЙТЕ код, сгенерированный Qt Designer, НИКОГДА.
Создайте другой класс, который наследуется от соответствующего виджета, и используйте созданный класс для его заполнения.
import sys
# ??? import res
import datetime
# ??? import time
from PyQt5 import QtCore, QtGui, QtWidgets

weekend = [
    "Empty", "понедельник", "вторник", "среда",
    "четверг", "пятница", "суббота", "воскресенье"
]
month = [
    "Empty", "января", "февраля", "марта", "апреля",
    "мая", "июня", "июля", "августа", "сентября",
    "октября", "ноября", "декабря"
]

class Ui_Form(object):
    def setupUi(self, Form):
#        self.show_current_time()
        Form.setObjectName("Form")
        Form.resize(960, 616)
        Form.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        Form.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.widget = QtWidgets.QWidget(Form)
        self.widget.setGeometry(QtCore.QRect(20, 30, 910, 560))
        self.widget.setObjectName("widget")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setGeometry(QtCore.QRect(10, 10, 890, 540))
        self.label.setStyleSheet("border-image: url(:/images/kpk.png);\n"
"border-radius: 20px;")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setGeometry(QtCore.QRect(120, 115, 670, 61))
        font = QtGui.QFont()
        font.setPointSize(48)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.widget)
        self.label_3.setGeometry(QtCore.QRect(120, 173, 671, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.widget)
        self.pushButton.setGeometry(QtCore.QRect(148, 277, 50, 50))
        self.pushButton.setStyleSheet("border-image: url(Ok.png);\n"
"border-radius: 10px;")
        self.pushButton.setText("")
        self.pushButton.setObjectName("pushButton")
#        self.pushButton.clicked.connect(self.protokol)
        self.label_4 = QtWidgets.QLabel(self.widget)
        self.label_4.setGeometry(QtCore.QRect(138, 326, 61, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        font.setStyleStrategy(QtGui.QFont.PreferDefault)
        self.label_4.setFont(font)
        self.label_4.setMouseTracking(False)
        self.label_4.setTabletTracking(False)
        self.label_4.setAcceptDrops(False)
        self.label_4.setAutoFillBackground(False)
        self.label_4.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_4.setScaledContents(False)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setWordWrap(True)
        self.label_4.setObjectName("label_4")
        self.pushButton_2 = QtWidgets.QPushButton(self.widget)
        self.pushButton_2.setGeometry(QtCore.QRect(819, 264, 40, 40))
        self.pushButton_2.setStyleSheet("border-image: url(:/images/zero.png);")
        self.pushButton_2.setText("")
        self.pushButton_2.setObjectName("pushButton_2")
#        self.pushButton_2.clicked.connect(self.setMainWindow)
        self.pushButton_3 = QtWidgets.QPushButton(self.widget)
        self.pushButton_3.setGeometry(QtCore.QRect(224, 277, 50, 50))
        self.pushButton_3.setStyleSheet("border-image: url(:/images/database.png);")
        self.pushButton_3.setText("")
        self.pushButton_3.setObjectName("pushButton_3")
#        self.pushButton_3.clicked.connect(self.DataBase)
        self.label_5 = QtWidgets.QLabel(self.widget)
        self.label_5.setGeometry(QtCore.QRect(219, 326, 61, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        font.setStyleStrategy(QtGui.QFont.PreferDefault)
        self.label_5.setFont(font)
        self.label_5.setMouseTracking(False)
        self.label_5.setTabletTracking(False)
        self.label_5.setAcceptDrops(False)
        self.label_5.setAutoFillBackground(False)
        self.label_5.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_5.setScaledContents(False)
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setWordWrap(True)
        self.label_5.setObjectName("label_5")
        self.pushButton_4 = QtWidgets.QPushButton(self.widget)
        self.pushButton_4.setGeometry(QtCore.QRect(306, 277, 50, 50))
        self.pushButton_4.setStyleSheet("border-image: url(im.png);\n"
"border-radius: 10px;")
        self.pushButton_4.setText("")
        self.pushButton_4.setObjectName("pushButton_4")
#        self.pushButton_4.clicked.connect(self.Koap)
        self.label_6 = QtWidgets.QLabel(self.widget)
        self.label_6.setGeometry(QtCore.QRect(300, 324, 61, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        font.setStyleStrategy(QtGui.QFont.PreferDefault)
        self.label_6.setFont(font)
        self.label_6.setMouseTracking(False)
        self.label_6.setTabletTracking(False)
        self.label_6.setAcceptDrops(False)
        self.label_6.setAutoFillBackground(False)
        self.label_6.setStyleSheet("color: rgb(255, 255, 255);")
        self.label_6.setScaledContents(False)
        self.label_6.setAlignment(QtCore.Qt.AlignCenter)
        self.label_6.setWordWrap(True)
        self.label_6.setObjectName("label_6")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_2.setText(_translate("Form", ""))
        self.label_3.setText(_translate("Form", ""))
        self.label_4.setText(_translate("Form", "Составить протокол"))
        self.label_5.setText(_translate("Form", "База данных"))
        self.label_6.setText(_translate("Form", "КоАП"))

class Ui_Protokol(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(960, 616)
        self.widget = QtWidgets.QWidget(Form)
        self.widget.setGeometry(QtCore.QRect(20, 30, 910, 560))
        self.widget.setObjectName("widget")
        self.label = QtWidgets.QLabel(self.widget)
        self.label.setGeometry(QtCore.QRect(10, 10, 890, 540))
        self.label.setStyleSheet("border-image: url(:/images/kpk.png);\n"
"border-radius: 20px;")
        self.label.setText("")
        self.label.setObjectName("label")
        self.pushButton_2 = QtWidgets.QPushButton(self.widget)
        self.pushButton_2.setGeometry(QtCore.QRect(819, 264, 40, 40))
        self.pushButton_2.setStyleSheet("border-image: url(lena.jpg);")
        self.pushButton_2.setText("")
        self.pushButton_2.setObjectName("pushButton_2")
#        self.pushButton_2.clicked.connect(self.setMainWindow)
        self.label_2 = QtWidgets.QLabel(self.widget)
        self.label_2.setGeometry(QtCore.QRect(116, 80, 681, 402))
        self.label_2.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border-radius: 7px;")
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.widget)
        self.label_3.setGeometry(QtCore.QRect(120, 100, 671, 131))
        font = QtGui.QFont()
        font.setPointSize(35)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_3.setText(_translate("Form", "Составить протокол"))

# !!! +++
class Protokol(QtWidgets.QWidget, Ui_Protokol):                           # !!! +++
    def __init__(self, parent):                                           # +++ parent
        super().__init__()
        self.setupUi(self)
        self.parent = parent

        self.pushButton_2.clicked.connect(self.setMainWindow)

    def setMainWindow(self):
        print("MainWindow")
        self.parent.show()
        self.hide()

class MainWindow(QtWidgets.QWidget, Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
#        self.show_current_time()

        self.pushButton.clicked.connect(self.up_protocol)
        self.pushButton_2.clicked.connect(self.setMainWindow)
        self.pushButton_3.clicked.connect(self.dataBase)
        self.pushButton_4.clicked.connect(self.koap)

# !!! +++
        self.protokol = Protokol(self)                                    # !!! +++
# !!! +++
        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.show_current_time)
        self.timer.start()

    def up_protocol(self):
        print("Составить протокол")
        self.protokol.show()
        self.hide()

    def setMainWindow(self):
        print("MainWindow")

    def dataBase(self):
        print("База данных")

    def koap(self):
        print("КоАП РФ")

    def show_current_time(self):
        current_datetime = datetime.datetime.now()
        daynow = weekend[datetime.datetime.today().isoweekday()]
        monthnow = month[current_datetime.month]
        self.label_2.setText(QtCore.QTime.currentTime().toString("hh:mm:ss"))
        self.label_3.setText(f"{daynow}, {current_datetime.day} {monthnow}")

if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())


text:
Q: Round to 3 decimal places if needed otherwise round to 2 decimal places in Pythonic manner I want to take a float and convert to a 2 decimal or 3 decimal place percentage. However, I only want to show 3 decimal places if 2 decimal places would display the percentage as 0.00%.
>>> x = 0.0001
>>> f'{x:,.2%}'
'0.01%'
>>> y = 0.00001
>>> f'{y:,.2%}'
'0.00%'

How can I have it show 3 decimal places for the case of y in a Pythonic manner? Is there some way I can avoid conditionals?

A: Nested f-strings! I choose you!
In [42]: x=1e-4

In [43]: f'{x:{",.2%" if x >= 1e-4 else ",.3%"}}'
Out[43]: '0.01%'

In [44]: x=1e-5

In [45]: f'{x:{",.2%" if x >= 1e-4 else ",.3%"}}'
Out[45]: '0.001%'


text:
Q: PDF download icon at right corner not working in browser, Opening PDF String in new window with javascript? When I click the download icon on the right corner, nothing happen. How to make it downloadable?
The following code i have used for PDF preview.
let pdfWindow = window.open("", "_blank")
pdfWindow.document.write("<iframe src='data:application/pdf;base64, " + yourDocumentBase64VarHere+"' width='100%' height='100%'  allowfullscreen></iframe>")

A:
This works for me in all browsers!

viewPdf(base64String) {
    let byteCharacters = atob(base64String);
    let byteNumbers = new Array(byteCharacters.length);
    for (var i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    let byteArray = new Uint8Array(byteNumbers);
    let blob = new Blob([byteArray], { type: 'application/pdf' });

    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
       window.navigator.msSaveOrOpenBlob(blob, 'Report.pdf');
    }
    else {
       var fileURL = URL.createObjectURL(blob);
       window.open(fileURL);
    }
}


text:
Q: new to this - django-nonrel / social-auth I'm trying to implement django-social-auth on a google app engine project, but I keep getting an error that says:
raise NotImplementedError("The database backend only supports "
NotImplementedError: The database backend only supports count() queries.

The main page works, but I get that error whenever I click any of the login links.  Any help would be greatly appreciated!
The full text of the error is below (I shortened some of the directories).  Thank you so much in advance for any help.
Environment:

Request Method: GET
Request URL: http://localhost:8080/login/google-oauth2/

Django Version: 1.4.3
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.contenttypes',
 'django.contrib.auth',
 'django.contrib.sessions',
 'djangotoolbox',
 'autoload',
 'dbindexer',
 'httplib2',
 'openid',
 'oauth2',
 'social_auth',
 'djangoappengine')
Installed Middleware:
('autoload.middleware.AutoloadMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware')

Traceback:
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\core\handlers\base.py" in get_response
  188.                 response = middleware_method(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\middleware.py" in process_response
  36.                 request.session.save()
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\cached_db.py" in save
  42.         super(SessionStore, self).save(must_create)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\db.py" in save
  51.             session_key=self._get_or_create_session_key(),
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\base.py" in _get_or_create_session_key
  145.             self._session_key = self._get_new_session_key()
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\base.py" in _get_new_session_key
  139.             if not self.exists(session_key):
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\cached_db.py" in exists
  39.         return super(SessionStore, self).exists(session_key)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\db.py" in exists
  27.         return Session.objects.filter(session_key=session_key).exists()
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\db\models\query.py" in exists
  565.             return self.query.has_results(using=self.db)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\db\models\sql\query.py" in has_results
  441.         return bool(compiler.execute_sql(SINGLE))
File ".\app project directory\dbindexer\compiler.py" in execute_sql
  24.         return super(SQLCompiler, self).execute_sql(*args, **kwargs)
File ".\app project directory\djangotoolbox\db\basecompiler.py" in execute_sql
  364.         raise NotImplementedError("The database backend only supports "

Exception Type: NotImplementedError at /login/google-oauth2/
Exception Value: The database backend only supports count() queries.


text:
Q: cosmosDB Cannot read property 'replace' of undefined at trimSlashes Im facing an issue where I try to create an item to cosmosDB but whenever I try to save an item it complains about trimSlashes function.
Language: Nodejs 10.x.x
Npm moduel: "@azure/cosmos": "^3.7.4",
The Error:
{ TypeError: Cannot read property 'replace' of undefined
    at trimSlashes (D:\home\site\wwwroot\node_modules\@azure\cosmos\dist\index.js:324:23)
    at D:\home\site\wwwroot\node_modules\@azure\cosmos\dist\index.js:7002:40
    at Generator.next (<anonymous>)
    at D:\home\site\wwwroot\node_modules\@azure\cosmos\node_modules\tslib\tslib.js:114:75
    at new Promise (<anonymous>)
    at Object.__awaiter (D:\home\site\wwwroot\node_modules\@azure\cosmos\node_modules\tslib\tslib.js:110:16)
    at httpRequest (D:\home\site\wwwroot\node_modules\@azure\cosmos\dist\index.js:6979:22)
    at D:\home\site\wwwroot\node_modules\@azure\cosmos\dist\index.js:6375:24
    at Generator.next (<anonymous>)
    at D:\home\site\wwwroot\node_modules\@azure\cosmos\node_modules\tslib\tslib.js:114:75
  headers:
   { 'x-ms-throttle-retry-count': 0,
     'x-ms-throttle-retry-wait-time-ms': 0 } }

The Input:
{ id: '1',
  subEntries: 'a',
  errorName: 'b',
  errorMessage: 'c',
  errorCode: 'd',
  errorStack: 'e' }

 { id: '1'}

The code:
async function saveToCosmosDB(error) {
    const client = new CosmosClient({ cosmosDBEndpoint, cosmosDBKey });
    const database = client.database(cosmosDBDatabase);
    let container = database.container(cosmosDBContainer);
    const res = await container.items.create(error);
    return res
}

Now I have tried with different inputs also where I only pass the ID in the input all of them is failing for some reason. Tried with defining the partition key as in above example, also tried without it, it seems all of them end up the same error, and at this moment im clueless what could cause it.
Also checked tutorials and official documentations.
eg:https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-nodejs-application
eg:https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-nodejs-samples
Any help appreciated to move forward with this.
Edit
I was digging into the node_module library a bit and it seems this error happens when the package tries to connect to the database, which is really weird since the cosmos DB im working with is public, and also no restrictions on azure function from NSG. Will post an update/solution once found one

A: Long story short the error was a syntax/naming error:
Re naming the passed variables when i create the new CosmosClient will solve the issue. From my opinion its pretty much dumb that SDK dont throw meaningfull error. Also there are other issues with the SDK i ran into, which connects to partitionKeyDefinition issues. But this thread is considered as solved from my side.
async function saveToCosmosDB(error) {
    const client = new CosmosClient({ endpoint, key});
    const database = client.database(cosmosDBDatabase);
    let container = database.container(cosmosDBContainer);
    const res = await container.items.create(error);
    return res
}


text:
Q: Is setValues slower than setValue? I've got a Google Doc with Google Apps Script script running that multiple people contribute to. There is an onEdit trigger that is fired when people edit the sheet. As I understand it, if one person edits the sheet this triggers my onEdit trigger function.
If a second person edits the sheet before the first onEdit finished processing then it stops the first instance and the second onEdit starts without finishing the first one.
To avoid this I'm trying to make my code as efficient as possible with the theory that if the onEdit process takes less time it's less likely to overlap. To accomplish this I've tried to minimize my read/writes. Using a series of logger statements I've tracked down lines of code that are time consuming. I've noticed that one of my setValues() lines takes almost 6 seconds to run. It's a large array being posted back to the sheet after I've made adjustments to it.
My Questions:

*

*Does a setValues() call take longer than a setValue()?

*Does a setValues() call of a small array take less time than a setValues() of a large array?

I know that one setValues() will be much faster than 1000 setValue() commands.
I had presumed one write to the sheet should take about the same amount of time regardless of size. Is there any way I can minimize this time?

A:
Q1: Does a setValues() take longer than a setValue()?

A1: It's no. About this, you can see from the following experimental result.

Q2: Does a setValues() call of a small array take less time than a setValues() of a large array?

A2: It's yes. About this, you can see from the following experimental result.

Q3: I had presumed one write to the sheet should take about the same amount of time regardless of size. Is there any way I can minimize this time?

A3: When you want to reduce the process cost for putting the values more, how about using Sheets API? About this, you can see it at the figure of "A2".
Note:

*

*The rationale of above answers is Benchmark: Reading and Writing Spreadsheet using Google Apps Script.

*As @TheMaster's comment, I also think that your issue might be resolved by LockService.

*

*I think that the sample script of LockService can be seen at the stackoverflow. Ref


text:
Q: Prove or disprove: If $a\mid (b+c)$, then either $a\mid b$ or $a\mid c$ Prove or disprove: If $a\mid (b+c)$, then either $a\mid b$ or $a\mid c$
I'm so confused how to go about this since it says prove or disprove. Should I start off by doing proof by contradiction? Step by step explanation please?

A: HINT. Maybe try a few examples, like $a=1,b=2,c=3$, and $a=2,b=4,c=6$, and $a=5,b=2,c=3$.
So does this work all the time? If it does how would you show it? If it does not, give an example where it fails. And if it fails, don't stop there! When does it fail? Is it sometimes true? For what examples? Can you add more assumptions to make the statement always true?

"Don't just read it! Ask your own questions, look for your own examples,
  discover your own proofs. Is the hypothesis necessary? Is the converse
  true? What happens in the classical special case? Where does the proof
  use the hypothesis?"
          - Paul Halmos

A: Try $b + c  = a, 1\leq b,c<a$


text:
Q: Looping with list comprehensions To simplify what I am trying to do:
I have 50 employees, each with a 40 task capacity.
I have a dataframe that I am reading in from a SQL table that I want to filter down to tasks with a score equal to 10 and then assign them to each employee so they have a full "basket" or workload. I want to assign one task to each employee and then iterate until finished.
My final output would look like a list with each list based off of position, denoting the employee number and the tasks that are assigned to them.
final_basket = [[task1, task2,...] , [task8, task11], ...[task45,task4]]

each one of the lists within the final basket would correspond to an employee, example:
final_basket[0] = [task1, task2,...] would be all the tasks for the first employee.
I can assign a task to each employe fine, but I get stuck with re-looping over all the employees to fill their capacity.
def basket_builder(i):
    agent_basket = [[ ] for basket in range(40)] #define empty basket for all 40 agents
    score_10 = base_data_1_mo[base_data_1_mo.case_score == 10] #filter data to score 10 only
    score_10 = score_10[['investigation_id']] #select only investigation id df
    score_10 = score_10.sort_index() ##sort by index asc
    for i in range(40):
        investigation_id = score_10.iloc[0]['investigation_id']
        agent_basket[i].append(investigation_id)
        index_drop_v2 = score_10[score_10.investigation_id == investigation_id].index[0]
        score_10 = score_10.drop([index_drop_v2])
        return final_basket

for i in range(40):
    final_basket = []
    final_basket = [[basket_builder(i) for agent in agent_basket[i]]

final_basket

Since I made some modifications to use a function to try and loop over here, I am now having an issue even printing the final_Basket

A: Could you do it with something like:
employee_task = {}
for n, task in enumerate(tasks):
   employee_number = n % 50
   if employee_number not in employee_task:
      employee_task[employee_number] = []
   employee_task[employee_number].append(task)

and check a posteriori that each employee has less than 40 tasks


text:
Q: Best Ansi Escape beginning Which Ansi escape sequence is the most portable and/or simply best and why?
1. "\u001B[32;1mThis is bright green\u001B[0m"
2. "\x1B[33;1mThis is bright yellow\x1B[0m"
3. "\e[35;4;1mThis is bright purple underlined\e[0m"

I have been using printf "\x1B[32;1mgreen\x1B[0m" (that's an example in unix bash script for example) out of habit, but I was wondering if there were any reasons to use one over the other. Is one more portable than the others? That would be my assumption.
Also, if you know of any other Ansi Escape sequence feel free to share it in the comments or at the end of your answer.
If you don't know what an Ansi Escape sequence is or want to become more familiar with it, then here you go: http://en.wikipedia.org/wiki/ANSI_escape_code
NOTE:
All of the escape sequences above have worked on all of the Unix systems I have been on, however one must still rely on the system itself to interpret the escape codes. Windows, for example, does not permit any sort of escape codes except four (BEL, L-F or linefeed, C-R or carriage return and, of course, BS or backspace), so Ansi escape sequences will not work.

A: Short answer: It depends on the host string parser.

Long answer:
It depends on the string parser; that is, the piece of code that actually takes in your string ("\x1b[1mSome string\x1b[0m") as a literal and parses the escape characters using the backslash ANSI escape sequence.

*

*For parsers that support hexadecimal escapes (\x), then \x1b (character 0x1B) should work.

*For parsers that support octal escapes (\ddd), then \033 (octal 33) should work.

*For parsers that support unicode escapes (\u), then \u001B should work.

Quick elaboration: \x and \u are similar; \x usually refers to a single character, 0-255, in hexadecimal radix. \u means the same (as it is represented in hexadecimal), but supports two bytes (in most parsers) and generally refers to 16-bit unicode characters.

A lesser used/supported escape character, as you mentioned, is \e. This escape is most commonly used with parsers/languages that expect a lot of ANSI escaping to happen, such as bash (and most other shells).
For instance, Node.js does not support \e:
> console.log("\x1b[31mhello\x1b[0m")
hello
undefined
> console.log("\e[31mhello\e[0m")
e[31mhelloe[0m
undefined

Neither does Lua:
> print('\x1b[31mhello\x1b[0m')
hello
> print('\e[31mhello\e[0m')
stdin:1: invalid escape sequence near '\e'

Or even Python:
>>> print("\x1b[31mhello\x1b[0m")
hello
>>> print("\e[31mhello\e[0m")
\e[31mhello\e[0m
>>>

Though PHP does:
<?php
echo "\x1b[31mhello\x1b[0m\n"; // hello
echo "\e[31mhello\e[0m\n"; // hello


text:
Q: Disk space allocated for system volume I have just bought a laptop with 1000 GB SSD disk and the laptop came up with preinstalled Windows 10 operating system. What I am trying to do now is to divide the disk into two volumes with the Disk manager usage.
My idea was that the first volume (lets say System) should be occupied by the operating system itself and the antivirus software and the second volume (lets say Data) should be occupied by software which I need for my work (i.e. Matlab, Netbeans IDE, MPLABX IDE, TexLive, Cygwin, Doxygen and Python) and associated files.
I have been struggling with how much space shall I dedicate for the System volume. I have found that the Windows 10 need at least 32 GB (recommended value is 40 GB) and the antivirus software which I have been using consumes 77 MB. Does anybody have any rule of thumb how much space should be dedicated for the System volume? Thanks for any ideas.


text:
Q: The MailSpool service is not available I started getting errors:
coldfusion.server.ServiceFactory$ServiceNotAvailableException: The MailSpool service is not available.
This exception is usually caused by service startup failure.
Check your server configuration.

It started happening after installing newest windows updates. I cannot even access CF administrator.
Windows Server 2008 R2 Enterprise

ColdFusion 9.0.1

There is a log after last reboot: pastie.org/9456023

A: Two files got corrupted: \lib\neo-cron.xml \lib\neo-mail.xml Restored them from the backup, restarted server and worked


text:
Q: User Does not Exist Oracle SQL developer Forgive me if this is a simple fix, I am quite new to SQL, just started learning it on Tuesday. So I am experimenting with functions and made a simple one to test it out such as
CREATE FUNCTION CHINOOKHW.AddPara(@a1 int, @b2 int)
RETURN INT
BEGIN AS
  DECLARE @C3 INT = SUM(A1, B2)
  RETURN @C3
END
GO
CHINOOKHW.AddPara(1, 2);

but I get the error
Error report -
ORA-01435: user does not exist
01435. 00000 -  "user does not exist"
*Cause:
*Action:

I have already defined my user as
CREATE USER chinookhw
IDENTIFIED BY p4ssw0rd;

And while I know this is normally bad practice, I even gave my user all access like
GRANT ALL PRIVILEGES to chinookhw IDENTIFIED BY p4ssw0rd;

I am not sure if this is relevant but I a connected to the chinook database from
https://chinookdatabase.codeplex.com/
and I made another connection from the system database with the lines
GRANT DBA TO chinook;
GRANT DBA TO chinookhw;
commit;

Can anyone tell me what I am doing wrong? I've been at this for hours with no fix. Thank you in advance

A: Try the following - note how it's not specifying the user that the function is to be created under. Note also how the syntax is PL/SQL and not T-SQL or whatever it is you wrote yours in:
CREATE FUNCTION AddPara(a1 integer, b2 integer)
RETURN INTeger
AS
BEGIN
  return A1 + B2;
END;
/


text:
Q: How to make a java regular expression which matches a word in any language To match a word in english I would use pattern [a-zA-Z]+.
Is there any way how to write a regular expression which will match a word in any language? That is even if the word contains characters like ščžé.... I have no idea what possible characters exist in the world so I don't think that pure [a-zA-Zščžé]+ would be enough...
Is there a better way to write this expression?

A: According to the Pattern javadoc, \p{L}+ should match a sequence of Unicode letters (i.e. characters that have the category L in Unicode). That's probably the widest possible definition though you may want to look at the unicode categories list to decide whether you want to add other categories (e.g. there is one called "Number Letter").

A: Usually you would use some unicode character ranges
[a-zA-Z\u0000-\u1111]

or
[a-zA-Zš-é]

So you have to take a look at the unicode character code and add whatever range of special characters you have in the target language


text:
Q: iOS - How to Remove UIButton border color? Current button settings
button.backgroundColor = UIColor.brown
button.layer.cornerRadius = 60/2
button.layer.borderWidth = 5
button.layer.borderColor = UIColor.white.cgColor

It looks like the code above
The problem is, there is a very thin border on the outside as shown in the image below.

The border color is the same as the backgroundColor you set.
Changing backgroundColor to red changes the bottom border to red.
I have set button.layer.shadowColor.
The button size is 60, and the width / height is set using anchor.
Still searching. But only the borderColor settings.
It is frustrating. Please ask for help. Why does this happen?

A: You can implement UIView extension this way,
extension UIView {
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))

        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask

        let borderPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let borderLayer = CAShapeLayer()
        borderLayer.path = borderPath.cgPath
        borderLayer.lineWidth = borderWidth
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.frame = self.bounds
        self.layer.addSublayer(borderLayer)
    }
}

Use it like this,
button.backgroundColor = UIColor.brown
button.roundCorners([.allCorners], radius: 30.0, borderColor: UIColor.white, borderWidth: 10.0)

This will display output like this,

Above image contains button with white borderColor.
This will be generic solution for all buttons in your applications.
Let me know in case of any queries.

A: Setting shadowOpacity to zero should solve your issue.
button.layer.shadowOpacity = 0.0;

A: You have to clip a layer's bounds.
button.layer.masksToBounds = true

A: I know why there's a line around the button, I met it before. Actually the line is the gap between border and background, button.layer.border doesn't draw correctly. You can try to draw a border yourself and cover on the button.

A: you have to clip the bound and add a blank title
 button.clipsToBounds = true
 button.setTitle("  ", for: .normal)


text:
Q: Django: saving pickled object i have a large dictionary I'd like to save. I have pickled it using cPickle.dumps and saved the result into a TextField. When trying to retrieve it (cPicle.loads) i get the following error:
loads() argument 1 must be string, not unicode

Does anybody have any experience in serializing python objects and storing them in a DB using Django? Thanks in advance.

A: The best advice you're probably going to get is to use json rather than pickle not only for security reasons, but also because it's simply a string which can easily be read and modified if necessary.
edit: in response to the actual problem you're having -
pickle.loads(str(textfield))


text:
Q: Write a function named is_two that takes in a variable and returns True or False if the input is the number 2 or the string "2" I'm having some issues with getting my code to validate the "2" as a True value. Just need some help with seeing exactly why that is?

Write a function named ˚ that takes in a variable and returns True or False if the input is the number 2 or the string "2"

def is_two(x):
    return x == 2

assert is_two(2) == True
assert is_two("2") == True
assert is_two(3) == False
assert is_two(10) == False
assert is_two("two") == False
print("Exercise 4 is complete.")``

A: As @Barmar has hinted in his comments, if you want a True result for either 2 or "2", you can use or to test this as follows:
def is_two(x):
    return x == 2 or x == "2"

An alternative is to create a tuple containing the two target results 2 and "2" and to test whether x is in this tuple:
def is_two(x):
    return x in (2, "2")

A: The issue is that equality comparisons are generally type-aware; 2 != "2".  (There are some funny cases, e.g. True == 1, but that's not relevant here.)
I'd suggest:
def is_two(x):
    return str(x) == "2"

In the case where x is a str already, converting it to a str is a no-op; in the case where it's an int, 2 will become "2", so the comparison will return True.

A: You just need to add a few line to your code:
def is_two(x):
  if isinstance(x, str) and x.isdigit():
    x = int(x)
  if x == 2:
    return True
  return False
assert is_two(2) == True
assert is_two("2") == True
assert is_two(3) == False
assert is_two(10) == False
assert is_two("two") == False

If you run the abovementioned code, you will see all the assertions will be validated.
Explanation
You need to use isinstance in order to check whether the x variable is a string or not. Then if it's a string, you need to make sure it is a number, but in the form of a string. Then by using int function, you parse this string into a digit(integer).


text:
Q: What is the point in the doctype declaration at the top of html form? Does it change anything? Been writing web apps for years and this line:
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Has always confused me. What is it for exactly? What are the implications if I remove it?
I understand the w3c conventions about nested elements etc but what actually happens why is the declaration there do browsers fail or something if I take it out?
Cheers,
Pete

A: It kicks the browser into standards mode, which makes the browser properly render elements. Not every doctype kicks the browser into standards mode, see this chart. If a valid doctype is not used to kick the browser into standards mode, the browser will basically try to render your page according to "standards" ( or lack thereof ) in 2002-2003 when everyone used crappy table layouts. You do not want quirks mode.
Conclusion: always use a doctype.

A: The doctype declaration tells the browser how it should interpret the HTML contents that follow. There's a good overview of how and why in the introduction to Mark Pilgrim's book Dive Into HTML 5

A: It iforms the browser of what elements will be used, and affects the rendering of the page. (Mostly IE)
In many cases, elements will not always display correctly if a DOCTYPE is left out.

A: In HTML 2.0, 3.2, 4.x and XHTML 1.x:
In theory:

*

*It allows the user agent to decode entities (e.g. … to …)

*It allows a validator to determine which tags, attributes and attribute values are allowed where

In practice:

*

*It allows a validator to determine which tags, attributes and attribute values are allowed where

*It allows browsers to make a guess as to if the author has a clue about what they are doing and switch between standards mode and quirks mode
In HTML 5:

*

*It is a mystic string used to start a document so that standards mode is triggered


text:
Q: Quarks falling in a black hole? All I know about quarks is that they make up protons and neutrons and you can't really pull a quark pair apart, you just end up with 2 quark pairs because of all the energy you added becomes 2 new quarks.
All I know about black holes is objects falling into them are pulled apart by tidal forces as the gravity at the close end is stronger than at the far end of the object. Eventually matter is pulled into individual atoms.
So I was thinking about what happens when a quark pair falls into a black hole. Quarks have mass, so they should be affected by gravity and get pulled in. If quark pairs can be spaghettified, at some point they will pull apart generating two quark pairs instead of one. If this process were allowed to continue you'd have infinite quarks.
This is where I think I've made an error. If black holes could make infinite quarks, their mass should increase over time as gravitational energy is converted into new quarks. This extra mass should increase the black hole's gravitational force, increasing its ability to pull new matter in and to split quark pairs. If this were true black holes could gain mass even without absorbing new matter. These seem like blatant violations of conservation of mass and energy, but I don't know enough about advanced physics to figure out where I went wrong. I was hoping someone here could tell me.

A: As in all extrapolations, one reaches a point where they break down.
In the case of a black hole singularity and quark triplets ( neutrons and protons, pairs are quark antiquark i.e. mesons) falling into a black hole ,   the neutrons and protons falling in acquire energy from the gravitational energy  of the black hole and at some point in energy will start interacting with each other.  The strong force will  produce quark-antiquark pairs i.e.  mesons, and other particle antiparticle pairs. As more energy is gained by the fall, the strongly interacting mass  will reach the quark gluon plasma stage :

A quark–gluon plasma (QGP) or quark soup is a phase of quantum chromodynamics (QCD) which is hypothesized to exist at extremely high temperature, density, or both temperature and density. This phase is thought to consist of asymptotically free quarks and gluons, which are several of the basic building blocks of matter. It is believed that up to a few milliseconds after the Big Bang the Universe was in a quark–gluon plasma state.

The quark gluon plasma is being currently studied in the strong interactions of ions at the LHC:

The ALICE detector at the LHC is used to study the properties of the Quark-Gluon Plasma produced in heavy-ion collisions

The energy of this plasma is the energy of the rest masses of the infalling particles plus the energy gained by the fall. No excess in the sense you think. There will be as many quarks and gluons as the logistics allows, no infinities.

A: I would imagine that, the energy that pulls the quark pair into the black hole is intrinsic energy (ie it comes from the black hole), and the quarks created through 'spaghettification' would only be proportional to that energy pulling on them. Therefore, seeing as energy is equal to mass and vice versa this new mass would not be created, rather transformed from the energy of the black hole. The black hole never gains more mass/energy than the original quark pair because it already contained the mass/energy in its system that would be then created into more quark pairs.
I hope that makes sense


text:
Q: F1 Results with Haskell What is the most simple solution to do this ?
Define a function for calculating the series of Formula 1 race in function "f1Results". The parameter is a list whose elements are lists based on the result of each Grand Prix. Each such list shall contain the names of the competitors listed by the GP result (the winner is the first of the list). The result of the function has to be a list of names of F1 pilots sorted by number of points in the overall F1 season.
   f1Results :: [[String]] -> [String]

Points have to be granted for each position like in the list bellow (again the 25 is for the winner) pointsScoring (eg: 1st place 25 points, 2nd place 18 points, etc.).
   pointsScoring :: [Int]
   pointsScoring = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]

A: You have a constant for what the scoring is
scoring :: [Int]
scoring = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]

Then you need a way for pairing up a driver with the score they got.  Whenever you're pairing two things in Haskell, the canonical choice is to use a tuple.  The easiest way to construct a list of tuples from two lists is the zip function:
zip :: [a] -> [b] -> [(a, b)]

And in this case can be used to assign scores for a race:
assignScores :: [String] -> [(String, Int)]
assignScores race = zip race scoring

Now, we need a way to total up the scores for a driver for each race.  We want to be able to turn something like
[("Bob", 12), ("Joe", 10), ("Bob", 18), ("Joe", 25)]

into
[("Bob", 30), ("Joe", 35)]

The easiest way would be to make a single list of all the scores for all the races
assignAllScores :: [[String]] -> [(String, Int)]
assignAllScores races = concatMap assignScores races

Then we can use sortBy from Data.List to get all the same names next to each other
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
compare :: Ord a => a -> a -> Ordering

sortByDriver :: [(String, Int)] -> [(String, Int)]
sortByDriver races = sortBy (\(n1, s1) (n2, s2) -> compare n1 n2) races

Then we can use groupBy (also from Data.List) to group them all by name
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

groupByDriver :: [(String, Int)] -> [[(String, Int)]]
groupByDriver races = groupBy (\(n1, s1) (n2, s2) -> n1 == n2) races

But this gives us a list like
[[("Bob", 12), ("Bob", 18)], [("Joe", 10), ("Joe", 25)]]

We now need a way to convert this into the form
[("Bob", [12, 18]), ("Joe", [10, 25])]

where all the scores are aggregated back into a list, and we don't repeat the names at all.  This is left as an exercise.
aggregateScores :: [[(String, Int)]] -> [(String, [Int])]

Then we can finally calculate the sum of these scores
sumScores :: [(String, [Int])] -> [(String, Int)]
sumScores races = map (\(name, scores) -> (name, sum scores)) races

Then finally we can sort by the scores to get everyone in order
sortByScore :: [(String, Int)] -> [(String, Int)]
sortByScore races = sortBy (\(n1, s1) (n2, s2) -> compare s2 s1) races

Notice that I have compare s2 s1 instead of compare s1 s2, this means it will be sorted in descending order instead of ascending order.
The last step is to strip out the scores, now we have our list of drivers in order from winner to loser
removeScores :: [(String, Int)] -> [String]
removeScores races = map fst races

So to combine everything together into one function
f1Results :: [[String]] -> [String]
f1Results races =
    removeScores $
    sortByScore  $
    sumScores    $
    aggregateScores $
    groupByDriver $
    sortByDriver $
    assignAllScores races

There are several tricks that can make this code shorter, namely Data.Function.on, Data.Ord.comparing, and a fun operator from Control.Arrow.  Don't turn this in as homework, I just wanted to show an alternative that uses less code.
import Data.List
import Data.Function (on)
import Data.Ord (comparing)

scoring :: [Int]
scoring = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]

f1Results :: [[String]] -> [String]
f1Results =
    map fst . sortBy (on (flip compare) snd) .
    map ((head *** sum) . unzip) .
    groupBy (on (==) fst) . sortBy (comparing fst) .
    concatMap (`zip` scoring)

Or using Data.Map:
import Data.Map (assocs, fromListWith)
import Data.List
import Data.Ord (comparing)

scoring :: [Int]
scoring = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]

f1Results :: [[String]] -> [String]
f1Results =
    reverse . map fst . sortBy (comparing snd) .
    assocs . fromListWith (+) .
    concatMap (`zip` scoring)

A: One way could be to use a map where the keys are the drivers' names and the values are the scores. To associate scores with drivers for each sublist in f1results, one could zip the sublist with pointsScoring. A function could take each of the zipped sublists and add the score for each driver encountered in (or newly added to) the map. Then sort the map according to the values.
For example,
import qualified Data.Map as M
import Data.List(sortBy)

pointsScoring :: [Int]
pointsScoring = [25, 18, 15, 12]

f1List :: [[String]]
f1List = [["alex","bart","cecyl","dark"]
         ,["dark","bart","cecyl","alex"]
         ,["bart","cecyl","alex","dark"]]

f1Results :: [[String]] -> [String]
f1Results list = map fst . sortBy (\(n1,s1) (n2,s2) -> compare s2 s1) . M.toList
               $ foldr f M.empty (concatMap (zip pointsScoring) list)
  where f (score,name) results = M.insertWithKey updateMap name score results
        updateMap key newValue oldValue = newValue + oldValue

Output:
*Main> f1Results f1List
["bart","alex","dark","cecyl"]


text:
Q: Python: pickling nested functions Using the example
def foo(a):
    def bar(b):
        return a+b
    return bar

d = {1:foo(1), 2:foo(2)}

It appears that pickle module will not work with a function not defined at the module scope, so pickling 'd' will not work. Is there another pickling mechanism available that I should consider?

A: I'm afraid that you can't pickle nested functions.
The pickle module serializes functions by name. That is, if you have a function myfunc in a module mymodule it simply saves the name mymodule.myfunc and looks it up again when unserializing. (This is an important security and compatibility issue, as it guarantees that the unserializing code uses its own definition for the function, rather than the original definition which might be compromised or obsolete.)
Alas, pickle can't do that with nested functions, because there's no way to directly address them by name. Your bar function, for instance, can't be accessed from outside of foo.
If you need a serializable object that works like a function, you can instead make a class with a __call__ method:
class foo(object):
    def __init__(self, a):
        self.a = a
    def __call__(self, b): # the function formerly known as "bar"
        return self.a + b

This works just like the nested functions in the question, and should pose no problem to pickle. Do be aware though, that you'll need to have the same class definition available when you unserialize a foo instance.

A: You can pickle nested functions if you use dill instead of pickle.
>>> import dill
>>>
>>> def foo(a):
...   def bar(b):
...     return a+b
...   return bar
...
>>> d = {1:foo(1), 2:foo(2)}
>>>
>>> _d = dill.dumps(d)
>>> d_ = dill.loads(_d)
>>> d_
{1: <function bar at 0x108cfe848>, 2: <function bar at 0x108cfe8c0>}
>>> d[1](0) + d[2](10)
13
>>>

A: according to Blckknght's answersing. if nested function is the only extrac serialized type and will use it as decorator, you can just add functools.warps at top of inner function defination to lead other interpret find the correct name:
from functools import warps

def foo(func):
    @wraps(func)
    def bar(b):
        return func(b)
    return bar

@foo
def zzz(b):
    return b


text:
Q: 14.04 wifi disconnect reason 2 Ubuntu 14.04
HW: rt2860 (I'm sure since is my eeepc 1000he) BUT seen from ubuntu as rt2890
lspci:
01:00.0 Network controller: Ralink corp. RT2790 Wireless 802.11n 1T/2R PCIe

module: rt28000pci
It's a wep connection, it connect just for a couple of minutes, then disconnect with reason 2, here just a few lines from dmesg.
[  238.999880] wlan0: authenticate with e0:91:53:25:0b:f1
[  239.012788] wlan0: send auth to e0:91:53:25:0b:f1 (try 1/3)
[  239.019096] wlan0: authenticated
[  239.019814] rt2800pci 0000:01:00.0 wlan0: disabling HT/VHT due to WEP/TKIP use
[  239.019836] rt2800pci 0000:01:00.0 wlan0: disabling HT as WMM/QoS is not         supported by the AP
[  239.019850] rt2800pci 0000:01:00.0 wlan0: disabling VHT as WMM/QoS is not supported by the AP
[  239.020176] wlan0: associate with e0:91:53:25:0b:f1 (try 1/3)
[  239.022206] wlan0: RX AssocResp from e0:91:53:25:0b:f1 (capab=0x431 status=0 aid=17)
[  239.023239] wlan0: associated
[  239.023345] IPv6: ADDRCONF(NETDEV_CHANGE): wlan0: link becomes ready
[  239.063810] wlan0: deauthenticated from e0:91:53:25:0b:f1 (Reason: 2)
[  240.025701] wlan0: authenticate with e0:91:53:25:0b:f1
[  240.028223] wlan0: send auth to e0:91:53:25:0b:f1 (try 1/3)
[  240.032416] wlan0: authenticated

With open networks it works without problems, I'll check with WPA as soon as I can.
Any idea?

A: Please run the following commands one line at a time and just copy and paste for accuracy:
echo "options rt2800pci nohwcrypt=1" | sudo tee /etc/modprobe.d/rt2800pci.conf
sudo modprobe -rfv rt2800pci
sudo modprobe -v rt2800pci

This command changes encryption from hardware to software and in many cases corrects the issue you are having.
Wep is not very secure and ubuntu will connect to wpa2 (AES) (CCMP) better then any other settings,  not mixed mode or especially (TKIP).


text:
Q: Create Bluetooth PAN between iPhone and Windows (Reverse Tethering) It's really easy to create a Bluetooth personal area network between iPhone and MAC OS X.
On Windows, it's quite difficult. We can pair iPhone but the link icon never appears in iOS status bar.
The goal is to let the iPhone reach local network and access Internet.
How to create a Bluetooth PAN under Windows?


text:
Q: HTML5 validation in Bootstrap Modal, focusable error on submit I got a simple form:

                                    Aktualizuj dane użytkownika

                                        ×

Profil użytkownika

                                            Imię
                                            <input
                                                class="form-control form-control-sm"
                                                name="imie"
                                                type="text"
                                                required="required">
                                            <input class="form-control form-control-sm" name="userid" type="hidden">

                                            Nazwisko
                                            <input
                                                class="form-control form-control-sm"
                                                name="nazwisko"
                                                type="text"
                                                required="required">

                                            Telefon
                                            <input
                                                class="form-control form-control-sm"
                                                name="telefon"
                                                type="text"
                                                required="required">

                                            Adres e-mail
                                            <input
                                                class="form-control form-control-sm"
                                                name="email"
                                                type="email"
                                                required="required">

                                            Hasło
                                            <input class="form-control form-control-sm" name="password" type="password">

                                            Powtórz hasło
                                            <input
                                                class="form-control form-control-sm"
                                                name="password_confirm"
                                                type="password">

                                                Zdjęcie profilowe

                                                <input type="file" class="custom-file-input" name="avatar" id="avatar">
                                                Wybierz plik

Poziom dostępu

                                            Wybierz poziom dostępu
                                            <select class="form-control" name="roles">
                                                <option>Poziom dostępu</option>
                                                <option value="ROLE_SUPER_ADMIN">Administrator</option>
                                                <option value="ROLE_FINANCE">Księgowy</option>
                                                <option value="ROLE_WRITER">Redaktor</option>
                                            </select>

                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Zamknij</button>
                                <button type="submit" id="saveEditUser" class="btn btn-primary">Zapisz</button>

                        </from>

and I got a submit handled in js
var form = $('form[name="editUser"]');
form.on('submit', function (e) {
    e.preventDefault();

And validate show without problem, but if i correct all inputs than i got a error like this:
An invalid form control with name='imie' is not focusable.
32An invalid form control with name='nazwisko' is not focusable.
32An invalid form control with name='telefon' is not focusable.
32An invalid form control with name='password_confirm' is not focusable.

I have tried to delete all required and other but its still same error.
Please notice that form is after show modal, input gets value from ajax get request, after change inputs i can`t submit it becouse of this error.

A: Ok, problem solved. If someone use form inside modal be sure that you self-closed all input elements.


text:
Q: Is the model specific put() called for each entity when db.put() is called with a list of entities? I've got some models on my GAE app, and I've overriden put() on some of them. When I call db.put() with a list of these entites, is there a guarantee that the overriden put() on each entity will be called?
What I'm seeing right now is that the entities are just getting saved without it being called. Is there any good way to make sure stuff is done before every save, even batches?

A: No.  You need to monkeypatch db.put() too.  For a good example of this, check out Nick Johnson's excellent blog post on Pre- and post- put hooks for Datastore models.
If you look at the source code for the db module, you'll see that db.put() does not call the entity's put() function.

A: You could try something like:
class SomeModel(db.Model):
    aprop = db.IntegerProperty()

    def _populate_internal_entity(self, *args, **kwargs):
        logging.warn('about to Put() SomeModel: %r', self)
        return super(SomeModel, self)._populate_internal_entity(*args, **kwargs)

However, there is probably a better way to do it. If you are trying to set some properties you should check out custom property classes. If you are trying to do logging or caching you should investigate datastore hooks.


text:
Q: Write to Samba fails for only one application A samba server was setup on a Centos 6.4 box with SELinux unenforced.
It's configured and running, and from Windows with it mapped to a network drive most users and applications can read and execute them. I can make new documents, save from MS Office, open, and delete, all from the same login with the samba mapped to Z:\ on the Windows machine. What I cannot do is save from DreamSpark PCB run on the same machine for reasons that escape me.
The permissions for the designsparktest/onemorelevel/ is are 0770, its group is wheel, recursively. Every user is in wheel.
Here's the relevant bits of smb.conf:
[global]

acl check permissions = no

#============================ Share Definitions ==============================

[working]
    comment = 'working' directory
    path = /misc/working
    writeable = yes
    read only = no
    guest ok = yes
    inherit permissions = yes
    create mode = 0770
    directory mode = 0770
    valid users = blake randy jeffg ccchen andrew jlumish ivanh bobbief michal denzel pawel przemek jpcaram jreeves thchen darek adam wguest

Here's a snippet of the error that occurs from smbd.log, set to level 3 so there's a lot of similar stuff.  Ask me and I'll grep through it for you.
[2014/02/05 11:54:32, 3] smbd/process.c:process_smb(1101)
  Transaction 349 of length 172
[2014/02/05 11:54:32, 3] smbd/process.c:switch_message(932)
  switch message SMBtrans2 (pid 10747) conn 0x2ba0f70d7420
[2014/02/05 11:54:32, 3] smbd/trans2.c:call_trans2qfilepathinfo(3314)
  call_trans2qfilepathinfo: TRANSACT2_QPATHINFO: level = 1004
[2014/02/05 11:54:32, 3] smbd/vfs.c:reduce_name(821)
  reduce_name [designsparktest/onemorelevel/TestBoardPCB.sch] [/misc/working]
[2014/02/05 11:54:32, 3] smbd/vfs.c:reduce_name(922)
  reduce_name: designsparktest/onemorelevel/TestBoardPCB.sch reduced to /misc/working/designsparktest/onemorelevel/TestBoardPCB.sch
[2014/02/05 11:54:32, 3] smbd/trans2.c:call_trans2qfilepathinfo(3350)
  call_trans2qfilepathinfo: SMB_VFS_STAT of designsparktest/onemorelevel/TestBoardPCB.sch failed (No such file or directory)

I've seen similar questions in response to that last line about not being able to create new files but they always apply across the board. This user has demonstrated that it has permissions and can create files. It's just this one application that I've encountered where he cannot save to the shared Samba.


text:
Q: Adding two array objects together I'm trying to add two DNumber objects in the add(DNumber b) method. The point is to be able to do binary arithmetic. The elements are stored normally. How should I handle ArrayLists that are not even? Fill the one with fewer elements with 0s?. Then how should I retrieve each element? Also what would be a good way to convert to decimal without using the convert to decimal method:
public class DNumber{
    ArrayList<Digit> binary = new ArrayList<Digit>();
    /**
     * Constructor for objects of class DNumber
     */
    public DNumber()
    {
        Digit num = new Digit(0);
        binary.add(num);
    }

    public DNumber(int val){
        int num = val;
        if(num > 0){
            while (num > 0){
                Digit bin = new Digit(num%2);
                num /= 2;
                binary.add(0, bin);
            }
        }
        else{
            Digit bin = new Digit(0);
            binary.add(0,bin);
        }
    }

    /**
     * An example of a method - replace this comment with your own
     *
     * @param  y  a sample parameter for a method
     * @return    the sum of x and y
     */
    public String toString(){
        String s = "";
        for(Digit d : binary){
            s = s + d.toString();
        }
        return s;
    }

    public void add(DNumber b){
        int ArraySize1 = binary.size() -1;
        int ArraySize2 = b.binary.size() -1;

    }

    public void toDecimal(){
        /**
         *
         *  String s = "";
         int result = 0;
         int power = 0;
         for(Digit d : binary){
         s = s + d.toString();
         result = Integer.parseInt(s);
         }
         */
    }
}

public class Digit {
    int x = 0;

    /**
     * Constructor for objects of class Digit
     */
    public Digit(int val) {
        if (val != 0 && val != 1) {
            System.out.println("Error Must be either 1 or 0");
            x = 0;
        } else {
            x = val;
        }
    }

    /**
     * An example of a method - replace this comment with your own
     *
     * @param y a sample parameter for a method
     * @return the sum of x and y
     */
    public int getValue() {
        return x;
    }

    public void setValue(int num) {
        if (num != 0 && num != 1) {
            System.out.println("Error Must be either 1 or 0");
            System.out.println("Old Value Retained");
        } else {
            x = num;
        }
    }

    public String toString() {
        return Integer.toString(x);
    }

    public Digit add(Digit b) {
        int returnInt = getValue() + b.getValue();
        Digit carry = new Digit(0);
        if (returnInt == 2) {
            carry = new Digit(1);
            setValue(0);
        } else if (returnInt == 1) {
            carry = new Digit(0);
            setValue(1);
        } else if (returnInt == 0) {
            carry = new Digit(0);
            setValue(0);
        }
        return carry;
    }

    public Digit add(Digit b, Digit c) {
        int returnInt = getValue() + b.getValue() + c.getValue();
        Digit carry = new Digit(0);
        if (returnInt == 2) {
            carry = new Digit(1);
            setValue(0);
        } else if (returnInt == 1) {
            carry = new Digit(0);
            setValue(1);
        } else if (returnInt == 0) {
            carry = new Digit(0);
            setValue(0);
        } else if (returnInt == 3) {
            carry = new Digit(1);
            setValue(1);
        }
        return carry;
    }
}

A: Consider this small change to your constructor.
while (num > 0){
    Digit bin = new Digit(num%2);
    num /= 2;
    binary.add(bin);
}

This might seem strange at first, new DNumber(6) gives you a list (0,1,1) which seems backwards, but is much easier to work with.
You can easily convert this to a decimal:
    public int toDecimal() {
        int total = 0;
        int power = 1;
        for (int i = 0; i < binary.size(); i++) {
            total += binary.get(i).getValue() * power;
            power *= 2;
        }
        return total;
    }

When it comes to adding you start at the 0th element with a carry of 0, if one array is longer than the other it's much easier to handle.
Consider adding 6 and 4
carry = 0
a = (0,1,1)
b = (0,0,1)
answer = ()

at start, it's 0+0+0 = 0, carry 0
carry=0
a = (1,1)
b = (0,1)
answer = (0)

the next interation, it's 0+1+0 = 1, carry 0
carry=0
a = (1)
b = (1)
answer = (0,1)

the next iteration, it's 0+1+1 = 0, carry 1
carry=1
a = ()
b = ()
answer = (0,1,0)

The next iteration both input lists are empty, so we just add the carry bit
answer = (0,1,0,1) which if you run through toDecimal is 10


text:
Q: Поменять тригер в шаблоне XAML ("наследование шаблонов") Я создал стиль для кнопок DefaultButton, в котором сделал сеттер для шаблона, и внутри шаблона сделал несколько тригеров, чтобы кнопка меняла фон:
<Style TargetType="Button" x:Key="DefaultButton">
    <Setter Property="Background" Value="#FFE5E5E5" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Margin" Value="1" />
    <Setter Property="FontSize" Value="22" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button" >
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter
                        Margin="5"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"/>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsDefault" Value="True">
                        <Setter Property="Background" Value="#FFE5E5E5"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#FFD6D6D6"/>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="#FFA5A5A5"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Background" Value="#FFBABABA"/>
                        <Setter Property="Foreground" Value="#FF9A9A9A"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

После этого я захотел точно такой же стиль, но только что бы поменять два тригера, так, чтобы фон при наведении был другим. Я могу с лёгкостью унаследовать стиль с помощью BaseOn="StaticResource DefaultButton" и изменить сеттер для шаблона.
Получился вот такой 2й стиль:
<Style TargetType="Button" x:Key="OperationButton" BasedOn="{StaticResource DefaultButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button" >
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter
                        Margin="5"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"/>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsDefault" Value="True">
                        <Setter Property="Background" Value="#FFE5E5E5"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#FF89E8E6"/> <!-- первое отличие --!>
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="#FF94F3F2"/> <!-- второе отличие --!>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Background" Value="#FFBABABA"/>
                        <Setter Property="Foreground" Value="#FF9A9A9A"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Получилось 90% повторяющегося кода из-за отсутсвия наследования для шаблонов. Можно ли как-то этого избежать и писать 2 строчке вместо копирования 20ти?

A: Подмена данных в стилях легко достигается при помощи следующего трюка. В триггере данные не хардкодируем, а берём из ресурсов стиля, а в новом стиле переопределяем их. Получается вот что:
<Style TargetType="Button" x:Key="DefaultButton">
    <Style.Resources>
        <SolidColorBrush x:Key="MouseOverBrush">#FFD6D6D6</SolidColorBrush>
    </Style.Resources>
    <Setter Property="Background" Value="#FFE5E5E5" />
    ...
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button" >
                ...
                <ControlTemplate.Triggers>
                    ...
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background"
                                Value="{DynamicResource MouseOverBrush}"/>
                    </Trigger>
                    ...
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style TargetType="Button" x:Key="OperationButton" BasedOn="{StaticResource DefaultButton}">
    <Style.Resources>
        <!-- тут переопределяем цвета -->
        <SolidColorBrush x:Key="MouseOverBrush">#FF89E8E6</SolidColorBrush>
    </Style.Resources>
</Style>


text:
Q: Should I throw PDOException from my PDO class extension? I'm extending PDO and I want to throw exceptions from it. Should I make my own exception class that is not inherited from PDOException, throw PDOException or throw a class inherited from PDOException?

A: If your exception does not contain any extra data or custom properties, just throw the original PDOException, as you have no reason to extend it.