text:
Q: What is the difference between an ORM and an ODM? I am trying to figure out what the difference is between ORM and ODM, as far as I understand the concept, ORM (Object Relational Mapper) maps the relations between data, where as ODM (Object Document Mapper) deals with documents. Am I right in assuming that mySQL is an example of ORM and MongoDB is a example of ODM?
As I am sure you can see, I am not too familiar with the theory of the concept. Could someone please clarify the differences between the two?

A: Mongoose is a good example for ODM(Object Data Model) for MongoDB in which you can directly perform operations with objects and that gets translated into the appropriate query and schema.
It can be found Here at https://mongoosejs.com/

A: An ORM maps between an Object Model and a Relational Database. An ODM maps between an Object Model and a Document Database. MySQL is not an ORM, it's a Relational Database, more specifically, a SQL Database. MongoDB is not an ODM, it's a Document Database.

A: MySQL is an example of a relational database - you would use an ORM to translate between your objects in code and the relational representation of the data.
Examples of ORMs are nHibernate, Entity Framework, Dapper and more...
MongoDB is an example of a document database  - you would use an ODM to translate between your objects in code and the document representation of the data (if needed).
Mandango is an example of an ODM for MongoDB.

A: Essencially, an ORM use a SQL database Driver like ODBC, JDBC or OLEDB to translate the object notation to relational notation and an ODM use a JSON or JSONB api to translate the Object notation to Document notation.
There are different kind of implementations under the hood.
PS: JSONB is a JSON text document notation stored in a binary format as used by MongoDB.

A: To understand the difference between an ORM and an ODM, I think that it would be helpful to first review the differences between a relational database, and a document database. I'll do so in a hand-wavy way.
A relational database is the one that you're probably used to. The one that stores data in tables, like this:

Common examples of relational databases are MySQL, Postgres, and SQLite. To query a relational database, you'd use SQL.
What about document databases? Well, with document databases, data is stored in JSON instead of in tables.

Actually, that's not 100% accurate. MongoDB explains:

Documents store data in field-value pairs. The values can be a variety of types and structures, including strings, numbers, dates, arrays, or objects. Documents can be stored in formats like JSON, BSON, and XML.

Ok, so now, what is an ORM, what is an ODM, and how do they compare?
Well, ORM stands for... actually, I'll let this answer explain:

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM".

Basically, in your application code, you are usually dealing with objects. But in your database, you have tables. An ORM is a library that maps between the two. As Wikipedia explains:

This creates, in effect, a "virtual object database" that can be used from within the programming language.

Here is an example. Active Record is a popular ORM for Ruby on Rails. With Active Record, you could do something like User.find_by(name: 'David') and get back something like { id: 1, name: 'David' }. So the ORM is doing the following mapping for you:

And then with an ODM, it's basically doing the same thing, except for document databases. It's mapping from the objects in your application code to the documents in the database. Mongoose is a good example of an ODM. It works with MongoDB.

A: Mongoose is an example for ODM which maps between object models and MongoDB. Mongoose provides a lot of functions for querying and editing documents in a collection on the model class, as well as a rich query class to make manual queries.
Sequelize is a modern example for ORM which maps between object models and an SQL DB. Sequelize works with many Relational Databases such as Postgres, MariaDB, SQLite, MySQL, Oracle and SQL Server. Sequelize has a very similar interface to Mongoose, where you start by defining tables (instead of collections) as models in TypeScript.


text:
Q: PHP: Whois via AJAX I am extremely bad at AJAX (actually, I just started to learn it).
So, I write whois service on PHP and I want to make it to output the result via AJAX-request.
All I have at the moment is:
my PHP code:
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:application/json");
$res = $whois->getWhois($domain); // Calls the Whois-query function;

echo json_encode($res);

my JS code:
$('#submit').on('click', function() {
    e.preventDefault();
    var domain = $('#value').val();
});

$.ajax({
    url: 'ajax/whois.php',
    type: "post",
    data: {'domain': domain, 'action': 'whois'},
    dataType: "json",
    success: function(json) {
        $('#whoisResult').html('
Whois Query result for ' + domain + '
');
        $('#whoisContent').html(json.html);
    },

    error: function(xhr, status) {
        $('#whoisResult').html('
Sorry, an error occured. Try again later, please!
')
    }
});

As HTML I have an input: <input type="text" id="value"> and the submit button.
I searched for the script examples and tried to make something similar, but it does not work at all...
P.S. Guess you won't hit this question a negative rating :)
P.P.S: As requested, this is my response from PHP:
{"domain":"exp.cm","whois":"[Domain]\nDomain: exp.cm\nStatus: active\nChanged: 2014-02-25T12:22:00.957819+02:00\n\n[Holder]\nType: Legal person\nName: Name, Surname\nEmail: email@example.com\nPhone: Phone here\nAddress: Address goes here\nSome other info\n\nUpdated: 2014-03-18T18:12:35.717462+00:00\n"}

A: In this case you don't need the JSON datatype, just return html.
Additionally, you'll want the ajax request to be inside the click event. In your click event, you also forgot to pass the e parameter.
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:text/html");
$res = $whois->getWhois($domain); // Calls the Whois-query function;

echo $res;

js:
$('#submit').on('click', function(e) {
    e.preventDefault();
    var domain = $('#value').val();

    $.ajax({
        url: 'ajax/whois.php',
        type: "post",
        data: {'domain': domain, 'action': 'whois'},
        //dataType: "json",
        success: function(html) {
            $('#whoisResult').html('
Whois Query result for ' + domain + '
');
            $('#whoisContent').html(html);
        },

        error: function(xhr, status) {
            $('#whoisResult').html('
Sorry, an error occured. Try again later, please!
')
        }
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell StreamReader - how to wait for a new file to be readable My script generally assumes the existence of a *.txt file with settings to help it function better. However, if the script doesn't exist, it creates a local file to hold these settings. I realise there's no logical need to then read this file, but I'd like to understand why I can't.
[void][System.IO.File]::Create($PSFileName)
$ReadPS = New-Object System.IO.StreamReader($PSFileName)

Immediately after the script may (rarely) create the file, it attempts to read it, which generates the following error: New-Object : Exception calling ".ctor" with "1" argument(s): "The process cannot access the file 'C:\Temp\MyFile.txt' because it is being used by another process."
So I have to wait for the file to be available, right? Yet a simple start-sleep for 5s doesn't work. But if I wrap it in a loop with a try-catch, it works within a fraction of a second every time:
[void][System.IO.File]::Create($PSFileName)
$RCount = 0                                                             # if new file created, sometimes it takes a while for the lock to be released.
Do{
    try{
        $ReadPS = New-Object System.IO.StreamReader($PSFileName)
        $RCount+=100
    }catch{                                                             # if error encountered whilst setting up StreamReader, try again up to 100 times.
        $RCount++
        Start-Sleep -Milliseconds 1                                     # Wait long enough for the process to complete. 50ms seems to be the sweet spot for fewest loops at fastest performance
    }
}Until($RCount -ge 100)
$ReadPS.Close()
$ReadPS.Dispose()

This is overly convoluted. Why does the file stay locked for an arbitrary length of time that seems to increase the more I wait for it? Is there anything I can adjust or add between the file creation and the StreamReader to ensure the file is available?

A: As it was already mentioned in the comments, the method you are using does create a lock on the file, which stays until you call the close / dispose method or the powershell session end.
That's why the more you wait for it, the longer your session stays open and the longer the lock on the file is maintained.
I'd recommend you to just use New-Item instead which is the Powershell native way to do it.
Since you are creating a StreamReader object though, don't forget to close / dispose the object once you are over.
New-Item -Path $PSFileName -ItemType File
$ReadPS = New-Object System.IO.StreamReader($PSFileName)

#Stuff

$ReadPS.Close()
$ReadPS.Dispose()

Finally, if for some reason you still wanted to use [System.IO.File]::Create($PSFileName), you will also need to call the close method to free the lock.

A: You have simply to close the file handle. Try:
$fh = [System.IO.File]::Create($PSFileName)
[void]$fh.Close()
[void]$fh.Dispose()
$ReadPS = New-Object System.IO.StreamReader($PSFileName)

A: The Create method returns a FileStream object.  Since StreamReader is derived from Stream, My Solution was to recast as astream reader.  Almost a one-liner...:
$PSFileName = 'c:\temp\testfile.txt'
$Stream = [System.IO.StreamReader][System.IO.File]::Create($PSFileName)

OR, Suggestion From Jeroen Mostert :
$PSFileName = 'c:\temp\testfile.txt'
$Stream = [System.IO.StreamReader]::New( [System.IO.File]::Create($PSFileName) )

You don't have to worry about Garbage Collection with this approach because the resulting object is referenced to the variable...
Honestly I'm not too sure about this, I believe the FileStream object can be leveraged directly to read & write, but I'm less familiar than I am with StreamReader & Writer objects, so if it were me I'd do the re-cast so I can move on, but research further later.
Also, if you use another approach I would use .CLose() instead of .Dispose().  My understanding based on the .Net documentation is close is more thorough, and calls Dispose internally anyhow...


text:
Q: When to use "find" & when to use "look for"?
find [transitive] to get back something/somebody that was lost after searching for it/them
find something for somebody Can you find my bag for me?
find somebody something Can you find me my bag?
find somebody/something I wanted to talk to him but he was nowhere to
  be found.
find somebody/something + adj. The child was found safe and well.

look [intransitive] to try to find somebody/something
I can't find my book—I've looked everywhere.
look for somebody/something Where have you been? We've been looking
  for you.
Are you still looking for a job?
We're looking for someone with experience for this post.

Generally, we know that "look for" means "try to find" and "find" means "successfully get something after searching for it"
My question is that
When to use "find" & when to use "look for"?
For examples:
could you go find Tommy?
could you go look for Tommy?
I want to find a good stone
I want to look for a good stone (does it sound strange?)
But seem we don't use "find" with continuous tenses
"I am finding my book" sounds strange
But "I am looking for my book" sounds ok.

A: There's little difference between the activity of searching for some missing object (find) and trying to locate that missing object (search for), so, as you note both imperative forms are fine:
[1a] Find Tommy.
[1b] Search for Tommy.
The same goes for the infinitive:
[2a] It takes time to look for a good stone.
[2b] It takes time to find a good stone.
Presumably you're looking for the right diamond for your fiancee's engagement ring.
The same also goes for the gerund:
[3a] Looking for a good stone takes a lot of time.
[3b] Finding a good stone takes a lot of time.
But while you're looking for a specific object like your book, you aren't finding it. In fact, you may never find it. After you've found your book, you stop looking. So in these cases there isn't much opportunity for the progressive form of the verb to indicate a continuing activity, which is why
[4a] I am looking for my book.
sounds OK, but
[4b] I am finding my book.
doesn't.
But there's another connotation to the word find, and that's discovery. This can well be an ongoing process, and one suitable for the progressive form of the verb. Here's an example from Successful Single-Sex Classrooms (2010) by M Gurian, K Stevens, and P Daniels:

[5] I am finding that writing tends to be a chore for the boys.

This is particularly prevalent in touchy-feely self-help books in the locution "to find oneself," meaning to come to self-awareness. For example from Finding the Deep River Within (2007) by A Seixas:

[6]  It feels as if I am finding myself again, coming home to myself.


text:
Q: how display button for special users django How can display button example ' download file.pdf ' for special users in django.

*

*Django version 2, 1, 0

*Python version 3.7.0

A: You can do this in the template to show a button, in this case just for the superusers:
{% if request.user.is_superuser %}

{% else %}
    ...
{% endif %}

If you want to show this to specific user names or to user groups you need to adapt change the if clause.


text:
Q: Interactive ZoomGraph in R Shiny Is it possible to create interactive Shiny graph that when you click zoom button on a Shiny Page, the graph will expand to the entire size of the browser window? Right now I have four ggplots on one shiny page and would like to expand one to full screen size when I click zoom. I think it could be using either shinyjs or conditional panels, but can't seem to figure it out. This has similar logic:https://gallery.shinyapps.io/105-plot-interaction-zoom/, instead of zooming in the graphic, would just like to zoom the entire graphic to the browser.
Thanks!

A: My solution was much easier actually and I ended up using Shiny BS that has a built in modal function.


text:
Q: How to setup a dynamic sender address for a catchall mail address with Dovecot and Postfix? Sometimes I need to send a mail via a sender address which would normally received by a catchall mail address. But the normal method to manipulate the returnmail isn't a nice solution. So I use a "working" scenario with i-MSCP + RoundCube:

*

*fixed mailboxes and one catchall

*If I need to send via a dynamic mail address (will be catched by catchall), I register a mailbox (temporary for this one mail or mailbox+forward) and uses the new credential with RoundCube.

But now I've a minimal server without a management software. I configured postfix with fixed mailboxes and one catchall (regex based + blacklist). Also dovecot works with IMAP and the catchall credential. Beside I can't send a mail via a mail client at the moment (authentification problems), I want a much easier way to send a mail from any address. I don't want register something, just use <dynamic name>@domain.tld and a global password.
My postfix/dovecot:

*

*multiple domains

*no database, only hash and regex files

*maildir (near standard)

*no virtual users (catchall has his own unix user)

*no transport manipulation

What is postfix secret weapon to achieve this send scenario?
my main.cf (login via smtp doesn't work yet, general send and imap are working:
myhostname = domain.tld
smtpd_banner = $myhostname ESMTP $mail_name
biff = no
append_dot_mydomain = no
delay_warning_time = 4h
readme_directory = no

smtpd_tls_cert_file=/etc/letsencrypt/live/domain.tld/cert.pem
smtpd_tls_key_file=/etc/letsencrypt/live/domain.tld/privkey.pem
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_tls_security_level = may
smtpd_tls_auth_only = no
smtpd_tls_received_header = yes
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3
smtpd_tls_protocols = !SSLv2, !SSLv3

smtp_tls_mandatory_protocols = !SSLv2, !SSLv3
smtp_tls_protocols = !SSLv2, !SSLv3

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination

alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = $myhostname, domain.tld, localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
mynetworks_style = host
home_mailbox = Maildir/
virtual_alias_maps = hash:/etc/postfix/virtual, regexp:/etc/postfix/regexp_virtual

smtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/recipient_access, permit_mynetworks, reject_unauth_destination

smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

A: While some mail provider actually enforce the sender address belongs to the authenticated account, this is not generally valid, especially not for the default configuration of Postfix. Actually, it is rather common to use some mail provider as mail relay when hosting servers behind home uplinks with dynamic IP addresses (which are blocked by most black lists because lots of spam is sent from those addresses). I'd guess most don't even enforce the sender domain.
You should be able to authenticate with your catch-all-account's mail address, but configure the account with another sender address. Thunderbird for example also allows to provide multiple identities per SMTP account, which is available for exactly this purpose.


text:
Q: Excel VBA Copy-paste-move I am only new to VBA coding so I don't have much of a clue of what I am doing unfortunately. I was hoping that I could get a hand here.
What I want to do is.
Step One: Copy a line (which has formulas) and paste it in the same position but as values only.
Step Two: Move a selection of cells down one line.
Step Three: Copy a line (with formulas) and past it on another line with the formulas.
This is all done on the same sheet.
If I could get some help with this or some direction to some tutorials that would be really appreciated.

A: Normally I wouldn't do this without your showing some effort, but why not?  The below are about as simple as I can get.  Please still though, use the macro recorder to see how this all works. It's how a lot of us get started.
Sub StepOne()
Dim myRow As Long
myRow = 1 ' We will "copy/paste" on Row 1
' To avoid using the clipboard, you can simply set two ranges' values equal. This will
' clear out any formulas and leave the values.
Rows(myRow).Value = Rows(myRow).Value
End Sub

And the second:
Sub StepTwo()
Dim rng As Range
'Change this as required. Note the use of `Set` with a `Range` type.
Set rng = Range("A1:A10")
rng.Cut rng.Offset(1, 0)
End Sub

And the last one:
Sub StepThree()
' Not tellin :P!  You should be able to get this. Hint: look at StepOne.
End Sub

Edit: Ah, I realize now that Step Three is a little more involved than setting two ranges equal since you want to maintain the formula. However, I'll leave this as a learning opportunity for you to investigate.  If you can't figure it out, let me know and I can guide you. :D


text:
Q: Locating GSM Cell information for any android device Using AT Commands I would like to retrieve  Network information from any Android device.
I know i could use it as a modem (when connected to a PC) and then call AT+KCELL which is exactly what i need - yet i have no idea how to do this while a user isn't operating (IE the device is on but not in any use like telephoning or browsing)
the device.
Is this at all possible, the aim is to triangulate my location.
Thanks
Aiden
EDIT
<scan time="20120729232941" distance="50.175018457421366" >
    <gps time="20120729232922" lng="34.9510156" lat="50.49416856" alt="137.60000610351563"         hdg="308.5" spe="16.25" accuracy="4.2426405" />
    <gsmserving mcc="255" mnc="03" lac="53100" id="8512" ss="-93" act="EDGE" rxlev="10" />
    <gsmneighbour mcc="255" mnc="03" lac="53100" id="513" psc="-1" rxlev="16" act="EDGE" />
    <gsmneighbour mcc="255" mnc="03" lac="53100" id="122" psc="-1" rxlev="14" act="EDGE" />
    <gsmneighbour mcc="255" mnc="03" lac="53100" id="121" psc="-1" rxlev="17" act="EDGE" />
    <gsmneighbour mcc="255" mnc="03" lac="53100" id="8513" psc="-1" rxlev="10" act="EDGE" />
</scan>

So that i can extract signal strenth and neighboring towers/cells.
An application on the Market/Play Store which found a way to do this is "Open Signal"
EDIT
I found a simmilar query here: How to properly triangulate GSM cell towers to get a location?
EDIT
Finally i got somewhere
Dialling: *#197328640# from my Galaxy SII, under Debug Screen I get all the info i want.
Is there some way to do this programmatically
The GT-I9100 Baseband Processor (BP/CP) Specifications: http://forum.xda-developers.com/showthread.php?t=1471241

A: I would not post you full code, but i think you can find what you need in this sample project http://api.yandex.ru/locator/doc/dg/samples/android_sample.zip . Check WifiAndCellCollector.java class, collectCellInfo() method. I think you could find lots of useful things there. Good luck!

A: Device manufacture (i mean mobile manufacturer )should give interface and support for AT commands to give response.(from PC serial communication)


text:
Q: Remove everything between pairs of braces with sed I've got a string that looks like this:
[%{%B%F{blue}%}master %{%F{red}%}*%{%f%k%b%}%{%f%k%b%K{black}%B%F{green}%}]

I want to remove the substrings matching %{...}, which may or may not contain further substrings of the same order.
I should get: [master *] as the final output. My progress so far:
gsed -E 's/%\{[^\}]*\}//g'

which gives:
echo '[%{%B%F{blue}%}master %{%F{red}%}*%{%f%k%b%}%{%f%k%b%K{black}%B%F{green}%}]' | gsed -E 's/%\{[^\}]*\}//g'
[%}master %}*%B%F{green}%}]

So, this works fine for %{...} sections which do not contain %{...}. It fails for strings like %{%B%F{blue}%} (it returns %}).
What I want to do is parse the string until I find the matching }, then remove everything up to that point, rather than removing everything between %{ and the first } I encounter. I'm not sure how to do this.
I'm fully aware that there are probably multiple ways to do this; I'd prefer an answer regarding the way specified in the question if it is possible, but any ideas are more than welcome.

A: This might work for you:
echo '[%{%B%F{blue}%}master %{%F{red}%}*%{%f%k%b%}%{%f%k%b%K{black}%B%F{green}%}]' |
sed 's/%{/{/g;:a;s/{[^{}]*}//g;ta'
[master *]

A: Use recursion to eat it out from the inside out.
s/%{.*?%}//g

Then wrap in
while(there's at least one more brace)

(probably while $? -ne 0 ...  whatever rcode sed uses to say "no matches!")

A: Try this:
sed -E 's/%{([^{}]*({[^}]*})*[^{}]*)*}//g'


text:
Q: Vba add hyperlink to a picture I have a code to add hundreds of pictures from weblinks to a sheet. It works perfectly! Now I need to modify it to add a hyperlink to each picture and I cannot get it to work. Any help is appreciated! The hyperlink is the same link that contains the picture, in this script is the variable Filename. The idea is to open the picture in a larger size if the user clicks on it.
Line_dest = n - 1
Filename = Sheets("LISTOFLINKS").Cells(n, 15).Value
Rows(Line_dest).RowHeight = 100
ActiveSheet.Pictures.Insert(Filename).Select
Set shp = Selection.ShapeRange.Item(1)
With shp
     .LockAspectRatio = msoTrue
     .Width = 180
     If .Height > 95 Then .Height = 95
     .Cut
End With
Selection.Hyperlinks.Add
Anchor:=Selection.ShapeRange.Item(1), _
Address:=Filename

Thanks

A: It should be
ActiveSheet.Hyperlinks.Add _
Anchor:=shp, _
Address:=Filename

and you should remove the .Cut. This cuts the image (like ctrl + x)  and if it is removed you can not add a link to it. Alternatively you can add the hyperlink before you cut it:
ActiveSheet.Pictures.Insert(Filename).Select
Set shp = Selection.ShapeRange.Item(1)
ActiveSheet.Hyperlinks.Add Anchor:=shp, Address:=Filename
With shp
     .LockAspectRatio = msoTrue
     .Width = 180
     If .Height > 95 Then .Height = 95
     '.Cut 'removed that I guess you don't want the image to be cut
End With


text:
Q: Creating a custom button in android in the xml layout I am trying to change the style of android default buttons. I have created an xml file in the drawable folder in res folder called custom_button.xml and have referenced it in the xml layout file, however when I run the application, the button style has not changed and instead I have lost the outline of the original button.
custom_button.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    <solid
        android:color="#FF0000" />
</shape>

main.xml
 <TextView
        android:id="@+id/textView1"
        android:layout_width="85dp"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="#6600ff"
        android:text="" />

    <Button
        android:id="@+id/button_getDraw"
        style="?android:attr/buttonStyleSmall"
        android:background="@drawable/custom_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_getDraw"
        android:onClick="getLotteryDrawFromWebsite" />

    <Button
        android:id="@+id/check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_check"
        android:onClick="checkNumbers"
        android:enabled="false" />

Whats the problem? Thx in advance..

A: Change your custom_button xml to this .
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<solid android:color="#FF0000"/>

A: Try using this link....
also you set button selection effect.


text:
Q: Geogebra: Transformation of an image - translation matrix does NOT work ( rotation & scaling works fine ) I have created three 3x3 transformation matrices in Geogebra:
$$S=\begin{bmatrix}
sx&0&0\\
0&sy&0\\
0&0&1
\end{bmatrix}$$
$$R=\begin{bmatrix}
cos(\alpha)&sin(\alpha)&0\\
-sin(\alpha)&cos(\alpha)&0\\
0&0&1
\end{bmatrix}$$
$$T=\begin{bmatrix}
1&0&0\\
0&1&0\\
x&y&1
\end{bmatrix}$$
When I use the ApplyMatrix(S, pic1) command, the pic1 image scales as the sx and sy are varied, as expected.
When I use the ApplyMatrix(R, pic1) command, the pic1 image rotates as the $\alpha$ is varied, as expected.
When I use the ApplyMatrix(T, pic1) command, the pic1 DOES NOT translate as the x and y are varied.
I think this is because pic1 is processed as a list of {x,y} vectors and it needs to be processed as a list of {x,y,1} vectors.
Q: How to get the translation matrix T to work properly with an image ?
P.S.
I need this 3x3 matrix in order to simulate the PDF matrix transformations described here in Section 4.2.3 on Page 208.

A: The correct form of $T$ is as follows
$ T = \begin{bmatrix} 1 && 0 && x \\ 0 && 1 && y \\ 0 && 0 && 1 \end{bmatrix}$


text:
Q: Python array segmented in ranges I have the following array [1, 4, 7, 9, 2, 10, 5, 8] and I need to separate the array in 3 different arrays: one for values between 0 and 3, anther for 3 to 6 and anther for 6 and 25.The result must be something like that:
array1 = [1, 2]
array2 = [4, 5]
array3 = [7, 9, 10, 8]

Any idea about how to do it simple?

A: You can do that in a very simple way using a combination of a for loop and range functions:
lists = ([], [], [])

for element in [1, 4, 7, 9, 2, 10, 5, 8]:
    if element in range(0, 3):
        lists[0].append(element)

    elif element in range(3, 6):
        lists[1].append(element)

    elif element in range(6, 25):
        lists[2].append(element)

array1, array2, array3 = lists

A: *

*First, define your "pole" numbers

*Second, generate your intervals from those "pole" numbers

*Third, define as many lists as there are intervals.

*Then for each interval, scan the list and appends items in the relevant list if they belong to the interval

code:
source = [1, 4, 7, 9, 2, 10, 5, 8]

poles = (0,3,6,25)
intervals = [(poles[i],poles[i+1]) for i in range(len(poles)-1)]

# will generate: intervals = [(0,3),(3,6),(6,25)]

output = [list() for _ in range(len(intervals))]

for out,(start,stop) in zip(output,intervals):
    for s in source:
        if start <= s <stop:
            out.append(s)

print(output)

result:
[[1, 2], [4, 5], [7, 9, 10, 8]]

This solution has the advantage of being adaptable to more than 3 lists/intervals by adding more "pole" numbers.
EDIT: There's a nice & fast solution (O(log(N)*N)) if the output lists order don't matter:

*

*first sort the input list

*then generate the sliced sub-lists using bisect which returns insertion position of the provided numbers (left & right)

like this:
import bisect

source = sorted([1, 4, 7, 9, 2, 10, 5, 8])

poles = (0,3,6,25)

output = [source[bisect.bisect_left(source,poles[i]):bisect.bisect_right(source,poles[i+1])] for i in range(len(poles)-1)]

print(output)

result:
[[1, 2], [4, 5], [7, 8, 9, 10]]

A: "One-line" solution using set.intersection(*others) and range(start, stop[, step]) functions:
l = [1, 4, 7, 9, 2, 10, 5, 8]
l1, l2, l3 = (list(set(l).intersection(range(3))), list(set(l).intersection(range(3,6))), list(set(l).intersection(range(6,25))))

print(l1)
print(l2)
print(l3)

The output:
[1, 2]
[4, 5]
[8, 9, 10, 7]

https://docs.python.org/3/library/stdtypes.html?highlight=intersection#set.intersection


text:
Q: Using EncryptSymmetric in Web Analytics Connector I'm looking for a solution to pass SFMC SubscriberKey value to external application. I'm thinking about encoding it with DES Encryption and using Web Analytics Connector to append all links with it. It's something similar to:
par1=%%=URLEncode(EncryptSymmetric('Value', 'des;mode=ecb;padding=zeros', 'KEYID', @null ,@null, @null, @null, @null), 1, 1)=%%

Will it degrade overall send time performance significantly? If yes, are there any other ways to pass this value securely without exposing it in the URL and making it readable on external website?


text:
Q: Displaying a different view when user is logged in swift not working I am developing an app in Swift3, and using Parse.
For my start screen, I have a Sign In page. However, I want it to automatically go to the Home screen if the user is Logged In.
override func viewDidLoad() {
    super.viewDidLoad()

    if PFUser.current() != nil {
        print((PFUser.current()?.username)!)
        self.performSegue(withIdentifier: "ShowHomePage", sender: self)
    }
    else {
        print("No User Logged in")
    }

That's my code on the SignIn page. Im getting the print message showing me that a user is Logged In, however, it's not actually going to a different view.
Any help would be much appreciated.


text:
Q: How to check that mockito has mock the function and return as mentioned in when.ThenReturn Mockito - when→thenReturn is not working as expected. Same is working in the same UnitTest class. I have other function which I tested the same way is working as expected.
Following is my test method
@Test
public void testAlerts_whenReturnsData() {
//Assemble
Product product = new Product(null, null, 0, "-1");

when(api.alerts("-1", null, null))
    .thenReturn(Single.just(product));

//Act
viewModel.getAlertsData().observeForever(dataObserver);
viewModel.getIsPhoneLoadingData().observeForever(loadingObserver);

viewModel.getAlerts("1234567890");

//Verify
verify(loadingObserver).onChanged(true);
verify(dataObserver).onChanged(product);
verify(loadingObserver).onChanged(false);
}

My actual getAlerts() method in Class:
void getAlerts(String phone) {
  isPhoneLoadingData.setValue(true);

  alertDisposable =
      api.alerts(id,
              userManager.getNonNullUserId(), AlertsRequest.create(phone, true))
          .doOnEvent((product, throwable) -> isPhoneLoadingData.postValue(false))
          .compose(RxSingleSchedulers.DEFAULT.applySchedulers())
          .subscribe(alertsData::setValue, errorData::setValue);
}

Exception: Seems like it's not able to mock api.alerts(String, String, AlertRequest)
Tried with
when(api.alerts(any(String.class), any(String.class), any(AlertsRequest.class)))
    .thenReturn(Single.just(product));

//Api->alerts
public interface Api {
  Single<Product> alerts(
   String Id,
   String customerId,
   AlertsRequest request
  );
}

java.lang.NullPointerException at .doOnEvent - api.alerts() in getAlerts
How to check whether mockito is able to mock the function and will return as defined in when.thenReturn

A: I can think of these possible causes:

*

*Have you double-checked all other possible reasons for the NullPointerException?
(uninitialized api, userManager, isPhoneLoadingData etc.)

*A null argument does not match any(String.class).

*If there are multiple alert methods with the same parameter count, passing null can make it ambiguous. In this case, you need to cast your null arguments, e.g. (String) null.

With JUnit 5, Mockito can detect

*

*method invocations that don't match the mock configuration,

*mock configurations that are not hit by any invocations.

when you use the org.mockito.junit.jupiter.MockitoExtension.

A: Ahh! AlertsRequest.create(phone, true) was the culprit. Was stuck in the same scenario; with a clear mind & another day, you can see your problem with much different angle.
I was mocking
when(api.alerts("-1", null, null))
.thenReturn(Single.just(product));

where
// here AlertsRequest.create(phone, true) mocking as null.
// But when actual call is made it creates a Object of AlertsRequest with phone as null & another parameter as true
// that's the reason mocking was creating for api.alerts("-1", null, null)
// here is it was api.alerts("-1", null, AlertsRequest(null, true))

api.alerts(id, userManager.getNonNullUserId(), AlertsRequest.create(phone, true))

 void getAlerts(AlertsRequest request) {
  isPhoneLoadingData.setValue(true);

  alertDisposable =
        api.alerts(id,
          userManager.getNonNullUserId(), request)
          .doOnEvent((product, throwable) -> isPhoneLoadingData.postValue(false))
          .compose(RxSingleSchedulers.DEFAULT.applySchedulers())
          .subscribe(alertsData::setValue, errorData::setValue);
  }

Test Passed!


text:
Q: Efficiently check if all the values of columns are null (or equivalent) I have a dataframe (1910 columns) which in some columns contains only null (or equivalent) values. I want to have a list of all those columns whose null count value is = 3103276687 (equal to row count).
As the number of rows and columns is huge, I need a highly optimized query. Otherwise my Databricks notebook runs for hours at stretch and sometimes doesn't generate results.
I want the list of columns where all the rows are null, so that I could drop them.
P.S: don't give answers using collect(), it's an expensive function.
My code:
from pyspark.sql.functions import col, isnan, when, count

df_5 = df_2.select([count(when(col(c).contains('None') | \
                               col(c).contains('NULL') | \
                               (col(c) == '' ) | \
                               col(c).isNull() | \
                               isnan(c), c
                          )).alias(c)
                    for c in acceptedColumns ])

nullColumns = []

totalcount = df_2.count()

for col in accpetedColumns:
    if(df_5.select(col).collect()[0][0] == totalcount):
        nullColumns.append(col)

print(nullColumns)

A: It could be that any would perform better than count. However, any is not available in Python API, so expr is needed.
from pyspark.sql.functions import expr

df_5 = df_2.select(
    [expr(
        f"""
        !any(
            case when {c} is null or
                      {c} = 'NULL' or
                      {c} = 'None' or
                      {c} = '' or
                      isnan({c})
                 then true
                 else false
            end
        ) as {c}
        """)
     for c in acceptedColumns]
)
df_6 = df_2.select([c for c in acceptedColumns if df_5.head()[c]])

df_6 is already filtered - it does not have columns containing only null values.
BTW, you have a typo in accpetedColumns. In this code, I have changed it to acceptedColumns.


text:
Q: Python slice how-to, I know the Python slice but how can I use built-in slice object for it? What's the use of built-in function slice and how can I use it?
The direct way of Pythonic slicing I know - l1[start:stop:step]. I want to know if I have a slice object, then how do I use it?

A: >>> class sl:
...  def __getitem__(self, *keys): print keys
...
>>> s = sl()
>>> s[1:3:5]
(slice(1, 3, 5),)
>>> s[1:2:3, 1, 4:5]
((slice(1, 2, 3), 1, slice(4, 5, None)),)
>>>

A: Square brackets following a sequence denote either indexing or slicing depending on what's inside the brackets:
>>> "Python rocks"[1]    # index
'y'
>>> "Python rocks"[1:10:2]    # slice
'yhnrc'

Both of these cases are handled by the __getitem__() method of the sequence (or __setitem__() if on the left of an equals sign.)  The index or slice is passed to the methods as a single argument, and the way Python does this is by converting the slice notation, (1:10:2, in this case) to a slice object: slice(1,10,2).
So if you are defining your own sequence-like class or overriding the __getitem__ or __setitem__ or __delitem__ methods of another class, you need to test the index argument to determine if it is an int or a slice, and process accordingly:
def __getitem__(self, index):
    if isinstance(index, int):
        ...    # process index as an integer
    elif isinstance(index, slice):
        start, stop, step = index.indices(len(self))    # index is a slice
        ...    # process slice
    else:
        raise TypeError("index must be int or slice")

A slice object has three attributes: start, stop and step, and one method: indices, which takes a single argument, the length of the object, and returns a 3-tuple: (start, stop, step).

A: The slice function returns slice objects. Slice objects are one of Python's internal types, which are optimized for read performance - all of their attributes are read-only.
Altering slice could be useful if wish to change the default behaviour. For example, lxml uses slice notation to access DOM elements (however, I haven't confirmed how they did that myself).

A: You create a slice by calling slice with the same fields you would use if doing [start:end:step] notation:
sl = slice(0,4)

To use the slice, just pass it as if it were the index into a list or string:
>>> s = "ABCDEFGHIJKL"
>>> sl = slice(0,4)
>>> print(s[sl])
'ABCD'

Let's say you have a file of fixed-length text fields.  You could define a list of slices to easily extract the values from each "record" in this file.
data = """\
0010GEORGE JETSON    12345 SPACESHIP ST   HOUSTON       TX
0020WILE E COYOTE    312 ACME BLVD        TUCSON        AZ
0030FRED FLINTSTONE  246 GRANITE LANE     BEDROCK       CA
0040JONNY QUEST      31416 SCIENCE AVE    PALO ALTO     CA""".splitlines()

fieldslices = [slice(*fielddef) for fielddef in [
    (0,4), (4, 21), (21,42), (42,56), (56,58),
    ]]
fields = "id name address city state".split()

for rec in data:
    for field,sl in zip(fields, fieldslices):
        print("{} : {}".format(field, rec[sl]))
    print('')

# or this same code using itemgetter, to make a function that
# extracts all slices from a string into a tuple of values
import operator
rec_reader = operator.itemgetter(*fieldslices)
for rec in data:
    for field, field_value in zip(fields, rec_reader(rec)):
        print("{} : {}".format(field, field_value))
    print('')

Prints:
id : 0010
name : GEORGE JETSON
address : 12345 SPACESHIP ST
city : HOUSTON
state : TX

id : 0020
name : WILE E COYOTE
address : 312 ACME BLVD
city : TUCSON
state : AZ

id : 0030
name : FRED FLINTSTONE
address : 246 GRANITE LANE
city : BEDROCK
state : CA

id : 0040
name : JONNY QUEST
address : 31416 SCIENCE AVE
city : PALO ALTO
state : CA

A: While trying to answer Subset a string based on variable , I recalled that numpy has a syntactically nice way to define slice objects:
>>> import numpy as np
>>> s = "The long-string instrument is a musical instrument in which the string is of such a length that the fundamental transverse wave is below what a person can hear as a tone."
>>> z = np.s_[18:26]  # in this case same as slice(18, 26, None)
>>> s[z]
'strument'

The problem solved here is how to store the slice in a variable for later use, and np.s_ allows to do just that. Yes, it's not built-in, but as that original question was redirected here I feel like my answer belong here as well. Also, numpy was one of the reasons why so advanced slicing abilities were added to Python, IIRC.
An example of a more complex "slicing":
>>> data = np.array(range(6)).reshape((2, 3))
>>> z = np.s_[:1, 1:2]
>>> data[z]
array([[1]])
>>> data
array([[0, 1, 2],
       [3, 4, 5]])
>>> z
(slice(None, 1, None), slice(1, 2, None))

where z is now a tuple of slices.

A: Slice objects let you programmatically generate and manipulate slices. Especially for multidimensional numpy arrays, and especially if you don't know the dimensionality in advance, you might want to construct slices on-the-fly to specify the axes or dimensions that you want.
import numpy as np
dimension = np.random.randint(10) # Might have up to 10 dimensions
shape = []
for d in range(dimension):
    shape.append(np.random.randint(10))
zz = np.random.rand(tuple(shape))
print(zz)
>>> array([[0.68379351, 0.50854469, 0.64578775, 0.73441699, 0.28977396],
           [0.88797164, 0.81603025, 0.63978659, 0.22677299, 0.93455738],
           [0.0892855 , 0.28048706, 0.04262895, 0.9353467 , 0.13062249],
           [0.88561035, 0.93378367, 0.12124208, 0.25600301, 0.96035638]])

Here our data ended up being two dimensional (4-by-5), but there was no guarantee of that. How will you request slices from zz?
One problem is that I can't manipulate Python's slice notation. It's not valid syntax outside of a slicing operation.
my_slice = 2:3:1
>>> SyntaxError: Invalid Syntax

What if I could just build up the exact slice request I wanted in a loop, the way I can build up a string? Wouldn't that be great? I mean, sure you can use a string to do it, but it would be messy and requires eval.
your_slice_definitions = [(2,3,1), *[(None, None, None)]*(zz.ndim - 1)]
my_slice_str = ""
for slice_start, slice_end, slice_step in your_slice_definitions:
    my_slice_str += "{}:{}:{},".format(slice_start, slice_end, slice_step)
eval("zz["+my_slice_str+"])

So here we are: slice objects let you do this. You can assemble lists and tuples of them on-the-fly, pass them as function parameters, sort them, shuffle them, and so on.
my_slices = []
for slice_start, slice_end, slice_step in your_slice_definitions:
    my_slices += slice(slice_start, slice_end, slice_step)
print(zz[my_slices])
>>> array([[0.0892855 , 0.28048706, 0.04262895, 0.9353467 , 0.13062249]])


text:
Q: What is a distance function of circles outgoing from the center while shifting at constant rates towards the positive Y axis?
I have the following problem: I want a distance equation that depending on the X and Y Coordinates will give me a distance to the circle center.
The circle center is drifting towards a certain direction, let's just say the positive Y direction, as the distance from the center increases.
The images I provided should make this clearer. The first two images show the X and the Y coordinate values respectively. The brighter the pixel the higher the value. The value 0 is assigned to black, which means that unfortunately negative values can't be displayed. For example the left side of the first iamge is completely black, but this is because the values are all negative not because X is 0.
To make visualization easier I used a rounding function, which rounds every value up to the nearest multiple of 0.1.
The third image shows the distance function of a circle when the origin is fixed at (0,0).
This is the simplest case, as it only requires the use of the pythagorean theorem.
The third image shows what I have been able to derive so far: The circle center moves towards the positive Y axis exactly by the distance between the circle center and the point at which the distance function is evaluated.
To get this function I used the fact that the distance of the point to the center and the distance of the center to the point (0,0) are equal:

(The red point is the point where the distance function is evaluated)
Using this I derived the equation below image five (the rightmost image).
One interesting thing of the equation that I derived is that it is symmetric around the X axis, which is something that I didn't intend but don't mind.
The distance function when mapped to the XY plane now looks like circles emenating from point (0,0).
Now comes my question: What would an equation for the fourth image be and how would you derive it?
As you can see when mapping the distance function it should look like the the circle origin moves along the postive Y axis such that when going in the negative Y direction the distance function increases by a constant amount.
Thank you and have a great day!

A: Let's say the rate of vertical drift is $\alpha$, and the rate of radius change is $\beta$. The circle has centre $\vec c=(0,\alpha t)$ and radius $r=\beta t$ where $t$ is time.
A generic point $(x,y)$ on the circle has
$$\lVert(x,y)-\vec c\rVert^2=r^2$$
$$x^2+(y-\alpha t)^2=(\beta t)^2$$
$$x^2+y^2-2\alpha yt+(\alpha^2-\beta^2)t^2=0$$
Solving for $t$ with the quadratic formula, we get
$$t=\frac{2\alpha y\pm\sqrt{4\alpha^2y^2-4(\alpha^2-\beta^2)(x^2+y^2)}}{2(\alpha^2-\beta^2)}$$
$$=\frac{\alpha y\pm\sqrt{(\beta^2-\alpha^2)x^2+\beta^2y^2}}{\alpha^2-\beta^2}$$
So the radius as a function of $x$ and $y$ is
$$r=\beta t=\frac{\beta}{\alpha^2-\beta^2}\Big(\alpha y\pm\sqrt{(\beta^2-\alpha^2)x^2+\beta^2y^2}\Big)$$
It looks like you have the drift being smaller than the radius change: $\alpha<\beta$. And the radius should be positive. So we can find the proper signs in that formula:
$$r=\frac{\beta}{\beta^2-\alpha^2}\Big(-\alpha y\mp\sqrt{(\beta^2-\alpha^2)x^2+\beta^2y^2}\Big)$$
The lower sign should be taken; otherwise $r$ would be negative for some values of $x$ and $y$.
$$r=\frac{\beta}{\beta^2-\alpha^2}\Big(-\alpha y+\sqrt{(\beta^2-\alpha^2)x^2+\beta^2y^2}\Big)$$
(This is indeed always positive, because $(\beta^2-\alpha^2)x^2+(\beta^2-\alpha^2)y^2>0$ (except at the origin $x=y=0$).)

A: Following mr_e_man's brilliant answer I want to add a generalization of it. Mr_e_man's answer only allows for vertical drift however this approach can be generalized for both vertical and horizontal drift.
Instead of using radius r=βt and first calcuating t I opted for using the ratio β/α and then directly calculate the radius.
The circle has center $\vec c=(a*r,b*r)$ where a and b are the
proportionality factor between drift along the X or Y axis and the X or Y coordinate of the point being evaluated.
A generic point $(x,y)$ on the circle has
$$\lVert(x,y)-\vec c\rVert^2=r^2$$
$$(x-ar)^2+(y-br)^2=r^2$$
$$r^2(a^2+b^2-1)+r(-2xa-2yb)+x^2+y^2=0$$
When we solve this quadratic function for r we get:
$$r={a x + b y \pm \sqrt{x^2 - b^2 x^2 + 2 a b x y + y^2 - a^2 y^2}\over (-1 + a^2 + b^2)}$$
It turns out that for some reason using $-$ for $\pm $ always give positive values, so I will use that.
Therefore the general equation for the radius of a circle drifting along an arbitrary direction is:
$$r={a x + b y - \sqrt{x^2 - b^2 x^2 + 2 a b x y + y^2 - a^2 y^2}\over (-1 + a^2 + b^2)}$$
Here are some photos showing the function plotted on the XY plane:

Interestingly for $\sqrt{(a^2+b^2)}<1$ we get a picture of a Mach wave on the on side. As for what's happening on the opposite side i have no idea so please tell me if you can explain how that shape gets to be.
The avid reader will have noticed that when $a^2+b^2=1$ it will cause division through 0.
This means that we need a different function for the cases where $b=\sqrt{1-a^2}$ and $b=-\sqrt{1-a^2}$
So instead of $$(x-ar)^2+(y-b t)^2=r^2$$ we have
$$(x-ar)^2+(y-\sqrt{1-a^2}r)^2=r^2$$
and $$(x-ar)^2+(y+\sqrt{1-a^2}r)^2=r^2$$
respectively.
Solving for r give us for $b=\sqrt{1-a^2}$ $${x^2+y^2\over 2y\sqrt{1-a^2}+2xa}$$
and for $b=-\sqrt{1-a^2}$ $$-{x^2+y^2\over 2y\sqrt{1-a^2}-2xa}$$
Therefore our final equation is:
$$\require{cancel}\begin{cases}
r={a x + b y - \sqrt{x^2 - b^2 x^2 + 2 a b x y + y^2 - a^2 y^2}\over (-1 + a^2 + b^2)}   \text{  if  } a^2+b^2 \neq1 \\[2ex]
r={x^2+y^2\over 2y\sqrt{1-a^2}+2xa}  \text{  else if  }   b=\sqrt{1-a^2} \\[2ex]
r=-{x^2+y^2\over 2y\sqrt{1-a^2}-2xa} \text{  else  }
\end{cases}
$$

A: Circles tangential to lines through the origin can be expressed in polar coordinates $(\rho,\theta)$  with the radius vector $ OP=\rho(\theta) $.
where $d$ is the variable diameter of any circle, $\alpha $ is common inclination to x-axis, the angle between red tangent and $Ox$. Angles in the alternate segment $\theta+ \alpha $ are equal. Angle $OPQ$ in semi circle is $ 90^{\circ}$. $ OQ $ is the hypotenuse in right angled triangle $OPQ$.
$$ \rho= d \sin (\theta + \alpha )$$

This coincides with the fifth image you gave in your question as the special case $\alpha=0$. Three circle diameters are shown.
$$ \alpha = \pi/6, \quad \rho=(2,2.5,3)  $$


text:
Q: R / dplyr: Joining two tables with wide vs. long format on joinable columns I'm working with some public address data that I want to join together, but I'm not sure on the best approach and how to achieve this due to the different wider vs. longer formatting on the columns to join on.
My first table contains all addresses in the country; postal code + adress number lead to unique combinations. Each address also is related to a specific neighborhood and area per county. This table does not contain any other info.
My second table contains relevant information regarding each neighborhood, area and county such as the number of residence, inhabitant ages, energy consumption, etc. The idea is simply to merge this information with the full addresses list so that I can view these statistics for each address in the country.
What gives me a headache is the different formatting of both tables.
The first table is formatted as follows such that every combination of address + postal code is unique (but different addresses can be in the same county, area or neighborhood):
adresses <- data.frame("postal_code" = c("1000A", "1010A", "1000B", "1100B", "1500C", "2700C"),
                 "adress_nr" = c(1, 2, 3, 15, 1, 35),
                 "neighborhood" = c("A1", "A2", "B1", "B1", "C5", "C7"),
                 "area" = c("AA1", "AA2", "BB2", "BB1", "CC1", "CC3"),
                 "county" = c("AAA", "AAA", "BBB", "BBB", "CCC", "CCC")
                   )

The second table has a long format in which one column contains all unique values for BOTH the neighborhood and area (per the overarching county):
neighborhood_area_data <- data.frame(
"county" = c("AAA", "AAA", "AAA", "AAA", "BBB", "BBB", "BBB", "BBB", "CCC", "CCC", "CCC"),
"neighborhood_and_area" = c("NEIGH_A1", "AREA_AA1", "AREA_AA2", "NEIGH_A2", "AREA_BB2", "AREA_BB1", "NEIGH_B1", "NEIGH_C5", "NEIGH_C7", "AREA_CC3", "AREA_CC7"),
"type" = c("Neighborhood", "Area", "Area", "Neighborhood",  "Area", "Area", "Neighborhood", "Neighborhood", "Neighboordhood", "Area", "Area"),
"Number_of_Residents" = c(10, 50, 40, 30, 100, 70, 80, 60, 70, 70, 20),
"Average_Age" = c(55, 44, 33, 22, 66, 77, 55, 88, 99, 44, 11))

So for each overarching county you would have the data for all its existing areas and neighborhoods. ID's of which are stored into a single column, hence the long format. The "NEIGH_" and "AREA_" parts of the string identify whether it's a neighborhood or area and I remove those from the string to be able to join them).
In my example the data of interest would be the Number_of_Residents and Average_Age columns that I want to join onto the individual addresses table.
What I'm looking for is a solid approach/way to combine these tables (preferably via dplyr).
My initial approach was to take the second table and separate the neighborhood_and_area into separate columns (neighboorhood and area) whilst removing the identifier (e.g., "NEIGH_AA1"-> "AA1"part of the string). However because there is no summarizing/pivoting, the second table retains its original format and won't join properly. I am not sure what is the best/most elegant way to reconcile these two formats.
Hopefully my question and examples are clear! Thank you!

A: Assuming you want both the neighborhood and area data stored:
library(tidyverse)

area_data <-
    neighborhood_area_data %>%
    separate(neighborhood_and_area, into = c(NA, 'code'), sep = '_') %>%
    filter(grepl('Area', type)) %>%
    rename(Area_Number_of_Residents = Number_of_Residents,
           Area_Average_Age = Average_Age) %>%
    select(-type)

neighborhood_data <-
    neighborhood_area_data %>%
    separate(neighborhood_and_area, into = c(NA, 'code'), sep = '_') %>%
    filter(!grepl('Area', type)) %>%
    rename(Neighborhood_Number_of_Residents = Number_of_Residents,
           Neighborhood_Average_Age = Average_Age) %>%
    select(-type)

You can then join on each of the split datasets:
adresses %>%
    left_join(area_data,
              by = c('county', 'area' = 'code')) %>%
    left_join(neighborhood_data,
              by = c('county', 'neighborhood' = 'code'))

Output:
  postal_code adress_nr neighborhood area county Area_Number_of_Residents Area_Average_Age Neighborhood_Number_of_Residents Neighborhood_Average_Age
1       1000A         1           A1  AA1    AAA                       50               44                               10                       55
2       1010A         2           A2  AA2    AAA                       40               33                               30                       22
3       1000B         3           B1  BB2    BBB                      100               66                               80                       55
4       1100B        15           B1  BB1    BBB                       70               77                               80                       55
5       1500C         1           C5  CC1    CCC                       NA               NA                               NA                       NA
6       2700C        35           C7  CC3    CCC                       70               44                               70                       99


text:
Q: VBA user form closing causes excel to hang I'm having an issue here with a macro causing excel to hang. I've tried several options and searched endlessly. I have 3 forms, but separate. Here's my steps in it:

*

*Userform pops up

*Item from listbox is double clicked in the form.

*That opens another workbook and runs code on each sheet.

*

*(This is done in another function and works perfectly and takes about 15 seconds ending with the focus on the new workbook.)

*Closes the userform. (This causes it to hang from 7 seconds to 90 seconds depending on the other workbooks size.)

Code below (please excuse the improper format, I had to use my phone... can't login via computer.)
Private sub lb_blah_DblClick (Byval Cancel as MSForms.ReturnBoolean)
  Me.lbl_blah2.caption = "opening aND running"
  'Open and edit xls - Works fine.
  LoadAndFormat me.lb_blah.value

  Me.lbl_blah2.caption = "Ran through format."
  Me.repaint

  '90 seconds with 29 sheets
  'Me.hide
  'Application.enableevents = false '70 seconds

  Unload me '90 seconds - 29 sheets

End Sub

A: I restarted my computer, and that seemed to fix it. I'm sorry.


text:
Q: Add Polymer gesture listeners depending on variable How can I add the gesture listeners without adding them directly to the template or in the 'listeners' property, so I can add them depending on an option.
e.g.
Polymer({
    is: 'my-element',

    properties: {
        enableDrag: Boolean
    },

    listeners: {
        // DO NOT DEFINE HERE
        // 'viewer.track': 'handleTrack'
    },

    ready: function() {
        if(this.enableDrag) {
            // attach listeners to an element here, something like
            // this.$.viewer.addEventListener('track', this.boundHandleTrack);
        }
    }
});

I have tried addEventListener('track', this.boundHandleTrack) and setAttribute('on-track', 'handleTrack') and could not get either to work.
Thanks!

A: You should be able to use the listen method to add gestures imperatively. Fwiw, it's better to observe enableDrag rather than relying on the property being configured at ready time.
Unfortunately there is no unlisten at the moment, because (iirc) the gesture code didn't have support for removing listeners at 1.0 (this is Coming Soon[tm]). The shenanigans with boundHandleTrack are in there because there is no unlisten.
It's easier to just always listen to on-track on the target node and no-op the handler (like I had to do below anyway) if it works for your use case.
properties: {
  enableDrag: {
    type: Boolean,
    observer: 'enableDragChanged'
  },
  boundHandleTrack: {
    value: function() { return this.handleTrack.bind(this); }
  }
},
enableDragChanged: function(drag) {
  if (drag && this.boundHandleTrack) {
    this.listen(this.$.viewer, 'track', 'boundHandleTrack');
    this.boundHandleTrack = null;
  }
},
handleTrack: function(e) {
  if (!this.enableDrag) return;
  // ... otherwise do stuff
}


text:
Q: About OrdinalEncoder in Python Some of my features have values such as excellent, good, average, bad and so on. Obviously they are in order. So I decided to use OrdinalEncoder in sklearn. I want to encode like that: excellent=0, good=1,average=2, bad=3. But I find it has encoded like this: excellent=2, good=3, bad=1, average=0.
How can I adjust the order? Does OrdinalEncoder has some parameters to control that?

A: OrdinalEncoder does not carry a specific ordering contract by default (the current source code for sklearn appears to use np.unique) to assign the ordinal to each value. You can assign the ordering yourself by passing a 2D array (features x categories) as the categories parameter to the constructor. For your case, try this:
from sklearn.preprocessing import OrdinalEncoder
# This is the actual answer:
oe = OrdinalEncoder(categories=[['excellent', 'good', 'average', 'bad']])
# Prove it
X = [['bad'], ['excellent'], ['average'], ['bad'], ['good']]
oe.fit_transform(X)

Resulting in:
array([[3.],
   [0.],
   [2.],
   [3.],
   [1.]])

The advice from the comments to create a dictionary instead is not a bad option either if you have a small number of known classes. {'excellent':0, 'good':1, 'average':2, 'bad':3} is simpler and more portable than lugging around an OrdinalEncoder object.


text:
Q: Как получить синхронный ответ от async метода? Есть метод, который обращается к серверу, а потому использует примерно такой вызов:
public static async Task<Page> GetPageAsync(Uri url)
{
    var webClient = new CookieClient();
    await webClient.DownloadStringTaskAsync(url);
    return new Page(result, webClient.ResponseUri);
}

Метод работает, но он обычно используется в других, и выше получается так:
public static async Task<string> GetName(Uri uri)
{
  var name = string.Empty;
  var document = new HtmlDocument();
  var page = await Page.GetPageAsync(uri);
  document.LoadHtml(page.Content);
  var nameNode = document.DocumentNode.SelectSingleNode("//head/title");
  return WebUtility.HtmlDecode(nameNode.InnerHtml);
}

Суть проблемы - GetName(uri).Result молча висит и ничего не делает, при попытке вызвать таким образом метод в обычном коде. Таска при этом находится в состоянии WaitingForActivation.
Можно вызывать async методы в синхронном коде или надо писать аналогичный синхронный код отдельными методами?

A: У вас deadlock.
Смотрите, в чём проблема.
Вы блокируетесь в ожидании Task'а в UI-потоке. Это значит, что когда вы пишете GetName(uri).Result, ваш UI-поток висит в ожидании окончания Task'а GetName(uri).
Почему же GetName(uri) не завершается? Смотрим на GetPageAsync(Uri url). Он начинает выполняться тоже в UI-потоке. Код await webClient.DownloadStringTaskAsync(url) уходит в ожидание, и когда загрузка завершится, должен получить управление. Это значит, что тот поток, где был получен сигнал об окончании загрузки, запускает остаток метода в UI-потоке при помощи Dispatcher.BeginInvoke или чего-то подобного.
Но UI-поток блокирован! И ждёт, пока завершится вызов .Result. Поэтому он не может отработать хвост метода.
Итак, что делать в этом случае? Есть две рекомендации, и любая из них решает проблему (но следовать стоит обеим).
Итак, рекомендация номер 1: в «библиотечном» коде, наподобие GetPageAsync или GetName, вам не обязательно всё время возвращаться в UI-поток. Вы можете сообщить это системе при помощи следующей конструкции:
result = await webClient.DownloadStringTaskAsync(url)
                        .ConfigureAwait(continueOnCapturedContext: false);

При этом после окончания ожидания в await код не будет перебрасываться в UI-поток, но вам это и не нужно в этом методе.
Все «библиотечные» процедуры (которым не нужен UI-контекст) стоит оформлять с .ConfigureAwait(false).
Рекомендация номер 2: Никогда не блокируйтесь в UI-потоке! Если асинхронная функция будет выполняться долго, ваш UI зависнет, а это плохо. Старайтесь протягивать async до конца. Это вовсе не сложно, кстати.
Дополнительное чтение по теме: Stephen Cleary: Don't Block on Async Code.


text:
Q: Javascript: Compose a function with argument placement instructions for each composition I'm looking for a javascript function that can:
 Condition (I)
compose another function when it does not have recursion in its definition, kind of like in maths when the function is given a power, but with multiple arguments possible in the first input - e.g. with a (math) function f:

f(x) := x+2
f5(x) = f(f(f(f(f(x))))) = x+10
 Condition (II)
Or maybe even input custom arguments into each step of composition:

(52)2)2=
Math.pow(Math.pow(Math.pow(5,2),2),2) = Math.pow.pow([5,2],2,["r",2]])
//first arg set, how times the next, 2nd arg set - "r" stands for recursion -
//that argument will be occupied by the same function

//Using new solution:
_.supercompose(Math.pow,[[5,2],[_,2],[_,2]]) //-> 390625

2((52)3)=
Math.pow(2,Math.pow(Math.pow(5,2),3)) = Math.pow.pow([5,2],["r",2],["r",3],[2,"r"])

//Using new solution:
_.supercompose(Math.pow,[[5,2],[_,2],[_,3]]) //-> 244140625
_.supercompose(Math.pow,[[5,2],[_,2],[_,3],[2,_]]) //-> Infinity (bigger than the max. number)

Note: The above are just templates, the resulting function doesn't have to have the exact arguments, but the more close to this (or creative, for example, a possibility of branching off like this ->[2,4,"r",4,2,"r"], which would also be complicated) the better.
I've been attempting to do at least (I) with Function.prototype, I came up with this:
Object.defineProperty(Function.prototype,"pow",{writable:true});
//Just so the function not enumerable using a for-in loop (my habit)
function forceSlice(context,argsArr)
{returnArray.prototype.slice.apply(context,argsArr)}
Function.prototype.pow = function(power)
{
  var args=power<2?forceSlice(arguments,[1]):
  [this.pow.apply(this,[power-1].concat(forceSlice(arguments,[1])))];
  return this.apply(0,args);
}
//Usage:
function square(a){return a*a;}
square.pow(4,2) //65536
function addThree(a,b){return a+(b||3); }
// gives a+b when b exists and isn't 0, else gives a+3
addThree.pow(3,5,4) //15 (((5+4)+3)+3)

Worst case, I might just go with eval, which I haven't figured out yet too. :/
Edit: Underscore.js, when played around with a bit, can fulfill both conditions.
I came up with this, which is close to done, but I can't get it to work:
_.partialApply = function(func,argList){_.partial.apply(_,[func].concat(argList))}

_.supercompose = function(func,instructions)
{
_.reduce(_.rest(instructions),function(memo,value)
{
return _.partialApply(_.partialApply(func, value),memo)();

},_.first(instructions))
}
//Usage:
_.supercompose(Math.pow,[[3,2],[_,2]]) //should be 81, instead throws "undefined is not a function"

Edit: jluckin's cleareance of terms (recursion-> function composition)
Edit: made example function return number instead of array

A: The term you are looking for is called function composition, not necessarily recursion. You can apply function composition in javascript easily since you can pass a function as an argument.
I created a small function called compose, which takes a function, an initial value, and the number of times to compose the function.
function compose(myFunction, initialValue, numberOfCompositions) {
    if (numberOfCompositions === 1) {
        return myFunction(initialValue);
    }
    else {
        return compose(myFunction, myFunction(initialValue), --numberOfCompositions);
    }
}

When this function is evaluated, you pass in some function f(x), some initial x0, and the repeat count. For example, numberOfCompositions = 3 gives f(f(f(x)));
If there is one composition, then f(x) is returned. If there are two compositions, compose returns f(x) with f(x) replacing x as the argument, with 1 passed in as the composition so it will evaluate f(f(x)).
This pattern holds for any number of compositions.
Since functions are treated as objects and can be passed as arguments of functions, this method basically wraps your "non-recursive" functions as recursive functions to allow composition.

A: Success(simplicity wins):
_.supercompose = function (func,instructions,context)
{
var val;
for(var i = 0; i < instructions.length; i++)
  {
 val = _.partial.apply(_,[func].concat(instructions[i])).apply(context||this,val?[val]:[]);
  }
return val;
}

//Usage (with a function constructor for operations):
_.op = function(o){return Function.apply(this,"abcdefghijklmnopqrstuvwxyz".split("").concat(["return " + o]))}
_.op("a+b")(3,5) //-> 8
_.op("a*b")(3,5) //-> 15
_.supercompose(_.op("(a+b)*c*(d||1)"),[[1,2,3],[-5,_,1],[1,2,_,3]])
//-> (1+2)*((-5+((1+2)*3))*1)*3 -> 36


text:
Q: Knowing is a polynomial has a root in a finite field of $125$ elements I was looking at this post and saw a comment left without an answer that intrigued me. The question posed was about a field being isomorphic to a quotient ring and an answer showed that: $$\frac {\mathbb Z[x,y]}{(5,x^2-y,xy+x+1)}\cong \frac {\mathbb Z_5[x,y]}{(x^2-y,xy+x+1)}\cong\frac {\mathbb Z_5[x]}{(x^3+x+1)} $$ The comment left asked if there was an easy way to see if the polynomial $x^3+3x+2$ has a root in a finite field of $125$ elements. Is there a general way to show this for any function and any finite field?

A: $x^3+3x+2$ has no root mod $5$ and so is irreducible. Therefore, $\frac {\mathbb Z_5[x]}{(x^3+x+1)}$ is a field with $5^3=125$ elements which contains a root of $x^3+3x+2$.
Things are not always so easy. In general, a polynomial $f$ has a root in a finite field of order $q=p^n$ iff $\gcd(f,x^q-x)\ne1$ mod $p$. This can be settled with Euclid's algorithm, but is not suitable for hand computation for large $q$ and $f$.

A: The general question of whether a polynomial $\ p(x)\in\mathbb{F}_q[x]\ $ over a finite field $\ \mathbb{F}_q $ of order $\ q\ $ has any roots in $\ \mathbb{F}_q\ $ can be decided by computing the greatest common divisor of $\ p(x)\ $ and $\ x^q-x\ $.
If  $\  g(x)=$$\,\gcd(\,p(x),$$\,x^q-x\,)\ $, then $\ p(x)\ $ has a root in $\ \mathbb{F}_q\ $ if and only if $\ \deg(g(x))>0\ $. When this is the case, $\ g(x)\ $ splits into linear factors over $\ \mathbb{F}_q\ $ whose roots comprise all those of $\ p(x)\ $ that lie in $\ \mathbb{F}_q\ $.  The remaining roots of $\ p(x)\ $—namely those of $\ \frac{p(x)}{g(x)}\ $—will belong to some extension field $\ \mathbb{F}_{q^r}\ $ of $\ \mathbb{F}_q\ $ of degree $\ r>1\ $.
The roots of any irreducible factor of $\ p(x)\ $ of degree $\ d\ $ will belong to $\ \mathbb{F}_{q^d}\ $. Those roots which are primitive will not belong to any proper subfield of $\ \mathbb{F}_{q^d}\ $, but if $\ \alpha $ is a primitive root and $\ e\ $ a proper divisor of $\ d\ $ then $\ \alpha^e \ $ will be a root belonging to the proper subfield $\ \mathbb{F}_{q^\frac{d}{e}}\ $.
If $\ d_1, d_2,\dots,d_t\ $ are the degrees of the irreducible factors of $\ p(x)\ $, and $\ \ell=\text{lcm}(d_1, d_2,\dots,d_t)\ $, then $\ \mathbb{F}_{q^\ell}\ $ is the smallest field that contains all the roots of $\ p(x)\ $.


text:
Q: Nestjs define GraphQL Object type got this error: Schema must contain uniquely named types but contains multiple types named "Address" I use Nestjs & GraphQL for backend development, when I define model class (code first), I got following error: Schema must contain uniquely named types but contains multiple types named "Address". Following is my Reader model file:
@ObjectType()
class Address {
  @Field()
  homeAddress: string;
  @Field()
  province: string;
  @Field()
  postcode: string;
}

@ObjectType()
class FavouriteBook {
  @Field()
  bookID: string;
  @Field()
  createDate: Date;
}

@ObjectType()
export class ReaderProfile {
  @Field()
  _id: string;
  @Field()
  firstName: string;
  @Field()
  lastName: string;
  @Field()
  gender: string;
  @Field()
  birthday: Date;
  @Field()
  address?: Address;
  @Field()
  postcode: string;
  @Field(type => Int)
  readTimes: number;
  @Field(type => Int)
  readDuration: number;
  @Field(type => Int)
  score: number;
  @Field()
  securityQuestion: string;
  @Field()
  securityAnswer: string;
}

@ObjectType()
export class ReaderReadHistory {
  @Field()
  _id: string;
  @Field()
  bookID: string;
  @Field(type => Int)
  currentPage: number;
  @Field()
  startTime: Date;
  @Field()
  lastReadTime: Date;
  @Field(type => Int)
  readTimes: number;
  @Field(type => Int)
  readDuration: number;
}

@ObjectType()
export class Reader {
  @Field()
  _id: string;
  @Field()
  username: string;
  @Field()
  password: string;
  @Field()
  email: string;
  @Field()
  registerDate: Date;
  @Field()
  isActive: boolean;
  @Field({ nullable: true })
  currentRefreshToken?: string;
  @Field(type => ReaderProfile)
  readerProfile: ReaderProfile;
  @Field(type => [FavouriteBook])
  favouriteBook: FavouriteBook[];
  @Field(type => [ReaderReadHistory])
  readHistory: ReaderReadHistory[];
}

And this is my GraghQL configuration in app module: (code first)
GraphQLModule.forRoot({
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
      cors: false,
      sortSchema: true,
      context: ({ req }) => ({ req }),
    }),

Does anyone know how to fix this? Thanks a lot!

A: Eventually I did not find reason, and I changed coding to schema first which works well as expected. Hopefully this help for those have same issue but can't fixed with code first approach, try schema first. Also I found schema first approach has less boil-plates, especially you can use separate auto generate function (refer to following) to generate all the type script interfaces in one file, there is pretty helpful.
import { GraphQLDefinitionsFactory } from '@nestjs/graphql';
import { join } from 'path';

const definitionsFactory = new GraphQLDefinitionsFactory();
definitionsFactory.generate({
  typePaths: ['./src/**/*.graphql'],
  path: join(process.cwd(), 'src/graphql.ts'),
});


text:
Q: Unresizable ever JavaFX Window My problem is that my JavaFX window expands further than it should at the bottom, thus showing a weird blank background...
I set stage.setResizable(false) but it doesn't seem to work. I also set
stage.setMinWidth(1280);
stage.setMaxWidth(1280);
stage.setMinHeight(800);
stage.setMaxHeight(800);

I think it's due to some ImageView bigger than the window, but I really would like my window to stick to the max I set and be absolutely not resizable ever.
Here's what it looks like : click here
I also noticed it happens only when I set stage.initStyle(StageStyle.TRANSPARENT).
But I don't want my window to be decorated with stage.initStyle(StageStyle.DECORATED)... :(
Thank you in advance for your help. :)

A: Have you tried directly using setWidth and setHeight:
stage.setWidth(1280);
stage.setHeight(800);

I think the setMaxWidth, setMinHeight... etc. only works on a decorated screen because its main purpose is to limit the sizes the user can set the window. Here's my example:
public class FixedWindowSize extends Application
{

    public static void main(String[] args)
    {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        Pane p = new Pane();
        p.setBackground(new Background(new BackgroundFill(Color.RED, null, null)));
        p.setMinSize(6000, 6000); //Make this go out beyond window bounds.
        Scene s = new Scene(p);

        primaryStage.setScene(s);
        primaryStage.initStyle(StageStyle.TRANSPARENT);

        //This doesn't work
        //primaryStage.setMinWidth(1280);
        //primaryStage.setMaxWidth(1280);
        //primaryStage.setMinHeight(800);
        //primaryStage.setMaxHeight(800);

        //This should work.
        primaryStage.setWidth(1280);
        primaryStage.setHeight(800);

        primaryStage.show();
    }

}


text:
Q: Horizontally centered div with a div next to it, kind of responsive-ly Here's my code:

        Example Content

        Bla Bla Bla Bla Bla

#container
{
    background: #aaa;
    padding: 3em 0;
    text-align: center;
}
#container > div
{
    display: inline-block;
    background: #777;
    padding: 3em;
}

and a fiddle of my current situation:
http://jsfiddle.net/zu0f6jcm/

Now my questions are;
a) How can I center the inner div, so that the span doesn't affect it's position?and
b) How can I keep the span inline with the inner div, unless there's not enough space to display the span on one line, in which case it should move below the inner div?
To clarify b): the behaviour I'm looking for is kind of like when you add
span
{
    float: right;
}

to the current fiddle, while taking into account the a). I should also preferably be able to position the span with margins and what not.
Without JS.

A: The positioning you're looking for can be achieved by modifying your CSS like this:
#container {
    background: #aaa;
    padding: 3em 0;
    text-align: center;
    position: relative:  /* additional style */
}

/* no changes to the '#container > div' rule */

#container span {
    position: absolute;
    padding: 3em 0;  /* copied this from your padding above, mod as necessary */
    right: 0;        /* adjust this to whatever positioning you need */
    top: 0;          /* adjust this to whatever positioning you need */
}

This will not automatically handle the "move to the bottom if there's not space" part of your question, however.  For that, you'll need to use media queries and change your style rules at different device widths.

A: Here is a basic example of how you could achieve it with floats:

         Example Content

         Example Content

     Bla Bla Bla Bla Bla

css:
 #container{
     background: #aaa;
     padding: 3em 0;
     text-align: center;
     position:relative;
     overflow: auto;
 }
 #container > div {
    float:left;
    width:33%;
 }

 #container #content{
     background: #777;
     min-width:200px;
 }

Your last div will wrap when there is not enough room for it to take up 33% of the screen with the #content containers min-width set to what-ever value you want for this.
fiddle: http://jsfiddle.net/s4secygm/


text:
Q: Implementing Ruby Refinements in Javascript Ruby's refinements allow you to temporarily "upgrade" an object within a lexical scope.  I'm trying to implement a similar idea in javascript.  Here's some working code that does almost what I want:
function dateExtension() {
  return {
    day: function() { return this.getDate() }
  }
}

function refine(ctor, mixin) {
  return function() {
    var ret = new (Function.prototype.bind.apply(ctor, arguments));
    return Object.assign(ret, mixin);
  }
}

function test() {
  // Cant overwrite native Date function,
  // so have to rename it.
  var XDate = refine(Date, dateExtension());
  var d = new XDate();
  console.log(d.day()); // prints the day of the month to console

}

test();

What I really want to do is this:
function test() {
  var Date = refine(Date, dateExtension());
  var d = new Date();
  console.log(d.day());  // Uncaught TypeError: Bind must be called on a function
}

The idea would be to make the local var Date overide the built in Date, within the body of test() only.  So that, within test(), it would acquire the new method day(), but outside of test() Date would be unaffected.  This apparently is not allowed.
Is there some workaround to make this idea work?

A: I made a tiny library called chill-patch to do exactly that. It enables you to use functions as methods, and to safely patch prototypes.
Here's an example of how to use it:
const chillPatch = require('chill-patch')
const lastFunc = arr => arr[arr.length - 1]
const array = [1, 2, 3]

// safely add a method to `Array`
const last = chillPatch(Array, lastFunc, 'last')

// call the new method!
array[last]() //=> 3

If you want to roll your own, the entire source code is as follows:
'use strict'

const chillPatch = (klass, func, optionalDescription) => {
  const symbol = Symbol(optionalDescription)
  klass.prototype[symbol] = function(){
    const args = Array.prototype.slice.call(arguments)
    args.unshift(this)
    return func.apply(null, args)
  }
  return symbol
};

module.exports = chillPatch

I see you said in a comment that you do not want to modify prototypes, but your reason is probably that modifying prototypes is dangerous. However, the method above patches using Symbol, which is completely safe. The change will be invisible to other parts of the codebase unless someone is doing reflection with Object.getOwnPropertySymbols()

A: So I came up with something that works, although it's fairly hacky.
Here's a fiddle: https://jsfiddle.net/40cty4qa/
And here's the code
function lg() { console.log.apply(console, arguments) }

function extend(o, mixin) {
  for (var k in mixin) o.prototype[k] = mixin[k]
}
function unextend(o, mixin) {
  for (var k in mixin) delete o.prototype[k];
}

Function.prototype.refine = function(ctor, mixin) {
  var self = this;
  return function() {
    extend(ctor, mixin);
    var ret = self.apply(this, arguments);
    unextend(ctor, mixin);
    return ret;
  }
}

function dateExtension() {
  return {
    day: function() { return this.getDate() }
  }
}

function refine(ctor, mixin) {
  return function() {
    var ret = new (Function.prototype.bind.apply(ctor, arguments));
    return Object.assign(ret, mixin);
  }
}

function test() {
  var d = new Date();
  lg(d.day());
}
test = test.refine(Date, dateExtension());

test();  // This works, since were inside a refinement
var d = new Date();
lg(d.day());  // This doesnt work, as desired.


