text:
Q: django: unable to login using django Remote authentication I'm developing a new django project ,in the i have created a simple login page, which i want to just login and go to the home page.
when i try to login i'm getting and login is not happening successfully.
Project name: mysite
appname : dsmdata
Below are the codings

*

*project(mysite) Settings.py file below

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 2.1.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

os.environ['REMOTE_USER'] = "dsmuser1"

#LOGIN_URL = '/dsm/login'

# Redirect to home URL after login (Default redirects to /accounts/profile/)
#LOGIN_REDIRECT_URL = '/dsm/logged_in'
LOGIN_REDIRECT_URL = '/'

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y%cwxi-m5s-0zct+k%$u1$z!#o#u52zu_!z*#8(8saqdx+6t$l'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates',],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.RemoteUserBackend',
    'dsmdata.pmauth.pmauth',
]

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
     {
         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
     },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'C:/karthik/Projects/Postgres-DB-All/Statistics/debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

*

*Login page html:

{% extends 'base.html' %}

{% block content %}
    {% if form.errors %}

Your username and password didn't match. Please try again.

{% endif %}

{% if next %}
    {% if user.is_authenticated %}

Your account doesn't have access to this page. To proceed,
    please login with an account that has access.

    {% else %}

Please login to see this page.

    {% endif %}
{% endif %}

                    <form method="post" action="{% url 'login' %}">
{% csrf_token %}

                                    {{ form.username.label_tag }}
                                    {{ form.username }}

                                    {{ form.password.label_tag }}
                                    {{ form.password }}

                                <input class="btn btn-success btn-sm" type="submit" value="login" />

                        <input type="hidden" name="next" value="{{ next }}" />
                    </form>

{% endblock %}

{% block javascript %}

{% endblock %}

*forms.py (from my app , appname -dsmdata)

   #log/forms.py
from django.contrib.auth.forms import AuthenticationForm
from django import forms

