text:
Q: Backup S3 bucket with identical links I have a Question Bank application with +10k questions.
The questions are a combination of text (stored within a database) and images (hosted on Amazon S3). The images are embedded as links through a admin panel.
For security purposes, I want to figure out if I can back-up the entire S3 bucket and later restore it with the same identical links.
Any experience with this?

A: I presume that your users are accessing the images via an Amazon S3 URL.
The URL consists of the bucket name and the Key (filename) of the object. To provide a file with the "same identical link" simply means putting it in the same bucket and giving it the same Key.
Please note that data stored in Amazon S3 is replicated between multiple Availability Zones. Therefore, it is typically not necessary to backup data for resilience purposes. However, it can be wise to backup in case somebody accidentally or maliciously deletes the objects. (Turning on Versioning could also be a way to safeguard against such cases.)
If you do wish to "backup an entire bucket", one option is to use Same-Region replication, which will automatically replicate objects between buckets. It requires that Versioning is activated.


text:
Q: Impedance of an LCR circuit
So I am trying to understand how to find the impedance of the parallel LC component of this filter circuit. I am given that the transfer function $\mathbf{T}_C = \dfrac{\mathbf{V}_{out}}{\mathbf{V}_{in}} = \dfrac{R_2}{R_2+z_p}$ where $z_p = R_p||j\omega L||\dfrac{1}{j\omega C} = \dfrac{R_p}{1+jR_p(\omega C-\dfrac{1}{\omega L})}$
$R_p$ is supposed to represent the resistance from the inductor and capacitor in parallel.
I thought that to calculate impedance over parallel components I had to take the product of the impedances of each 'side' (here meaning just the product of the inductor's and capacitor's impedances) divided by the sum of the impedance of each 'side'.
I am confused as to what $R_p$ really means and why we are taking the norm of the inductors impedance. Basically, I am struggling to find out how each of the equations for the total impedance for the parallel compenents are found.

A:
I thought that to calculate impedance over parallel components I had to take the product of the impedances of each 'side' (here meaning just the product of the inductor's and capacitor's impedances) divided by the sum of the impedance of each 'side'.

This works when there are only devices...
$$z = \frac{z_1 z_2}{z_1 + z_2} $$
For more than two devices, better formula is
$$\frac1z = \frac1z_1 + \frac1z_2$$
This formula can be extended easily to more than two devices.
So for you circuit, result of parallel network will be
$$\frac1z_p = \frac1R_p + \frac1{j\omega L} + jwC $$
You can simplify this to get the result given in the book.

A: Analyisis of these circuit diagrams always assume idealized elements, resistors, capacitors, inductors, etc. In the real world, inductors have series resitance in their wire, and parallel capacitance between coils, etc. In many cases some or all of these parasitic reactances can be ignored, for example, if the frequency is high enough that $R \ll \omega L$, the resistance is usually negligible, and if frequency is low enough that $\omega L \ll 1/\omega C$, the capacitance can be ignored . Similiarly, capacitors have small leakage current that can be modeled by a large parallel resistance, and also some series inductance in their wires. So it is often necessary for high frequency applications that each of these components must be represented by a more complex combination of ideal elements.
In the circuit you were given to analyze, it seems that a parallel resistor may have been used to represent dissipation in both the parallel capacitor and inductor. As has been pointed out in the comments, the $\parallel$ symbols indicated that these elements are combined in parallel, and are not intented to represent a norm. Combining elements in parallel is done by adding their conductaces and admittances, then inverting the result to get the equivalent impedance.
Ideal resistors obey Ohm's law for both dc and ac applied voltages, so the voltage across them is proprtional to current, and not frequency. Current, of course, will be time dependent for ac sources, and may also depend on other frequency dependent reactances in series or parallel.

A:
I am confused as to what Rp really means

If $R_p$ were 'infinite', there would just be the parallel connected (ideal) inductor and (ideal) capacitor.  The impedance of this combination is 'infinite' at angular frequency $\omega_0 = \frac{1}{\sqrt{LC}}$
However, for the parallel connected physical inductor and capacitor, the impedance is never infinite. The parallel resistance $R_p$ niavely models this fact by providing an upper limit on the impedance of the parallel LC combination.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Throwing http 500 error and removing htaccess not working This site www.collegeconn.com is suddenly throwing this error and to fix the error I have tried every possible changes. I have renamed htaccess file to check if it is the cause but still the same error occurs stating bellow error message

The collegeconn.com page isn't working
collegeconn.com is currently unable to handle this request. HTTP ERROR
  500

A: You first try to access simple PHP test file by placing them into root folder. If that file runs well than you need to access your files using File Zilla and try to remove .htaccess file.
In case still you are getting error than you need to contact to your hosting provider.


text:
Q: templateUrl not working in angular 2 I have a product-list.component.ts as this:
import { Component } from '@angular/core'

@Component({
    selector: 'pm-products',
    templateUrl: 'app/products/product-list.component.html'
})

export class ProductListComponent {

}

app.component.ts:
 import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

 import { Component } from '@angular/core';

import { ProductListComponent } from './products/product-list.component';

@NgModule({
       bootstrap:    [ ],
       imports: [ ProductListComponent],
       schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
       declarations: [AppComponent,ProductListComponent ],

})

@Component({
selector: 'pm-app',
template: `

{{pageTitle}}

        <pm-products></pm-products>

`
})

   export class AppComponent {
pageTitle: string = 'Acme Product Management';
}

I used of pm-app in index.html but product-list.component.html don't appear in screen.
thanks in advance!

A: Your templateUrl should be:
templateUrl: './app/products/product-list.component.html'

A: Change your app.component.ts as below :
import { NgModule, Component } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { ProductListComponent } from './products/product-list.component';

@Component({
  selector: 'pm-app',
  template: `

{{pageTitle}}

        <pm-products></pm-products>

  `
})

export class AppComponent {
  pageTitle: string = 'Acme Product Management';
}

@NgModule({
   bootstrap:    [AppComponent ],
   imports: [ BrowserModule ],
   declarations: [AppComponent,ProductListComponent ]
})
export class AppModule {}


text:
Q: Вывести посты определенным образом Wordpress Этот код выводит на страницу посты которые являются ссылками.
      <?php
            $args = array(
                'post_type' => array('job')
            );
            $the_query = new WP_Query( $args );
            ?>

            <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

                <a href="<?php the_permalink(); ?>" class="jobs">

<?php the_title(); ?>

<?php the_content(); ?>

            <?php endwhile;  endif; ?>

Каждый блок содержит заголовок и контент (параграфы).
Блоки отображаются не корректно (не так как указано). Ссылка выводится внутри блока
.
И еще один момент, как можно изменить разметку для блока с конкретным id? Т.е. блок с id=683 не должен быть ссылкой.

A: Ссылку внутрь помещает браузер, пытаясь исправить нарушение правил html. Внутри ссылки не может быть блочных элементов: http://htmlbook.ru/samhtml/ssylki/pravila-vlozheniy-dlya-tega
Чтобы не выводить ссылку определенного поста, используйте глобальную переменную $post.
<?php global $post; ?>
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php if ( 683 !== $post->ID ) { ?>
    <a href="<?php the_permalink(); ?>" class="jobs">
    <?php } ?>

<?php the_title(); ?>

<?php the_content(); ?>

    <?php if ( 683 !== $post->ID ) { ?>

    <?php } ?>
<?php endwhile;  endif; ?>


text:
Q: "None" added to list when input search does not match trying to complete a project shopping cart. I show available items then ask how many items required, then ask to input each item by name, which get added to cart. problem is when input does not match an item the code blows up. Im guessing i need maybe an if statement somewhere but struggling to figure it out. this also my first ever post so be gentle with me haha. Code below
inven = {"eggs" : 1.99, "bacon" : 2.99, "bread" : 1.99}
basket = list()
purchase_list = list()
print("Items available to purchase")
print(inven)
n = int(input("how many items do you wish to buy?"))

for i in range(n):
    b = input("type item")
    a = (inven.get(b))
    basket.append(a)
    purchase_list.append(b)
    print(purchase_list)
    print("Items in basket" + str(purchase_list))

total = sum(basket)
print("Basket Total is: £", "%.2f" % total)

A: a = inven.get(b) Is a nice way to get the item in the dictionary but what happens when it cant find the item you specified?
The function returns None so you need to catch this and put a conditional statement around your code that pushes the items onto the list.
I would also recommend changing your variable names such as a and b.

A: You could go for
b = input("type item")
a = inven.get(b)
if a and b:
    basket.append(a)
    purchase_list.append(b)

Note that you do not need the parentheses around the .get() line.


text:
Q: How to search for users by ID and customData in Stormpath I'm thinking about using Stormpath with it's Java API as a user storage.
Looks good, except that I can't search for users.
For example, I get this error:
Exception in thread "main" com.stormpath.sdk.resource.ResourceException: HTTP 400, Stormpath 2105 (http://docs.stormpath.com/errors/2105): Account ID is not a supported query property.

when I execute this query:
HashMap<String, Object> queryParams = Maps.newHashMap();
queryParams.put("ID", "4mPXXXXXXXXXX");
searchResult = application.getAccounts(queryParams);

Searching for a user by e-mail however works. I get the same error when I try to search a user by a login-token I stored in the customData property.
It looks like what I want to do is not possible as it looks like the only properties you can query are e-mail and username. But why would they provide this functionality if it didn't work. What am I missing?

A: There is an impedance mismatch between common relational database behaviors and those in a REST API.   Querying by id, while common in relational databases, is not idiomatic behavior for REST APIs (or most HTTP-based web sites).  The URL (href) is the canonical 'pointer' to a resource on the web.  In other words, in REST APIs, the canonical identifier is the href.  Any token inside an href (any internal 'id', special characters, whatever) should be opaque to REST clients and ignored by clients entirely.  URLs are king in HTTP and REST.
That being the case, the Stormpath SDK tries to be true to RESTful best practices, so you can obtain any Stormpath resource by using the client.getResource method, which accepts an href and the type of object you expect that href to represent:
String href = "https://api.stormpath.com/v1/accounts/" + id;
Account account = client.getResource(href, Account.class);

That said, there's nothing wrong with wanting this to be more conveniently represented in the client API, for example, client.getAccount(String id) if you want to keep the notion of IDs.  If so, please open a new feature request and we'll be very happy to consider it.
As for queryable Account properties, those are documented here.  Stormpath will soon make data in Custom Data searchable as well.  While Stormpath feature timelines are never announced, it is the company's highest engineering priority and it should be out soon.
One workaround that is helpful for some people is to store data they want to search in Account Fields that you don't use in your applications.  For example, you could use the 'middle name' field to store, say, favorite color.  This would only be temporary until custom data search is available.  HTH!


text:
Q: Adding two random variables with convolution I am trying to understand the purpose of convolution of two probability functions. Also when it is appropriate to use the convolve function on two independent probability distributions.
VariableOne = {
    1: 0.5,
    3: 0.5
}
VariableTwo = {
    7: 0.5,
    8: 0.5
}

Meaning that the probability of getting either 1 or 3 is 0.5 and probability of getting either 7 or 8 is 0.5.
Now looking at wikipedia I quote The probability distribution of the sum of two or more independent random variables is the convolution of their individual distributions. However, when running the following in R:
convolve(c(0.5, 0.5), rev(c(0.5, 0.5)), type="o")

I get
0.25 0.50 0.25

But I would expect to get 4 values one for each of the following combinations:
{
    1+7 : p1,
    1+8 : p2,
    3+7 : p3,
    3+8 : p4
}

Update
However it works if I have
VariableOne = {
    1: 0.4,
    2: 0.6
}

VariableTwo = {
    1: 0.3,
    2: 0.7
}

If I run the following in R:
convolve(c(0.4, 0.6), rev(c(0.3, 0.7)), type="o")

Giving
0.12 0.46 0.42

This makes sense because I can do this which gives the correct probabilities
{
    1+1     : 0.12,
    1+2, 2+1: 0.46,
    2+2     : 0.42
}

Obviously my understanding is missing something, any help appreciated.

A: First, we are assuming the variables are independent so that
$$
P(X=x\land Y=y)=P(X=x)\,P(Y=y)\tag{1}
$$
Then, for discrete distributions on the integers,
$$
\begin{align}
P(X+Y=n)
&=\sum_{k\in\mathbb{Z}}P(X=k\land Y=n-k)\\
&=\sum_jP(X=k)\,P(Y=n-k)\tag{2}
\end{align}
$$
Thus, $(2)$ says that the distribution of $X+Y$ is the convolution of the distributions of $X$ and $Y$.

Let's apply this to your data: the convolution of the distributions
$$
\begin{array}{c|c}
k&P(\mathtt{VariableOne}+\mathtt{VariableTwo}=k)\\\hline
7&\overbrace{0.5}^1\cdot\overbrace{0.0}^6+\overbrace{0.0}^2\cdot\overbrace{0.0}^5+\overbrace{0.5}^3\cdot\overbrace{0.0}^4=0.0\\
8&\overbrace{0.5}^1\cdot\overbrace{0.5}^7+\overbrace{0.0}^2\cdot\overbrace{0.0}^6+\overbrace{0.5}^3\cdot\overbrace{0.0}^5=0.25\\
9&\overbrace{0.5}^1\cdot\overbrace{0.5}^8+\overbrace{0.0}^2\cdot\overbrace{0.5}^7+\overbrace{0.5}^3\cdot\overbrace{0.0}^6=0.25\\
10&\overbrace{0.5}^1\cdot\overbrace{0.0}^9+\overbrace{0.0}^2\cdot\overbrace{0.5}^8+\overbrace{0.5}^3\cdot\overbrace{0.5}^7=0.25\\
11&\overbrace{0.5}^1\cdot\overbrace{0.0}^{10}+\overbrace{0.0}^2\cdot\overbrace{0.0}^9+\overbrace{0.5}^3\cdot\overbrace{0.5}^8=0.25\\
12&\overbrace{0.5}^1\cdot\overbrace{0.0}^{11}+\overbrace{0.0}^2\cdot\overbrace{0.0}^{10}+\overbrace{0.5}^3\cdot\overbrace{0.0}^9=0.0\\
\end{array}
$$
The call to reflect these distributions should be
convolve(c(0.5, 0.0, 0.5), c(0.5, 0.5, 0.0), type="o")
because the first distribution has a $0.0$ at $2$.

A: You have the correct values for the sum. Also, it is easy to see
(multiplication rule for independent events) that each of them has probability 1/4.
A simulation in R, confirms this (only approximately, of course):
 m = 10^6
 x = sample(c(1,3), m, rep=T)
 y = sample(c(7,8), m, rep=T)
 s = x + y
 round(table(s)/m, 4)
 ## s
 ##      8      9     10     11
 ## 0.2498 0.2499 0.2499 0.2505

I have not used the 'convolve' function enough to be sure of an
example of that. Maybe you can figure it out.
I'm not sure whether the assignment was to do the convolution
by hand from theory (almost trivial), specifically to use
'convolve' in R, or to get the answer by any means possible.
Anyhow, I hope this helps.

A: You have two sequences given that are indexed by the integers. They are given by
$a_n = \begin{cases}1/2 & n = 1 \vee n = 3 \\ 0 & \text{else}\end{cases}$
$b_n = \begin{cases}1/2 & n = 7 \vee n = 8 \\ 0 & \text{else}\end{cases}$
Now you want to calculate the convolution of these both sequences, which means you ned to calculate the sequence $(a *b)_n = \sum \limits
_{k \in \mathbb{Z}} a_k b_{n-k}$. This will yield the desired result that one would expect. For $n = 8, 9, 10, 11$ the value will be $1/4$, while all other values will be zero.
Now why does the result in R differ from this? Quite simple, R doesn't know at which position you have the values $1/2$, you have only given the information that the value $1/2$ appears twice in every sequence. Now R must guess the positions at which it has to position these values, which will be (canonically) the positions 1 and 2. The same thing holds for the second sequence, so you've actually calculated the convolution $c*c$ where
$c_n = \begin{cases}1/2 & n = 1 \vee n = 2 \\ 0 & \text{else}\end{cases}$
We can fix this problem relatively simple: We need to tell R the correct sequence. This means you need to calculate the convolution of $c(.5, 0, .5, 0, 0, 0, 0, 0)$ and $c(0, 0, 0, 0, 0, 0, .5, .5)$. This will lead to the correct result:
> convolve(c(.5, 0, .5, 0, 0, 0, 0, 0), c(0, 0, 0, 0, 0, 0, .5, .5), type="o")
 [1]  2.500000e-01  2.500000e-01  2.500000e-01  2.500000e-01  5.419008e-17
 [6] -1.152638e-17  6.661338e-17  3.028642e-17  5.599892e-17  5.181041e-17
[11] -6.804757e-19  1.801594e-17  2.960595e-17  1.982479e-17  4.113233e-17

Note that the values less than $10^{-16}$ should be 0 and they only appear because R uses the FFT to calculate the convolution - therefore there are some inaccuracies when working with floating point numbers. Also, R defines the convolution in the following way:

 If 'r <- convolve(x, y, type = "open")' and 'n <- length(x)', 'm
 <- length(y)', then

                   r[k] = sum(i; x[k-m+i] * y[i])

 where the sum is over all valid indices i, for k = 1, ..., n+m-1.

this means that the result is a shifted version of the "correct convolution". To get the proper convolution you would now need to pad the result with zeroes.


text:
Q: How to make cascading drop-down list using just one class? I've already saw examples of that perfectly working but with two separate classes but I'm trying to do a cascading drop-down list just using a single class using ASP.NET MVC.
My class:
namespace e_Recarga.Models
{
    public class Estacao
    {
        public int Id { get; set; }
        [Required]
        [StringLength(255)]
        public string Distribuidora { get; set; }
        [Required]
        [StringLength(255)]
        public string Nome { get; set; }
        [Required]
        [StringLength(255)]
        [Display(Name = "Região")]
        public string Regiao { get; set; }
        [Required]
        [StringLength(255)]
        [Display(Name = "Localização")]
        public string Localizacao { get; set; }
        [Required]
        [Display(Name = "Disponibilidade")]
        public int Disponibilidade_Postos { get; set; }
        public IEnumerable<Reserva> Reservas { get; set; }

    }
}

 namespace e_Recarga.Models
{
    public class Reserva
    {
        public int Id { get; set; }

        [Required]
        public Utilizador Utilizador{ get; set; }
        public Estacao Estacao { get; set; }
        public byte EstacaoId { get; set; }

    }
}

So in the controller I have everything get from the Database and returning it to the view.
public class ReservaController : Controller
{
    private ApplicationDbContext _context;

    public ReservaController()
    {
        _context = new ApplicationDbContext();
    }
    protected override void Dispose(bool disposing)
    {
        _context.Dispose();
    }
    public ActionResult Index()
    {
        var estacoes = _context.Estacoes.ToList();

        var estacoesDistinct = estacoes.GroupBy(x => x.Regiao ).Select(x => x.First());

        var viewModel = new NovaReservaViewModel
        {
            Estacoes = estacoesDistinct

        };

        return View(viewModel);
    }

In the view in terms of HTML I have the drop-down lists already implemented, but I think I need to have a javascript to do the cascading stuff.
    @model e_Recarga.ViewModels.NovaReservaViewModel
@{
    ViewBag.Title = "New";
    Layout = "~/Views/Shared/_Layout.cshtml";

}

Nova Reserva

@using (Html.BeginForm("New", "Reserva"))
{

        @Html.LabelFor(e => e.Reserva.Estacao.Regiao)
        @Html.DropDownListFor(e => e.Reserva.Estacao.Id, new SelectList(Model.Estacoes, "Id", "Regiao"), "Escolha a Região", new { @class = "form-control" })
        <select id="regiao"></select>

        @Html.LabelFor(e => e.Reserva.Estacao.Distribuidora)
        @Html.DropDownListFor(e => e.Reserva.Estacao.Id, new SelectList(Model.Estacoes, "Id", "Distribuidora"), "Escolha a Região", new { @class = "form-control" })
        <select id="distribuidora"></select>

        @Html.LabelFor(e => e.Reserva.Estacao.Nome)
        @Html.DropDownListFor(e => e.Reserva.Estacao.Id, new SelectList(Model.Estacoes, "Id", "Nome"), "Escolha a Estação", new { @class = "form-control" })

    @Html.HiddenFor(e => e.Reserva.Estacao.Id)
    <button type="submit" class="btn btn-primary">Save</button>
}

How can I do that?
I've tried the following javascript code:
@section scripts {

}


text:
Q: save file :PermissionError [Errno 13] Permission denied windows 10 python mysql I tried to fetch an image and a text from MySQL and save it into a drive of Windows 10 but when I entered for example D:\test show me this error:
Exception has occurred: PermissionError
[Errno 13] Permission denied: 'd:\test'
My code is:
import mysql.connector
from mysql.connector import Error

def write_file(data, filename):
    #convert binary data to the proper format and write it on the hard disk
    with open(filename, 'wb') as file:
        file.write(data)

def readBLOB(emp_id, photo, bioData):
    print("Reading BLOB data from python_employee table")
    print("Inserting BLOB into Employee table")
    try:
        conn = mysql.connector.connect(
            host = 'localhost',
            user = 'ashix',
            passwd = '*****',
            database = 'mydatabase',
        )
        cursor = conn.cursor()
        sql_fetch_blob_query = """select * from employee where id = %s"""
        cursor.execute(sql_fetch_blob_query, (emp_id, ))
        record = cursor.fetchall()
        for row in record:
            print("ID = ", row[0])
            print("name = ", row[1])
            image = row[2]
            file = row [3]
            print("storing employee image and bio-data on disk \n")
            write_file(image, photo)
            write_file(file, bioData)
    except mysql.connector.Error as error:
        print("Faild to read BLOB data from MySQL table {}".format(error))
    finally:
        if(conn.is_connected()):
            cursor.close()
            conn.close()
            print("MySql connection is closed")

id = int(input("Enter ID: "))
imageFile = input("Enter Image path and file name: ")
bioFile = input("Enter Bio-data path and file name: ")
readBLOB(id, imageFile,bioFile)


text:
Q: docker client and server containers connection refused I want to connect client image and server image. So I tried to use --link, docker-compose.yml, but I failed. However, when I tried to connect local client code and server container, it succeed. I think it may be a problem of Dockerfile, but I can't fix it..
these are my code:
---server
import socket

HOST = socket.gethostbyname('localhost')
PORT = 65456

print('> echo-server is activated')
#print(HOST,PORT)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serverSocket:
    serverSocket.bind(('', PORT))
    serverSocket.listen()
    clientSocket, clientAddress = serverSocket.accept()
    with clientSocket:
        print('> client connected by IP address {0} with Port number {1}'.format(clientAddress[0], clientAddress[1]))
        while True:
            # [=start=]
            RecvData = clientSocket.recv(1024)
            print('> echoed:', RecvData.decode('utf-8'))
            clientSocket.sendall(RecvData)
            if RecvData.decode('utf-8') == 'quit':
                break
            # [==end==]
print('> echo-server is de-activated')

---client
import socket

HOST = socket.gethostbyname('localhost')
PORT = 65456

print('> echo-client is activated')
#print(HOST,PORT)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as clientSocket:
    #print(HOST,PORT)
    clientSocket.connect((HOST, PORT))
    while True:
        sendMsg = input("> ")
        clientSocket.sendall(bytes(sendMsg, 'utf-8'))
        recvData = clientSocket.recv(1024)
        print('> received:', recvData.decode('utf-8'))
        if sendMsg == "quit":
            break

print('> echo-client is de-activated')

---server Dockerfile
FROM python:latest
COPY . /me
RUN apt-get update

RUN mkdir -p /me
CMD ["python", "/me/server.py"]

EXPOSE 65456

---client Dockerfile
FROM python:latest
COPY . /you
RUN apt-get update

RUN mkdir -p /you
CMD ["python", "/you/client.py"]

EXPOSE 65456

This is echo program.

A: Your code works for me.
You don't include the commands that you tried. These would be helpful additions to your question.
Build both containers. I using different Dockerfile names to disambiguate between the two.
Q="74282751"

docker build \
--tag=${Q}:server \
--file=./Dockerfile.server \
${PWD}

docker build \
--tag=${Q}:client \
--file=./Dockerfile.client \
${PWD}

Then in one shell, run the server container publishing the container's port 65456 on the host's port (65456):
docker run \
--interactive --tty --rm \
--publish=65456:65456 \
${Q}:server

And, in another shell, run the client container, binding the container to the host's network. This is an easy way to provide access to the host's 65456 port which now maps to the server container port 65456:
docker run \
--interactive --tty --rm \
--net=host \
${Q}:client

Feedback

*

*When you FROM python, you're actually implicitly referencing Docker's container registry. Always be explicit and FROM docker.io/python

*Try to never use :latest. In this case, you'd want to consider using the actual latest version of the Python container (i.e. 3.9.15).

*Conventionally WORKDIR is used to define a working directory in a container. This creates and changes to the folder and save RUN mkdir and repeatedly referencing the destination folder.

*Try to be explicit about what is being COPY'd. For the server, it's only server.py rather than . the entire directory.

*EXPOSE is for documentation only. It has no effect. It only applies to the server since the client doesn't expose any ports.

*Rather than hard-code constants (HOST,PORT) in your code, it's good practice to access these as environment variables (i.e. HOST = os.getenv("HOST")). This makes your code more flexible. Generally (!) for code that's destined to be containerized, you'll be able to default HOST to localhost (or 127.0.0.1 sometimes 0.0.0.0).

FROM docker.io/python:3.9.15

RUN apt-get update

WORKDIR /me

COPY server.py .

EXPOSE 65456

CMD ["python", "/me/server.py"]


text:
Q: Is there an OS X equivalent to the web debugging proxy Fiddler? I do web development on Windows for my day job, and I rely a lot on Fiddler, which is web debugging proxy.  What is an equivalent tool for OS X?

A: These are both free and haven't been mentioned so far.  I found that both of these are far superior to the X11 Wireshark.

*

*Cocoa Packet Analyzer

*Packet Peeper

A: http://mitmproxy.org/ is text-based tool, but does a great job.  For any http-speaking app you want to analyse, and even modify and replay requests.

A: Fiddler now has an Alpha build based on Mono.

A: Stuff that's Free:

*

*Burp Suite

*WiireShark

*ParosProxy

*NetTool

*LiveHTTPHeaders

*Safari WebInspector Network Tab

*FireBug
Stuff that Costs:

*

*$1.99 -  HTTPClient

*$15.00 - HTTP Scoop

*$50.00 - CharlesProxy

A: I use CharlesProxy, and while it isn't as scriptable as Fiddler, it does the job. And with single license key, you can run it on all OSes (it's written in Java).
My needs were little different when I needed it ... I used it to debug webdav connections or to debug http communication between servers.

A: If you just want to see HTTP traffic, try Cellist.

A: Try Tamper
It's a Chrome extension that lets you view and modify HTTP requests in the current tab's scope

A: Try Proxyman, which is exclusively built for macOS.

*

*Easy to use and set up the certificates on mac/iOS/Android

*All advanced tools: Map Local, Map Remote, Breakpoint, Scripting, ...

*Active development and bug/feature tracker

*It's a premium app without time limit

Disclaimer: I'm a creator of Proxyman. Just come here to suggest a better alternative to boost productivity. Hope you enjoy the app!

A: ZAP Attack proxy from OWASP is an excellent OpenSource alternative.
The already mentioned Burp is also excellent but the paid version is much better than the free version.
I use both for work.

A: Captor, available on mac app store
It's a native app , can capture HTTP/HTTPS just like CharlesProxy.

A: There's a mac version now via mono.
Install Fiddler on Mac OSX
About the App
App name: Fiddler
App description: fiddler (App: Fiddler.app)
App website: http://www.telerik.com/fiddler
Install the App
Press Command+Space and type Terminal and press enter/return key.
Run in Terminal app:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null ; brew install caskroom/cask/brew-cask 2> /dev/null
and press enter/return key. Wait for the command to finish.
Run:
brew cask install fiddler
Done! You can now use Fiddler.


text:
Q: Erratic behavior of Javascript - Cannot read property 'longitude' of undefined I'm working on an Angular App, which loads data from an API.
Everything is working as expected, except periodic receiving this bug in Chrome console.log

TypeError: Cannot read property 'longitude' of undefined

This causes some of the subsequent functions to disfunction aswell. The line angular complains at, is the following
    function updateMapWaypoint(lastposition) {
        console.log("updateMapWaypoint(%s) called", lastposition);
        console.log($scope.units[$scope.selectedUnitIndex]);
        var longitude = (lastposition) ? $scope.units[$scope.selectedUnitIndex].lastposition.gps.longitude : $scope.unsortedPositions[$scope.selectedPositionIndex].gps.longitude;

Where to two first is debugging and the last one, the line causing trouble. As far as I can see from the printet object in the console. Javascript should have no trouble locating longitude from the object, however it throws the error and I can't find any way to solve it.
All help is appreciated and if more details is required, I'll provide if possible for me.

A: This looks like it might be a race condition.
console.log() will show you the object as it is right now, and not what is was when you called console.log(). To see the properties of an object at a certian point in time you must copy its content and send them to console.log(), for example by stringifying it:
console.log(JSON.stringify(myObject))

Or if you are using Angular:
console.log(angular.extend({}, myObject));

This is confusing (it has messed with me several times). Remember that you are sending console.log() an object reference, not a copy of the object.


text:
Q: MSBuild Exec task fails with Unicode filenames? I'm using MSBuild, FLAC and LAME to manage my MP3 collection, but it fails when it encounters a file with a non-ASCII character in the filename.
The following, cut down, project file shows the problem:
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
         ToolsVersion="4.0" DefaultTargets="Default">

  <PropertyGroup>
    <FLAC>"C:\Program Files (x86)\Flac\bin\flac.exe"</FLAC>
  </PropertyGroup>

  <ItemGroup>
    <Decode
      Include="D:\Music\Artists\Kruder Dorfmeister\The K&D Sessions\**" />
  </ItemGroup>

  <Target Name="Default" Inputs="@(Decode)" Outputs="%(Identity).always">
    <Exec Command="$(FLAC) --decode "@(Decode)"" />
  </Target>
</Project>

When this gets to "D:\Music\Artists\Kruder Dorfmeister\The K&D Sessions\Part One\02 - Jazz Master (K&D Session™).flac", it fails with the following error message:
Default:
  "C:\Program Files (x86)\Flac\bin\flac.exe" --decode "D:\Music\Artists\Kruder Dorfmeister\The K&D Sessions\Part One\02
   - Jazz Master (K&D SessionT).flac"

  02 - Jazz Master (K&D SessionT).flac: ERROR initializing decoder
  init status = FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE

  An error occurred opening the input file; it is likely that it does not exist
  or is not readable.

As you can see, something is munging the "™" and converting it to "T".
But what? And how can I fix this?

A: The built-in MSBuild Exec task writes the given command to a batch file and then runs it with cmd /c /q. Unfortunately, it writes the batch file with the OEM code page.
This means that Unicode filenames are mangled.
You'll have to write your own Exec (or Pipe, or even ConvertMusic) task instead.


text:
Q: postgres plpy.execute with hstore string literal FAIL I'm writing a plpython function using postgresql 9.2.  Assume the code has already executed a query that returns hstore strings.   I wish to then issue a query:
SELECT hstore_to_matrix('hstorestring')

Let's say that it is a string containing the hstore string: A=>B
create or replace function testfreq()
returns text
as $$
hstorestring = '"GT"=>"thing","HS"=>"[-0.1,-0.2]"'
rv2 = plpy.execute("SELECT hstore_to_matrix(%s)" % (plpy.quote_literal(hstorestring)))
plpy.log("Hstore:",rv2[0])
return("done")
$$ LANGUAGE plpythonu;

Run as
select testfreq();

Returns
testdb=# select testfreq();
ERROR:  plpy.Error: unrecognized error in PLy_spi_execute_fetch_result
CONTEXT:  Traceback (most recent call last):
PL/Python function "testfreq", line 3, in <module>
rv2 = plpy.execute("SELECT hstore_to_matrix(%s)" % (plpy.quote_literal(hstorestring)))
PL/Python function "testfreq":

If you replace with hstore_to_array in the code above, the output is:
testdb=# select testfreq();
LOG:  ('Hstore:', {'hstore_to_array': ['GT', 'thing', 'HS', '[-0.1,-0.2]']})
CONTEXT:  PL/Python function "testfreq"
testfreq
----------
done
(1 row)

I have also tried to use hstore operators instead of functions and I have tried out these functions in a pgsql terminal to make sure they work when not embedded in python.  Any pointers would be greatly appreciated.

A: It looks like PL/Python doesn't correctly handle multi-dimensional arrays:
create or replace function testarray()
returns text
as $$
rv2 = plpy.execute("SELECT ARRAY[ ARRAY['1','2','3'], ARRAY['a','b','c'] ];" )
$$ LANGUAGE plpythonu;

Result:
craig=# select testarray();
ERROR:  plpy.Error: unrecognized error in PLy_spi_execute_fetch_result
CONTEXT:  Traceback (most recent call last):
  PL/Python function "testarray", line 2, in <module>
    rv2 = plpy.execute("SELECT ARRAY[ ARRAY['1','2','3'], ARRAY['a','b','c'] ];" )
PL/Python function "testarray"

(Tested on Pg 9.2.4, Python 2.7.3).
The hstore text is valid:
craig=# SELECT '"GT"=>"thing","HS"=>"[-0.1,-0.2]"'::hstore;
               hstore
------------------------------------
 "GT"=>"thing", "HS"=>"[-0.1,-0.2]"
(1 row)

and the query works outside PL/Python:
craig=# select hstore_to_matrix('"GT"=>"thing","HS"=>"[-0.1,-0.2]"');
        hstore_to_matrix
---------------------------------
 {{GT,thing},{HS,"[-0.1,-0.2]"}}
(1 row)

further suggesting that this is a PL/Python issue.
You can probably work around this by casting to text then casting back to text[] after returning the result, though it's inefficient:
create or replace function testfreq()
returns text
as $$
hstorestring = '"GT"=>"thing","HS"=>"[-0.1,-0.2]"'
rv2 = plpy.execute("SELECT hstore_to_matrix(%s)::text" % (plpy.quote_literal(hstorestring)))
plpy.log("Hstore:",rv2[0])
return("done")
$$ LANGUAGE plpythonu;

Result:
craig=# SELECT testfreq();
 testfreq
----------
 done
(1 row)


text:
Q: array_unique only on one field? I have following code for an autocomplete box, I'm adding an image for choice clarification but want to make sure the title returned is unique, but, when I get to the code which makes the array unique, i've added other code which makes it non unique in other areas. Is there a way around this?
$query = "SELECT $title, imageURL FROM PRprodINFO2 WHERE ((prodcatID = '$cat_id')
          AND ($title LIKE \"%" . $_GET["q"] . "%\")) group by $title LIMIT 8";
}

$result = mysql_query($query);

// set the array
$output_items = array();

while($row = mysql_fetch_array($result)) {

    // clean after first non letter/number
    $row[$title] = preg_replace('/[^\w\s].*$/', "", $row[$title]);

    //trim spaces
    $row[$title] = trim($row[$title]);

    // add image src
    $output_items[] = ''
                      .$row[$title];

} // while

// here i need just $row[title] to be unique,
// it is made non unique after regex strips off some characters
$output = array_unique($output_items);

print(implode("\n", $output));

mysql_close();

A: I am possibly confused by what you are asking.  It seems like you would already have unique titles since you are grouping by title in your sql.  But, maybe you have extra non alpha-numeric characters you are stripping out with your regex that makes some unique titles the same.
In that case, instead of building up your $output_items like you are, try:
$output_items[$row['title']] = $row['imageURL'];

This will ensure that each title is unique.  You will have the imageURL of the last row that matched that title.  If you want, instead, the first title that matched, then just check isset before overwriting it like:
if (!isset($output_items[$row['title']])) $output_items[$row['title']] = $row['imageURL'];

Then, outside of the loop, build up your output string.
$output = '';
foreach ($output_items as $title => $image) {
    $output .= ''.$title."\n";
}
echo $output;


text:
Q: OpenCV Canny Edge detector in Processing (Live video) I am currently working on a project that requires human body detection with a onboard camera. Long story short, I am now trying to do it using OpenCV canny edge detector.
All problem is that I can't really figure out how to apply detection for the captured video (well, for images there is example included in the library).
Maybe there is somebody who did it in Processing environment?
import processing.video.*;
import gab.opencv.*;

OpenCV opencv;
Capture cam;

PImage src, canny;

void setup(){
  size(640,480);

  cam = new Capture(this, 640/2,480/2);
  cam.start();
  opencv = new OpenCV(this, cam);
  opencv.findCannyEdges(20,75);
  canny = opencv.getSnapshot();

}

void draw(){
  pushMatrix();
  scale(2);
  image(cam, 0,0);
  image(canny, cam.width, 0);
  popMatrix();
}

void captureEvent(Capture c){
  c.read();
}

A: I think what you need is the cv2.VideoCapture method.
Below is an example I did in Python but you should be able to transfer the usage.
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):
    ret, frame = cap.read()
    gray_vid = cv2.cvtColor(frame, cv2.IMREAD_GRAYSCALE)
    cv2.imshow('Original',frame)
    edged_frame = cv2.Canny(frame,100,200)
    cv2.imshow('Edges',edged_frame)
# Quit with 'Esc' key
    k= cv2.waitKey(5) & 0xFF
    if k==27:
        break
cap.release()
cv2.destroyAllWindows()

Best regards / Colm


text:
Q: Proper using of scope watch for many variables Which solution is best. Set three watches in controller to each data and accordingly set differrent method or set one watch for all three variables and then check which changed and run specified method.
In allegory to event handling, best is to delegate event on parent object and then delegate for parts of dom, according to specified event. If angular permit such watching, how to implement this?
Basic solution is simple, but demands three watches:
$scope.$watch(function() {
    return service.var1;
},
function callback(new,old) {
    $scope.function1();
});
$scope.$watch(function() {
    return service.var2;
},
function callback(new,old) {
    $scope.function2();
});
$scope.$watch(function() {
    return service.var3;
},
function callback(new,old) {
    $scope.function3();
});

Second solution seems to be better, according to event observing, but i don't know how to determine watched element:
$scope.$watch(function() {
     return service.var1 + service.var2 + service.var3; },
  function callback(new,old) {
  var changed = ;//?here how to determine which variable changed
  switch ( changed ) {
    case 'var1' : $scope.function1();break;
    case 'var2' : $scope.function2();break;
    case 'var3' : $scope.function3();break; }
})

How to implement delegating to watched variables in Angular?

A: I would preferred second way you used but there should be $$watchGroup
Code
$scope.$watchGroup(['service.var1', 'service.var2', 'service.var3'],
  function(newVal, oldVal) {
    var changed = ''
    if (newVal[0] != oldVal[0])
        changed = 'var1';
    if (newVal[1] != oldVal[1])
        changed = 'var2';
    if (newVal[2] != oldVal[2])
        changed = 'var3';
    switch (changed) {
        case 'var1':
            $scope.function1();
            break;
        case 'var2':
            $scope.function2();
            break;
        case 'var3':
            $scope.function3();
            break;
    }
});

For more info refer this SO answer which has explained the same.


text:
Q: Using Regular Expression to define a yes/no logic in Selenium IDE Basically I want an IDE line that says:
If $variable matches XXXXX format then make value 'DoesVarMatch'=Yes
This is so I can then do conditional gotoIf statements if the variable matches the regexp. Ultimately I want to do this with a date (validate as dd/mm/yyyy) and email variable, but I am starting with a simple regular expression to get the logic worked out.
I have tried the following (which does not work):

    gotoIf
    'Green' == /[Gg]reen/
    GreenTrue

    stop

    label
    GreenTrue

I also tried to use javascript (which also didn't work, I expected a True value to be returned):

    runScript
    var re = /[Gg]reen/.test('Green'); return re.test('Green');
    Colour

    echo
    ${Colour}

The following execute correctly but I don't seem to be able to use them to define yes/no logic:

    verifyEval
    'Green'
    regexp:[Gg]reen

    storeEval
    'Green'
    regexp:[Gg]reen

I appreciate any insights into using Selenium to use the regexp or javascript to define a variable I can use to do the logic test.

A: I have found a solution. If anyone has any suggestions to improve what I have here please feel free to comment. Basically instead of creating a value to then do the gotoIf statement I used the regex validation itself to determine the gotoIf statement.

    verifyEval
    'Green'
    regexp:[Gg]reen

    storeEval
    'Green'
    regexp:[Gg]reen

    store
    Blue
    Colour

    gotoIf
    javascript{ var re = /[Gg]reen/g; re.test(storedVars.Colour);}
    GreenTrue

    stop

    label
    GreenTrue

    stop

A: Just as a heads up. The way you're using the verify/assertEval command is true, to a sense of it equates correctly. However not in terms of the parameters
verifyEval | logicaltest | outcome

So if your logical test wasn't == then you would need a better syntax. For example
verifyEval | 'Green'!==/[Gg]reen/ | false/true

A: Hello Selenium Developers
I found the answers to getting a Boolean result to use in this problem.  First, upgrade to Selenium 2.9.1 or higher.  That gives you access to the JavaScript function "test".  Then you can code the following that works to give you a Boolean result that you can use in your "gotoif".  Here is an example of one that I used recently.

*

*Prompt the user for a number from 1-11.

*Place the prompt variable into a number object. (Not sure if this is necessary?)

*Define the regular expression into a variable.

*Lastly, use the JavaScript "test" function to produce a Boolean response placed in the "results" variable.

*This leaves you a "results" field to determine your "gotoif".

Here is the code.

    showPrompt
    Please select a number between 1-11 only!!!
    userAnswer
<\tr>

    storeEval
    new Number(storedVars['userAnswer'])<\td>
    nbrAnswer

    storeEval
    javascript{var regExpTester = /^[1-9][0-1]?$/; regExpTester.test(storedVars.nbrAnswer);}
    results
<\tr>


text:
Q: How to use JavaScript replace() without triggering the special replacement patterns? I'm trying to inject some code into a file by using replace. The problem is if the target code contains any of the replace() function's special character sequences, namely $$, it will do something different than what I expect, which is to just copy the characters exactly as they are.
'replaceme'.replace('replaceme', '$$');

you would think this would result in $$ but it actually returns $
Is there a way to disable this functionality so that it maintains the $$ like I want?

A: No idea why the $$ wasn't working, I too am wondered.
But you can get the result by using the callback function.
'replaceme'.replace('replaceme', () => '$$');

A: If you do not like to apply the replacement string patterns, you can use a replacement function:
'replaceme'.replace('replaceme', (_match) => '$$');

A: This might be a bit hacky, but you can create a new method on String that replaces all $ characters in the replacement string with $$:

function replaceRaw(original, match, text) {
  text = text.replaceAll('$', '$$$');
  return original.replace(match, text);
}

console.log(replaceRaw('replaceme', 'replaceme', '$$'));

Note that $$ in the replacement text will become a single $, so this new method makes all $s in the replace $$ (see this MDN article).


text:
Q: MKMapView calloutview height I want to increase height of calloutview but i tried lot of code but still height is not increasing ,
Please tell me how can i increase calloutbubble height
I am using this code
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
static NSString *AnnotationViewID = @"annotationViewID";
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[map dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil)
{
    annotationView =[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
}

NSLog(@"array count %lu ",(unsigned long)[arrayOfAnnotation count]);

if ([arrayOfAnnotation containsObject:annotation])
{
    for (OSAnnotation *anootation in arrayOfAnnotation)
    {
        if (anootation==annotation)
        {
            //NSLog(@"UserName : %@ ",model.fullName);
            annotationView.image = [UIImage imageNamed:@"pinGold24.png"];
            annotationView.frame=CGRectMake(0, 0,32,32);
            annotationView.canShowCallout = YES;
            annotationView.draggable=NO;
            annotationView.userInteractionEnabled=YES;

            //   NSLog(@"latitude = %f logintude = %f",lati,longi);

            UIView *calloutView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 300, 100)];
            UIImageView *imgListingImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 60, 60)];
            imgListingImage.backgroundColor = [UIColor redColor];
            UILabel *lbl_title = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, 200, 21)];
            lbl_title.text = map_title;
            [lbl_title setTextColor:[UIColor darkGrayColor]];
            [calloutView addSubview:lbl_title];
            [calloutView addSubview:imgListingImage];

            annotationView.leftCalloutAccessoryView=calloutView;
            annotationView.rightCalloutAccessoryView = nil;
        }
    }
}
else
{
    annotationView.canShowCallout=YES;
    annotationView.draggable=NO;
    annotationView.image=[UIImage imageNamed:@"pinGold24.png"];
}

