text:
Q: Set Default MySQL Socket in PHP, pdo_mysql.default_socket PHP 5.3 I'm having an issue setting the default PDO socket location for MySQL, without doing it through the initialisation of the PDO class into a variable. I've tried altering the mysql.default_socket variable. But no joy with that. The only way that works currently is through the class DSN instantiation.
php.ini Contents:
[PHP]
engine = On
zend.ze1_compatibility_mode = Off
short_open_tag = On
asp_tags = Off
precision    =  14
y2k_compliance = On
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func=
serialize_precision = 100
allow_call_time_pass_reference = Off
safe_mode = Off
safe_mode_gid = Off
safe_mode_include_dir =
safe_mode_exec_dir =
safe_mode_allowed_env_vars = PHP_
safe_mode_protected_env_vars = LD_LIBRARY_PATH
disable_functions =
disable_classes =
expose_php = Off
max_execution_time = 300
max_input_time = 60
memory_limit = 128M
error_reporting = E_ALL & ~E_NOTICE
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
variables_order = "EGPCS"
register_globals = Off
register_long_arrays = Off
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 8M
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
doc_root =
user_dir =
extension_dir = "/usr/lib64/php/modules"
enable_dl = On
file_uploads = On
upload_max_filesize = 500M
allow_url_fopen = On
default_socket_timeout = 60

[Syslog]
define_syslog_variables  = Off

sendmail_path = /usr/sbin/sendmail -t -i

[SQL]
sql.safe_mode = Off

[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1

[MySQL]
mysql.allow_persistent = On
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port = 3306
mysql.default_socket = /home/mysql/mysql.sock
mysql.default_host = 127.0.0.1
mysql.default_user = conner
mysql.default_password = danica4eva
mysql.connect_timeout = 60
mysql.trace_mode = Off

[MySQLi]
mysqli.max_links = -1
mysqli.default_port = 3306
mysqli.default_socket = /home/mysql/mysql.sock
mysqli.default_host = 127.0.0.1
mysqli.default_user = conner
mysqli.default_pw = danica4eva
mysqli.reconnect = Off

[mSQL]
msql.allow_persistent = On
msql.max_persistent = -1
msql.max_links = -1

[PostgresSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0

[Sybase]
sybase.allow_persistent = On
sybase.max_persistent = -1
sybase.max_links = -1
sybase.min_error_severity = 10
sybase.min_message_severity = 10
sybase.compatability_mode = Off

[Sybase-CT]
sybct.allow_persistent = On
sybct.max_persistent = -1
sybct.max_links = -1
sybct.min_server_severity = 10
sybct.min_client_severity = 10

[bcmath]
bcmath.scale = 0

[Informix]
ifx.default_host =
ifx.default_user =
ifx.default_password =
ifx.allow_persistent = On
ifx.max_persistent = -1
ifx.max_links = -1
ifx.textasvarchar = 0
ifx.byteasvarchar = 0
ifx.charasvarchar = 0
ifx.blobinfile = 0.
ifx.nullformat = 0

[Session]
session.save_handler = files
session.save_path = "/var/lib/php/session"
session.use_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor     = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = 0
session.bug_compat_warn = 1
session.referer_check =
session.entropy_length = 0
session.entropy_file =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 1
session.hash_bits_per_character = 5
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"

[MSSQL]
mssql.allow_persistent = On
mssql.max_persistent = -1
mssql.max_links = -1
mssql.min_error_severity = 10
mssql.min_message_severity = 10
mssql.compatability_mode = Off
mssql.secure_connection = Off

[Verisign Payflow Pro]
pfpro.defaulthost = "test-payflow.verisign.com"
pfpro.defaultport = 443
pfpro.defaulttimeout = 30

[Tidy]
tidy.clean_output = Off

[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400

zend_extension = /etc/ioncube/ioncube_loader_lin_5.3.so

As you can see, I have changed the default socket settings within the php.ini file, but I still get a socket error in PDO when I try to connect to MySQL. It leads me to believe that the PDO driver is not using the settings from the php.ini. I was sure that there was some way of configuring PDO, but there was nothing within my php.ini. Should there be settings for PDO within the php.ini, or are they contained elsewhere?

A: There is a different ini setting for the PDO mysql driver. It is called
pdo_mysql.default_socket

Have you tried to set this ini value? Please refer to http://php.net/manual/en/ref.pdo-mysql.php
The value can also being influenced during compile time using the following configure option:
--with-mysql-sock=/my/path/mysql.sock

Update: I've figured out that the problem is a known PHP bug.
First: you can workaround the problem when using 127.0.0.1 as the db host instead of localhost. PHP will connect trough a TCP socket this way.
To change the location you'll have to compile PHP from sources with special configuration options. I was successful to change the location of the mysql socket with the following (basic) command lines :
 ./configure \
  --with-mysql \
  --with-mysqli=mysqlnd \
  --enable-pdo \
  --with-pdo-mysql=mysqlnd \
  --with-mysql-sock=/home/mysql/mysqld.sock

 make
 make install

The final trick made the combination of the last both of them. --with-mysql-sock=file sets the location of the .sock file but it is just used if --with-pdo-mysql= is set to mysqlnd (mysql native driver). If this option is missing pdo would be linked against the libmysqlclient from the system. As a result of this you can also recompile libmysqlclient (with modified socket path) and leave php untouched.
Note: This is just the basic configuration to make PHP working with PDO. You'll need additional configuration options if you need additional extensions (like json, xml, whatever). You'll find the configuration that your Linux Distribution has used to compile PHP if you execute the (original distribution) version this way: php -i.


text:
Q: Ruby on Rails simple dropdown does not retain value on a page refresh using cookies I have this very simple dropdown that selects the currency I want my page to display in. However, whenever I change the currency and then refresh the page, the selected option changes back to USD (the default value). I attempted to use cookies, but it is not working.
Here is my HTML which is just a form that calls a method in my controller:
<%= form_tag "/cryptos/currency_selector" do %>
            <%= select_tag(cookies[:currency_symbol], options_for_select([['USD'], ['JPY'], ['AUD'], ['EUR'], ['GBP'], ['CHF']], params[:currency_symbol]), :onchange => "this.form.submit();") %>
          <% end %>

Controller Code which just prints out cookie value for testing:
#handles currency conversion dropdown selector
def currency_selector
 puts cookies[:currency_symbol]
end

It's not even setting my cookie since I get an empty string in the terminal. Any help would be greatly appreciated!

A: First the form on your page:
<%= form_tag "/cryptos/currency_selector" do %>
    <%= select_tag(:currency_symbol,
        options_for_select(
          ['USD', 'JPY', 'AUD', 'EUR', 'GBP', 'CHF'], cookies[:selected_currency]
        ),
        onchange: "this.form.submit();") %>
<% end %>

And in your controller method to which /cryptos/currency_selector points to:
  def currency_selector
    cookies[:selected_currency] = params[:currency_symbol]

    redirect_back fallback_location: root_url
  end

Further improvements you might consider:

*

*Move the list of available currencies into a model or at least a constant.

*Give the /cryptos/currency_selector path a proper name in your routes.rb and use that name in your form instead of the hardcoded path.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript: setInterval and for loop explanation i searched around for a couple of questions related to the use of the for loop and the setInterval function in JavaScript but i couldn´t find a concrete answer on why this snippet doesn´t work. Could someone explain please what´s happening under the hood and why this code doesn´t print anything at all?
for (let i = 0; i++; i < 10) {
    window.setInterval(function () {
        console.log('Test');
    } , 100)
}

A: Your for loop is not correct. The condition needs to be the second statement in the for loop.
Following code should work.
for (let i = 0; i < 10 ; i++; ) {
    window.setInterval(function () {
        console.log('Test');
    } , 100)
}

Expected Syntax for loop. You can read more here

for ([initialization]; [condition]; [final-expression])
              statement

EDIT 1:
Though all answers (including mine) mentioned that condition needs to be second statement in the for loop which is correct. There is one more additional  important behavior.
The for loop for (let i = 0; i++; i < 10) is actually correct in terms of grammar and even the javascript runtime executes this code.
But, as in your case, if the condition is evaluating to falsy value then it would exit the loop.
Breaking your for loop for (let i = 0; i++; i < 10) into each seperate construct

*

*Initialization: let i = 0; This statement initializes the value of variable i to 0.

*Condition: i++; Javascript evaluates the statement to check if the statement is true or not. In case of i++ the runtime firstly checks for the current value of i which is 0 . Since 0 is considered a falsy value the condition evaluates to false and hence the statement is not executed. Also, i++  statement is a post increment which basically increments i and then result the original value of i.
So, if you would have written loop like below, using the intiliaztion of i=1, then it would have worked, though it would be running infinitely untill the browser/Server crashes as the condition i++ would always evaluate to true. I hope that makes sense.
for (let i = 1; i++; i < 10) {
    // Statements would run
}

Or
for (let i = 0; ++i; i < 10) {   **// Pre increment**
    // Statements would run
 }

Or
for (let i = 0; i=i+1; i < 10) {   **// increment i by assigment
         // Statements would run
     }

Douglas Crockford in his book Good Parts mention about the usage of ++ & -- and how it can confuse readers.

A: your for loop syntax is wrong, should be
for (let i = 0;  i < 10; i++)

your setInterval code will run every 100 milliseconds for each iteration of the loop (so 10 times every 100 milliseconds)

A: Nothing to do with setInterval, you simply malformed your for loop:
This:
for (let i = 0; i++; i < 10)

Should be this:
for (let i = 0; i < 10; i++)

First declare the initial state of the loop, then the terminating state of the loop, then the incremental change of the loop.
Observe.


text:
Q: Poderiam me explicar a parte construtora por favor, não entendi class Negociacao {

    **constructor(_data, _quantidade, _valor) {
        Object.assign(this, {
            _quantidade,
            _valor
        });
        this._data = new Date(_data.getTime())
        Object.freeze(this);
    }**

    getVolume() {
        return this._quantidade * this._valor;
    }

    getData() {
        return new Date(this._data.getTime());
    }

    getQuantidade() {
        return this._quantidade;
    }

    getValor() {
        return this._valor;
    }

}

A: analizando o construtor abaixo, o que acontece:
    constructor(_data, _quantidade, _valor) {
        Object.assign(this, {
            _quantidade,
            _valor
        });
        this._data = new Date(_data.getTime())
        Object.freeze(this);
    }

*

*São passados 3 valores para este construtor, _data, _quantidade e _valor.

*O método Object.assign(), atribui a this, no caso a classe Negociacao, os valores _quantidade e _valor (que na estrutura de classes, são atributos do objeto).

*Atribui a classe o valor de _data.

*O método Object.freeze(), congela o objeto, ou seja, não são permitidas mais modificações dos atributos fora do construtor.

Então, como conclusão, este construtor atribui valores iniciais para a classe Negociacao e a congela, para que novos valores não possam ser inputados após a construção da classe.
Referêcias:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze


text:
Q: Unable to display error message in IE but can display in Chrome I have a save button and on click of save, if the validation has failed it should throw an error 'Serial ID is required'.
This works fine with chrome browser but is not displaying in IE
HTML:

Serial ID is required

javascript:
$("#Save").on("click", function(e){
    $("#errorRow").css("visibility", "hidden");
    $("#errorRow").css("display", "none");

    //Validate
    if($("#form").val() == "")
    {
        $("#errorRow").css("visibility", "visible");
        $("#errorRow").css("display", "contents");
        return;
    }
});

A: "Note: "display: contents" does not work in Edge/Internet Explorer."
Quote from...
https://www.w3schools.com/cssref/pr_class_display.asp
Display block is more appropriate.
$("#Save").on("click", function(e){
$("#errorRow").css("visibility", "hidden");
$("#errorRow").css("display", "none");

//Validate
if($("#form").val() == "")
{
    $("#errorRow").css("visibility", "visible");
    $("#errorRow").css("display", "block");
    return;
}
});


text:
Q: Fix headphone jack so that the output is stereo, not part of surround sound I have an issue when listening to music through my headphones - sound appears to get lost, as if I had surround sound output and plugged in a stereo device. Moving the balance all the way to the left or right helps some, but the output isn't quite properly balanced.
What can I try to fix/troubleshoot this issue? I haven't been able to find much on the web about this particular topic.

A: The issue turned out to be hardware related. I tried a different set of speakers, and they worked fine. It turns out the plug didn't connect quite properly with the connections in the jack.


text:
Q: Is there a way to call a function on closing the server process in shiny? I have a shiny application in which I am making some connections to databases and other components. I wish to close these connections when the app is brought down. Is there a way to execute a function when the shiny app is closed?

A: As mentioned in the comments by @jdharrison you can us session$onSessionEnded in the shiny server.
This extremely simple example will print a message to the console when you close the app, but you can replace that print statement with some statements that close the database connections.
library(shiny)
ui <- fluidPage(
   #Empty UI
)

server <- function(input, output,session) {

  session$onSessionEnded(function() {
    print('hello, the session has ended')
  })
}

shinyApp(ui = ui, server = server)

A: As has been previously said, you can perform an action at the conclusion of a session by using session$onSessionEnded. This would work if you make one database connection for each user session, but often you might instead be sharing one database connection between multiple users. In that case you need run code when the server function terminates. This can be done using the onStop() function (https://shiny.rstudio.com/reference/shiny/latest/onStop.html). Example from the documentation:
library(shiny)
shinyApp(
  ui = basicPage("onStop demo"),

  server = function(input, output, session) {
    onStop(function() cat("Session stopped\n"))
  },

  onStart = function() {
    cat("Doing application setup\n")

    onStop(function() {
      cat("Doing application cleanup\n")
    })
  }
)


text:
Q: Why does Dataflow erratically fail in Datastore access? My simple Dataflow pipeline successfully copies multiple Kinds from one project's Datastore to another in most cases. But in certain Kinds (about 5% of them),  we always get these errors.
Dataflow retries 4-8 times with a delay of about 75 seconds, and then the pipeline fails.
How can I diagnose and resolve this?
EDIT: The answer includes: (1) there was a bug in the Datastore library used by Dataflow; after they fixed this bug, you can see the underlying cause and (2) the default batch size  for putting entities in this library is 500, which is also the max, and that goes over the 10 Mb limit of the Datastore API.
The (very simple) Pipeline looks like this:
Query.Builder qb = Query.newBuilder();
qb.addKindBuilder().setName(kindName);
Query query = qb.build();
Read dsRead = DatastoreIO.v1().read().withProjectId(inputProject).withQuery(query);
Write dsWrite = DatastoreIO.v1().write().withProjectId(outputProject);
PCollection<Entity> sourceEntities = pipeline.apply("read", dsRead);
Bound<Entity, Entity> entityFromSrcToTarget = ParDo.of(new EntityDoFn());/*Simple DoFn that copies Entities for insertion to target*/
PCollection<Entity> clonedEntities = sourceEntities.apply("clone-entity", entityFromSrcToTarget);
clonedEntities.apply("write-to-ds", dsWrite);

First stacktrace
com.google.datastore.v1.client.DatastoreException: I/O error, code=UNAVAILABLE at
com.google.datastore.v1.client.RemoteRpc.makeException(RemoteRpc.java:126) at
com.google.datastore.v1.client.RemoteRpc.call(RemoteRpc.java:95) at
com.google.datastore.v1.client.Datastore.commit(Datastore.java:84) at
com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1$DatastoreWriterFn.flushBatch(DatastoreV1.java:925) at
com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1$DatastoreWriterFn.finishBundle(DatastoreV1.java:899) Caused by: java.io.IOException: insufficient data written at
sun.net.www.protocol.http.HttpURLConnection$StreamingOutputStream.close(HttpURLConnection.java:3500) at
com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:81) at
com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981) at
com.google.datastore.v1.client.RemoteRpc.call(RemoteRpc.java:87) at
com.google.datastore.v1.client.Datastore.commit(Datastore.java:84) at
com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1$DatastoreWriterFn.flushBatch(DatastoreV1.java:925) at
com.google.cloud.dataflow.sdk.io.datastore.DatastoreV1$DatastoreWriterFn.finishBundle(DatastoreV1.java:899) at
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.finishBundle(DoFnRunnerBase.java:158) at
com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn.finishBundle(SimpleParDoFn.java:196) at
com.google.cloud.dataflow.sdk.runners.worker.ForwardingParDoFn.finishBundle(ForwardingParDoFn.java:47) at
com.google.cloud.dataflow.sdk.util.common.worker.ParDoOperation.finish(ParDoOperation.java:65) at
com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:80) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.executeWork(DataflowWorker.java:287) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.doWork(DataflowWorker.java:223) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.getAndPerformWork(DataflowWorker.java:173) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.doWork(DataflowWorkerHarness.java:193) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:173) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:160) at
java.util.concurrent.FutureTask.run(FutureTask.java:266) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at
java.lang.Thread.run(Thread.java:745)

Also
(9908b474b1492772): java.lang.RuntimeException:
com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException:
com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException:
com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException:
com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException:
com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException:
com.google.cloud.dataflow.sdk.util.UserCodeException:
com.google.datastore.v1.client.DatastoreException: I/O error, code=UNAVAILABLE at
com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn$1.output(SimpleParDoFn.java:162) at
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnContext.outputWindowedValue(DoFnRunnerBase.java:287) at
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnContext.outputWindowedValue(DoFnRunnerBase.java:283) at
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnProcessContext$1.outputWindowedValue(DoFnRunnerBase.java:507) at
com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsViaIteratorsDoFn.processElement(GroupAlsoByWindowsViaIteratorsDoFn.java:125) at
com.google.cloud.dataflow.sdk.util.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:49) at
com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.processElement(DoFnRunnerBase.java:138) at
com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:190) at
com.google.cloud.dataflow.sdk.runners.worker.ForwardingParDoFn.processElement(ForwardingParDoFn.java:42) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerLoggingParDoFn.processElement(DataflowWorkerLoggingParDoFn.java:47) at
com.google.cloud.dataflow.sdk.util.common.worker.ParDoOperation.process(ParDoOperation.java:55) at
com.google.cloud.dataflow.sdk.util.common.worker.OutputReceiver.process(OutputReceiver.java:52) at
com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:202) at
com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation.start(ReadOperation.java:143) at
com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:72) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.executeWork(DataflowWorker.java:287) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.doWork(DataflowWorker.java:223) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.getAndPerformWork(DataflowWorker.java:173) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.doWork(DataflowWorkerHarness.java:193) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:173) at
com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:160) at
 java.util.concurrent.FutureTask.run(FutureTask.java:266) at
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at
 java.lang.Thread.run(Thread.java:745)


text:
Q: How to create ancestor of an entity (google datastore) using php? I am working on google datastore. I need to create a Log kind of entity having user entity as its parent. I am using Google-api-php-client library to integrate the api in php. I am succeed in creating entites. To insert an entity I'm using following functions.
/*
 *Function to insert the entity into the google datastore.
 */
function google_set_insert($data) {

  $field_set = $data['field_set'];
  $entity_kind = $data['entity_kind'];
  $entity_name = $data['entity_name'];

  $entity = google_create_entity($field_set, $entity_kind, $entity_name);
  $mutation = new Google_Service_Datastore_Mutation();
  $mutation->setInsert($entity);
  $req = new Google_Service_Datastore_CommitRequest();
  $req->setMode('NON_TRANSACTIONAL');
  $req->setMutations($mutation);
  return $req;
}

But I am unable to create the ancestor of an entity. Can you please tell me what I am missing?

A: We recommend using the Google Cloud PHP client library (as long as you are not on GAE Standard).
You need to add the ancestor when you first create the entity, since it cannot be changed once initially written.
use Google\Cloud\Datastore\DatastoreClient;

$datastore = new DatastoreClient();

$key = $datastore->key('Person', 'Bob');
$key->ancestor('Parents', 'Joe');
$entity = $datastore->entity($key, [
    'firstName' => 'Bob',
    'lastName' => 'Testguy'
]);

echo $entity['firstName']; // 'Bob'
$entity['location'] = 'Detroit, MI';

See more in the documentation for keys.


text:
Q: Control error VS WP8.1
Cannot find type System.Windows.Controls.Control in module System.Windows.dll

Hi. I get this error in my WP8.1 App. I don't know what could be. I read all posts from StackOverflow and I didn't find anything. Also, all I get is this error, no line or file specified.

A: Use this namespace : Windows.UI.Xaml.Controls


text:
Q: Convert JSON tree data to nodes and links Good Day,
i like to know how to convert tree data from flare.json into nodes and links?
many thanks in advance, also i´m not using a tree visualization i need it for an Force-directed graph
from

to

A: Good Day .. the solution for me is very simple.. let´s tweak the d3:
checked on : http://bl.ocks.org/eesur/be2abfb3155a38be4de4


text:
Q: How to find tags that are not surrounded by specific tags and wrap them with tags Using Beautifulsoup, I want to find  not enclosed by
 and enclose it with
 but I do not know how to do it

example1.com

example2.com

example3.com

example3.com

I would like to change html as above

example1.com

example2.com

example3.com
 <-here

example3.com

A: You need to select those anchors using css selector and wrap each of them with p tag
In [2]: from bs4 import BeautifulSoup as BS

In [3]: html = """
example1.com

   ...:
example2.com

   ...: example3.com
   ...:
example3.com
"""

In [4]: soup = BS(html, "html.parser")

In [5]: for a in soup.select("p ~ a"):
   ...:     a.wrap(soup.new_tag("p"))
   ...:

In [6]: soup
Out[6]:

example1.com

example2.com

example3.com

example3.com

A: soup = BeautifulSoup(...)
items = soup.find_all('a')
for item in items:
    if item.parent.name != u'p':
        item.wrap(soup.new_tag('p'))

A: Try this:
from bs4 import BeautifulSoup

    data = """

example1.com

example2.com

    example3.com

example3.com

    """

    soup = BeautifulSoup(data, 'html.parser')
    for a in soup('a'):  # shortcut for soup.find_all('p')

        if a.parent.name != 'p' :
            a.wrap(soup.new_tag("p"))
    print soup


text:
Q: Of sum of cosines and the $7$th roots of unity In my solution here, it was shown that
$$\omega+\omega^2+\omega^4=-\frac 12\pm\frac{\sqrt7}2\qquad\qquad (\omega=e^{i2\pi/7})$$
from which we know that
$$\sin \frac{2\pi}7+\sin \frac{4\pi}7-\sin \frac{6\pi}7=\Im (\omega+\omega^2+\omega^4)=\frac{\sqrt7}2$$
This can also be verified easily by computation.
By the same token it would appear that
$$\cos \frac{2\pi}7+\cos \frac{4\pi}7-\cos \frac{6\pi}7=\Re (\omega+\omega^2+\omega^4)=\frac 12$$
However a quick computational check shows that the result is $1.3019...$ and not $\frac 12$.
Why is this so?

A: In that answer there is the following equality
$$\begin{align}
\sin\frac{2\pi}7+\sin\frac{4\pi}7-\sin\frac{6\pi}7
&=\Im(\omega^1+\omega^2-\omega^3)\\
&=\Im(\omega^1+\omega^2+\omega^4)\\
&=\Im(S)\\
&=\dfrac{\sqrt{7}}{2}\\
\end{align}.$$
For the real part you have
$$\begin{align}
-\dfrac{1}{2}&=
\Re(S)\\
&=\Re(\omega^1+\omega^2+\omega^4)\\
&=\Re(\omega^1+\omega^2+\omega^3)\\
&=\cos\frac{2\pi}7+\cos\frac{4\pi}7+\cos\frac{6\pi}7
\end{align}$$

A: You're starting from the wrong assumption that $-\omega^3=\omega^4$, which is obviously wrong, because it would imply $\omega=-1$.
The true fact is that
$$
-\sin\frac{6\pi}{7}=\sin\frac{8\pi}{7}
$$
but
$$
\cos\frac{6\pi}{7}=\cos\frac{8\pi}{7}
$$
because
$$
\frac{6\pi}{7}+\frac{8\pi}{7}=2\pi
$$
and
$$
\sin(2\pi-\alpha)=-\sin\alpha,\qquad
\cos(2\pi-\alpha)=\cos\alpha
$$


text:
Q: How to solve the Sleeping Barbers analogy with multiple barbers in Python? I have a working solution for the Sleeping Barber operating system problem using python 2.7 and threading that works with a single barber and a certain amount of chairs. But I would like it to be able to work in a situation where there are multiple barbers, in the same way as there is multiple customers.
Here is my current solution with a single barber:
from threading import Thread, Lock, Event
import time, random
from sys import exit
lock = Lock()
customerIntervalMin = 5
customerIntervalMax = 15
haircutDurationMin = 3
haircutDurationMax = 15

class BarberShop:
        waitingCustomers = []
        threads=[]
        finishedCustomers = []

        def __init__(self, barber, numberOfSeats):
                self.barber = barber
                self.numberOfSeats = numberOfSeats

        def openShop(self):
                print 'Barber shop is opening'
                workingThread = Thread(target = self.barberGoToWork)
                workingThread.start()
                self.threads.append(workingThread)

        def barberGoToWork(self):
                while True:
                        lock.acquire()

                        if len(self.waitingCustomers) > 0 and len(self.finishedCustomers)< 5:
                                c = self.waitingCustomers[0]
                                del self.waitingCustomers[0]
                                lock.release()
                                self.barber.cutHair(c)
                                self.finishedCustomers.append(c)
                        elif  len(self.waitingCustomers)==0 and len(self.finishedCustomers)<5:
                                lock.release()
                                print 'Aaah, all done, {0} is going to sleep'.format(barber.name)
                                barber.sleeps()
                                print '{0} woke up'.format(barber.name)
                        elif len(self.waitingCustomers)==0 and len(self.finishedCustomers)==5:
                                lock.release()
                                print 'The barber shop is closed. Come back tomorrow.'
                                exit(0)

        def enterBarberShop(self, customer):
                lock.acquire()
                print '{0} entered the shop and is looking for a seat'.format(customer.name)

                if len(self.waitingCustomers) == self.numberOfSeats:
                        print 'Waiting room is full, {0} is leaving.'.format(customer.name)
                        lock.release()
                else:
                        print '{0} sat down in the waiting room'.format(customer.name)
                        self.waitingCustomers.append(c)
                        lock.release()
                        barber.wakeUp()

class Customer:
        def __init__(self, name):
                self.name = name

class Barber:
        def __init__(self, name):
                self.name = name

        barberEvent = Event()

        def sleeps(self):
                self.barberEvent.wait()

        def wakeUp(self):
                self.barberEvent.set()

        def cutHair(self, customer):
                self.barberEvent.clear()
                print '{0} is having a haircut done by {1}'.format(customer.name, self.name)
                randomHairCuttingTime = random.randrange(haircutDurationMin, haircutDurationMax+1)
                time.sleep(randomHairCuttingTime)
                print '{0} is done with {1}'.format(customer.name, self.name)

if __name__ == '__main__':
        customers = []
        customers.append(Customer('Ken'))
        customers.append(Customer('Scott'))
        customers.append(Customer('Larry'))
        customers.append(Customer('Liam'))
        customers.append(Customer('Kieran'))

        barber = Barber('Mark')
        barberShop = BarberShop(barber, numberOfSeats=10)
        barberShop.openShop()

        while len(customers) > 0:
                c = customers.pop()
                barberShop.enterBarberShop(c)
                customerInterval = random.randrange(customerIntervalMin,customerIntervalMax+1)
                time.sleep(customerInterval)

I'm confused as to how to go about this. I originally thought it would be the same as the customers list inside the main where you would just append the class & the given name parameter into a list, use a loop to go through the list, pop each instance in the list & assign that to barber & keep the original barberShop definition in the main. But upon reflection that can't be right because that would just create 3 different threads with 10 seats each. So now I am unsure of how to solve the last part of this problem and while there is plenty of online implementations of this specific aspect of the problem in languages like Java & C but I don't have enough experience with those languages to even understand those solutions, let alone translate them into python & implement aspects of it in the solution above.
Is there any other way I can implement multiple barbers into this solution? Any help at all on this aspect of the problem or any suggestions for improvements that can be made to my solution would be greatly appreciated.

A: You need to design your system exactly as you've described in words: you instantiate three barbers, each of whom has full permissions on the same ten-chair waiting room.  This means that your mutex operations have to be hardy enough for 3 actors and 10 targets.  You also have to allow a new customer to wake up a sleeping barber, regardless of how many are asleep.
Think in terms of your barber states and your customer states.  Focus on each combination in turn, and design how the system should react.  Then, given those various actions (e.g. "customer wakes up barber", "barber moves customer to work chair"), decide how to allocate your methods to classes.
Does that help you get moving?


text:
Q: Type '{}' is missing the following properties from type 'IFilteredProjectionTableProps': I have a react functional component which goes like this
const Strategy: React.FC<IFilteredProjectionTableProps> = props => {
....
...
}
export default Strategy;

This FC is assigned to as the component property of a tab element in this way
interface ITabInfo {
  id: number;
  name: string;
  component: ReactElement;
}

const tabs: ITabInfo[] = [
  { id: 0, name: 'Board', component: <Board/> },
  { id: 1, name: 'Manager', component: <Manager /> },
  {
    id: 2,
    name: 'Strategy',
    component: <Strategy />
  },
  { id: 3, name: 'New', component: <Create /> }
];

This assignment of the FC to the reactelement is raising this error "Type '{}' is missing the following properties from type 'IFilteredProjectionTableProps': ......"
What am I doing wrong ?


text:
Q: How many distinct homeomorphism classes of lens spaces are there with a fixed p? This question is about the topological classification of lens spaces. Fix $p$ a positive integer, not necessarily a prime. From Brody, The topological classification of lens spaces, Annals of Math.
(2) 71 pp 163-184, the lens spaces $L(p,q_1)$ and $L(p,q_2)$ are homeomorphic if and only if either $q_1\equiv \pm q_2$ (mod $p$) or $q_1q_2\equiv \pm 1$ (mod $p$). Now the question is, for fixed $p$, how many homeomorphism classes of lens spaces are there with this fixed $p$. In particular, is there a formula $f(p)$ that gives the number of homemorphism classes as a function of $p$.
Example: When $p=7$, then $q$ can be chosen from the set $\{1,2,3,4,5,6\}$ (since any such $q$ is coprime to 7) and we find that $L(7,1)\approx L(7,6)$ (where $\approx$ denotes homeomorphism) and $L(7,2)\approx L(7,3)\approx L(7,4)\approx L(7,5)$ so that there are two distinct homeomorphism classes of lens spaces with $p=7$. Thus $f(7)=2$.
Example: When $p=8$, then $q$ can be chosen from the set  $\{1,3,5,7\}$ (since $p$ and $q$ need to be coprime) and then $L(8,1)\approx L(8,7)$ and $L(8,3)\approx L(8,5)$ so in this case there are again two homeomorphism classes of lens spaces with $p=8$. Thus $f(8)=2$.
Remark: For any $p$, the permissible $q$'s can be found and then Brody's formula can be applied to each such pair of $q$'s to determine which are homeomorphic to each other. Thus $f(p)$ can be computed by hand for any $p$.
My question is, is there a formula for $f(p)$?

