text:
Q: loading blue-imp fileupload with requirejs throws error on blobSlice I'm loading the fileupload plugin with requirejs
I was loading the plugin as follows:
define([
        'jquery',
        'jquery.iframe-transport',
        'jquery.fileupload-ui'
    ], function(
        jquery,
        itransport,
        fileupload_ui
    )
    {

This stackoverflow question confirms this:
requireJS with fileupload plugins
The problem occurs when "load-image-meta" is executed at those lines:
    loadImage.blobSlice = hasblobSlice && function () {

Uncaught TypeError: Cannot set property 'blobSlice' of undefined.
This is because loadImage is being passed as an argument as undefined and I can't figure out the reason once we already defined the dependecy on line 23.
can someone help me?
ADITIONAL INFORMATION (below)
Here is the list of paths defined for each plugin at requirejs.config.paths
 'jquery.postmessage-transport': './bower_components/blueimp-file-upload/js/cors/jquery.postmessage-transport',
        'jquery.xdr-transport': './bower_components/blueimp-file-upload/js/cors/jquery.xdr-transport',
        'jquery.ui.widget': './bower_components/blueimp-file-upload/js/vendor/jquery.ui.widget',
        'jquery.fileupload': './bower_components/blueimp-file-upload/js/jquery.fileupload',
        'jquery.fileupload-process': './bower_components/blueimp-file-upload/js/jquery.fileupload-process',
        'jquery.fileupload-validate': './bower_components/blueimp-file-upload/js/jquery.fileupload-validate',
        'jquery.fileupload-image': './bower_components/blueimp-file-upload/js/jquery.fileupload-image',
        'jquery.fileupload-audio': './bower_components/blueimp-file-upload/js/jquery.fileupload-audio',
        'jquery.fileupload-video': './bower_components/blueimp-file-upload/js/jquery.fileupload-video',
        'jquery.fileupload-ui': './bower_components/blueimp-file-upload/js/jquery.fileupload-ui',
        'jquery.fileupload-jquery-ui': './bower_components/blueimp-file-upload/js/jquery.fileupload-jquery-ui',
        'jquery.fileupload-angular': './bower_components/blueimp-file-upload/js/jquery.fileupload-angular',
        'jquery.iframe-transport': './bower_components/blueimp-file-upload/js/jquery.iframe-transport',
 'blueimp-canvas-to-blob': './bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
        'canvas-to-blob': './bower_components/blueimp-canvas-to-blob/js/canvas-to-blob',
        'load-image': './bower_components/blueimp-load-image/js/load-image',
        'load-image-ios': './bower_components/blueimp-load-image/js/load-image-ios',
        'load-image-orientation': './bower_components/blueimp-load-image/js/load-image-orientation',
        'load-image-meta': './bower_components/blueimp-load-image/js/load-image-meta',
        'load-image-exif': './bower_components/blueimp-load-image/js/load-image-exif',
        'load-image-exif-map': './bower_components/blueimp-load-image/js/load-image-exif-map',
        'tmpl': './bower_components/blueimp-tmpl/js/tmpl'

this is the dependency list of each file
jquery.postmessage-transport
---'jquery'

jquery.xdr-transport
---'jquery'

jquery.ui.widget.js
---'jquery'

jquery.fileupload.js
---'jquery',
---'jquery.ui.widget'

jquery.fileupload-process.js
---'jquery',
---'./jquery.fileupload' ***

jquery.fileupload-validate
---'jquery',
----'./jquery.fileupload-process' ***

jquery.fileupload-image
    'jquery',
    'load-image',
    'load-image-meta',
    'load-image-exif',
    'load-image-ios',
    'canvas-to-blob',
    './jquery.fileupload-process' ****

jquery.fileupload-audio
    'jquery',
    'load-image',
    './jquery.fileupload-process'

jquery.fileupload-video.js
    'jquery',
    'load-image',
    './jquery.fileupload-process'

jquery.fileupload-ui
    'jquery',
    'tmpl',
    './jquery.fileupload-image',
    './jquery.fileupload-audio',
    './jquery.fileupload-video',
    './jquery.fileupload-validate'

jquery.fileupload-jquery-ui
    'jquery',
    './jquery.fileupload-ui'

jquery.fileupload-angular
     'jquery',
    'angular',
    './jquery.fileupload-image',
    './jquery.fileupload-audio',
    './jquery.fileupload-video',
    './jquery.fileupload-validate'

jquery.iframe-transport
    'jquery'

blueimp-canvas-to-blob
// duplicated with key "canvas-to-blob" to match jquery.fileupload-image dependency key

load-image
    NO DEPS

load-image-ios
    'load-image'

load-image-orientation
    'load-image'

load-image-meta
    'load-image'

load-image-exif
    'load-image'
    'load-image-meta'

load-image-exif-map
    'load-image',
    'load-image-exif'

tmpl
   NO DEPENDENCIES

A: As @ant_Ti mentioned on it's comment to my question i had to force requirejs to load load-image before loading load-image-meta for that reason I added the following piece of code to my requirejs.config.shim object:
require.config({
    shim: {
        'jquery.fileupload-ui': {
            deps: ['load-image']
        }
    }
});

this ensures that when we try to load jquery.fileupload-ui, load-image will be already available.


text:
Q: Unexpected result when using atoi() on content of file, read char by char I have a text file in which there are only numbers (0, 1, 2 & 3) and I want to process the data to know how many times each number appears.
The following program works with small text file (<100 numbers) but with bigger files (I need to process in the end several thousands of data) the program reads numbers that are not in the text file.
Here's my code :
FILE *file;
char c;
int nb;
int th0 = 0, th1 = 0, th2 = 0, th3 = 0;

file = fopen("../data", "r");

if (file == NULL) {
    printf("ERROR FILE: %s", strerror(errno));
    return EXIT_FAILURE;
}

while (1) {
    if (fscanf(file, "%c", &c) == EOF)
        break;

    nb = atoi(&c);

    printf("%d", nb);

    switch (nb) {
      case 0:
        th0++;
        break;

      case 1:
        th1++;
        break;

      case 2:
        th2++;
        break;

      case 3:
        th3++;
        break;

      default:
        break;
    }
}

I would appreciate any suggestions.
EDIT, the input text with the output :
Data file (181 numbers):
001110120101010102012012021201021202102012012012012010210210210120120230103120130230123201320310231023102302301231203213210131032103210230120320310320213202301320123120312302321023
Output:
The end of the reading is not what is in the data file and count 156 numbers

A: Your problem is that atoi expects a string and you're calling it like this:
nb = atoi(&c);

with c being just a char. Sometimes that might work, but you're basically hitting undefined behaviour as you can't guarantee that the memory after c is empty.
Instead you want to calculate nb differently.
nb = c - '0';

This relies on the fact that in the ASCII table, the numbers 0 to 9 are in a block together. Subtracting the value of '0' from c will get you the numerical value of that character...assuming it is a digit.
And just to ensure it is a digit you should wrap this if statement around your code
if(isdigit(c)) // Check if c is a digit
    {
    nb = c - '0';

    switch(nb) {
        case 0: th0++;
        break;
    // rest of switch goes here....
         }
    }

A: Looking at
https://en.cppreference.com/w/c/string/byte/atoi
I see

Parameters
  str -   pointer to the null-terminated byte string to be interpreted

But with
char c;
/* ... */
nb = atoi(&c);

you are using a pointer to a single char, which is followed by who-knows-what.
For anything which happens to not be a '\0' you will get a result from atoi() which is
a) based on access beyond the intended variable
b) for following digits, is a two-digit number or higher
The first option means that your code needs fixing.
The second option can explain any number > 9.

A: You call atoi with a pointer to char that does not point to a proper C string, hence your code has undefined behavior and may seem to work as expected sometimes and misbehave at other times...
Since you are dealing with digits, you could compute the value represented by the digit with a simple subtraction c - '0'.
You could also simplify the code with an array:
#include <stdio.h>

int main() {
    FILE *file;
    int c, i;
    int count[10] = { 0 };

    file = fopen("../data", "r");
    if (file == NULL) {
        printf("ERROR FILE: %s", strerror(errno));
        return EXIT_FAILURE;
    }

    while ((c = getc(file)) != EOF) {
        if (c >= '0' && c <= '9')
            count[c - '0']++;
    }
    fclose(file);

    printf("counts:\n");
    for (i = 0; i < 10; i++) {
        printf("%d: %d\n", i, count[i]);
    }
    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What kinds of server roles can't you run on a Linux (or other OSOS) cluster? I've been thinking of trying out some freeware cluster software.  IIUC two of the main things we use servers for, Apache and PostgreSQL, can be set up to run redundantly on clusters by load-balancing modules and Slony-I replication.  Filesharing can be too, probably a little more easily.
What are some typically important services you wouldn't be able to host on a cluster (i.e., you would more or less be stuck with hosting on a single, beefy machine?)

A: People are really creative in ways that you wouldn't believe, in order to get clusters running and reliable.
When it comes to clustering (or at least HA-clustering), there are shared-storage clusters and shared-nothing clusters. Shared storage clusters typically use cluster-aware filesystems on a centralized array, like a SAN. They use OCFS, GFS, or something similar.
Services running on these are sometimes Active/Active, where both machines are fully capable of providing a full range of services to clients, and typically use weighted or round-robin style load balancing, but could also be setup as Active/Passive, where the "preferred" machine acts as a server until it fails, in which case another cluster member takes over.
Shared-nothing clusters have been typically Active/Passive, since there needed to be a state change to activate the passive member. This is changing with the advent of things like DRBD, which uses block-level filesystem replication over the network.
Between one of these two methods, pretty much every service that I can think of can be replicated across an array of servers, especially if you don't care much where you put your state files. Even NFS can be replicated without clients freezing if everything including the lock files are referenced from the centralized storage.
Enterprise computing in general has been very dedicated to the mindset that single-machine uptime doesn't matter as much as service availability. To that end, services have been engineered such that one machine failure doesn't mean disruption to the users.


text:
Q: .Net Collections: Node-Leaf Is there a built in node-like collection that will allow me to store information within information without building long hard to read generic declarations?
C# or VB.Net solutions would be appreciated.
For example:
dim base as new Dictionary(of String, Dictionary(of String, List(of String)))
dim mid as new Dictionary(of String, List(of String)
dim leaf as new List(of String)
leaf.add("leaf1")
leaf.add("leaf2")
mid.add("middle", leaf)
base.add("base", mid)

Logical Representation:
               / leaf
        mid    - leaf
     /         \ leaf
base
     \         / leaf
        mid    - leaf
               \ leaf

A: Nothing built in. Take a look at this.

A: There is nothing builtin, you're probably better off building your own class for each tree node.
public class Node {
  private List<Node> children = new List<Node>();

  public void Node(Node parent,Object node_data) {
    ...
  }

  // put some methods for adding, removing, retrieving children here
}

And only one private generic class!


text:
Q: React Native Image component, requiring unknown module The docs make it pretty clear that you can't do any dynamic requiring:
// GOOD
<Image source={require('./my-icon.png')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />

// GOOD
var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
<Image source={icon} />

I have a use case that isn't so cut and dry however, I have a ListView and in the renderRow method i would like to render an Image depending on some of the data in said row.  For instance I want to render ../img/12.png, by doing it
<Image style={styles.thumb} source={require("../img/12.png")} />

works fine, however
let imagePath = "../img/" + row.number + ".png";  // row.number being 12
<Image style={styles.thumb} source={require(imagePath)} />

gives the following error:
Requiring unknown module "../img/12.png"

Is there any workaround here, it seems like its still ending up requiring the exact same string, it just doesn't work

A: Ok I figured it out and figured I'd post an answer in case anyone in the future has this struggle.
The answer is that you need to explicitly require all images or else they will not be bundled, hence the unknown module error.
Solution:
In a separate file, I created and exported an object that is keyed by number, and the value is require("../img/x.png") where x is the key.
Then in my ListView's renderRow method I pull the image out from the object by keying into it using row.number

A: you need to do :
let imagePath = require("../img/" + row.number + ".png")
<Image style={styles.thumb} source={imagePath} />


text:
Q: Use gsutil commands in R through system() -- which environmental variables do I need do assign? Not sure how I should be going about this, but it is not working currently:
My first thought: in my home directory, I have the folder for GC SDK:
Sys.setenv(PATH="$HOME/google-cloud-sdk")
system(paste0("gsutil cp ",paste0(bucket,cancer.id,"/rnaseq_fpkm_*.csv "),paste0(cancer.id,"/rnaseq_fpkm_*.csv")),intern=F)

sh: 1: gsutil: not found
Warning message:
In system(paste0("gsutil cp ", paste0(bucket, cancer.id, "/rnaseq_fpkm_*.csv "),  :
  error in running command

Any assistance would be greatly appreciated.

A: If you want to add to your path rather than replace, the withr::with_path gives a good short term solution. You can also use expand.path to expand user paths to full paths. Try
withr::with_path( path.expand("~/google-cloud-sdk/bin/"), {
   system(paste0("gsutil cp ",paste0(bucket,cancer.id,"/rnaseq_fpkm_*.csv "),paste0(cancer.id,"/rnaseq_fpkm_*.csv")),intern=F)
})

Or even just to check that it works, try
withr::with_path( path.expand("~/google-cloud-sdk/bin/"), {
   print(Sys.getenv("PATH"))
   print(Sys.which("gsutil"))
})


text:
Q: HttpClient Get works when Fiddler is on and fails with 403 when fiddler is not running I have seen many posts but none of the solution is helping me. I have a simple get to one of the Amazon new webservices. The client is HttpClient.
When fiddler is on it passes and gets me result. When fiddler is not running it fails. Since it was not failing when fiddler was on, i installed another tool "Http Debugger" to see the failure and i could not make any difference in both the request (The pass and the failure). Bothe of them are given below
Failure Capture:
GET /sellers/v1/marketplaceParticipations HTTP/1.1
Accept: application/json
x-amz-access-token: Atza|IwEBIN3hOVtNi1xM47txtHcqXi5A3C960AypB7pkWYCxEo7lNiL9EFR-1b_EoD6PQ8lzAXgM4zujF0OBv0NS7sYQ9bWqPMDhHFt8kgvdmlmk3==jrinknrO6PYlZgmFLRGn1Hzmvgldmnj4973bjkfnbkldlcvld vc0BmuqKHUreonrWQxFO49u0yoIiNHVzSxHP0Wo4nWKW5pdd5Fj73gYxnZQQeYF5EAy8lKDCLtndTnJCdlrv5Kk8JK8iFD_H7h3FF5H4gNyTx3uIHxMaU8OkLz_IigsCTNQHwljnubhQlR9aK0J6lRbb0QfOQ4BAT_e1GOKDkShu-U5OdchdF5qNUkKU
user-agent: MSolution/1.0.0.0
X-Amz-Date: 20201201T224620Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIA5SU6JNBJKDAQB76813QI6V/20201201/eu-west-1/execute-api/aws4_request, SignedHeaders=accept;host;user-agent;x-amz-access-token;x-amz-date, Signature=71dd12ee0eaf33cd142dwr242424e91cb5c4bfd6fd4f46d929d
Host: sellingpartnerapi-eu.amazon.com
Connection: Keep-Alive

The error is Forbiden (Just this)
The success capture is (Fiddler running):
GET /sellers/v1/marketplaceParticipations HTTP/1.1
Accept: application/json
x-amz-access-token: Atza|IwEBIMfdZDDaca8HrDGIPft-HQs3Vzi75I4Bk9iNKfsHTkfwsfsfcsvcsaP86DqKkoZE37TiDr3XvmD_vdvavcUE9TzdXhf2jjuULL04keBHI_XYrnTnhXaCPE0gUAc8HvIiW7OXSERz_3RlS9R-nu2lTo_jqzaz0mbUaa-evavaVAVLauh2Ue7Io8pE1tThRTcqM60igPcrBViAUptTAsq-IL5ZT7hOfbNJTJ31GeN8e8IzjkWfe9n4l7B799VM1bJnC-D_alZ2J0HHj4cBNjd3RzAEvavav3fGWkW5iH2_MZ3IyaxYnslvSzNH4h8tvay87OywkkxVUKIn
user-agent: MSolution/1.0.0.0
X-Amz-Date: 20201201T224820Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAYWBDAQ7XYIPQI6V/20201201/eu-west-1/execute-api/aws4_request, SignedHeaders=accept;host;user-agent;x-amz-access-token;x-amz-date, Signature=7e4db1c114219546848eaffnvclknslnlcvs63c9e0af50edc3cdbe7231c9b
Host: sellingpartnerapi-eu.amazon.com

I have used:
ServicePointManager.ServerCertificateValidationCallback +=
                  (senderSP, certificate, chain, sslPolicyErrors) => true;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

Not sure what is causing this but has anyone seen this ?
The same call through "RestSharp" works, but i donot wnat to use rest sharp.

*

*Shankar


text:
Q: Как остановить @bot.message_handler Создаю бота на python 3 с помощью библеотеки telebot. И вот задался вопросом как остановить message hendler, например ты запустил message_handler что-бы пользователь ввёл своё имя и потом нужно остановить его, что-бы если он опять что-то введёт это "что-то" не должно запоминатся.

A: @bot.message_handler(commands=['start'])
def send_welcome_employer(message):
    msg = bot.send_message(message.chat.id, "Введите Ваше имя: ")

При запуске команды /start вам приложиться ввести имя. То что вы напишите в ответе то и сохраниться, все что будите писать дальше не будет сохраняться.
Например вы напишите "Коля", отправить, потом напишите еще "Саша", он сохранит только "Коля".


text:
Q: "None" shows instead name of object Django I have such an error: in my models there is two ones: subject and section. In section-model there is a field where saved every subject in this section.
class Section(models.Model):
    """Model for a section."""
    ename = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    definition = models.CharField(max_length=500)
    picture = models.ImageField(upload_to="physics/section", blank=True)
    subjects = models.ManyToManyField("Subject")

    def __str__(self):
        return self.name

class Subject(models.Model):
    """Model for a subject in section."""
    ename = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    definition = models.CharField(max_length=500)
    content = models.TextField()

    def __str__(self):
        return self.name

I am trying to show every subject in the section. My views and template below:
views:
def section(request, section_name):
    section = get_object_or_404(Section, ename=section_name)
    return render(request, 'section.html', {'section': section})

template:
{% extends 'base.html' %}
{% block content %}
{{ section.name }}
{{ section.subjects }}
{% endblock content %}

But "None" shows in the page of this section. It looks so:
(real subject name here) Physics.Subject.None
Can anybody say what's wrong? Thank you, in advance for attention.

A: Since you are using a ManyToManyField to reference your Section you need to access that set in your template and then pull information from it.
Something like this should suffice:
{% extends 'base.html' %}
{% block content %}
{{ section.name }}
{% for subject in section.subjects_set.all %}
{{ subject.name }}
{% endfor %}
{% endblock content %}


text:
Q: Ways to overcome the limitation of concurrent operations in SQL Database(azure) My application is using windows azure and SQL Database(Azure). In near future we will be having traffic for our SQL Database near to 50,000 transactions/min. I am using 5GB Web database.
Now there is a limit of 400 concurrent operations per partition in SQL Database:Reference
What are the possible ways to overcome this limitation? At the moment the best solution i can think of is federation. Which are the other ways? And which one is the best?
EDIT : Transactions will be write only. We are collecting performance data from our client systems every 5 seconds which are sent to our REST API which eventually inserts data to SQL Database. So no UI and caching is out of question.

A: Using Federations in Windows Azure SQL Database is one option. But I prefer offloading the heavy work to different data store like Table Storage, Blobs or Queues since they were built to handle a heavy load and they partition much easier. Combine this with good caching and you might overcome this limitation with ease.
Imagine your site has a top 10 products list on your home page and you have 100,000 visitors / day. One option would be to query SQL Azure each time, but this could cause a heavy load on SQL Azure. But you could have a worker process running every 24 hour for example and calculating the top 10 products at that time, and save them in Table Storage (you could make a few partitions in that table containing the top 10 per country, per category, ...). You could see this as a pre-generated view. Each time you want to show the top 10 products you would query the items from Table Storage (a specific partition in a table) which scales much better. Add some ASP.NET caching there and you'll have a very reliable system.
That was it for reading data. But I imagine you'll also be expecting some user input, where a user can create an order, send messages, ... There again, if you're expecting a heavy load SQL Azure might not be your best option to interact with directly (seen the limitations). Using queues between your front end and your back end might be a better solution.
When your users place an order you can write a message to a queue (Storage Queue or Service Bus Queue). A worker will pick up this message, and create a record in the table for that order with the time, product count and maybe even a status (like processing) that you would show in the user's orders screen. Once you've done this you have all the time you need to do finish the order and once you finished it you save the end result in SQL Azure (and you update the order record in table storage). Saving the end result in SQL Azure will still make it possible to use reporting etc...
This will have a big impact on your application. An other solution would be to host SQL Server yourself in a Virtual Machine, but note that this is still in CTP: Provisioning a SQL Server Virtual Machine on Windows Azure

A: Federations is of course an option because it's a shared nothing infrastructure. However you may want to first reflect on why you need such a high volume of transactions. Are your transactions going to be mostly read or write operations? Do you have a middle tier in place? The techniques available differ for write and read operations. Here are a few techniques you can use to help you minimize the number of transactions per second on a SQL Database instance when you have a middle tier in place:

*

*Caching (as mentioned by Sandrino)

*Set-based transactions

*Eventual consistency

Caching is important when your system is trying to provide data to a consumer, in a read scenario (or denormalization). I won't expand on caching other than to say you have serious pros and cons to consider, such as data freshness and synchronization issues across nodes. The other two techniques below are for writes.
Set-based transactions are absolutely crutial in a database system. If your system inserts lots of records every second for example, you would place the insert requests in a queue for example, then process the queue on a separate thread, then pool ten or twenty requests into a single database call. This requires asynchronous processing and set based operations on the database. But in the end groupping records for processing is one of the keys to success in SQL Database. We are designing a system right now that would make well above 500 transactions per second if it weren't for implementing a similar pattern.
Eventual consistency is another important concept, and I alluded to it previously with the set-based approach. Eventual consistency means that the database may not contain all the records right now, and that it may take some time for all the records to be available. But eventually, the records will make it. The example I provided above (with the queue) implements both a set-based operation and an eventual consistency pattern.


text:
Q: (Excel) conditional formatting based on adjacent cell, whole column I'm trying to highlight the changes in a long list of data, so I would like to have the cell shaded if its value is different than the cell above.  I can implement this for a single pair of cells using conditional formatting, but I can't get it to work for a whole column.  Here's what I want it to look like (I performed this shading manually, for this example):

I tried this, but it doesn't propagate down the column when I select the column.

A: First time responding to a question on Stack Overflow, so apologies if the formatting on this response is messy.
You will want the formula to read:
{ =A2<>A1 }
Conditional Formatting Rules Manager


text:
Q: How to choose DISPLAY value for X server programmatically? I discover a way to run second X server on top of primary with one of:
$ xinit ~/.fvwm/xinit -- `command -v Xnest` :1
$ xinit ~/.fvwm/xinit -- `command -v Xephyr` :1

How can I find which DISPLAY (here is :1) is free for use programmatically?
Preferred is solution from command line.
What limits for DISPALY value count (hardware/software)?

A: same limits as for port number ( it's 6000 + display if server is listening on TCP ). Try to bind to a port, if successful - consider it's free, release and start X server with DISPLAY= (port - 6000)


text:
Q: How to enter many points in the run process? I am now figuring out a problem: enter several coordinates of  points, then put them into three list, one for the points which are above the line y=x, one exactly on it, and one below it.
I am a novice, so i am really confusing.
Please also tell me how can i enter these points in the run time, not in the coding time.

A: Suppose you have a list of points of the form (x, y), where x and y are int or float values. Suppose this list is called points. Then, the following will work:
below = []
on = []
above = []
for coordinate_pair in points:
    if coordinate_pair[0] < coordinate_pair[1]: # That is, x < y, so (x, y) is above the line y = x
        above.append(coordinate_pair)
    elif coordinate_pair[0] == coordinate_pair[1]:
        on.append(coordinate_pair)
    # I'll leave the rest to you, since I believe this is a homework assignment

If you want to enter these points during runtime, you can use float(input("Enter a value for x: ")) to get x-values and float(input("Enter a value for y: ")) to get y-values.


text:
Q: Rails Console - ActiveRecord::RecordNotFound I am trying to delete a mass amount of records from my database. My destroy_all keeps getting stopped when a callback fails to destroy a record because of ActiveRecord::RecordNotFound. I want to skip the callbacks when the error ActiveRecord::RecordNotFound occurs on records that the callback is trying to delete.
All User records belong to school via a UserSchool relation. I am trying to delete all User Records where the school_id: 74 is present in any UserSchool record.
user_ids = UserSchool.where(school_id: 74).map(&:user_id)
User.where(id: user_ids).destroy_all

The result is:
ActiveRecord::RecordNotFound: Couldn't find Comment with 'id'=17

I want to skip over that error and continue destroying User records. How can I rescue here?

A: user_ids = UserSchool.where(school_id: 74).map(&:user_id)
users = User.where(id: user_ids)

users.each do |user|
  begin
    user.destroy
  rescue => ActiveRecord::RecordNotFound
    puts "Record not found"
  end
end

A: I think we can rescue by looping it over each object.
user_ids.each do |user_id|
 User.find(user_id).destroy rescue nil
end

For only ActiveRecord::RecordNotFound exception you could do,
user_ids.each do |user_id|
  begin
    Contact.find(user_id).destroy
  rescue => ActiveRecord::RecordNotFound
    puts "Record not found"
  end
end


text:
Q: Change Google Service Account picture As I am using service account to share Google Drive documents, it would be nice to get in invitation email a company picture instead of the silhouette.
Is it possible to change somehow Google Service account picture?
I tried using the Google Admin SDK, but I get the following error:
404 OK
- SHOW HEADERS -
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "Resource Not Found: userKey"
   }
  ],
  "code": 404,
  "message": "Resource Not Found: userKey"
 }
}

I tried this through the API explorer:
https://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update
EDIT, the userKey is the email address of the account. In the service account case it is in the format:
account-name@project-name.iam.gserviceaccount.com

A: Get your service account to use delegation to impersonate and use a separate Google Apps account email address to do the document sharing. Set the photo in that Google Apps account.


text:
Q: dpc++ start the do loop from 1 to n-2 using parallel_for range Is that possible to start the do loop and the index is from 1 to n-2 using dpc++ parallel_for?
h.parallel_for(range{lx , ly }, [=](id<2> idx

this will give a do loop from 0 to lx-1, and I have to do
idx[0]>0 && idx[1]>0 && idx[0]<lx-1 && idx[1]<ly-1

and then I can complete the loop?
Also, does dpc++ support like 4D parallel_for?

A: In SYCL 1.2.1, parallel_for supports offsets, so you could use h.parallel_for(range{lx-2, ly-2}, id{1, 1}, [=](id<2> idx){ ... });.
However, this overload has been deprecated in SYCL 2020:

Offsets to parallel_for, nd_range, nd_item and item classes have been deprecated. As such, the parallel iteration spaces all begin at (0,0,0) and developers are now required to handle any offset arithmetic themselves. The behavior of nd_item.get_global_linear_id() and nd_item.get_local_linear_id() has been clarified accordingly.

So, if you want to conform to the latest standard, you should apply the offset manually:
h.parallel_for(range{lx-2, ly-2}, [=](id<2> idx0) { id<2> idx = idx0 + 1; ... });
That said, depending on your data layout, your original approach of having "empty" threads might be faster.

Also, does dpc++ support like 4D parallel_for?

No. You will have to use 1D range and compute the 4D index manually.


text:
Q: Optimizing number of workers scraping a website I'm interested in scraping a particular website periodically that has ~100 million items on it.  The scraper can download and process items very quickly, on the order of 50ms, but even at that speed it will take days to complete.
The obvious solution is to use multiple scrapers.  However, at some point the underlying webservice will become saturated, and start to slow down.  I want to be respectful of the service and not DDoS it, while scraping as efficiently as possible.
This is clearly an optimization problem but I'm not sure how to approach modeling it.  Ideally I need to know the number of scrapers, and what delay to target for each of them.  Any ideas?

A: You may try out the URL frontier approach for crawling.
There is a Python library called Frontera that implements the same approach.
Disclaimer: I am not endorsing/advertising Frontera nor related to it in any way.


text:
Q: downloading data from GCE VM instance to a local PC - is it egress data? Is downloading the data from the GCE VM instance to a local PC also considered an egress network data?

A: Official documentation says that data leaving a Google resource is indeed part of egress data.


text:
Q: Ansible playbook to execute Oracle script I am attempting to run a playbook to execute Oracle Scripts.
---
- hosts: localhost
- tasks:
   - set_fact:
        execute_command: "sqlplus {{ Oracle_Username }}/{{ Oracle_Password }} @{{ sqlfile.sql }}"

   - name: Get Object_details
     shell: "echo exit | {{ execute_command }} >> ./Oracle_Output.csv"
     environment:
        ORACLE_HOME: "{{ Oracle_DBServer }}"
        ORACLE_SID: "{{ Oracle_SID }}"

I have declared all the variables in vars.When I execute it , am getting error "set_fact is not valid attribute for a play" .
Which is the best way to run SQL script using Ansible?  I have to declare all the connection details in variable.

A: ---
- hosts: localhost
- tasks:
   - name: Get Object_details
     shell: echo exit |sqlplus "{{ oracle_username }}/ {{ oracle_pwd}} @(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host={{ oracle_hostname }} )(Port={{ oracle_port }}))(CONNECT_DATA=(SERVICE_NAME= {{ service_name }})))"@sqlfile.sql;

With the above code , we will be directly able to connect to Oracle Host and execute sql script. If the Oracle Environment variables are not defined by default, we can set that too in the playbook task itself. Below is the example for that :
---
- hosts: localhost
- tasks:
   - name: Get Object_details
     shell: echo exit |sqlplus "{{ oracle_username }}/ {{ oracle_pwd}} @(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host={{ oracle_hostname }} )(Port={{ oracle_port }}))(CONNECT_DATA=(SERVICE_NAME= {{ service_name }})))"@sqlfile.sql;
     environment:
          ORACLE_HOME: <<Oracle Home path >>
          PATH: << bin path >>
          LD_LIBRARY_PATH: << lib path >>

A: You forgot to declare tasks section:
---
- hosts: localhost
- tasks:
    - set_fact:
        execute_command: "sqlplus {{ Oracle_Username }}/{{ Oracle_Password }} @{{ sqlfile.sql }}"

    - name: Get Object_details
      shell: "echo exit | {{ execute_command }} >> ./Oracle_Output.csv"
      environment:
        ORACLE_HOME: "{{ Oracle_DBServer }}"
        ORACLE_SID: "{{ Oracle_SID }}"

P.S. and I'm not aware of wait attribute for tasks.

A: You need to export ORACLE_HOME first. Then you can call sqlplus from oracle's bin folder.
---
- hosts: localhost
- tasks:
    - name: Execute table.sql using sqlplus
      shell: $ORACLE_HOME/bin/sqlplus -s username/password@connect @table.sql
      environment:
        ORACLE_HOME: "{{oracle_home_path}}"
        LD_LIBRARY_PATH: "{{ld_library_path}}"
        PATH: "{{bin_path}}"
      args:
        chdir: "{{sql_path}}"
      become: true
      become_method: su
      become_user: oracle

A: - hosts: "{{ hosts }}"
  become: true
  become_user: oracle
  gather_facts: false
  vars:
    oracle_home: /product/u01/app/oracle/product/db/12.1.0.2/
  tasks:
   - name : NAME TASK
     shell: "export ORACLE_SID={{ base }}\n\
          export ORACLE_HOME={{ oracle_home }}\n\
          export PATH=$PATH:/product/u01/app/oracle/product/db/12.1.0.2/bin\n\
          /home/oracle/scripts_neodt/CREATE_USER.sh "

Im doing like this and its fine !


text:
Q: Hide my div on hover but show another - HTML/CSS I have three paragraphs
When I hover over the one that's showing already, I want to show the second paragraph below it and also replace the first paragraph by the third one?
With my css, because when I hover over the first paragraph it shows it and the second paragraph, when I try to also say 'block' the first paragraph and show the third, the UI goes crazy because its simultaneously trying to block and show, what can I do?

.nodeParagraph {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  z-index: 10000000;
  left: 20px;
  top: 20px;
  width: 265px;
}

.nodeParagraph:hover+.nodeParagraph1 {
  display: block;
}

.nodeParagraph1 {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  z-index: 10000000;
  left: 47.5px;
  top: 10px;
  width: 265px;
  display: none;
}

.nodeParagraph2 {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  z-index: 10000000;
  left: 20px;
  top: 20px;
  width: 265px;
}

.nodeParagraph:hover {
  overflow: visible;
  white-space: normal;
  width: auto;
}

 I am the greatest in the worl...

 world

 I am the greatest in the

Expected result:
I am the greatest in the
world

A: check this snippet, it might help you.

.nodeParagraph {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  z-index: 10000000;
  left: 20px;
  top: 20px;
  width: 265px;
}

.nodeParagraph:hover + .nodeParagraph1 {
  display: block;
}

.nodeParagraph1 {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  z-index: 10000000;
  left: 47.5px;
  top: 10px;
  width: 265px;
  display: none;
}

.nodeParagraph2 {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  z-index: 10000000;
  left: 20px;
  top: 20px;
  width: 265px;
}
.nodeParagraph .show-on-hover{
  display: none;
}
.nodeParagraph:hover .hide-on-hover{
  display: none;
}

.nodeParagraph:hover .show-on-hover{
  display: block;
}

  I am the greatest in the worl...
  I am the greatest in the

 world

A: Why not just use ellipsis then you wouldn't have to mess around with js and your html would be more semantically correct (without the need to repeat text)

.paragraph {
  width:175px;  /* for demo purposes */

  white-space:nowrap;  /* need these three to make paragraph have ellipsis */
  overflow:hidden;
  text-overflow:ellipsis;
}

.paragraph:hover {
  white-space:normal;  /* change back to a normal p*/
}

I am the greatest in the world

A: Edited: in case you want a javascript solution.
Well. First I would position your first and third paragraph one above the other and use a bit of jquery to replace your hover css properties.
your second paragraph position needed a bit of repositioning after using position:absoluteon the other 2
I used pointer-events:none; on the third one as it's above the first
The basic script just shows the second paragraph on hover and I also add class color to first paragraph becouse one text over other will make a kind of bold effect

$(".nodeParagraph").hover(function(){
    $(".nodeParagraph1").toggle();
    $(".nodeParagraph2").toggle();
    $(".nodeParagraph").toggleClass("color");
});
  .nodeParagraph {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  left: 20px;
  top: 20px;
  width: 265px;
  position:absolute;
}

.nodeParagraph1 {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position: relative;
  font-weight: 300;
  left: 47.5px;
  top: 40px;
  width: 265px;
  display: block;
  display:none;
}

.nodeParagraph2 {
  font-size: 14px;
  letter-spacing: 0.03px;
  cursor: pointer;
  font-family: $font-family-base;
  position:absolute;
  font-weight: 300;
  left: 20px;
  top: 20px;
  width: 265px;
  pointer-events:none;
  display:none;

}
.color {color:#fff;}

 I am the greatest in the worl...

 world

 I am the greatest in the


text:
Q: How to save variables after application shut down? I want to save some integers after application shut down and restore them after application opening, what is the easiest way to do this?

A: Check out the NSUserDefaults documentation. You can set arbitrary key-value pairs there which (as long as you call the shared user defaults object's -synchronize at some point before your app terminates) will persist between launches.

A: You can save them in the NSUserDefaults. This is mainly used for preferences.
[[NSUserDefaults standardUserDefaults] setObject:someInteger forKey:@"someIntegerKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

You can also save them to a Property List file if you have more data you'd like to store.
NSDictionary *someDictionary = [NSDictionary dictionaryWithObjectsAndKeys:someInt1, @"someIntKey1", someInt2, @"someIntKey2", nil];

[someDictionary writeToFile:somePath error:&error];

To save upon exiting the app place any code in
- (void)applicationWillTerminate:(UIApplication *)application

A: Look into using NSUserDefaults. This works like a dictionary that you can add key/value pairs to. You save the variables in your app delegate's applicationWillTerminate and applicationDidEnterBackground methods. You load the variables again in applicationDidFinishLoading.

A: You should store and load data from NSUserDefaults:
http://developer.apple.com/library/IOS/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// to store
[defaults setObject:[NSNumber numberWithInt:12345] forKey:@"myKey"];
[defaults synchronize];

// to load
NSNumber *aNumber = [defaults objectForKey:@"myKey"];
NSInteger anInt = [aNumber intValue];

A: The easiest way is to use NSUserDefaults. Your app delegate will get an -applicationWillTerminate: message when the app is about to shut down, and you can write your data to NSUserDefaults (or write it into your own file if the amount of data is large). Then, when your app starts up again, your app delegate will get an -applicationDidFinishLaunching, and you can read your data back again.

A: Serialize them and store them on memory. You have to do this before shut down and load when app is reopened


text:
Q: Is there another way to write string to datetime SQL query? I have a problem with date time format in database. It has format dd.MM.yyyy. I want to change this format to yyyy-MM-dd. I have a query that works perfectly in SQL compiler, but it doesn't work in DBeaver Firebird 3 database. When I try to run this I get following error:

SQL Error [335544634] [42000]: Dynamic SQL Error; SQL error code =
-104; Token unknown

I'm presuming that Firebird 3 doesn't implement some SQL functions. So my question is, how can I write this query differently?
SELECT SDC_TIME_SERVER_TIMEZONE
FROM SDC_INVOICES
WHERE DATE(substr(SDC_TIME_SERVER_TIMEZONE, 7, 4) || '-' || substr(SDC_TIME_SERVER_TIMEZONE, 4, 2) || '-' || substr(SDC_TIME_SERVER_TIMEZONE, 1, 2)) BETWEEN DATE('2022-01-01') AND ('2022-04-08')

A: I managed to solve it, it was a syntax problem. In Firebird, the query needs to look like this:
SELECT * FROM SDC_INVOICES si
INNER JOIN SDC_INVOICES_ITEMS sii ON si.ID = sii.INVOICE_ID
INNER JOIN SDC_INVOICES_TAXES sit ON si.ID = sit.INVOICE_ID
WHERE SUBSTRING (SDC_TIME_SERVER_TIMEZONE FROM 7 FOR 4) || '-' || SUBSTRING (SDC_TIME_SERVER_TIMEZONE FROM 4 FOR 2) || '-' || SUBSTRING (SDC_TIME_SERVER_TIMEZONE FROM 1 FOR 2)
BETWEEN ('2022-04-07') AND ('2022-04-13')


text:
Q: Anything wrong with this soapclient request? Can anyone tell me a reason the following code shouldn't work, assuming it points to the right external files and calls the correct functions?
<?php

$xmlstr = simplexml_load_file("file.xml");

$wsdl = 'file.wsdl';
$client = new SoapClient($wsdl, array(
    'cache_wsdl'    => WSDL_CACHE_NONE,
    'cache_ttl'     => 86400,
    'trace'         => true,
    'exceptions'    => true,
));

$xmlVar = new SoapVar($xmlstr, XSD_ANYXML);
$client->DoFunction($xmlstr);

The xml file it points to is an exact output of what i should send the server to get a response but all I get is an error 'Fatal error: Uncaught SoapFault exception' talking about the header can't be null. Which sounds like it isn't getting the authentication details but they are all correct. Is there anything I'm obviously doing wrong here?


text:
Q: Run Flask application with Nginx and Gunicorn it is the first time that I deploy a webapp and I really need of your help.
I want to run a Flask web app on a server using Nginx and Gunicorn. I found this tutorial but I can not to run the application correctly. I tried also other ways found in internet, but nothing.
This is my current /etc/nginx/sites-available/test.conf file
server {
listen 80;
server_name hello.itu24.com;

root /home/ubuntu/test;

location / {
    proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://127.0.0.1:8000;
    }
}

Instead this is my app /home/ubuntu/test.py
from flask import Flask
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)

@app.route('/')
def test():
    return "Hello world!"

app.wsgi_app = ProxyFix(app.wsgi_app)

if __name__ == '__main__':
    app.run()

Then I run the following command
ubuntu@ace:~$ sudo service nginx reload
* Reloading nginx configuration nginx                           [ OK ]
ubuntu@ace:~$ sudo gunicorn -b h 127.0.0.1:8000 test:app

Then if I go to IP address of the machine, since I am connecting from another machine, I can see the Nginx page. But if I add the port in the address IP:8000 no page is found. What am I doing wrong?

A: Nginx probably has another site defaulting to port 80. Make sure you've deleted the default.conf symlink from /etc/nginx/sites-enabled. Check the nginx.conf to make sure it doesn't have a server configured in it.
Your gunicorn command doesn't look quite right either. You need to use gunicorn -b 127.0.0.1:8000 test:app from your app's directory.

A: You are binding the gunicorn server only to the local interface 127.0.0.1, so it is not available from outside. You have to use nginx as the reverse proxy at port 80.


text:
Q: Global projection with zero scale distortion at non-zero latitude I am looking for a global projection with zero scale distortion at non-zero latitude.
I have tried using an Oblique Mercator projection centred at a specific latitude and longitude of centre (with Mercator orientation) in GeoTools (specified using WKT) but it seems to be a standard Mercator projection in terms of scale distortion. I was hoping it might have zero scale distortion at the latitude of centre but this doesn't seem to be the case.
Does such a projection exist? If so, what is the WKT for it?

A: An Oblique Mercator will have near-zero distortion along a great circle of contact; that excludes all circles of latitude (except the Equator).
Projections that minimize distortion along circles of latitude tend to be derived from conic projections and their limiting forms, cylindrical projections.  The conic projections are usually good only for hemispheres.  (You could create an interrupted conic, perhaps joining one for the Northern hemisphere with a similar one for the Southern hemisphere along the Equator, but creating such custom projections would take us beyond the scope of this question, as well as outrunning the capabilities of all GISes.)
You can always modify a cylindrical projection to have true scale along any circle of latitude, simply by stretching or compressing it vertically.  This can be done with the Mercator (the usual one).

PROJCS["Sphere_Mercator",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6371000.0,0.0]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Mercator"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",72.0],UNIT["Meter",1.0]]

To confirm its accuracy, note that on the sphere one degree of longitude at 72 degrees latitude is the same length as cos(72 degrees) = 1/(1 + Sqrt(5)) = 0.309 degrees of latitude, whence the spacing on this ten-degree graticule ought to give rectangles with aspect ratios approximately 1+sqrt(5) = 3.24 near 72 degree latitude (north and south): that is indeed the appearance here.
Alternatively--to avoid the expansion of the map to infinity at the poles--you could use, say, an Equidistant Cylindrical projection.  Here is one with its latitude of scale set to 72 degrees:

PROJCS["Sphere_Equidistant_Cylindrical",GEOGCS["GCS_Sphere",DATUM["D_Sphere",SPHEROID["Sphere",6371000.0,0.0]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Equidistant_Cylindrical"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",72.0],UNIT["Meter",1.0]]

In this map, the aspect ratios of the rectangles in the graticule are a constant 1+sqrt(5).


text:
Q: Rails - on click event - how to deal with race condition between 2 Ruby methods? On my view I have a link_to element "Start Quiz!" that calls a controller method (method A) that sets a variable "Phase" and redirects the user to a new static page. In my CoffeeScript I have an event listener listening for clicks on this link_to element. The listener calls a different method (method B) on the backend that uses the "Phase" variable to do sth.
The problem: sometimes method B tries to use the "Phase" variable before it has been updated by the controller method A! Does anyone have a suggestion what the best way would be to ensure that the "Phase" variable was updated before using it for anything else?
I'm a Rails beginner and would appreciate any pointers. :)

EDIT:
"Phase" is a variable I use to track the current question of my quiz. It's not dependent on any input, but it needs increment whenever a new page is rendered (which is triggered by the button click).

EDIT2:
I've now tried to solve this by introducing an instance variable flag "is_changed" to my controller and letting the method B sleep until the flag is set to true:
#method B:
def send_answers
   until controller.index_changed?
     sleep(0.5)
   end
   ...
   do sth.
end

#method A (in controller):
def initialize
   @index_changed = false
end

def index_changed?
   @index_changed
end

def set_index_changed!
   @index_changed = false
end

def switch_to_next_question
   ...
   self.phase += 1
   if self.save
      Thread.new do
         @index_changed = true
         ActiveRecord::Base.connection.close
      end
   else
      ...
   end
end

It's not working. Method A gets stuck sleeping. How do I fix this? And is this even the right approach?
Is it a problem with the scope of my @index_changed variable? I'm trying to create an instance variable that is accessible from multiple methods within the class, but individual to each instance of this class.

A: Ok, I solved it by finding a way to call the 2 methods sequentially. I ended up eliminating the on click listener completely and calling the ActionCable backend method directly, which was possible by turning it into a class method:
class QuizDataChannel < ApplicationCable::Channel
  #method B:
  def self.send_answers #self. makes it a class method
    #...
    #do something with phase
  end
end

And in my controller:
#method A:
def switch_to_next_question
   #...
   self.phase += 1
   if self.save
      QuizDataChannel.send_answers
   else
      #...
   end
end

As you can see in the end I got rid of all of these: sleep, new threads and the index_changed flag.


text:
Q: Convert first row of excel into dictionary I am trying to convert first header row of excel table into dict with a value of 1. Fairly new to Python and not able to excute this code. My table in spreadhseet looks like:

Matrix
Column A
Column B

Row A
10
20

Row B
30
40

I would like my output as following dict:
{'Column A': 1,'Column B': 1}
I tried test_row = pd.read_excel("Test.xlsx", index_col=0).to_dict('index')
The column names will increase in future. So, it will be nice to have a solution that can extract n number of columns header into dict with a value of 1. Many thanks!

A: Given your example Dataframe as
df = pd.DataFrame({'Matrix': {0: 'Row A', 1: 'Row B'}, 'Column A': {0: 10, 1: 30}, 'Column B': {0: 20, 1: 40}})

You can use:
cols_dict = {col: 1 for col in df.columns}  # {'Matrix': 1, 'Column A': 1, 'Column B': 1}
rows_dict = {row: 1 for row in df.Matrix}  # {'Row A': 1, 'Row B': 1}


text:
Q: deadlock condition arises between child and parent process From a java program, I want to execute a script which reads an input from a specified folder and generates gcov data. The script generates part of the gcov data correctly, but fails to generate the remaining data until I explicitely terminate my java program, after which it completes its job as expected.
Here is the code that launches the script:
try {
    Process proc = Runtime.getRuntime().exec("/bin/bash CovSeq.sh");
    proc.waitFor();

    System.out.println("Generated gcov Data");
} catch(Exception e) {
    System.err.println("Error: "+e.getMessage());
}

Here is the script:
#!/bin/bash
lines=($(cat path))
mkdir output
mkdir gcovOut
rm -f -r ./gcovOut/*
rm -f -r ./output/*
gcc -g -o temp_exec -fprofile-arcs -ftest-coverage ${lines[0]}
path1=`pwd`
cd ${lines[1]}
for i in `ls *`
do
cd $path1
./temp_exec < ${lines[1]}/$i > ./output/$i
gcov -b -c ${lines[0]}
mkdir ./gcovOut/$i
mv *.gcov ./gcovOut/$i
mv *.gcda ./gcovOut/$i
cd ${lines[1]}
done

A: When you spawn a child process from Java, you must consume its standard output and standard descriptors, or the child process will block because these files are full.
There are are a couple of ways to do this. Within the script, you can direct all output to a file. Alternatively, you can alter the shell command to direct all output from the script to a file. Either of these approaches make it so that there is no output that needs to be consumed, thus, no blocking.
If you would rather handle this problem from the Java side, you can spawn threads to read the InputStream objects that represent the child's standard output and standard error streams. You can discard, log, or interpret these data in your Java program as needed.

A: My bet is that the script is blocked because the parent process does not consume its output. This is known behaviour for Runtime.exec(). Here is an example how to use it properly.


text:
Q: Insert a variable from JS to Django form input field I am writing a form that pays an employee's mileage between two cities.  I am using the Google Maps API to get the information.  I am running a script that yields a variable drivingDistanceMiles.  I would like to populate the field in my Django form mileage, which saves to a python variable distance.
Here is a snippet of my form html:
<form action="" method="post"><% csrf_token %}
{{  form.non_field_errors  }}

    {{  form.distance.errors  }}
    Mileage claim:
    {{  form.distance  }}

There is a distance calculator on the page just above the entry.
In my forms.py distance = forms.CharField(max_length=20, required = False).  I made this a CharField instead of an IntField in case my employees (not the most computer savvy bunch) add the word 'miles' at the end.
THE QUESTION:  Is it possible to get the value of drivingDistanceMiles to auto-populate when the user enters their city info into the distance calculator?

A: If you're using plain javascript (not jQuery or any frameworks) you can access the field by document.getElementById('id_distance').value. You can set it's value by document.getElementById('id_distance').value = <some_var>;


text: Q: Camera2 API Stop Preview from Rotating I'm following Camera2 Basic and I'm trying to stop the preview from rotating when the phone's orientation changes. If you open the stock camera app in Android, the camera preview doesn't rotate when you rotate your phone but rather the interface around it. This is the effect I want to achieve.


text: Q: /usr/local/bin has precedence over usr/bin : why is python still python2? I brew-installed python on my mac, and put usr/local/bin before usr/bin in my PATH, but python --version still gives me Python 2.7.10 while I want my default version to be Python 3.6.4 (which is the answer to python3 --version, so it's definitely installed). Also, I can't find Python 3.6.4 in /System/Library/Frameworks/Python.framework/Versions, if I list the content of the folder it just gives me 2.3 2.5 2.6 2.7 Current. How do I change that without causing any problem to my computer?


text:
Q: Add an object into an array with named fields I have trouble trying to add an object into an array with JavaScript.
I have searched in other questions, but my problem is more specific.
This is my array:
dataGameDentro = [{ Name  : "EM1Aaa", Pontos : 7000 },{ Name  : "EM1B", Pontos : 400 }];

I am trying to add
var currentPoint = $('#points-final').html().toString();

dataGameDentro.push({Name:"e5", Pontos : currentPoint});

or
dataGameDentro.splice(dataGameDentro.length, 0, {Name:"e5", Pontos : currentPoint});

but it doesn't work. What is wrong in my code?

A: As mentioned in the comments on the question, the problem here is that your Pontos are stored as integer values, whereas the result of .html() is always a string value.
Naturally, you want to coerce the string value into an integer. The best way* of doing this in JS is using parseInt, like so:
var currentPoint = parseInt($('#points-final').html(), 10);

dataGameDentro.push({ Name: 'e5', Pontos: currentPoint });

I hope this clarifies things a bit.
*N.B. There are faster ways of converting from a string to an integer, as shown by these benchmarks, but parseInt is by far the most clear and reliable.


text:
Q: Interrupts in AVR ATmega324A I have this code but i need to alter it to be for the rising edge of pin B2, ive had a look at the datasheet and does the INT0, get changed to INT2?
Im just a little unsure and im very new to the ATMEGA324A and avr

/* Set up interrupt to occur on rising edge of pin D2 (start/stop button) */
  EICRA = (1<<ISC01)|(1<<ISC00);
  EIMSK = (1<<INT0);
  EIFR = (1<<INTF0);

This is the current code block I want to add it to:
clock
Ticks = 0L;

    /* Clear the timer */
    TCNT0 = 0;

    /* Set the output compare value to be 124 */
    OCR0A = 124;

    /* Set the timer to clear on compare match (CTC mode)
     * and to divide the clock by 64. This starts the timer
     * running.
     */
    TCCR0A = (1<<WGM01);
    TCCR0B = (1<<CS01)|(1<<CS00);

    /* Enable an interrupt on output compare match.
     * Note that interrupts have to be enabled globally
     * before the interrupts will fire.
     */
    TIMSK0 |= (1<<OCIE0A);

    /* Make sure the interrupt flag is cleared by writing a
     * 1 to it.
     */
    TIFR0 |= (1<<OCF0A);

A: At first You should try example with LED.
So tasks to do:

*

*Enable external interrupt on PB2, check Pinout Configurations, you should take pin with description which contains INTx - [x - 0/1/2].

*Prepare pin to use it as source of external interrupt by setting it DDRx // DDRB if PINB2 as input.

*Prepare MCU registers to "catch" your interrupt, EICRA and EIMSK registers as you tried but for pin that you choose (INT2 on PB2).

*Write ISR (interrupt subroutines) according to your desired task (I would like to recommend you to start with simple toggle LED when interrupt occurs). You should use macro from avr/interrupt.h named ISR(INT2_vect){ // isr body}.

*Enable executing ISRs with sei(); function.

When I used external interrupts at first time I was enabling LED in ISR and disabling external interrupt to prevent multi-execution.
This is short "code" about above instructions.
#include <avr/io.h>
#include <avr/interrupt.h>

int main(void)
{
  // set your pin as input here
  // set your MCU to "catch" external interrupt here
  // enable interrupts with sei(); instruction here

  while(1);

  return 0;
}

ISR(INT2_vect)
{
  // your action when interrupt occurs here
}


text:
Q: Iterate through range selection This is very simple for someone that knows what they are doing.
I have a little script that pulls the current selection and formats the cell background to match the value (provided that the cell is a hex value). I'd like to make this work on any range selected. I'll have to do some checking that each string is a hex value etc but I'm blocked on iterating thru a range.
Any hints on how I would loop through a range selection with office.js?
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
    function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Failed) {
            console.log(asyncResult.error.message);
        } else {
            // write the result to range selection variable
            var rsel = asyncResult.value;
        }

        Excel.run(function(context) {
            // convert to string
            context.workbook.getSelectedRange().format.fill.color = rsel.toString();
            return context.sync();
        }).catch(function(error) {
            console.log(error);
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
    }
);

A: Based on your description, it sounds like you want somethign like this?

Here are two functions, one that just writes random hex values to the cells, and another that actually colors them.  Note that it's generally best to not mix ExcelApi 1.1 API syntax and Office 2013 getSelectedDataAsync in the same code block, or else the callback vs. promise pattern can get a little confusing -- though you did have it right above.  For my examples, though, I'll use just the ExcelApi 1.1 syntax:
function setRandomValues() {
    Excel.run(function (context) {
        var selection = context.workbook.getSelectedRange();
        selection.format.fill.clear();
        selection.load("rowCount, columnCount");

        return context.sync()
            .then(function() {
                var valuesArray = [];
                for (var r = 0; r < selection.rowCount; r++) {
                    var rowValues = [];
                    for (var c = 0; c < selection.columnCount; c++) {
                        rowValues.push(getRandomColor());
                    }
                    valuesArray.push(rowValues);
                }
                selection.values = valuesArray;
            })
            .then(context.sync);

        function getRandomColor() {
            // from http://stackoverflow.com/a/5092872/678505
            return "#000000".replace(/0/g, function(){
                return (~~(Math.random()*16)).toString(16);
            });
        }
    })
    .catch(console.log)
}

And
function highlightSelection() {
    Excel.run(function (context) {
        var selection = context.workbook.getSelectedRange();
        selection.load("rowCount, columnCount, values");

        return context.sync()
            .then(function() {
                for (var r = 0; r < selection.rowCount; r++) {
                    for (var c = 0; c < selection.columnCount; c++) {
                        selection.getCell(r, c).format.fill.color = selection.values[r][c];
                    }
                }
            })
            .then(context.sync);
    })
    .catch(console.log);
}


text:
Q: std::sort() not working on vector of pairs I have the following code snippet:
struct compare {
    bool operator()(const pair<size_t, double>& left, const pair<size_t, double>& right) {
               return left.second > right.second;
    }
};

int main() {
   size_t vertices = 31112738;
   vector<pair<size_t, double> > opt, one;
   opt.reserve(vertices);
   one.reserve(vertices);

   for(size_t i=0;i<vertices;i++) {
      opt[i] = make_pair(i,rand());
      one[i] = make_pair(i,rand());
   }

   sort(opt.begin(), opt.end(), compare());
   sort(one.begin(), one.end(), compare());

  return 0;

}

Even after calling the sort function, opt[] and one[] aren't sorted. If however I use push_back() to insert the elements and then call the sort() function, they get sorted.
Why is the outcome different in the two scenarios?

A: Because in the scenario you outlined, the vectors always have size 0.
You reserve more space in the vectors, but you never resize them. (So your for-loop just triggers undefined behavior by writing past the end of the vectors)
push_back grows the vector's size by 1, but if you don't call that, then you must call resize and set the size explicitly. (or specify the size as a constructor argument)


text:
Q: Changing Dropdown attribute to text in magento 1.9 without changing data In Magento 1.9, I am going to convert my drop-down attributes to text field without changing my current data
Below is the image of current attribute set

A: I have a couple of update statements that should change the data-type from int to varchar (should be the case for all non-numeric text fields), changes input-type from select to text, and migrates all of the existing data into the correct tables. You should be able to run these in either order, then just re-index and you're done!
Update attribute settings:
UPDATE eav_attribute
SET
    backend_type = 'varchar',
    frontend_input = 'text'
WHERE attribute_id = [add the attribute id];

Insert values from the old table into the new table:
insert into catalog_product_entity_varchar
(entity_type_id, attribute_id, store_id, entity_id, value)
(
    select
        cpei.entity_type_id,
        cpei.attribute_id,
        cpei.store_id,
        cpei.entity_id,
        eaov.value
    from eav_attribute_option eao
    join eav_attribute_option_value eaov
    on eao.option_id = eaov.option_id
    join catalog_product_entity_int cpei
    on eao.option_id = cpei.value
    where cpei.attribute_id = [one or more attribute_ids of your choosing]
)

hope its work for you


text:
Q: setTimeout never running, with or without clearTimeout I have the following two functions:
window.onbeforeunload = null;
// this part is never executing
this.timeout = setTimeout(function(){
    console.log("redirecting");
    location.href="/dashboard";
}, 10000);
try {
    // here I also call the other function
    await this.recorder.stop();
}
catch (err) {
    console.log(err);
    clearTimeout(this.timeout);
}

And the second one that is called from this.recorder.stop();.
console.log("sending mail");
var self = this;
// console.log(blob instanceof Blob);
var file = new File([blob], "recording");
var formData = new FormData();
formData.append("recording", file);
formData.append("format", (this.isIOS ? "mp4" : "webm"));
formData.append("routine_id", this.routine_id);
axios.post('/room/send/recording', formData)
    .then(function (response) {
        if(response.data.result) {
            console.log("email has been sent")
        } else {
            console.log("failed to send email")
        }
    })
    .catch(({response}) => {
        console.log("an error occured during email call")
        console.error(response);
    })
    .finally(function() {
        clearTimeout(self.timeout);
        console.log("timeout cleared");
    });

But the redirect inside the setTimeout is never executing...
The console.log also does not run.
this.timeout = setTimeout(function(){
    console.log("redirecting");
    location.href="/dashboard";
}, 10000);

The console.log looks like this (no "redirecting" output)
sending mail
email has been sent
timeout cleared

Any clues as to why?

A: As pointed out by @SergeS , I had misunderstood how clearTimeout() works entirely.
After clearTimeout, the function is not called anymore, therefore instead of
clearTimeout(self.timeout);

I also needed to call the function again. Since the function was only a single redirection something like this was fine
clearTimeout(self.timeout);
location.href="/dashboard";


text:
Q: Tesseract OCR not splitting text into different result sets correctly I need your help. I am trying to get the emails on the image bellow as separate results and respectively their bounding box's. Somehow Tesseract OCR does not recognize them as separate lines and returns them as a single result.
Current Output - One block
Top: 182, Bottom: 512, Left: 533, Right: 852 -
BCF6CC517E7642BBB21AAF2068E54C28 - Test
D4852831D8CA439EB9D98B54629D1840 - Test
8DFFDO6FA3B44989B224DABDD9292B3E - Test
10E1D83F0D834000AF7BDSDEA48442E8 - Test
6FOA122825AA42159FDEESEBFFAC279B - Test
E719274DA1CE46ADASBDB659812ED684 - Test
ES18EE9D7D7B4AA3ABAT81523F748B24 - Test
?0304b4b-ba1d-4897-8ebe-20bcc3930201 - Test
2ebad2h1-c385-4d84-96c7-bc9082141e1c - Test

Desired output - multiple blocks per GUID
Top: 182, Bottom: 210, Left: 533, Right: 852 -
BCF6CC517E7642BBB21AAF2068E54C28 - Test
Top: 210, Bottom: 230, Left: 533, Right: 852 -
D4852831D8CA439EB9D98B54629D1840 - Test
Top: 230, Bottom: 250, Left: 533, Right: 852 -
8DFFDO6FA3B44989B224DABDD9292B3E - Test
...

I have tried most of the OcrEngineMode's and PageSegmentationMode's.
Nothing worked out correctly.
I also scaled the image from 96 DPI to 300 DPI. Did not help.
Also I went through the documentation and couldn't find a solution.
I am using Tesseract 4
Thank you in advance for your time and help.

A: When iterating over the results, you should set your PageIteratorLevel to
RIL_TEXTLINE so that it can split the result paragraphs into separate lines.
  var resultIterator = tessBaseAPI.GetIterator();

  var pageIteratorLevel = PageIteratorLevel.RIL_TEXTLINE;


text:
Q: Javascript syntax on Facebook developer page I don't get some of the syntax in this block of code taken from the facebook developers site.
Are the first variables 'js' and 'id' bound in some way? What exactly is being returned in the first if statement?
     (function(d){
       var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
       js = d.createElement('script'); js.id = id; js.async = true;
       js.src = "//connect.facebook.net/en_US/all.js";
       d.getElementsByTagName('head')[0].appendChild(js);
     }(document));

This is the link to the page: http://developers.facebook.com/docs/guides/web/#personalization

A: What do you mean by "bound"?
They're function-local; js is a variable set in the 3rd and 4th lines, id is set to a string immediately.
The function itself is executed immediately after definition, with d set to document inside the function.
Nothing is returned by the first (and only explicit) return statement. And if this is the only code, a return value would be meaningless, because nothing captures the return value.

A: Nothing exiting here, just stolen whitespaces :)
(function(d){
    var js,    // variable (empty)
        id = 'facebook-jssdk';    // variable with string 'facebook-jssdk'

    if (d.getElementById(id)) {    // is there an element with id 'facebook-jssdk'
        return;    // yes, so we have nothing to do and get out of here
    }

    js = d.createElement('script');    // create 'script' element
    js.id = id;    // assign id 'facebook-jssdk'
    js.async = true;    // load in "background" (if supported)
    js.src = "//connect.facebook.net/en_US/all.js";    // set source (with the appropriate protocol; https if called via https, http otherwise)
    d.getElementByTagNam('head')[0].appendChild(js);    // append to first head element on page
}(document))    // immediately call the anonymous function and hand in the 'document'


text:
Q: Unknown column 'name' in 'where clause' I actually I'm working in an attendance system based on facial recognition.
But unfortunately, I'm facing  a problem with Mysql to record attendance
 if True in matches:
    first_match_index = matches.index(True)
    name = known_face_names[first_match_index]

    sql = "UPDATE stud_att SET P1=1 WHERE name = fname"
    mycursor.execute(sql)
    mydb.commit()

  draw.rectangle(((left, top), (right, bottom)), outline=(255,255,0))

      text_width, text_height = draw.textsize(name)
      draw.rectangle(((left,bottom - text_height - 10), (right, bottom)), fill=(255,255,0), outline=(255,255,0))
      draw.text((left + 6, bottom - text_height - 5), name, fill=(0,0,0))

    del draw

Here is my code the problem is Unknown column 'name' in 'where clause'
I don't know where is the wrong I'm sure the name that the system was recognized is Existing in the database!
My table
fname, lname, ID, P1, P2, P3, P4
Name1,  Name2, 1,

A: sql = "UPDATE stud_att SET P1=1 WHERE fname = " + name

your column name must be on the left side of the = and then compare it to the value you want to check.

A: Your immediate problem is a quoting issue: in SQL, strings need to be surrounded with single quotes; assuming that name is a string, you would need:
mycursor.execute("UPDATE stud_att SET P1 = 1 WHERE fname = '" + name + "'")

But this is error-prone to write, and still leaves you your code to SQL injection. So: you should just use a parameterized query:
mycursor.execute("UPDATE stud_att SET P1 = 1 WHERE fname = %s", (name))


text:
Q: Waiting for an event to happen on the server? Say I'm making a messaging web app (for example). Sending messages is easy enough; I can just use a POST request for that. But what if I want to be notified when a new message arrives? How can I handle that on the client and server?
Should I open an http request on the client to the server, and have the server simply wait until there's a new message before returning? How does Facebook do it?

A: I remember trying to reverse engineer facebook's approach but that was a few years ago. It seems like they just have one long request that returns only after a certain timeout (in which case, it retries) or if an interesting event has happened (which then triggers a few other queries).
Check out the following links:
http://ajaxpatterns.org/HTTP_Streaming
http://en.wikipedia.org/wiki/Push_technology#HTTP_server_push
A little googling turns out a nice feature of html5. Haven't tried this before, but it seems to do the same thing:
http://www.html5rocks.com/en/tutorials/eventsource/basics/


text:
Q: Passing plots out of a class I have been trying to pass a pyplot Figure out of an external class (as in must be imported), but have been unsuccessful.  I don't even know if this is the way I should be tackling the problem of getting a plot (un-shown) out of a class.
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

class Plotter(object):
    def __init__(self, xval=None, yval=None):
        self.xval = xval
        self.yval = yval

    def plotthing(self):
        f = Figure(1)
        sp = f.add_subplot(111)
        sp.plot(self.xval, self.yval, 'o-')
        return f

So that is the class roughly (names plotfile.py).  Here is the bulk other script.
from plotfile import Plotter
import matplotlib.pyplot as plt

app = Plotter(xval=range(0,10), yval=range(0,10))
plot = app.plotthing()
app.show(plot)

I have tried several variations on this theme and have tried my best googlefu, but not no avail.  Any help would be greatly appreciated.  If I am way off on my approach to this I am very open to hearing how to do it correctly.  Thanks.

A: A few points: I don't think Figure works like like you think it does, and your Plotter object doesn't have a .show() method, so app.show(plot) won't work.  The following worked for me:

# plotfile.py
import matplotlib.pyplot as plt

class Plotter(object):
    def __init__(self, xval=None, yval=None):
        self.xval = xval
        self.yval = yval

    def plotthing(self):
        f = plt.figure()
        sp = f.add_subplot(111)
        sp.plot(self.xval, self.yval, 'o-')
        return f

from plotfile import Plotter

app = Plotter(xval=range(0,10), yval=range(0,10))
plot = app.plotthing()
plot.show()
raw_input()


text:
Q: Can a C++ function return more than one value?
Possible Duplicate:
can a function return more than one value?

I want to return 3 variables from a c++ function but as one function can have only one running return value how I can return 3 values. tried using return(5,4); but this is an syntax error.

A: You can only return one value in C++. If you need to return more information, return a structure (or a container like a std::vector for example), or pass in some variables as non-const references (or pointers) and change those.

A:
tried using return(5,4); but this is an syntax error.

That is not a syntax error. (5,4) is a valid expression and here , is an operator. So the expression (5,4) evaluates to the rightmost operand, which is 4. Hence it will return 4.

Now coming to your problem: define a struct if any existing one doesn't help you, and return an object of struct instead, as:
struct values
{
   int i;
   int j;
   char *other;
};

values f()
{
  values v = {/*....*/};
   //...
   return v;
}

And if type of all values is same, then you can use std::vector as:
#include <vector>  //must include it!

std::vector<int> f()
{
   std::vector<int> v;
   v.push_back(5);
   v.push_back(4);
   //so on
   //...
   return v;
}

There are other containers as well, viz. std::map, std::list, std::stack, etc. Use which suits you the best. There is also std::pair which holds only two values, as the name implies.

A: A C++ function can return only one value. However, you can return multiple values by wrapping them in a class or struct.
struct Foo
{
     int value1;
     int value2;
};

Foo SomeFunction()
{
    Foo result = { 5, 4 };
    return result;
}

Or you could use std::tuple, if that is available with your compiler.
#include <tuple>

std::tuple<int, int, int> SomeFunction()
{
    return std::make_tuple(5, 4, 3);
}

If you don't know in advance how many values you're going to return, a std::vector or a similar container is your best bet.
You can also return multiple values by having pointer or reference arguments to your function and modifying them in your function, but I think returning a compound type is generally speaking a "cleaner" approach.

A: Or you could use std::pair for two results and look at boost::tuple for more than two. It can even handle different types in the same tuple.

A: There are several ways to achieve that.

*

*If you have objects of the same type, std::array would be a good return type for that.
 If you have varying numbers, use std::vector instead.

*If you have (a fixed number of) different types, use std::tuple:
std::tuple <int, long, double> f()
{
  return std::tuple <int, long, double>( 42, 4711l, 3.141 );
}

I know no way to return a varying number of non-polymorphic objects of different types built into the language or standard library.

A: No, but there are two ways to do that:
1) Give the pointers to the values to "return" as parameters, you change the value of it in the function.
2) You may create a struct that contains all these values and return the struct. Use this only if it is really necessary, though, the fist solution is much better.

A: Most of the answers here are correct that you should return a struct.
There is one more way if you are interested, and that is by sending reference of the variables that you want to return.
For example:
#include<iostream>
#include<cstdio>
using namespace std;
bool f(int a,int b,int& q,int& r)
{
    if(b==0)return 0;
    q=a/b;
    r=a%b;
    return 1;
}

int main()
{
    int a=64,b=7,q,r;
    bool pos=f(a,b,q,r);
    if(pos)
    {
        printf("Quotient = %d Remainder = %d\n",q,r);
    }
    else
    {
        printf("Divison by zero not possible!\n");
    }
    return 0;
}

A: return (a, b, c, ... , n) The statements a, b, c are separated with comma operators and the expression evaluates to the rightmost operand n . So the syntax is correct, but does not return multiple values.
To return multiple values:

*

*Put the variables you want to return in a structure and return it.

*Or make an array of multiple variables (dynamically allocated) and return the base address

A: It is possible to return more than one values from a function you have to use pointer for that case. Also this is possible by using the pointer arguments pointer arguments keep their value'
 Detailed usage of pointer for returning more than one value is at http://www.techyv.com/questions/how-do-i-return-multiple-variables-c-function

A: Return a structure.
struct a
{
   int x;
   int y;
   int z;
};

b()
{
    a.x = 2;
    a.y = 4;
    a.z = 8;
    return a;
}

A: You can't. You can, however, do tricks to fake it. For example, make your function return a pointer to int, and returning the pointer to an array of ints.


text:
Q: Programmatically embed Kanji in Textfield In the "Embed...Character Embedding" window in the Flash environment, you can select to embed Japanese Kanji. Does anyone know of a way to embed the same using a TextField created with Actionscript?

A: You need to create a font symbol in your library and assign a linkage class (in this case "Font1"):
var myFont:Font = new Font1();
var myFormat:TextFormat = new TextFormat();
myFormat.font = myFont.fontName;

var myTextField:TextField = new TextField();
myTextField.defaultTextFormat = myFormat;
myTextField.embedFonts = true;
myTextField.text = "Hello World!";
addChild(myTextField);

See article on Embedding fonts

A: I usually use this with succes:
    package
{

        import flash.display.Sprite;
        import flash.display.TextField;
        import flash.display.TextFieldAutoSize;

        import flash.text.TextFormat;
        import flash.text.AntiAliasType;

        public class EmbedFontTest extends Sprite
        {

                [Embed(source="C:\WINDOWS\Fonts\ARIAL.TTF", fontFamily="Arial")]
                private var _arial_str:String;

                private var _arial_fmt:TextFormat;
                private var _text_txt:TextField;

                public function EmbedFontTest()
                {
                        super();

                        this.initEmbedFontTest();
                }

                private function initEmbedFontTest():Void
                {
                        this._arial_fmt = new TextFormat();
                        this._arial_fmt.font = "Arial";
                        this._arial_fmt.size = 40;

                        this._text_txt = new TextField();
                        this._text_txt.embedFonts = true;
                        this._text_txt.autoSize = TextFieldAutoSize.LEFT;
                        this._text_txt.defaultTextFormat = this._arial_fmt;
                        this._text_txt.text = "Test Arial Format";

                        this.addChild(this._text_txt);
                }
        }

}

A: Actually, I ended up finding out that the best way to support Kanji (in my case) was to not embed the font at all and just use the _sans option in the TextField.


text:
Q: Disable Stylus Gestures for WinForm I need to disable all stylus gestures for a winform. I want the stylus to function normally (i.e. basically as a mouse substitute) but the stylus gestures are majorly in the way.
Ideally, the gestures would only be disabled for a specific form, but application wide is also acceptable.
Since my app is full screen I could even settle for disabling stylus gestures system wide but would need to restore the original state when the app exits.
So far, what I have is:
I catch the WM_TABLET_FLICK message in the WndProc and return with FLICK_WM_HANDLED_MASK, indicating the no further action is required.
That works in the sense that the flick is ignored. HOWEVER, I also loose all stylus movement that is part of the flick. It seems to me that I need to disable the flicks on a deeper level, such that the system doesn't even bother trying to recognize any flicks to begin with.
Any ideas?

A: Solution:
catch WM_TABLET_QUERYSYSTEMGESTURESTATUS in WndProc and return TABLET_DISABLE_FLICKS.
that disables even the detection of flicks, i.e. no stylus movement gets lost.
further "info":
msdn


text:
Q: Panel linear regression with duplicate time I am trying to carry out panel linear regression with yield and climate data from an project called ISIMIP. In this project, different groups of scientist running their crop models using the same GCMs so that they can compare their results to each other. I am using yield and climate data from 3 crop models that used 3 different GCMs (meaning I have 9 combinations of crop model-GCMs).
My plan is to run a panel linear regression through a yield-climate panel for each crop model (which means my panel consists of climate data from 3 different GCMs and the corresponding yield data of the same crop model). I am using 'plm' package from R. However, the issue I am running into now is as follow:
> panel.plr <- pdata.frame(panel, index = c('GCM','Grid','Year'), row.names = F)
Warning message:
In pdata.frame(panel, index = c("GCM", "Grid", "Year"), row.names = F) :
  duplicate couples (id-time) in resulting pdata.frame
 to find out which, use e.g. table(index(your_pdataframe), useNA = "ifany")

It is true since I am using 3 different climate series from 3 different GCMs. Therefore each year is duplicated three times.
Can someone please help me to find a way around this issue? Thank you very much.

A: Try as.data.frame rather than pdata.frame. I just got rid of the error through this simple change. I used as.data.frame for my panel regression (as below). I had four quarters data for > 10 year of > 10 firms.
pdata <- as.data.frame(emp_1990q1_2005q4)
fe2 <- plm(leverage ~ ibb + s, data = pdata, model = "within", effect = "twoways", index = c("id", "date"))


text:
Q: Is there any script handler to show pop up screen(jsp/html) page on lock or screen saver mode I have a parent page and it populate a pop up screen if there any message, its working fine but my case is, I want to display the pop up in front of the screen when the systems is in screen saver mode and lock screen mode.Is there any script handler to handle this.

A: No, this isn't possible.
From what I can tell, you want to be able to send the user an alert regardless of what they have open (screensaver/lock). This isn't going to be possible from the web browser without some sort of plugin installed.
You may be able to trigger an audio alert to sound when the screen saver/lock screen are on, but that is just a guess! Good luck.

A: Screen saver and lock screen mode are operating system's property, i dont think there will be any direct method to detect them.
Workaround would be take a "general" time of screen saver display and detect if there was no user activity in that time then display the message


text:
Q: Changing Radio button Input template using CakePHP 3 I would like change structure but it does not work, it's always the same structure. How to solve my problem?
 <?php
$default = 'wepay';
$options = array('wepay' => 'WePay', 'paypal' => 'Paypal', 'donorbank' => 'Donor Bank');
echo $this->Form->input('payment_method', [
    'templates' => [
        'radioWrapper' => '{{label}}'],
    'type'      => 'radio',
    'options'   => $options,
    'default'   => $default
]);
?>

But this code does not generate output properly. I want to generate output like below:

    <input type="radio" name="payment_method" value="wepay" id="payment-method-wepay" checked="checked">WePay

    <input type="radio" name="payment_method" value="paypal" id="payment-method-paypal">Paypal

    <input type="radio" name="payment_method" value="donorbank" id="payment-method-donorbank">Donor Bank

My Code generate output like below:

        <input type="radio" name="payment_method" value="wepay" id="payment-method-wepay" checked="checked">WePay

        <input type="radio" name="payment_method" value="paypal" id="payment-method-paypal">Paypal

    <input type="radio" name="payment_method" value="donorbank" id="payment-method-donorbank">Donor Bank

Here one extra label field added. How can I remove this extra-label?

A: What you are showing there is pretty much the default output, except for the class attribute and the missing for attribute on the label. So what you want to modify most probably is the nestingLabel template, surely not the radioWrapper one:
 'nestingLabel' =>
     '{{hidden}}{{input}}{{text}}'

If you want to remove the for attribute, then you'll have to remove the {{attrs}} placeholder, that way no further attributes can be added to the label element.

A: Finally, solved my problem using @ndm hints. Final solution like this below
<?php
$default = 'wepay';
$options = array('wepay' => 'WePay', 'paypal' => 'Paypal', 'donorbank' => 'Donor Bank');
echo $this->Form->input('payment_method', [
    'nestingLabel' =>
         '{{hidden}}{{input}}{{text}}',
    'type'      => 'radio',
    'options'   => $options,
    'default'   => $default
]);
?>

Hope this solution help others in future.


text:
Q: TFSBuild: Disabling Code-Analysis for one project We have a large VS2012 solution (~250 projects) that is 90% C#. 2 of the 3 C++ projects use the 'v110' Platform Toolset. The third has to use the 'v110_xp' toolset for compatibility with a third party library.  Our nightly TFS (2012) build is configured with 'Perform Code Analysis' set to Always.
Unfortunately, the v110_xp platform does not support code analysis (MSDN Blog).  This results with the following build failure:

Microsoft.Cpp.Win32.v110_xp.targets(28,5): error MSB8026: Static analysis is not supported with the current platform toolset.

Any ideas how we can prevent code analysis from running on this single project without enabling (by default) code analysis for all projects (except the one)?

A: You should change the build to be "As Configured" and select I your solution which projects to run analytics on and which not.
https://msdn.microsoft.com/en-us/library/dd547175.aspx

A: Changing the following helped me:
Configuration Properties -> General -> Platform Toolset

Change was from v120_xp  to v120


text:
Q: Is it possible to save Firebase topic notification save in sqlite when app is close in android when i sent Firebase Topic notification, onMessageReceived method is not fire when application is in

*

*Background and screen lock

*Application is close from recent application

in above two case i got notification only in system tray, i want to handle it programmatically in store in sqlite
same question i think
and its work in case application in foreground and background while listed in recent applications
So how i get thats notification , i want store notification in sqlite
my postman request is below
    {
  "to": "/topics/181_Red_Route",
  "data": {
    "sound": "default",
    "badge": "1",
    "title": "Title1",
    "body": "Desc1"
  },
  "notification": {
    "sound": "default",
    "badge": "1",
    "title": "Title1",
    "body": "Desc1"
  },
  "priority": "high",
  "content_available": true
}

thanks in advance

A: If you send a notification tag inside the FCM message, it will not trigger the onMessageReceived code when the app is in background.
Instead, always send the notification with data tag. This will ensure that all the FCM messages trigger the onMessageReceived call. In this call, you can save the message inside a db as per usual android methods.
Summary: Only send the data tag and no notification tag. Handle showing and saving the notification inside onMessageReceived(). Works whether the app is in foreground or background or killed.
Warning: If you are planning an IOS launch, FCM message with data tag will only get delivered if the app is in foreground or backgrounded but not killed yet. Until then no messages will be received.

A: https://firebase.google.com/docs/cloud-messaging/android/send-multiple
Check this link it is mentioned that , there are two ways so send message payload.
1) As Notification
2) As Data
If server send "Data" payload, then it will receive in the application onMessageReceived() method. And you can manage it in onMessageReceived() by checking the payload as given below.
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
    Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}

// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
    Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}

& Also check how to do server code, passing 'notification' / 'data'.
https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages


text:
Q: Ego Network using Gremlin I'm new to gremlin and have been working on creating an ego network using Gremlin.
Ego-alter connections are pretty easy to find, but the problem lies in finding alter-alter connections.
Is there a way to write a query which extracts all the alter-alter connections along with ego-alter connections in a n-radius ego network ?

For example in the Graph of the gods. 1-Radius ego network for 'jupiter' has ego-alter connections as 'Jupiter-neptune', 'Jupiter-pluto'. While the alter-alter connection is 'Neptune-Pluto'. How do I retrieve these connections.
Thanks in advance.

A: This is my attempt for finding the 'alter-alter' connections
g.V().has('name', 'jupiter').as('ego').repeat(out()).times(1).emit()
.dedup().aggregate('alter')
.as('from').out()
.where(within('alter'))
.as('to').select('from', 'to').by('name').dedup()

The number inside the times step is your redius.
In addition I created the graph in gremlify, so you can play with this query:
https://gremlify.com/1p


text:
Q: Setting the window's position in ICommands not working I have a simple WPF Application that has a menu on top. I am trying to bind a shortcut to one of the menu items, but I cannot figure this out. Please mind that I am doing this as a hobby and quite new to this.
MainWindow.xaml
<Window.InputBindings>
    <KeyBinding Gesture="Ctrl+R" Command="{Binding RepositionWindowCommand}" />