return annotationView;
}

my calloutview is looking like this


text:
Q: error 503 localhost google datastore So I am a total novice when it comes to datastore and cloud interaction, and I am trying to figure out the basics of datastore through the google bookshelf tutorial. I have the free trial running for 60 days and just want to wrap my head around how it works.
So in the setup I reached this portion of the tutorial (screenshot of google site) (this is the url: https://cloud.google.com/java/getting-started/using-forms) and I seem to be doing okay. I ran the code it asks for and seem to have started a jetty server in my terminal. It reads:

[INFO] Started ServerConnector@5ef8c2f7{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
  [INFO] Started @14439ms
  [INFO] Started Jetty Server

So the next step is to go to localhost8080 in my browser but when I get there I get an HTTP 503 Error that reads:

Problem accessing /. Reason:
  Service Unavailable

I can't seem to find a solution to this anywhere, so I was wondering if anyone could give me some insight into what I should do. Thanks!


text:
Q: Why is TypeError raised when attribute name matches class name using typing? I'm unable to initialise a dataclass list attribute where the attribute has the same name as the list elements' class.
The initialisation works fine when the attribute name is changed. I have the same problem with Pydantic classes.
from dataclasses import dataclass, field
from typing import List

@dataclass
class Thing:
    name: str

@dataclass
class MyClass:
    Thing: List[Thing] = field(default_factory=list)

c = MyClass()

This gives the following error:
TypeError: Parameters to generic types must be types. Got Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object at 0x00000201CA208518>,default_f.

When I change:
    Thing: List[Thing] = field(default_factory=list)

to:
    thing: List[Thing] = field(default_factory=list)

the TypeError is not raised.

A: Because then it's overriding Thing.
That's why thing works.


text:
Q: JSF - Custom Tags - Dynamic values disappear after refresh I've followed this tutorial for implementing a marquee-tag in JSF 2.1 and succeeded partly. As this tag does NOT support dynamic data, e.g. #{bean.var} as a value, I've decided to do it dirty inside the component.
However, after reloading my page, the value disappears. The tag is still there, but the content is gone.

*

*Could you show me how to implement is correctly, that I can use my dynamic value inside the value-attribute?

*Or would you point me into the right direction which code is causing the error in my component class?

Thank you very much!
http://myjavabuddy.blogspot.de/2013/04/writing-custom-components-for-jsf-20.html
This is my JSF
<customJSF:marquee value="" />

This is my Component
@FacesComponent ("amelunxenfast.prog3.wissensmanagement.components.marquee")
public class MarqueeComponent extends UIComponentBase {

  public static final String COMPONENT_TYPE = "com.himanshu.jsf.custom.marquee";

    String value = null;

    @EJB
    FeedEJB ejb;

    public String getValue() {
        return value;
    }

    @Override
    public String getFamily() {
        return COMPONENT_TYPE;

}

@Override
public void encodeBegin(FacesContext context) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    writer.startElement("marquee", this);
    writer.writeAttribute("scrollamount", "10", "");
    writer.write(ejb.getFeedString());
    writer.endElement("marquee");
}

@Override
public void encodeEnd(FacesContext arg0) throws IOException {
    super.encodeEnd(arg0);
}

public void setValue(String value) {
    this.value = value;
}

}

A: Too long for a comment...
I don't think it's legit to inject @EJB inside @FacesComponent and i don't think it's a good practice, in this specific case.
I think a better approach should be extending TextRenderer with your own class, declare a new component in faces-config and use it the same way you use h:outputText (passing ValueExpression in value attribute)


text:
Q: Are there any text-only CAPTCHA systems available? for some niche reasons I often find that a text-only captcha would be better than the traditional image/audio solutions. Some of the reasons I can think of off the top of my head:

*

*Text-based browser support(lynx, links, etc)

*To provide write-capable public APIs, but prevent massive amount of spam

*For accessibility reasons (I've heard that the audio versions are very hard to understand to prevent voice-recognition software attacks)

Are there any text-only CAPTCHA systems available out there?

A: http://textcaptcha.com/ is a logic based, but also purely text based, captcha system., and is free too.
I don't think you have any control over the type of questions that are passed to you, but worth reading the documentation. Whilst it may pose problems for users with cognitive disabilities, it's on the right track, and an improvement on the standard recaptcha type captchas, which create difficulties for blind and vision impaired users alike.

A: All of the CAPTCHAs I've seen that don't use images or audio involve some sort of cognition:

*

*What day of the week is tomorrow?

*Who was the host of last week's SNL?

*What is 2 + 3 plus four?


text:
Q: Which superheroes went to Agartha (or Attilan)? As I remember it, some superhero comic featured the mythical city of Agartha.
I think, in this version, it was a city tucked away in some mountains, maybe under some sort of shield or dome?
I can't remember whether the heroes had a base there of if they were trying to protect it.
I've been trying to find it, but I can't even remember which comic it was... I think it was a Marvel comic. I read in in Sweden in the eighties, and it was probably in Swedish, so probably X-Men or Fantastic Four. I believe it was a team of heroes (perhaps the X-Men), not a single protagonist like Spiderman.
I have tried to search for it but I can't it, so I'm starting to think I remember it wrong, maybe it wasn't Agartha at all, but some other legendary city.
Can anybody help me find what comic it was, and maybe point to specific stories?
Edit: I updated the topic, hoping this might help anybody else who confuses Agartha with Attilan. Of course, it might just a be me.

A: You may be thinking of Attilan, home of the Inhumans.
First introduced in FANTASTIC FOUR in the 1960s (around issues 44-47), the Inhumans were a race who could use something called terrigen mists to give themselves powers. They lived in Attilan (also called the Great Refuge), a city in the Himalayas. The city was trapped in a dome (placed there to protect it, but basically impenetrable). A couple of Inhumans were able to get out due to the powers of their pet dog (about the size of a small hippopotamus), Lockjaw, who could teleport. The Fantastic Four journey to Attilan. The dome was destroyed by Black Bolt, ruler of the Inhumans, who counts among his powers the ability to destroy things with his voice.


text:
Q: Building Expression Tree Using a Parameter's Indexer Given a class that has a property that is a Dictionary
public class Product
{
    public Dictionary<string, string> Attributes { get { return attributes; } }

    private Dictionary<string, string> attributes = new Dictionary<string, string>();
}

I want to be able to match products in a list of products based on criteria that are retrieved from a data store that are in the format of
Brand == Tyco
Color != Blue

My current approach is to construct an expression from the filter, and then pass that expression as the parameter to a LINQ Where method call like so
products = products.Where(myConstructedExpression);

where myConstructedExpression would normally be a lamda expression that looks like
p => p.Attributes[attribute] == value

I have assembled the following code for testing purposes, but it always fails the call to lambda.Compile() regardless of what I have tried for he left expression.
Dictionary<string, ExpressionType> expressionType = new Dictionary<string, ExpressionType>();
expressionType.Add("==", ExpressionType.Equal);
expressionType.Add("!=", ExpressionType.NotEqual);

string filter = "Brand == Tyco";
string[] fields = filter.Split(' ');
string attribute = fields[0];
string op = fields[1];
string value = fields[2];

Product product = new Product();
product.Attributes.Add("Brand", "Tyco");

var parameter = Expression.Parameter(typeof(Product), "p");
var left = /***** THIS IS WHAT I AM FAILING TO CONSTRUCT PROPERLY ********/
var right = Expression.Constant(value);
var operation = Expression.MakeBinary(expressionType[op], left, right);
var lambda = Expression.Lambda<Func<Product, bool>>(operation, parameter);

var result = lambda.Compile()(product);

Questions

*

*Is this even a reasonable approach, and, if so,

*How do I construct the left expression?

A: So to get p => p.Attributes["Brand"] <someoperator> "Tyco", you can do this.
The "trick", to work with indexed types, is to use their Item property (you could also work with the get_item method)
var parameter = Expression.Parameter(typeof(Product), "p");
Expression left = Expression.Property(parameter, "Attributes");
left = Expression.Property(left, "Item", new Expression[] { Expression.Constant(attribute) });

EDIT
the version with the IDictionary.ContainsKey(<value>) test
really step by step, but I think this makes things clearer at first.
//left part of lambda, p
var parameter = Expression.Parameter(typeof(Product), "p");
//right part
//p.Attributes
Expression left = Expression.Property(parameter, "Attributes");

var method = typeof(IDictionary<string, string>).GetMethod("ContainsKey");
//p.Attributes.ContainsKey("Brand");
Expression containsExpression = Expression.Call(left, method, Expression.Constant(attribute));
//p.Attributes.Item["Brand"]
Expression keyExpression= Expression.Property(left, "Item", new Expression[] { Expression.Constant(attribute) });
//"Tyco"
var right = Expression.Constant(value);
//{p => IIF(p.Attributes.ContainsKey("Brand"), (p.Attributes.Item["Brand"] == "Tyco"), False)}
Expression operation = Expression.Condition(
                           containsExpression,
                           Expression.MakeBinary(expressionType[op], keyExpression, right),
                           Expression.Constant(false));
var lambda = Expression.Lambda<Func<Product, bool>>(operation, parameter);


text:
Q: How could I detect mouseDown event outside my NSView? I create my custom NSView when a certain button is clicked, and I want to close this custom view if your click outside the NSView. But it seem that I could not receive mouseDown event in this custom NSView. Is there anyone know how to fit it ? Many thanks.

A: I wanted to share two other solutions that unlike the NSEvent approach, doesn't have the sandbox limitations.
A cover window.
It's more involved code and a good exercise in learning what's possible with windows and views. But worth learning and knowing.
Create a borderless window that takes up the whole screen. The borderless window can then handle mouse events.
A tracking area.
This approach is similar

A: you want to use NSEvent global event monitor.
Then you may need to convert the mouse NSPoint to your view coordinates and use the function NSPointInRect to see if it is inside or not.


text:
Q: Which GEO data format does this data represent I am parsing GIS data from a ESRI webservice in which I get the data specified as the following in a JSON file
"geometryType" : "esriGeometryPoint",
"spatialReference" : {
"wkid" : 102100

an example of the data provided has the following look
"geometry" : {
    "x" : 1734891.0457560429,
    "y" : 5740400.9625475956
  }

I don't usually work with GIS data so I am not sure what I am doing.
I want to store it in a SQL server DB as a GeoGrapy datatype which requires values between [-90, 90] and [-180, 180] degrees.
How Do I convert these coordinates. I do not know which format it is so I can not search for transformation equations.
could it be wgs84?
(The location is in Europe)

A: I just googled "wkid 102100" and it took me to
http://spatialreference.org/ref/sr-org/esri102100/
which should hopefully give you what you need.

A: WKID: 102100 is also known as WGS84 Web (or Pseudo) Mercator, or also known as EPSG:3857. It's a Mercator variant where it uses the spheroid formula but the lat/longs are ellipsoidal, and thus isn't conformal.
If you'd like to try to do your own conversion, read the EPSG Guidance Note 7-2, and you'll find the Pseudo-Mercator formula on page 40.


text:
Q: Why can't I connect to my DB I've  set  up an apache2 ubuntu server on AWS, I  create a mySQL db in said server, now  I'm trying to update the database from my android application but its  not  connecting.
This is the PHP file in the server side which should connect to the db.
<?php
 define('HOST','ec2-54-171-67-69.eu-west-1.compute.amazonaws.com');
 define('USER','root');
 define('PASS','password');
 define('DB','ugproject');

 $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
 ?>

This is the Java method.
private static final String REGISTER_URL = "ec2-54-171-67-69.eu-west-1.compute.amazonaws.com/volleyRegister.php";
 private void registerUser(){
        final String username = editTextUsername.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();
        final String email = editTextEmail.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

This is the error I get:
E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 412 for http://ubuntu@ec2-54-171-67-69.eu-west-1.compute.amazonaws.com/volleyRegister.php

I've tried to be as clear as possible feel free to ask for any more info, thanks.

A: Try this might work .
Separate the DB name
$con = mysql_connect (HOST,  USER,  PASS) OR die ('could not connect to MySQL.');
mysql_select_db(DB);

A: Based on this link in one of your comments (here), it doesn't look like you have PHP installed on the server since it's printing out the code.
Easiest way to install it is using sudo apt-get install lamp-server^ command on Ubuntu.
If you just need PHP, use sudo apt-get install php7.0. Once you install it, then use sudo service apache2 restart to restart your apache server to apply the PHP installation.
To test if PHP is up and running, write this code into a file, and you should get a table full of data about the PHP installation when you go to it in your browser:
<?php
phpinfo();
?>

A: Error code 412 means

Precondition Failed
  The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended.

This is likely cause by the fact that the URL that you provided

http://ec2-54-171-67-69.eu-west-1.compute.amazonaws.com/volleyRegister.php

Seems to be running a webserver, but is not properly interpreting the PHP script - it displays to me the raw text of the PHP file.
<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){
 $username = $_POST['username'];
 $email = $_POST['email'];
 $password = $_POST['password'];

 require_once('dbConnect.php');

 $sql = "INSERT INTO users (username,password,email) VALUES ('$username','$email','$password')";

 if(mysqli_query($con,$sql)){
 echo "Successfully Registered";
 }else{
 echo "Could not register";

 }
 }else{
echo 'error';
}
?>

Perhaps you do not have the php plugin installed, or is is not properly configured.

This is an issue on the server side, not on the app side.


text:
Q: how to change value of input before formControl directive get it in angular need to convert persian numbers to english ones in this input <input type="text" formControlName="mobile" myCustomDirective />.
so created a directive, with entering Persian number events fire with that value, then I change it to English number and again all events fire with English one. if I prevent events from firing for the second change it's wrong because I need events fire with English number.
actually, I need to get the value of the input and change it to English before FormControl directive catches it.
is there any solution?

A: finally I could resolve my question:
import { DecimalPipe } from '@angular/common';
import { Directive, ElementRef, forwardRef, HostListener } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
selector: '[appInputConvertNumbers]',
providers: [
 {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => InputConvertNumbersDirective),
  multi: true
 },
  DecimalPipe
]
})
export class InputConvertNumbersDirectiveimplements ControlValueAccessor {
private _onChange: (value: any) => {};
  constructor(private _elementRef: ElementRef) { }
  @HostListener('input') onInput() {
    let value = this._elementRef.nativeElement.value;
    let newValue = this.setInputValue(value);
    this._onChange(newValue);
  }
  private setInputValue(value: string): string {
    value = value.replace(/[۰-۹]/g, number => '۰۱۲۳۴۵۶۷۸۹'.indexOf(number).toString())
    this._elementRef.nativeElement.value = value;
    return value;
  }
  writeValue(value: string): void {
    this.setInputValue(value);
  }
  registerOnChange(fn: any): void {
    this._onChange = fn;
  }
  registerOnTouched(fn: any): void {
  }
}