A: This is an interesting question which can be solved by applying Burnside's lemma (as suggested by Qiaochu Yuan in a comment) and some knowledge of the group of units modulo $n$. The relevant facts about the groups of units mostly derive from the Chinese remainder theorem, quadratic reciprocity, and the knowledge that the group of units modulo a power of an odd prime is cyclic. This is all rather elementary group theory and number theory, but I found it to be a very instructional exercise. I have written the details below, partly for my own benefit.$\newcommand{\totient}{\varphi}$$\newcommand{\congruent}{\equiv}$$\newcommand{\To}{\longrightarrow}$$\newcommand{\ZZ}{\mathbb{Z}}$$\newcommand{\ZZmod}[1]{\ZZ/ #1 \ZZ}$$\newcommand{\set}[1]{\lbrace #1 \rbrace}$$\newcommand{\units}[1]{U(#1)}$$\newcommand{\size}[1]{\mathopen{}\mathclose{\left\lvert #1 \right\rvert}}$
I will first describe the final answer. Let $n > 2$ be an integer. The number $\psi(n)$ of distinct homeomorphism classes of $3$-dimensional lens spaces whose fundamental group has order $n$ is
$$ \psi(n) = \frac14 \bigl( \totient(n) + 2^{l(n) + \epsilon(n)} \bigr) $$
where $\totient$ is Euler's totient function. Moreover, $\epsilon(n)$ is $1$ if $-1$ is a quadratic residue modulo $n$, and zero otherwise. As will be shown below, $\epsilon(n) = 1$ if and only if $4$ does not divide $n$ and each of the odd prime divisors of $n$ is congruent to $1$ modulo $4$. Finally, describing $l$ requires the prime factorization of $n$:
$$ n = {p_1}^{\alpha_1} \cdots {p_k}^{\alpha_k} $$
where the numbers $p_i$ are distinct primes, and the $\alpha_i$ are positive integers. Assume further that $p_1$ is the smallest prime divisor of $n$. Then $l(n)$ is given by
$$ l(n) = \begin{cases}
k & \text{if }\ p_1 \neq 2 \\
k + \min\set{\alpha_1 - 2 , 1} & \text{if }\ p_1 = 2
\end{cases} $$
Notation.
To maintain a clear distinction between rings and groups, $\ZZmod{n}$ will denote the ring of integers modulo $n$, where $n$ is a positive integer. On the other hand, $C_n$ will denote a cyclic group with $n$ elements. The group of units in the ring $\ZZmod{n}$ is denoted by $\units{\ZZmod{n}}$. I will generally use multiplicative notation for the groups appearing in this answer.
Applying Burnside's lemma.
We follow here the suggestion of Qiaochu Yuan in a comment below the question. Fix an integer $n > 2$. Consider the group $G = C_2 \times C_2$, where $C_2 = \set{-1,1}$ with generator $-1$. Make $G$ act on $\units{\ZZmod{n}}$ in the following way: the generator $(-1,1)$ of the first copy of $C_2$ acts by taking a number to its negative (the additive inverse in $\ZZmod{n}$), and the generator $(1,-1)$ of the second copy of $C_2$ takes a number to its multiplicative inverse. From Brody's classification mentioned in the question, the set of homeomorphism classes of lens spaces with fundamental group of order $n$ is in bijection with the set of orbits for the action of $G$ on $\units{\ZZmod{n}}$. Let $\psi(n)$ denote the size of the quotient set $\units{\ZZmod{n}}/G$.
The so-called Burnside's lemma implies that
$$ 4\, \psi(n) = \size{G} \cdot \psi(n) = \sum_{g\in G} \size{\units{\ZZmod{n}}^g}    \tag{1a} $$
where $\units{\ZZmod{n}}^g$ denotes the set of fixed points of the action of $g$ on $\units{\ZZmod{n}}$, and $\size{\bullet}$ returns the size of a set. The fixed point sets corresponding to the first copy of $C_2$ are quickly determined. The unit $(1,1)\in G$ fixes everything in $\units{\ZZmod{n}}$ and thus contributes
$$ \size{\units{\ZZmod{n}}^{(1,1)}} = \size{\units{\ZZmod{n}}} = \totient(n) $$
The fixed points for the generator $(-1,1)\in G$ of the first copy of $C_2$ are the units $x \in \units{\ZZmod{n}}$ such that $2x = 0$ in $\ZZmod{n}$. The existence of such an invertible $x$ entails that $2 \congruent 0 \mod n$. Since $n>2$,
$$ \size{\units{\ZZmod{n}}^{(-1,1)}} = 0 $$
Square roots modulo $n$.
The fixed points for the remaining elements of $G$ are related to the number of square roots modulo $n$. For each $a\in\units{\ZZmod{n}}$, define the set of square roots of $a$:
$$ R(n,a) = \set{ x\in\units{\ZZmod{n}}  \mid  x^2 = a } $$
In particular, the set $R(n,a)$ is non-empty if and only if $a$ is a quadratic residue modulo $n$. Now, the fixed point set for the elements $(1,-1)$ and $(-1,-1)$ in $G$ consist precisely of the units which square to $1$ and $-1$, respectively:
$$ \begin{align*}
\units{\ZZmod{n}}^{(1,-1)} &= R(n,1) \\
\units{\ZZmod{n}}^{(-1,-1)} &= R(n,-1)
\end{align*} $$
Replacing everything back into (1a):
$$ 4\, \psi(n) = \totient(n) + \size{R(n,1)} + \size{R(n,-1)}    \tag{1b} $$
More generally, for any abelian group $A$ and an element $a\in A$, define the set:
$$ R(A,a) = \set{ x \in A  \mid  x^2 = a } $$
Then the sets of square roots modulo $n$ are an instance of this general definition: $R(n,a) = R\bigl(\units{\ZZmod{n}},a\bigr)$. Consider the squaring homomorphism $\sigma : A\to A$ on an abelian group $A$ which sends an element $x \in A$ to its square $x^2$ — we are using multiplicative terminology here. Then $R(A,a)$ is the fibre of $\sigma$ over $a \in A$: $R(A,a) = \sigma^{-1}(a)$. In particular, if $1 \in A$ denotes the identity element of $A$, $R(A,1)$ is the kernel of the squaring homomorphism, and is therefore an abelian group. The fibres of a group homomorphism are always torsors over the kernel, so $R(A,a)$ is a torsor over the group $R(A,1)$ for any $a\in A$. Hence, $\size{R(A,a)} = \size{R(A,1)}$ whenever $R(A,a)$ is non-empty. We conclude from equation (1b):
$$ 4\, \psi(n) = \totient(n) + \size{R(n,1)}(1 + \epsilon(n))    \tag{1c} $$
where $\epsilon(n) = 1$ if $R(n,-1)\neq\emptyset$ and $\epsilon(n) = 0$ if $R(n,-1)=\emptyset$. In other words, $\epsilon(n) = 1$ if and only if $-1$ is a quadratic residue modulo $n$.
Square roots and the Chinese remainder theorem.
As before, set the prime factorization of $n$ to $n = {p_1}^{\alpha_1} \cdots {p_k}^{\alpha_k}$, where the numbers $p_i$ are distinct primes, and the $\alpha_i$ are positive integers. According to the Chinese remainder theorem, there is an isomorphism of rings
$$ \ZZmod{n} = (\ZZmod{{p_1}^{\alpha_1}}) \times \cdots \times (\ZZmod{{p_k}^{\alpha_k}}) $$
determined by the canonical projections from $\ZZmod{n}$ onto each of the factors in the target. Consequently, we deduce an isomorphism between the groups of units:
$$ \units{\ZZmod{n}} = \units{\ZZmod{{p_1}^{\alpha_1}}} \times \cdots \times \units{\ZZmod{{p_k}^{\alpha_k}}} $$
Since $R\bigl(A\times B,(a,b)\bigr) = R(A,a) \times R(B,b)$, taking the set of square roots of $a\in\units{\ZZmod{n}}$ on each side of the previous expression produces:
$$ R(n,a) = R({p_1}^{\alpha_1},a) \times \cdots \times R({p_k}^{\alpha_k},a)    \tag{2} $$
In each term above, $a$ really stands for the projection of $a$ in the corresponding group.
Determining when $-1$ is a quadratic residue.
Recall that $a$ is a quadratic residue modulo $m$ if and only if $R(m,a) \neq \emptyset$. As a consequence of the isomorphism (2), $a \in \units{\ZZmod{n}}$ is a quadratic residue modulo $n$ if and only if $a$ is a quadratic residue modulo ${p_i}^{\alpha_i}$ for every $i\in\set{1,\ldots,k}$. The following claim reduces the case of a prime power modulus to the case of a prime modulus.
Proposition: Let $p$ be an odd prime, and $\alpha$ a positive integer. A unit $a \in \units{\ZZmod{p^\alpha}}$ is a quadratic residue modulo $p^\alpha$ if and only $a$ is a quadratic residue modulo $p$.
Proof:
Consider the projection map $\pi : \ZZmod{p^\alpha} \to \ZZmod{p}$, which is a ring map. Then $\pi^{-1}\bigl(\units{\ZZmod{p}}\bigr) = \units{\ZZmod{p^\alpha}}$: an integer $m$ becomes invertible in $\ZZmod{p^\alpha}$ if and only if it is coprime to $p^\alpha$, which happens precisely when $m$ is not divisible by $p$ and thus invertible in $\ZZmod{p}$. Hence, we obtain a short exact sequence of groups:
$$ 1 \To \pi^{-1}(1) \To \units{\ZZmod{p^\alpha}} \To \units{\ZZmod{p}} \To 1    \tag{ES} $$
The group $\pi^{-1}(1) = 1 + p(\ZZmod{p^\alpha})$ has order $p^{\alpha-1}$, which is odd. Therefore, the squaring homomorphism on $\pi^{-1}(1)$ is necessarily a self-bijection, and so every element in $\pi^{-1}(1)$ is a square. Chasing around the preceding short exact sequence, it follows that when $a \in \units{\ZZmod{p^\alpha}}$ is a quadratic residue modulo $p$, it is also a quadratic residue modulo $p^\alpha$.  ■
The first supplement to the law of quadratic reciprocity now implies the following result.
Corollary: If $p$ is an odd prime, and $\alpha$ is a positive integer, then $-1$ is a quadratic residue modulo $p^\alpha$ if and only $p \congruent 1 \mod 4$.
It remains to deal with the case of powers of the prime two. Observe that $-1$ is a quadratic residue modulo $2$. However, $-1$ is not a quadratic residue modulo $4$, and thus cannot be a quadratic residue modulo $2^\alpha$, for any $\alpha > 1$. The following proposition collects what we have learned in this section.
Proposition: Given an integer $n > 1$, $-1$ is a quadratic residue modulo $n$ — i.e. $\epsilon(n) = 1$ — if and only if:

*

*each odd prime divisor of $n$ is congruent with $1$ modulo $4$,

*and $4$ does not divide $n$.

Counting square roots of unity.
To finish the proof, we need to find the number of square roots of the unit in the ring $\ZZmod{n}$, that is, the size of $R(n,1)$. By (2), this is reduced to calculating the size of $R({p_i}^{\alpha_i},1)$ for each $i$. We will use the fact that $R(C_m,1) \cong C_1$ (where $1 \in C_m$ is the identity element) is trivial if $m$ is odd, and $R(C_m,1) \cong C_2$ if $m$ is even.
Claim: For $p$ an odd prime, and $\alpha$ a positive integer, $R(p^\alpha,1) \cong C_2$.
Proof: This follows from the fact that $\units{\ZZmod{p^\alpha}}$ is a cyclic group of even order equal to $p^{\alpha-1}(p-1)$ (stated on the relevant wikipedia page). Alternatively, it may be deduced from two results stated in the proof of the first proposition from the previous section: the short exact sequence (ES), and the observation that the squaring homomorphism is a bijection on the kernel of that exact sequence.  ■
Claim: For $\alpha > 2$, $R(2^\alpha,1) \cong C_2 \times C_2$. Moreover, $R(4,1) \cong C_2$ and $R(2,1) \cong C_1$. In particular, $\size{R(2^\alpha,1)} = 2^{\min\set{\alpha-1,2}}$ for each positive integer $\alpha$.
Proof: This is a consequence of the following facts (see the wikipedia page):

*

*$\units{\ZZmod{2}} \cong C_1$, so that $R(2,1) \cong C_1$;

*$\units{\ZZmod{4}} \cong C_2$, so that $R(4,1) \cong C_2$

*for $\alpha > 2$, $\units{\ZZmod{2^\alpha}} \cong C_2 \times C_{2^{\alpha-2}}$, so that $R(2^\alpha,1) \cong C_2 \times C_2$.

For reference, section 4.5 of Helmut Hasse's book Number theory proves the results, identifying the groups $\units{\ZZmod{p^\alpha}}$, which were used in this proof and in the previous one.  ■
Using the isomorphism (2), these two claims prove that $R(n,1)$ is the product of a certain number of cyclic groups of order $2$. We calculate:
$$ \size{R(n,1)} = \prod_{i=1}^k \size{R({p_i}^{\alpha_i},a)} = 2^{l(n)} $$
Here, $l(n) = l({p_1}^{\alpha_1} \cdots {p_k}^{\alpha_k})$ is as defined at the beginning:
$$ l(n) = \begin{cases}
k  &  \text{if }\ p_1 \neq 2 \\
k + \min\set{\alpha_1 - 2 , 1}  &  \text{if }\ p_1 = 2
\end{cases} $$
where we assume that $p_1$ is the smallest prime number which divides $n$.
Finally, equation (1c) implies
$$ 4\, \psi(n) = \totient(n) + 2^{l(n)}(1+\epsilon(n)) = \totient(n) + 2^{l(n) + \epsilon(n)} $$
since $\epsilon(n)$ only takes the values $0$ and $1$.


text:
Q: Help with setting up MySQL on a dedicated server - detailed report given I need help because I do not understand much MySQL settings on a dedicated server.
I have one WordPress website installed with medium traffic with W3 Total Cache.
The storage engine is InnoDB.
Below is my configuration and report from MySQLTuner which I do not understand much and need some help, please.
Server
CPU: 8 cores / 8 threads, 1 CPU
64bit architecture
L3 cache: 8MB
Speed: 2400 MHz
RAM: 32GB RAM DDR3
Storage: 2x250GB SSD (RAID1)
Link: 1Gbps

Setup
Debian 7 (Linux)
Nginx
PHP 5.4 using php-fpm (cache: PHP-APC, PHP-memcache, Memcached)
MySQL 5.5

MySQL config
key_buffer 512M
max_allowed_packet 16M
thread_stack 256K
thread_cache_size 286
table_cache 1024
table_open_cache 16384
table_definition_cache 8192
sort_buffer_size 32M
read_buffer_size 32M
read_rnd_buffer_size 32M
join_buffer_suze 32M
query_cache_limit 20M
query_cache_size 2048M
tmp_table_size 1024M
max_heap_table_size 1024M
innodb_buffer_pool_size 20G
innodb_buffer_pool_instances 8
[mysqldump]
max_allowed_packet 16M
[isamchk]
key_buffer 16M

