Sum of an Array in Apps Script

Question: In google Apps script i am pulling rows of numbers into an array
I need to find the sum of every element in that array
This code works fine: (This is pulling the values into the array)
   var test = [];
   test = sheet.getRange(13, 6, 4, 24).getValues();

I've tried a couple different formulas i've found and haven't been able to get it to work right:
 function testSum (test) {
 let total = 0;
 for (const i of test) {
 total += i;
 }
 return total;
 }

 var test1 = test.flat();

 var test1 = test.reduce((a, b) => a + b, 0);

Tried everything i could find and nothing would work
Comment: What is the test input giving value ? can you show me an example ?
Comment: When i log test.typeOf it returns undefined

When i console log test i get

[ [ 583.95,
    '',
    '',
    '',
    '',
    '',
    225,
    '',
    11,
    '',
    20,
    '',
    21.95,
    '',
    279,
    '',
    19,
    '',
    8,
    '',
    690,
    '',
    '',
    '' ],
  [ 145,
    '',
    80,
    '',
    10,
    '',
    '',
    '',
    '',
    '',
    '',
    '',
    55,
    '',
    '',
    '',
    '',
    '',
    '',
    '',
    110,
    '',
    '',
    '' ],
  [ '',
    '',
    '',
    '',
    '',]...
Comment: the elements shown in the array are columns and every column shows the rows ? that what I get
Comment: I thought that if `test` of `var test1 = test.flat();` is `test` of `test = sheet.getRange(13, 6, 4, 24).getValues();`, how about modifying `var test1 = test.reduce((a, b) => a + b, 0);` to `var test1 = test.flat().reduce((a, b) => a + Number(b), 0);`? By this, `test1` might be your expected result. Because, in your current script, `test` is a 2-dimensional array. If I misunderstood your actual script, I apologize.
Comment: Getting a ".reduce is not a function" error.
Answer:     const test = [
      [
        583.95,
        '',
        '',
        '',
        '',
        '',
        225,
        '',
        11,
        '',
        20,
        '',
        21.95,
        '',
        279,
        '',
        19,
        '',
        8,
        '',
        690,
        '',
        '',
        '',
      ],
      [
        145,
        '',
        80,
        '',
        10,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        55,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        110,
        '',
        '',
        '',
      ],
      ['', '', '', '', ''],
    ];

    const columnWiseSums = [];

    for (const ele  of test) {
        let sum = 0;
        columnWiseSums.push(ele.reduce((prev, curr) =>  typeof curr === 'number' ? prev + curr : prev, 0));
    }
console.log(columnWiseSums);

There are other ways to find sum as well, but I used  array.reduce one
Comment: This worked, Thank you !
Comment: @DavidAbbott Welcome, Don't forget to upvote/mark as answer as I can't ask questions in case chatgpt is unable to help as well.
Comment: I need the sums of each element to stay in their own element so i can push that sum back into sheets.  When i go to push it back now it just assigns test[0] value to every cell
Comment: @DavidAbbott you can take separate array for sums
Answer:
For 1D array

     const sumOfArrayElement = (input) => {
             return input.reduce((total, item)=>total+item)
     }
     console.log(sumOfArrayElement([3,2,4]));

For 2D Array

     const sum = [];
     const test = [
                    [1,2,3],
                    [ 3,4,5]
                  ];
     test.forEach(item => {
         sum.push(item.reduce((total,num)=> {
             return num!= ''?total +parseFloat(num):total;
         }));
     });

Answer: this code will be make the mistake solucion.

function testSum(test) {
  var sum = 0;
  for (var i = 0; i < test.length; i++) {
    for (var j = 0; j < test[i].length; j++) {

      if (typeof test[i][j] == "number") {
        sum += test[i][j]
      }
    }
  }
  return sum
}

Sum of an Array in Apps Script


Python module name aliases?

Question: I've got a module called 'cloud.aws.boto'. I need this to import the boto library I installed into my virtualenv.
If I add import boto.ec2 to my 'cloud.aws.boto.py' file, python complains because it's trying to import 'ec2' from the local file instead of the library in my virtualenv.
How can I import another module with the same name as the one I'm importing from?
Answer: http://docs.python.org/2/tutorial/modules.html
You can try to remove "." from sys.path just before this import (but don't forget to prepend it back once you are done, otherwise you won't be able to imnport your other local modules).
Comment: Yuck. Ugly but I guess it'll do the job

Python module name aliases?


Python pickle's data can't update in tkinter

Question: here's a part of my code from recent game i've try to make
i'm confused about the data loaded from [pickle] cannot apply to the Label in [tkinter]
it works when i'm saving and loading the data
from tkinter import *
import pickle

Prvs_controll = [3,3,3,3,3]
Prvs_size = [1,1,1,1,1]
GameData= [Prvs_controll, Prvs_size]

class MainGame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        global canvas
        self.parent.title('PythonEuropaGame')
        self.pack(fill=BOTH, expand=1)
        tkframe = Frame(self)
        canvas = Canvas(self)
        canvas.pack(fill = BOTH, expand = 1)
        canvas.update()

def save():
    global GameData
    with open('Save_01.pickle', 'wb') as handle:
        pickle.dump(GameData, handle)
        print(GameData)
def load():
    global canvas
    global GameData
    with open('Save_01.pickle', 'rb') as handle:
        GameData = pickle.load(handle)
        Label_size_b.configure(text = Prvs_size[0])
        print(GameData)

def change_controll():
    global GameData
    GameData[0] = [9,9,9,9,9]

def change_size():
    global GameData
    GameData[1][0] += 150
    Label_size_b.configure(text = Prvs_size[0])

root = Tk()
ex = MainGame(root)
root.geometry('900x650')

Label_size_a = Label(root, text = 'Size')
Label_size_b = Label(root, text = '---')
Label_size_a.place(x = 700, y = 195)
Label_size_b.place(x = 750, y = 195)

Button_save = Button(root, text = 'Save', command = save)
Button_load = Button(root, text = 'Load', command = load)
Button_size_add = Button(root, text = 'Upgrade', command = change_size)
Button_save.place(x = 700, y = 500)
Button_load.place(x = 750, y = 500)
Button_size_add.place(x = 800, y = 225)

At first, I called change_size() and save(),
it printed "[3, 3, 3, 3, 3], [151, 1, 1, 1, 1]]"
and the label[Label_size_b] had showed the change in size(it printed "151) and it is saved.
However when I restart the module and call load(), it still print the data above  "[3, 3, 3, 3, 3], [151, 1, 1, 1, 1]]" .
But the main problem is label[Label_size_b] is printed as "1" but not "151"
that mean I changed something and load it, but the Label still print the Original data!(see the top on code)
I guess it may be the "global" problem but I can't find any way to correct it.
Answer: The problem is this line in the load() function:
Label_size_b.configure(text = Prvs_size[0])

Here Prvs_size refers to the global variable that is initialised to [1,1,1,1,1] when the script starts, and is never updated. You need to access the values loaded from the pickle file into GameData like this:
Label_size_b.configure(text = GameData[1][0])

This accesses the first element of the second list in the GameData list as loaded from the pickled data.
There is a similar problem in the change_size() function.
Comment: @Montague27: not sure if you noticed my last update, but there's a similar problem in `change_size()`.
Comment: Yes, I knew it. :D


drupal ajax callback on language selection

Question: Is there way to bind an ajax callback when the language is changed, i want to update a nodereference-dropdown when a language is changed (to show the values only in that language).
following code is not working (form_alter) although other callbacks are working.
Can someone help me how can i achieve that?
$form['language']['#ajax'] = array(
            'callback' => 'mymodule_something_language_callback',
            'wrapper' => 'my-module-replace',
            '#weight' => 2
        );

Thanks.
FROM COMMENTS
heres the var_dump of $form['language'];
array
  '#type' => string 'select' (length=6)
  '#title' => string 'Language' (length=8)
  '#default_value' => string 'und' (length=3)
  '#options' =>
    array
      'und' => string 'Language neutral' (length=16)
      'en' => string 'English' (length=7)
      'ar' => string 'Arabic' (length=6)

Comment: Definitely remove the `#weight` from the `#ajax` property, it doesn't belong there
Comment: not working means that ajax callback is not getting fired when i change the value in language dropdown but the exact same code works for other dropdown fields.
Comment: How do you know the AJAX callback isn't firing?
Comment: @Clive i dont know if `#weight` makes a difference i copied it from a tutorial and this has worked very well for other dropdowns, i will remove that and check again
Comment: @jantimon no the ajax request is not getting sent in the network tab
Comment: You could try to set `['#ajax']['event'] = 'change'` but that shouldn't be necessary. Do you get any js errors?
Comment: Are you sure your form_alter is called and you are using `&$form`?
Comment: yes, my form alter is called, as i said other callbacks are working perfectly fine in the same form_alter, this one isnt and no i dont get any js errors
Comment: Same problem here, my ajax event isn't firing. I don't see any items in the network tab of chrome. Did you fix the problem meanwhile? I'm adding the ajax callback in this function: `hook_form_node_form_alter(&$form, &$form_state, $form_id)`. If I check my `$form["language"]` it only contains `#type = "value"` and `#value = "und"`...
Comment: Strangely enough if I define my callback in the i18n_menu.module the $form["language"] is filled as a type select, and not only value and type. As reference I used this link: https://drupal.org/files/issues/restrict_parent_menu-5043252-4.patch if I define my ajax callback in that file it does get triggered, not in my custom module. Any ideas?
Comment: Looks to me like the language selection field gets build in a later process than my form_alter gets called. And overwrites the ajax i give with it.
Answer: The problem is that the Locale module alters this form element after hook_form_alter() is called (see this post).
Here's how I solved this problem:
First, change the order in which Drupal implements its hooks, putting 'form_alter' as the last one:
<?php

/**
 * Implementation of hook_module_implements_alter()
 */
function chronos_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move mymodule_form_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['chronos'];
    unset($implementations['chronos']);
    $implementations['chronos'] = $group;
  }
}

Next, add a form element and the '#ajax' element that you want on $form['language']:
<?php

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'page_node_form') {
        // alter the form
        $form['container'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
    );
        $form['language']['#ajax'] = array(
                'callback' => 'mymodule_save_language_callback',
                'wrapper' => 'ajax-language'
        );
        return $form;
    }
}

Lastly, add your callback:
<?php

/**
 * Returns changed part of the form.
 *
 * @return renderable array
 *
 * @see ajax_example_form_node_form_alter()
 */
function chronos_save_language_callback($form, $form_state) {
  # set session variables or perform other actions here, if applicable
  return $form['container'];
}


Angles and ellipse (proof)