text:
Q: How to use the new FirebaseCrash/upload-sym? I have created new iOS project and in the process of integrating it with Firebase Core and Crash. I have the following run script"
GOOGLE_APP_ID=1:my:app:id

"${PODS_ROOT}"/FirebaseCrash/upload-sym "${SRCROOT}/path/to/my-json-file"

This was working fine on my previous projects, I have checked my old projects and they are fine.
However, the new project seems to have a upload-sym from Pod FirebaseCrash which does not expect arguments.
I have also confirmed that the upload-sym file in my older projects is different from the upload-sym file in my freshly created project.
How to use upload-sym without supplying the path to my json file?

A: The readme for the FirebaseCrash pod that suggests upload-sym does not take an argument is incorrect.  It does require your service account file path as shown in the docs on the website.  Look at the upload-sym script itself in the FirebaseCrash pod directory to verify for yourself what it does.  The latest version of the pod at the time I write this is 1.1.4.


text:
Q: Disable button after ajax Success I need to disalble submit button after ajax forever!
But when I reload the page submit button is active(
function submitConfirmAjaxList(e){
    var url = "<?php echo $this->getUrl('wedding/gifts/confirmList') ?>";
    var getTransferId = '<?php echo $checkTransferId?>';
    var getCurrentCustomerId = '<?php echo $getCurrentCustomerId?>';
    var confirmResponse = 1;
    var disalleButton = $('confirmButton').setAttribute('disabled', 'disabled');

    new Ajax.Request(url, {
        method:'post',
        parameters: {
            getTransferId : getTransferId,
            getCurrentCustomerId : getCurrentCustomerId,
            confirmResponse : confirmResponse
        },
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport) {
            location.reload();
            e.disable();

        }
    });

}

    __('Сonfirm the list')?>" class="button" onclick="submitConfirmAjaxList(this)">__('confirm the list')?>

