Q:

Registering 2 activities to receive images, it doesn't work when sharing from Google Photos app

Let's say in my app, users can make posts & send messages to other users, & I want to register my app as a component among those appears in the Share-via picker when sharing either text or an image, I'm defining my 2 activities in my AndroidManifest.xml as follows (like this official example):
<activity
    android:name=".SharePostActivity"
    android:label="MyApp (Post)">
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>

<activity
    android:name=".ShareMessageActivity"
    android:label="MyApp (Message)">
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>

When sharing text, this works perfectly fine, where I see 2 icons of my app among available apps for sharing text, named MyApp (Post) & MyApp (Message),
Problem happens when sharing an image, because only one icon appears with the second defined label in the manifest (which is MyApp (Message)), and actually it opens the first defined activity in the manifest (which is SharePostActivity),
So, how to show the 2 options when sharing an image (just like what happens when sharing text)?
(I've tried on an emulator running Nougat & a real device running Oreo)
----- Update -----
I've found that this weird behavior happens only when sharing images from Google's Photos app, but everything works fine when sharing an image from other apps!

A:

Some investigation leads to a solution: each of your intent-filter must contain an android:label which points to a resource, not a hardcoded string.
...
<intent-filter android:label="@string/first_value">
...

Different Activities must have different labels, so in your case the Manifest should look like
<activity
    android:name=".SharePostActivity"
    android:label="@string/my_app_post">
    <intent-filter
        android:label="@string/my_app_post">
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    <intent-filter
        android:label="@string/my_app_post">
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>

<activity
    android:name=".ShareMessageActivity"
    android:label="@string/my_app_message">
    <intent-filter
        android:label="@string/my_app_message">
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
    <intent-filter
        android:label="@string/my_app_message">
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>


Q:

Firebase functions how to get a boolean value from Firebase Database

I have a code in node.js in the functions of Firebase, that simply what I want to know is how to get the Boolean value of the variable "read" within each user within the class "Users".
My code:
let functions = require('firebase-functions');

let admin = require('firebase-admin');

admin.initializeApp();

exports.sendNotificationNewChat = functions.database.ref('/Usuarios/{usuarioId}/Chats/{chatsId}').onWrite((change, context) => {

    //get the userId of the person receiving the notification because we need to get their token
//const receiverId = context.params.userId;
//console.log("receiverId: ", receiverId);
/*
    // Only edit data when it is first created.
      if (change.before.exists()) {
        return null;
      }*/
      // Exit when the data is deleted.
      if (!change.after.exists()) {
        return null;
      }

    if (!change.after.exists()) {
        return null;
    }
    //te escribe el json de el mensaje nuevo
    const afterData = change.after.val();
    console.log("afterData: ", afterData);

  //  const readChat = afterData.read;
   // console.log("readChat: ", readChat);

//get the user id of the person who sent the message
    const senderId = context.params.usuarioId;
    console.log("senderId: ", senderId);

//get the user id of the person who sent the message
    const receiverId = afterData.IdOtherUser;
    console.log("receiverId: ", receiverId);

//get the message
    const nameAd = afterData.nameAd;
    console.log("nameAd: ", nameAd);

//get the message
    const ChatId = context.params.chatsId;
    console.log("ChatId: ", ChatId);

    /*
    //get the message id. We'll be sending this in the payload
    const messageId = context.params.messageId;
    console.log("messageId: ", messageId);
    */
    return admin.database().ref("/Usuarios/"+senderId+"/Chats/"+ChatId).once('value').then(snap => {
        const readChat = snap.child("read").val();
       // if (readChat) return null
        console.log("readChat: ", readChat);

//query the users node and get the name of the user who sent the message
    return admin.database().ref("/Usuarios/" + senderId).once('value').then(snap => {
        const senderName = snap.child("name").val();
        console.log("senderName: ", senderName);

//get the token of the user receiving the message
        return admin.database().ref("/Usuarios/" + receiverId).once('value').then(snap => {

            const receiverName = snap.child("name").val();
            console.log("receiverName: ", receiverName);

            const token = snap.child("token").val();
            console.log("token: ", token);

//we have everything we need
//Build the message payload and send the message
            console.log("Construction the notification message.");
            const payload = {
                data: {
                    data_type: "direct_message",
                    title: "Nueva conversación de " + senderName,
                    message: "Selecciona para ver los mensajes",
                }
            };

            return admin.messaging().sendToDevice(token, payload)
                .then(function(response) {
                    return console.log("Successfully sent message:", response);
                })
                .catch(function(error) {
                    return console.log("Error sending message:", error);
                });
        });
    });
});
});

I use this part of code to get the read value but always the records of firebase function tells me that it gets null value
Part of code to get the boolean value from "read":
admin.database().ref("/Usuarios/"+senderId+"/Chats/"+ChatId).once('value').then(snap => {
            const readChat = snap.child("read").val();
           // if (readChat) return null
            console.log("readChat: ", readChat);

A:

snap.val() will return an object so you can object and store it in a variable and try access it or otherwise try like below
admin.database().ref("/Usuarios/"+senderId+"/Chats/"+ChatId).once('value')
.then(snap => {
        if(snap.numChildren() === 0) // check for no data available
        snap.child("read").val(); // instead of this line write like below
        const readChat =  **snap.val()[read];** or **snap.val().read**
       // if (readChat) return null
        console.log("readChat: ", readChat);
})

// Considering this your structure
---user
-----senderId
--------Chats
-----------ChatId
---------------read: true

the above code will do


Q:

JS array splice don't remove the index for some reason

This is the code that I'm sending :
for (var com = 0; com < 10; com++) {
        var op = [0, 1, 2, 3];
        combo = op[Math.floor(Math.random() * op.length)];
        door1[com] = combo;
        op.splice(combo, 1);
        combo = op[Math.floor(Math.random() * op.length)];
        door2[com] = combo;
        op.splice(combo, 1);
        combo = op[Math.floor(Math.random() * op.length)];
        door3[com] = combo;
        op.splice(combo, 1);
        combo = op[Math.floor(Math.random() * op.length)];
        door4[com] = combo;
        eim.print(op.toString());
}

Now when I print the op array. I should get only 1 value because I've deleted already the other indexes. with the splice.
but when I print the result 10 times. I find that some of the indexes didn't removed.
I'm trying to create 4 different combos. Each combo is different from the other one.

A:

You need to use the index of the item to remove it from the array, not the value

var door1 = {},
  door2 = {},
  door3 = {},
  door4 = {};
for (var com = 0; com < 10; com++) {
  var op = [0, 1, 2, 3];
  door1[com] = getValue(op);
  door2[com] = getValue(op);
  door3[com] = getValue(op);
  door4[com] = getValue(op);
  snippet.log(JSON.stringify(op));
  console.log(op)
}

function getValue(array) {
  var idx = Math.floor(Math.random() * array.length),
    val = array[idx];
  array.splice(idx, 1);
  return val;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


Q:

Registration necessary for new Offers schema?

Is the "Registration with Google" process that's necessary for Quick Actions also necessary to participate in the Offers schema for the new Promotions tab?

A:

Emails that include the Offer schema and that are classified as Promotions by Gmail ignore the registrations requirements.
We'll update the docs to make this clear.


Q:

add NA for a value based on a condition, with tidyverse only, R

I have age variable with very odd numbers such as 1000, 6666. Now obviously this data is bad for any analysis. I want to keep the obvious age, but want to replace weird numbers with NA. For example, 0, 1,2,3 4, ... 100, I shall keep. But from >100 I want to put them as NA. Yet, want this only with tidyverse. I looked int several functions like na_if for example but cannot achieve what I want.
This is an example of data I have. Look at row 66 and you will see what I am talking about.
age_dput <- structure(list(Age = c(63, 19, 23, 28, 40, 31, 60, 26, 35, 44,
    30, 47, 26, 45, 21, 38, 40, 28, 26, 40, 60, 33, 72, 40, 32, 32,
    43, 24, 25, 39, 50, 22, 37, 53, 51, 42, 52, 29, 19, 42, 58, 61,
    29, 26, 45, 29, 20, 26, 28, 43, 2, 42, 40, 33, 43, 53, 55, 27,
    36, 41, 30, 54, 55, 6222, 21, 26, 38, 23, 48, 29, 44, 42, 35,
    27, 28, 20, 59, 80, 35, 36, 24, 29, 34, 31, 25, 37, 30, 31, 48,
    28, 30, 65, 45, 27, 39, 29, 34, 29, 76, 40)), row.names = c(NA,
    -100L), class = c("tbl_df", "tbl", "data.frame"), problems = structure(list(
        row = c(2910L, 35958L), col = c("how_unwell", "how_unwell"
        ), expected = c("a double", "a double"), actual = c("How Unwell",
        "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
        "'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
        )), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
    )))

A:

You can use replace or if_else :
library(dplyr)
age_dput %>%
  mutate(clean_age_replace = replace(Age, Age > 100, NA_real_),
         clean_age_if_else = if_else(Age > 100, NA_real_, Age))


Q:

Generate non-obfuscated binary content for PDF files

When I open a PDF file compiled from LaTeX with a text editor (e.g. Notepad++), the content of the file is a not human readable and it looks like below, so it seems to me that the information cannot be processed by potential crawlers.

n×å9.â^ÑäùàÉ¨•”    HTÏ•ì#ò Ž–}q”mÃ¤Š9ÒrbtRšá™g—û}Açú¦nƒÖ…‡”jKœˆ FàÆµÀmþåá•N:º‚~éWF¶DX‹m#‚D˜Àm;Ñum?OŠÀÊ¢ßÎ[ÈuóõÄ÷;Ý6"-@pñÃ¤Ù(ÖXÜÕËaœyýûdRìørêÑbÎ²(\n^Øþ2Öƒ;¬÷ª»¦Òv0þ®±úßY'°³½‹%…ß¥ºíúŸKåÒì¶¶\êæñÕ_–áúª  –ò1üj9¶,Ö×VæY¼wæ¬Döð}]

Is there a possibility to generate the PDF file so that when the PDF document displays an information like "Specific detail 1", I can also find this string "Specific detail 1" in the binary content of the file when I open it with a text editor?
This is useful for example when a PDF resume is created in LaTeX and it must be automatically parsed by various text analyzers.

A:

For pdfTeX
\pdfcompresslevel = 0 %
\pdfobjcompresslevel = 0 %

For LuaTeX
\pdfvariable compresslevel = 0 %
\pdfvariable objcompresslevel = 0 %

For use with (x)dvipdfmx (XeTeX, upTeX, etc.)
\special{dvipdfmx:config z 0}
\special{dvipdfmx:config C 0x40}

For ps2pdf routes
\special{/setdistillerparams where
    {pop<</CompressPages false>>setdistillerparams}
  if
}
\special{/setdistillerparams where
    {pop<</CompressStreams false>>setdistillerparams}
  if
}


Q:

Does rsa-oaep provide or not plaintext integrity in addition to confidentiality?

My own understanding (possibly wrong of course) of RSA-OAEP encryption scheme is that it  provides plaintext integrity (in addition to confidentiality) due to MGF function which for encryption operation, applies to maskeDB sequence which value directly depends of input M (plaintext) message, and is further checked during decryption operation.    However in previous post on that subject, the answer indicated that no public key encryption scheme can satisfy INT-PTXT (nor INT-CTXT) requirements
So is it possible to have confirmation if rsa-oaep insures integrity of input symmetric session key to be encrypted or if it is recommended with rsa-oaep to encrypt a symmetric session key appended with a hash or eventually crc value for insuring integrity ?

A:

RSA-OAEP does not provide "plaintext integrity in addition to confidentiality".  By the definition of PKE, anyone with the public key can encrypt whatever plaintexts they choose.  In particular, encrypting "a symmetric session key appended with a hash or eventually crc value for insuring integrity" doesn't help.  To get integrity, there has to be something [the honest party knows which the adversary doesn't know] or [the honest party can do that the adversary can't do].


Q:

Find an item in a file in Bash

cat "test1.txt" | while read delete
do
  grep -i "$delete" test2.txt > /home/user/nodes_deleted.txt
done

It's not working. Can anyone help. It's just printing all entries in test1.txt to nodes_deleted.txt.

A:

Your  expected input and output are quite vague, but since you have asked for a custom message "no match found..", I am putting together a small shell script for this, with file1 and file2 contents as follows,
abc
bcd

and file2 as
abc_no

And the script.sh contents as,
#!/bin/bash

while IFS= read -r line
do
   capture=$(grep -i "$line" file2 2>/dev/null)

   if [ ! -z "$capture" ]
   then
       echo "$capture"
   else
       echo "$line not found"
   fi

done <file1

Running it on the command line gives output
$ bash script.sh
abc_no
bcd not found


Q:

Accessing a function's variable from another function

from threading import Thread
import time

def print_k():
    while true:
        if main.k % 2 == 1: # ditto
            print(main.k, "is even.") # <-- my problem is HERE ( Ignore all the other stuff )
        time.sleep(2)

def main():
    k = 1
    while k != 200:
        k += 1
        print k
        time.sleep(0.5)

if __name__ == '__main__':
    Thread(target=print_k).start()
    Thread(target=main).start()

in this script (example only, ignore all realistic functionality) I am trying to run main(), which adds up to 200 and prints it, and in print_k, i am printing main's variable, k.
I have an exception raised, unsurprisingly, and am wondering how i can access a separate function's variable from a different function (they are both running at the same time, by the way, hence the Threading module.)

A:

You can't print main's variable k. The whole point of local variables is that they're local. It doesn't matter whether they're running at the same time or not; they each have their own separate local environment. (In fact, if you call main 60 times, each of those 60 calls has its own local environment.)
But there are a number of things you can do.
The simplest, but generally worst, is to use global variables instead of local variables. Just add global k to the top of the main function, add some start value for k at the top level (before either thread starts), and you can now access the same global variable inside print_k.
Bundling the shared state and functions up together in a class, where both functions become methods that can access self.k, is a better solution. Passing in some kind of mutable "holder" to both main and print_k is also a better solution. Redesigning your app around explicit message passing (e.g., on a Queue.Queue) is even better.
I'll show how to do it with a class:
class KCounter(object):

    def __init__(self):
        self.k = 0

    def print_k(self):
        while True:
            if self.k % 2 == 1:
                print(self.k, "is even.")
            time.sleep(2)

    def main(self):
        self.k = 1
        while self.k != 200:
            self.k += 1
            print self.k
            time.sleep(0.5)

if __name__ == '__main__':
    kcounter = KCounter()
    Thread(target=kcounter.print_k).start()
    Thread(target=kcounter.main).start()

Now, because we're using self.k, an attribute of the KCounter instance, instead of k, a local variable, both methods see the same variable.


Q:

Is it possible to run an Asp.net web application (web forms app) from last successful build in IIS server app pool (production)

My application got some serious problems regarding to asp.net version and other Nuget miss much versions and I can't build it due to these incompatibilities. I am looking for a solution to run my app in production server from last successful compiled build.
The application has developed in asp.net version 4.0, Visual Studio 2010.
Is that possible or not? I do not have no time for rebuilding.

A:

DLL will not be created, in this case you will be able open page in browser


Q:

Unable to get the CSS :not() selector working as required

I'm a bit stumped with trying to get the CSS :not() selector to work for me in a very specific way.  I've spent a huge amount of time looking around and found some good resources like this page but in the end I had to admit defeat.  I'm hoping a more enlightened soul here will be able to help.
Basically, I want to blur some text while leaving other bits of text untouched.  Please see below for the HTML/CSS:

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

.top-hide :not(.reveal) {
    color: transparent;
    text-shadow: 0 0 10px black;
}

I would like to reveal paragraphs 1 to 5, while 6 to 8 should be blurred out. However, paragraphs 1, 2 and 5 are revealed with the others blurred out.  Could you please tell me why my CSS doesn't work and construct the correct CSS to achieve my goal.
I've also constructed a JSFiddle to demonstrate the problem I'm facing.
Many thanks

A:

Paragraph 4

Despite the paragraph having class="reveal", the selector you wrote matches the div element (and then the paragraph inherits the transparent foreground colour and the shadow).
There is no parent selector in CSS, so you can't exclude divs that contain elements with class="reveal".
The simplest solution to this would be to:

Move all the class="reveal"s to the child elements (i.e.

Paragraph 4

 and
Use a child combinator so you only hide the unrevealed children (and not the descendants): .top-hide > :not(.reveal)

A:

Hope this helps. Here you go:
HTML

Paragraph 1

Paragraph 2

Paragraph 3

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

CSS
.top-hide :not(.reveal) {
    color: transparent;
    text-shadow: 0 0 10px black;
}

.top-hide .reveal, .top-hide .reveal *{
    color: black;
    text-shadow: none;
}

Updated JSFIDDLE


Q:

My networking service is not getting is failing in lubuntu

I have been trying to start networking service, but its not working. I am getting the below error.I tried many ways but none worked.
root@cerberos:~# service networking restart
Job for networking.service failed because the control process exited with error code. See "systemctl status networking.service" and "journalctl -xe" for details.

After entering systemctl command I am getting this :
● networking.service - Raise network interfaces
   Loaded: loaded (/lib/systemd/system/networking.service; enabled; vendor preset: enabled)
  Drop-In: /run/systemd/generator/networking.service.d
           └─50-insserv.conf-$network.conf
   Active: failed (Result: exit-code) since Thu 2019-04-04 14:47:36 UTC; 5min ago
     Docs: man:interfaces(5)
  Process: 749 ExecStart=/sbin/ifup -a --read-environment (code=exited, status=1/FAILURE)
  Process: 746 ExecStartPre=/bin/sh -c [ "$CONFIGURE_INTERFACES" != "no" ] && [ -n "$(ifquery --read-environment --list --exclude=lo)" ] && udevadm settle (code=exited
 Main PID: 749 (code=exited, status=1/FAILURE)

Apr 04 14:47:36 cerberos systemd[1]: Starting Raise network interfaces...
Apr 04 14:47:36 cerberos ifup[749]: Cannot find device "eth0"
Apr 04 14:47:36 cerberos ifup[749]: Failed to bring up eth0.
Apr 04 14:47:36 cerberos systemd[1]: networking.service: Main process exited, code=exited, status=1/FAILURE
Apr 04 14:47:36 cerberos systemd[1]: Failed to start Raise network interfaces.
Apr 04 14:47:36 cerberos systemd[1]: networking.service: Unit entered failed state.
Apr 04 14:47:36 cerberos systemd[1]: networking.service: Failed with result 'exit-code'.
lines 1-17/17 (END)

The below configuration file of /etc/network/interfaces gives me this.
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# Source interfaces
# Please check /etc/network/interfaces.d before changing this file
# as interfaces may have been defined in /etc/network/interfaces.d
# See LP: #1262951
source /etc/network/interfaces.d/*.cfg

and the content of /etc/network/interfaces.d/ shows

uto eth0
iface eth0 inet static
address 10.4.0.2
netmask 255.255.255.0
gateway 10.4.0.1
dns-nameservers 10.4.1.12

Actually I am unable to understand why ifup is unable to find eth0 device and how can make it work?

A:

If I'm understanding your problem correctly, you need to do this...
Change /etc/network/interfaces to look like this...
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback

# Source interfaces
# Please check /etc/network/interfaces.d before changing this file
# as interfaces may have been defined in /etc/network/interfaces.d
# See LP: #1262951
#    source /etc/network/interfaces.d/*.cfg

#    and the content of /etc/network/interfaces.d/ shows

#   auto eth0
#    iface eth0 inet static
#    address 10.4.0.2
#    netmask 255.255.255.0
#    gateway 10.4.0.1
#    dns-nameservers 10.4.1.12

Then go to the NetworkManager GUI, create a new Wired Connection, set it for manual addressing, and enter the above static info there. Here's what it should look like... mine will look a little different than yours, as I'm on 18.10, but you'll get the idea...


Q:

Can't reload app from android device

I'm trying to reload the app directly from my phone.
I click on this button but nothing is happen.

A:

Another way is to use adb command line on your terminal.
Reload change:
adb shell input text rr

Show dev menu:
adb shell input keyevent 82

A:

Hi you can shake your device to display developer menu on your device. And then you can choose reload to reload your app or enable live reload to automatically reload when you make some changes on your code. Looks like this.


Q:

How to remove characters before and including an underscore?

In bash scripting what's an efficient way to do the following please?
var="fooo_barrrr"

What is the best way to remove all characters before and including the '_'  so that var becomes "barrrr" please?

A:

Using Parameter Expansion:
$ var="fooo_barrrr"
$ echo ${var#*_}
barrrr

To change the var itself, var=${var#*_}.
Note this removes up to the first _:
$ var="fooo_barrr_r"
$ echo ${var#*_}
barrr_r

If you wanted to remove up to the last one, you would need to use ## instead:
$ var="fooo_barrr_r"
$ echo ${var##*_}
r

See some alternatives:
With sed:
$ sed 's/^[^_]*_//' <<< "foo_barrrr_r"
barrrr_r

With awk:
$ awk 'gsub(/^[^_]*_/,"")1' <<< "foo_barrrr_r"
barrrr_r

With grep:
$ grep -oP '[^_]*_\K.*' <<< "foo_barrrr_r"
barrrr_r

In all cases, to store the new value in the same var, do var=$(command <<< "$var").


Q:

How to get all assembly references using Mono.Cecil?

I'm using Mono.Cecil to inspect a portable class library I've built. I'm wondering how to get all of the referenced assemblies after I read the DLL in, much like how ILSpy does it. Can anyone help? Here is the code I have so far:
var module = ModuleDefinition.ReadModule(assemblyPath);

// No `References` or `GetReferences()` property on the
// resulting object, so I'm confused about what to do here

A:

Never mind, I'm blind. You can do this via the AssemblyReferences property:
var references = module.AssemblyReferences;


Q:

Different approaches for partial image derivation

I know there are different ways for partial derivation of an image, among others: Sobel kernel, LoG, Prewitt and so on.
But the simplest one is the central difference:
$$
  \frac{d}{dx} f(x) \approx \frac{f(x+1) - f(x-1)}{2} \longrightarrow 0.5[1\ 0\ -1]
$$
Which means convolving the image with above matrix.
Assume the image looks like this:
$$
        I(x,y) =
        \left(
        \begin{matrix}
        0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
        0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
        0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\
        0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\
        0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\
        0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\
        0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
        0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
        \end{matrix}
       \right) \in \mathbb R^{8\times8}
$$
Convolving this image with matrix $$G_x = 0.5\ [1\ 0\ -1] \in \mathbb R^{1 \times 3} $$ results in:
$$
\lvert I \ast G \rvert =
        \left(
        \begin{matrix}
 0 & 0 &  0 & 0 & 0  & 0 & 0 & 0 \\
 0 & 0 &  0 & 0 & 0  & 0 & 0 & 0 \\
 0 & 0.5 & 0.5 & 0 & 0 & 0.5 & 0.5 & 0 \\
 0 & 0.5 & 0.5 & 0 & 0 & 0.5 & 0.5 & 0 \\
 0 & 0.5 & 0.5 & 0 & 0 & 0.5 & 0.5 & 0 \\
 0 & 0.5 & 0.5 & 0 & 0 & 0.5 & 0.5 & 0 \\
 0 & 0 &  0 & 0 & 0  & 0 & 0 & 0 \\
 0 & 0 &  0 & 0 & 0  & 0 & 0 & 0 \\
        \end{matrix}
       \right)
$$
The cells containing $0.5$ are the edges of the image in $x$ direction.
Know assume we would extend our filter $G_x$:
$$
G_x = 0.5
\left(
\begin{matrix}
 1 & 0 & -1 \\
 1 & 0 & -1  \\
 1 & 0 & -1 \\
\end{matrix}
\right) \in \mathbb R^{3 \times 3}
$$
Now convolving this filter with our image results to:
$$
\lvert I \ast G \rvert =
        \left(
        \begin{matrix}
 0 & 0 & 0 & 0 & 0  & 0 & 0 & 0 \\
 0 & 1 & 1 & 0 & 0  & 1 & 1 & 0 \\
 0 & 2 & 2 & 0 & 0 & 2 & 2 & 0 \\
 0 & 3 & 3 & 0 & 0 & 3 & 3 & 0 \\
 0 & 3 & 3 & 0 & 0 & 3 & 3 & 0 \\
 0 & 1 & 1 & 0 & 0  & 1 & 1 & 0 \\
 0 & 2 & 2 & 0 & 0 & 2 & 2 & 0 \\
 0 & 0 &  0 & 0 & 0  & 0 & 0 & 0 \\
        \end{matrix}
       \right)
$$
Now instead of one unique number for edge like we had before with $0.5$ we get a gradient in $x$ direction $[1, 1, 2, 2, 3, 3, 2, 2, 1, 1]$.
Now my Questions:
1) Which approach is better, convolving the image with a $\mathbb R^{1 \times 3}$ -Filter or with a $\mathbb R^{3 \times 3}$-Filter?
2) And why is one better than the other?
Thanks

A:

Non-zero pixels after derivation provide you with two informations: a potential location (where the pixel is), and a potential strength (in magnitude) of an edge-pixel. Linear edge detectors are linear filters. A $3\times3$ kernel adds a smoothing effect in the orthogonal direction. It will favor edges with a certain spatial extend, over short-lengthed isolated pixels that do not qualify for real-edges. In other words, an isolated $[0,1,0]^T$, a duplet $[1,1,0]^T$ will be affected a smaller magnitude than three vertical ones $[1,1,1]^T$ after a $3\times3$ kernel.
In different words, the Prewitt  $3\times 3$ separable gradient/smoothing kernel can be written as a (Cartesian) product of two $3\times 1$ and $1\times 3$ kernels:
$$
\left(
\begin{matrix}
 1 & 0 & -1 \\
 1 & 0 & -1  \\
 1 & 0 & -1 \\
\end{matrix}
\right) =
\left(
\begin{matrix}
 1  \\
 1   \\
 1 \\
\end{matrix}
\right) \times \left(
\begin{matrix}
 1 & 0 & -1 \\
\end{matrix}
\right)
$$
This scheme can be generalized: any smoothing filter in one direction, combined with any derivative in the other (orthogonal) direction, can form an horizontal or vertical square/rectangular image edge detector.  You can find a source in Smoothed Differentiation Filters for Images, Meer and Weiss, 1992:

For the two-dimensional case we restrict ourselves to square
  neighborhoods. In such neighborhoods it is always possible to define a
  separable two-dimensional orthonormal basis built by the Cartesian
  product of two identical one-dimensional bases.

and in Derivative-based Operations or the wiki page Image derivatives
.
If you have clear vertical edges, with same pixel amplitudes, little noise, the $1\times 3$ filter will do the job. Otherwise, good $3\times 3$ are almost always preferable. An image is really a 2D thing, and processing it through 1D tools often wastes information.


Q:

URI formats are not supported in webclient c#

I call my service as you can see like this :
  public ReceptionView ReceptionViewByReceptionId(string receptionId)
    {
        ClientRequest.Headers["Content-type"] = "application/json";
        ClientRequest.Encoding = System.Text.Encoding.UTF8;
        string result = ClientRequest.DownloadString("http://localhost:1111" + " /ReceptionService.svc/ReceptionViewByReceptionId/" + receptionId);

        var javascriptserializer = new JavaScriptSerializer();
        return javascriptserializer.Deserialize<ReceptionView>(result);
    }

But i get this error in DownloadString:
{"URI formats are not supported."}

my service works ok and when i call my service by browser like this :
http://localhost:1111/ReceptionService.svc/ReceptionViewByReceptionId/1

I get the expected result .but in my application i can't
My service interface
 [WebGet( UriTemplate = "/ReceptionViewByReceptionId/{receptionId}", RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]

    ReceptionView ReceptionViewByReceptionId(string receptionId);

As a note my function worked before without any error ,but today suddenly returns this error.
My fiddler result in browser:

A:

The problem was the space here " /Reception as you can see in the url
string result = ClientRequest.DownloadString("http://localhost:1111" + " /ReceptionService.svc/ReceptionViewByReceptionId/" + receptionId);

I removed that and every thing worked fine .


Q:

what about a newbie tag ?

I'm torn. I'd love to have a newbie tag to browse and learn things at my level, but I also realize that sometimes is not easy to say what is "newbie" and what is not. Also it would require a lot of effort to tag what it's already in the database, I guess.
What do you think about it ?

A:

Definitely not.  Not only is 'newbie' very informal, but we already have [beginner], which is (unfortunately for those trying to make the site more professional-oriented) the fifth-most popular tag.
The following was true Oct 3 '10. The tag has since been removed.
You can read all 47 questions currently tagged [beginner] here: https://electronics.stackexchange.com/questions/tagged/beginner.  This URL has a few features which were not present in Chiphacker's SE 1.0 platform, such as a wiki, an FAQ, an About page, and various ways of viewing users and questions in the tag.  If you were interested in tagging these questions, perhaps you'd be interested in drafting these pages?  The place to discuss that would be a separate question here on meta.  See this question on meta.SO for an example of how this was done for the C tag.

A:

No. Tags should give an indication about the question's topic(s), nothing else. That's the reason the homework tag is deprecated too, for instance. If you want to indicate that you're a beginner in order to get answers at your level of knowledge, say so in the question.
If there would be any need to have an indication about difficulty level, like the number of chef's caps in kitchen recipes, that should be something separate, but I don't advocate this. Like Olin says levels can be different for different answers, and there's nothing wrong with that; answers should be as widely useful as possible. So if you're lost at the second sentence of an answer, move on to the next.
After all, if you're looking up questions it will be based on "555" rather than "beginner".
PS: I notice there are 25 questions tagged learning, I think that tag should go as well.


Q:

A question in Banach space

Given $A\in\Bbb R^{m\times n}$, define $$\gamma_2(A)=\min_{XY=A}\max_{i,j}\|x_i\|_{\ell_2}\|y_j\|_{\ell_2}$$ where rows of $X$,columns of $Y$ given by $\{x_i\}_{i=1}^m,\{y_j\}_{j=1}^n$ respectively.
Where could I find a reference for fact that $$\gamma_2^2(A)\leq\| A\|_{\ell_1^n\rightarrow\ell_{\infty}^m}rank(A)?$$
Should this be  $$\gamma_2^2(A)\leq\| A\|_{\ell_1^n\rightarrow\ell_{\infty}^m}^2rank(A)?$$
Above is lemma 4.2 in http://www2.mta.ac.il/~adish/Pubs/Papers/complexity_matrices.pdf
What is terminology for $\gamma_2(A)$ in literature?
posted https://math.stackexchange.com/questions/1196950/a-question-in-banach-space

A:

Given a linear operator $A$ from a Banach space $E$ to a Banach space $F$, the quantity $\gamma_2(A)$ is the infimum (actually, it is a minimum) of $\|X \| \cdot \|Y\|$, where the minimum is over all operators $Y: E\to H$, $X: H \to F$ s.t. $XY=A$ with $H$ a Hilbert space.  This agrees with your definition when $E= \ell_1^n$ and $F= \ell_\infty^m$. The quantity $\gamma_2(\cdot)$ is an important operator ideal norm; it is discussed in many books on Banach space theory. The most elementary of those is the book of Albiac and Kalton (section 7.3), but they do not use the notation $\gamma_2(\cdot)$.  Or look at Diestel, Jarchow, Tonge or Tomczak-Jaegermann. The second form for your inequality is the correct one (after all, it must be homogeneous) and is immediate from the ideal property of $\gamma_2(\cdot)$ and John's theorem that the isomorphism constant of an $n$-dimensional Banach space to $\ell_2^n$ is at most $\sqrt{n}$.


Q:

How to do this: After every space key press, create a new span element and put caret there?

How to put the cursor on a div and a certain position of that div.
Try to put it with setStar but the cursor is located at the beginning and I do not want
the error is:  {"message": "Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset}

let written = '';

document.getElementById('parent').addEventListener('keypress', function(e) {
  var palabra = written;
  written += String.fromCharCode(e.which);

  if (e.which === 32) {
    var element = document.getElementById("parent");
    var doc = element.ownerDocument || element.document;

    var win = doc.defaultView || doc.parentWindow;
    // seleccionamos el nodo activo
    var sel = window.getSelection();

    if (sel.rangeCount > 0) {
      var range = win.getSelection().getRangeAt(0);
      const index = range.startOffset;
      // range.setStart(document.getElementById(window.getSelection().anchorNode.parentNode.id), index);
    }
    sel.focusNode.textContent = sel.focusNode.textContent.replace(palabra, "");

  }
})
#parent>div {
  border-color: yellow;
  float: left;
}

.root {
  padding-right: 1px;
}

Que

word

Lorem

Ipsum

I want to put in the node document.getElementById(window.getSelection().anchorNode.parentNode.id)
and your position of node is saved in the variable index
Example:
When I type 'hi' and I press spacebar should this be the result

A:

This is the result of a while of research and coding, hope it helps you :)
For other people: I changed the
 to  after  confirming with the question asker if it was okay.

var newString = "";

document.body.onkeyup = function(e) {
  newString += String.fromCharCode(e.keyCode);
  if (e.keyCode == 32) {
    var parent = document.getElementById("parent");
    var targetelement = parent.childNodes[parent.childNodes.length - 1];
    var div = document.createElement("SPAN");
    div.className = "root";
    div.id = parseInt(document.getElementsByClassName("root")[document.getElementsByClassName("root").length - 1].id) + 1;
    div.contenteditable = false;
    div.innerHTML = " ";
    var beforeelement = parent.childNodes[parent.childNodes.length - 1];
    beforeelement.innerHTML = beforeelement.innerHTML.substring(0, 1) + beforeelement.innerHTML.substring(1).replace(' ', '');
    document.getElementById("parent").appendChild(div);
    console.log("appended!");

    var selectionrange = document.createRange();
    var selection = window.getSelection();
    selectionrange.setStart(targetelement, 1);
    selectionrange.collapse(true);
    selection.removeAllRanges();
    selection.addRange(selectionrange);
  }
}
#parent>div {
  border-color: yellow;
  float: left;
}

.root {
  padding-right: 1px;
}

  Que
  word
  Lorem
  Ipsum


Q:

Watir with Tor browser

I've been playing with Watir and Tor browser and I can't get them to work.
The correct browser opens, however, I'm unable to open a website.
My code:
Selenium::WebDriver::Firefox.path = '\path\Tor Browser\Start Tor Browser.exe'
driver = Selenium::WebDriver.for :firefox
browser = Watir::Browser.new :firefox, :driver => driver

This results in a message box popping up, which says:

Your Firefox profile cannot be loaded. It may be missing or inaccessible.

The correct browser also opens up, however, the website doesn't.
I've also tried:
Selenium::WebDriver::Firefox.path = '\path\Tor Browser\Browser\firefox.exe'
driver = Selenium::WebDriver.for :firefox
browser = Watir::Browser.new :firefox, :driver => driver

With this, the message box doesn't appear, but still, the website is not loaded.
I'm not sure, if the problem is in my code or in the browser.
Thank you very much for any help!

A:

Start Tor then run this, assuming your socks port is 9050
require 'watir-webdriver'

profile = Selenium::WebDriver::Firefox::Profile.new
profile['network.proxy.socks'] = "127.0.0.1"
profile['network.proxy.socks_port'] = 9050
profile['network.proxy.type'] = 1
$browser = Watir::Browser.new :firefox, :profile => profile

$browser.goto "whatsmyip.org"


Q:

How to build a form without using tables in asp.net?

i need a three columns form, in the past using tables was easy but now using divs i dont know from where to start... im googling but the css i found doesnt work for me, any help or link will be appreciated

A:

a sample row  which shows one of the ways u can do this.

here's some other links which might help http://snook.ca/archives/html_and_css/getting_your_di


Q:

Python BigQuery Storage. Reading multiple streams in parallel

I have the following toy code:
import pandas as pd
from google.cloud import bigquery_storage_v1beta1
import os
import google.auth

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]='key.json'
credentials, your_project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
bq_storage_client = bigquery_storage_v1beta1.BigQueryStorageClient(credentials=credentials)

table_ref = bigquery_storage_v1beta1.types.TableReference()
table_ref.project_id = "bigquery-public-data"
table_ref.dataset_id = "libraries_io"
table_ref.table_id = "versions"

parent = "projects/{}".format(your_project_id)
session = client.create_read_session(
    table_ref,
    parent,
    format_=bigquery_storage_v1beta1.enums.DataFormat.ARROW,
    sharding_strategy=(bigquery_storage_v1beta1.enums.ShardingStrategy.BALANCED),
)

reader1 = bq_storage_client.read_rows(bigquery_storage_v1beta1.types.StreamPosition(stream=session.streams[0]), timeout=100000)
reader2 = bq_storage_client.read_rows(bigquery_storage_v1beta1.types.StreamPosition(stream=session.streams[1]), timeout=100000)

df = pd.concat([reader1.to_dataframe(session),reader2.to_dataframe(session)])
df

I used BALANCED ShardingStrategy to initiate more than 1 stream which can be read independently.
BigqueryStorage documentation says:

However, if you wanted to fan out multiple readers you could do so by
  having a reader process each individual stream.

I initiated two readers, one for each of streams in the session. Afterwards, two dataframes (1 created from each reader) are concatenated into single one. However this approach doesn't give any speed up compared to the LIQUID ShardingStrategy.
I am trying to make both readers read rows in parallel. However I failed to find anything about parallel stream reading in library documentation.
The questions are:
1) Does BugQuery Storage provide any native means for reading multiple streams simultaneously if BALANCED ShardingStrategy is chosen?
2) What is best way to read stream in parallel? Do I need to use multiprocessing or asyncio for that?
3) I would appreciate if anyone could provide any basic example on parallel streams reding

A:

You are missing the requested_streams value:
n_streams = 2
session = client.create_read_session(
    table_ref,
    parent,
    requested_streams=n_streams,
    format_=bigquery_storage_v1beta1.enums.DataFormat.ARROW,
    sharding_strategy=(bigquery_storage_v1beta1.enums.ShardingStrategy.BALANCED),
)

You can concat the dataframes in one line:
readers = []
for i in range(n_streams):
    stream = session.streams[i]
    position = bigquery_storage_v1beta1.types.StreamPosition(stream=stream)
    reader = bqstorageclient.read_rows(position)
    readers.append(reader)
df = pd.concat([reader.to_dataframe(session) for reader in readers])

Hope this helps.


Q:

Any DI Frameworks that convert from string to constructor Types?

I'm just wondering if there is a DI Framework for .net that handles string-to-some type conversion for me?
Basically I have this constructor:
public MyImplTwo(bool someParam)

and a string like "true" or "1". I've tried Unity, but this throws an error saying that no constructor with the signature MyImplTwo(string) exists:
container.RegisterType<MyImplBase, MyImplTwo>(new InjectionConstructor(new object[] {"true"}));

Is there one? Essentially I mainly need a wrapper around Activator.CreateInstance, so I'm looking for the simplest IoC that works. On the other hand, I wouldn't mind the extra functionality of the "big" containers as long as the above works.
Edit: I can get the desired type as a string as well, and if required also the argumentName. The things I cannot do is a) have a container-specific config file (configuration is done through a database) and b) decorate the classes that should be resolved with any attributes as I don't control them.

A:

Based on the edit in your question, I'd say Castle Windsor should be able to address your needs.
Using Windsor's XML configuration, you can specify primitive parameter values, e.g.
<component id="myImp"
           service="MyImplBase, MyAssembly"
           type="MyImplTwo, MyOtherAssembly">
    <parameters>
        <someParam>true</someParam>
    </parameters>
</component>

Windsor doesn't require you to put the XML configuration in an application configuration file. You can read it from any XML stream, including from a database. Here's a code snippet that shows how to read XML configuration from an XML string:
string myXml = // read XML from a custom resource...

var container = new WindsorContainer();
container.Install(
    new ConfigurationInstaller(
        new XmlInterpreter(
            new StaticContentResource(myXml))));

You can now use container to resolve MyImplBase and it will return an instance of MyImplTwo with someParam set to true.
Also with Windsor you can pass dependencies as strings to the fluent registration API, and conversion subsystem in Windsor will convert them for you, which completely eliminates need for any form of XML config.


Q:

Is it possible to get text from a website in terminal

I would like to get a timetable from my schools website and use it in a script to set automatic alerts but I don't know how.
So it seems my school uses FullCalendar to set the timetable so the times aren't HTML tags in the .html file.

A:

As we don't have the real website you want to scrape data from, and website scraping is always different if you don't have some standardized API, it's not possible to give a 100% working solution. But I'll try to explain a way to get to your information.
fullcalender.io is Javascript based, the events are set up as Javascript object or may be imported from json format. If the latter is the case, you can easily just download the ready json file that is referred to somewhere in the Javascript source code. Regarding parsing json, there are many Questions and Answers around here.
If it's set up as a Javascript Object, you can just parse the .js file or if it's included in a html <script> tag, parse the html for the $('#calendar').fullCalendar( object.
We can use curl to get the website, then extract the information using e.g. awk.

I made a small script to get the object for the fullcalender.io Basic View demo. Your script may look similar.
curl -s https://fullcalendar.io/releases/fullcalendar/3.9.0/demos/basic-views.html \
  | awk '/\.fullCalendar\(\{/{s=1; print "{"; next;};
         /\}\)\;/{s=0};
         s{print};
         END{print "}";}'

Explanation:

/\.fullCalendar\(\{/{s=1; print "{"; next;}; Searches .fullCalender({ and if found sets variable s=1 and prints {
/\}\)\;/{s=0}; Searches for )}; and sets variable s=0
s{print}; prints the line if s is set and not 0.
END{print "}";}' prints the } at the end.

Output:
{
  header: {
    left: 'prev,next today',
    center: 'title',
    right: 'month,basicWeek,basicDay'
  },
  defaultDate: '2018-03-12',
  navLinks: true, // can click day/week names to navigate views
  editable: true,
  eventLimit: true, // allow "more" link when too many events
  events: [
    {
      title: 'All Day Event',
      start: '2018-03-01'
    },
    {
      title: 'Long Event',
      start: '2018-03-07',
      end: '2018-03-10'
    },
    {
      id: 999,
      title: 'Repeating Event',
      start: '2018-03-09T16:00:00'
    },
    {
      id: 999,
      title: 'Repeating Event',
      start: '2018-03-16T16:00:00'
    },
    {
      title: 'Conference',
      start: '2018-03-11',
      end: '2018-03-13'
    },
    {
      title: 'Meeting',
      start: '2018-03-12T10:30:00',
      end: '2018-03-12T12:30:00'
    },
    {
      title: 'Lunch',
      start: '2018-03-12T12:00:00'
    },
    {
      title: 'Meeting',
      start: '2018-03-12T14:30:00'
    },
    {
      title: 'Happy Hour',
      start: '2018-03-12T17:30:00'
    },
    {
      title: 'Dinner',
      start: '2018-03-12T20:00:00'
    },
    {
      title: 'Birthday Party',
      start: '2018-03-13T07:00:00'
    },
    {
      title: 'Click for Google',
      url: 'http://google.com/',
      start: '2018-03-28'
    }
  ]
}

You can then parse the JS object to a JSON object using python and demjson:
Install demjson:
pip3 install demjson

and then run this:
curl -s https://fullcalendar.io/releases/fullcalendar/3.9.0/demos/basic-views.html \
  | awk '/\.fullCalendar\(\{/{s=1; print "{"; next;};
         /\}\)\;/{s=0};
         s{print};
         END{print "}";}' \
  | python3 -c "import demjson, sys, json; print(json.dumps(demjson.decode('\n'.join(sys.stdin.readlines()))));" \
  | jq ".events"

From here it should be fairly easy to move on using jq. Of course instead of bash and jq you can do the whole thing in Python.


Q:

Handling Leap Day, both when it exists and when it doesn't

I have a data set that is supplied via CSV.  Whenever that csv is supplied in a leap year it contains the 29th of February and whenever it is supplied in a non-leap year it does not.  I only get a single year of data and I have to copy that data forward for X amount of years.
I need to remove the 29th if it exists in years it shouldn't and create it if it doesn't exist in the years it should.
EDIT:
I am going back to the beginning so that the entire picture is presented.
I am given 3 csv files that I utilize to make a single dataframe:

df0 contains 4 columns that I require to filter and create a final dataframe
from df1
df2 contains 3 columns that I require to filter and create a final
dataframe from df1
df1 is the dataframe that contains a single year
of data (but it is initially missing the year, I have to add it from df0 based on start date)

df0 Partitioned for the correct columns looks like this:
+------------+------------+--------------------+--------------------+
| project_id | start_date | degredation_factor |      snapshot      |
+------------+------------+--------------------+--------------------+
| pid1       | 1/1/2021   | 0.60%              | 2/28/2020 18:35:46 |
| pid2       | 1/1/2024   | 0.40%              | 2/28/2020 18:35:46 |
+------------+------------+--------------------+--------------------+

*note this could have 20+ unique projects in it
df2 looks like this :
+------------+---------------+--------------------+
| project_id | duration_year |      snapshot      |
+------------+---------------+--------------------+
| pid1       |            10 | 2/28/2020 18:35:46 |
| pid1       |            15 | 2/28/2020 18:35:46 |
| pid2       |            20 | 2/28/2020 18:35:46 |
| pid2       |            25 | 2/28/2020 18:35:46 |
+------------+---------------+--------------------+

*can contain multiple lines per project, need only the line with the longest duration
df1 looks like this:
+-----+-------+------+-------------+--------------------+------------+------+
| day | month | hour | hourly_rate |      snapshot      | project_id | year |
+-----+-------+------+-------------+--------------------+------------+------+
|   1 |     1 |    1 |      123.43 | 2/28/2020 18:35:46 | pid1       | 2021 |
|   1 |     1 |    2 |      120.11 | 2/28/2020 18:35:46 | pid1       | 2021 |
| ... |   ... |  ... |         ... | ...                | ...        |  ... |
|  31 |    12 |   24 |      123.43 | 2/28/2020 18:35:46 | pid1       | 2021 |
+-----+-------+------+-------------+--------------------+------------+------+

*every day, every hour, 1 year
I have to take that 1 year dataframe and append to it all the forward years for every project.  so in the case of pid1 I need to append 2022 - 2036 and I need to perform the degradation on the hourly rate for 2022 and beyond ( formula : hourly_rate  * (1 - (float(row.loc['degradation_factor_solar'].strip('%')) * (year# - 1)/ 100))
my code previously (which was doing all of the appending and calculations, except it had the 29th of February in all years and hence the problem):
        df0_partition_1 = df0[['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']]
        df0_partition_2 = df0_partition_1.groupby(
            ['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']).size().reset_index()
        df2_partition_1 = df2.groupby(['project_id', 'snapshot_datetime'])['duration_year'].max().reset_index()
        df_merge = pd.merge(df0_partition_2, df2_partition_1, on=['project_id', 'snapshot_datetime'], how='left')
        df_parts = df_merge[
            ['project_id', 'start_date', 'duration_year', 'degradation_factor', 'snapshot_datetime']].dropna()

        for index, row in df_parts.iterrows():
            df1_filtered = df1[(df1['project_id'] == row['project_id']) &
                               (df1['snapshot_datetime'] == row['snapshot_datetime'])]
           df1_filtered['year'] = pd.to_datetime(row['start_date']).year
            df1_filtered.reset_index(inplace=True, drop=True)
            df1_filtered.drop(columns='project_name', inplace=True)
            df_stg_1 = df1_filtered.copy()  # deep=True)
            df_stg_2 = pd.DataFrame()
            df_final = pd.DataFrame()

            for y in range(1, int(row['duration_year']) + 1):
                year = df1_filtered['year'] + (y - 1)
                hourly_production = df1_filtered['hourly_production']
                df_stg_1['year'] = year
                df_stg_1['hourly_production'] = hourly_production * (
                        1 - (float(row.loc['degradation_factor_solar'].strip('%')) * (y - 1)/ 100))
                df_stg_2 = df_stg_2.append(df_stg_1)
            df_final = df1_filtered.append(df_stg_2)

this was giving me all of the years, but it presented the leap year problem when the data was input on a leap year.  The 29th exists and it gets populated into every year.  On Non-leap years when they provide the data it will lack the leap day and thus the leap day would have to be created from the 28th.
This is now a partial duplication of a previous post, my apologies.  I needed to expand to show the entire issue and why I am trying to solve what I am trying to solve.
I am happy to create the final dataframe in a different manner if it gets rid of this issue for leap day.
EDIT 2:
I tried df_stg_3.drop(df_stg_3[(df_stg_3['year'] % 4 != 0) & (df_stg_3['month'] == 2) & (df_stg_3['day'] == 29)].index)
for the drop is not actually working, I had the wrong file.

A:

Here is where I ended up.  It may not be the most elegant, but it does work.
        df0_partition_1 = df0[['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']]
        df0_partition_2 = df0_partition_1.groupby(
            ['project_id', 'start_date', 'degradation_factor', 'snapshot_datetime']).size().reset_index()
        df2_partition_1 = df2.groupby(['project_id', 'snapshot_datetime'])['duration_year'].max().reset_index()
        df_merge = pd.merge(df0_partition_2, df2_partition_1, on=['project_id', 'snapshot_datetime'], how='left')
        df_parts = df_merge[
            ['project_id', 'start_date', 'duration_year', 'degradation_factor_solar', 'snapshot_datetime']].dropna()

        for index, row in df_parts.iterrows():
            df1_filtered = df1[(df1['project_id'] == row['project_id']) &
                               (df1['snapshot_datetime'] == row['snapshot_datetime'])]
            dest_key_name = 'dw/project_8760/{}/{}/{}'.format(row['project_id'], file_partition_time, 'df.csv')

            df1_filtered['year'] = pd.to_datetime(row['start_date']).year
            df1_filtered.reset_index(inplace=True, drop=True)
            df1_filtered.drop(columns='project_name', inplace=True)
            df_stg_1 = df1_filtered.copy()
            df_stg_2 = pd.DataFrame()
            df_final = pd.DataFrame()

            for y in range(2, int(row['duration_year']) + 1):
                year = df1_filtered['year'] + (y - 1)
                hourly_production = df1_filtered['hourly_production']
                df_stg_1['year'] = year
                df_stg_1['hourly_production'] = hourly_production * (
                        1 - (float(row.loc['degradation_factor'].strip('%')) * (y - 1)/ 100))
                df_stg_2 = df_stg_2.append(df_stg_1)
            df_stg_3 = df1_filtered.append(df_stg_2)

            if df1_filtered[(df1_filtered['month'] == 2) & (df1_filtered['day'] == 29)].empty is False :
                filter_final_1 = df_stg_3[(df_stg_3.year % 4 != 0) & (df_stg_3.month == 2)]
                filter_final_2 = filter_final_1[(filter_final_1.day == 29)]
                df_final = pd.concat([df_stg_3, filter_final_2, filter_final_2]).drop_duplicates(keep=False)
            else:
                df_stg_3_filtered = df_stg_3[(df_stg_3.year % 4 == 0) & (df_stg_3.month == 2)]
                df_stg_4 = df_stg_3_filtered[(df_stg_3_filtered.day == 28)]
                df_stg_4['day'] = 29
                df_final = pd.concat([df_stg_3, df_stg_4])
                df_final.sort_values(by=['year', 'month', 'day', 'hour'])


Q:

How to set default browser to Internet Explorer in R?

I am rarely using IE for web browsing, so would like R help opens in it when calling help functions. Currently it opens my default web browser (Chrome). I would like to leave system-wide default browser intact, but change browser only for R.
Is it possible?
I found some texts about how to edit Rprofile.site, but failed to deduce how to set for IE and Windows.

A:

A solution could be to create a file named .Rprofile in your home directory and put the following line:
 options(browser="path/to/IE")

Of course, you have to replace the path/to/IE part to the actual path to the IE executable (could be something like C:\\Program Files\\Internet Explorer\\iexplore.exe\).
Restart R and try for instance browseURL("www.google.com") to see if it has taken effect.


Q:

Why does f# dot operator have such a low precedence

The precedence of F#'s member selection dot (.) operator as used in
System.Console.WriteLine("test")

has a lower precedence than [space] such that the following
ignore System.Console.WriteLine("test")

must be written explicitly as
ignore (System.Console.WriteLine("test"))

though this would be the intuition from the notion of juxtaposed symbols. Having used CoffeeScript, I can appreciate how intuitive precedence can serve to de-clutter code.
Are there any efforts being made to rationalize this kerfuffle, perhaps something along the lines that incorporated the "lightweight" syntax of the early years?
==============
Upon review, the culprit is not the "." operator but the invocation operator "()", as in "f()". So, given:
  type C() = class end

then the following intuitive syntax fails:
  printfn "%A" C()    <-- syntax error FS0597

and must be written thus (as prescribed by the documentation):
  printfn "%A" (C())    <-- OK

It seems intuitive that a string of symbols unbroken by white space should implicitly represents a block. In fact, the utility of juxtaposing is to create such a block.

A:

a b.c is parsed as a (b.c), not (a b).c. So there are no efforts to rationalize this - it simply is not true.


Q:

Android NDK: no archive symbol table (run ranlib)

I am updating my projects to use Android ndk 16b and it was previously using 12b (was working fine). After I updated, I am running into the following error while building the final .so:
/Users/ssk/code/client/git/thirdparty/android-ndk-r16b/android-ndk/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-androideabi/bin/ld: error: jni/../../../shared-library/SharedCommon/build/arm-linux-androideabi/lib/libSharedCommon.a: no archive symbol table (run ranlib)

This is leading to a bunch of linker errors. I tried the following answers:
Android NDK: no archive symbol table
How to run ranlib on an archive built through Android.mk?
no archive symbol table (run ranlib) while building libcryptopp.a through ndk-build
with no luck.

A:

You need to build static libraries with a GNU AR (like the one we include in the NDK, same directory as GCC). Darwin's AR is a BSD AR that does not automatically perform ranlib tasks.


Q:

How is electricity generated in A Quiet Place?

In the movie A Quiet Place, the Abbotts are using electricity to power up their light bulbs, cameras, speakers and other electrical equipment.
But it is obvious that the monsters have destroyed most of human civilizations,

Lee Abbott has been sending SOS to every country's emergency frequency but no one has responded.

Given the monsters have got super-sensitive hearing, I would imagine they have attacked all power stations and all electricity generators as well, so here comes the question:

Where do they get their electricity from?

Below is a chart I pulled from Wiki showing Electricity generation by type USA 2014:

All electricity generation methods involve heavy machinery and regular maintenance, e.g. lots of noise will be generated.

A:

Here's a screenshot from the movie showing solar panels.

A:

Solar Energy has been mentioned as a very quiet (not totally silent) source of energy. You can hear inverters humming, however, this constant low level noise seems to be the kinds of noise they ignore. They seem to react more to distinct changes in noise. FYI -
 You need inverters to turn solar's DC current to "grid compatible" AC.
Hydro-power could be easily produced and the noise would be covered up by the rushing water (as shown when they go on their favourite pass-times of fishing and waterfall-shouting). In fact, I was wondering why people aren't all living by rivers or housing up in hydroelectric plants!
Finally, wind power could be produced, the main noise here would come from high up so the creatures might well leave it alone. You don't see them constantly chasing after birds.
At 13% of the USA's current electricity mix, it should easily cover the new post-apocalyptic national load with, let's assume, 1% of the original population. Further, we can assume there is no heavy industry, server-racks, aircon or big cities to power.
There is the issue of maintenance and load balancing but we can maybe assume that this is can be automated to some extent.

A:

Generators below the ground.
The screenwriters talk about this in an interview about the original script. It didn't make it to the final cut due to time limitations.

Since you’ve thought about every aspect of this world, you probably have an answer. How is the family getting their electricity?
Scott: In the original draft, and they never really did anything with it in the final film, we had written that they have underground generators that are basically underneath the ground so they’re not producing any audible sound above ground. That was the idea behind it.


Q:

Can Applescript list all the applications placed in the dock?

I can't work out how to list all the Applications that a user has placed in the dock.
Is this possible?

A:

Try this. This is a list of the apps a person has that are persistent in the dock. What I've basically done is use system events to read the plist file into an applescript record in the pListItems variable. Then I can use applescript techniques to access the lists and records inside of pListItems.
There's lots of information in com.apple.dock so you can look at the pListItems variable and work your way through it to pull out whatever you need. For example you might want the "|bundle-identifier|" instead of the "|file-label|". Good luck.
set plistpath to (path to preferences folder as text) & "com.apple.dock.plist"

tell application "System Events"
    set plistContents to contents of property list file plistpath
    set pListItems to value of plistContents
end tell
set persistentAppsList to |persistent-apps| of pListItems

set dockAppsList to {}
repeat with thisRecord in persistentAppsList
    set end of dockAppsList to |file-label| of |tile-data| of thisRecord
end repeat

return dockAppsList


Q:

How to pass optional arguments to winform commandline

So I've written tools in the past where I pass commandline arguments to a winforms c# tool. How can I pass specific arguments which are optional.
 Static void test(string name="bill", int age=5, string location = "home")
 {
      Console.writeline (name)
      Console.writeline (age)
 }

In simple terms I would like the users to be able to call this function commandline passing age or name or both.
example...
Test name:"JOEY"
Test location:"bed" age:5
Maybe there is a recommendation for the way I write the commandline argument which I parse in a way I can pass optional arguments. Suggestions welcome.

A:

As I understand and as devdigital had suggested, you can use the Command Line Parser Library (available using NuGet).
I use it in my project in order to start the application in different states.
First you will define all your accepted parameters (with possibility to set some of them as optional, more info on library docs)
public class CommandLineArgs
{
    [Option('t', "type", Required = false, HelpText = "Type of the application [safedispatch, safenet]")]
    public string AppType { get; set; }

    [Option('c', null, HelpText = "Enable the console for this application")]
    public bool Console { get; set; }

    [Option('l', null, HelpText = "Enable the logs for this application")]
    public bool Log { get; set; }

    [Option('h', null, HelpText = "Help for this command line")]
    public bool Help { get; set; }

    [HelpOption]
    public string GetUsage()
    {
        // this without using CommandLine.Text
        //  or using HelpText.AutoBuild
        var usage = HelpText.AutoBuild(this);

        return usage.ToString();
    }
}

Next, on you Program.cs class, inside the main function you will create a CommandLineArgs object and parse the received parameters. Finally you will take the decisions depending on what parameters has been passed to you.
static void Main(string[] args)
{
var cmdArgs = new CommandLineArgs();
if (args.Length > 0 && CommandLine.Parser.Default.ParseArguments(args, cmdArgs))
    {
    // display the help
    if (cmdArgs.Help)
    {
          Utils.WriteLine(cmdArgs.GetUsage());
          Console.ReadKey();
    }

    // display the console
    if (!cmdArgs.Console)
    {
          // hide the console window
          setConsoleWindowVisibility(false, Console.Title);
    }

   // verify other console parameters and run your test function
}
else if (args.Length == 0)
{
     // no command line args specified
}

// other lines ...
}

Hope this helps.


Q:

complex regex with preg_replace, replace a word not inside [ and ]

I'm having trouble finding a correct regex to achieve what I want.
I have a sentence like that :
Hi, my name is Stan, you are welcome, hello.

and I would like to transform it like that :
[hi|hello|welcome], my name is [stan|jack] you are [hi|hello|welcome] [hi|hello|welcome].

Right now my regex is half working, because somes words are not replaced, and those replaced are deleting some characters
Here is my test code
<?php

$test = 'Hi, my name is Stan, you are welcome, hello.';

$words = array(
    array('hi', 'hello', 'welcome'),
    array('stan', 'jack'),
);

$result = $test;
foreach ($words as $group) {
    if (count($group) > 0) {
        $replacement = '[' . implode('|', $group) . ']';
        foreach ($group as $word) {
            $result = preg_replace('#([^\[])' . $word . '([^\]])#i', $replacement, $result);
        }
    }
}

echo $test . '
' . $result;

Any help will be appreciated

A:

The regex you are using is overcomplicated. You simply need to use a regex substitution using regular brackets ():
<?php

$test = 'Hi, my name is Stan, you are welcome, hello.';

$words = array(
        array('hi', 'hello', 'welcome'),
        array('stan', 'jack'),
        );

$result = $test;
foreach ($words as $group) {
    if (count($group) > 0) {
        $imploded = implode('|', $group);
        $replacement = "[$imploded]";
        $search = "($imploded)";
        $result = preg_replace("/$search/i", $replacement, $result);
    }
}

echo $test . '
' . $result;


Q:

There are no commands defined in the "indexer" namespace. php 7.2 (ubuntu)

When i want to re Index in Magento2 in php version of 7.3,
this display me this error
An exception was raised while creating "Request"; no instance returned
And when i change to version 7.2
Display this Error.....

Also i use this command with my root Directory (same error)
So how can i simply use Indexer command in Magento2
I thing something too wrong with my Magento :(
Also check this image :--

My all commands are not working.
Also i change my Magento Folder Permissions

A:

Please mention your Magento Version first.

An exception was raised while creating "Request"; no instance returned

Your First error is coming due to most likely not changing php version properly, you should only use PHP version 7.2 when you're working on Magento 2.3.x

Change PHP version according to your Magento version, refer below link
  if you're using Magento 2.3.x

https://devdocs.magento.com/guides/v2.3/install-gde/system-requirements-tech.html
Try below commands for changing PHP version
sudo a2dismod php7.0
sudo a2enmod php7.2
sudo service apache2 restart
sudo update-alternatives --set php /usr/bin/php7.2

Also refer this link for similar issue
Magento 2.2 with PHP 7.1.9 Issue

About your second error regarding 7.2 version,

Try to give permission first to your Magento Directory
sudo chmod -R 777 magentoDir

then use your upgrade-deploy commands.
if that doesn't help try to find solution in below link.
https://community.magento.com/t5/Magento-2-x-Admin-Configuration/CLI-not-recognizing-magento-commands/td-p/45869


Q:

Как получить два набора данных (Таблицы или Reader) из двух выборок SQL?

В Microsoft SQL Server Managment Studio большой запрос возвращает все выборки. Как сделать что б после Command.Execute получить програмно все выбранные таблицы. Т.е.
create PROCEDURE [dbo].p1  begin
   select 1 select 2,3   -- выборка
end
/*results:
1

2  3*/

Что б дало две таблицы а не одну. Да запрос можно "разделить" на два, но до тех пор пока нет связи между ними через локальные переменные.  Можно конечно и их передать, но Studio ловит две три таблицы из выполняемой хранимой  процедуры.
1) Пробовал OleDb - там дополнительных курсоров не получилось получить. Думаю что поддержка нескольких таблиц заложена в sqlncli.dll. 2) Возможно как-то можно средствами sql сделать такую выборку, что б сложить таблицы в таблицу (курсорное поле), или например с помощью sp_msforeachtable.

A:

Попробуйте поработать с объектом ADO Recordset для С++.

Пример работы с Recordset в VBA:
        Dim rsTree As ADODB.Recordset
        Dim rsTreeGrp As ADODB.Recordset
        Dim rsGrp As ADODB.Recordset
        Set rsTree = ExecuteRS("usp_pct_CatList", 2, 0, "")
        Set rsTreeGrp = rsTree.NextRecordset()
        Set rsGrp = rsTreeGrp.NextRecordset()

Процедура usp_pct_CatList возвращает три выборки.


Q:

jQuery UI + Bootstrap 3 sortable accordion not working properly

I wanted to build a accordion menu with drag and drop sortable capabilities, I could build it using bootstrap 3 + jQuery UI, but the problem is jQuery UI is conflicting with general operation of a bootstrap accordion. I'm very specific on using Bootstrap Accordion, but I need to resolve the problems produced by jQuery UI.

Sometimes on sorting either one tab disappears
When one tab is open and sorted, the closing is done only when the other tab is clicked.
Improper arrangements of the sort order when tabs are open.

I have consolidated it in a plnkr
$(function(){
   $( "#accordion" ).accordion().sortable({
      connectWith: "#dropBag"
   });

   $( "#dropBag" ).sortable({
      connectWith: "#accordion"
   });
});

http://plnkr.co/edit/LpQuO9nfB4d5Nwhaj6my?p=preview
Please Help.

A:

You have a little error in your script - accordion() should be replaced with collapse() (see Collapse paragraph in documentation. Rewrite your code as follows:
$(function(){
   $( "#accordion" ).collapse().sortable({
      connectWith: "#dropBag"
   });

   $( "#dropBag" ).sortable({
      connectWith: "#accordion"
   });
});

Plus, there is unclosed div at the end of your markup (dropBag). I can update my answer as soon as I'll understand the sorting problem you have.


Q:

Navigation bar changes upon returning to previous VC

I'm having a few issues with my navigation bar styling. Let's say I have two view controllers.
VC 1 has an orange bar with white text that I have set up like so:
   func stylingStuffs(){
    self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.94, green: 0.38, blue: 0.24, alpha: 1)
    self.navigationController?.navigationBar.backgroundColor = UIColor(red: 0.94, green: 0.38, blue: 0.24, alpha: 1)
    self.navigationController?.navigationBar.tintColor = UIColor.white
    self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
    self.navigationController?.navigationBar.isTranslucent = false
    UIApplication.shared.statusBarStyle = .lightContent
}

VC 2 has a transparent navigation bar and the code for that is:
func stylingStuffs(){
    navigationController?.setNavigationBarHidden(false, animated: true)
    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.94, green: 0.38, blue: 0.24, alpha: 0)
    self.navigationController?.navigationBar.backgroundColor = UIColor(red: 0.94, green: 0.38, blue: 0.24, alpha: 0)
    navigationController?.navigationBar.shadowImage = UIImage()
    navigationController?.navigationBar.isTranslucent = true
    navigationController?.navigationBar.tintColor = UIColor.white
    self.navigationController?.navigationBar.barStyle = .default
    UIApplication.shared.statusBarStyle = .lightContent
}

When I navigate from VC1->VC2 everything works fine, when I navigate from VC2->VC1, VC1's Navbar is now white/transparent as well as the status bar.
How can I fix this or I guess reset the styles upon return to VC1?
Thanks in advanced!

A:

first view VC 1 controller viewDidAppear call  stylingStuffs()
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated: animated)

    stylingStuffs()
}

@rmaddy comment

You are confused because there is actually only one navigation bar. It is part of the one navigation controller that both view controllers are in

so need to reset navigation bar style for VC 1


Q:

Javascript simple animation loop

I am new to javascript, and trying to learn the basics before jumping to jQuery and all the other libraries, so I can understand what's going on (or be able to even try)
I have tried to run a simple animation with a for loop, activated by onclick. There is a single div (id=demo), 4 classes of CSS for the div (up, down, left, right, all modifing the position:relative) and I want to make it move in a square motion.
<div id="demo" class="left" onclick="initElemAnim()"

css
#demo {
    width:100px;
    height:100px;
    background-color: red;
    -webkit-transition: 2s linear;
    position:relative;
    left: 0px;
    }

  #demo.right {
    position: relative;
    left: 200px;
  }

  #demo.left {
    position: relative;
    left:0px;
  }
  #demo.down {
    position: relative;
    top:200px;
  }
  #demo.up {
    position: relative;
    bottom:200px;
  }

js
var elem = document.getElementById("demo");
  var useMe = ["right", "down", "left", "up"];
  var i = 0;

  function initElemAnim() {
    for (; i < 4; ) {
      elem.className = useMe[i];
      setTimeout(i+=1, 2000);
    }
}

Link to code http://jsbin.com/holusevedo/1/watch?html,css,js,output
What happens after I click is - the red square disappears.
What is wrong?
thanks.