Question: First of all, sorry for my poor English! Can you please help me? I'm trying to prove that, given a point P at an ellipse.
Please help me prove that the angles are equal.
Thanks!
Comment: I drew it badly :x
Comment: Please, complete you questions. Edit it.
Comment: I'm real bad with specific math terms in English, that's why I drew it :(
Comment: What are you trying to prove? You didn't wrote. Given $P$ on an ellipse, prove what?
Comment: prove that the angles are equal
Comment: @Mariana You can edit your post to include the question in your native language at the end, and someone can translate it for you.
Answer: It is not true for any point $P$. See the image:
Comment: So it must be at the vertice of the ellipse?
Comment: Note that $PO$ must be the bisectrix and the median of the triangle $F_1PF_2$.
Comment: Oh, I got it! Thanks
Comment: I thought @MarianaCiotta was after the Reflection Property of ellipses. (A light ray emanating from one focus will bounce off the ellipse and head for the other focus.) Note the right angle marker in her diagram: this suggests (to me) that she's interested in the angle-dividing behavior of the *perpendicular to the tangent line* at $P$, not the behavior of line $OP$. In that case, it *is* true for any $P$: the perpendicular to the tangent always bisects the angle.
Answer: You haven't stated the problem. You want to prove that a light ray from one focus reflects off the ellipse back to the other focus. You don't tell us what you know. Personally, I would represent the ellipse as a level set of the function
$$f(\mathbf x) = \|\mathbf x-F_1\| + \|\mathbf x-F_2\|$$ and use the fact that $\nabla f$ is the normal vector.
You could also write down the equation
$$\frac{x^2}{a^2} + \frac{y^2}{b^2}=1$$
and use implicit differentiation and lots of slopes.
Comment: On second thought, maybe the OP wants it just for the one point, where it's obvious by congruent triangles?

Angles and ellipse (proof)


How to force reserve() to use a non-default constructor?

Question: Suppose we have the following code snippet:
MyType::MyType();            // size of MyType.aMember is a default size
MyType::MyType(int mySize);  // size of MyType.aMember depends on mySize
...
...
std::vector<MyType> myTypeVector;
myTypeVector.reserve(numberOfObjects);  // memory reserved is numberOfObjects * sizeof(MyType)
...

How can one make reserve not use the default constructor to determine the size of the individual objects, but use a desired constructor instead?
One can try the following:
MyType::MyType();            // size of MyType.aMember is a default size
MyType::MyType(int mySize);  // size of MyType.aMember depends on mySize
...
...
std::vector<MyType> myTypeVector(numberOfObjects, MyType(desiredSize));  // memory allocated is numberOfObjects * sizeof(MyType(desiredSize))
...

But the above calls the copy constructor which I would like to avoid for efficiency reasons. Hence my question.
Comment: `reserve` shouldn't use the default-constructor, because it doesn't *construct* anything, it just allocates.
Comment: Your part `size of MyType.aMember depends on mySize` is not possible, so question does not make sense.
Comment: `reserve()` doesn't construct any items anyway, but reserves space.
Comment: Why would one need a constructor to know the size, isn't `sizeof` adequate?
Comment: I think you misunderstood something. `MyType` can't change it's size. It just can't. Maybe you have a pointer or a container in `MyType` that does allocate memory based on `mySize`, but that doesn't change the size of `MyType`. Also `reserve` does not call any constructor, it just allocates memory.
Comment: Why is that not possible? I have `aMember.reserve(mySize)` in the constructor code.
Comment: I don't get how an object can have different size depending on the constructor ... Can someone explain that ?
Comment: `aMember.reserve(mySize)` reserves a separate block of memory that `aMember` then points at. That has no effect whatsoever on the size of memory needed to hold a `MyType` object. Its size is determined at compile-time, not run-time (`sizeof(MyType)` is constant), regardless of what `aMember` does at run-time.
Answer: A type can only have exactly one size. Calling a non-default constructor has no effect on the size of the object. As such, there is no need for what you're asking. reserve does not and can not use a constructor to determine the size of the objects.
Your attempt std::vector<MyType> myTypeVector(numberOfObjects, MyType(desiredSize)); does something wholly different. It constructs numberOfObjects number copies of a temporary MyType object and therefore must copy. If you wanted to simply reserve the space for those objects, then myTypeVector.reserve(numberOfObjects); would allocate exactly the correct amount of memory.
A vector does not contain objects inside itself. If it did, it could never change size. Instead, vector contains pointer(s) to a buffer which is allocated separately. Therefore, the capacity or object count of the vector has no effect on the size of the vector object itself and therefore they also have no effect on the size of an object that contains a vector member.
You cannot reserve memory for a the buffer of vector that doesn't exist. As I said, myTypeVector.reserve(numberOfObjects); is sufficient to allocate memory for your MyType instances and once the instances have been constructed, you can reserve space for the member vectors.
Comment: Sorry if my question did not make my need clear: I would like to reserve enough memory to hold the desired number of objects, each alike, but with a specific memory requirement of their own.
Comment: Could you rephrase that? Do you mean that you want to store objects of different types in the vector?
Comment: @ChandraMouli: `reserve()` merely reserves a block of memory that is large enough to hold N number of objects. It does not construct any objects inside that memory. You need to use the `push_...()` or `resize()` method to do that. So it does not matter what constructors are defined for `MyType`, `reserve()` will not call any of them. The memory requirements of the object's members are irrelevant to `reserve()`.
Comment: I may be using a wrong pattern, but here's what I would like to do: Reserve the space for a vector of objects, where each object is of the same type, but a member, which happens to be another vector, have a certain desired space reserved for itself.
Comment: Ah, now this is getting a bit clearer. You cannot reserve space for vectors that don't exist yet. You can only reserve memory `myTypeVector` and once you've constructed the `MyType` instances, you can then reserve the memory for the each member vector that now exist.
Comment: @RemyLebeau: `reserve()` needs to know the size of the object, which in turn depends on the size of its members. If I need to also reserve for a member, such that a call to `emplace_back()` with a value for the vector member already has reserved space for itself, I'm not sure how I can achieve that.
Comment: "*`reserve()` needs to know the size of the object, which in turn depends on the size of its members.*" That is true. But you are confusing the fact that the size of `MyType::aMember` itself versus the size of the data that `MyType::aMember` refers to internally are **two different things**. The data that `MyType::aMember` refers to is dynamically allocated at run-time and is *irrelevant* to the size needed to reserve a `vector` of `MyType` objects, as that data is not part of `MyType` itself. It is external to `MyType`, allocated elsewhere in memory where only `MyType::aMember` knows.


Slider- Não consigo aplicar o JavaScript num slider

Question: Boa tarde.
Estou a desenvolver um website para um projeto de universidade. Ainda sou novo no que se trata de desenvolvimento web, mas tenho muito interesse no tema. Estou a usar templates para me poder guiar no desenvolvimento do projeto em si. No entanto, não compreendo porque é que as funções em java não se estão a aplicar nos botões do slider nem nas transições do mesmo.
Agradeço por todo o tipo de ajuda e espero que estejam todos com boa saúde :)

const slides = document.querySelectorAll(".slide");
const next = document.querySelector("#next");
const prev = document.querySelector("#prev");
const auto = false; // Auto scroll
const intervalTime = 5000;
let slideInterval;

const nextSlide = () => {
  // Get current class
  const current = document.querySelector(".current");
  // Remove current class
  current.classList.remove("current");
  // Check for next slide
  if (current.nextElementSibling) {
    // Add current to next sibling
    current.nextElementSibling.classList.add("current");
  } else {
    // Add current to start
    slides[0].classList.add("current");
  }
  setTimeout(() => current.classList.remove("current"));
};

const prevSlide = () => {
  // Get current class
  const current = document.querySelector(".current");
  // Remove current class
  current.classList.remove("current");
  // Check for prev slide
  if (current.previousElementSibling) {
    // Add current to prev sibling
    current.previousElementSibling.classList.add("current");
  } else {
    // Add current to last
    slides[slides.length - 1].classList.add("current");
  }
  setTimeout(() => current.classList.remove("current"));
};

// Button events
next.addEventListener("click", (e) => {
  nextSlide();
  if (auto) {
    clearInterval(slideInterval);
    slideInterval = setInterval(nextSlide, intervalTime);
  }
});

prev.addEventListener("click", (e) => {
  prevSlide();
  if (auto) {
    clearInterval(slideInterval);
    slideInterval = setInterval(nextSlide, intervalTime);
  }
});

// Auto slide
if (auto) {
  // Run next slide at interval time
  slideInterval = setInterval(nextSlide, intervalTime);
}

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  <link rel="stylesheet" href="css/css_home.css">

  <title>Official 7R</title>

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

            HOME
                (current)

            A STORY

            WHO MADE YOUR CLOTHES

            ARTICLES

            SUPPORT US

            OUR TEAM

Slide One

          Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit hic maxime, voluptatibus labore doloremque vero!

Slide Two

          Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit hic maxime, voluptatibus labore doloremque vero!

Slide Three

          Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit hic maxime, voluptatibus labore doloremque vero!

Slide Four

          Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit hic maxime, voluptatibus labore doloremque vero!

Slide Five

          Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit hic maxime, voluptatibus labore doloremque vero!

Slide Six

          Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sit hic maxime, voluptatibus labore doloremque vero!

    <button id="prev"></button>
    <button id="next"></button>

Comment: Você está removendo a classe `current` duas vezes? E outra, o `setTimeout` pede dois argumentos: a função a ser executada (que foi o que você já forneceu), e **o tempo a esperar**, em milissegundos.
Answer: Creio que está faltando importar seu arquivo Javascript no seu HTML não? Aparentemente você adicionou somente as folhas de estilo.


image of a circle under conformal trasformation

Question: Consider a circle:
$C_R=\{w=(x,y): |w|^2=x^2+y^2=R^2\}$
Prove that $A(C_R)$ remains a circle if $A$ is either a conformal or an anticonformal matrix.
My attempt:
I defined the complex number $z:=x +iy$. Therefore, $\overline{z}=x-iy$.
$A(C_R)=A(|z|^2+|\overline{z}|^2)=A((Re^{it})^2+(Re^{-it})^2)=A(R^2)$
but it doesn't seem to take me anywhere!
Answer: One approach is to use a connection between complex numbers and $2\times 2$ matrices. This also helps in other situation. Namely, for a fixed complex number $a+ib$ the linear map $z\mapsto (a+ib)z$ can be written out as a linear transformation of $\mathbb R^2$ with the matrix
$$\begin{pmatrix} a & -b \\ b & a\end{pmatrix} \tag 1$$
This is a conformal matrix. Conversely, any matrix of the form (1), that is antisymmetric and with  constant diagonal, corresponds to the complex number $a+ib$, taken from its first column.
Similarly, anticonformal matrices come from linear maps $z\mapsto (a+ib)\overline{z}$:
$$\begin{pmatrix} a & b \\ b & -a\end{pmatrix} \tag 2$$
So, if a matrix of either form (1) or (2) is applied to the circle $|z|=R$, the image can be immediately written as the set of numbers $w=(a+ib)z$ (or $w=(a+ib)\bar z$) with $|z|=R$.


Kubernetes Ingress with static IPv4 address

Question: I have set Kubernetes up with kubeadm, bare-metal on Ubuntu Linux instances. These are instances on GCE, but I am not using the specific GKE native cluster service. Each instance (as a node) has a static, external IPv4 address. I am trying to make a service available to the outside using an ingress. I've tried MetalLB or port-forwarding, but can't get it to work. The former seems to require addresses to be commissioned on demand, which I don't have.
Is there a recommended way to get LoadBalancing to work with static, external IPs?
Comment: Could you provide your configuration manifests and more details about env? What OS did you use, Ubuntu/Debian? How did you configure Ingress, services. How did you test it. All steps to replicate your environment would be good.
Comment: Hi, thanks for the offer to help. As I have moved on to a different approach it probably makes little sense to discuss all the details. I am now using Cloudflare's Argo tunnel to connect web content directly with the CDN.
Comment: Could you provide your solution as an answer? It might help others users who encounter similar issue.
Comment: Well, I don't have a solution to the original problem. I sidestepped the issue by tunneling between server pods and CDN. See here: https://developers.cloudflare.com/argo-tunnel/create-tunnel/kubernetes-sidecar-model
Answer: I think root cause of this issue is the Firewall configuration. You can connect to cluster in a few ways. Below I will provide you examples of NodePort methods.
Assuming that there is a Kubernetes cluster is configured correctly (with CNI, Docker, Kubeadm bootstrap, taints, etc).
You can use below example to spawn hello-app pods that will respond to your traffic:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deployment-1
spec:
  replicas: 1
  selector:
    matchLabels:
      key: application-1
  template:
    metadata:
      labels:
        key: application-1
    spec:
      containers:
      - name: hello1
        image: gcr.io/google-samples/hello-app:1.0
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8080

Using NodePort service type.
You are using GCE instance so your VM already have static ExternalIP.
Hello-app  was deployed in previous step, now you will need to expose it with service of type NodePort
apiVersion: v1
kind: Service
metadata:
  name: service-one
spec:
  type: NodePort
  selector:
    key: application-1
  ports:
    - port: 80
      targetPort: 8080

By default, firewall will block the incoming requests on ports that are not whitelisted. You will need to create a rule that will allow traffic to enter on specific ports (ie. 31085). For details, please check Configuring Firewall Rules.
You can do it by following below path:
Navigation Menu > VPC Network > Firewall > Create Firewall Rule.
You can create a rule that allows:

single port for NodePort for example 31085
whole range 30000-32767

$ kubectl get svc
NAME          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes    ClusterIP   10.96.0.1        <none>        443/TCP        50m
service-one   NodePort    10.110.184.238   <none>        80:31085/TCP   5m53s

To reach your cluster you can use
$ curl ExternalNodeIP:NodePort
$ curl 220.127.116.11:31085
Hello, world!
Version: 1.0.0
Hostname: deployment-1-77ddb77d56-v5826

If you wouldn't create FirewallRule for this NodePort, curl output will be:
curl: (7) Failed to connect to 18.104.22.168 port 31085: Connection refused

Using Ngin Ingress Controller as baremetal considerations
When using Nginx Ingress you can use:

Over a NodePort Service
host network

You can depoy Nginx BareMetal using:
$ kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v0.41.2/deploy/static/provider/baremetal/deploy.yaml

It will create Nginx service as NodePort type. It's very similar to previous method, but difference is that your services can be ClusterIP and NodePort type.
You can apply Ingress to expose more than 1 service using this method.
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - http:
      paths:
      - path: /one
        backend:
          serviceName: service-one
          servicePort: 80
      - path: /two
        backend:
          serviceName: service-two
          servicePort: 80

$ kubectl get svc -A
NAMESPACE       NAME                                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
default         service-one                          ClusterIP   10.106.21.3      <none>        80/TCP                       2m4s
default         service-two                          ClusterIP   10.105.161.86    <none>        80/TCP                       2m2s
ingress-nginx   ingress-nginx-controller             NodePort    10.110.149.194   <none>        80:31337/TCP,443:30417/TCP   6m31s
ingress-nginx   ingress-nginx-controller-admission   ClusterIP   10.98.15.73      <none>        443/TCP                      6m31s

### Output:
$ curl 126.96.36.199:31337/one
Hello, world!
Version: 1.0.0
Hostname: deployment-1-77ddb77d56-v5826
curl 188.8.131.52:31337/two
Hello, world!
Version: 2.0.0
Hostname: deployment-2-fb984955c-8pfls


Can an R function ever return nothing, as in []?

Question: Anyone who has played around with R for a little while knows that there is a a difference between genuinely nothing and any of NULL, 0, objects of length 0:
> a<-list(1,2,3,4)
> a[]#"Genuinely nothing"
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

> a[NULL]
list()
> a[0]
list()
> a[integer(0)]
list()

This first case has my interest. Is there any way to make an R function return what I've called "genuinely nothing", so that a[foo] returns all of a and interacts with subassignment like a[] does? I'm aware of equivalent behavior, like a[TRUE], but I want to know if it's possible to have a function return what I'm calling "genuinely nothing". Presumably, the example that I've given must be feeding some sort of argument to [, so it should exist in R somewhere.
Comment: This might shed some light on it: https://stackoverflow.com/questions/20904827/the-representation-of-an-empty-argument-in-a-call/20906150 But basically there's no object in user space that you can easily pass that will act like an empty argument.
Answer: As pointed out by Hadley in the comments of the above mentionned post:
a <- list(1,2,3,4)

foo <- function() {quote(expr=)}
a[foo()]

#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 2
#>
#> [[3]]
#> [1] 3
#>
#> [[4]]
#> [1] 4

Comment: Maybe that will work in terms of this specific use with the `[` operator, but it doesn't work in the general case for all functions: `b <- function(x=6) print(x)` where `b(foo)` is not the same as `b()`
Comment: @MrFlick, you're right, as the empty object exists, the `b` function doesn't use its default argument value. This is genuinely empty but not genuinely nothing ;-)
Comment: That's why it might be better just to mark this as a dup since this is just a copy of the information that's already on the other question and the other question has a fuller discussion of the topic.
Comment: @MrFlick, agree


Why the approximation of $\log \pi_{\theta}(a|s)$ improves numerical stability?

Question: In Maxim Lapan's book Deep Reinforcement Learning Hands-on, section Continuous A2C, it says

By definition, the probability density function of the Gaussian
  Distribution is $$f(x | \mu, \sigma^2) = \frac{1}{\sqrt{2 \pi
 \sigma^2}} e^{-\frac{(x-\mu)^2}{2 \sigma^2}}$$ We could directly use
  this formula to get the probabilities, but to improve numerical
  stability, it is worth doing some math and simplifying the expression
  for $\log \pi_{\theta}(a|s)$.
The final result will be this: $\log \pi_{\theta}(a|s) =
 \frac{-(x-u)^2}{2 \sigma^2} - \log \sqrt{2 \pi \sigma^2}$

Can you explain to me how to get the approximation of  $\log \pi_{\theta}(a|s)$? How does it improve the numerical stability?
Comment: You are missing a negative sign in the exponential in the initial density function.  Taking logarithms gives you the result (which is exact, not an approximation).
Answer: If you take the log of $f(x\vert \mu, \sigma^2)$, you get the expression you want.  I'm not sure why the author wants to change from $f$ to $\pi_\theta$, but perhaps he explains the notation elsewhere earlier in the book.
As for numerical stability, you're likely going to be talking about likelihood functions sooner or later.  The likelihood is the product of density values evaluated at the data.  It looks like
$$ \prod_i f(x_i, \mu, \sigma^2)$$
If many of the $f(x_i\vert \mu , \sigma)$ are smaller than one, we risk underflowing when computing this product.  Working with the log-likelihood combats this problem while retaining all the information about the location of the optima of the likelihood.
Answer: Look at the standard normal PDF and the range of values within $x=[0,9]$:

The Gaussian PDF values go from 0.4 to 1e-18, while their log varies from -0.9 to -41. Numerical algorithms are less stable when the values vary too much, especially when the sensitivity is so different at different values of x. Logarithm of PDF is very steady though.
This is especially important when you have products of PDF, such as likelihood expressions.
Answer: This computational principle applies in a wide range of probability problems involving density and mass functions.  The reason for this advice is that probability density values can be very small positive numbers, and when you try to compute these directly from the density formula you can get a problem of arithmetic underflow.  This occurs when numbers involved in the computation are smaller than the smallest positive number represented by the computational facility, so they get rounded down to zero in the computation.  This causes inaccuracy in computation when you are dealing with formulae involving very small positive numbers.
By transferring over to "log-space" you convert small probabilities into non-small negative numbers, and this massively reduces the problem of arithmetic overflow.  For this reason, algorithms used to compute density and mass functions almost always conduct their computations in log-space and then exponentiate to get back to regular probability space at the end of the computation.  (For details on computing in log-space see related questions here and here.)


Travel time of $n$ people by group: generalizing the Bridge-and-Torch Problem

Question: I am working on a project related to an emergency evacuation:

Find the minimum time to make $n$ people to evacuate the city (travel time of the slowest). There is 1 vehicle that can contain $p$ people and travel at the speed of the slowest person of the group. One person has to bring back the vehicle used for transportation.

This problem is a generalization to the bridge crossing / torch problem.
I found solution for $p \leq 2$ which comes down to sort the people by travel time and to iterate pairwise whether it is better for the pair of people to travel together using 2 runners or to travel separately using 1 runner.
I tried to adapt it for $p=3$ but things escalated quickly and I ended up with many strategies to compare for every group of 3 persons with 1, 2, 3 runners and could not find a way to generalize for $p \geq 3$.
Comment: If a recurrence relation cannot be found, it is likely that it is NP-hard if p is unbounded. If p is constant, it feels like there is a polynomial-time algorithm with respect to n. (It would be exponential with respect to p.)
Comment: I am not entirely sure that I understand the problem---people cannot move unless they are in the vehicle?   There is no walking out?  Also, I am unfamiliar with "the bridge crossing / torch problem".  Could you please explain the rules in a little more detail?
Comment: @XanderHenderson: https://en.wikipedia.org/wiki/Bridge_and_torch_problem
Comment: @MaxFt The [PDF](http://aps.cs.nott.ac.uk/wp-content/uploads/2008/05/capacity-c-torch-problem-aps-club.pdf) at the bottom of the [Bridge and torch problem Wikipedia page](https://en.wikipedia.org/wiki/Bridge_and_torch_problem) has a polynomial-time solution.  Is checking references so hard?
Comment: @dtldarek Bridge and torch problem page from Wikipedia does not at all deal with my problem. Do not think any references deal with the problem of $p\geq 3$. If you find an article I would be grateful
Comment: @MaxFt How so? From the current formulation it looks exactly the same (where your car is $p$-capacity torch). Either I have failed to understand what you have written, or there are some important details missing.
Comment: If it is the first "External links" from the wiki page it is the only link I can not open... I checked all other references. One of the link gives a example of solution for k = 3 but no general algorithm https://www.math.uni-bielefeld.de/~sillke/PUZZLES/crossing-bridge.
I can not open the PDF link either on my phone or my desktop. =(
Comment: Yeah, it appears that [aps.cs.nott.ac.uk](aps.cs.nott.ac.uk) is down right now. That's the department where Roland Backhouse is, and it looks like he's the author of a few papers on the subject, including that top *External Link* on Wikipedia. It looks like they just [changed their website structure](https://www.nottingham.ac.uk/computerscience/index.aspx), so maybe that particular file just got moved somewhere new.
Answer: I would check out the paper The capacity-$C$ torch problem (behind a paywall) and this similar (same?) paper The Capacity-$C$ Torch Problem
Full Version (including all proofs) (pdf) by Backhouse and Truong. Since the answer to your question is the subject of these research papers, it'd be tough to synthesize their algorithms into a response here, so I won't, but they appear to contain an algorithm that solves the question you are seeking to answer.

Abstract
  The torch problem (also known as the bridge problem or the flashlight problem) is about getting a number of people across a bridge as quickly as possible under certain constraints. Although a very simply stated problem, the solution is surprisingly non-trivial. The case in which there are just four people and the capacity of the bridge is two is a well-known puzzle, widely publicised on the Internet. We consider the general problem where the number of people, their individual crossing times and the capacity of the bridge are all input parameters. We present two methods to determine the shortest total crossing time: the first expresses the problem as an integer-programming problem that can be solved by a standard linear-programming package, and the second expresses the problem as a shortest-path problem in an acyclic directed graph, i.e. as a dynamic-programming problem. The complexity of the linear-programming solution is difficult to predict; its main purpose is to act as an independent test of the correctness of the results returned by the second solution method. The dynamic-programming solution has best- and worst-case time complexity proportional to the square of the number of people. An empirical comparison of the efficiency of both methods is also presented.
Comment: Thank you  I am taking a look at it. It seems to be what I wanted ! I will see if I can understand the principles of the algorithms.


Is accessing the current node from multiple block plugins on a single page costly from a performance perspective?

Question: I use a combination of Block plugins and panels to populate the layouts of the display modes of various content types.
Here's an example:
<code>class MyBlockPlugin extends BlockBase
{
    /**
     * {@inheritdoc}
     */

    public function build()
    {
        $node = \Drupal::routeMatch()->getParameter('node');
        $profile_pic = ImageStyle::load('350x300')->buildUrl($node->field_image->entity->getFileUri());
        return [
            '#theme' => 'mytwigtheme',
            '#name' => $node->title->value,
            '#headshot' => $profile_pic
        ];
    }
}
</code>
It certainly works but I'm wondering if this is a bad path to travel because I'll have multiple block plugins loading and accessing the same node. I suppose I could access the node with a preprocess block hook but I'm assuming that will load for every block as well.
If the performance cost is trivial then I'm not too worried about redundancy. Is my method okay? If not, what would be a better way for a block plugin to access the data of the current node it appears on?
Update:
Just another thought. Is me using a twig template making this a non issue as long as it's been loaded before?
Answer: No performance issue concerning the node entity, which is loaded only once per request and then stored in memory.
For caching between requests there are also no performance issues, because the rendered twig template(s) of a block are cached by default. But you have to make sure you provide the correct cache data, which is possible via a plugin context in the annotations (preferred) or by adding the cache metadata to the render array. See Block cache depending on current node and its last modification time
Comment: Yes, otherwise the block doesn't update when the node is modified and, even worse, it is displayed on the wrong node pages.
Comment: So the way I had doing it is mostly fine and to make it better I could just add something like ''#cache' => array(
                'tags' => array('node:' . $node->id()),
                'contexts' => array('url'),
            ),' to the render array?


How to safely delete IIS7 Logs

Question: I've google'd for this without much luck.. but I'm looking for an manual (one time run, free) / open source way to safely clear iis logs from /inetpub/logs/logFiles
I've seen ppl refer to isslogs.com, I have no idea how reliable that is, but even then I dont want any kind of scheduled task nor wish to pay for something i'm not really going to use often
I just want a simple safe way to delete all logs from inside the multiple folders in /inetpub/logs/logFiles
Recommendations or walkthroughs on how these can be removed would be appreciated.
Comment: Why don't you just delete them in Explorer or on the command line?
Comment: The point is that this *isn't* a one-time-only task. For the duration of your time administering this server, you will need to keep a lid on log-file growth. The easiest way to do that is with a scheduled task that does the same thing every day (or week, whatever.)
Comment: Explorer looks like alot of hard work with the number of different folders. No idea how to do from the command line. + I cant stop IIS so the active log, whichever that is cannot be deleted.
Comment: i think you need to clarify the question a bit. You will have to have some sort of scheduled task to keep removing them or they will just grow and grow (unless you turn logging off). While iis is running nothing will be able to get rid of the current log, so you will have to stop it. I would write a batch file to stop iis in the middle of the night, then remove the logs, then star iis again
Comment: As I said this is a one-time run only task. I dont want to schedule anything but wish to save myself a few hours doing this manually.
Comment: I'm doing it the one time, and nor am i a server admin. I have been delegated to do this by the powers that be. N quite simply I want to achieve it in the most risky free, future impact, or bite me in the @rse way in the future when the actual server admin returns.
Comment: Ah, I see. Whoever is the server admin is, isn't on top of things, then.
Comment: If you read the FAQ, you'd see why we're hammering the point home. We're assuming this system is yours to manage.
Answer: Here is a script that deletes IIS logfiles older that 90 days
MaxDays = 90
strComputer = InputBox("This script will delete IIS .log files over 90 days old "_
    & "from the machine you specify below.")
wmiQuery = "Select * from Win32_OperatingSystem"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery(wmiQuery)
    For Each objItem In colItems
        sWindowsPath = objItem.WindowsDirectory
    Next
Set objW3SVC = GetObject( "IIS://" & strComputer & "/W3SVC")
    For Each objSite In objW3SVC
        If objSite.Class = "IIsWebServer" Then
            strLogDir = UCase(objSite.LogFileDirectory)
                strLogDir = Replace(strLogDir,"%WINDIR%",sWindowsPath,1,1,1)
                strLogDir = Replace(strLogDir,"%SYSTEMROOT%",sWindowsPath,1,1,1)
                strLogDir = Replace(strLogDir,":","$",1,1,1)
            objLogFolder = "\\" & strComputer & "\" & strLogDir
            Set oFSO = CreateObject("Scripting.FileSystemObject")
            Set oFolder = oFSO.GetFolder(objLogFolder)
            Set colSubFolders = oFolder.Subfolders
            For Each oSubFolder In colSubFolders
                If InStr(UCase(oSubFolder),"W3SVC") Then
                    For Each oFile In oSubFolder.files
                        If InStr(LCase(oFile.Name),".log") Then
                             If (Date - oFile.DateCreated > CInt(MaxDays)) Then
                                oFSO.DeleteFile(oSubFolder & "\" & oFile.Name)
                            End If
                        End If
                    Next
                End If
            Next
        End If
    Next
MsgBox("All done.")

Comment: How do I use this, where do I execute the script?
Comment: Copy this into notepad and save it somewhere as script.vbs, or something like that To run it open the command prompt and type cscript script.vbs.
Comment: You save this as script.vbs and then you run it.
Answer: You can use the /S flag to del to force it to delete files in subdirectories. The /Q flag will prevent it prompting you - omit it if you want to be cautious. So something like:

del /S/Q logdir\*.log

If you want to also delete sub-directories, you can use 'rmdir'. it has the same two flag options.
Answer: This one worked best for me.  Save as Retention.vbs and run or schedule.
Source: https://docs.microsoft.com/en-us/iis/manage/provisioning-and-managing-iis/managing-iis-log-file-storage
sLogFolder = "c:\inetpub\logs\LogFiles"
iMaxAge = 30   'in days
Set objFSO = CreateObject("Scripting.FileSystemObject")
set colFolder = objFSO.GetFolder(sLogFolder)
For Each colSubfolder in colFolder.SubFolders
        Set objFolder = objFSO.GetFolder(colSubfolder.Path)
        Set colFiles = objFolder.Files
        For Each objFile in colFiles
                iFileAge = now-objFile.DateCreated
                if iFileAge > (iMaxAge+1)  then
                        objFSO.deletefile objFile, True
                end if
        Next
Next

How to safely delete IIS7 Logs


How can you prove that $\frac{a(a^2+2)}{3}$ is always an integer

Question: Where a is a non zero integer. I tried but I wasn't able to factor that 3 out
Answer: If $3\mid a$ we are done, if not either $a = 1 \pmod 3$ or $a = 2 \pmod 3$, either case $a^2+2 = 0 \pmod 3$.
Answer: You can write the numerator as

$$a^3-a\mod 3.$$

Fermat's little theorem says all $a$ are congruent to $a^3$ mod $3$, hence the numerator is divisible by $3$.
Comment: $a^3-a=(a-1)a(a+1)$
Answer: Just discuss the situation $a=3k, 3k+1, 3k+2$
Comment: I see your point. These situations are from the Division Algorithm, since $0\leq r \lt b$, right?


Prove that $\frac 12\leq \frac{1}{n+1}+\frac {1}{n+2}+\frac{1}{n+3}...+\frac{1}{n+n}$

Question: How do I prove $$\frac 12\leq \frac{1}{n+1}+\frac {1}{n+2}+\frac{1}{n+3}...+\frac{1}{n+n}$$
without using induction? Note that clearly $n\neq 0$
Thanks for any help!!
Comment: You can find several posts showing that this is at least $\frac{13}{24}$. For example http://math.stackexchange.com/questions/508664/proving-frac1n1-frac1n2-cdots-frac12n-frac1324-for
Comment: @JoshChen Why for $1$?
Comment: @tatan I think you need to check the question. Do we have to disprove the theorem? For n =1 , 1/(n+1) becomes 1/2. All the other terms will just add to it so L.H.S. will be greater than 1/2
Comment: @TonyClayton Yeah...I have given $\leq$ sign...
Answer: The reverse inequality is true for $n≥1$.
If $1≤k≤n$ then $\frac{1}{n+k}≥\frac{1}{n+n}$. Therfore, you get :

$$\frac{1}{n+1}+\frac {1}{n+2}+\frac{1}{n+3}...+\frac{1}{n+n} ≥ \frac{1}{n+n}+\frac {1}{n+n}+\frac{1}{n+n}...+\frac{1}{n+n} = n \cdot \frac{1}{n+n} = \frac{1}{2}$$
Answer: This inequality does not hold since for any $n\in \mathbb N$ you have
$$\frac{1}{2}\leq \frac{1}{n+1}+\frac {1}{n+2}+\frac{1}{n+3}+...+\frac{1}{n+n}.$$
To see this, note first that any term above is greater than $\frac{1}{n+n}$, so that your sum is greater than $n\cdot \frac{1}{2n}=\frac{1}{2}.$


Prove that $ N = \frac{5^{125} - 1}{5^{25} - 1} $ is a composite number.

Question:
Prove that $$ N = \frac{5^{125} - 1}{5^{25} - 1} $$ is a composite number.

I just proved it will be a natural number with
quotient= $5^{100} +5^{75}+5^{50}+5^{25}+1$
But I do not know how to factorise it for proving it composite.
Comment: How about you edit this question and include exactly what it is you don't understand?
Comment: Hint: try to factor the terms
Comment: Ya , I tried but wasn't able to do
Comment: This is a repetition of this post: [https://math.stackexchange.com/questions/2314779/prove-that-n-frac5125-1525-1-is-a-composite-number](https://math.stackexchange.com/questions/2314779/prove-that-n-frac5125-1525-1-is-a-composite-number)
Answer: By Aurifeuillean factorization, it's $(5^{50}+5^{38}+3\times5^{25}+5^{13}+1)(5^{50}-5^{38}+3\times5^{25}-5^{13}+1)$.


Proof of the theorem $(p\to\lnot q)\to(q\to\lnot p)$ in Classic logic

Question: Verify if the formula is a theorem in Classic Logic and prove it using the axiomatic system.

$(p\to\lnot q)\to(q\to\lnot p)$

I verify it and it's a tautology, so it's a theorem.
I also proved it but I didn't use the axiomatic system directly since we have proved in class 7 theorems and I used them to proof 1.
This is the proof I did:
$(p\to\lnot q)\vdash_{CL}(q\to\lnot p)$
by the deduction theorem, we have as hypothesis, $(p\to\lnot q),q$.
By theorem proved in class, $(p\to\lnot q)\to(q\to \lnot p)$ so now we have the result $(q\to \lnot p)$. With $(q\to \lnot p),q$ and Modus ponens, we have $\lnot p$. And again by the deduction theorem, $(q\to\lnot p)$.
Did I solve it correctly ??
Comment: Using the theorem to prove the theorem is quite circular.
Comment: you're right. Haven't notice, actually the proof doesn't have sense then.
Answer: I don't know which axiomatic system you are using, but to prove it by deduction I would assume $p\to\neg q, q,$ and $p$, so as to prove $(p\to \neg q)\to(q\to\neg p)$ via contradiction.
Comment: I see. And then modus ponens with $p\to\neg q, p$, and the result would be $\lnot q$.  And $q\land\lnot q\equiv C$ and there it is the contradiction.


Easier(better) way to write LINQ query

Question: I have two LINQ queries, I use the results of the 1st LINQ query and use a foreach loop to iterate through each element found and use it in the 2nd LINQ query
var entries = dbo.OnDemand.Where(c => c.LOTNO == LotNo).Where(c => c.ODHisDate >= start && c.ODHisDate <= end).Where(c => c.Activity.Contains(reprinted)).OrderBy(c => c.ODHisDate);

foreach (var X in entries)
{
    Barcodes.Add(X.Barcode);    // Barcodes is a List<string>
}

foreach (string barcode in Barcodes)
{
    var entries2 = dbo.OnDemand.Where(c => c.Barcode.Contains(barcode)).Where(c => c.ODHisDate >= start && c.ODHisDate <= end).OrderBy(c => c.ODHisDate);

    // Do stuff with entries2
}

Is there a way I could execute this using a single query?
I read around, and people use JOIN but I am not entirely sure how to use it.
Some of the expressions are common for both queries (the selected date range, and the ORDERBY by date)
Currently this way works but I think there is a better way of doing what I am trying to achieve.
Any help would be appreciated.
EDIT 1:
Sample SQL query:
select * FROM [dbo].[OnDemand]
where barcode in
(
SELECT [Barcode]
  FROM [dbo].[OnDemand]
  group by barcode
  having count(*) > 1
  )
 and odhisdate between  '2017-01-11' and '2017-01-31'

 and Activity like '%reprinted%'

  order by ODHisDate asc, ODHisTime asc

Comment: Could you explain a little the logic here?
Comment: Models would help.
Comment: @octavioccl - With the first query I get a list of barcodes that match the criteria. In the second query I get entries based on the each barcode
Comment: You should make your code as easy to debug as possible. Having a long linq statement would make it very difficult to debug since when you have an error in one of those statements, the stack trace only shows you the first line of those linq chain (i.e it would say line 1 even though the problem occurred in line 4). I'd suggest either having those condition checks in a select statement and having that select statement as a separate function or doing it one by one
Answer: As far as I can tell, there is no need for a JOIN because you are querying the same table and you are not trying to do a recursive or cross-join query.
Why do you query the same table with the same parameters? You get a List of entries back, then iterate through Barcode values and then go back again and query the same table with the same Barcode value.
If you want to iterate in-line, the syntax is straight forward, but I am not sure if you understand what you are doing there.
dbo.OnDemand.Where(c => c.Barcode.Contains(barcode))
    .Where(c => c.ODHisDate >= start && c.ODHisDate <= end)
    .OrderBy(c => c.ODHisDate)
    .ForEach(c =>
        {
            // do stuff
        }

Comment: Could you explain a bit more on your answer?
Comment: I won't know the barcodes until I run the first query. So I don't think I can use `.Where(c => c.Barcode.Contains(barcode))` but I'll try it
Comment: Do you have a sample SQL query? What you do is get all barcodes, then iterate through the barcodes that you just got and query the same table again? Why would you want to do that? At this point, barcodes don't even make any difference to you: what you get back you query again... with the same parameters. I simply take your query and do an in-line iteration on it.
Comment: I have added a sample SQL query which I used for testing
Answer: I guess you're doing this because there are elements with the same barcode. A solution could be:
var entries = dbo.OnDemand.Where(c => c.LOTNO == LotNo
                                   && c.ODHisDate >= start && c.ODHisDate <= end
                                   && c.Activity.Contains(reprinted))
                          .Select(c => c.Barcode);//Don't need to orderby here

// You will get a IEnumerable<List<OnDemand>> as result of this query
var entries2 =entries.Select(barcode =>  dbo.OnDemand.Where(c => c.Barcode.Contains(barcode)
                                                              && c.ODHisDate >= start && c.ODHisDate <= end)
                                                     .OrderBy(c => c.ODHisDate)
                                                     .ToList());

foreach (var list in entries2)
{
 // do stuff
}

Better Idea could be filter first by the common conditions, later group by barcode and then keep those groups who have an element that meets the second where conditions
var entries = dbo.OnDemand.Where(c.ODHisDate >= start && c.ODHisDate <= end)
                          .GroupBy(c=>c.BarCode)
                          .Where(g=>g.Any(c=>c.LOTNO == LotNo && c.Activity.Contains(reprinted) ))
                          .Select(g=>g.OrderBy(c => c.ODHisDate).ToList());

Update
var entries = dbo.OnDemand.Where(c.ODHisDate >= start && c.ODHisDate <= end && c.Activity.Contains(reprinted))
                          .GroupBy(c=>c.BarCode)
                          .Where(g=>g.Count()>1)
                          .Select(g=>g.OrderBy(c => c.ODHisDate));

Comment: yes you are right there are elements with the same barcode, I am trying to display information when reprinted barcodes are found. I also removed the `orderby` in the first query
Comment: your query in your edit is different and simplifies the problem
Comment: I was using that query in the SQL server management studio for testing,  but I don't know how to write it in C#
Comment: No I haven't tried it yet. I'll try it when I get the chance and let you know the result
Comment: I modified your updated query and now it works. Thanks for your help. Thanks to @bc004346 for suggested answer

Easier(better) way to write LINQ query


Quotient objects, their universal property and the isomorphism theorems

Question: This is a question that has been bothering me for quite a while. Let me put between quotation marks the terms that are used informally.
"Quotient objects" are always the same. Take groups, abelian groups, rings, topological vector spaces for example. Inside every object there are certain "subobjects" that we can divide by: normal subgroups, subgroups, ideals and subspaces with the subspace topology, respectively.
I (think I) know from an universal algebra viewpoint (of which I know nothing) that in the case of "algebraic" objects, the "subobjects" we take the quotient by are determined by congruences: equivalence relations on the cartesian product that respect the operation(s).
The first problem is:
1) How to define categorically the "subobjects" by which we take quotients?
Now, the resulting "quotient object" $G/N$ always satisfies the same universal property: it comes with a morphism $\pi$ such that $\pi:G\to G/N$ and $N\subset ker \,\pi$, which is universal with respect to this: any other such morphism factors through $\pi$.
The second (intimately linked) problem is:
2) How to define categorically these "quotient objects" and express in fancy terms the universal property they satisfy?
Now, in "algebraic" categories there are well-known isomorphism theorems. In the Wikipedia link, it is explained that they are all a special case of the universal algebra statement.
3) How can we express them in categorical terms?
Any insightful answer, even if partial, will be very welcome.
Comment: Just a technical quibble: topological quotients are by equivalence relations, not subspaces.  Even if your equivalence relation is defined to identify all points in a given subspace, the subspace topology isn't really involved.  This may or may not have implications for whether topological quotients fit into the general scheme you're asking for.
Comment: @Bruno: There is already a notion of quotient object (it is the dual of a subobject), but the ones you are referring to seem to be coequalisers of some kind. Is this the kind of answer you want?
Comment: Let me also point to [this answer](http://math.stackexchange.com/questions/14282/why-do-we-define-quotient-groups-for-normal-subgroups-only/14315#14315), which will give you some of the flavor of congruences, and recommend, yet again, George Bergman's excellent [Invitation to General Algebra and Universal Constructions](http://math.berkeley.edu/~gbergman/245/) which will give you the universal algebra *in* a categorical context.
Comment: @Zhen: The problem is mainly that in non-"algebraic" categories there are at least 5 notions of epimorphisms see e.g. [Adámek-Herrlich-Strecker](http://katmat.math.uni-bremen.de/acc/acc.pdf) page 121 that deserve to be called such (the cancellation property of epimorphisms is far too weak for many purposes). Somewhere in SGA 4/1 there are even more such notions. Calling the codomain of an epimorphism a quotient is most of the time not what you want (as witnessed by this question). As you suspect, Bruno seems to be after *regular epimorphisms* (those arising as coequalizers).
Comment: I should have thought of it earlier, but since I never really read that book, I forgot about it. Unification of isomorphism theorems and similar algebraic lemmas is one of the main aims of Borceux-Bourn, *[Mal'cev, protomodular, homological and semi-abelian categories](http://books.google.com/books?id=olmeksCI22cC)*, maybe it contains some of the results you're looking for. See also the [n-lab entry](http://ncatlab.org/nlab/show/Borceux-Bourn) on that book.
Comment: Even in algebraic categories, quotients are not necessarily defined via "subobjects". Quotients in semigroups are defined via **congruences**, not subsemigroups. (There is a connection: a congruence is an equivalence relation that, when considered as a subset of $S\times S$, is a subsemigroup of $S\times S$; but you have to go to a different object before you can identify quotient of $S$ with subobject, and not with a subjobject of $S$ in any case).
Comment: @yoyo: I know what an abelian category is. What does it have to do with this? The category of groups is not abelian, for example, and all that's stated in the question applies to it.
Comment: @Noah: right. I changed $Top$ to $TVS_k$.
Comment: @Theo: Thanks for the references. I've never gotten around to reading _Joy of Cats_; perhaps I should if it contains such gems!
Comment: @Zhen: I admittedly never had the patience to go through it. I use it mostly as a reference work. One of the great things about it is that the electronic version is cross-referenced very well and has an extremely extensive index, so it's easy to locate what you need (if it's in there).
Answer: First of all, let me say that there already well-defined notions of subobjects and quotient objects in category theory. I'll state them here for reference:
Definition. A subobject of an object $A$ in a category $\mathbf{C}$ is an equivalence class of monomorphisms with codomain $A$, where we identify two monomorphisms $m : B \to A$, $m' : B' \to A$ as equivalent just if there is an isomorphism $f : B \to B'$ such that $m = m' \circ f$.
Definition. A quotient object of an object $A$ in a category $\mathbf{C}$ is a subobject of $A$ in the opposite category $\mathbf{C}^{\textrm{op}}$. Explicitly, it is an equivalence class of epimorphisms with domain $A$, where we identify two epimorphisms $e : A \to B$ and $e' : A \to B'$ as equivalent just if there is an isomorphism $f : B' \to B$ such that $e = f \circ e'$.
But we shall see by means of examples that these aren't necessarily what we want them to be.
Example. In the category of topological spaces, subspaces are subobjects. But so are other things. Indeed, if $B$ has a finer topology than $A$, then $B$ is also a subobject of $A$.
Example. In the category of monoids, $\mathbb{Z}$ is a quotient of $\mathbb{N}$, because the natural inclusion map $\mathbb{N} \hookrightarrow \mathbb{Z}$ is epic.
The problem is that the notions of monomorphism and epimorphism are a bit too general to capture the properties we want. So we should begin by defining some 'stronger' notions of mono/epi.
Definition. A regular monomorphism is an monomorphism which is an equaliser of some pair of parallel morphisms. A regular epimorphism is a coequaliser of some pair of parallel morphisms.
Example. The kernel of a group/ring/module/etc. homomorphism is a regular monomorphism: indeed, $\ker f$ is the equaliser of $f$ and the zero morphism.
Example. Conversely, in an abelian category, every regular monomorphism is a kernel: indeed, the equaliser of $f, g : A \to B$ is precisely the same thing as $\ker (f-g)$, by the above observation.
Example. In the category of topological spaces, the inclusion of a subspace $B \hookrightarrow A$ is a regular monomorphism: it is the equaliser of its characteristic map $A \to 2$ (where $2$ is given the indiscrete topology) and a constant map. Conversely, every regular monomorphism is (isomorphic to) the inclusion of a subspace.
This suggests we're on the right track. Let's look now at the epimorphisms.
Example. The coimage of a group/ring/module/etc. homomorphism is a regular epimorphism: indeed, $\operatorname{coim} f$ is the coequaliser of $\ker f$ and the zero morphism. In particular, the projection maps onto quotient groups/rings/modules/etc. are regular epimorphisms. The converse is true in abelian categories by an argument similar to the one before.
Example. Let $A / R$ be the quotient of a topological space $A$ by an equivalence relation $R$. Then the projection map $\pi : A \to A / R$ is a regular epimorphism. Recall that $R$ is a subset of the cartesian product $A \times A$; so let us take $A \times A$ with the induced product topology and topologise $R$ with subspace topology. Then we have reified $R$ as an object in $\textbf{Top}$. Let $p_1, p_2 : R \to A$ be the projections. It is not hard to verify that $\pi : A \to A / R$ is the coequaliser of $p_1$ and $p_2$, so it is indeed a regular epimorphism.
Unfortunately, it turns out that in the category of groups, monomorphisms and regular monomorphisms are the same thing. (For a proof, see here.) So perhaps regular monomorphisms aren't a perfect fit for what we're looking for. Nonetheless, in sufficiently nice categories, we do have the following analogue of the first isomorphism theorem:
Theorem. In any regular category, (the domain of) the image of a morphism is isomorphic (the codomain of) its regular coimage (the coequaliser of its kernel pair).
Examples. Any abelian category is regular, as is any semiabelian category and any topos.
So I think this is probably the right level of generality, even though it doesn't cover the category of groups or the category of topological spaces. (In fact, the conclusion of the above theorem is blatantly false in the category of topological spaces: intuitively, the regular coimage is topologised by the domain, while the image is topologised by the codomain; so, for example, the map from a discrete space to an indiscrete space will have non-isomorphic image and regular coimage.)
Comment: As you say, this notion of quotients is suitable in essentially algebraic contexts. In most of the categories I encounter the notion of quotient objects is more or less of no interest. As I pointed out in a comment above there has been considerable effort of trying to unify all the similar lemmas. I basically agree with you that what you describe is the right generality because everything else tends to become unreadable. Anyway, a very nice answer!
Comment: @Bruno: Ah, but it wouldn't say anything about the category of sets or the category of topological spaces, which don't have zero morphisms. I had thought about saying something about normal monomorphisms but in the end it seemed like cheating.
Comment: The final theorem you state: can it be stated that the coequalizer of the kernel pair is isomorphic to the equalizer of the cokernel pair?
Comment: Thank you for your answer. What about considering a category with zero morphisms and normal monomorphisms? This would cover at least the category of groups. At any rate I'm still not fully satisfied, as per your comment on your last paragraph... maybe category theory is not the right language to express what is at hand?


É correto repetir o atributo itemprop?

Question: Queria saber se repetir itemprop dessa forma está errado. Na verdade, eu quero mostrar 3 produtos e colocar os respectivos itemprop de cada situação:

produto1

produto2

produto3

Está correto dessa forma?
Comment: Relacionado: https://pt.stackoverflow.com/q/91330/8063
Comment: Bom também: https://www.w3.org/TR/microdata/
Comment: https://schema.org/docs/gs.html#microdata_itemprop
Answer: Não é proibido, estar correto vai depender da finalidade a que quer chegar ao utilizar este atributo.
Como dito :

O atributo global  itemprop é usado para adicionar propriedades para um item. Todo elemento HTML pode ter um atributo itemprop  especificado, e um itemprop consiste em um par de nome e valor. Cada par de nome e valor é chamado de propriedade, e um grupo de uma ou mais propriedades forma um item.

Vai depender do itemscope
Comment: o itemscope é organization...

É correto repetir o atributo itemprop?


Composition of stable-pseudomonomorphisms

Question: Terminology
Let $\mathbf{C}$ be a finitely-complete finitely-cocomplete category with zero object (not necessarily additive!).  A morphism $f\colon A\rightarrow B$ is a pseudomonomorphism iff $(0\rightarrow A)=\ker (f)$, and dually for pseudoepimorphism.  A pseudomonomorphism is stable iff its push-out along any morphism is a pseudomonomorphism, and dually a pseudoepimorphism is stable iff its pull-back along any morphism is a pseudoepimorphism.
Question
Let $f\colon A\rightarrowtail B$ and $g\colon B\rightarrowtail C$ be stable-pseudomonomorphisms such that both $\operatorname{coker}(f)$ and $\operatorname{coker}(g)$ are both stable-pseudoepimorphisms.  Does $g\circ f$ likewise have these properties?
Unless I made a mistake, I was able to show that $g\circ f$ is a stable-pseudomonomorphism.  What I do not know is if $\operatorname{coker}(g\circ f)$ is a stable-pseudoepimorphism.
In other words, is the collection of stable-pseudmonos whose cokernels are stable-pseudoepis closed under composition?
Answer: It seems as if it is true.
We must check that $\operatorname{coker}(g\circ f)$ is a stable-pseudoepimorphism.  So, let $x\colon X\rightarrow \operatorname{Coker}(g\circ f)$ be arbitrary and consider the pull-back

Want want to show that $c'$ is a pseudoepimorphism.
As $\operatorname{coker}(g)\circ (g\circ f)=0$, $\operatorname{coker}(g)$ factors through $\operatorname{Coker}(g\circ f)$, and so there is a unique morphism $\alpha \colon \operatorname{Coker}(g\circ f)\rightarrow \operatorname{Coker}(g)$ such that $\operatorname{coker}(g)=\alpha \circ \operatorname{coker}(g\circ f)$.  Now form the two displayed consecutive pull-backs, with $\twoheadrightarrow$ used to denote morphisms which we know to be stable-pseudoepimorphisms.  (Note that pull-backs of stable-pseudoepimorphisms are again stable-pseudoepimorphisms.)

As $\operatorname{coker}(g)\circ x'=\alpha \circ \operatorname{coker}(g\circ f)\circ x'=\alpha \circ (x\circ c')$, because the bottom square is a pull-back, there is a unique morphism $\beta \colon C'\rightarrow C''$ such that $x'=\alpha '\circ \beta$ and $x\circ c'=c''\circ \beta$.  The second equation here immediately gives us, using the fact that the top square is a pull-back, a unique morphism $\gamma \colon C'\rightarrow C'''$ such that $\beta =x''\circ \gamma$ and $c'=c'''\circ \gamma$.
Now consider the following diagram.

We wish to show that the bottom square is a pull-back.  Then, as the middle square and the outer-rectangle are pull-backs, it will follow that the top square is a pull-back, whence it will follow that $c'$ is a pseudoepimorphism, as desired.
So, let $a\colon Y\rightarrow C$ and $b\colon Y\rightarrow \operatorname{Coker}(g\circ f)$ be such that $\operatorname{coker}(g\circ f)\circ a=\operatorname{id}_{\operatorname{coker}(g\circ f)}\circ b$.  Then, $\alpha \circ b=\alpha \circ \operatorname{coker}(g\circ f)\circ a=\operatorname{coker}(g)\circ a$, and so as the bottom square of the second displayed equation is a pull-back, there is a unique morphism $y\colon Y\rightarrow C''$ such that $a=\alpha '\circ y$ and $b=c''\circ y$.  Thus, indeed, the bottom square in the third displayed equation is a pull-back, as desired.


What is the "unicital complement" really called, and which lowersets $\lambda$ satisfy $(\lambda^{\perp})^{\perp}= \lambda$?

Question: Whenever $P$ is a poset, write $L(P)$ for the collection of lowersets of $P$: $$L(P) := \{\lambda \subseteq P : \forall x,y \in P : x \leq y \,\&\, y \in \lambda \rightarrow x \in \lambda\}$$
With that notation in place, we can define "unicital complements" as follows, where $X$ is an arbitrary set:
$$L(\mathcal{P}(X)) \rightarrow L(\mathcal{P}(X)), \quad \lambda \mapsto \lambda^\perp$$ $$\lambda^\perp := \{x \in \mathcal{P}(X) : \forall y \in \lambda : |x \cap y| \leq 1\}.$$
In words: given a lowerset $\lambda$ of $\mathcal{P}(X)$, we get another lowerset $\lambda^\perp$ defined as the collection of all subsets of $X$ that intersect each element of $\lambda$ in at most one point. Call this the unicital complement of $\lambda$.

Mini Question. What is the "unicital complement" of a collection of subsets really called, and has it been studied anywhere? (Please answer in the comments section.)

Remark 0. This is an orthomap, or in other words an antitone Galois connection whose domain and codomain are identical.
Remark 1. If $P$ is a partially ordered set, then $\mathrm{Chain}(P)$ and $\mathrm{Antichain}(P)$ are unicital complements of each other.

Definition. Call $\lambda$ unicital-closed iff $(\lambda^\perp)^\perp = \lambda$.

Remark 2. Not every lowerset satisfies $(\lambda^\perp)^\perp = \lambda$. For example, let $X$ denote a set and let $\lambda$ denote the empty subset of $X$. Then $\lambda^\perp$ is the collection of all subsets of $X$, and hence $(\lambda^\perp)^\perp$ is the collection of all subsets of $X$ with at most one element.

Main Question. Given a set $X$, can we usefully characterize those lowersets $\lambda$ of $\mathcal{P}(X)$ that are unicital-closed?
Answer: Let $\lambda$ be in $L(\mathcal P(X)$. Define $\lambda_2$ to be the set of all the members of $\lambda$ that have exactly two elements. Note that $\lambda^\bot$ consists of exactly those subsets $x$ of $X$ that have no subset in $\lambda_2$.
As a consequence, if $\mu$ is another element of $L(\mathcal P(X))$, then $\lambda^\bot=\mu^\bot$ if and only if $\lambda_2=\mu_2$. Recall the general property of Galois connections that $\lambda^{\bot\bot}$ is the largest element $\mu$ in the poset such that $\lambda^\bot=\mu^\bot$. So in our situation, $\lambda^{\bot\bot}$ is the largest $\mu$ in $L(\mathcal P(X))$ such that $\lambda_2=\mu_2$.
That $\mu$ is simply the collection of those $x\subseteq X$ such that all $2$-element subsets of $x$ are in $\lambda_2$.
With this description of $\lambda^{\bot\bot}$, we get that $\lambda$ is unicital-closed iff, whenever it contains all $2$-element subsets of some $x\subseteq X$, then it also contains $x$.
Such families $\lambda$ have shown up in various contexts and, as a result, have various names. In connection with linear logic, Girard called them coherence spaces. They are also called clique complexes in graph theory. (The point is that $\lambda_2$ is the set of edges of a simple graph with vertex set $X$, and $\lambda=\lambda^{\bot\bot}$ consists all the cliques of that graph.) I've also seen such $\lambda$'s called flag complexes, but I don't remember where.
On the other hand, I don't recall having seen a name for the ${}^\bot$ operation.


Evaluate $\lim \limits_{n \to \infty\ } \Biggl( \frac{2,7}{(1+\frac{1}{n})^n}\Biggr)^n=0?$

Question: $\lim \limits_{n \to \infty\ } \Biggl( \frac{2,7}{(1+\frac{1}{n})^n}\Biggr)^n$
I would like to replace $(1+\frac{1}{n})^n$ by $e$, and then $\frac{2,7}{e}<1$, so $\lim \limits_{n \to \infty\ } \Biggl( \frac{2,7}{(1+\frac{1}{n})^n}\Biggr)^n=0$, and I will get correct result, but I think this replacement is inadmissible.
I'm looking for the easiest way ( without advanced tools)
Comment: The replacement is inadmissible but the idea can be used in a rigorous manner thanks to squeeze theorem. See my answer for details.
Answer: Yes the limit is zero indeed by root test
$$\sqrt[n]{\Biggl( \frac{2,7}{(1+\frac{1}{n})^n}\Biggr)^n}= \frac{2,7}{(1+\frac{1}{n})^n}\to\frac{2.7}e<1$$
As an alternative, to make your way rigorous we need to observe that eventually
$$\frac{2,7}{\left(1+\frac{1}{n}\right)^n}\le \frac{2,7}{\frac{e+2.7}{2}}<1$$
and conclude by squeeze theorem
$$\left(\frac{2,7}{\left(1+\frac{1}{n}\right)^n}\right)^n\le \left(\frac{2,7}{\frac{e+2.7}{2}}\right)^n\to 0$$
Comment: It's probably also worth noting that the proof in the question doesn't work, for precisely the same reason that $\left(1+\frac{1}{n}\right)^n \to \left(1 + 0\right)^n \to 1$ doesn't.
Comment: @matematiccc Since $\left(1+\frac{1}{n}\right)^n \to e$ eventually we have that it is greater that $2.7$ but smaller that $e$ (since the sequence is increasing).
Comment: I can't use methods which haven't been proven at my lectures.
Comment: @matematiccc I've added a secon way to prove that.
Comment: Could you explain why $\frac{2,7}{\left(1+\frac{1}{n}\right)^n}\le \frac{2,7}{\frac{e+2.7}{2}}$? I mean, why we can do it.
Comment: Why do you bring up $(e+2.7)/2?$ Seems odd to me.
Comment: @zhw. What would you select instead? we need a value between 2.7 and e, it seems the simpler to me.
Comment: $2.71\,\,\,\,\,$
Answer: It sounds like you already know that $(1 +1/n)^n \to e$.  By the definition of a limit: for all $\epsilon > 0$, there exists $N > 0$ so that $|(1 + 1/n)^n - e| < \epsilon$ for all $n \geq N$.
Consider $\epsilon = 1/100$.  Then, $|(1 + 1/n)^n - e| < 1/100$ for $n \geq N$ for some $N$.  Thus, $(1 + 1/n)^n \geq 2.708$ for $n \geq N$.
Finally we have $2.7 / (1 +1/n)^n \leq 2.7/2.708$, and hence $\left( 2.7 / (1 +1/n)^n\right)^n \leq \left(2.7/2.708\right)^n$ for $n \geq N$.
Comment: @ParamanandSingh Yes, it was posted 40 second earlier.  If you are interesting in nit-picking, then user gimusi posted this idea as a comment 5 hours ago.
Comment: This is same my answer which was posted a few minutes earlier.
Answer: You need two results here. First is that the limit of $(1+(1/n))^n$ exists and is commonly denoted by $e$. Second is the fact that $e>2.7$.
Next note that if $a_n=2.7/(1+(1/n))^n$ then by above two facts the sequence $a_n\to l$ where $0<l<1$. Let's choose a specific number $\epsilon>0$ such that $$0<l-\epsilon<l+\epsilon<1$$ This we can choose $\epsilon$ to be any positive number less than $\min(l, 1-l)$.
Since $a_n\to l$ it follows by definition of limit that there is a positive integer $m$ such that $$l-\epsilon <a_n<l+\epsilon, \forall n\geq m$$ Note that each term of the inequality is positive and hence if we raise each term to $n$'th power we get $$(l-\epsilon) ^n<a_n^n<(l+\epsilon) ^n, \forall n\geq m$$ Applying squeeze theorem we get the desired limit as $0$ because both $l-\epsilon, l+\epsilon $ lie between $0$ and $1$.
Answer: You're right –  one cannot replace only a part of an expression with its limit.
The simplest way consists in determining the limit of the log, using Taylor's formula at order $12$:
\begin{align}
n\log(2.7)-n^2\log\Bigl(1+\frac1n\Bigr)&=n\log(2.7)-n^2\biggl(\frac1n-\frac1{2n^2}+o\Bigl(\frac1{n^2}\Bigr)\biggr) \\
&=n\log(2.7)-n+\frac12+o(1)\\
&=n(\underbrace{\log 2.7-1}_{<\,0})+\frac12+o(1)\bigg]\to -\infty.
\end{align}
Without Taylor's formula:
From the inequalities $\;1-x<\dfrac1{1+x}<1$ $(x>0)$, you can deduce with the mean value theorem that
$$x-\frac{x^2}2<\log(1+x)<x\quad\forall x>0$$
so that
\begin{align}
n\log(2.7)-n^2\log\Bigl(1+\frac1n\Bigr)&<n\log(2.7)-n^2\biggl(\frac1n-\frac1{2n^2}\biggr) =
n(\underbrace{\log 2.7-1}_{<\,0})+\frac12
\end{align}
The same conclusion as above follows by the comparison theorem.
Comment: Thanks, I  understand it, but I can use at most squeeze theorem.
Comment: I've added a proof by the comparison theorem (no squeeze theorem required here since the limit of the log is $-\infty$).


How do I get the content underneath the bootstrap card when using position relative

Question: I am creating a bootstrap card with an image. The card body is moved up onto the image using position: absolute an top.
When I add a new div underneath the card, the div is pushed up to the image. I need the content to stay underneath the card body.
I hope this makes sense, but to clear any confusion, please check out the jsfiddle. If you need more information, let me know.
Here is an image of the dilemma:

Answer: Just remove position: absolute; top: 320px; left: 76px; styles from .card-body rule and add margin-top:-50px; margin-left: 50px; instead.

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}
.card {
    border: none;
}
.card-body {
  width: 80%;
   border: 1px solid rgba(0,0,0,.125);
    border-radius: .25rem;
    background: #fff;
    /*position: absolute;
    top: 320px;
    left: 76px;*/
    margin-top:-50px;
    margin-left: 50px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

    Go somewhere

I need this text to be underneath the card.I tried using margin-bottom for the card, but the problem with this is the content of the card body changed, therefore the height changes which is what i want.

You can test it here also.
Comment: I can't believe I didn't think of that. Thank you so much!
Comment: You got it buddy!


Why isn't the guitar tuned EADGCE?

Question: One of the most annoying idiosyncrasies of standard guitar tuning EADGBE is that third between the G and the B.  When you move chord shapes or scale patterns around the neck you always have to take account that G-B is a third instead of a fourth like the other strings.
I don't think it's a good idea to tune the guitar entirely in fourths as is suggested in Is even-interval tuning a sensible idea for lead guitar?
This question is not a duplicate also because I am interested in the historical reasons for the EADGBE tuning as discussed in Why is the guitar tuned like it is?
I don't think tuning in fourths is good both for ergonomic reasons and for open string reasons but I think that shifting the third from GB to CE in a EADGCE tuning takes advantage of the symmetry of the low E and high E strings. Chord shapes across the neck are also identically shaped for one more precious string.
Why isn't the guitar tuned EADGCE?  Is there an ergonomic reason or is it just historical, like QWERTY instead of Dvorak keyboards?
Comment: @ghellquist I think the point of the OP is to inquire as to why EADGBE evolved in the first place.  Regardless of alt tuning the standard is most widely used.
Comment: When you move chord shapes or scale patterns around the neck, you would always have to take account that C-E is a third instead of a fourth like other strings. You just move the 'problem' on. Every chord and scale pattern will need tweaking, but where's the advantage?
Comment: @pro First, it's a minor second. Second, both EADGCE and EADGBE are all fourths except one major third, so that the outer strings are both E. You are claiming that the former "takes advantage of the symmetry", implying that the latter doesn't. What do you mean?
Comment: For the historical context: the lute and viola da gamba were historically tuned in fourths except for a major third in the middle, which is at least more symmetrical than the guitar.  How (or whether) this led to guitar tuning I do not know.
Comment: @Tim, like I said, symmetry.  The low E string note positions are so ingrained in my consciousness, the high E comes for free.  Chord shapes are also identically shaped for one more precious string.
Comment: You may tune your guitar any way you wish (within some limits). So go ahead and try!
Comment: Isn't it simply to avoid having to use the fourth fret for "B", when all the other "white" notes are on the first three frets?
Comment: I don't understand your thing about "symmetry". How exactly is EADGCE more "symmetrical" than EADGBE?
Comment: Why not do perfect fourths all the way? `E A D G C F`. That `E` at the end of `E A D G C E` is a bit arbitrary.
Answer: I have answered a similar question in the past.  I do not believe that what others consider better tuning is really better.  Whether for ergonomic or other reasons what you think is better is based on what you play.  A lot of older classical guitar music plays very easily on the current standard tuning and I'd have to guess that over the centuries tuning options have converged on EADGBE for this reason.  Of course "easy" depends on your hand physiology, etc.  And one could argue that written music choices depend on the instrument.  I think they evolved together.  By the way, even classical guitar pieces call for alternate tuning!  By the way changing the B to a C doesn't result in any better tuning from the symmetry point of view IMO.  What argument supports that?
Here is my take on it.  If you explore chord forms you will find that many of the different chords within a key have IDENTICAL shape when moved across strings.  A case in point is the minor ii-V-i which is usually ii-7(b5) --> V7 --> i-7.  Believe it or not these are all identical in shape in one position in standard tuning.  One can find other examples common to classical, flamenco, jazz in major and minor keys.  Many guitarists seem obsessed with having all of one type of chord (e.g. all Maj, all min, etc) be the same shape everywhere on the guitar but in fact that does not help make them easier to play (unless you're playing power chords only).  To be able to play all three chords in a ii->V->I sequence with the same shape is far more advantageous since these chords will always (very likely to be fair) show up in a group.  This makes playing over the chords easy as well since the same scale patterns translate across the strings with the same fingering.  For me this became apparent the more I studied Latin Jazz and Spanish classical guitar music.  I think the standard tuning is very well suited for those genres.  And again, alt tuning is called for even in 150 yo music so that should be considered too.
Comment: Reminds me of all the guitar music by Classical-/Romantic-era composers like Fernando Sor that specifically calls to tune the 6th string down one whole tone--i.e. use Drop D tuning. Quite a few of those pieces actually use the low D now made playable this way.
Comment: Yes, Capricio Arab has drop D tuning.
Answer: I would suggest that you try out the tuning, and see what happens. You don't even need to do this on a real instrument, you can just work it out on paper.
One immediate problem I see is that the open E chord gets a lot messier. In standard tuning:
<code> E
</code>
But in EADGCE:
<code> %0/0.2/2.2/3.1/1.4/4.0/0
</code>
That E-shape chord is an absolute staple, and now you can't even play a basic major chord with a barre due to running out of fingers.
The fundamental "problem" of guitar is that there are more strings than fingers, so we need the tuning to help us out if we want to play 5- or 6-string chords. One of the main benefits of standard tuning is that two of the notes are the same, plus one is a fifth above, so barring takes care of three strings with one finger.
Now, you might notice that in EADGCE, you have four strings that are part of a single chord: C major. Thus, it results in an easily moveable C-shape chord. But this voicing is inferior, plus it makes the major third an open string so you can't easily convert this shape to minor.
Comment: If you play chords with string sets most of the time, which I do instead of playing all 6 strings this is isn't much of any issue. The advantage I mainly see is in symmetry of the chords and scales across the neck.
Answer: Well, just for a start, in standard tuning you have an inverted major triad on the D/G/B strings, and an inverted minor triad on G/B/E. This already makes many things easier.
Given that the most common scales that we use are themselves non-symmetrical, there is really no reason to think that tuning the guitar symmetrically will make anything easier. It will probably make it worse.
It's a musical instrument, not a computer. Note that the piano itself also has an irregular layout. The only instruments I can think of that are symmetrical are four stringed ones - but on many of those (violin family) you rarely play a full chord, and on others (banjo etc) you have more fingers than strings, which shifts the odds in your favour for chordal playing.
Answer: Stanley Jordan famously tunes his guitar in 4ths, i.e. EADGCF, which makes chord and scale shapes the same all over the fretboard. In the second video linked below, at around 13 minutes in, he explains the pros and cons of this tuning.
He mentioned somewhere else that it took him about one month to become completely familiar with the new tuning after switching from the standard one. But after that adjustment period, at least for him, everything was easier than before.
(Edit) Stanley Jordan starter pack:
Comment: Stanley also really committed to it. IIRC Stanley said that the frets work more like a piano and I think "Stanley Jordan trio live paris" is more informative regarding this. The double guitar performances have a tendency to mystify non-musicians. I mean Stanley is incredible, but the double hand technique (playing counterpoint) of piano is the main inspiration. ( https://www.youtube.com/watch?v=p9Ae3R6QP6c )

Why isn't the guitar tuned EADGCE?


GetElements from a URL with powershell

Question: I am trying to get all links for each object, in order to make a log of which items are new and which are old
I dont understand how to grab links from a shopping website...
Tis is the code that works.
$URI = 'http://superwidgets.wordpress.com/category/sql/'
$HTML = Invoke-WebRequest -Uri $URI
($HTML.ParsedHtml.getElementsByTagName('h2') | Where{ $_.className -eq 'entry-title' } )

(Ref: https://social.technet.microsoft.com/wiki/contents/articles/26009.getting-information-from-web-pages-via-powershell.aspx )
This code does not
$url = 'https://www.norrona.com/nb-NO/o/herre/?displaysize=L%7CM&s=7&h=69000'
$x = Invoke-WebRequest -Uri $URL
($x.ParsedHtml.getElementsByTagName('div') | Where{ $_.className -eq 'productcard' } )

WHY?
Answer: This works but there is no div element with a productcard classname. Html and Javascript are just a bunch of text that are not rendered by any browser when retrieved from PowerShell. This means all the javascript is not executed.
There is a

that probably should be invoked to render the elements you look for.
But this is another call to another web ressource that probably return javascript objects. This doesn't tell if the objects would be styled with a productcard CSS class when rendered by javascript code.
This is probably not the right way to get the product list. You should directly access the API (if available) to get the list of products. You can then use PowerShell to convert json to powershell objects with ConvertFrom-Json cmdlet.

GetElements from a URL with powershell


PHP white space

Question: PHP:
<?php
echo '
';
include 'world.php';
echo '
';

There is whitespace between each construct. Thanks!
Comment: @Madbreaks: Knowing the reason *why* is the best way to get the most helpful answer.
Comment: According to http://php.net/manual/en/language.basic-syntax.phpmode.php thats not suppose to happen.
Comment: Why is the "white space" an issue?
Comment: I have test your code and see whitespace only before `` and it is normal because you have "\r\n" after ``
Comment: @WesleyMurch Why does it matter? It's a valid question.
Comment: NOTE: I pasted the wrong code when I asked the question. Sorry about that!
Comment: `include` is also a language construct, not a function. References: http://lxr.php.net/xref/PHP_5_4/Zend/zend_language_scanner.l#1248 and http://lxr.php.net/xref/PHP_5_4/Zend/zend_language_parser.y#57. **DO NOT** use parentheses for language constructs.
Comment: Also: do not put `?>` for the last PHP processing block in the file, it's closed automatically by PHP, but it's cleaner, it avoids sending unwanted output to the browser. Reference, section 2.2 from PSR-2: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
Answer: <?php echo '
'; ?>

<?php echo '
';

No whitespace!
There is a line break after ?>
Comment: PHP eats up a single `\n` newline after each `?>`. So OP assuredly has other whitespace shuffled there. The linebreak after `` however can only be mitigated by removing it.
Comment: `echo` is not a function, but a language construct. Do not use parentheses to reflect that, even if it works with them. References: http://lxr.php.net/xref/PHP_5_4/Zend/zend_language_scanner.l#1138 and http://lxr.php.net/xref/PHP_5_4/Zend/zend_language_parser.y#140
Comment: Alternatively (maybe too obvious) `'; ?>`

PHP white space


Linear Programming Confusion about Complexity

Question: In the wiki page of Linear Programming is told that Linear Programming problems belong to P complexity class.
However, the method generally used to solve Linear Programming problems is the Simplex method that not belong to P. So, does this make Linear Programming problems exponentially complex ?
Comment: the performance of the simplex algorithm may also greatly depend on the specific pivot rule used. simplex method has polynomial smoothed complexity. Please check: [Complexity of the simplex algorithm](https://cstheory.stackexchange.com/questions/2373/complexity-of-the-simplex-algorithm)
Comment: As example Quick sort has worst complexity of $O(n^2)$ but it's still preferred instead of merge sort with $O(n\log n)$ worst complexity.
Answer: Linear Programming can be solved in polynomial time with ellipsoid algorithms.
However, in practice, the simplex algorithm is more efficient, despite the fact that its worst time run times are exponential.
So in summary : linear programming problems are not "exponentially complex", but they are typically solved with an algorithm that may run in exponential times in worst case scenarios.


preg expression to match four consecutive consonants excluding "chr" group

Question: $string = "sqrtpdrt"; // matched
$string = "qwntfschrprtkjs"; // not matched (contains chr group)

I use
preg_match('/[bcdfghjklmnpqrstvwxz]{4}/i', $string )

to match 4 consecutive consonants, but now I what to exclude strings containing "chr" group.
Comment: `chr` will be together or can they appear separately in the input?
Comment: Ok good then below answer should work.
Answer: It is not the best pattern of the world, but it must do the job:
preg_match('~(?!.*chr)^.*[bcdfghj-np-tvwxz]{4}~si', $string);

pattern details:
~                     # pattern delimiter
(?!.*chr)             # negative lookahead: not followed by something and "chr"
^                     # start of the string anchor
.*                    # anything zero or more times
[bcdfghj-np-tvwxz]{4} # (it's shorter with ranges!)
~si                   # the s modifier allows the dot to match newlines

you can also do the opposite:
preg_match('~(?=.*[bcdfghj-np-tvwxz]{4})^(?>[^c]++|c(?!hr))+$~is', $string);

pattern details:
~
(?=.*[bcdfghj-np-tvwxz]{4}) # lookahead: followed by something and 4 consonants
^
(?>                         # open an atomic group
    [^c]++                  # all that is not a "c"
  |                         # OR
    c(?!hr)                 # "c" not followed by "hr" (negative lookahead)
)+                          # repeat the group one or more times (possessive)
$                           # end of the string anchor
~is


how to get the height and width of image in javascript?

Question: I have a code where I am trying to get all images tag height and width.
var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third',  $(this)[0].height,  $(this)[0].clientHeight,  $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height'));                                                                                });

Even i tried for img in loop.
tried the same with width , the result will be either 0 or undefined.
  tried same thing for width.

Can you tell me where I am doing wrong
Answer: You are passing $(img) this should be only img inside you $.each.Also you where printing console.log('first',.. instead of this if your image has name attribute use that .
Here is demo code :

var img = $('.data').find('img');
$.each(img, function() {
  console.log($(this).attr("name") + "-> Height: " + $(this)[0].height + " Width:" + $(this)[0].width);
});

Comment: thank you for replying, even i tried for img , but the result is same
Answer: i was not getting the height and width of an image because the image load event happens very late in the load process
Finally I found an answer
var img = $('.data').find('img');
$.each(img, function() {
  $(this).bind('load', function() {
    console.log($(this).height);
  }
});

it worked for both img and $(img)


How to provide basis and the dimension of W? Give geometric interpretation of W.

Question: $W = { (x_1, x_2, x_3)^T: x_1\cdot  x_2\cdot x_3=0 }. $Is W a subspace? If yes, provide a basis and the dimension of W? Give geometric interpretation of W.
Comment: Are you sure $W$ is a subspace?
Answer: Take $\;u=(1,1,0)^t\;,\;\;v:=(0,0,1)^t\;$ . Observe that $\;u\,,\,v\in W\;$ , but what can you say about $\;u+v\;$ ?
Comment: @AkaliGreen Because you can. You know subspaces **must** be closed with respect to vector addition and scalar multiplication, right?
Comment: why I choose 1,1,0 and 0,0,1
Answer: In order for a vector $(x_1,x_2,x_3)$ to belong in $W$ at least one of its coordinates must be zero. Thus, a visual picture of $W$ consists of the three coordinate planes.
Now, it is clear that this is not a subspace of $\mathbb{R}^3$: a subspace must be closed under addition, but if you add two vectors belonging in two different coordinate planes, their sum does not belong in either of the three coordinate planes. For example: $(1,1,0)+(0,0,1)=(1,1,1)\notin W$.
Comment: Can you explain me why you use 110 and 001
Comment: I just picked two vectors in $W$, i.e. two vectors from two different coordinate planes to show that their some is not in $W$. There is no particular significance in the choice of the vectors. For example use $(0,1,1)$ and $(1,0,1)$ which are elements of $W$. However, their sum $(1,1,2)$ is obviously not in $W$.
Comment: how do I know that that isn't in W
Comment: @AkaliGreen Check it directly with the definition of $\;W\;$ !
Comment: $1\cdot 1\cdot 2=2$, so it does not satisfy the definition of $W$. $(1,1,2)$ does not belong to any of the coordinate planes.