and simply in the form I can use this directive
<form [formGroup]="exampleForm">
  <input appInputConvertNumbers formControlName="number">
</form>


text:
Q: Legacy database - model validation I am using a legacy database in my rails app.
I would like to incorporate model validation in my application but it does not seem to work with legacy database.
** model Person **
class Person < ActiveRecord::Base

set_table_name "EMI_PERSON"
set_primary_key "PER_ID"
attr_accessor :person_title
validates :PER_FORENAME, :presence => true

end

When I include 'validates :PER_FORENAME, :presence => true' in my model, I get the following error message:
NoMethodError in PersonsController#edit

undefined method `validates' for Person(Table doesn't exist):Class

I would really appreciate any help regarding this.

A: Try using validates_presence_of instead of validates.


text:
Q: (Tricky) Call method from app.xaml.cs I have a Pivot-Page App, which has different app-bars for each different page.
The methods from the app-bar are all declared in app.xaml.cs but all the input-elements are on MainPage.xaml.cs.
I have a login button on one of my app-bars, but in the app.xaml.cs I have no access to textboxes etc.
Creating a new instance of MainPage isn't helping, because all textbox values would be empty.
Yes, my method in MainPage is public, but MainPage.method(); doesn't work.
How can I call a method in MainPage.xaml.cs, which uses MainPage's textboxes, from app.xaml.cs?

A: ((MainPage)App.Current.RootVisual).method()

A: I went brute force: I made my app bar by hand in the class I wanted to make it.
And it works.
I got the tip from MS

A: Here is a generic how to based on the code I needed for an app I am writing:
In MainPage.xaml you create a method as follows:
public static void InMainPage()
{
    System.Diagnostics.Debug.WriteLine("Hi I am a method in MainPage.xaml.cs");
}

Now in App.xaml.cs you can now reference it in any method as such:
MainPage.InMainPage();

Hope this answer helps you or someone else in the same predicament


text:
Q: How to prove that F is constant in this question? "Be $f: R^2 \rightarrow  R $ a continuous function that has continuous first order partial derivatives and satisfies the relation $2f_x(x,y)+f_y(x,y) =0$, for all (x, y). Being $f_x$ the derivative with respect to X and $f_y$ the derivative in relation to y, prove that F is constant on the lines of equation x - 2y = c"
Is this question missing information? I don't know how to start.
I know that there is a relation between x and y on the line of equation x - 2y = c, but I don't know how to calculate the integral of F starting of this point to prove that F is constant.

A: Basically, we know $f_y = -2f_x$ everywhere, so if we take a directional derivative, which is the same as taking the dot product of the gradient and the direction (in this case, along the lines), we get zero for the direction specified by the lines. That is, the lines give the direction (2,1), while the gradient is proportional to (1,-2), so the dot product is 2-2=0.

A: Substitute for $x$ in the differential equation to get $$2\partial f_x(c+2y,y)+\partial f_y(c+2y,y)=0.$$ Then it follows that $\partial f_x(c+2y,y)=0.$ Consequently, we also have that the second summand vanishes. Since the gradient vanishes, it follows by MVT that the function is constant provided the restraint $x-2y=c$ holds.


text:
Q: Call function is not a function $(function() {
    var previous_page = "<?=$_SESSION["previous_page"]?>";
    if (previous_page == "bar_settings")
        $.club_settings();

    $.club_settings = function() {
        $(".bar_settings").fadeIn(1000);
        $(".bar_photos").hide();
        $(".bar_activities").hide();
        $(".bar_campaigns").hide();
        $(".etkinlik_ekle").hide();
        $(".kampanya_ekle").hide();
    }

})(jQuery);

I got an error that is $.club_settings is not a function. How can i call $.club_settings in a if condition ?

A: You're defining the function after you call it.  Switch around the code like so:
$(function() {
    $.club_settings = function() {
        $(".bar_settings").fadeIn(1000);
        $(".bar_photos").hide();
        $(".bar_activities").hide();
        $(".bar_campaigns").hide();
        $(".etkinlik_ekle").hide();
        $(".kampanya_ekle").hide();
    }

    var previous_page = "<?=$_SESSION["previous_page"]?>";
    if (previous_page == "bar_settings")
        $.club_settings();

})(jQuery);

A: JavaScript only hoists declarations, not initializations.
The reference above displays how variables are hoisted but it works for functions too.
$(function() {
   var previous_page = "<?=$_SESSION["previous_page"]?>";
   if (previous_page == "bar_settings")
     club_settings();

   function club_settings() {
     $(".bar_settings").fadeIn(1000);
     $(".bar_photos").hide();
     $(".bar_activities").hide();
     $(".bar_campaigns").hide();
     $(".etkinlik_ekle").hide();
     $(".kampanya_ekle").hide();
   }
})(jQuery);

The drawback would be is that it would be found in your $ variable which may lead to codes elsewhere breaking. But that could be another question.
Trying to resolve this by doing $.club_settings() = function club_settings() { ... will not work unless you reorder your codes as suggested by Mike


text:
Q: How that JavaScript will resolve? I am using some node.js code and there is one line in that code.
Can any one help me how that following javascript code will resolve?
var silent = 'test' == process.env.NODE_ENV;

why that code use = and == at one line?
I guess its a kind for shorthand coding style but I do not know what will be its full-form.

A: The var, variable declaration statement works from the left most expression to the right. The left hand side expression is evaluated first and then the right hand side expression. So, it creates a variable silent and then assigns the result of the comparison to it.
Parenthesis would have helped to understand this better,
var silent = ('test' == process.env.NODE_ENV);

This checks if the environmental variable NODE_ENV is equal to "test" or not. And the boolean result will be used to initialize the newly created variable silent, at runtime.

A: It will resolve to a boolean value ( true/ false ):
// if process.env.NODE_ENV is 'test'
var silent = 'test' == process.env.NODE_ENV;
console.log(silent); // true

// if process.env.NODE_ENV is 'production'
var silent = 'test' == process.env.NODE_ENV;
console.log(silent); // false

The developer is doing this for semantic value. He could done:
var silent;
if ('test' == process.env.NODE_ENV){
    silent = true;
}
else {
    silent = false;
}

but this is less succinct and poignant.


text:
Q: nservicebus a client sends command to msmq and azure service queue I would like to know how, if possible, a client app (winform) sends NServicebus command A to be processed by a MSMQ queue and command B to be processed by a Azure storage queue or Azure service bus? If not, how may I get around of it?

A: Since this question was asked, there is now a transport bridge which is specifically for this scenario: bridging messages between two different transports.

A: Will this help? https://docs.particular.net/samples/azure/azure-service-bus-msmq-bridge/

Common examples include:

A hybrid solution that spans across endpoints deployed on-premises and in a cloud environment.
Departments within organization integrating their systems that use different messaging technologies for historical reasons.
Traditionally, such integrations would require native messaging or relaying. Bridging is an alternative, allowing endpoints to communicate over different transports without a need to get into low-level messaging technology code. With time, when endpoints can standardize on a single transport, bridging can be removed with a minimal impact on the entire system.```


text:
Q: How to stop flickering from prompts when saving Excel rows to different file format? I have a VBA macro that saves Excel row data to .svg files. This code is working but I can't get the prompts to stop.
I want the code to work silently without throwing prompts after each conversion.
I am referring to the flickering not the actual prompts.
Sub SaveRowsAsSVGs()

Dim wb As Excel.Workbook, wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim r As Long, c As Long
Set wsSource = ThisWorkbook.Worksheets("Images")

Application.DisplayAlerts = False 'will overwrite existing files without asking

r = 1
Do Until Len(Trim(wsSource.Cells(r, 1).Value)) = 0
    ThisWorkbook.Worksheets.Add ThisWorkbook.Worksheets(1)
    Set wsTemp = ThisWorkbook.Worksheets(1)

    For c = 2 To 7
        wsTemp.Cells((c - 1) * 2 - 1, 1).Value = wsSource.Cells(r, c).Value
    Next c

    wsTemp.Move
    Set wbNew = ActiveWorkbook
    Set wsTemp = wbNew.Worksheets(1)
    Dim myPath As String
    myPath = "C:\Users\myname\Desktop\Folder\Images\"
    wbNew.SaveAs myPath & wsSource.Cells(r, 1).Value & ".svg", xlCSV
    'wbNew.SaveAs "cell.Text" & r & ".svg", xlCSV 'new way
    wbNew.Close
    ThisWorkbook.Activate
    r = r + 1
Loop

Application.DisplayAlerts = False

End Sub


text:
Q: How to get CODE from formatResult in an Autocomplete plugin? I have this:
var objects_list = [{
    "code": "44",
    "name": "Privilegios de cuenta",
    "alias": "account-privileges",
    "typename": "Opci\u00f3n",
    "typealias": "object",
    "description": null
}, {
    "code": "104",
    "name": "Asignar aplicaciones",
    "alias": "add-application-to-user",
    "typename": "Opci\u00f3n",
    "typealias": "object",
    "description": "Permite asignar aplicaciones a las cuentas"
}];
$('#find_object').autocomplete(objects_list, {
    minChars: 0,
    width: 310,
    matchContains: "word",
    autoFill: false,
    formatItem: function(row, i, max) {
        return "<b>" + row.name + "</b>" + " (" + row.description + ")";
    },
    formatMatch: function(row, i, max) {
        return row.name + " " + row.alias + " " + row.description + " " + row.typename + " " + row.typealias;
    },
    formatResult: function(row) {
          $('#code_to_use').val( row.code );
          return row.name + " (" + row.description + ") ";
    }
});

This code works well, but I can't understand the code very clearly. In the formatResult function, the line  $('#code_to_use').val( row.code ) is never executed or did I get it wrong?


text:
Q: Log user in via frontend in Selenium Capybara Rspec Tests I want to be logged in as a user during my tests that use javascript, so I figured I should have a helper method which logs a user in via frontend.
However with the helper
    def log_user_in_via_frontend(user)
        visit root_path
        fill_in 'user_session_login', :with => user.login
        fill_in 'user_session_password', :with => user.password
        click_on('Login')
    end