MySQLTuner report
-------- CVE Security Recommendations     --------------------------------------------------------------
[OK] NO SECURITY CVE FOUND FOR YOUR VERSION

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 1d 21h 26m 35s (8M q [49.822 qps], 471K conn, TX: 399G, RX: 1G)
[--] Reads / Writes: 87% / 13%
[--] Binary logging is disabled
[--] Physical Memory     : 31.4G
[--] Max MySQL memory    : 42.4G
[--] Other process memory: 5.7G
[--] Total buffers: 23.5G global + 128.2M per thread (151 max threads)
[--] P_S Max memory usage: 0B
[--] Galera GCache Max memory usage: 0B
[!!] Maximum reached memory usage: 26.8G (85.18% of installed RAM)
[!!] Maximum possible memory usage: 42.4G (135.00% of installed RAM)
[!!] Overall possible memory usage with other process exceeded memory
[OK] Slow queries: 0% (0/8M)
[OK] Highest usage of available connections: 17% (26/151)
[OK] Aborted connections: 0.12%  (576/471646)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[OK] Query cache efficiency: 59.6% (3M cached / 5M selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (42 temp sorts / 629K sorts)
[OK] No joins without indexes
[!!] Temporary tables created on disk: 56% (236K on disk / 414K total)
[OK] Thread cache hit rate: 99% (26 created / 471K connections)
[OK] Table cache hit rate: 84% (1K open / 2K opened)
[OK] Open file limit used: 5% (1K/32K)
[OK] Table locks acquired immediately: 99% (2M immediate / 2M locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Performance schema is disabled.
[--] Memory used by P_S: 0B
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 21.5% (115M used / 536M cache)
[OK] Key buffer size / total MyISAM indexes: 512.0M/416.0K
[OK] Read Key buffer hit rate: 100.0% (148M cached / 16K reads)
[!!] Write Key buffer hit rate: 53.2% (546K cached / 290K writes)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[!!] InnoDB File per table is not activated
[OK] InnoDB buffer pool / data size: 20.0G/1.9G
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (0.048828125 %): 5.0M * 2/20.0G should be equal 25%
[!!] InnoDB buffer pool instances: 8
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[OK] InnoDB Read buffer efficiency: 100.00% (12017309000 hits/ 12017381306 total)
[!!] InnoDB Write Log efficiency: 59.93% (169492 hits/ 282840 total)
[OK] InnoDB log waits: 0.00% (0 waits / 113348 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] Binlog format: STATEMENT
[--] XA support enabled: ON
[--] Semi synchronous replication Master: Not Activated
[--] Semi synchronous replication Slave: Not Activated
[--] This is a standalone server

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
Reduce your overall MySQL memory footprint for system stability
Dedicate this server to your database for highest performance.
Enable the slow query log to troubleshoot bad queries
Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
Temporary table size is already large - reduce result set size
Reduce your SELECT DISTINCT queries without LIMIT clauses
Consider installing Sys schema from github
Before changing innodb_log_file_size and/or innodb_log_files_in_group read this
Variables to adjust:
*** MySQL's maximum memory usage is dangerously high ***
*** Add RAM before increasing MySQL buffer variables ***
query_cache_size (=0)
query_cache_type (=0)
innodb_file_per_table=ON
innodb_log_file_size should be (=2G) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
innodb_buffer_pool_instances(=20)

Please help. Thanks.

A: Suggestions to consider for your my.cnf [mysqld] section
Lead with # spacebar to allow defaults to work for you for the following
sort_buffer_size
read_buffer_size
read_rnd_buffer_size
join_buffer_size

the values you have above are impacting the RAM footprint for no useful purpose
thread_cache_size=100  # from 286  for CAP suggested in v 8.0 to avoid OOM
key_buffer_size=256M  # from 512M because only 115M used
key_cache_age_threshold=64800  # from 300 seconds to reduce key_reads
key_cache_division_limit=50  # from 100 percent for Hot/Warm caches
key_cache_block_size=16384  # from 1024 to minimize overhead
tmp_table_size=320M  # from 1024M for 1% of RAM
max_heap_table_size=320M  # should always be same size as tmp_table_size
innodb_buffer_pool_size=4G  # from 20G with ~2G of data and ndx's 4G allows growth

for additional assistance, see my profile for contact info.
Would like to have feedback on your success when time permits.


text:
Q: Nextjs automatic deployment to a cpanel using github actions I have successfully deployed a static html, css site to my "Bluehost" cPanel using GitHub actions, when I tried to deploy my Next.js app I failed, during the first try I get a plain web page with index and the folders of my projects after doing some research I have tried to upload the build folder to the FTP and it gave me the same error.
The plain web page after uploading the build folder files:

Anyway I know that I'm doing it the wrong way. All I'm asking for is the best automated way to deploy my Next.js app to the cPanel using GitHub actions or any other automated tools.


text:
Q: Strange issue with Json & PHP There is any reason why a json string fail to be evaluated (transport.responseText.evalJSON();) on the server but works on my local installation ?
I'm doing a simple ajax request like this one:
new Ajax.Request(
        this.saveUrl, {
            method: 'post',
            parameters: Form.serialize(this.form),
            onLoading: function () {
                totals.update('

');
            },
            onSuccess: function (transport) {
                if (transport.status == 200) {
                    var data = transport.responseText.evalJSON();
                    totals.update(data.shipping_method);
                }
            },
            onFailure: checkout.ajaxFailure.bind(checkout)
        }
    );

On server side I output an array containing some html:
 $data = array(
            'shipping_method' => $shipping_method,
            'payment_method' => $payment_method
        );

echo json_encode($data);

I have tried to valorize $total and '$other' as empty string '' but I get the same result:
transport.responseText.evalJSON(); return an "unexpected token"
As said above the weird thing is that on my local it works ( the output is the same as the server but js doesn't trigger any error )
I'm struggling with this almost all day ... any help is really appreciate thanks
UPDATE:
console.log(transport.responseText)
-> {"shipping_method":"","payment_method":""}

Inspecting the server response 'network tab' in chrome I can see a small difference, in comparison to my local: there is a small red dot before the response content if ( is say \ufeff if I move the mouse over it, I'm not sure about the meaning ... )

A: After some test I found out that the issue is encoding used in some PHP files, my co-worked had the brilliant idea to switch to ANSI. (ISO-8859)
For some reason these files coded with ANSI produced JSON content to be different:

*

*chrome inspector was showing a red dot -> Byte_order_mark \ufeff character (aka BOM)

This probably means the BOM character is missing and this was breaking the json parse.
SOLUTION:
After I parsed and cleaned all my project files from the BOM character, chrome doesn't show the red dot in the inspector and the issue is gone
Still it is not clear why on my local installation the issue was not present while on the server it was ( both linux ) but there are probably multiple settings involved here ...
To clean your files see: Elegant way to search for UTF-8 files with BOM?

A: you can use map function to evaluate json value
       $.map(transport, function (item){
 totals.update(item.total);;
       });

I think its Working fine


text:
Q: How to make gwt material table I got gwt material table from github https://github.com/GwtMaterialDesign/gwt-material-table
But i am not getting any jar of it to inherit. So if any one who got the jar please reply me.
If jar is not there then what we have to do either using the class from git or any other way.
After having research on it i have try to make plugin by taking all file from git but $this() is creating a problem.
I can't able figure out what is use of $this() in gwt. I have also include the file gwt material query but then also the  method $this() is undefined for the type AbstractDataTable error is comming.

A: You will need to add this to your pom.xml
<!-- For GWT Material JQuery -->
<dependency>
   <groupId>com.github.gwtmaterialdesign</groupId>
   <artifactId>gwt-material-jquery</artifactId>
   <version>1.0-SNAPSHOT</version>
</dependency>

<!-- For GWT Material Table -->
<dependency>
   <groupId>com.github.gwtmaterialdesign</groupId>
   <artifactId>gwt-material-table</artifactId>
   <version>1.0-SNAPSHOT</version>
</dependency>

A: I'm not sure whether I understand your problem correctly. If it's about resolving dependency, you should be able simply to get it from Maven. As you see from Github, this is a Snapshot. It means you need to add proper repository to your pom.xml file. Please see the section "repositories" and details related to "snapshots-repo" provided there: https://github.com/GwtMaterialDesign/gwt-material-table/blob/master/pom.xml .
<dependency>
    <groupId>com.github.gwtmaterialdesign</groupId>
    <artifactId>gwt-material-table</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

Hope you'll find it helpful.


text:
Q: Define connection pool size in iis 7 (not by connection string) So our connection string is constructed from app settings rather than stored as an actual connection string. Stupid I know, was done years before I was here.
Question is, can I do something in the web.config or in IIS itself to define the processes default connection pool from a configuration standpoint so I don't have to change the code that creates the connection string and deploy a new version of the dal to increase the connection pool.
Ideas?

A: This cannot be done. Connection pool size can be defined only by connection string.


text:
Q: django orm how to make sure postgres array field is not an empty list? I have the following model for django. This model creates an array field called metric_vals but it is allowing the array to be an empty array. Is there a way of making sure the array is always a non empty array?
from django.db import models
import uuid
from django.contrib.postgres.fields import ArrayField

class SampleModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    metric_vals = ArrayField(models.FloatField(null=False), null=False, default=list)

A: You can use the validators kwarg:
from django.contrib.postgres.validators import ArrayMaxLengthValidator, ArrayMinLengthValidator

def get_default_list():
    return [float(1), float(2)]

class SampleModel(models.Model):
    metric_vals = ArrayField(
        models.FloatField(null=False),
        null=False,
        # ensure the default passes the validation
        default=get_default_list,
        # like this
        validators=[
           ArrayMinLengthValidator(2),
           ArrayMaxLengthValidator(10),
        ]
    )

Related:

*

*https://docs.djangoproject.com/en/4.1/ref/validators/

A: Something like this:
from django.core.exceptions import ValidationError

class SampleModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    metric_vals = ArrayField(models.FloatField(null=False), null=False, default=list)

    def save(self, *args, **kwargs):
        if self.metric_vals == []:
            raise ValidationError('Empty list not allowed')

        super().save(*args, **kwargs)


text:
Q: Cannot call method 'use' of undefined I have a problem with implementing passport in node.js express.
I am trying to follow different guides, but just won't succeed..
This time theres an error like this:

My code looks like this:
In app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
// TODO - Why Do we need this key ?
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());

Any idea why it wont work?
I have installed express-session, passport, passport-local etc.

A: you need to initialize app with express()
  var express= require('express');
    var app=express();


text:
Q: How can I divide one time string into years, months etc. and then calculate it in milies I am trying to write a method that calculate and divide one string, like:
13mo8w8d

In other words, 13 months, 8 weeks and 8 days.
I want to turn this string into the following:
1 Year 3 Months 1 Week and 1 Day

and then to get the total of this in milliseconds.
How can I do that?
What have I done?
public static long toMilliSec(String s) {
    String[] sl = s.toLowerCase().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
    long i = Long.parseLong(sl[0]);
    switch (sl[1]) {
        case "s":
            return i * 1000L;
        case "m":
            return i * 1000L * 60L;
        case "h":
            return i * 1000L * 60L * 60L;
        case "d":
            return i * 1000L * 60L * 60L * 24L;
        case "w":
            return i * 1000L * 60L * 60L * 24L * 7L;
        case "mo":
            return i * 1000L * 60L * 60L * 24L * 30L;
        case "y":
            return i * 1000L * 60L * 60L * 24L * 30L * 365L;
    }
    return -1L;
}

The problem in this case is logically that this just work for one, like 13d


text:
Q: java.lang.UnsatisfiedLinkError in my java program :( I created a program which uses JNI. I compiled it, generated header file, created a corresponding C program, and created dll for it.
I am running into an exception:
Exception in thread "main" java.lang.UnsatisfiedLinkError: D:\examples\FirstJNIExample.dll: Can't find dependent libraries
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.load0(Unknown Source)
at java.lang.System.load(Unknown Source)
at com.ankur.FirstJNIExample.(FirstJNIExample.java:9)
Could not find the main class: com.ankur.FirstJNIExample. Program will exit.
I don't know which all dlls my FirstJNIExample.dll is dependent on.
I saw in Dependency Walker that my dll is dependent on following dlls:
msvcr90.dll
kernel32.dll
and this kernel32.dll is dependent on:
ntdll.dll
I also see an error in Dependency Walker for msvcr90.dll that system can't find the file specified.
This dll is present in my system at this location: D:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT
When I thought of loading it on my own in code like this:
enter code here

System.load("D:/Program Files/Microsoft Visual Studio 9.0/VC/redist/x86/Microsoft.VC90.CRT/msvcr90.dll");
System.load("d:/examples/FirstJNIExample.dll");
I get a windows error:

Microsoft Visual C++ Runtime Library
Runtime Error!
Program: C:\Windows\system32\java.exe
R6034
An application has made an attempt to load the C runtime library incorrectly.
Please contact the application's support team for more information.

OK
And this exception:
Exception in thread "main" java.lang.UnsatisfiedLinkError: D:\Program Files\Micr
osoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\msvcr90.dll: A dynamiclink library (DLL) initialization routine failed
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.load0(Unknown Source)
at java.lang.System.load(Unknown Source)
at com.ankur.FirstJNIExample.(FirstJNIExample.java:10)
Could not find the main class: com.ankur.FirstJNIExample. Program will exit.
I am just lost. So many questions:
Why my dll is dependent on msvcr90.dll?
How do I load this dll?
I never worked with dlls before.

A: Looks like you need a manifest, or to switch to static linking, and/or manipulate PATH.
Almost any C++ code you write on Windows will make use of the MSVC runtime. By default, that code is linked dynamically. If you use dumpbin /imports on your JNI DLL you will see the dependency.
The JRE calls LoadLibrary and not LoadLibraryEx, so it isn't good enough to have the dependency sitting right next to the JNI library. You have to have the directory containing the MSVC runtime DLL in PATH. Or, you need to link it statically, but I'm not sure this is possible with MSVC90. Or, you need to manifest it.


text:
Q: Custom upscale filter in matlab Is it possible to upscale a 960x540 raw video to 1920x1080 using a custom filter in matlab?
The filter I want to use is [1 2 3 3 2 1] 1/12
imresize has custom interpolation kernel but i don't know how to use it with my filter instead of lanczos2 filter.
B = imresize(A, [1920 1080], {@lanczos2,4.0} )

function f = lanczos2(x)
f = (sin(pi*x) .* sin(pi*x/2) + eps) ./ ((pi^2 * x.^2 / 2) + eps);
f = f .* (abs(x) < 2);
end

A: You are not thinking about interpolation kernels in the same way as imresize is. It requires a function of a real value x, not a discrete-time filter. So you could make such a function, 'mykern.m':
function f = mykern(x)
f = (3 - floor(abs(x)))/12 .* double(abs(x) <= 3);

and call imresize(x, 2, {@mykern,6}) on each frame.
If you are confused about how these kernels work, it's useful to plot them:
n = -5:.1:5;
figure; plot(n, lanczos2(n));
figure; plot(n, mykern(n));

Or, you could avoid using imresize by upsampling your image and then filtering it. But in this case you would want to use a 2D filter.
As for reading and writing video, look at the examples for VideoReader and VideoWriter


text:
Q: mySQL: Issue Using LIMIT I'm attempting to query 200 users, but don't know the exact Subj_Ids. Therefore, I cannot just query a range of Subj_Ids (though I know I want to start at 200), but need to set a limit on the range of Subj_Ids I'm querying. I tried:
SELECT *
    FROM session2
    WHERE Subj_Id > 200
    AND Subj_Id IN (
        SELECT Subj_Id
            FROM userdata
            WHERE `Primary Lang` != ''
            OR `Primary Lang` != '-'
            OR `Primary Lang` != '--'
    )
    LIMIT 200;

However, it only returns a handful of Subj_Ids. Is this an issue with my syntax, or with the db I'm using?

A: Select the users that you want in a subquery and then join back to get the sessions.
You are not clear about the format of the tables.  The following assumes that each table has a user_id and that user_id/subj_id define a session:
select s.*
from (SELECT user_id, max(subj_id) as maxsi
      FROM session2
      WHERE Subj_Id > 200 AND
            Subj_Id IN (SELECT Subj_Id FROM userdata WHERE `Primary Lang` not in ('', '-', '--') )
      group by user_id
      LIMIT 200
    ) u join
    session2 s
    on u.user_id = s.user_id and s.subj_id = maxsi


text:
Q: Is it possible to use teamcity message from shell scripts? I have several build steps that use command line with custom scripts. And i want to use teamcity messages. Like this ones:
##teamcity[message 'value']
##teamcity[buildNumber '<new build number>']
##teamcity[buildStatus status='<status value>' text='<text>']

But it seems that this commands are  not working at all. What's wrong with them? Is it possible to run this commands in shell scripts in teamcity? Any ideas how to use them?

A: In a shell script, use
echo "##teamcity[buildStatus status='<status value>' text='<text>']"

Here is the detailed docs for TeamCity 2020.2.


text:
Q: dda algorithm using OpenGL Errors while compiling:

*

*redefinition of 'y1' as different kind of symbol float x1 = 0, y1 = 0, x2 = 0, y2 = 0;

*non-object type 'double (double)' is not assignable
                       y1 = 240-y;

*no matching function for call to 'drawPixel'
                       drawPixel( x1, y1 );

*no matching function for call to 'dda'
                       dda( x1, y1, x2, y2 );

Code:
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

#include <iostream>
using namespace std;
#include <cstdlib>
#include <cmath>

//defining constants
#define MAX_WIDTH 640
#define MAX_HEIGHT 480

int flag = 1;
float x1 = 0, y1 = 0, x2 = 0, y2 = 0;
//method for drawing the pixel
void drawPixel( int x, int y ){

    glBegin( GL_POINTS );
        //setting the pointer color
        glColor3f( 1.0, 1.0, 1.0 );
        glVertex2i( x, y );

    glEnd();
    glFlush();
}

//display callback function
void display(){

    glClear( GL_COLOR_BUFFER_BIT );

    gluLookAt( 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 1.0, 0.0 );
    /*
    glBegin( GL_POINTS );
        //setting the pointer color
        glColor3f( 1.0, 1.0, 1.0 );
        glVertex2i( 0, 0 );
        glVertex2i( 10, 0 );

    glEnd();
    */
    glFlush();
}

//catching keyboard events
void keyboardEvent( unsigned char c, int x, int y ){

    if( c == 27 ){
        exit(0);
    }
}

//dda implementation
void dda( float m1 , float n1 , float m2 , float n2 ){

    float slope , Dx , Dy;
    float dx , dy , length;

    int i = 1;

    dx = dy = length = 0.0;
    slope = Dx = Dy = 0.0;

    dx = m2 - m1;
    dy = n2 - n1;
    slope = dy/dx;      //slope

    cout << m1 << "\t" << n1 << "\t" << m2 << "\t" << n2 << endl;

    length = (dx >= dy)?dx:dy ;
    cout << length<< endl;

    Dx = dx/length;
    Dy = dy/length;

    drawPixel( round(m1), round(n1) );
    cout << m1 << m2 << endl;

    for( ; i <= length ; i++ ){
        m1 = m1 + Dx;
        n1 = n1 + Dy;
        drawPixel( round(m1), round(n1) );
        cout << m1 << m2 << endl;
    }
}

//catching mouse click events
void mouseEvent( int button, int state, int x, int y ){

    //checking if the mouse button is clicked or not using state para.
    if( state == GLUT_DOWN ){

        if( button == GLUT_LEFT_BUTTON && flag == 1 ){
            x1 = 320-x;
            y1 = 240-y;
            drawPixel( x1, y1 );
            flag++;
        }
        else if( button == GLUT_LEFT_BUTTON && flag == 2 ){
            x2 = 320-x;
            y2 = 240-y;
            drawPixel( x2, y2 );
            flag++;
        }
        else if( button == GLUT_RIGHT_BUTTON && flag > 2 ){

            drawPixel( 320-x, 240-y );
            cout << x1 << "\t" << y1 << "\t" << x2 << "\t" << y2 << endl;
            dda( x1, y1, x2, y2 );
        }
    }
}

//adjusting window when it is moved or resized
void reshape( int w, int h ){

    glViewport( 0, 0, w, h );
}

//initialising the window at startup
void initialise(){

    glClearColor( 0.0, 0.0, 0.0, 1.0 );
    glPointSize( 5 );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( -320, 320, -240, 240 );

}

int main( int argc, char **argv ){

    //initialising the glut library
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
    glutInitWindowSize( MAX_WIDTH, MAX_HEIGHT );
    glutInitWindowPosition( 100, 100 );
    glutCreateWindow("DDA Assignment");

    //calling normal functions
    initialise();

    //registering callback functions
    glutDisplayFunc( display );
    glutKeyboardFunc( keyboardEvent );
    glutMouseFunc( mouseEvent );
    glutReshapeFunc( reshape );

    glutMainLoop();

    return 0;
}

A: If you compile this on POSIX, you will end up with <math.h> (and cmath)  declaring functions with the name y0, y1 and yn, which will totally conflict with any global variable of the same name.
Since you explicitely tagged this question as c++14, you should also tell your compile to use that standard by using
 g++ -std=c++14

(or any other appropriate version of the standard), which will also prevent the libc headers from declaring functions which are not in that standard.


text:
Q: Use Arduino to Plot the balance of my airplane propeller using optical sensor and reflective tape I would like to use an arduino to determine how out of balance my airplane propeller is.  I've seen a production device that uses an optical sensor and reflective tape to plot this.  Can this be done with an arduino, and if so, what would I need to do it?

A: The optical sensor is not sufficient. It works in conjunction with an accelerometer to measure the actual imbalance. An Arduino should be able to control the two sensors and have the results displayed. Interesting little project. Btw, the reflector will cause an imbalance itself when attached to the propeller; this should be compensated in some way.


text:
Q: In Yii2, how can I exclude layout from rendering in a view file? I have an admin login page that I want to render without the layout. How can I render a view in Yii2 without rendering the main layout?

A: This can be done using renderPartial() method.
You can get more from the official documentation. Here's a link!

A: In your controller you can assing layout for all actions of controller or turn it off:
class AdminController extends Controller
{
//  public $layout='//admin';
  public $layout=false;

OR you can do it for only one action:
public function actionIndex()
{
  $this->layout = false;

A: You can use renderPartial to exclude header and footer of layout from view file. However if you renderPartial it will not load asset files (css and js files). To load asset files without layout you can use renderAjax.


text:
Q: Modal component in VueJS I am building a web app. I have few components that are modals (that show data about customers, lessons, ...).
I search a way to show one of the components easily.
And if possible doing lazy loading.
What's the best way to perform this?

A: Check out conditional rendering, specifically v-if. This would only load the modal if the button is clicked for example.
https://v2.vuejs.org/v2/guide/conditional.html#v-if
Single page component:
<template>
  <div>
    <div
      v-if="showModal"
      class="modal">
      Stuff
    </div>
    <button @click="toggleModal">
      Toggle Modal
    </button>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        showModal: false
      }
    },
    methods: {
      toggleModal() {
        this.showModal = !this.showModal
      }
    },
  }
</script>


text:
Q: How can I tweak this split-tar-gz-archive script? I came across this shell script that can be used to split an entire directory across multiple compressed files.
I am interested in making a minor tweak to this script. Lets say I have n GB of files in a directory. I do not want the contents of a particular folder to be split across multiple tar files but inside the same file. I want the n MB folder to be fit within a single compressed file and the remaining (n GB -n MB) split across multiple files.
I am not sure whether it is possible with this script. I was looking forward to some suggestions. Though the script has been well documented, it is quite complex to understand for me


text:
Q: Flutter Web UUID Unique Identifier How can I get UUID in Flutter Web.
I need some unique identifier in order to keep record of devices useb by customer,my testing device,develeper device.
In android, I'm using device_info_plugin.
How can I get Unique identifier in Web?
Thanks in Advance

A: You can use platform_device_id to get the browser details.
For browser info, you can use it as
import 'package:platform_device_id/platform_device_id.dart';
String? deviceId = await PlatformDeviceId.getDeviceId;
print($deviceId);

OR
hare is the Answer to the approach to set a custom uuid for flutter web


text:
Q: How to trigger javascript function when select print preview I use rangeslider to  create a slider component, it looks like below
However, when I ready for print this, in print preview, the slider bar has scale in while slider button position value keep same with the value in html(In html, when window resize, there is a js function to re-calculate the size of bar and postion of slider button).
slider in print preview:

So my question is, how to call function to re-calculate slider button postion in print preview, like window.resize event.
Appreciate for any comment!!

A: To detect print requests with javascript you can try:
var beforePrintFunc = function() {
    ...
}
//for chrome
window.matchMedia('print').addListener(function(mql) {
    if (mql.matches) {
        beforePrintFunc();
    }
});

window.onbeforeprint = beforePrintFunc;

To detect after print preview event:
var afterPrintFunc = function() {
    ...
}
//for chrome
window.matchMedia('print').addListener(function(mql) {
    if (!mql.matches) {
        afterPrintFunc();
    }
});
window.onafterprint = afterPrintFunc;

However, there may be an easier approach as pointed out by @torazaburo in the comment below as long as you are only making styling changes:
@media print {
    //your print specific styles go here
}

A: I was looking for a jQuery equivalent of the solution proposed by @Moishe Lipsker but with no effect.
That is why for jQuery I make the changes on Print Preview once it is visible, with the following code:
$(window).on({
   'beforeprint': () => {
       this.detectPrintPreview();
    },
    'print-preview': () => {
        this.formatDesktopPrintPreview();
    }
});

detectPrintPreview() {
    $('.article-page').trigger('print-preview');
}

formatPrintPreview() {
    console.log('print preview');

    $('.box').appendTo('.example-elem);

}


text:
Q: References to Controls in ContentControl are null at the Parent (Page) Level As a follow up to this question where it was suggested I use a ContentControl, I have run into a scenario when I use a custom made class that dervies from ContentControl on a page, any controls defined within that ContentControl are not accessible from the page. All member variables turn out null.
For Instance, say the custom class I created that derives from ContentControl is named MyGroupBox and I try to use this inside a Page control:
<UserControl x:Class="MyApplication.MyUserControl">
   <local:MyGroupBox Title="Basic Information">
      <TextBox x:Name="MyTextBox" />
   </local:MyGroupBox>
</UserControl>

When I try to access MyTextBox from within the Page's code behind, the member variable is null. What is the best workaround for this scenario to get access to these controls so that I can use them in the Page's code behind?
Thanks!
EDIT:
Here is the Default Template for the MyGroupBox control
<Style TargetType="local:MyGroupBox">
    <Setter Property="Foreground" Value="#FF000000"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Top"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyGroupBox">
                <Border BorderThickness="1" Margin="8,8,0,0">
                    <Border.BorderBrush>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                            <GradientStop Color="#FF979797" Offset="0"/>
                            <GradientStop Color="#FFF1F1F1" Offset="1"/>
                        </LinearGradientBrush>
                    </Border.BorderBrush>
                    <StackPanel>
                        <Grid>
                            <Rectangle>
                                <Rectangle.Fill>
                                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                        <GradientStop Color="White" Offset="0"/>
                                        <GradientStop Color="#FFDFE2ED" Offset="1"/>
                                    </LinearGradientBrush>
                                </Rectangle.Fill>
                            </Rectangle>
                            <TextBlock Text="{TemplateBinding Title}" Margin="10,3,3,3" TextAlignment="Center" HorizontalAlignment="Left" />
                        </Grid>
                        <ContentPresenter Cursor="{TemplateBinding Cursor}" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

EDIT:
public MyUserControl()
{
    InitializeComponent();

    if (this.MyTextBox == null)
    {
        // MyTextBox is null at this point - is there a way to get
        // the InitializeComponent method to find the control named MyTextBox when
        // it is inside of a ContentControl derived class?
        MessageBox.Show("MyTextBox is null");
    }
}

A: Let me step you through putting it together by showing the steps I took to test what you posted:-

*

*In Visual Studio create a Silverlight Application

*Add a new item to the Silverlight project selecting "Silverlight Templated Control", call this "MyGroupBox".

*Open the Themes\Generic.xaml which will now have been created.  It will contain the a style:-
Generic.Xaml:-
<Style TargetType="local:MyGroupBox">
   ...
</Style>

*

*Replace its entire content with the content in your question.

*Edit MyGroupBox.cs, modify to inherit from ContentControl and add Title dependency property.
MyGroupBox.cs:-
public class MyGroupBox : ContentControl
{
    public MyGroupBox()
    {
        this.DefaultStyleKey = typeof(MyGroupBox);
    }

    #region public string Title

    public string Title
    {
        get { return GetValue(TitleProperty) as string; }
        set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register(
                    "Title",
                    typeof(string),
                    typeof(MyGroupBox),
                    new PropertyMetadata(null));
    #endregion public string Title

}

*

*Open MainPage.Xaml add some usage for MyGroupBox

In MainPage.xaml
<Grid x:Name="LayoutRoot">
    <StackPanel>
        <local:MyGroupBox Title="Test" HorizontalContentAlignment="Stretch">
            <TextBox x:Name="MyTextBox" />
        </local:MyGroupBox>
    </StackPanel>
</Grid>

*

*Edit the MainPage.xaml.cs to test whether MyTextBox is null
public MainPage()
{
    InitializeComponent();
    MessageBox.Show((MyTextBox == null).ToString());
}

I get "False", InitializeComponent has succesfully found the element with the name "MyTextBox".


text:
Q: template variable to `FormControl` I'm trying figure out, is a simple way to use template variable to access FormControl in FormGroup to get shorter form ? I have example like below, this is working - i always use that long format, but it annoys me.
<form [formGroup]="form">
    <mat-form-field>
        <mat-label>Field</mat-label>
        <input type="text" matInput formControlName="field">
        <mat-error *ngIf="form.get('field').hasError('required')">
            Email is required
        </mat-error>
        <mat-error *ngIf="form.get('field').hasError('otherError')">
           ...
        </mat-error>
    </mat-form-field>
</form>

Thinking about shorter form, but it doesn't work:
<form [formGroup]="form">
    <mat-form-field>
        <mat-label>Field</mat-label>
        <input type="text" matInput formControlName="field" #fieldRef>
        <mat-error *ngIf="fieldRef.hasError('required')">
            ...
        </mat-error>
        ...
    </mat-form-field>
</form>

I need to replace multiple form.get(...) calls with local variable. Anybody helps ?

A: I can't think of a neat way around it, but I can think of a couple ways to do it differently. Maybe something suits your taste:
#1 Use object property access instead of get:
<form [formGroup]="form">
    <mat-form-field>
        <mat-label>Field</mat-label>
        <input type="text" matInput formControlName="field">
        <mat-error *ngIf="form.field.hasError('required')">
            Email is required
        </mat-error>
    </mat-form-field>
</form>

#2 Use the matInput directive to access the control:
<form [formGroup]="form">
    <mat-form-field>
        <mat-label>Field</mat-label>
        <input type="text" matInput formControlName="field" #field="matInput">
        <mat-error *ngIf="field.ngControl.hasError('required')">
            Email is required
        </mat-error>
    </mat-form-field>
</form>

#3 Access it from the TS
export class FormExampleComponent {
  readonly field = new FormControl();

  readonly form = new FormGroup({ field: this.field });
}

<form [formGroup]="form">
    <mat-form-field>
        <mat-label>Field</mat-label>
        <input type="text" matInput formControlName="field">
        <mat-error *ngIf="field.hasError('required')">
            Email is required
        </mat-error>
    </mat-form-field>
</form>

Besides all this, you can also think of creating your own form directive which extends from the angular one. With which you may be able to do something like:
<mat-error *myError="'required'">
  Email is required
</mat-error>

But that might be outside the scope of this question :)

A: your must add in your component.ts a function that return the form control
get f(): { [key: string]: AbstractControl } {
return this.form.controls;
 }

and use this in your component.html to acess to the errors using the name of formcontrol.
*ngIf="submitted && f.filed.errors"


text:
Q: VSTS Windows Machine file copy robocopy error Getting error when copying the files using windows machine file copy in vsts:
[error]The term 'robocopy' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.


text:
Q: How to match multiple patterns with Dir.glob? In my Rails app I am trying to collect the paths to all the files contained in two different directories using Dir.glob.
The following code works but is not very concise. Isn't there a way two match two patterns at once with Dir.glob?
common_file_paths = Dir.glob("app/assets/mystuff/*").reject do |path|
  File.directory?(path)
end

more_file_paths = Dir.glob("app/assets/mystuff/more/*").reject do |path|
  File.directory?(path)
end

file_paths = common_file_paths + more_file_paths

A: Dir.glob also accepts an array of patterns.
Dir.glob(["app/assets/mystuff/*", "app/assets/mystuff/more/*"])

A: this should do it for you .. tested it in my local machine and it works as expected.
lets say , you have the following directory and subdirectory :
z$ find deletpractic/
deletpractic/
deletpractic/sub_dir
deletpractic/sub_dir/file1_in_subdir.txt
deletpractic/sub_dir/file2_in_subdir.txt
deletpractic/text1
deletpractic/text2
deletpractic/text3
deletpractic/text4
deletpractic/text5
deletpractic/text6
deletpractic/text7

it pretty much  boils down to this  Dir.glob("/mydir/**/*")
[za]$ /usr/bin/ruby -rpp -e 'common_file_paths =    Dir.glob("/dev/deletpractic/**/*").reject do |path|   File.directory?(path) end ; pp common_file_paths'

Output :
["/dev/deletpractic/sub_dir/file1_in_subdir.txt",
 "/dev/deletpractic/sub_dir/file2_in_subdir.txt",
 "/dev/deletpractic/text1",
 "/dev/deletpractic/text2",
 "/dev/deletpractic/text3",
 "/dev/deletpractic/text4",
 "/dev/deletpractic/text5",
 "/dev/deletpractic/text6",
 "/dev/deletpractic/text7"]


text:
Q: How to allow snap applications to access /tmp folder? Usually I'm avoiding snap-based applications, but sometime I need them.
For example - Markdown Lint Tool is shipped only as Snap named  mdl.
It works great when files are in home folder -
$ echo "# header" > ~/test.md
$ /snap/bin/mdl ~/test.md ; echo $?
0

but it fails when file is located in /tmp directory:
$ echo "# header" > /tmp/test.md
$ cat /tmp/test.md
# header
$ /snap/bin/mdl /tmp/test.md
/snap/mdl/140/lib/ruby/gems/2.4.0/gems/mdl-0.9.0/lib/mdl/doc.rb:57:in `read': No such file or directory @ rb_sysopen - /tmp/test.md (Errno::ENOENT)
    from /snap/mdl/140/lib/ruby/gems/2.4.0/gems/mdl-0.9.0/lib/mdl/doc.rb:57:in `new_from_file'
    from /snap/mdl/140/lib/ruby/gems/2.4.0/gems/mdl-0.9.0/lib/mdl.rb:75:in `block in run'
    from /snap/mdl/140/lib/ruby/gems/2.4.0/gems/mdl-0.9.0/lib/mdl.rb:73:in `each'
    from /snap/mdl/140/lib/ruby/gems/2.4.0/gems/mdl-0.9.0/lib/mdl.rb:73:in `run'
    from /snap/mdl/140/lib/ruby/gems/2.4.0/gems/mdl-0.9.0/bin/mdl:10:in `<top (required)>'
    from /snap/mdl/140/bin/mdl:23:in `load'
    from /snap/mdl/140/bin/mdl:23:in `<main>'

For this particular application there are no options for snap connect:
$ snap connections | grep mdl
home                      mdl:home                             :home                                 -

Also I can't install it as classic:
$ snap install mdl --classic
Warning: flag --classic ignored for strictly confined snap mdl

mdl 0.9.0 from Snapcrafters installed

What should I do to give Snap application full access to the /tmp folder?
Does it happen by Snap design or not?

A: I'm usually very supportive of change and of Ubuntu, but if, like me, you find this really annoying, the fix I came up with is to add a directory to my home:
mkdir /home/mlissner/tmp

And to add a crontab to nuke it on reboot:
sudo crontab -e

Then add:
@reboot rm -rf /home/mlissner/tmp/*

Having to do this is really dumb.
I'm all for sandboxing and security. I'm all for change, but this removes an important use case of "Save this file here, and then delete it later without me thinking about it."
It's also really buggy from a user perspective. You can save something from Firefox into /tmp, no errors. But then when you try to find that thing in the file browser, it doesn't exist. WTF.
Count me very annoyed.

A: It seems you may be looking for the "proper" way to solve the issue caused with snaps...
but if you were looking for a workaround so you can use your tmp directory, you could:
mkdir /home/you/tmp
sudo mount --bind /tmp /home/you/tmp/

mdl will have full access to the /tmp directory via the /home/you/tmp mountpoint:
echo "# header" > /home/you/tmp/test.md
mdl /home/you/tmp/test.md

To make it permanent you can add this line to the /etc/fstab:
 # <file system> <mount point>   <type>  <options>       <dump>  <pass>
/tmp        /home/you/tmp   auto    bind    0   3

and rebuild the initrd with sudo update-initramfs -u -k all .