A: You could easily accomplish that if you would delete your location.reload();. The idea of ajax is the asynch call, which is executed and processed without reloading the entire page. That said you can just put $('#confirmButton').attr('disabled', 'disabled'); in your onSuccess: function(transport) {} method and you should be fine

A: Use this
$('#button_id').prop('disabled', 'disabled');

A: If you reload the page then you have a new page which doesn't maintain state from any previous changes you made with JavaScript.
You need to store something on the server (e.g. in session data or the user's account data in the database) that indicates the submit button should be disabled.
Then your server side code should include a disabled attribute in the button when the page loads.

A: After sucess, put some value in cookie, validaty of cookie should be till current session, on page load (may be document.ready) check if cookie value is specific to which you stored then disable the button with jquery.

A: Use this in AJAX Success:
$(".class").attr('disabled','disabled');


text:
Q: $E_1$ and $E_2$ are disjoint then $m(E_1\cup E_2)=m(E_1)+m(E_2)$? My professor told me that the following statement is not always right:

$E_1$ and $E_2$ are disjoint then $m_*(E_1\cup E_2)=m_*(E_1)+m_*(E_2)$

where $m_*(\cdot)$ denotes the outer measure. However I'm not sure why, because I learned a theorem of the following:

If $E=E_1 \cup E_2$, and $d(E_1, E_2)>0$, then $m_*(E)=m_*(E_1)+m_*(E_2)$

So I think my problem with this part is that I can't distinguish the difference between 'being disjoint', and 'having a positive measure'. What will be some example of sets that are disjoint, yet has zero distance, or not disjoint, yet has a positive distance.
Edit: Thanks to the answer of @Giorgio Zorzi detto Giorgione, I have an example of sets that are disjoint, yet has zero distance, namely the rational and irrationals. I think I got the difference between them. However, if we take $E_1=[0, 1]\cap Q$ and $E_2=[0, 1]\cup Q^C$, we still notice that the first statement holds. Then, in which particular cases does the first statement not hold, and if this difference is not coming from "disjoint" and "positive distance", where is it coming from?

A: Pick the rationals and the irrationals. Their distance is zero (by definition of distance, which involves an infimum) but they are disjoint.
If the distance between two sets is not zero, this implies they are disjoint.


text:
Q: Node Callback from database query to express request I want the function below (listServers()) to callback data to be used in the express request below. But I am confused by the set up of a callback as I have got conflicting information from searching.
The server runs listServers fine but seems to timeout when returning the value to the request.
The output from me requesting / on the server is:
forEach length:1
forEach length:2
listServers length:2
::ffff:*IP* - - [30/Nov/2016:09:31:19 +0000] "GET / HTTP/1.1" - -

Code:
var listServers = function (err, data) {
    var list=[];
    db.all("SELECT * FROM Servers;", function(err, rows){
    rows.forEach(function(e){
      var confi = fs.readFileSync(paths.factorioDir + "server" + e.serverID + paths.conf);
      var conf = JSON.parse(confi);
      var item = {id: e.serverID, conf:conf};
      list.push(item);
        console.log("forEach length:" + list.length);
    });
    if (err) throw err;
      console.log("listServers length:" + list.length);
      data = list;
    return data;
    });

};

admin.get('/', function(req, res) {
   listServers(function(err, data){
     console.log(data.length);
     servers = data;
     console.log("/ servers length"+ servers.length);
      var adminTemplate = pug.compileFile(__dirname + '/template.pug');
      var context = { servers: servers };
      var html = adminTemplate(context);
      res.send(html);
});
});

Full code is here

A: What you are passing to listServers() is a callback function, so instead of returning the data/throwing an error in listServers() you should invoke that callback and pass it either the error or the data:
var listServers = function (callback) {
    var list=[];
    db.all("SELECT * FROM Servers;", function(err, rows){
        if (err) {
            callback(err, []);

            return;
        }

        rows.forEach(function(e){
            var confi = fs.readFileSync(paths.factorioDir + "server" + e.serverID + paths.conf);
            var conf = JSON.parse(confi);
            var item = {id: e.serverID, conf:conf};
            list.push(item);
            console.log("forEach length:" + list.length);
        });

        console.log("listServers length:" + list.length);
        callback(null, list);
    });
};

admin.get('/', function(req, res) {
    listServers(function(err, data){
        if (err) {
            // Handle error
        }

        console.log(data.length);
        servers = data;
        console.log("/ servers length"+ servers.length);
        var adminTemplate = pug.compileFile(__dirname + '/template.pug');
        var context = { servers: servers };
        var html = adminTemplate(context);
        res.send(html);
    });
});


text:
Q: Typescript: define interface without specific keys & chain objects I have such example of data, that I receive:
{
  Europe: {
    WestEurope: {
      Belgium: [French, English, Dutch]
   }
  }
}

Not sure how I can create an interface for such a dynamic structure, where I have a tree:

Object->Object(of Regions)->Object(of SubRegions)->Object(of
  Countries)->ArrayOfStrings(of languages)

I tried so:
export interface Localisation {
    [key: string]: Localisation;
}
export interface Region {
    [key: string]: Region;
}
export interface SubRegion {
    [key: string]: SubRegion;
}
export interface Country {
    [key: string]: Country;
}
export interface Language {
    [index: number]: Array<string>;
}

but they aren't 'chained' -> so 'Localisation' doesn't know that it contains 'Regions' etc. And I want to connect them somehow. Is it possible?

A: How about this?
interface Country {
  [proporty: string]: string[];
}

interface SubRegion {
  [property: string]: Country;
}

interface Region {
  [property: string]: SubRegion;
}

interface Localisation {
  [property: string]: Region;
}

A: An alternative is not to use separate interfaces, but nest everything under one interface. This only works if you don't need the separate types though.
interface Localization {
    [region: string]: {
        [subregion: string]: {
            [country: string]: string[]
        }
    }
}

// Usage

const data: Localization = {
    Europe: {
        WestEurope: {
            Belgium: ['French', 'English', 'Dutch']
        }
    }
};

const westEurope = data['Europe']['WestEurope']; // Is of type { [country: string]: string[] }


text:
Q: Autospec / rspec not working, doing something wrong? I wonder if this has its place on StackOverflow, but since it IS programming-related, I will shoot it away.
Here's my problem. I am new to TDD and I love Ruby, so the obvious path I'm taking is testing stuff with rspec. Why obvious? I saw it in diverse screencasts and thought it was really neat. Then I saw "autospec" somewhere, and tried to use it.
So I install the gem, using sudo gem install ZenTest (according to the instructions here)
Next, I go into my folder, containing "digit.rb" and "digit_spec.rb", and fire up autospec without any parameter. Nothing happens. Worthy of note that I have two tests in my spec file and that I can test it fine just using the spec command, but I'd be delighted to use autotest...
Any help/pointers/documentation link available? Please? :P

A: You need to create .autotest file containing this code:
Autotest.add_hook :reset do |at|
  at.clear_mappings
  at.add_mapping(/^(.*?)(_spec)?\.rb$/) { |filename, m|
    if m[2]
      filename
    else
      "#{m[1]}_spec.rb"
    end
  }
end

it changes the default mapping of file to spec

A: Maybe you can give spork + autospec a try. The spork instructions on the rspec wiki is probably the most current way to go: https://github.com/dchelimsky/rspec/wiki/spork---autospec-==-pure-bdd-joy-


text:
Q: Cant trust a project .DLL on a network location I am having an issue of editing a Visual Studio project by which it is saved on a remote server at home.
First of all, my setup is:-

*

*Windows 8 64bit RC, With Visual Studio 2010 installed.

*Windows Server 2012 RC. With a Shared Folder accessed with an account (//Dev).

The problem here is from Windows 8 RC, I can access the share and create the projects I want. But if I build the project I got this error:-
Could not load the assembly file:///C:\***.dll. This assembly may have been downloaded from the Web. If an assembly has been downloaded from the Web, it is flagged by Windows as being a Web file, even if it resides on the local computer. This may prevent it from being used in your project. You can change this designation by changing the file properties. Only unblock assemblies that you trust. See http://go.microsoft.com/fwlink/?LinkId=179545 for more information.
I tried to unblock the .DLL file from its properties but the UNBLOCK button is not available.
Plz help.

A: There is a thread regarding a similar issue:
Error building Visual Studio 2010 Silverlight 4 projects on Windows 7 with XP Mode
Adding the <loadFromRemoteSources enabled="true"/> under <configuration> <runtime> in devenv.exe.config actually fixed "This assembly may have been downloaded from the Web" issue for me in VS2010, give it a try.


text:
Q: Junit test with mouse click event I have a Jpanel that contain a JTabel and JTextField that display the value of the Jtable row when the row is clicked twice. the user can edit the  JTextField value than click a button to update once the button is click the updateUser method will be called. I am trying to write a JUnit test to test that the updateUser is updating user.
How can I perform double click on a specific table row to get the data displayed in the specified JTextField?
 public void updateUser(){

      String  id= txtid.getText();
      String  name =txtName.getText();
      String q = "UPDATE `user` SET `name`=? WHERE `id`=?";
        try{
             PreparedStatement ps = Login.con.prepareStatement(q);
             ps.setString(2, id);
             ps.setString(1, name);
             ps.executeUpdate();
             JOptionPane.showConfirmDialog(null, "User Updated");
            }catch(Exception eu){

                      }
}

A: Unittest should test the Unit, specefically the logical unit, in your case i would change the updateUser() method to:
bool updateUser(String id, String name)
which you can test then undependant from the GUI elements.
The showConfirmDialog can then be shown according to the return value of the updateUser method.


text:
Q: Making PySNMP resolve Object IDs I'm trying to do a SNMP-walk with PySNMP. I wrote the following script, which works, but for every device I "walk" the OIDs of only about ten rows can be resolved to a "real name".
from pysnmp.entity.rfc3413.oneliner import cmdgen
from os.path import exists
import sys
import os

# Turn on debugging
#debug.setLogger(debug.Debug('msgproc', 'secmod'))

# Enter parameters
target_IP           = raw_input('Target IP (192.168.13.100): ') or '192.168.13.100'
target_port         = raw_input('Target port (161): ') or 161
max_timeout         = int(raw_input('Maximum timeout in seconds (1):')) or 1
max_retries         = int(raw_input('Maximum number of retries (0):')) or 0
target_file_name    = raw_input('Target filename (.txt is added): ') + '.txt'

# Check for already existing file
path = 'walks/'
if not os.path.exists(path):
    os.makedirs(path)
if exists(path+target_file_name):
    sys.exit("The file '%s' already exists. Try again." % target_file_name)
else:
    target_file = open(path+target_file_name, 'w+')

# Initialize counter to zero
counter = 0

# Create command generator
cmdGen = cmdgen.CommandGenerator()

# Get data

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
    cmdgen.CommunityData('public'),
    cmdgen.UdpTransportTarget((target_IP, target_port), timeout=max_timeout, retries=max_retries),
    '1.3',
    lexicographicMode=True,
    #maxRows=1000,
    ignoreNonIncreasingOid=True,
    lookupNames=True
)

# Print errors and values to file
if errorIndication:
    print(errorIndication)
else:
    # Print error messages

    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
            )
        )
    else:
        # Print values
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                counter += 1
                target_file.write("(%s)\t %s value = \t%s\n" % (counter, name.prettyPrint(), val.prettyPrint()))

        # Finish the operation
        target_file.close()
        print('Writing to %s successful. %d lines have been written' % (target_file_name, counter))
        sys.exit(0)

The result is a file with very many rows.
the first entrys look like this:
(1)  SNMPv2-MIB::sysDescr."0" value =   Hirschmann MAR
(2)  SNMPv2-MIB::sysObjectID."0" value =    1.5.6.9.1.1.248.4.10.90
(3)  SNMPv2-MIB::sysUpTime."0" value =  2626357
(4)  SNMPv2-MIB::sysContact."0" value =     Hirschmann Automation and Control GmbH
(5)  SNMPv2-MIB::sysName."0" value =    mar1030.plc-s7-15000
(6)  SNMPv2-MIB::sysLocation."0" value =    Hirschmann MAR
(7)  SNMPv2-MIB::sysServices."0" value =    2
(8)  SNMPv2-MIB::sysORLastChange."0" value =    300

But then the OIDs are not resolved anymore:
(9)  SNMPv2-SMI::mib-2."2.1.0" value =  27
(10)     SNMPv2-SMI::mib-2."2.2.1.1.1" value =  1
(11)     SNMPv2-SMI::mib-2."2.2.1.1.2" value =  2
(12)     SNMPv2-SMI::mib-2."2.2.1.1.3" value =  3
.....

What causes this and what can I do about it?

A: To resolve MIBs with pysnmp you have to load them into pysnmp engine prior to make SNMP queries. Your script performs MIB resolution for SNMPv2-MIB because it is automatically loaded by pysnmp engine.
To make use of plain-text MIBs with pysnmp you have to convert them from plain text form (e.g. ASN.1) into pysnmp format (Python code). You could use the build-pysnmp-mib shell script (based on libsmi) or download and install a pre-compiled pack of common MIBs (pysnmp-mibs Python package).
To load some or all available MIBs you could use the MibVariable.loadMibs(*mibs) method. See this script for example.


text:
Q: Are native map, filter, etc. methods optimized to operate on a single intermediary array when possible? Consider the below snippet, which converts an array of objects to an array of numbers, with negative values filtered out, and then doubled by 2:
var objects = (new Array(400)).fill({
    value: Math.random() * 10 - 5
});

var positiveObjectValuesDoubled = objects.map(
    item => item.value
).filter(
    value => value > 0
).map(
    value => value * 2
);

When chained together like this, how many actual Array objects are created in total? 1, or 3? (excluding the initial objects array).
In particular, I'm talking about the intermediary Array objects created by filter, and then by the second map call in the chain: considering these array objects are not explicitly referenced per se, are Javascript runtimes smart enough to optimize where possible in this case, to use the same memory area?
If this cannot be answered with a clear yes-or-no, how could I determine this in various browsers? (to the best of my knowledge, the array constructor can no longer be overridden, so that's not an option)

A: Good commentary so far, here's a summary answer: an engine might optimize for memory usage across chained method calls, but you should never count on an engine to do optimization for you.
As your example of chained methods is evaluated, the engine's memory heap is affected in the same order, step by step (MDN documentation on the event loop). But, how this works can depend on the engine...for some Array.map() might create a new array and garbage collect the old one before the next message executes, it might leave the old one hanging around until the space is needed again, it might change an array in place, whatever. The rabbithole for understanding this is very deep.
Can you test it? Sometimes! jQuery or javascript to find memory usage of page, this Google documentation are good places to start. Or you can just look at speed with something like http://jsperf.com/ which might give you at least an idea of how space-expensive something might be. But you could also use that time doing straightforward optimization in your own code. Probably a better call.