I am able to be logged in and am redirected to the right page as long as I don't put :js => true at the end. I call this helper via
    user = FactoryGirl.create(:user)
    log_user_in_via_frontend(user)

Visiting root_path afterwards yields No route matches {:controller=>\"users\", :action=>\"show\", :id=>#<User id: nil, login: nil...
What's the best way to have an logged in user in my selenium tests?

A: Actually by now this works for me. I am not sure what for exactly, but I think the key is deactivate transitional fixture, and to have database cleaner do the cleaning.


text:
Q: An Apparent Incongruity I thought of a certain point that seems to point to an apparent incongruity. Hopefully someone would promptly point out the logical mistake and/or some implicit assumption that may not hold under a closer look. Even though the question is a quite long in length, the actual point is very short. I have thought about it for a good number of hours, but I am likely suffering from a blindspot (and possibly an easy one, though I would hope it isn't trivial).
So here is the rather short construct, so to speak. Let's first consider the case of $\omega_{CK}$. Now we want to define two functions $F:\omega \rightarrow \omega_{CK}$ and $f:\omega \rightarrow \omega$ (the way I consider $F$ and $f$ in the actual question is almost exactly the same). For $F$, we simple define $F(x)$ to be the ordinal value whose well-order relation (for a well-order of $\mathbb{N}$) is generated by program with index $x$. If the program with index $x$ doesn't generate a well-order relation we can set $F(x)=\omega_{CK}$ (just as a matter of convention really).
Now we want to define the function $f$. We define $f(0)$ to be the smallest value $a \in \mathbb{N}$ that satisfies the property $F(a)<\omega_{CK}$. Now we recursively define $f(x+1)$ to be the smallest value $a \in \mathbb{N}$ such that:
(1) $F(a)>F(f(x))$ AND (2) $F(a)<\omega_{CK}$. It isn't difficult to see that: (a) $f$ is a strictly increasing function (b) The function $G:\omega \rightarrow \omega_{CK}$ defined by the equation $G(x)=F(f(x))$ forms a (fundamental) sequence for $\omega_{CK}$.
Now before proceeding, an elementary point that is relevant to the question. Consider an ordinary program where all variables start from value $0$. We also assume that the only way to increase the value of a variable is by the command of form $v:=v+1$. Now suppose we wanted to set a variable value to say $1000,000$. We don't have to write the same number of lines for increment. We can just write a function ($\mathbb{N}$ to $\mathbb{N}$) such as $x \rightarrow 10^x$. Suppose hypothetically that this function takes $100$ lines. Now all we have to do is increment a variable (call it $v$) six times in the beginning and then place the body of function calculating $10^x$ afterwards (replacing the input variable by $v$ in the body of course). This will set the output variable to $1000,000$ in $106$ lines.

And now here is my confusion. Let $c$ be the supremum of clockable values for an ordinal-register program (or a program model that is quite similar to it). Now define a function $F:\omega \rightarrow c$ so that $F(x)$ returns the value clocked by the program with index $x$. If the program with index $x$ doesn't halt set $F(x)=c$ (as convention). Now define functions $f:\omega \rightarrow \omega$ and $G:\omega \rightarrow c$ in a manner completely identical to how they were defined in first part of question.
Consider the family of programs that, for some given value $a \in \mathbb{N}$, simulate the program with index $f(a)$. These programs halt in their simulation when the program with index $f(a)$ halts. These programs all have the same structure. For convenience choose $f$ to be a very simple function, say $x \rightarrow 10^x$ (obviously $f$ can't be recursive, but the main thing is just that $f$ is strictly increasing). The main point that is confusing me is, that for a very large value $a \in \mathbb{N}$ (and hence also very large $f(a)$), why can't we just set a variable equal to value $f(a)$ rapidly in a few lines and then simulate the program with index $f(a)$ using essentially a universal program. And unless the specific construction for infinite case (since I have never written it in full detail) has some drastic different from finite case here, wouldn't this be a constant overhead in terms of number of lines.
It sounds too abstract but a simple example would help. Suppose writing the universal program takes about $200$ lines. Now as I mentioned above, suppose that $f(x)=10^x$. In particular, we have $f(6)=1000,000$. But couldn't we just set a variable whose value equals $1000,000$ in $106$ lines (as I mentioned in first part of answer) and then place the body of universal program afterwards (to simulate the program with index $1000,000$). Wouldn't this would take a total of just $200+106=306$ lines? Sure its index will be a bit higher, but I am not clear that this makes any real difference. The program with index $1000,000$ clocked the value $G(5)=F(f(5))$. And now somehow the program with smaller index is clocking a value greater than or equal to $G(5)$ [assuming that simulating a program will always be at least as expensive as directly running the program]?
Now given that our indexing is well-behaved in the sense that it assign the program of bigger length the greater index, then what I wrote in above paragraph simply shouldn't hold (otherwise there seems to be an incongruity). Hopefully someone will promptly point out the error.

A: This is an OK question, you just have not explained it very clearly. I think people are downvoting because they think you are confused about whether $f$ is computable or not (which you aren't).
What you're running into is something that ultrafinitists study in detail. It boils down to the fact that "having a short description" is not closed downwards. For example, we can describe a very, very large number with only a handful of characters by $4 \uparrow^{100} 5$ in Knuth's "up arrow" notation. But most of the numbers less than $4 \uparrow^{100} 5$ don't have descriptions that could ever be written down, or even descriptions of length less than $4 \uparrow^{99} 5$. This is just the pigeonhole principle.
One way to think about this is to use algorithmic incompressibility using prefix free Kolmogorov complexity. Fix a compression factor $r < 1$, and look at the proportion of strings $\sigma$ of length $<n$ which can compressed by at least factor $r$ (i.e., have $K(\sigma) < r|\sigma|$, where $K(\sigma)$ is the length of the shortest description of $\sigma$ according to a fixed universal encoding scheme). This proportion has to converge to zero as $n \rightarrow \infty$.
This tells you that you shouldn't expect a priori that the values of your function $f$ are going to be compressible. And in fact if you think carefully about what you've written, you've actually proven that they can't be compressible by more than than a fixed additive constant determined by the size of a universal machine.


text:
Q: Diesel compilation hangs on Lightsail I'm trying to deploy a database-backed Rust app on Amazon Lightsail.  It uses the ORM crate Diesel.  It compiles without trouble on my local (Arch) Linux machine.
To compile the app remotely, I SSH into a Lightsail Debian VM.  After installing Rust, cloning the repo, and specifying the toolchain, I run cargo build.  This does compile a bunch of crates, but in compiling Diesel it appears to hang.  At least, calling ps shows the cargo and rustc processes appearing to continue after 30 mins.
I've tried Diesel versions 1.4.5 and 2.0.0, stable and nightly Rust toolchains, and Ubuntu as well as Debian VMs.
[Edit: the app also compiles without trouble on a Linode VM.]
What could be the problem?  (How can I collect further information for diagnosis?)

A: What is the CPU graph showing?
Lightsail uses burstable instances that have a baseline of CPU and can handle occasional traffic spikes, but if you spike the CPU for too long then the CPU gets throttled.
If you check on the instances metrics tab you can see if it's running out of burst capacity (choose burst capacity percentage or minutes from the drop down).


text:
Q: Optimizing Entity Framework (Multiple queries per model in gridview) I am working on an application in WinForms. My data is stored in an MSSQL server (Azure). Part of my application includes some basic billing features. One model I have is Invoices, but I have run into quite the performance issue. My first question really is, who is to blame? My poorly optimized code or the underlying entity framework. The main issue lays in when I am displaying a list of invoices in a DataGridView. For each invoice that I list, I need to make multiple calls to the DBContext. Is that unresonable? I need to make multiple calls for this reason; one to get the list of invoices to display (Based on the FK CustomerID), and then for each Invoice model I call some methods which calculate things like SubTotal, TaxTotal, Etc. Those functions are below.
    public decimal SubTotal()
    {

        decimal subtotal = 0;
        List<Billing_InvoiceItems> LineItems = db.Billing_InvoiceItems.Where(a => a.InvoiceID == this.id).AsNoTracking().ToList();
        {
        foreach (var LineItem in LineItems)
            subtotal += (LineItem.Cost * LineItem.Quantity);
        }

        return subtotal;
    }

    public decimal TaxTotal()
    {

        decimal taxtotal = 0;
        List<Billing_InvoiceItems> LineItems = db.Billing_InvoiceItems.Where(a => a.InvoiceID == this.id).AsNoTracking().ToList();
        foreach (var LineItem in LineItems)
        {
            if (LineItem.Taxable)
            {
                taxtotal += LineItem.Cost * (decimal) LineItem.TaxPercentage;
            }
        }

        return taxtotal;
    }

    public decimal Total()
    {

        return (this.SubTotal() + this.TaxTotal());
    }

    public decimal TotalDue()
    {
        return (this.Total() - this.TotalPaid());
    }

    public decimal TotalPaid()
    {

        List<Billing_PaymentToInvoice> paymentsToInvoice = db.Billing_PaymentToInvoice.Where(a => a.InvoiceID == this.id).ToList();
        decimal totalpaid = 0;
        foreach (var Payment in paymentsToInvoice)
        {
            totalpaid += (decimal)Payment.AmountApplied;
        }

        return totalpaid;
    }

Am I being unreasonable by needing to make multiple SQL "Queries" per Invoice that I list? Or is there a way I can optimize these functions? I have tried one approach as to cache the invoice items (allowing me to calculate the totals for display to the user) However, this required me to then have a function which i seemingly called often to keep the cache up to date.
EDIT: You'll see .AsNoTracking() in there on the LineItems query, this was an attempt at optimizing it from some searching online.


text:
Q: JZZ's Standard MIDI File extension plays MIDI too slowly This is the code I used to initialize SMF. I don't really know what to try here, and I can't seem to find any other mention of it online.
var fileplayer = new JZZ.MIDI.SMF(mididata).player();
fileplayer.connect(out);
fileplayer.play();

I tried using midi-player-js and easy-midi together but I couldn't find a nice way to play a MIDI that way.
The tempo is far too slow, as you can see here:
Demonstration (MP4, H264/AAC)


text:
Q: Excel: How to add unique values based on another column but not unique when on its own Is there way to achieve the SUM() of all the unique values in the WEIGHT column, based on the unique value from VISIT ID column, and only add those that repeat only if the VISIT ID value changes?
So control-break on VISIT ID and add unique values per VISIT ID. I hope that made sense? Thanks
The SUM() here is only for illustration of what I am trying to achieve.

Data:
VISIT ID    VESSEL NAME  WEIGHT
15  FLORA DELMAS     2,740.9580
15  FLORA DELMAS     2,740.9580
15  FLORA DELMAS     2,740.9580
15  FLORA DELMAS     2,740.9580
15  FLORA DELMAS     2,591.1002
15  FLORA DELMAS     2,591.1002
15  FLORA DELMAS     2,591.1002
15  FLORA DELMAS     578.7480
15  FLORA DELMAS     124.9010
15  FLORA DELMAS     19,994.0000
20  SOUTHGATE    19,994.0000
20  SOUTHGATE    19,994.0000
20  SOUTHGATE    11,013.0000
22  CAMILA   11,013.0000
22  CAMILA   28,521.0000
32  GULF LIVESTOCK 1     3,696.0000
32  GULF LIVESTOCK 1     3,696.0000
34  GOLDEN YOSA  2,905.0000

UPDATE 1
I forgot to say that I want the formula to use the range by columns and not across several adjacent columns... ie: A2:A19 and C2:C19... as the unique identifiers. Reason is I have many columns actually between A and C that are not in this sample, and I don't want to span all of them as they could change for other reasons.

A: Try:

Formula in F1:
=SUM(INDEX(UNIQUE(A2:C19,0),0,3))

Or, specifically VISIT ID and WEIGHT:
=SUM(INDEX(UNIQUE(CHOOSE({1,2},A2:A19,C2:C19)),0,2))
=SUM(TAKE(UNIQUE(HSTACK(A2:A19,C2:C19)),,-1))

A: Give a try on-
=SUM(FILTER(UNIQUE(FILTER(A2:C19,{1,0,1})),{0,1}))