A:

You need to set bot left and top for every point in the animation, otherwise going from the "left" step to "down" the element will move diagonally to the bottom-left corner (because .down doesn't have left property, so the browser animates top to 200px and left to 0).
Then your loop starts all the timeouts at the same moment, so all the class changes will execute after two seconds and the only class name on the element will be from whichever timeout has finished last. You should use setInterval.
CSS
#demo.tl {
  left:0;
  top:0
}

#demo.tr {
  top:0;
  left:200px;
}

#demo.br {
  left:200px;
  top:200px;
}
#demo.bl {
  top:200px;
  left:0;
}

JS:
 var elem = document.getElementById("demo");
 var useMe = ["tr", "br", "bl", "tl"];
 var i = 0;

  function initElemAnim() {
    setInterval(function(){
      // this function executes every 2000ms,
      // setting the class name then incrementing the counter
      // or going back to 0 if it reaches the last class name
      elem.className = useMe[i];
      i = i < 3 ? i+1 : 0;
    }, 2000);
}

http://jsbin.com/holusevedo/3/watch?html,css,js,output


Q:

iPad iOS 6 How prevent top corners UINavigationBar from rounding with background image

I have found a lot of posts on this but so far no luck. I am targeting iOS 6.0 and have a custom background image for my navigation bar. The top 2 corners are rounding and I have not found a way to prevent this. I've tried setting the status bar to black translucent (seems you can't do this on the iPad) but no luck. I'm attaching a screenshot (see the blue is rounded on the top edges). Any help greatly appreciated, thanks.

A:

First of all, your app looks great.
Second, that rounding is something that the status bar itself does - see this answer. So, there is a way - get rid of the status bar.
However, your app doesn't look like the type that it would make sense to have the status bar go away. If I were you, I would just leave it as-is - it looks great how it is.


Q:

Why aren't parametrizations equivalent to their "equation form"?

Consider the parametrization $(\lambda,t)\mapsto (\lambda t,\lambda t^2,\lambda t^3)$. This is a union of lines (not sure how to visualize it precisely. I think it's a double cone). It doesn't appear that the $x$ or $z$ axis are in this parametrization (if $y$ and $z$ are both zero, so must $x$ be).
However, when you solve the parametrization in terms of $x,y,z$ you obtain the relationship $y^2=xz$. In which the $x$ and $z$ axes are solutions!
Why is this? Is this the closure? If so, how can we relate the closure to the original set?

A:

When you say that you "solve" and obtain the relationship $y^2 = xz$ I image you just observed that $(\lambda t^2)^2 = (\lambda t)(\lambda t^3)$ correct?  In this case what you have shown is that the set for which you have a parameterization is a subset of the set of solutions to $y^2 = xz$.  What you have not shown is that every solution of $y^2 = xz$ is covered by the parameterization.  Indeed, as you pointed out, this is not true.


Q:

Existence of a null sequence that dominates an infinite family of null sequences

Let us call $a =(a_n)_{n \geq 0}$ a $\textit{null sequence }$ if $a_n \geq 0$ for all $n \geq 0$ and $\lim_{n \rightarrow \infty} a_n =0$.
For two null sequences $a$ and $b$, we say that $a$ dominates $b$ if there exists $n_0$ such that $a_n \geq b_n$ for all $n \geq n_0$.
Given an infinite family of null sequences $(a^{(i)})_{i \in \mathbb{N}}$, is there a null sequence $a$ that dominates $a^{(i)}$ for all $i \in \mathbb{N}$?

A:

Yes. Choose positive integers $N_1\lt N_2\lt N_3\lt\cdots$ so that
$$\max\left(a^{(1)}_n,a^{(2)}_n,a^{(3)}_n,\dots,a^{(i)}_n\right)\le\frac1i\text{ for all }n\ge N_i.$$
Define a sequence $b=(b_n)$ so that $b_n=\frac1i$ when $N_i\le n\lt N_{i+1}$. You can easily verify that $b$ is a null sequence which dominates each of the given null sequences.


Q:

Count the number of values that are bigger than 20

I have a table in my database, tbl. In that table I have id and num, both as regular int values.
I want to count how many IDs have num that is bigger than 20 (num > 20). Just to count how many rows have num > 20.  I wrote this:
$counter= 0;
$sqlQuery = "select num from tbl";
$finalResult= $databasename->prepare($sqlQuery );
$finalResult->execute();
$numArr= $finalResult->fetchColumn();
foreach ($numArra $row){
    if($row > 20)
        $counter++;
}

echo ($counter);

The problem is, that it prints 0 everytime... Thanks in advance.

A:

You don't need any of this. Just do
SELECT COUNT(*) FROM tbl WHERE num > 20

If you want to plug that into PHP and if you want to do this dynamically.
$finalResult= $databasename->prepare("SELECT COUNT(*) FROM tbl WHERE num > ?");
$finalResult->bindParam(1,$someParam);
$finalResult->execute();
$numArr = $finalResult->fetchColumn();

echo ($numArr);

Much simpler


Q:

Java enums and arrays

I have some C++ code I am porting to Java.
My code looks something like this@
enum direction {UP, DOWN, LEFT, RIGHT, NEUTRAL};
int LINK[5];
.....
//fill LINK array
.....
if (desired_direction == LEFT  ) || (LINK[LEFT]  > 0) return true;
if (desired_direction == RIGHT ) || (LINK[RIGHT] > 0) return true;
if (desired_direction == UP    ) || (LINK[UP]    > 0) return true;
if (desired_direction == DOWN  ) || (LINK[DOWN]  > 0) return true;

So I have an array filled with ints and I am using an enum for the index of the array.
What is the Java way of going about this?
Thanks

A:

Basically, nothing is different.
In fact the only things missing here are the parenthesis around the two conditions of each if statements.
Also, your call to the enum value will be direction.whatever.ordinal() instead of just whatever.


Q:

URLDecoding requests

I am trying to get the original url from requests. Here is what I have so far:
res = requests.get(...)
url = urllib.unquote(res.url).decode('utf8')

I then get an error that says:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 60-61: ordinal not in range(128)

The original url I requested is:
https://www.microsoft.com/de-at/store/movies/american-pie-pr\xc3\xa4sentiert-nackte-tatsachen/8d6kgwzl63ql

And here is what happens when I try printing:
>>> print '111', res.url
111 https://www.microsoft.com/de-at/store/movies/american-pie-pr%C3%A4sentiert-nackte-tatsachen/8d6kgwzl63ql
>>> print '222', urllib.unquote( res.url )
222 https://www.microsoft.com/de-at/store/movies/american-pie-prÃ¤sentiert-nackte-tatsachen/8d6kgwzl63ql
>>> print '333', urllib.unquote(res.url).decode('utf8')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 60-61: ordinal not in range(128)

Why is this occurring, and how would I fix this?

A:

UnicodeEncodeError: 'ascii' codec can't encode characters

You are trying to decode a string that is Unicode already. It raises AttributeError on Python 3 (unicode string has no .decode() method there). Python 2 tries to encode the string into bytes first using sys.getdefaultencoding() ('ascii') before passing  it to .decode('utf8') which leads to UnicodeEncodeError.
In short, do not call .decode() on Unicode strings, use this instead:
print urllib.unquote(res.url.encode('ascii')).decode('utf-8')

Without .decode() call, the code prints bytes (assuming a bytestring is passed to unquote()) that may lead to mojibake if the character encoding used by your environment is not utf-8. To avoid mojibake, always print Unicode (don't print text as bytes), do not hardcode the character encoding of your environment inside your script  i.e., .decode() is necessary here.

There is a bug in urllib.unquote() if you pass it a Unicode string:
>>> print urllib.unquote(u'%C3%A4')
Ã¤
>>> print urllib.unquote('%C3%A4') # utf-8 output
ä

Pass bytestrings to unquote() on Python 2.


Q:

Auto_increment option doesn't work on server

Need your help, strange. I have the same tables based locally and on the server - the one on the server doesn't increment ? The local one does...here's the SQL statement for the colum. I can only register / input one row when there are no data, then it doesn't auto increment on next submissions:
-- phpMyAdmin SQL Dump
-- version 3.3.9.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Oct 25, 2011 at 01:31 PM
-- Server version: 5.0.92
-- PHP Version: 5.2.6

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `name`
--

-- --------------------------------------------------------

--
-- Table structure for table `basic`
--

   CREATE TABLE IF NOT EXISTS `basic` (
  `user_id` int(11) NOT NULL auto_increment,
  `username` varchar(255) character set utf8 NOT NULL,
  `email` varchar(255) character set utf8 NOT NULL,
  `email_active` enum('1','0') character set utf8 NOT NULL default '0',
  `password` varchar(128) character set utf8 NOT NULL,
  PRIMARY KEY  (`user_id`),
  UNIQUE KEY `email` (`email`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `basic`
--

INSERT INTO `basic` (`user_id`, `username`, `email`, `email_active`, `password`) VALUES
(2, 'mrd', 'ddddd.ddddd@gmail.com', '0', '05cb6e7ad0f2a84ee6b1cc097dbf2787');

Why does it work locally ? (I'm using PHP my admin on the server and locally as well )
Thank you...

A:

Make sure you set the AUTO_INCREMENT flag:
CREATE TABLE users
(
user_id int NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
email varchar(255) UNIQUE,
email_active TINYINT(1),
password varchar(12),
PRIMARY KEY (user_id)
)


Q:

On the isomorphism between two finite groups

Let $G$ be a finite group and $K,H$ be two normal subgroups of $G$ such that $N \cong K$. Then can we say that $G/N \cong G/K$?

A:

With $G = Z_4 \times Z_2$, consider subgroups of order two.


Q:

Integration (with singularity) of Hankel functions

I need to calculate an integral like
B[a_, t_] :=  1/(2 I) (t)^(9/2) NIntegrate[ x^(1/2) (HankelH1[a, x]^3 HankelH2[a, t]^3 -  HankelH2[a, x]^3 HankelH1[a, t]^3), {x, t, 2}, WorkingPrecision -> 40,  MinRecursion -> 10,  MaxRecursion -> 20] // N

$t$ ranges from Exp[-60] to 1. $a$ ranges from 0 to 1.5. Notice that $t$ appears in the lower integration limit, in the argument of Hankel functions and as $t^{9/2}$. Moreover, the integrand is purely imaginary. The integrand diverges in the limit $t\rightarrow 0$. For $a\equiv1.5$, the analytical result predicts a logarithmic divergence for $t\rightarrow 0$. The problem is that
B[1.5,Exp[-20]]=5.5
B[1.5,Exp[-30]]=-5.89145*10^22

I have tried to increase the precision, but results do not change. I suspect that the Hankel functions are evaluated with too low precision and hence I get wrong results.
You can see the (analytical) logarithmic divergence plotting
G[x_, a_, t_] := (t)^(9/2) Im[x^(1/2) (HankelH1[a, x]^3 HankelH2[a, t]^3-HankelH2[a, x]^3 HankelH1[a, t]^3)]
LogLinearPlot[{G[x, 1.5, Exp[-20]], 1/x}, {x, Exp[-10], 2}, PlotRange -> {{0, Exp[-10]}, {0, 100}}, PlotPoints -> 10000]

I am interested in the behavior of the function both for fixed $a$ and for fixed $t$ (but the former is more important).
How can I evaluate this integral?
Thanks in advance to those who will try to help me.

A:

Clear[B]
Add an optional third argument to control the WorkingPrecision
B[a_?NumericQ, t_?NumericQ, wp_:40] :=
 1/(2 I) (t)^(9/2) NIntegrate[
    x^(1/2) (HankelH1[a, x]^3 HankelH2[a, t]^3 -
       HankelH2[a, x]^3 HankelH1[a, t]^3), {x, t, 2}, WorkingPrecision -> wp,
    MinRecursion -> 10, MaxRecursion -> 20] // N

If you provide input values with $MachinePrecision then the calculation will be done with $MachinePrecision.  Either input exact numbers
B[3/2, Exp[-20]]

(*  5.46327  *)

or high arbitrary precision numbers (EDIT: see Precision: "Numbers entered in the form digits`p are taken to have precision p.")
B[1.5`45, Exp[-20]]

(*  5.46327  *)

B[3/2, Exp[-30]]

(*  8.0434  *)

B[1.5`60, Exp[-30], 50]

(*  8.0434  *)


Q:

editing data in a list while the length of data is different

I have a list like this:
a = [c0001203, c0334, c0000456, c034554, c00034506]. I need to remove 'c' and all 0 after 'c', until the data starts with a number. The length of each data is variable.  The output should be like this:
a = [1203, 334, 456, 34506]. How can I do it without using regular expression?
Thank you.

A:

You can drop the c and then .strip() the 0's like:
Code:
b = [x[1:].lstrip('0') for x in a]

Test Code:
a = ['c0001203', 'c0334', 'c0000456', 'c034554', 'c00034506']
b = [x[1:].lstrip('0') for x in a]
print(b)

Results:
['1203', '334', '456', '34554', '34506']


Q:

Compile less and output minify and non-minify files

I have a task in Gulp that compile a less file in css. I want to output the non-minify and the minify version with sourcemaps. I can't find a soluction.
This is my actual task that should do this job:
return gulp.src(['./src/less/main.less'])
.pipe(sourcemaps.init())
.pipe(less({
    paths: ['node_modules'],
}))
.pipe(sourcemaps.write('.'))
.pipe(cssnano())
.pipe(rename(function (path) {
    console.log(path);
    path.basename = path.basename.split('.')[0] + '.min' + (path.basename.split[1] || ''); //to change the name from main.css to main.min.css
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/css/'));

I get an error because cssnano want minify the map file. Can someone post his complete task with that feature?
Thank you in advance!

A:

Something like this using 'gulp-clone' package:
var files = gulp.src(['./src/less/main.less']);

files
  .pipe(clone())
  .pipe(sourcemaps.init())
  .pipe(less())
  .pipe(cssnano())
  .pipe(sourcemaps.write('.'));

files
  .pipe(sourcemaps.init())
  .pipe(less())
  .pipe(sourcemaps.write('.'));


Q:

Node.js on localhost

I am very new to node.js. I am developing a multiplayer card game. So, someone suggest me to use node.js with apache and php.
how?

A:

Doing a bit research will solve your problem. It seems you have lack of information about sockets read and then go ahead.


Q:

How do you insert multiple unique records into another table based off of individual rows in a starting table

How do you iterate through a table row by row, and insert entries based off of those individual rows, into another table in MSSQL?

A:

If you MUST go row-by-row, you'd be declaring and using a cursor.  It's usually not a good idea, and I'd be curious why you need to do so.  The tags on your question (fetch, while) imply that you already have some clue about cursors.  The general form looks something like:
SET NOCOUNT ON;
DECLARE @num INT; -- other columns

-- EDIT added LOCAL STATIC READ_ONLY FORWARD_ONLY per comment below
DECLARE excruciatingly_slow CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR
    SELECT 1  --this is just a sample, your query (which you might want to supply) will differ
    UNION ALL
    SELECT 2;

OPEN excruciatingly_slow;
FETCH NEXT FROM excruciatingly_slow
    INTO @num -- other variables
    ;

WHILE @@FETCH_STATUS > -1
    BEGIN
        -- Do something here
        INSERT destination_table
            (    column_list -- other columns...
            )
        SELECT @num -- other columns
            ;

        FETCH NEXT FROM excruciatingly_slow
            INTO @num-- other variables
            ;
    END;
CLOSE excruciatingly_slow;
DEALLOCATE excruciatingly_slow;

In most cases this would be better done with the INSERT...SELECT... constructs suggested by the other replies.  There is a homework tag if this is course-related.  I'm having trouble thinking of a case where a single insert would be better served by a cursor.


Q:

c++ templates call specific constructor for specific type of class

I’m trying to make generic binary tree in c++ using templates.
So for example the type of value in Node class could be string, int or double.
I create my tree from the string and in in method I extract e.g single number from string and call constructor for Node.
Node class in header file without rest of the methods:
template <class T>
class Node {
public:
Node(const string value){
    this->value = value;
    this->leftChild = nullptr;
    this->rightChild = nullptr;
};
private:
T value;
Node *parent;
Node *rightChild;
Node *leftChild;
};

So what I’m asking is how to define different constructor for specific type of Node class so e.g it would be possible to do:
Node<int> node(„2”);

and define and call constructor like:
Node(const string value){
    this->value = stoi(value);
    this->leftChild = nullptr;
    this->rightChild = nullptr;
};

Before I was trying to has just one constructor but overload = operator:
void operator=(int &n,string &s){
n = stoi(s);
};

But when it’s defined outside of class, compiler say "overloaded 'operator=' must be a non-static member function"

A:

First off you need to learn about member initializer lists: C++ initializes object directly. So you’d have a ctor like this:
Node::Node(std::string const& value)
    : value(value) // this line will need adjustment; see below
    , leftChild(nullptr)
    , rightChild(nullptr) {
}

For a generic data structure you’d most likely actually adjust the ctor argument type to match the value type. It is unusual that a generic data structure deals with type conversions. However, for the discussion below I’ll assume you want to stick to std::string, e.g., because the values are read from a text file.
If you need to convert between types you’ll want to use a generic type converter. These come in two flavors:

an existing function template like boost::lexical_cast
use a specific customization point

Both approaches have their place and it may be reasonable to even combine them. What they have in common is that the generic code uses identical syntax and the type-specific handling is done elsewhere.
Using boost::lexical_cast
The idea of boost::lexical_cast is to convert the argument to a character sequence, parse the result using a stream to produce the destination type, and yield the result. The actual implementation is heavily optimised to avoid costly operations for common conversions, e.g., the conversiin from std::string to int iis effectively doing the same as stoi().
It would be used like
Node::Node(std::string const& value)
    : value(boost::lexical_cast<T>(value))
    , leftChild(nullptr)
    , rightChild(nullptr) {
}

Using a Customization Point
Another approach is to define a specific customization point, i.e., a generic interface which can be customized by users of the data structure. The advantage of this approach is that there is a bit more flexibility, e.g., to do suitable conversions based on how the data structure is used. Using a suitable default could avoid the drawback that the customization point has to be defined by every user.
Assuming the function used for the conversion is called my_convert it could be used like that (there are other approaches to define customization points, too):
Node::Node(std::string const& value)
    : value(my_convert<T>(value))
    , leftChild(nullptr)
    , rightChild(nullptr) {
}

This approach assumes that there is a primary template defined which probably defines a suitable default, e.g.:
template <typename T>
T my_convert(std::string const& value) {
    return boost::lexical_cast<T>(value);
}

It could be customized for a specific target type using template specialization:
template <>
int my_convert<int>(std::string const& value) {
    return std::stoi(value);
}


Q:

Proving logarithmic maths graphically

I'm just going through some further maths units as I prepare for a PHD in chemical engineering. I'm finding the thought processes to be invaluable in my problem solving skills.
However, I recently came unstuck on this question....and while I know I can't be helped here due to the requirement to construct a graph, I wondered what would be the right way a mathematician would approach this?
Show graphically that the following figures support the belief that a relationship of the form =^ exists and use your graph to find approximate values for the constants  and .
   5    8   12   14     20    30
 22.4 45.3 83.1 104.8 178.9 328.6
Thank you

A:

If the relationship $y=ax^k$ holds, then taking logs of both sides yields
$$
\log y = \log a + k\log x.
$$
This means that plotting $\log y$ against $\log x$ should give a straight line with slope $k$ and intercept $\log a$.


Q:

How to replicate only one data type 'n' times in list using rep()

fred <- list(num = c(1:10) , name = "hello")

How to repeat num type 5 times and name type 10 times in lists using rep()?

A:

You can try mapply which applies the function to the elements of fred and the times vector.
mapply(function(x, y) rep(x, times=y), fred, c(5, 10))
$num
 [1]  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9
[30] 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10

$name
 [1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"

The list is replicated simply using
rep(fred, c(5,10))


Q:

android studio new project cannot find symbol 'R'

I just made a clean android studio project and I'm getting errors in my Main file saying R isn't found. I know it's not an xml error since it's a new project...I've tried to sync project with gradle files but that doesn't seem to do anything. It just comes back with an :app:mergeDebugResources error..

A:

Select Build > Clean Project
It should rebuild and recreate the R file :-)


Q:

For what value of C is P(X=n) = C/n! For all n in the non-negative integers a probability density function?

For what value of $C$ is $P(X=n) = \frac{C}{n!}$? For all n in the non-negative integers a probability density function?
Summary of what I did:
Set $f(n)$ equal to $1$ and summed over all non negative integers.
Used $\frac1{n!}$ as defined by the recurrence relation $a(n)=\frac{a(n-1)}{(n+1)}$. With initial conditions $a_0=1,a_1=1$.
$C(1/0!$ + $\sum_{n=1}^\infty a(n)$
Then used infinite version of geometric series formula.
$C(1+(1*(1/2))/(1-1/2))$
$C=1/2.$

A:

By definition:
$$\sum\limits_{n=0}^\infty \frac{x^n}{n!}=e^x$$
So, by plugging in $1$ in place of $x$ we have:
$$e = \sum\limits_{n=0}^\infty \frac{1}{n!}$$
Dividing both sides by $e$ gives us
$$1 = \sum\limits_{n=0}^\infty \frac{e^{-1}}{n!}$$


Q:

Use the browser cookie in fetch in a WebExtension

I’m currently porting an addon from the jetpack to the WebExtension API. I need to continuously update a browser action (toolbar button) with data (e.g. set its badge text).
For this, I would like to do a request from a background script in my extension to an API of the page, which is accessible when the user is logged in (i.e. a cookie is set). What I did so far:

I gave myself host permissions, which is mentioned to be necessary for request from content scripts.
However, content scripts are for injecting JS into pages the user visits.
I created a background script that uses fetch to do a request to the API.

However, when queried from the background script, the API tells me that nobody is logged in, while I can access it with the browser flawlessly.
This is the relevant part of the manifest.json:
{
  "background": {
    "scripts": ["background.js"]
  },
  "permissions": [
    "*://subdomain.domain.com/*"
  ]
}

How can I have a continuously running background script that can use the user’s cookie to access this API?

A:

Firefox has stricter cors restrictions for cookies. I solved this by doing the api call from a content-script injected on the page with the same domain. That api call generated an auth token that was used for api calls from the background page, and enabling cors on backend for requests containing token in auth header.