</Window.InputBindings>

<MenuItem Header="_Options">
    <MenuItem x:Name="Menu_RepositionWindow" Header="_Reposition Window" Command="{Binding RepositionWindowCommand}" InputGestureText="Ctrl+R" />
</MenuItem>

MainMenu.cs
namespace WPF_Practice
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new PracticeDataContext();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RepositionWindow();
        }

        public void RepositionWindow()
        {
            Left = SystemParameters.PrimaryScreenWidth - Width;
            Top = 0;
        }
    }

    public class PracticeDataContext
    {
        public ICommand RepositionWindowCommand { get; } = new RepositionWindowCommand();
    }

    public class RepositionWindowCommand : ICommand
    {
        public void Execute(object parameter)
        {
            var RepositionWindowClass = new MainWindow();
            RepositionWindowClass.RepositionWindow();
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged { add { } remove { } }
    }
}

The goal here is to move the main window to top right corner whenever I click the menu item, or use the shortcut key of Ctrl+R. I also tried to put Top, Left, and Width in ICommand just in case like below to this if it solves the problem.
    public class RepositionWindowCommand : ICommand
    {
        public void Execute(object parameter)
        {
            Left = SystemParameters.PrimaryScreenWidth - Width;
            Top = 0;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged { add { } remove { } }
    }

It does not recognize Left, Top, and Width when they are in ICommand. It says "The name does not exist in current context."
What am I missing here? How do I achieve this goal?

A: Definitely, you don't need to create RepositionWindowClass inside RepositionWindowCommand. To access a Window instance inside command you should pass it as parameter to command using CommandParameter binding. You also should properly implement CanExecuteChanged event
    public class RepositionWindowCommand : ICommand
    {
        public void Execute(object parameter)
        {
            if (parameter is Window window)
            {
                 window.Left = SystemParameters.PrimaryScreenWidth - window.Width;
                 window.Top = 0;
            }
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }

Xaml usage
<MenuItem x:Name="Menu_RepositionWindow" Header="_Reposition Window" Command="{Binding RepositionWindowCommand}" InputGestureText="Ctrl+R" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>


text:
Q: TCPDF - How can I show a div with absolute position in a pdf created with tcpdf? I have following tcpdf code:
    <?php
    require_once('config/lang/eng.php');
    require_once('tcpdf.php');

    // Extend the TCPDF class to create custom Header and Footer
    class MYPDF extends TCPDF {

      //Page header
      public function Header() {
      }

      // Page footer
      public function Footer() {
      }
    }

    // create new PDF document
    $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Stimart');
    $pdf->SetTitle('test');
    $pdf->SetSubject('test');
    $pdf->SetKeywords('test');

    // set default header data
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);

    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    //set margins
    $pdf->SetMargins(40, 40, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    //set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    //set some language-dependent strings
    $pdf->setLanguageArray($l);

    // ---------------------------------------------------------

    // set font
    $pdf->SetFont('times', '', 12);

    // add a page
    $pdf->AddPage();

    // set some text to print
    $html = '
Hi, I am an ABSOLUTE div.
';

    $pdf->writeHTML($html, true, false, false, false, '');
    // ---------------------------------------------------------
    $pdf->lastPage();
    //Close and output PDF document
    $pdf->Output('test.pdf', 'I');

    //============================================================+
    // END OF FILE
    //============================================================+

after the line "// set some text to print" I set up the html code to show but it doesn't works as expected.
In this case I need to pass a div with absolute position but when the code runs it creates the pdf page showing the div in relative position.
How can I solve this annoying problem??

A: TCPDF has a very limited CSS support. It doesn't support all attributes.
Currently, only the following CSS attributes are supported:

*

*font-family

*font-size

*font-weight

*font-style

*color

*background-color

*text-decoration

*width

*height

*text-align

So try removing the other attributes, and tell if it works.