# If you don't do this you cannot use Bootstrap CSS
class LoginForm(AuthenticationForm):
    username = forms.CharField(label="Username", max_length=30,
                               widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'}))
    password = forms.CharField(label="Password", max_length=30,
                               widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'}))

*My custom authentication class derived from RemoterUserBackend class

from django.contrib.auth.models import User
from django.contrib.auth.backends import RemoteUserBackend
import logging

logger = logging.getLogger(__name__)

class pmauth(RemoteUserBackend):
    def authenticate(self,request,username=None):
        logger.debug("Inside authenticate")
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # Create a new user. There's no need to set a password
            # because only the password from settings.py is checked.
            user = User(username=username)
            user.is_staff = True
            user.is_superuser = True
            user.is_authenticated = True
#           user.is_anonymous = abc.test
            user.save()
        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

    def configure_user(self,user):
        """Set user groups and privs.
        This method is called the first time a non-django user logs in.
        A user is created in the django database, this method
        adds the new user to the appropriate groups, and
        sets privs. """

        #Add all remote users to a group
        #user.groups.add(s.ALL_USERS_GROUP)

        #all remote users are staff - so they can access the admin interface
        user.is_staff=True

        user.is_superuser=True

        user.is_authenticated = True

        user.is_anonymous = abc.test

        logger.debug("Inside configure_user")
        logger.debug(user.username)

        #To determine if the user is to have further priviledges
        #we consult LDAP

        #connect to ldap server
#         l = ldap.initialize(s.LDAP_SERVER)

        #get list of superusers
#         superusers=l.search_s(s.LDAP_SEARCH_TREE,\
#                 ldap.SCOPE_SUBTREE,\
#                 s.LDAP_FILTER)\
#                 [0][1][s.LDAP_FIELD]

        #close LDAP Connection
#         l.unbind()

        #Check if this user should be a superuser.
#         if user.username in superusers:
#             user.is_superuser=True
        #dsm.authenticate = true
        user.save()
        print("successfully saved the user")
        return user

*project(mysite)  urls.py

"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include,path
from django.urls import re_path
from django.conf.urls import url
from django.contrib.auth import views as auth_views

from dsmdata.forms import LoginForm
from dsmdata.pmauth import pmauth

urlpatterns = [
    #path('polls/', include('polls.urls')),
    path('polls/', include('django.contrib.auth.urls')),
    path('admin/', admin.site.urls),
    re_path(r'', include('dsmdata.urls')),
    url(r'^login/$', auth_views.LoginView.as_view() , {'template_name': 'login.html', 'authentication_form': LoginForm}, name="login" ),
    #url(r'^login/$', pmauth , {'template_name': 'login.html', 'authentication_form': LoginForm}, name="login" ),
    url(r'^logout/$', auth_views.LogoutView.as_view(), {'next_page': '/login'}),
    #re_path(r'^dsm/',include('django.contrib.auth.urls')),
    #re_path(r'^dsm/login', include('dsm.urls')),
]

*dsmdata application views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required

from pip._vendor.requests.api import request

# Create your views here.
# this login required decorator is to not allow to any
# view without authenticating

@login_required(login_url="login/")
def home(request):

    return render(request,"home.html", testdict)

# Create your views here.


text:
Q: Dynamic definition of active tab I have 3 tabs. In some cases the first one is hidden.
The first one is the active one. If it's hidden, the 2nd one should be active.
.html code:

.js Code:
this.isvis = ko.computed(function () {
            return this.Type() === 'xxxx';
        }.bind(this));

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to auto click on a radio button if a determined image is loaded on screen? There's two radio buttons on the page, one for "Yes" and another one for "No". I have no experience with jQuery, javascript or html, but I need to create some script/code to auto click on one of those buttons according with the image src that is loaded on the page.
So, if the image src on the page is "a.jpg", it will auto click always on the "Yes" radio button, and if it's "b.jpg" will always click on the "No" radio button.

A: First, write a conditional for what you want to check based on img src
Then to check it: $('input').attr('checked', true)
If you need more help post the HTML/JS that you have so far

You could do something like this using jQuery:
var imageSrc = $('img').attr('src');
if(imageSrc === 'http://localhost/mysite/a.jpg'){
  $('.true').attr('checked', true);
}else{
  $('.false').attr('checked', true);
}

Note you would have to set the class name of the inputs as well.

<input type="radio" class="form-check-input true" value="true">Yes

<input type="radio" class="form-check-input false" value="false">No

A: You can do this with jquery too
$('img[src="YourImgSrc"]').on('load',function(){
     $('#YourRadioId').prop("checked",true);
});


text:
Q: Memory leaks using JNI: are we releasing objects property? IMPORTANT NOTE: This snippet of code is not a native function called from Java. Our process is written in C++, we instantiate a Java VM, and we call Java functions from C++, but never the other way around: Java methods never calls native functions, but native functions instantiate Java objects and call Java functions on them.
We are doing something like this:
void some_fun()
{
    // env is a JNIEnv*, cls (and cls2) a jclass, and init (and mid) a jmethodID
    jobject obj = env->NewObject(cls, init);
    fill_obj(obj, cpp_data);
    env->callStaticVoidMethod(cls2, mid, obj);
    // env->DeleteLocalRef(obj); // Added out of desperation.
}

Where fill_obj depends on the kind of cpp_data that must be set as fields of obj. For example, if the Java class cls contains an ArrayList, cpp_data will contain, for example, a std::vector. So the fill_obj overload will look like this:
void fill_obj(jobject obj, SomeType const& cpp_data)
{
   std::vector<SomeSubType> const& v = cpp_data.inner_data;
   jobject list_obj = env->NewObject(array_list_class_global_ref, its_init_method);

   for (auto it = v.begin(); it != v.end(); ++it) {
      jobject child_obj = env->NewObject(SomeSubType_class_global_ref, its_init_method);
      fill_obj(child_obj , *it);
      env->CallBooleanMethod(list_obj, add_method, child_obj);
   }

   env->SetObjectField(obj, field_id, list_obj);
}

According to our understanding on the JNI docs, that code should not have any memory leaks since local objects are destroyed when the native method ends. So, when the first fill_obj ends, at C++ side there's no more references to list_obj or any of its childs, and when some_fun ends, any reference of obj at C++ side is gone as well.
My understanding is that jobject contains some sort of reference counter and when that reference counter reachs 0, then there's no more references to the Java object at C++ side. If there's no more references to the object at Java side either, then the Java's garbage collector is free to release the resources occupied by the object.
We have a method that, when called, creates thousand of those objects, and each time that method is called, the memory that the process occupies in RAM (the resident memory) grows by more than 200 MiB, and that memory is never released.
We have added an explicit call to DeleteLocalRef but the result is the same.
What is going on? Are we doing something wrong?

A: Since you say your some_fun() function is not being called by Java code, it is just pure C++ code that is internally calling into JNI, then yes, you will need to call DeleteLocalRef() on any local references you hold to Java objects that you don't pass back to Java.  You will need to do this inside of your for loop as well.
Try this:
void some_fun()
{
    // env is a JNIEnv*, cls (and cls2) a jclass, and init (and mid) a jmethodID
    jobject obj = env->NewObject(cls, init); // <-- local ref created
    fill_obj(obj, cpp_data);
    env->callStaticVoidMethod(cls2, mid, obj);
    env->DeleteLocalRef(obj); // <-- local ref released
}

void fill_obj(jobject obj, SomeType const& cpp_data)
{
   std::vector<SomeSubType> const& v = cpp_data.inner_data;

   jobject list_obj = env->NewObject(array_list_class_global_ref, its_init_method); // <-- local ref created

   for (auto it = v.begin(); it != v.end(); ++it) {
      jobject child_obj = env->NewObject(SomeSubType_class_global_ref, its_init_method); // <-- local ref created
      fill_obj(child_obj, *it);
      env->CallBooleanMethod(list_obj, add_method, child_obj);
      env->DeleteLocalRef(child_obj); // <-- local ref released
   }

   env->SetObjectField(obj, field_id, list_obj);
   env->DeleteLocalRef(list_obj); // <-- local ref released
}

Alternatively, you can use (Push|Pop)LocalFrame() instead, so that JNI can keep track of all the local references you create and then release them for you in one go, eg:
void some_fun()
{
    // env is a JNIEnv*, cls (and cls2) a jclass, and init (and mid) a jmethodID

    env->PushLocalFrame(1);

    jobject obj = env->NewObject(cls, init);
    fill_obj(obj, cpp_data);
    env->callStaticVoidMethod(cls2, mid, obj);

    env->PopLocalFrame(NULL);
}

void fill_obj(jobject obj, SomeType const& cpp_data)
{
   std::vector<SomeSubType> const& v = cpp_data.inner_data;

   env->PushLocalFrame(1+v.size());

   jobject list_obj = env->NewObject(array_list_class_global_ref, its_init_method);

   for (auto it = v.begin(); it != v.end(); ++it) {
      jobject child_obj = env->NewObject(SomeSubType_class_global_ref, its_init_method);
      fill_obj(child_obj, *it);
      env->CallBooleanMethod(list_obj, add_method, child_obj);
   }

   env->SetObjectField(obj, field_id, list_obj);

   env->PopLocalFrame(NULL);
}

A: Note the section Implementing Local References from the JNI specification:

To implement local references, the Java VM creates a registry for each transition of control from Java to a native method. A registry maps nonmovable local references to Java objects, and keeps the objects from being garbage collected. All Java objects passed to the native method (including those that are returned as the results of JNI function calls) are automatically added to the registry. The registry is deleted after the native method returns, allowing all of its entries to be garbage collected.

The term "after the native method returns" means the reversal of the "transition of control from Java to a native method", in other words, the method declared inside a Java class using the keyword native has been called and returns to the caller.
Once this is understood, it's also clear how to read the Global and Local References section

Local references are valid for the duration of a native method call, and are automatically freed after the native method returns.

So when you have code that runs for a long time before returning to the Java caller or has no Java caller at all, there is no way around deleting references manually using DeleteLocalRef.
As Remy Lebeau mentioned, you can also use PushLocalFrame and PopLocalFrame to perform bulk destruction of references created between two points.
Mind that the destruction of the reference does not imply the destruction of the referenced object, but just not to prevent the garbage collection of the object. So after calling env -> CallBooleanMethod(list_obj, add_method, child_obj);, you can destroy the child_obj reference, because the object is still referenced by the list you're referencing via list_obj, so the added object will be kept as long as it is still in use.


text:
Q: What's wrong with this mysql import? The dump file was created by phpMyAdmin. I'm having problems with importing it to my local MySQL server. Seems like this line is causing issues:
PRIMARY KEY (`arid`)

Dump file header
-- phpMyAdmin SQL Dump
-- version 4.0.8
-- Server version: 5.5.32-cll
-- PHP Version: 5.3.17

Local MySQL version
innodb_version: 1.1.8
protocol_version: 10
version: 5.5.17

Dump file reduced to bare minimum
CREATE TABLE IF NOT EXISTS `ar` (
    `arid` int(11) NOT NULL,
    PRIMARY KEY (`arid`)
) ENGINE=InnoDB;

Update
This is getting strange...

*

*This command works via MySQL prompt.
create table ar (arid int(11) not null);

*I delete the table.

*I put that same command (Ctrl+V) into the dump file. The dump file only has that command.

*Using DOS prompt, I navigate to the folder with the dump file and execute type file.sql. DOS prompt confirms that file only has the command from step 1.

*When I try to import it, I get "You have an error in your sql syntax"

A: The error is in your sql file. One of the SQL queries present in the admin_WebSiteAdmin.sql file has an error.

A: Can you tell us mysql version that you have on your host and mysql on your local machine?
Most likely than not, reason for this error is incompatibilities between versions.


text:
Q: Strict_types does not affect array_walk While working on the following code I noticed that declare(strict_types=1) has no effect on the arguments of a callback function through array_walk()
<?php
declare(strict_types=1);

function myCallBack(int $value, $key) {

    echo $value;
}

function myFunc(int $value, $key) {
    echo $value;
}

$myArr = array("eggs" => 4, "Butter" => 4, "meat" => 4.5);

echo 'myCallBack..';
array_walk($myArr, 'myCallBack'); // Output: 444

echo ' <br />myFunc..';
myFunc(4.2, 'eggs'); // Output:Fatal error: Uncaught TypeError: Argument 1 passed to myFunc() must be of the type integer

?>

I'm expecting php to throw an exception instead of 444 because [meat] value in $myArr is not integer!
apparently php ignores the fact that [meat] in $myArr is float for some reason! instead of throwing an exception just like what happened with myFunc().
Is this a normal php behavior or am I missing something?.


text:
Q: How to automate labeling of many plot labels with the par() function? I am using the par() function to create a 3 x 4 matrix of histograms. I successfully used the apply function to populate the matrix, but I am having trouble labeling all of the plots.
I have tried doing so using a for loop such as this:
par(mfrow = c(3,4))
features <- colnames(winequality.white)
for (name in features){
  truehist(winequality.white$name)
  mtext(name)
}

but it gives me the error:  Error in stats::var(x) : 'x' is NULL.
I prefer using the par function because it saves me the trouble of creating 12 separate graphical elements, but is there a way to automate the labeling of the plots?
Here is the code that I used to create the plots, as well as the graphical result:
#import/load data
winequality.white <- read.csv("/Users/me/Documents/winequality-white.csv", sep = ";")
#load library
library("MASS",lib.loc="/Library/Frameworks/R.framework/Versions/3.3/Resources/library")
#Examine Histograms of the Data
par(mfrow = c(3,4))
apply(winequality.white, 2 , truehist )

Lastly, here is the data, which you can load with
winequality.white <- read.table("https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv", sep=";", header=TRUE)


text:
Q: AttributeError: 'Group' object has no attribute 'rect' I am working on debugging my code. I have come across this error, and I dont know what I should be looking for. If anyone could treat me like a kid and explain it to me as if I was 3 years old, that would be great. Pretty lost on this.
pygame 2.1.2 (SDL 2.0.18, Python 3.10.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 221, in <module>
    ss.run_game()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 54, in run_game
    self._update_target()
  File "C:\Users\2\Desktop\python_work\Chapter 11 - 15\Chapter 14\14.2 Target Practice.py", line 163, in _update_target
    if pygame.sprite.spritecollideany(self.bullets, self.sideways_target):
  File "C:\Users\2\AppData\Roaming\Python\Python310\site-packages\pygame\sprite.py", line 1771, in spritecollideany
    default_sprite_collide_func = sprite.rect.colliderect
AttributeError: 'Group' object has no attribute 'rect'
[Finished in 2.4s]

A: You swapped the arguments pygame.sprite.spritecollideany detects the collision between a pygame.sprite.Sprite and the objects in a pygame.sprite.Group, but not the other way around:
if pygame.sprite.spritecollideany(self.bullets, self.sideways_target):
if pygame.sprite.spritecollideany(self.sideways_target, self.bullets):


text:
Q: The Poisson Process and different distributions Fix a strictly positive real number $\lambda$.
Suppose $S_1<S_2<S_3< \dots$ are the instances of a Poisson process having intensity $\lambda$. Fix a non-negative integer $n$ and define a sequence of random variables by $\epsilon_1,\epsilon_2, \dots , \epsilon_k , \dots$ by
$$\epsilon_k = \begin{cases}
  1 & \text{if there exists an r such that $S_r \in (\frac{k-1}{n}, \frac{k}{n})$} \\
  0 & \text{otherwise}.
\end{cases} $$
What is the distribution of $\epsilon_k$?
Fix some positive integer $n$. What is the distribution of $M=\sum_{k=1}^n \epsilon_k$?
Let $N$ be the number of instances of the Poisson process occurring before time $1$. What is the distribution of $N$?
Prove that $\mathbb{P}(M \neq N) \leq n(1-e^{- \lambda/n} - \frac{\lambda}{n}e^{- \lambda/n}) \leq \frac{\lambda^2}{n}$ if $n \geq \lambda$.
I think $\epsilon_k$ follows the Bernoulli distribution, $M$ follows the Binomial distribution, and $N$ follows the Geometric distribution. Am I correct for these pars?
Would anybody help me to prove the given inequality?
Thank you in advance.

A: Your formulation of the Poisson process is a bit different than what I normally see, so I will formulate it this way. Let $\{X(t):t\geqslant 0\}$ be a Poisson process with rate $\lambda>0$. Let $$S_n=\inf\{t:X(t)=n\}$$ be the arrival times. For a positive integer $n$, let $$\varepsilon_k=\begin{cases}1,& \text{if } X\left(\frac kn\right) - X\left(\frac{k-1}n\right)>0\\0,&\text{otherwise}.\end{cases}$$
You're correct in that $\varepsilon_k$ has a Bernoulli distribution, with success parameter
$$
\begin{align*}
p &= \mathbb P\left(X\left(\frac kn\right) - X\left(\frac{k-1}n\right)>0\right)\\ &= 1 - \mathbb P\left(X\left(\frac kn\right) - X\left(\frac{k-1}n\right)=0\right)\\
&= 1 - \exp\left(-\lambda\left(\frac kn - \frac{k-1}n\right) \right)\\
&= 1 - \exp\left(\frac{-\lambda}n\right).
\end{align*}
 $$
From the independent increments property of the Poisson process, we have that the $\varepsilon_k$ are iid, so$$M=\sum_{k=1}^n\varepsilon_k\sim\operatorname{Bin}\left(n,1-\exp\left(\frac{-\lambda}n\right)\right).$$
$N$ is just $X(1)$, so it has a $\operatorname{Pois}(\lambda)$ distribution.
As for $\mathbb P(M\ne N)$, this is the probability that at least one subinterval $\left(\frac{k-1}n,\frac kn\right)$ has more than one arrival, i.e.
$$\{M\ne N\}=\bigcup_{k=1}^n \left\{X\left(\frac{k-1}n\right) - X\left(\frac kn\right) \geqslant2\right\}, $$
and from the union bound we have
$$
\begin{align*}
\mathbb P(M\ne N)
&=\mathbb P\left(\bigcup_{k=1}^n\left\{X\left(\frac{k-1}n\right) - X\left(\frac kn\right) \geqslant2\right\} \right)\\
&\leqslant \sum_{k=1}^n\mathbb P\left(X\left(\frac{k-1}n\right) - X\left(\frac kn\right) \geqslant2\right)\\
&=n\mathbb P\left(X\left(\frac1n\right)\geqslant 2\right)\\
&=n\left(1-e^{-\frac\lambda n}-\frac\lambda n e^{-\frac\lambda n}\right).
\end{align*}
$$
From the inequality $1-x\leqslant e^{-x}$ we have
$$
\begin{align*}
1 - e^{-\frac\lambda n} - \frac\lambda n e^{-\frac\lambda n}&\leqslant
\frac\lambda n - \frac\lambda ne^{-\frac\lambda n}\\
&=\frac\lambda n\left(1-e^{-\frac\lambda n}\right)\\
&\leqslant \left(\frac\lambda n\right)^2,
\end{align*}
$$
and the desired inequality is attained by multiplying by $n$.


text:
Q: ssl and loadbalancing : answer directly from backend? Context
debian 64bits.
I try to learn https. I created a loadbalancer but I cannot answer tthe client directly from the backend since it receive the LB ip.
Question
I would like to know how I could achieve the following with ssl connection:
client -------> loadbalancer Level4 -----> 3 backends (ssl termination) -----> Back to client
The goal is to avoid decrypting on the loadbalancer but still be able to send the requests to each of the backend servers, decrypt there and send back to client directly.
Any way to make it happen ? I am learning and it is difficult to follow all the things happening in haproxy or tinyproxy. I need a visual help.

A: What you are asking for is called Direct Server Return. It is a feature available on some load balancers, but not all. I have not found any definitive answer as to whether HAProxy or tinyproxy supports DSR.
A couple of significant advantages of DSR are:

*

*You can do SSL on backends behind the LB and still know the IP of the client

*You can get better scalability because the LB only need to handle packets in one direction (usually the one with the least traffic).

A disadvantage of DSR is that you can no longer rely on standard IP routing for packets from the LB to the backend. This is due to the packets still having the VIP as destination address, and thus IP routing would route them to the LB.
Two approaches to get around this are the following:

*

*The LB bypass the ARP/ND layer when incoming packets are forwarded. Instead the LB fill in the destination MAC with the MAC of the selected backend. This approach only works if LB and backend are on the same segment.

*Use an IP tunnel between LB and backend. This approach works even if there is a router between LB and backend. When using this approach, one must take care to avoid MTU issues. Reducing MSS can avoid MTU issues, but the LB cannot do that due to DSR, so the backend need to be configured with lower MSS.


text:
Q: Show using the definition of convergence that the sequence 1/n does not converge to any number $L > 0$. Let $\epsilon > 0$
$|1/n - L| < \epsilon$ for some $n\geq N$. (definition of convergence)
This implies $-\epsilon\cdot n < 1 - nL < \epsilon\cdot n$
Therefore $1 - nL > -\epsilon\cdot n$
Therefore $1 < n(\epsilon - L)$
Choose $\epsilon = 1/n$
Therefore $nL < 2$
Therefore $L < 2/n$ for all $n\geq N$
By Archimedean property, we know that this only holds when $L = 0$.
Hence the sequence converges to $0$, by uniqueness of convergence the sequence does not converge to any $L > 0$.
My issue with this proof is that when I choose $\epsilon = 1/n$, technically $\epsilon$ is changing for every choice of $N$. Is this still a valid proof?

A: Since you are attempting to prove, by the definition, that the sequence does not converge (to $L$, when $L\neq0$), you are supposed to fix a $\varepsilon>0$. But $\varepsilon$ should be a fixed number neverthelsss.
Take $\varepsilon=\frac{\lvert L\rvert}2$ and let $N\in\mathbb N$. You want to prove that there's a $n\geqslant N$ such that $\left\lvert\frac1n-L\right\rvert\geqslant\frac{|L|}2$. Just take $n$ large enough so that $n\geqslant N$ and also that $\frac1n<\frac{|L|}2$. Then\begin{align}\left|\frac1n-L\right|&\geqslant\left|\frac1n-|L|\right|\\&=|L|-\frac1n\\&>|L|-\frac{|L|}2\\&=\frac{|L|}2.\end{align}

A: $a_n=1/n>0$, decreasing, bounded below by $0$, hence convergent.
Since $a_n >0$, $\lim_{n \rightarrow \infty} a_n=L \ge 0$.
Assume $L>0$.
Let $\epsilon >0$.
There is a $n_0$, positive integer, s.t. for $n \ge n_0$
$|1/n-L| \lt \epsilon$, or
$-\epsilon < 1/n -L < \epsilon$
$-\epsilon +L < 1/n$.
Choose $\epsilon =L/2$ (for example),
then $L/2 <1/n$.
Archimedean principle:
There is a $n_1$, positive integer, s.t.
$n_1>2/L$.
For $n > m=: \max(n_0, n_1)$:
$L/2 > 1/m \ge 1/n$,
contradiction.
Hence $L=0$.


text:
Q: Converting a wave equation from three to two dimensions.
I've recently been set the following problem in a takeaway paper and I have one small problem with my result.
Using the Leibniz integral rule I found:
$$u_t=v(x,t,t)+\int^t_0v_t(x,t;s)ds, u_x=\int^t_0v_x(x,t;s)ds$$
then following from that I got:
$$u_{tt}=2v_t(x,t,t)+\int^t_0v_{tt}(x,t;s)ds, u_{xx}=\int^t_0v_{xx}(x,t;s)ds$$
This is of course incorrect as this leaves the correct boundary conditions for u however u$_{tt}$-u$_{xx}$=2f(x,t) not f(x,t)? Where in my explanation is wrong? I feel like what I found was correct however I don't know how I could have got one of these v$_t$s out of my equation for u$_{tt}$.


text:
Q: Error in public class I am attaching the code and the error message, I am not sure what's my mistake here.
BTW I saved the J.java file in the the same directory of javac.

A: Assuming your Java PATH variable is set correctly, you have to execute the javac command inside the folder containing the class you want to compile. BUT the Java artifact must not be in the same folder with the JDK. Move your classes somewhere outside and it will work.
If you don't want to set your PATH variable, just manually point to the javac in the command prompt:
C:\Users\USER>C:\Program Files\Java\jdk1.7.0_40\bin\javac J.class


text:
Q: Coq eapply generates a goal with a question mark while proving existence of a function I would like to prove that for every group there exists a minus function that takes an element of the group and returns its negative.
My Coq code is as follows:
Record Group:Type := {
G:Set;
plus: G->G->G;
O:G;
assoc: forall x y z:G, plus x (plus y z)=plus (plus x y) z;
neut: forall x:G, plus x O=x /\ plus O x=x;
neg: forall x:G, exists y:G, plus x y=O
}.

Lemma minus_exists(H:Group):exists minus_func:G H->G H, (forall x:G H, plus H x (minus_func(x))=O H).
eapply ex_intro.

The last tactic generates the following output:
  H : Group
  ============================
   forall x : G H, plus H x (?12 x) = O H

My first issue is the ?12 which I figure is probably a badly displayed character. What is the meaning of this and is there a way to make it readable.
My second question is how to complete the proof, which might become clearer after the first question is answered.

A: In my Coq version, I get instead:
forall x : G H, plus H x (?minus_func x) = O H

which is slightly better. In Coq, a term displayed of the form ?T is what we call a "meta" or an "existential variable" (evar).
The terminology comes from the field of logic programming and automated theorem proving, and it could be roughly interpreted as representing "an unknown term". Usually, evars play the role of variables in the unification process. The whole Coq proof engine is built around this notion of unknown or evar.
In your case, eapply ex_intro (or eexists) is missing the witness. Coq will create a new "evar" to stand for the missing function, and allows you to continue your proof. Note however that in order to complete the proof, you will need to provide a witness later on.
How are evars made into actual terms? The act of replacing an evar by an actual term is known as "instantiation". In many cases, instantiation will be performed by the unification algorithm. For instance, if we had a lemma:
Lemma f_plus x : plus H x (f x) = O H

we could do apply f_plus and ?minus_func would be replaced by f. Another  way is to use the instantiate tactic, but it is obsolete these days. In our previous case, you could then write instantiate (1 := f) and that would replace ?minus_func by f. Due to technical reasons this approach is not well supported anymore, thus in practice you are bound to either instantiating evars by unification or providing the actual witness to tactics.
I suggest you read a bit more about unification and logic programming.

A: ?12 is not a badly displayed character, it is a hole. The eapply tactics is a kind of "apply this lemma/hypothesis, but I don't have all the input at hand yet, so please insert holes instead, that I will fill later".
By entering eapply ex_intro (or eexists) you are just saying "There exists a function which I don't know yet, so please replace it by a hole, I will provide it later". However since the whole purpose of your lemma is to build this function, I'm not sure you are on the right path. Try proving your lemmas without any efoo tactics, you don't need them.


text:
Q: How to create a treeview with radio buttons in the [grand]child nodes? I am trying to create a treeview that looks something like the following:
Parent
|__Child1
|__ __ __ O Grandchild1
|__ __ __ O Grandchild2
|__Child2
|__ __ __ O Grandchild3
|__ __ __ O Grandchild4
I am using vb.net in Visual Studio 2008. Any insights as to how I can accomplish this will be very much appreciated!

A: You cannot have radio buttons in a TreeView, only checkboxes.
A solution would be to make the checkboxes behave like radio buttons:
Private Sub TreeView1_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCheck
    If e.Node.Checked Then
        If e.Node.Level = 2 Then
            For Each node As TreeNode In e.Node.Parent.Nodes
                If node IsNot e.Node Then
                    node.Checked = False
                End If
            Next
        Else
            e.Node.Checked = False
        End If
    End If
End Sub

The e.Node.Level = 2 check makes sure only grandchild nodes behave like radio buttons.
Set the TreeView's CheckBoxes property to True to enable checkboxes.
This is an example of how to change text style of selected nodes and its parents:
Private Sub TreeView1_BeforeSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeSelect
    If TreeView1.SelectedNode IsNot Nothing Then
        MakeSelected(TreeView1.SelectedNode, False)
    End If
    MakeSelected(e.Node, True)
End Sub

Private Sub MakeSelected(ByVal node As TreeNode, ByVal selected As Boolean)
    Dim SelectedFont As New Font(TreeView1.Font, FontStyle.Bold)
    node.NodeFont = IIf(selected, SelectedFont, TreeView1.Font)
    node.ForeColor = IIf(selected, Color.Blue, TreeView1.ForeColor)

    If node.Parent IsNot Nothing Then
        MakeSelected(node.Parent, selected)
    End If
End Sub

It recursively changes the text style of the selected node and its parents and sets it back to the TreeView's default style when the selection changes.

A:  Public Sub getAFCategories(selectedId As String)
        Dim cn As Data.SqlClient.SqlConnection
        cn = New Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings("ConnStr"))
        Try
            Dim MerchantSiteId As String = get_MerchantSiteID()
            Dim da As SqlDataAdapter
            Dim dt As New DataTable
            Dim cmd As New SqlCommand()
            cmd.Connection = cn
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "SELECT categoryId, Category, ParentId FROM tblCategories"
            cn.Open()
            da = New SqlDataAdapter(cmd)
            da.Fill(dt)
            TrViewAfCategories.Nodes.Clear()
            Me.PopulateTreeView2(dt, 0, Nothing, dt, selectedId)
        Catch ex As Exception
        Finally
            cn.Close()
        End Try

    End Sub

 Private Sub PopulateTreeView2(dtParent As DataTable, parentId As Integer, treeNode As TreeNode, dtMain As DataTable, selectedId As String)
        Dim redindex As Integer = 1
        For Each row As DataRow In dtParent.Rows
            Dim child As New TreeNode() With { _
             .Text = row("Category").ToString(), _
             .Value = row("AFCategoryId").ToString() _
            }
            If row("ParentId").ToString() = 0 Then
                TrViewAfCategories.Nodes.Add(child)
                redindex = parentId + redindex
                Dim dtChild As DataTable = Me.GetFilterData(dtMain, child.Value) 'Me.getData("SELECT AFCategoryId, Category, ParentId FROM tblAFFeedCategories WHERE ParentId = " + child.Value)
                PopulateTreeView2(dtChild, redindex, child, dtMain, selectedId)
            Else
                If parentId = 1 Then
                    child.ShowCheckBox = False
                    Dim dtChild As DataTable = Me.GetFilterData(dtMain, child.Value)
                    If dtChild.Rows.Count = 0 Then
                        If (selectedId = child.Text) Then
                            child.Text = "<input type='radio' name='rdoC" + row("AFCategoryId").ToString() + "' value ='" + row("Category").ToString() + "'  checked='checked'/>" + child.Text
                        Else
                            child.Text = "<input type='radio' name='rdoC" + row("AFCategoryId").ToString() + "' value ='" + row("Category").ToString() + "' />" + child.Text
                        End If
                    End If
                    treeNode.ChildNodes.Add(child)
                    'Me.getData("SELECT AFCategoryId, Category, ParentId FROM tblAFFeedCategories WHERE ParentId = " + child.Value)
                    PopulateTreeView2(dtChild, parentId, child, dtMain, selectedId)
                End If
            End If

        Next
    End Sub
 Private Function GetFilterData(parentData As DataTable, filterValue As String) As DataTable
        Dim dt As New DataTable()
        Dim dvFilter As New DataView
        dvFilter = parentData.DefaultView
        dvFilter.RowFilter = Nothing
        dvFilter.RowFilter = "ParentId = " & filterValue
        dt = dvFilter.ToTable()
        Return dt
    End Function


text:
Q: Changing the location on disk where XP Mode VHD file is stored Using Windows 7 x64, my boot disk is an SSD. I'd like to reserve it for Windows 7 programs, and locate the XP Mode VHD on a second standard HD.  Can that be done?  After creating XP Mode, can I shut it down, relocate it, and then edit the pathname node in "Windows XP Mode.vmc"?
<ide_controller id="0">
 <location id="0">
   <drive_type type="integer">1</drive_type>
 <pathname>
  <absolute type="string">**C:\Users\foo\AppData\Local\Microsoft\Windows Virtual PC\Virtual Machines\Windows XP Mode.vhd**</absolute>
<relative type="string">.\Windows XP Mode.vhd</relative>
</pathname>
<undo_pathname>
   <absolute type="string" />
    <relative type="string" />
</undo_pathname>
</location>

A:
After creating XP Mode, can I shut it down, relocate it, and then edit
  the pathname node in "Windows XP Mode.vmc"?

I'd say, just try it. If it doesn't work, revert the changes and create a symlink, that should always work.

A: By rule of thumb, the base VHD file located in Program Files cannot, unfortunately, be moved or renamed. If you do attempt to do this, XP Mode will cease functioning.
To move the files under the C drive to an alternate location you would first boot up in to XP Mode.
Instead of saving the virtual machine (VM), you want to shut it down. (Be sure to change the close settings to prompt the user for close action.)
When closing the VM you will want to choose shutdown. This will remove the .VSV file. Do not manually delete the .VSV file, as it contains unsaved data within the VM.
Now, you can move the VHD located in the following path: C:\Users\[yourusernamehere]\AppData\Local\Microsoft\Windows Virtual PC\Virtual Machines\Windows XP Mode.vhd to your desired location.
Open XP mode settings, navigate to Hard Disk 1 settings, and repoint the hard disk to the new location of your VHD file. You should now be able to boot the VM as you did previously.


text:
Q: Plotly: How to retrieve values for major ticks and gridlines? I'd like to retrieve the x-values highlighted in this plot:

The plot is generated in a Jupyter Notebook using this snippet:
import plotly
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import pandas as pd
import numpy as np

# setup
init_notebook_mode(connected=True)
np.random.seed(123)
cf.set_config_file(theme='pearl')

# Random data using cufflinks
df = cf.datagen.lines()

# plot
fig = df.iplot(asFigure=True, kind='scatter',xTitle='Dates',yTitle='Returns',title='Returns')
iplot(fig)

This is what I've tried:
With this setup, you can retrieve every x and y value for every series by simply running fig in the notebook. But the tick values are nowhere to be found.
I'v also tried digging deeper in dir(fig), and thought maybe the output from fig.axis would do the trick, but no:
{'x1': {'gridcolor': '#E1E5ED',
  'showgrid': True,
  'tickfont': {'color': '#4D5663'},
  'title': {'text': 'Dates', 'font': {'color': '#4D5663'}},
  'zerolinecolor': '#E1E5ED'},
 'y1': {'gridcolor': '#E1E5ED',
  'showgrid': True,
  'tickfont': {'color': '#4D5663'},
  'title': {'text': 'Returns', 'font': {'color': '#4D5663'}},
  'zerolinecolor': '#E1E5ED'}}

There are however other options for the grid and ticks there like 'showgrid': True, and 'tickfont', but the values seem to be "hidden" somewhere else.
Any suggestions?

A: This data is only available in the Javascript context, and so unfortunately is inaccessible from Python.


text:
Q: Creating a draggable image view I have been searching the net for a long time and I have not found a concrete way of making an image view draggable. Here is what I have so far:
tempViewController.h
#import <UIKit/UIKit.h>
#import "MyRect.h"
@class UIView;
@interface tempViewController : UIViewController

@property (nonatomic, strong) MyRect *rect1;
@end

tempViewController.m
#import "tempViewController.h"

@interface tempViewController ()

@end

@implementation tempViewController

@synthesize rect1 = _rect1;

- (void)viewDidLoad
{
    [super viewDidLoad];

    _rect1 = [[MyRect alloc]initWithFrame:CGRectMake(150.0, 100.0, 80, 80)];
    [_rect1 setImage:[UIImage imageNamed:@"cloud1.png"]];
    [_rect1 setUserInteractionEnabled:YES];
    [self.view addSubview:_rect1];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    if([touch view] == _rect1)
    {
        CGPoint pt = [[touches anyObject] locationInView:_rect1];
        NSLog(@"%@",NSStringFromCGPoint(pt));
        _rect1.center = pt;
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    if([touch view] == _rect1)
    {
        CGPoint pt = [[touches anyObject] locationInView:_rect1];
        NSLog(@"%@",NSStringFromCGPoint(pt));
        _rect1.center = pt;
    }
}

@end

MyRect right now is an empty UIImageView Class.
Dragging the image from a point such as [532,589] on micron moves it to a totally different part of the screen such as [144, 139]

A: Just attach a UIPanGestureRecognizer to your view.  In the recognizer's action, update your view's center based on the "translation" (offset) of the recognizer, then reset the recognizer's translation to zero.  Here's an example:
- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *draggableView = [[UIView alloc] initWithFrame:CGRectMake(150, 100, 80, 80)];
    draggableView.userInteractionEnabled = YES;
    draggableView.backgroundColor = [UIColor redColor];
    [self.view addSubview:draggableView];

    UIPanGestureRecognizer *panner = [[UIPanGestureRecognizer alloc]
        initWithTarget:self action:@selector(panWasRecognized:)];
    [draggableView addGestureRecognizer:panner];
}

- (void)panWasRecognized:(UIPanGestureRecognizer *)panner {
    UIView *draggedView = panner.view;
    CGPoint offset = [panner translationInView:draggedView.superview];
    CGPoint center = draggedView.center;
    draggedView.center = CGPointMake(center.x + offset.x, center.y + offset.y);

    // Reset translation to zero so on the next `panWasRecognized:` message, the
    // translation will just be the additional movement of the touch since now.
    [panner setTranslation:CGPointZero inView:draggedView.superview];
}

A: Don't use -touchesBegan:withEvent: etc.
What you want to use for such "high-level" things are UIGestureRecognizers.
You would add a pan gesture recognizer to your view set a delegate (possibly the view itself), and in the callback move the view by the distance the recognizer moved.
You either remember the initial position and move by the -translationInView each time, or simply move by the translation and then use -setTranslation:inView: to reset the recognizers translation to zero, so on the next call of the delegate method, you will again get the movement since the last call.


text:
Q: Running a Windows Batch Script to Startup Multiple Files I'm trying to replace the programs that run from my startup directory with a batch script.  The batch script will simply warn me that the programs are going to run and I can either continue running the script or stop it.
Here's the script as I have written so far:
@echo off
echo You are about to run startup programs!
pause

::load outlook
cmd /k "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" /recycle
::load Visual Studio 2008
call "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"

Both of these commands will load the first program and wait until I close it to load the second.  I want the script to load the processes simultaneously.  How do I accomplish this?
Edit:  When I use the start command it opens up a new shell with the string that I typed in as the title. The edited script looks like this:
start  "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE"
::load Visual Studio 2008
start "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"

A: This works:

@echo off
echo You are about to run startup programs!
pause

::load outlook
start /b "" "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE" /recycle
::load Visual Studio 2008
start /b "" "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"

A: Use START like this:
START "" "C:\Program Files\Microsoft Office\Office12\OUTLOOK.EXE"

When your path is enclosed in quotes, START interprets it as the title for the window. Adding the "" makes it see your path as the program to run.

A: There is the start command that will behave much like if you clicked the files in Explorer.


text:
Q: Does facebook video embed follow og:video redirect? I have a page with a video on it .. say (http://example.com/123) and it provides all the og: meta tags for facebook... so when I make a post on FB with that url, facebook would automagically embed that video into the post.   open graph tags such as these:
<meta property="og:title" content="My Title" />
<meta property="og:description" content="This is a description." />
<meta property="og:video" content="https://example.com/player.swf?id=123&autoplay=on&blah=12345&etc"/>
<meta... etc. etc>

This works great.  However, I have a bunch of parameters on that swf player that I don't want facebook embed code to cache.  For example, i might have the parameter
autoplay=on

but if hardcode that into the og:video string, all videos embedded has autoplay turned on by default and would be hard to change.  Hence I want to have a level of indirection like:
<meta property="og:video" content="https://example.com/redirswf/123" />

where /redirswf/123 would redirect to the original full player.swf url
I tried this but when I post the url to FB, the video just doesn't play.  I'm not sure how to debug this.. all I can think of is that FB is not following the 302 redirect when it tries to go to redirswf/123?  can anyone confirm or deny?
And I did confirm via the facebook debugger tool that it's pulling out the og:video field as expected:
{
    "url": "https:\/\/example.com\/redirswf\/123",
    "secure_url": "https:\/\/example.com\/redirswf\/123",
    "type": "application\/x-shockwave-flash",
    "width": 640,
    "height": 360
}

A: Bleh, it's by design I guess =(
https://developers.facebook.com/bugs/182548548598977


text:
Q: probability riddle 50 songs are played once each in a random order. Jack likes 44 of these songs. What is the minimum number of songs that will need to be played to ensure that there would be 3 consecutive songs that jack likes?

A: There are 6 songs that Jack don't like.  The worst outcome is that these songs appear as number $3,6,\dots,18$.  Thus, the minimum number of songs that must be played is 21.


text:
Q: Polygon Torque Map- problem changing polygons to points I'm trying to alter my data on cartodb map to get maritime emissions over about 20 years- by country. Hence trying get a torque map for polygons, and  by changing polygons to points based on a previous suggestion:
SELECT ST_Centroid(the_geom) the_geom, carto_date FROM maritime_emissions_my_data_trial_copy

But I keep getting a syntax error at SELECT.... the_geom appears to be properly valued - all rows state "Polygon".
My data is here: http://bit.ly/1M77NjG
I'm quite a novice.

A: Almost there! The difference is that CartoDB needs the geometry to be aliased as the_geom_webmercator. Also, make sure to use the (hidden) the_geom_webmercator to avoid having to project the_geom to web mercator. You should also include the primary key of the table (cartodb_id).
The following should work:
SELECT
    ST_Centroid(the_geom_webmercator) As the_geom_webmercator,
    carto_date,
    cartodb_id
FROM
  maritime_emissions_my_data_trial_copy

A: From the error message I would assume that there is an error in the SELECT statement which is independent of the data. Is the missing comma between ST_Centroid(the_geom) and the_geom a typo in the post?
Does
SELECT ST_Centroid(the_geom), the_geom, carto_date FROM maritime_emissions_my_data_trial_copy

instead of
SELECT ST_Centroid(the_geom) the_geom, carto_date FROM maritime_emissions_my_data_trial_copy

?
If not, please post the full error message.


text:
Q: Synapse notebook - reference to unpublished notebook I was trying to using %run to refer to an unpublished notebook, based on here https://learn.microsoft.com/en-us/azure/synapse-analytics/spark/apache-spark-development-using-notebooks#reference-unpublished-notebook, this feature seems been disabled by default, does anyone know how to enable it? Many thanks.
Regards,
Alex

A: This feature is not released yet. Expecting this feature to get release in MARCH end or APRIL early weeks.
This feature only works when running notebook on UX interactively. In pipeline you still need to publish it. You can find an option in notebook properties to enable this. Please refer to the image below:


text:
Q: Golang: Parsing two array of arrays in JSON, using the same struct Assume I have this data:
{
"code": 10000,
"msg": "Successful request processing",
"asks": [
    [
        "0.03434400",
        "0.31100000"
    ],
    [
        "0.03436300",
        "0.18900000"
    ],
    [

],
"bids": [
    [
        "0.03427400",
        "0.21100000"
    ],...

Thanks to the Go to JSON converter, I know it can be parsed like this (working, in my script):
type AutoGenerated struct {
Code int        `json:"code"`
Msg  string     `json:"msg"`
Asks [][]string `json:"asks"`
Bids [][]string `json:"bids"`
}

I'd rather parse it like this:
type Box struct {
Number int `json:"code"`
Message string `json:"msg"`
Asks []MarketData `json:"asks"`
Bids []MarketData  `json:"bids"`
}

type MarketData struct {
Sell []string
}

Or, even better, this (assuming Box struct stays the same):
type MarketData struct {
SellPrice string
SellQuantity string
}

The problem is that if I try to print the above using   price :=response.Asks[0].SellPrice, or using the previous example, response.Asks[0].Sell, I get an empty struct.
Why doesn't this work? It seems like legitimate go, to me. It builds fine, but whenever I try to run it, it prints empty braces.

A: package main

import (
    "encoding/json"
    "fmt"
)

var j = `{
    "code": 10000,
    "msg": "Successful request processing",
    "asks": [
        [
            "0.03434400",
            "0.31100000"
        ],
        [
            "0.03436300",
            "0.18900000"
        ]

    ],
    "bids": [
        [
            "0.03427400",
            "0.21100000"
        ]
        ]
    }
        `

type Box struct {
    Number  int          `json:"code"`
    Message string       `json:"msg"`
    Asks    []MarketData `json:"asks"`
    Bids    []MarketData `json:"bids"`
}

type MarketData struct {
    SellPrice    string
    SellQuantity string
}

func (md *MarketData) UnmarshalJSON(d []byte) error {
    val := []string{}
    err := json.Unmarshal(d, &val)
    if err != nil {
        return err
    }
    if len(val) != 2 {
        return fmt.Errorf("MarketData unmarshal error len != 2")
    }
    md.SellPrice = val[0]
    md.SellQuantity = val[1]
    return nil
}

func main() {
    ins := new(Box)
    err := json.Unmarshal([]byte(j), ins)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", ins)
}

https://play.golang.org/p/EKH3ICJJuZ_W

A: You are changing the structure of the data, of course it will not parse the same way.
You can probably do it like this:
type MarketDataInput []string

This doesn't give you useful field names.
If you can't change the structure of the input data, you can probably do this instead:
func (m MarketData) SellPrice() string {
    return m[0]
}

func (m MarketData) SellQuantity() string {
    return m[1]
}

But overall this just seems like a bad way of handling the data. You should probably transform it to a different data structure after you parse it to json.
type MarketDataInput []string

type MarketData struct {
    SellPrice float64
    SellQuantity float64
}

func MarketDataFromInputs(inputs []MarketDataInput) []MarketData {
    var output = make([]MarketData, 0, len(inputs))
    for _, input := range inputs {
        var item MarketData
        item.SellPrice, _ = strconv.ParseFloat(input[0], 64)
        item.SellQuantity, _ = strconv.ParseFloat(input[1], 64)
        output = append(output, item)
    }
    return output
}

Now you have the data in a more useful structure that you can process better.


text:
Q: Unable to download file: Could not find acceptable representation This has tons of example on the internet but for some reason I just cannot download a csv file. I keep getting the error:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation`.

Here is the code below for my @RestController:
      @GetMapping(value = "/tasks/{taskId}/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
      public ResponseEntity<InputStreamResource> download(@PathVariable String taskId, @RequestParam String format) throws IOException {

        var path = "string path to file"

        var file = new UrlResource(Path.of(path).normalize().toUri());
        return ResponseEntity
            .ok()
            .contentLength(file.contentLength())
            .contentType(
                MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(file.getInputStream()));
      }

I set the header Accept: application/octet-stream but still get the same error. What could be wrong any ideas?


text:
Q: Calculating value tag DICOM I have a set of 20 DICOM images, and I need to show the average of Window and Center of these 20 images.
Using pydicom I get the value of these tags, where the value of the 20 images are equal, WindowWidth = ['56', '3200'] and WindowCenter = ['29', '700'].
How can I calculate this average value to Window and Center?
My simplified code, if it helps:
from dicom import read_file

ds = read_file("01.dcm")

print ds.WindowWidth # = ['56', '3200']
print ds.WindowCenter # = ['29', '700']

A: Some images [CT in particular] have multiple window levels specified to highlight different features. If your values are all the same between the 20 images, then choose one of the two sets (ideally, let the user choose them). Check attribute (0028,1055), Window Width and Center Explanation, to see if there is information there.


text:
Q: behaviour of reduce function in python I am confused by the behavior of the reduce function.

*

*In the first example, I get the expected result: (1-1/2) * (1-1/3) = 1/3
>>> reduce(lambda x, y: (1 - 1.0/x) * (1 - 1.0/y), [2,3])
0.33333333333333337

*In the second example, I do not get the expected result:  (1-1/2) * (1-1/3) * (1-1/5) = 0.2666666
>>> reduce(lambda x, y: (1 - 1.0/x) * (1 - 1.0/y), [2,3,5])
-1.5999999999999996

Can someone please explain me what I am missing?

A: EDIT: I approve map/reduce answer above.
To understand why, read this:

https://docs.python.org/2/library/functions.html#reduce

Reduce recursively calls your function on each element of your list with 2 arguments: an accumulator (value of last call) and current element.
So you get:
(1 - 1.0/( (1 - 1.0/2) * (1 - 1.0/3) )) * (1 - 1.0/5)

With:
reduce(lambda acc, x: (1 - 1.0/acc) * (1 - 1.0/x), [2,3,5])
>>-1.5999999999999996

A: To add to why you get -1.5999999999999996 as your result and for completeness we can compute it using https://docs.python.org/2/library/functions.html#reduce as our guide:
The first iteration will be (which takes our first 2 iterator values of 2 and 3 as x and y):
(1 - 1.0 / 2) * (1 - 1.0 / 3)
which becomes:
0.5 * 0.6666666666666667
which yields:
0.33333333333333337.
We then use 0.33333333333333337 to move on to our next iteration which takes this result as x and our next iteration number of 5 as y:
Therefore, our second iteration will be:
(1 - 1.0 / 0.33333333333333337) * (1 - 1.0/5)
which becomes:
-1.9999999999999996 * 0.8
which yields:
-1.5999999999999996

A: What you need is a map and reduce:
>>> from functools import reduce
>>> yourlist = [2, 3]
>>> reduce(lambda x, y: x*y, map(lambda x: (1-1/x), yourlist))
0.33333333333333337

>>> yourlist = [2, 3, 5]
>>> reduce(lambda x, y: x*y, map(lambda x: (1-1/x), yourlist))
0.2666666666666667

Because map converts each item to the (1-1/item) and then the reduce multiplies all of them.
Additional remarks:
Instead of the lambda x, y: x * y you could also use the faster operator.mul, for example:
>>> import operator
>>> yourlist = [2, 3, 5]
>>> reduce(operator.mul, map(lambda x: (1-1/x), yourlist))
0.2666666666666667

Thanks @acushner for pointing this out (in the comments).
What went wrong in your function
In this case it's actually quite easy to see what doesn't work, just use a named function and add some prints:
def myfunc(x, y):
    print('x = {}'.format(x))
    print('y = {}'.format(y))
    res = (1 - 1.0/x) * (1 - 1.0/y)
    print('res = {}'.format(res))
    return res

reduce(myfunc, [2, 3])
# x = 2
# y = 3
# res = 0.33333333333333337

reduce(myfunc, [2, 3, 5])
# x = 2
# y = 3
# res = 0.33333333333333337
# x = 0.33333333333333337
# y = 5
# res = -1.5999999999999996

So it uses the last result as "next" x value. That's why it worked for the length-2-list case but for more elements it simply doesn't apply the formula you want.
Alternative
Instead of using map and reduce you could also use a simple for-loop. It's much easier to get them right and most of the times they are more readable (and in some cases it's faster than reduce).
prod = 1
for item in yourlist:
    prod *= 1 - 1 / item
print(prod)

Yes, instead of 1 line it's now 4 lines long but it's easy to understand what is happening (but there might be some edge cases in which that doesn't behave like reduce, for example for empty inputs).
But I generally prefer simple loops over complicated reduce-operations but as always YMMV. :)

A: In your second example you have 3 inputs. You need:
reduce(lambda x, y: (1 - 1.0/x) * (1 - 1.0/y)* (1 - 1.0/z),...


text:
Q: Load Word file and fill it from the DataGridView and export it I have a Word document with a header and I need to export the data from the DataGridView to this Word document.
Then I need to create an button to load the Word file and fill it with the data in the DataGridView.

A: The best option for manipulating Office Documents from C# is using the OpenXml SDK and then open the word document using Process.Start. Use a class linked to your button to:

*

*Create a word doc (in code)

*Write out your table

*Save the word doc to disk

*Open the word doc Using Process.Start

Something like this:
using System.Diagnostics;
...
...
...
Process.Start(@"D:\Path\To\My\Word.docx");


text:
Q: Using the SLLN to show that the Sample Mean of Arrivals tends to the Arrival Rate for a simple Poisson Process Let $N_t = N([0,t])$ denote a Poisson process with rate $\lambda = 1$ on the interval $[0,1]$.
I am wondering how I can use the Law of Large Numbers to formally argue that:
$$\frac{N_t}{t} \rightarrow \lambda \quad  \text{  a.s.} $$
As it stands, I can almost prove the required result but I have to to assume that $t \in Z_+$. With this assumption, I can define Poisson random variables on intervals of size $1$ as follows
$$N_i = N([i-1,i])$$
where
$$\mathbb{E}[N([i-1,i])] = \text{Var}[N([i-1,i])] = 1$$
and
$$N_t = N([0,t]) = \sum_{i=1}^t N([i-1,i]) = \sum_{i=1}^t N_i$$
Accordingly, we can use the Law of Large Numbers to state the result above...
Given that $t \in \mathbb{R}_+$, this proof needs to be tweaked in some way... But I'm not exactly sure how to do it.
Intuitively speaking, I believe that the correct approach would be to decompose $N[0,t]$ into $N[0,\lfloor t\rfloor]$ and $N[\lfloor t\rfloor, t]$, and argue that the latter term $\rightarrow 0$ almost surely.
However, I'm not sure how to formally state this.

A: If $n\leqslant t\lt n+1$, then $N_n\leqslant N_t\leqslant N_{n+1}$ hence
$$
\frac{n}t\cdot\frac{N_{n}}{n}\leqslant\frac{N_t}t\leqslant\frac{n+1}t\cdot\frac{N_{n+1}}{n+1}.
$$
When $t\to\infty$, $\frac{n}t\to1$ and $\frac{n+1}t\to1$ because $n$ is the integer part of $n$ hence $t-1\lt n\leqslant t$. Furthermore, $\frac{N_n}n\to\lambda$ (the result you showed) because $n\to\infty$, and  $\frac{N_{n+1}}{n+1}\to\lambda$ for the same reason. You are done.


text:
Q: Will Linux servers running MONGODB be affected by plans to add a leap second in 2016? I have read that there are plans to add a leap second in December 2016.
At work we are running a number of mongodb servers with ntpd installed to keep the time in sync and correct across them.
Does anybody know how this time change will affect us, i.e. whether or not we need to do anything other than ensure the normal operation of mongodb?
I can find no information on the sites for mongodb
For context:
red hat enterprise linux 6.6
mongodb3.2.3

A: You can operate normally as your Red Hat relies on NTP:
From MongoDB and Leap Seconds:

Remember, MongoDB relies on host operating system capabilities for reading the wall clock time, and for synchronizing events with wall clock time. As such, you should ensure that the operating system running under MongoDB is itself prepared for leap seconds.

From Resolve Leap Second Issues in Red Hat Enterprise Linux:

Systems running any version of Red Hat Enterprise Linux should automatically account for leap second corrections if they are using the NTP (Network Time Protocol) daemon to synchronize their local timekeeping with an NTP server. During the last day before a leap second correction, NTP servers should notify their clients that a leap second will occur, and at 23:59:59 UTC, the Linux kernel should add or remove an extra second by making the 60th second occur twice or removing it entirely.


text:
Q: How to avoid downloading glove-wiki-gigaword-300 or any other word vector package everytime? My use case : I get input (a sentence) from the user and need to find similar sentences from my repository file. I will be giving back three best matching sentences to the user.
As of now, I have coded rule based logics in python and it is working fine for lexical matches.
I am trying to improve the logic with semantic matching, soft cosine in specific.
I am planning to use the code which will look like : https://stackoverflow.com/a/65813988/11049287
My question is should I have to execute the below download statement
api.load('glove-wiki-gigaword-300'))

everytime I execute the code or any other work-arounds?
Is it possible to save the file?


text:
Q: Unable to make my script stop printing wrong result I've created a script in vba using IE to fill in few inputs in a webpage in order to reach a new page to check for some items availability based on inputting some values in an inputbox.
To walk you through: what the script is currently doing:

*

*Select Buy Bricks from landing page

*Enter age 30 and country United Kingdom and then click on submit button

*On the next page, enter the unique identification number for the Lego piece in the Element/design number box to populate result.

My script can satisfy all the requirements stated above. However, when I try with three different numbers, as in 4219725,765467 and 230223 I can see that the one in the middle 765467 doesn't populate any result but It prints the result of it's earlier number.

All the three numbers have been used in a for loop within my script below.
How can I make my script print nothing when there is no result instead of printing wrong result?
Site address
My script so far: (could not kick out hardcoded delay)
Sub GetDetails()
    Const timeOut = 10
    Dim IE As New InternetExplorer, Html As HTMLDocument
    Dim elem As Object, post As Object, inputNum As Variant
    Dim ageInput As Object, itm As Object, T As Date

    With IE
        .Visible = True
        .navigate "https://www.lego.com/en-gb/service/replacementparts"
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set Html = .document
        Dim event_onChange As Object
        Set event_onChange = .document.createEvent("HTMLEvents")
        event_onChange.initEvent "change", True, False

        Html.querySelectorAll(".arrow-list-info")(2).Click

        Do: Set ageInput = Html.querySelector("input[id*='How old']"): DoEvents: Loop While ageInput Is Nothing
        ageInput.innerText = 30
        Html.querySelector("[label='United Kingdom").Selected = True
        Html.querySelector("select").dispatchEvent event_onChange
        Html.querySelector("[ng-click='startFlow()'").Click

        While .Busy Or .readyState < 4: DoEvents: Wend
        Set Html = .document

        For Each inputNum In [{4219725,765467,230223}]
            T = Timer
            Do: Set post = Html.querySelector("[placeholder='Element/design number']"): DoEvents: Loop While post Is Nothing
            post.ScrollIntoView
            post.Focus
            post.innerText = inputNum
            Html.querySelector("button[ng-click='searchItemNumber()']").Click

            'Can't kick out this hardcoded delay
            Application.Wait Now + TimeValue("00:00:02")

            Do
                Set elem = Html.querySelector("div.list-item")
                If Timer - T > timeOut Then Exit Do
                DoEvents
            Loop While elem Is Nothing

            Set itm = Html.querySelector("h6.title")
            If Not itm Is Nothing Then
                Debug.Print itm.innerText
            Else:
                Debug.Print "Found Nothing"
            End If
        Next inputNum
        Stop
    End With
End Sub

A: So this needs tidying up but does it. I got rid of the explicit wait and added a wait for the spinner to disappear. For the no results section I look for an additional element to be present in the html when not found.
Option Explicit
Public Sub GetDetails()
    Const timeOut = 10
    Dim ie As New InternetExplorer, html As HTMLDocument
    Dim elem As Object, post As Object, inputNum As Variant
    Dim ageInput As Object, itm As Object, t As Date

    With ie
        .Visible = True
        .navigate "https://www.lego.com/en-gb/service/replacementparts"

        While .Busy Or .readyState < 4: DoEvents: Wend

        Set html = .document

        Dim event_onChange As Object
        Set event_onChange = .document.createEvent("HTMLEvents")
        event_onChange.initEvent "change", True, False

        html.querySelectorAll(".arrow-list-info")(2).Click

        Do: Set ageInput = html.querySelector("input[id*='How old']"): DoEvents: Loop While ageInput Is Nothing

        ageInput.innerText = 30
        html.querySelector("[label='United Kingdom']").Selected = True
        html.querySelector("select").dispatchEvent event_onChange
        html.querySelector("[ng-click='startFlow()']").Click

        While .Busy Or .readyState < 4: DoEvents: Wend

        For Each inputNum In [{4219725,765467,230223}]

                Do: Set post = .document.querySelector("[placeholder='Element/design number']"): DoEvents: Loop While post Is Nothing

                post.Focus
                post.innerText = inputNum
                html.querySelector("button[ng-click='searchItemNumber()']").Click

                Do
                Loop While .document.querySelectorAll(".basic-search-btn .icon-spinner-arrows").Length > 0

            t = Timer
            Do
                Set elem = html.querySelector("div.list-item")
                If Timer - t > timeOut Then Exit Do
                DoEvents
            Loop While elem Is Nothing

            Set elem = Nothing
            Set itm = html.querySelector("h6.title")

            If html.querySelectorAll(".alert.alert-info.margin-top.ng-hide").Length = 1 Then
                Debug.Print "Found nothing"
            Else
                Debug.Print itm.innerText
            End If
            Set itm = Nothing
        Next inputNum
        ie.Quit
    End With
End Sub


text:
Q: Stackdriver Logs Don't Show Up on Console I've been using the Stackdriver Client API to write logs for Google Compute Engine. When I run gcloud logging logs list, I see my logs directory, but they don't show up on the logs interface: https://console.cloud.google.com/logs/viewer.
How do I get this to show up on the interface?


text:
Q: Importing Access DB file in SAS but failing I am trying to run below code but failing with error 'ERROR: DBMS type ACCESS not valid for import.' Not sure what is the issue.
LIBNAME db 'C:\Extra';
PROC IMPORT DBMS=ACCESS
            OUT=WORK.Finished_IP
            DATATABLE='IP Input Data'
            REPLACE;
            DATABASE= "db.Finished data.accdb";
   USEDATE=YES;
   SCANTIME=NO;
   DBSASLABEL=NONE;
RUN;

A: If you have the "Microsoft Access Driver (*.mdb, *.accdb)" driver installed you can use this to create your libname directly to the database file like so:
libname Test ODBC noprompt="DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};
                            DBQ=C:\local\Your_DB.accdb";

You can see if you have the driver under the ODBC Data Source Administrator found in Administration Tools in the Control Panel.
Using this method means that tables in the database can be read in like normal SAS datasets.


text:
Q: Android : Branch SDK Api Error after changed date on device I try to apply branch.io link
After changed the date with device settings, for example, month before or after the current date; branch.io shows error: "Trouble initializing Branch. Branch API Error: poor network connectivity. Please try again later."
In the source code I see matching from "Trouble reaching server. Please try again in a few minutes" endpoint "v1/install"
If I return the correct date - everythink is ok
branch sdk version 4.3.2
How can I fix applying links with incorrect time?

A: Branch does not allow the device time to be changed.This is done to maintain accuracy of attribution. If you try to change the device time, it causes the app itself to experience a CertPathValidatorException when it try's to reach the Branch servers.


text:
Q: Ms Sql: import csv into msql database does not work I am using the following code to load the csv into the database:---
LOAD DATA LOCAL INFILE 'C:\Documents and Settings\vishu.singhvi\Desktop\5columns.csv'
INTO TABLE digite61new.copy_ENTERPRISEUSER FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY
'\n' IGNORE 1 LINES;
But its showing the error:--
Incorrect syntax near 'C:\Documents and Settings\vishu.singhvi\Desktop\5columns.csv'
Please help.

A: On SQL Server this syntax is not supported.
On MySQL I don't think it should give the error you see, but your filename is wrong.
LOAD DATA LOCAL INFILE 'C:\\Documents and Settings\\vishu.singhvi\\Desktop\\5columns.csv'

From the documentation:

Backslash is the MySQL escape character within strings in SQL statements, so to specify a literal backslash, you must specify two backslashes for the value to be interpreted as a single backslash


text:
Q: Replicate entity values with relationship values into another entity I have entity called user and I want to have exact copy of entity values into another entity called "history" or "cache" or as "order user" for record keeping, so incase user entity values changes, we will have copy of the user values and long list of fields with its sub entities in history.
Solution
I have tried this solution, but all my properties are private which is not working for this. because it requires public properties only (unless I'm wrong on this).
Symfony 2 - Clone entity to different table

A: I have solved the issue by making parent extended entity properties to be protected and following solution worked fine then.
Symfony 2 - Clone entity to different table
Entity copy
class OrderProduct extends Product {
}

// make sure product entity property values are protected and not private.

Solution 2
Solution by @JmilL and by @Gerben is also something to look into, if you want to keep complete history of all the changes.

https://github.com/simplethings/EntityAudit
https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/loggable.md


text:
Q: Bootstrap tabs - Next & previous Buttons I am using Bootstrap 3.4.
I am using tab-pills on a form with 3 tabs.
I am trying to place next & previous buttons to aid navigation between the tab form.
I have read this post on the topic (and the bootply), which is exactly what I require, and I applied the necessary code.
On my form, in all 3 tabs, I always see the next1 button, I never see the other buttons.
I finally figured out that the error is to do with the class=active on the
 line of code> (or at least I am almost certain this is the error).
I have searched Google and SO to figure out how to get the js code working, but I cannot figure out to correct this simple issue. I have exhausted all my attempts, so I turn to SO for assistance.
Can anyone suggest how I might correct this?
Here is my js code:
$('.btnNext').click(function(){
    $('.nav-pills > .active').next('li').find('a').trigger('click');
});

$('.btnPrevious').click(function(){
    $('.nav-pills > .active').prev('li').find('a').trigger('click');
});

Here is my HTML code:

             Tab #1

             Tab #2

             Tab #3

        Next1

        Next2
        Previous3

        Previous4

A:

                First Tab

                Second Tab

                Third Tab

            Test1

            Test2

            Test3

            <button class="btn" id="prevtab" type="button" data-toggle="tab">Prev</button>
            <button class="btn" id="nexttab" type="button" data-toggle="tab">Next</button>

  $(document).ready(function () {
        let tabs = $('.tabs-wrapper li');
        $('#prevtab').on('click', function () {
            console.log( tabs.find('.active').parent())
            tabs.find('.active').parent().prev('li').find('a[data-toggle="tab"]').tab('show');
        });
        $('#nexttab').on('click', function () {
            tabs.find('.active').parent().next('li').find('a[data-toggle="tab"]').tab('show');
        });
    })


text:
Q: why I can't stream an audio or video stored in dropbox? so in my Android app, I can use an exoplayer like this
lateinit var player : SimpleExoPlayer!

val mediaItem = MediaItem.fromUri("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")
player = SimpleExoPlayer.Builder(mContext).build()
player.setMediaItem(mediaItem)
playerView.player = player

I can stream the audio without any use if I use the code above.
but if I want to use an audio file that have in dropbox, the sound will never play, the code and link is like this
val mediaItem = MediaItem.fromUri("https://www.dropbox.com/s/lbe1kod9t6yuh5j/sample1.m4a")

how to solve this ?

A: replace www by dl from your link and add ?dl=1 to end
for example
https://dl.dropbox.com/s/lbe1kod9t6yuh5j/sample1.m4a?dl=1

try this. it's work for me.

A: Adding ?raw=1 to the end of the URL, worked for me.
Example:
https://www.dropbox.com/s/lbe1kod9t6yuh5j/sample1.m4a?raw=1


text:
Q: count many different values with mongoDB Here is a clear example of documents
{
    "_id" : ObjectId("56d8559b634049654854f621"),
    "nameFile" : "FDR-IA 444",
    "type" : "type",
    "branch" : "branch",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
},
{
    "_id" : ObjectId("56d8559b634049654854f622"),
    "nameFile" : "FDR-IA",
    "type" : "type",
    "branch" : "branch1",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
},
{
    "_id" : ObjectId("56d8559b634049654854f623"),
    "nameFile" : "FDR",
    "type" : "type1",
    "branch" : "branch2",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
},
{
    "_id" : ObjectId("56d8559b634049654854f624"),
    "nameFile" : "FDR -test",
    "type" : "type1",
    "branch" : "branch2",
    "service" : "service",
    "bin" : { "$binary" : 'binary code of the file'}
}

My mongoDB contains documents with this format and I want to count all the services, all the branchs for each service, all the types for each service, all the files for each service.
A file belongs to a unique type, a type belongs to a unique branch, and a branch belongs to a unique service: that's my conception.
To count each value, I know that I should make many mongo requests with callbacks, I want to optimize my code, I tried to use bulk but it doesn't have the count option.
For the given example: I want this result :
   name of service     numbBranchs    numbTypes     numbFiles
     'service'             3              2             4

A: db.getCollection('services').aggregate([
    {
        "$group": {
            "_id": "$service",
            "files": {
                "$sum": 1
            },
            "branches": {
                "$addToSet": "$branch"
            },
            "types": {
                "$addToSet": "$type"
            }
        }
    }, {
        "$project": {
            "name of service ": "$_id",
            "numbFiles": "$files",
            "numbBranches": {
                "$size": "$branches"
            },
            "numbTypes": {
                "$size": "$types"
            }
        }
    }

]);

MongoDB output:
{
    "waitedMS" : NumberLong(0),
    "result" : [
        {
            "_id" : "service",
            "name of service " : "service",
            "numbFiles" : 4,
            "numbBranchs" : 3,
            "numbTypes" : 2
        }
    ],
    "ok" : 1.0000000000000000
}


text:
Q: Xcode 7 develop for iOS without developer account I have updated my iPod to iOS 9 and want to make my own apps for it, however, I do not want to pay for a developer account because of how much it costs. I read that in Xcode 7 that you can develop apps for iOS without a developer account, this does not seem the case for me, instead when I try and build my test application (a blank single view application) I get an error saying 'no code signing identities found' and requires me to 'join a program'.
Is there a way I can develop applications without paying for a developers account (is there a 'free' option in the program options or not? Don't want to go through the steps and find out I was charged $99!)

A: please follow the below steps :-
Requirements: You must be running iOS 9 on your  devices (iPhone or iPad), latest Xcode 7  and you'll need a free developer account, which lets you "test on device".
Step 1: Launch your application which you want to run  on device.
Step 2: Connect your iOS device via USB.
Step 3: In the drop down device selection menu, select your device (not a simulator).
Step 4: Wait as Xcode 7 indexes and processes symbol files. This may take a while as well, so be patient. Once complete, the status will say Ready.
Step 5: Click the Play button (Run application). You'll likely get an error that says "failed to code sign". That's okay. Click Fix Issue and click Add to log in with your developer account. Remember, you don't need a paid developer account, but you will need a free developer account (Apple ID). If you don't have a developer account, create one by clicking Join a Program instead.
Step 6: Once you log in, click the Play button again to proceed with the compile. You may receive another error that says An App ID with Identifier…is not available. Please enter a different string. To fix this, click the General tab, and give the Bundle Identifier a unique name (delete the name between the two dots and add your own name. Leave the prefix and suffix as it is).
Step 7: Click the Play button once more. The compile should complete, and you'll see the app that you compiled appear on your iOS device's Home screen.
Step 8: You'll need to enable access to the app by trusting the developer on your iOS device. This can be done by going to Settings → General → Profile and tapping on the Developer app and granting access.
Step 9: Launch the app on your device Home screen, and iOS should allow you to use it.
Happy code signing :).
Note: you cannot test Push Notification and In-App purchase on Free Membership Account.

A: You can develop apps for your own iOS device be registering on https://developer.apple.com/resources/.

Enrollment to any specific developer programs is a separate steps which you don't have to do. Happy coding.

A: You don't need to pay for a Apple developer store certificate for personal use and there are waivers for what in the pas was paid-only features of the developer program as well.
Your personal AppleID is good enough to sign apps in Xcode and load them on a limited number of devices (5 or so) from your Mac to get started with developing. Once you need TestFlight or want to make a signed app that is reviewed - you need to pay or obtain a waiver, but please do get started for free.
Apple now waives the fee for accredited non profit and educational groups. This includes App Store distribution of free apps.

*

*https://developer.apple.com/support/membership-fee-waiver/
Here's how I would undo a previous paid AppleID - you might need Apple Developer support to help you release your AppleID from the paid program if you are reusing the same AppleID (and I encourage always reusing the same and not making new accounts when you run into a hiccup like this).
Instead, delete all Xcode copies you might have installed earlier - whether they are from the Mac App Store or downloaded and then install Xcode 7 from the Mac App store:

*

*https://itunes.apple.com/us/app/xcode/id497799835?mt=12
Once it downloads, run the app and go to the settings:

*

*click Accounts

*click the + in the lower left and add an Apple ID

*enter a personal Apple ID, the one you use for the App Store is fine to reuse

*you're done

When you build an app for iOS, connect the iOS device and choose that AppleID to sign the app when asked.

A: The solution that has been marked works. But instead of re-downloading it, you can remove temporary files that Xcode creates on first start. It can be done using apps like CleanMyMac.

*

*Select Xcode, then it will find relative files

*select all other than actual Xcode.app binary file

*Uninstall them

And you are ready to go with fresh install of Xcode

A: Update 2020/11/6 :

*

*You can develop on Xcode 7 on the Mac for iOS devices without having entered the developer program, billed 99€/$ per year. You will be able to test freely your program in simulated iOS devices and on a device connected to your Mac.

*You can build your app to execute on the iOS device you connected, once away from your Mac. However, by default, this is only temporary and will only last for 7 days. After that time, your application will not launch anymore on your device. You'll need to reconnect your device and rebuild it in Xcode. This is due to Apple generating a temporary profile for you allowing the iPhone to recognize the app. I've not been made aware of anyway to get around this default behavior, and from what I've been said it is not possible without jailbreaking your iPhone.

*As a consequence, you can develop an app freely though Xcode, but you can't really use it freely, even on your own device.


text:
Q: DNS domain name format for a valid DNS query I was told that in order for my DNS query to work, I have to convert the domain name.
 i.e. rit.edu -> rit3edu ; www.google.com to 3www6google3com
I cannot find where in the RFC https://www.ietf.org/rfc/rfc1035.txt that this is discussed, as I even tried performing a find. In my packets that I send to the DNS server. I keep the '.' domain name, and I am getting 'unknown extended label'. I cannot find any helpful threads either. I found a function on GitHub, but there is no discussion on the format. Does anyone have experience with this?
Thanks in advance

A: You may refer to this:
http://www.keyboardbanger.com/dns-message-format-name-compression/#Data_label
And in RFC1035 you attached:
4.1.2. Question section format

QNAME
    a domain name represented as a sequence of labels, where
    each label consists of a length octet followed by that
    number of octets.  The domain name terminates with the
    zero length octet for the null label of the root....

A: In a DNS query, each label of the domain name should be preceded by a number that indicates length of the label. So if facebook.com is the question, the actual qname in the DNS query should be 8facebook3com.


text:
Q: Trying to create an .MP4 from .TIF frames, syntax works on MacOS but not Windows 10 I currently use FFMPEG to create .GIFs from a set of .TIF frames and now my use case is making me need to instead make an .MP4 video from the same set of .TIF frames.
This syntax works just fine on my Mac:
ffmpeg -framerate 4 -i frame_%02d.tif out.mp4

But using ffmpeg.exe on Windows and passing the same arguments, I receive an error on the -framerate token.  Any ideas as to why?
Thanks in advance.
Randal Stout

A: What version of ffmpeg are you using? The command works for me (ffmpeg version 2021-03-28-git-8b2bde0494-essentials_build-www.gyan.dev). Type ffmpeg -version to see your version.
-framerate is an alias for -r (see docs), so try using -r instead.


text:
Q: How to generate a QR Code for an Android application? I need to create a qrcode in my android application, and I need a library or source code that lets me create a QR Code in an Android app.
The library I need must:

*

*not leave a watermark (like onbarcode library)

*not use web service API to create the qrcode (like Google's library zxing)

*not need 3rd party installers (like QR Droid)

I already created such code for iPhone (Objective-C) but I need a quick fix for Android until I have time to make a QR Code generator of my own. It's my first android project so any help will be appreciated.

A: Have you looked into ZXING?
I've been using it successfully to create barcodes.
You can see a full working example in the bitcoin application src
// this is a small sample use of the QRCodeEncoder class from zxing
try {
    // generate a 150x150 QR code
    Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);

    if(bm != null) {
        image_view.setImageBitmap(bm);
    }
} catch (WriterException e) { //eek }

A: Maybe this old topic but i found this library is very helpful and easy to use
QRGen
example for using it in android
 Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);

A: zxing does not (only) provide a web API; really, that is Google providing the API, from source code that was later open-sourced in the project.
As Rob says here you can use the Java source code for the QR code encoder to create a raw barcode and then render it as a Bitmap.
I can offer an easier way still. You can call Barcode Scanner by Intent to encode a barcode. You need just a few lines of code, and two classes from the project, under android-integration. The main one is IntentIntegrator. Just call shareText().

A: Here is my simple and working function to generate a Bitmap!
I Use ZXing1.3.jar only!
I've also set Correction Level to High!
PS: x and y are reversed, it's normal, because bitMatrix reverse x and y. This code works perfectly with a square image.
public static Bitmap generateQrCode(String myCodeText) throws WriterException {
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage

    QRCodeWriter qrCodeWriter = new QRCodeWriter();

    int size = 256;

    ByteMatrix bitMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
    int width = bitMatrix.width();
    Bitmap bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < width; y++) {
            bmp.setPixel(y, x, bitMatrix.get(x, y)==0 ? Color.BLACK : Color.WHITE);
        }
    }
    return bmp;
}

EDIT
It's faster to use bitmap.setPixels(...) with a pixel int array instead of bitmap.setPixel one by one:
        BitMatrix bitMatrix = writer.encode(inputValue, BarcodeFormat.QR_CODE, size, size);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
            }
        }

        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

A: I used zxing-1.3 jar and I had to make some changes implementing code from other answers, so I will leave my solution for others. I did the following:
1) find zxing-1.3.jar, download it and add in properties (add external jar).
2) in my activity layout add ImageView and name it (in my example it was tnsd_iv_qr).
3) include code in my activity to create qr image (in this example I was creating QR for bitcoin payments):
    QRCodeWriter writer = new QRCodeWriter();
    ImageView tnsd_iv_qr = (ImageView)findViewById(R.id.tnsd_iv_qr);
    try {
        ByteMatrix bitMatrix = writer.encode("bitcoin:"+btc_acc_adress+"?amount="+amountBTC, BarcodeFormat.QR_CODE, 512, 512);
        int width = 512;
        int height = 512;
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (bitMatrix.get(x, y)==0)
                    bmp.setPixel(x, y, Color.BLACK);
                else
                    bmp.setPixel(x, y, Color.WHITE);
            }
        }
        tnsd_iv_qr.setImageBitmap(bmp);
    } catch (WriterException e) {
        //Log.e("QR ERROR", ""+e);

    }

If someone is wondering, variable "btc_acc_adress" is a String (with BTC adress), amountBTC is a double, with, of course, transaction amount.

A: with zxing this is my code for create QR
 QRCodeWriter writer = new QRCodeWriter();
    try {
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 512, 512);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        ((ImageView) findViewById(R.id.img_result_qr)).setImageBitmap(bmp);

    } catch (WriterException e) {
        e.printStackTrace();
    }


text:
Q: Draw a vertical line I want to put an image (I will create) in my status bar app and this image should made of vertical line but I don't now how to draw them.

A: Found
let graphWidth: CGFloat = 22.0;
let graphHeight: CGFloat = 22.0
let size = NSMakeSize( graphWidth, graphHeight )
let image = NSImage(size: size)
image.lockFocus()

let path = NSBezierPath()
path.move(to: NSPoint(x: 20.0, y: 0))
path.line(to: NSPoint(x: 20.0, y: 20.0))
path.stroke()
image.unlockFocus()

statusItem.image = image


text:
Q: Perl - Run script remotely through SSH that includes a require directive Consider the following 2 scripts :
main.pl
#!/usr/bin/env perl

require 'lib.pl';
testSub('Hello World');

lib.pl
sub testSub
{
    my ($input) = @_;
    print $input, "\n";
}
1;

I need to run main.pl script remotely through SSH using sudo while including lib.pl as a dependency.
I know how to run a single Perl script through SSH using sudo :
$ ssh user@host 'sudo perl' < /path/to/local/perl/script

But, in this case, the following error is immediately raised :
Can't locate libs.pl in @INC (@INC contains: /usr/lib/perl5/5.10.0/x86_64-linux-thread-multi /usr/lib/perl5/5.10.0 /usr/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi /usr/lib/perl5/site_perl/5.10.0 /usr/lib/perl5/vendor_perl/5.10.0/x86_64-linux-thread-multi /usr/lib/perl5/vendor_perl/5.10.0 /usr/lib/perl5/vendor_perl .) at - line XX.

But how could I do the same while including another script as a dependency ?
Thanks all in advance.

A: Perl can only look at the local file system for includes and can not call back through a ssh channel to get data. So you either need to transfer the libs.pl to the other side before executing the program or just include its content directly in your program.
If you don't like to do this maybe Object::Remote can help you. But don't ask me how to use it, I've only heard a great talk about it.


text:
Q: Delete selected keys from Dart Map What is the Dart idiomatic way to remove selected keys from a Map?
Below I'm using a temporary emptyList to hold String keys.
Is there a cleaner way?
List<String> emptyList = new List<String>();
_objTable.keys.forEach((String name) {
  if (_objTable[name].indices.isEmpty) {
    emptyList.add(name);
    print("OBJ: deleting empty object=$name loaded from url=$url");
  }
});
emptyList.forEach((String name) => _objTable.remove(name));

A: Simply do:
_objTable.removeWhere((key, value) => key == "propertyName");

It works with nested Maps too.

A: You can do something like this :
_objTable.keys
  .where((k) => _objTable[k].indices.isEmpty) // filter keys
  .toList() // create a copy to avoid concurrent modifications
  .forEach(_objTable.remove); // remove selected keys


text:
Q: Integrate an Internal zoom on my products in my big cartel store I've followed another answer from a qustion with this problem Can I integrate an Internal zoom on my products in my big cartel store?
I have a Bigcartel webshop with the Luna Theme. I will like to integrate an internal zoom on my products images. But i can't get it to work.
I've added the jquery.elevatezoom.js file like this:

In the Layout file.
I've changed the code for the image in the Product page file to this:

And finally i've added the script code to activate, also in the Product file:

But it still doesn't work. Anybody who can tell me what i've done wrong? I'm getting really frustrated about it:-(
Thanx,
Paw

A: You can do this with Magic Zoom. Here is a Big Cartel website using it:
http://beetea.bigcartel.com/product/test-product-2
That site zooms the image to the side. Instead, you can use the internal zoom option to make the zoom happen within your main image.
Add Magic Zoom to the Layout file e.g.

Then add the product image code like so: