text:
Q: Node.js on Heroku? I wonder if all Heroku addons - that are currently working for Rails - will work for Node.js once the support is there?
And what is the ETA for the launch of Node.js support?

A: Node.js is now officially supported on Heroku.

A: Several addons currently require specific ruby gems to be installed so I think Node.js will have its own separate set of addons.
As for launch, to my knowledge there is no ETA yet.

A: Whether or not an addon will work with node is going to specific to the addon itself, probably whether the addon requires a Ruby lib to work.
I'm currently using Loggly, RedisToGo, Mongolab, and RabbitMQ via Addons all with node.

A: It is supported by CEDAR stack on heroku
All you have to do is put into .gitignore node_modules directory and create Procfile eg.
web: node web.js

This is just a command to startup your application.
Important thing is that you should layout your app as node_module i wrote a blog post about it
http://no-fucking-idea.com/blog/2012/04/23/building-node-dot-js-module-using-npm/
So you can look it up.
url explaining how to deploy is here:
https://devcenter.heroku.com/articles/nodejs
Have fun!


text:
Q: invalid dsn: invalid connection option "postgis_extension" On localhost everything is working fine. But I am having problems with https://rossdjangoapp.herokuapp.com/.

I tried to follow this tutorial https://medium.com/the-geospatials/deploy-geodjango-application-to-heroku-in-2019-part-3-41ca4535f377.
I got the below error messages.
remote: -----> App not compatible with buildpack: https://github.com/peterkeen/heroku-buildpack-

remote:  !     The GDAL, GEOS and PROJ binaries and BUILD_WITH_GEO_LIBRARIES functonality are now deprecated.
remote:  !     An alternative buildpack to enable GDAL, GEOS and PROJ use is available here - https://github.com/heroku/heroku-geo-buildpack

remote:        ### WARNING: THIS BUILDPACK HAS BEEN DEPRECATED
remote:        Please check https://git.io/fj5QW

These are the build packs I now have.

I want to add map functionality to my site.

settings.py
import os

if os.name == 'nt':
    import platform
    OSGEO4W = r"C:\OSGeo4W"
    if '64' in platform.architecture()[0]:
        OSGEO4W += "64"
    assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W
    os.environ['OSGEO4W_ROOT'] = OSGEO4W
    os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal"
    os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj"
    os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH']
    GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal300.dll'
import django_heroku

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = os.environ.get('SECRET_KEY')

DEBUG = True

ALLOWED_HOSTS = ['rossdjangoawesomeapp.herokuapp.com', 'localhost', '127.0.0.1', 'localhost:8000']

INSTALLED_APPS = [
    'blog.apps.BlogConfig',
    'users.apps.UsersConfig',
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    'django_comments',
    'shops',
    'django.contrib.gis'
]

SITE_ID = 1

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.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

ROOT_URLCONF = 'django_project3.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'django_project3.wsgi.application'

DATABASES = {

    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'Albertros577015',
        'HOST': 'localhost',
        'PORT': '5432'
    }

}

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',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = 'blog-home'
LOGIN_URL = 'login'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD =  os.environ.get('EMAIL_PASS')
EMAIL_PORT = 587

AUTHENTICATION_BACKENDS = (

    'django.contrib.auth.backends.ModelBackend',

    'allauth.account.auth_backends.AuthenticationBackend',
    )

CRISPY_TEMPLATE_PACK = 'bootstrap4'

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

django_heroku.settings(locals())

It is now working
I looked at Adems answer (Running PostGIS with Django on Heroku). And also had to go to https://data.heroku.com/, click on Settings and look at the Database credentials.

A: Remove all the external  import in the settings.py file,for example the heroku import and remove the django_heroku.settings(locals()) but only leave the AWS settings,then run again

redpajama_set_name: RedPajamaStackExchange


text:
Q: assigning value to a column by applying if statement with multiple conditions How can I fix this code where I'm trying to assign the values in a column according to the various conditions. Writing the below code gives me an error saying:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

list = [df1,df2,df3,df4]             # multiple dataframes
grp_list = ["con", "eco", "dip", "pol"]      # multiple categories in a column

for i in list:
    if i['pgp'].isin(group_list) and (i.egp == i.pgp):
        i['value'] == 1
    elif ~i['pgp'].isin(group_list):
        i['value'] == 2
    else:
        i['value'] == 0

Expected Output df1:
pgp     egp     value
con     con      1     # return 1 if pgp value is in the element list & pgp = egp
eco     eco      1
dip     health   0     # else 0
pol     health   0
god     con      2
ent     eco      2     # return 2 if pgp value is not in the element list

A: Use np.select~
def apply_conditions(df, group_list):
    in_group_list = df['pgp'].isin(group_list)
    conditions = (
        in_group_list & df['egp'].eq(df['pgp']),
        ~in_group_list
    )
    choices = (
        1,
        2
    )
    df['value'] = np.select(conditions, choices, default=0)
    return df

dfs = [df1,df2,df3,df4]
grp_list = ['con', 'eco', 'dip', 'pol']

dfs = [apply_conditions(df, grp_list) for df in dfs]

A: You can use np.select here:
import numpy as np

df1 = pd.DataFrame({
    'pgp': ['con', 'eco', 'dip', 'pol', 'god', 'ent'],
    'egp': ['con', 'eco', 'health', 'health', 'con', 'eco']
})

grp_list = ["con", "eco", "dip", "pol"]

m1 = df1['pgp'].isin(grp_list)
m2 = df1['pgp'] == df1['egp']

conditions=[m1&m2, ~m1]
choices = [1, 2]

df1['value'] = np.select(conditions, choices, default=0)
print(df1)

Output:
   pgp     egp  value
0  con     con      1
1  eco     eco      1
2  dip  health      0
3  pol  health      0
4  god     con      2
5  ent     eco      2


text:
Q: Polymer 1.x: Obervers bug? Fix or Workaround? Let me start by saying, I'm like 90% sure this is a bug with the Polymer observers system.
Conduct the following test and notice the following unexpected behaviors:
Test Procedure

*

*Open this JSBin.

*Toggle the <paper-toggle-button>.

*Notice the changes variable does not increment as expected.

*Enter any text into the <paper-input> field.

*Notice the changes variable does increment as expected.

*Toggle the <paper-toggle-button> again.

*Notice the changes variable now does increment as expected.

Note I also observed the same problems with <paper-dropdown-menu> as demonstrated here with <paper-toggle-button> but omitted it from this question for brevity.
Questions

*

*What's going on here?

*Is this a bug?

*Is there any workaround or fix?

http://jsbin.com/saxewimowu/edit?html,output

  <title>My Element</title>

  <base href="http://element-party.xyz/" />
  <link rel="import" href="all-elements.html" />

  <dom-module id="my-element">
    <template>
      <paper-input value="{{str::input}}"></paper-input>

      <paper-toggle-button checked="{{bool}}"></paper-toggle-button>

changes:[[num]]

str: [[str]]

bool:[[bool]]

    </template>

  </dom-module>
  <my-element></my-element>

A: It does after both properties have a value different of undefined (I guess or null).
After you enter a text and click the toggle, each change prints A.
To work around assign default values to your properties.
I added
      properties: {
        str: {
          type: String,
          value: ''
        },
        bool: {
          type: Boolean,
          value: false
        }
      },

to your element and with this I can't reproduce your problem anymore.

A: A workaround would be to observe props individually.
 (function() {
    Polymer({
      is: 'my-element',
      properties: {
        str:        {
          type:       String,
          notify:     true,
          observer:   '_somethingChanged'
        },
        bool:       {
          type:       Boolean,
          notify:     true,
          observer:   '_somethingChanged'
        }
      },
      _somethingChanged: function(evt) {
        // At this point, evt contains infos about what changed. Eg path and value.
        console.log('Something changed');
      },
    });
  })();

Another workaround would be to make str and bool parts of the same property (An object named foo) and observe foo.*.
  (function() {
    Polymer({
      is: 'my-element',
      properties: {
        foo:        {
          type:       Object,
          notify:     true,
          value:      function(){
            return {
              str:     'Default',
              bool:    false
            }
          }
        },
      },
      observers: [ '_somethingChanged(foo.*)' ],
      _somethingChanged: function() {
        // At this point, evt contains infos about what changed. Eg path and value.
        console.log('Something changed');
      },
    });
  })();

A: For the sake of completeness, I will add the source code and this link to the JSBin of the accepted answer and working solution.

http://jsbin.com/pufalegofe/1/edit?html,output

  <title>My Element</title>

  <base href="http://element-party.xyz/" />
  <link rel="import" href="all-elements.html" />

  <dom-module id="my-element">
    <template>
      <paper-input value="{{str::input}}"></paper-input>

      <paper-toggle-button checked="{{bool}}"></paper-toggle-button>

changes:[[num]]

str: [[str]]

bool:[[bool]]

    </template>

  </dom-module>
  <my-element></my-element>


text:
Q: Perl to check the sub directories and change the onwership I am trying to write a perl script which checks all the directories in the current directory and then accordingly penetrates in the subsequent directories to the point where it contains the last directory. This is what I have written:
#!/usr/bin/perl -w
use strict;
my @files = <*>;
foreach my $file (@files){
    if (-d $file){
            my $cmd = qx |chown deep:deep $file|;
            my $chdir = qx |cd $file|;
            my @subfiles = <*>:
            foreach my $ subfile(@subfiles){
                if (-d $file){
                    my $cmd = qx |chown deep:deep $subfile|;
                    my $chdir = qx |cd $subfile|;
            .  # So, on in subdirectories
            .
            .
            }
    }

    }
 }

Now, some of the directories I have conatins around 50 sub directories. How can I penetrate through it without writing 50 if conditions? Please suggest. Thank you.

A: Well, a CS101 way (if this is just an exercise) is to use a recursive function
sub dir_perms {
 $path = shift;
  opendir(DIR, $path);
  my @files = grep { !/^\.{1,2}$/ } readdir(DIR); # ignore ./. and ./..
  closedir(DIR);
  for (@files) {
   if ( -d $_ ) {
    dir_perms($_);
  }
  else {
   my $cmd = qx |chown deep:deep $_|;
   system($cmd);
  }
 }
}

dir_perms(".");

But I'd also look at File::Find for something more elegant and robust (this can get caught in a circular link trap, and errors out if you don't call it on a directory, etc.), and for that matter I'd look at plain old UNIX find(1), which can do exactly what you're trying to do with the -exec option, eg
/bin/bash$ find /path/to/wherever -type f -exec chown deep:deep {} \;

A: perldoc File::Find has examples for what you are doing. Eg,
       use File::Find;
       finddepth(\&wanted, @directories_to_search);
       sub wanted { ... }

further down the doc, it says you can use find2perl to create the wanted{} subproc.
 find2perl / -name .nfs\* -mtime +7 \
           -exec rm -f {} \; -o -fstype nfs -prune

A: NOTE: The OS usually won't let you change ownership of a file or directory unless you are the superuser (i.e. root).
Now, we got that out of the way...
The File::Find module does what you want. Use use warnings; instead of -w:
use strict;
use warnings;
use feature qw(say);
use autodie;
use File::Find;

finddepth sub {
    return unless -d;    #  You want only directories...
    chown deep, deep, $File::Find::name
        or warn qq(Couldn't change ownership of "$File::Find::name\n");
}, ".";

The File::Find package imports a find and a finddepth subroutine into your Perl program.
Both work pretty much the same. They both recurse deeply into your directory and both take as their first argument a subroutine that's used to operate on the found files, and list of directories to operate on.
The name of the file is placed in $_ and you are placed in the directory of that file. That makes it easy to run the standard tests on the file. Here, I'm rejecting anything that's not a directory. It's one of the few places where I'll use $_ as the default.
The full name of the file (from the directory you're searching is placed in $File::Find::name and the name of that file's directory is $File::Find::dir.
I prefer to put my subroutine embedded in my find, but you can also put a reference to another subroutine in there too. Both of these are more or less equivalent:
my @directories;
find sub {
   return unless -d;
   push @directories, $File::Find::name;
}, ".";

my @directories;
find \&wanted, ".";

sub wanted {
   return unless -d;
   push @directories, $File::Find::name;
}

In both of these, I'm gathering the names of all of the directories in my path and putting them in @directories. I like the first one because it keeps my wanted subroutine and my find together. Plus, the mysteriously undeclared @directories in my subroutine doesn't look so mysterious and undeclared. I declared my @directories; right above the find.
By the way, this is how I usually use find. I find what I want, and place them into an array. Otherwise, you're stuck putting all of your code into your wanted subroutine.


text:
Q: Finding the EOM for a charged relativistic particle For an exercise sheet of a course in general relativity I'm asked to derive the equations of motion for a charged particle in an EM-field given by a potential $A^\mu$. I am give the action:
$$S = -m\int ds-e\int A_\mu dx^\mu$$
With parametrization in proper time I get:
$$S = -\int d\tau\left(mg_{\alpha\beta}\dot{x}^\alpha\dot{x}^\beta+eA_\mu\dot{x}^\mu\right)$$
where $\dot{x}^\alpha =\frac{d x^\alpha}{d\tau}$. Euler-Lagrange gives:
$$0=\frac{\delta L}{\delta x^\alpha}-\frac{d}{d\tau}\frac{\delta L}{\delta\dot{x}^\alpha}$$
The first term is zero, so:
$$0 = \frac{d}{d\tau}\left(2mg_{\alpha\beta}\dot{x}^\beta+eA_\alpha\right)=2mg_{\alpha\beta}\ddot{x}^\beta+e\dot{A}_\alpha$$
where in the first equality we used the fact that $g$ is a symmetric $(0,2)$-tensor. Now I'm asked to write the equations of motion in terms of the field tensor $F_{\mu\nu}=\frac{\partial A_\nu}{\partial x^\mu}-\frac{\partial A_\mu}{\partial x^\nu}$. I have tried to use the identity
$$\dot{A}_\alpha = \frac{\partial A_\alpha}{\partial x^\nu}\dot{x}^\nu$$
but I couldn't get anywhere. Can someone help me out see how to do it (it's probably some dumb algebra trick) or say me where I'm wrong (if I'm wrong somewhere in the steps above)?

A: You're wrong in $\frac{\partial L}{\partial x^{\mu}} = 0$. Let's look at the equations for $\alpha = 1, 2, 3$:
$$
\frac{\partial L}{\partial \mathbf r} = q\frac{\partial A_{\mu}}{\partial \mathbf r}\dot {x}^{\mu} = \partial_{\mathbf r }(\mathbf A \cdot \mathbf v) + \partial_{\mathbf r}\varphi .\tag{1}
$$
Also you made the mistake in the summand $mg_{\alpha \beta}\dot {x}^{\alpha}\dot {x}^{\beta}$. $ds$ is equal to $\sqrt{g_{\alpha \beta }dx^{\alpha}dx^{\beta}}$, not to $g_{\alpha \beta }dx^{\alpha}dx^{\beta}$. Also, your convolution $\sqrt{g_{\alpha \beta }\dot {x}^{\alpha}\dot {x}^{\beta}}$ is equal only to $1$. So you will get
$$
S = -\int (m + qA_{\mu}\dot {x}^{\mu})d\tau. \tag{2}
$$


text:
Q: How can I generate an arc in numpy? If I know the center(x,y,z) of the arc and the diameter, and the starting and ending point, how can I generate the values between the start and the end?

A: It sounds like your "arc" is an circular approximation to a curve between two known points. I guessing this from the word "diameter" (which is twice the radius) in your post. To do this you parameterize the circle (t) -> (x,y) where t goes from 0..2pi. Given a center, two end points and a radius we can approximate a portion of the curve like this:
from numpy import cos,sin,arccos
import numpy as np

def parametric_circle(t,xc,yc,R):
    x = xc + R*cos(t)
    y = yc + R*sin(t)
    return x,y

def inv_parametric_circle(x,xc,R):
    t = arccos((x-xc)/R)
    return t

N = 30
R = 3
xc = 1.0
yc = 3.0

start_point = (xc + R*cos(.3), yc + R*sin(.3))
end_point   = (xc + R*cos(2.2), yc + R*sin(2.2))

start_t = inv_parametric_circle(start_point[0], xc, R)
end_t   = inv_parametric_circle(end_point[0], xc, R)

arc_T = np.linspace(start_t, end_t, N)

from pylab import *
X,Y = parametric_circle(arc_T, xc, yc, R)
plot(X,Y)
scatter(X,Y)
scatter([xc],[yc],color='r',s=100)
axis('equal')
show()

This example is only in 2D, but it is easily adaptable since the curve will always lie along the plane between the two points and the center.


text:
Q: Testing image uploads in Wikimedia Commons I want to use pywikibot to upload a batch of images into Wikimedia Commons.
However, when you add images in Commons, you can't easily delete them if you made a mistake.
Is there a way to locally install Wikimedia Commons for validation and testing ?
I tried installing mediawiki, but I can't seem to upload images using pywikibot.
Is there some specific procedure to do that?

A: Way more effort than just uploading and saying sorry if it goes wrong (just don't do batch operations until you are reasonably confident the script works; also see Guide to batch uploading and bot requests if you haven't yet). Also, licensing tends to be just as easy to get wrong as the technology; if you are not sure about what you are doing, ask first.
You can also use the test wiki for testing the bot (but no mass uploads please, just a few test files). Note it does not support structured data in image descriptions, unlike Commons. (There is a Commons test wiki but not for long.)
If you want to install a local MediWiki anyway, the mediawiki package is the easiest way (it will be dissimilar from Commons in a number of ways, but most of them probably don't matter much), make sure it is properly configured for uploading (not sure if the Debian package does that out of the box), then generate a wiki family for pywikipediabot.


text:
Q: Android XML design in 10.1 tab but do not support other screen resolution I have used dp as my unit to scale the size of objects in the design. I designed the xml interface in 10.1 in WXGA and can run properly in this device. However, when I try to install in other screen size, for example, 4.7 in WVGA , the objects(including images, buttons, text) are extremely larger than normal. This is my xml code:
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/loginback" >

        <EditText
            android:id="@+id/editText2"
            android:layout_width="400dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="500dp"
            android:layout_marginLeft="550dp"
            android:inputType="textPassword" >

        </EditText>

        <Button
            android:id="@+id/button1"
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="120dp"
            android:layout_marginRight="600dp"
           android:text="Log Masuk" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="120dp"
            android:layout_marginRight="330dp"
            android:text="Pengguna Baru?Daftar di sini" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="430dp"
            android:layout_marginLeft="250dp"
           android:text="Nama Pengguna: "
            android:textColor="#FFFFFF"
            android:textSize="30sp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="500dp"
            android:layout_marginLeft="250dp"
           android:text="Kata Laluan: "
            android:textColor="#FFFFFF"
            android:textSize="30sp" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="400dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="430dp"
            android:layout_marginLeft="550dp"/>

    </RelativeLayout>

What should I do to enable my apps can be viewed on other smaller screen devices?

A: For that you have to make different layout and drawable folders and put your xmls and images according to your screen resolution:
For supporting multiple screen sizes check this link
and for designing multiple screens check this link


text:
Q: Várias Divs com mesma Altura responsiva Tenho quatro cinco divs, sendo que uma delas é um container para as outras quatro.
Estrutura:

As divs das laterias vão ter o mesmo tamanho por causa dos li mas as do meio terão outro tipo de informação. Se eu setar valor de height fixo o UL vai sair da div quando for diminuindo a resolução. Preciso que todas as divs filhas tenham a mesma altura no começo e quando for se adaptando a outras resoluções ela vá crescendo junto para que os UL não saiam fora das divs

A: Fiz algumas alterações no id do html, para melhor referenciar no css:

1

2

3

Caixa 2

Caixa 3

1

2

3

e o css:
.divPai {
font-size: 0;
}
.content {
display: inline-block;
float:left;
font-size: 1rem;
}
.caixa {
box-sizing: border-box;
padding: 5px;
width: 25%;
min-height:100px;
}
.container {
margin: 10px;
}
.content:nth-child(1){background:#DCAE4C;}
.content:nth-child(2){background:#ECEDEF;}
.content:nth-child(3){background:#ECEDEF;}
.content:nth-child(4){background:linear-gradient(45deg, #5B5B5F, #868589);}

A: Já deu uma olhada nisso aqui?
http://codepen.io/chriscoyier/pen/zlntC
Um pouco mais sobre o flexbox...
No CSS-TRICKS: http://css-tricks.com/using-flexbox/
Documentação completa: http://css-tricks.com/snippets/css/a-guide-to-flexbox/
Aconselho também dar uma olhada no suporte dos browsers antes.


text:
Q: Restrict usage of annotations in Scala Given a custom defined annotation class GreaterThan(m: Double) extends scala.annotation.StaticAnnotation and a case class case class Person(name: String, @GreaterThan(0) age: Double), how can make sure that the uses of the annotation GreaterThanare used on doubles but not strings, obviously GreaterThan does not make sense to use on the name parameter.
Is there a way to emit a warning if the user uses an annotation in the wrong place( that I define), or like an error ?
Thanks

A: Macro annotations transform untyped trees, so you should use c.typecheck
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

class GreaterThan(m: Double) extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro GreaterThanMacro.impl
}
object GreaterThanMacro {
  def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
    import c.universe._

    annottees match {
      case q"$_ val $_: $tpt = $_" :: tail =>
        if (!(c.typecheck(tq"$tpt", mode = c.TYPEmode).tpe <:< typeOf[Double]))
          c.abort(c.enclosingPosition, s"$tpt is not Double")

        q"..$tail"
    }
  }
}

case class Person(name: String, @GreaterThan(0) age: Double) // compiles

  // doesn't compile: String is not Double
// case class Person(@GreaterThan(0) name: String, age: Double)

Besides c.abort there are c.error, c.warning.
Please beware of limitations for type checking in macro annotations (when a type is defined in the same scope where annotation is expanded)
type Dbl = Double // outer scope

{
  case class Person(name: String, @GreaterThan(0) age: Dbl) // compiles
}

type Dbl = Double // the same scope

  // doesn't compile: scala.reflect.macros.TypecheckException: not found: type Dbl
// case class Person(name: String, @GreaterThan(0) age: Dbl)

Scala whitebox macro how to check if class fields are of type of a case class
Sometimes implicit macros (macro-generated type classes) can be an alternative to macro annotations.
Maybe you could also try the library https://github.com/fthomas/refined/
import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Positive

case class Person(name: String, age: Double Refined Positive)


text:
Q: Investigating the importance of boundedness in Heine-Borel's theorem. We know that $[1,\infty)$ is not compact in $\Bbb{R}$. A simple proof: the cover $\mathfrak{C}=\bigcup B(n,\frac{3}{4})$ for all $n\in\Bbb{N}$ of $[1,\infty)$ does not have a finite subcover.
What is wrong with the following argument (which closely resembles the proof of Heine-Borel's Theorem):
Let $B=\{x\in [1,\infty): [1,x]\text{ has a finite subcover of }\mathfrak{C}\}$. If $B$ is not bounded, then the whole of $[1,\infty)$ has a finite subcover. So let us assume $B$ is bounded, and let $m=\sup B$. All the open sets $m$ is contained in are of the form $(a,b)$, where $b>m$ and the point $\frac{b+m}{2}$, which is larger than $m$, is also contained in $(a,b)$. We can select one such open set. So there are points larger than $m$ in $B$, which is a contradiction. Hence, $B$ is unbounded, and the whole of $[1,\infty)$ is compact.
Thanks in advance!

A: The mistake is the implication $B$ unbounded $\Rightarrow [1, \infty)$ has a finite subcover. But really $B$ being unbounded just means that for any $x$ (no matter how large), $[1,x]$ has a finite subcover of $\mathfrak{C}$, which is not surprising since for any such $x, [1,x]$ is compact.

A: $B$ is actually unbounded.
What the proof shows is that for each $x\in [1,\infty)$, $[1,x]$ has a finite subcover of $\mathfrak C$, which is not surprinsing as these intervals are compact. But it does not imply that $[1,\infty)$ has a finite subcover.


text:
Q: Android SQLite query string to reach to D in A~B~C~D~E~F where A,B,C,D,E and F could have any interested length and data In an Android application,
In SQLite database, there is a column with the following data:
A~B~C~D~E~F
Where each of A,B,C,D,E and F could have variable length and data
For example,
A could be every possible interested name like Mike, Andy, Tom , ...
Or B could be any interested country name and so on
Now I need a Query to reach to D part, how?
FYI, '~' character is unique in the data (there would be just 5 characters of '~')
In other word, A,B,C,D,E,F don't contain '~'
Edit:
I need LIKE clause in a basic SQLite

A: I actually don't know of a way to do this using only the basic SQLite string functions.  Therefore, I would suggest handling this from Java, after you have queried:
String input = "A~B~C~D~E~F";
String[] parts = input.split("~");
String target = parts.length >= 4 ? parts[3] : "";

A: Eureka! It's possible with LIKE clause (NOT LIKE) in a basic SQLite:
          SELECT_QUERY =
                        String.format("SELECT * FROM %s WHERE %s NOT LIKE %s;",
                                Constants.TABLE_M4,
                                Constants.KEY_M4_Data,
                                "%~%~%~~%'"
                        );

If D is not empty, it is identified with the above query


text:
Q: Why Spydroid-ipcamera needs two sockets before using RTPsocket? Spydroid-ipcamera is an open-source Android code that streams the camera and microphone of the phone to the browser or to VLC.
Its website is here: http://code.google.com/p/spydroid-ipcamera/
It is a typical example in stackoverflow when someone asks about streaming the camera of an Android phone.
Looking into its code:
(1) It builds two sockets as a pair: mSender, mReceiver
private LocalServerSocket mLss = null;
mLss = new LocalServerSocket("net.majorkernelpanic.librtp-"+sId);

mReceiver = new LocalSocket();
mReceiver.connect( new LocalSocketAddress("net.majorkernelpanic.librtp-" + mSocketId ) );
mReceiver.setReceiveBufferSize(500000);
mSender = mLss.accept();
mSender.setSendBufferSize(500000);

(2) The output of the camera is written to mSender:
In streaming/MediaStream.java
// We write the ouput of the camera in a local socket instead of a file !
setOutputFile(mSender.getFileDescriptor());

(3) It builds another object, mPacketizer, which includes a member of RtpSocket.
The object mPacketizer receives the camera inputStream from mReceiver, encapsulates the camera stream to RTP packets, and then send packets over the network.
// the packetizer encapsulates this stream in an RTP stream and send it over the network
mPacketizer.setInputStream(mReceiver.getInputStream());

In this sense, the whole camera stream flow is:
camera stream --> mSender --> mReceiver --> mPacketizer, RtpSocket --> send out to the network.
My question is:
Why does it need two sockets, mSender and mReceiver?
Is one socket is sufficient to mediate camera stream and RtpSocket?

A: MediaRecorder allows you to write camera stream to a file or socket. Now when you need live feed for broadcasting you send it to a LocalSocket(to yourself) and receive at receiver socket for further processing.


text:
Q: Listbox could not resize automatically in Tkinter (python) I have written a Tkinter app with Python (2.7), I found that the listbox does not grow to fit the outer window when dragging in vertical direction (to increase the height of the window).
The code is as following shown
from Tkinter import *

def main():
    root = Tk()
    mainframe = Frame(root)
    mainframe.pack(expand=YES, fill=BOTH)

    status = Entry(mainframe)
    status.pack(side=BOTTOM, expand=YES, fill=X)

    list = Listbox(mainframe)
    list.pack(side=LEFT, expand=YES, fill=BOTH)
    root.mainloop()

main()

So what's the problem? Is there any way to resizing the listbox in vertical direction?

A: You are expanding the space for the Entry widget, but you only fill it to X.
If you want to keep the Entry as it is and only expand the Listbox use: status.pack(side=BOTTOM, expand=NO, fill=X)
If you want to expand both the Listbox and the Entry use:
status.pack(side=BOTTOM, expand=YES, fill=BOTH)


text:
Q: How to get the built-in contact form working in a CMS page in Magento? I implemented the contact form into a CMS page here.
As you can see, the forms shows up fine.  However, when I fill the form out to test and click "send", there is no message indicating if the mail was sent correctly or failed.  But a new page loads, so I think it is doing something. When I check my email, no email comes.  I've checked spam folder too.
Current Setup:
In the CMS page, I have this code:
{{block type="core/template" name="contactForm" form_action="/contacts/index/post" template="contacts/form.phtml"}}

In the form.phtml file, I have modified the form tag action attribute to:
<form action="/contacts/index/post/" id="contactForm" method="post">

Stuff I've tried already:
And I don't think its the server because I tried the "forgot password" when logging into the Admin, and I received an email to reset the password.
In System Config, I've verified that "Enable Contact Us" is Yes.  "Disable EMail Communications" is No.  And makes no difference if "Set Return Path" is Yes or No.
It is set to send to an email address that is not hosted by the same server as the Magento site is on.  The email address is a Google Apps email.

A: Ok, I figured it out.  For some reason, the path in the action attribute of  needed another parent folder.  So in my case, it should be
<form action="/2/contacts/index/post/" id="contactForm" method="post">

A: just go to app/design/frontend/your_theme/default/template/contacts/form.phtml
and set form action to <?php echo $this->getFormAction(); ?>
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post">


text:
Q: Using 'of' vs no 'of' I've run into a small question about using of. Which of the following sentences are correct? If they both are correct, which one is more correct?

The theme is told through the characters Bob, Joe, and Ann.
The theme is told through the characters of Bob, Joe and Ann.

I've overthought this, as I always do, so I can't tell which one sounds right anymore. Can anyone help?

A: Yes it is a restrictive apposition. No, it is not a case of noun acting as adjective.  The names are a restrictive appositive for "characters". But in the second sentence, Interposing "of" between "characters" and the names makes them not juxtaposed, hence not an appositive. The reason that the "of" in the second sentence does not work semantically is that it means the story depends on Bob, Joe, and Ann's "character" (their moral fiber, as it were).  Unless you really mean that, it's better to focus on the three characters (in fhe sense of roles). As for the comma, I agree with Dr Moishe Pippik.

A: The first sentence is wrong because it omits a comma after "characters". With the comma, it would be correct; the names are used as an appositive. Another example of apposition: "My friend, Alice, is here." Note the commas around Alice.
The second sentence is correct as-is, because "of" links characters to their names in a prepositional phrase.

A: The first one is correct.  What you have here is a case of a noun acting as adjective, or a restrictive apposition.  This becomes apparent if you were to phrase the sentence with a singular noun.
The theme is told through the character Bob.

Character, which is normally a noun, is actually an adjective describing Bob, much like you might say
The lesson was taught by the history teacher.

In this case, Bob, Joe, and Ann are three parallel nouns, and characters is a noun-as-adjective describing all three of them.


text:
Q: Automating Adobe Media Server install everyone!  I'm making an installer that is going to set a machine up for use of a piece of software.  Adobe Media Server is one of the software requirements.  I'm wondering if there's any way to automate the installation of it.  I can, of course, open the wizard through a command line, but at that point, the user needs to be there to continue installation.  I'm really looking for more of a "set it and forget it" type of solution.  If anybody knows of any way this is possible, please tell me.  I'm not finding anything online so far.

A: I'm assuming you are doing this on a Windows server, in which case you will have to do some heavy integration with the Adobe Media Server installer. A good open source tool for installer bundling would be Inno Setup. This is much easier to accomplish on a linux server, where you could execute a function within a script that downloads the installer, and extracts it with defined parameters. I believe the package name for a YUM install on linux is: AdobeMediaServer_5_LS1_linux64.tar.gz

A: You can search for any installers building tool which supports adding prerequisites and add the Adobe Media Server as a prerequisite to your installer. Also, you should configure your Adobe Media Server prerequisite to be installed with a silent/unattended command line.


text:
Q: Using webpack to get all paths in directory I have some front end code which needs to run for each png in a specific directory. I am using Webpack but am unsure of how use it for this.
I realize that Webpack only runs server-side, but that's fine. What I'm looking for is a variable which is an array of paths. I don't want to hard-code it because there are a lot of png files.
Ideally, there is some sort of general-purpose compile time command I can use to interpolate Javascript into the result, something like this:
var glob = require("glob")
var loadFiles = new Promise(funtion(resolve, reject) {
  CompileTimeCommand(function() {
    glob("assets/tilesheet_images/*.png", function (er, paths) {
      if (err) { reject(err) } else { resolve(paths) }
    })
  })
})
loadFiles.then(function(paths) {
  // etc
})

The problem is, this CompileTimeCommand doesn't exist.
Is there a way I can do this with require, or some sort of general purpose compile-time macro system? I have written a Webpack loader before, but it seems overkill to have to make a new package for a simple, ad-hoc command.
Is there a better way than to just make a separate script which runs the dir glob and saves the paths into a json file which is read by my program?

A: If you need to get a list of files at run-time and it can change at run-time then you'd rather use your back-end technology to access file system and return results to front-end via http call for example.
Otherwise if files are static and are determined at compile time then you can use glob in webpack config file and put its results into DefinePlugin to replace some variable with a list of files.


text:
Q: All array possibilities I have pascal code (programming language actually doesn't mean anything):

box[1] := 14;   box[2] := 2;
  box[3] := 4;   box[4] := 5;
  box[5] := 6;   box[6] := 8;

I want to get all possibilities. For instance, box[1] = box[6], then box[6] = box[1]. Yes, I can write it by my hand, but I guess I can make it more clever, by loop. Any suggestions?

A: I have taken the first permutation algorithm I found in wikipedia and implemented it in Delphi (2009); I hope that is what you are looking for:
type
  TIntegerArray = array of Integer;

procedure Permutation(K: Integer; var A: TIntegerArray);
var
  I, J: Integer;
  Tmp: Integer;

begin
  for I:= 2 to Length(A) do begin
    J:= K mod I;
    Tmp:= A[J];
    A[J]:= A[I - 1];
    A[I - 1]:= Tmp;
    K:= K div I;
   end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  K, I: Integer;
  A: TIntegerArray;
  S: string;

begin
  Memo1.Lines.Clear;
  for K:= 0 to 719 do begin
    A:= TIntegerArray.Create(14, 2, 4, 5, 6, 8);
    Permutation(K, A);
    S:= '';
    for I:= 0 to Length(A) - 1 do
      S:= S + Format('%3.d ', [A[I]]);
    Memo1.Lines.Add(S);
  end;
end;

A: I've answered you already? =S

A: So basically, you have set of items that can either be included (1) or excluded (0). If you count from 0 to 2^(the number of items)-1, every integer will be a set of bits indicating which items are included.
If you have 7 items, in your loop from 0 to 127 the items chosen are:
x0000000 (loop variable = 0, no items are chosen)
x0000001 (loop variable = 1, item [1] is chosen)
x0000010 (loop variable = 2, item [2] is chosen)
x0000011 (loop variable = 3, items [1] and [2] are chosen)
...
x1111111 (loop variable = 127, items [1], [2], [3], [4], [5], [6], [7] are chosen)


text:
Q: Uninstalling unwanted MiKTeX packages I basically use MiKTeX for converting Markdown documents & Jupyter notebooks into PDF files (with pandoc) and never use it for making documents (as a text editor). But my MiKTeX installation happens to contain a large number of big packages that are of no use to me. But I cannot find a way to get rid of them. In the Packages section of MiKTeX console, there's an option to see all installed packages where there are many packages installed to support non English languages. And they tend to be bigger in size (each in 200 - 300 MiB range). I have no need for languages of non Latin origin. So, these packages (e.g support for middle eastern languages & Asian languages) are essentially a bloat for me. I would like to remove these and keep my installation at a bare minimum. Is there a way to do this?
I'm open to remove MiKTeX and switch to another application if I cannot do this in MiKTeX, but that application must be able to get my job done (converting Jupyter notebooks, Markdown files & RMarkdown documents to pdf). The fact I really don't need the TeXworks text editor that's bundled with MiKTeX either makes me willing switch to any other minimal versions of LaTeX systems. Any help would be appreciated. Thank you!.
P.S I'm on a Windows 10 machine. MiKTeX version 22.7 (MiXTeX console version 4.7).

A: You may want to check TinyTex which is a lightweight, cross-platform, portable, and easy-to-maintain LaTeX distribution based on TeXLive.
And also another option could be for you to make a switch to Quarto which would get your job (converting Jupyter notebooks, Markdown files & RMarkdown documents to pdf) done easily.
And Most importantly, while converting to pdf it will install only those latex packages that are necessary for the rendering process of the file (If they are not installed only).
Read this Get Started Guide to know how to install Quarto and You can use this with VS code, Jupyter Lab, Rstudio or any other text editor.
And to render

*

*Jupyter notebooks to pdf see here

*Rmarkdown files to pdf see here

*And you can render markdown files to pdf in the same of Rmarkdown files.

And lastly, I am not a MiKTex user, so actually can't be of help addressing the original problem of yours. Hopefully someone other may have solution regarding the problem.

A: LaTeX by its nature is a 4GB+ "Distro" of interdependent modules so LiveTex TinyTex MiKTeX and W32TeX have package managers.
texlive2022-20220321.iso 2022-03-21 22:59    4.3G
Needs expanding
For MiKTeX its easy to command line or GUI
MiKTeX Remove [--package-id-file file] package-id...
e.g. Remove installed MiKTeX packages. see https://docs.miktex.org/manual/miktex-packages.html However best to use the GUI admin to resolve some inter dependency.

"Just enough TeX"
MiKTeX supports the notion of a scalable TeX system: users install just the TeX packages they need for their authoring tasks.

Date: 7/18/2022 File name: basic-miktex-22.7-x64.exe Size: 132.71 MB
needs expanding

your minimal TeX system
From now on, whenever a package is required which hasn't been installed yet, the package installer comes into play.

Due to the nature of "on the fly" installation setting it can appear less stable than the full ProTex variant. But if set correctly any removed essentials should be auto renewed when necessary.
Generally MiKTeX is the best distro suite for western windows users, just as W(in)32Tex is more suited to eastern windows users.
TinyTex is best for R users and is modeled on MiKTeX

I appreciate one nice feature of MiKTeX on Windows (which seems to be cross-platform now): automatically installing missing LaTeX packages. I think this is very helpful, so I borrowed this feature to the R package tinytex,

TinyTeX-v2022.08.zip 226 MB
Needs expanding


text:
Q: Pandas dataframe indexing: Use of '.values' for different index occurrence frequencies Imagine a dataframe like that:
     A    B
ID
1    4    5
2    6    7
2    6    8

If I want to access the values for ID=1 in column A, I can do the following:
df.ix[1, 'A']

For ID=2 in column A, this works:
df.ix[2, 'A'].values

Is there a way to combine both statements without e.g. using a try/except statement? I couldn't find a nice way for doing this....

A: One way to do this would be to use lists (or tuples, slices, etc) as indexes. Example -
In [63]: df
Out[63]:
    A  B
ID
1   4  5
2   6  7
2   8  9

In [64]: df.loc[[1],'A'].values #Works for `.ix` as well.
Out[64]: array([4], dtype=int64)

In [65]: df.loc[[2],'A'].values #Works for `.ix` as well.
Out[65]: array([6, 8], dtype=int64)


text:
Q: Filter custom post with multiple checkboxes via AJAX I'm working on multiple filters functionality in Wordpress page.
I have done selectors and AJAX query, and get data correct (I think). But result of AJAX function is wrong - every request result is every not-filtered post.
My code:

Product series

                      <input class="products__filters--checkbox" type="checkbox" name="product_series" value="Castillo">
                                                                      Castillo

                      <input class="products__filters--checkbox" type="checkbox" name="product_series" value="Robinia">
                                                                      Robinia

                      <input class="products__filters--checkbox" type="checkbox" name="product_series" value="Test">
                                                                      Test

                      <input class="products__filters--checkbox checked" type="checkbox" name="product_series" value="Wooden">
                                                                      Wooden

Colors

                      <input class="products__filters--checkbox" type="checkbox" name="colors" value="blue">

                                              blue

                      <input class="products__filters--checkbox checked" type="checkbox" name="colors" value="red">
                                                                      red

Age group

                      <input class="products__filters--checkbox" type="checkbox" name="age_group" value="1-3">
                                                                      1-3

                      <input class="products__filters--checkbox checked" type="checkbox" name="age_group" value="4-7">
                                                                      4-7

Search

JS Code:

      (function ($) {
      $(document).ready(function (){
        $(document).on('click', '.js-filter-search', function (e) {
          e.preventDefault();
          var choices = {};
          var choice = $('.products__filters--checkbox:checked').attr('name');

          $('.products__filters--checkbox:checked').each(function() {
                         if (!choices.hasOwnProperty(this.name))
                             choices[this.name] = [this.value];
                         else
                             choices[this.name].push(this.value);
                     });
          console.log(choices);

          var ppp = -1;
          var url = window.location.origin;

          $.ajax({
            url: url.concat('/wp-admin/admin-ajax.php'),
            data: {action: 'filterproducts', termNames:choices, ppp:ppp },
            type: 'post',
            success: function(result) {
              $('.js-products-result').html(result);
            },
            error: function (result) {
              console.warn(result);
            }
          })
        })
      })
    })(jQuery);

and PHP request:

add_action('wp_ajax_nopriv_filterproducts', 'filterproducts_ajax');
add_action('wp_ajax_filterproducts', 'filterproducts_ajax');

function filterproducts_ajax() {

   header("Content-Type: text/html");
    $ppp = $_POST['ppp'];
    $termNames = $_POST['termNames'];
    $tax_query = array('relation' => 'OR');
      foreach($termNames as $key=>$value){
        if(count($value)){
          foreach ($value as $inkey => $invalue) {
            $tax_query[] = array( 'taxonomy' => $key, 'terms' => $invalue, 'field' => 'name');
          }
        }
      }

      var_dump($tax_query);
      $args = array(
            'post_type' => 'products',
            'meta_query' =>$tax_query
        );

    $query = new WP_Query($args);
      if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();?>

           <a href="<?php echo get_permalink($product);?>"  class="products__item--title"><?php echo get_the_title($product);?>

     <?php
     endwhile;
   endif;
   wp_reset_postdata();
   die();
 }

Output of var_dump($tax_query):
array (size=3)
  'relation' => string 'OR' (length=2)
  0 =>
    array (size=3)
      'taxonomy' => string 'product_series' (length=14)
      'terms' => string 'Robinia' (length=7)
      'field' => string 'name' (length=4)
  1 =>
    array (size=3)
      'taxonomy' => string 'colors' (length=6)
      'terms' => string 'blue' (length=4)
      'field' => string 'name' (length=4)

finally I'm stuck in the result of query - output is all of my Products CPT repeated 4 times after all $tax_query dump.

A: Yeah, I made it.
Below I share my code, maybe somebody use it.
$tax_query = array('relation' => 'AND');

 foreach($_POST['termNames'] as $key => $terms) {
   if(count($terms)) {
     foreach ($terms as $inkey => $invalue) {
       $tax_query[] = array( 'taxonomy' => $key, 'field' => 'name', 'terms' => $invalue);
     }
   }
 }
 $args = array(
   'post_type' => 'products',
   'tax_query' =>$tax_query
 );
  $query = new WP_Query($args);
    if( $query->have_posts() ) :
      while( $query->have_posts() ): $query->the_post(); ?>
       // here your post tile code
  else :
    echo "Sorry, no products was found";
  endif;
wp_reset_postdata();


text:
Q: Valgrind throwing error on fresh cocoa app on Mac Sierra I'm new to Valgrind and want to learn to use it on OSX (version 10.12.5 (16F73)). I installed it, created a fresh cocoa app in xcode and simply used the following command in the terminal.
valgrind --leak-check=full "blaattest.app"

This is showing me the following error and I have no idea how to continue from here. Is there anyone who has seen this before and/or knows how to solve this?
==20458== Memcheck, a memory error detector
==20458== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==20458== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==20458== Command: blaattest.app/Contents/MacOS/blaattest
==20458==
--20458-- run: /usr/bin/dsymutil "blaattest.app/Contents/MacOS/blaattest"
==20458== Syscall param msg->desc.port.name points to uninitialised byte(s)
==20458==    at 0x103C7434A: mach_msg_trap (in /usr/lib/system/libsystem_kernel.dylib)
==20458==    by 0x103C73796: mach_msg (in /usr/lib/system/libsystem_kernel.dylib)
==20458==    by 0x103C6D485: task_set_special_port (in /usr/lib/system/libsystem_kernel.dylib)
==20458==    by 0x103E0910E: _os_trace_create_debug_control_port (in /usr/lib/system/libsystem_trace.dylib)
==20458==    by 0x103E09458: _libtrace_init (in /usr/lib/system/libsystem_trace.dylib)
==20458==    by 0x100BFB9DF: libSystem_initializer (in /usr/lib/libSystem.B.dylib)
==20458==    by 0x10001BA1A: ImageLoaderMachO::doModInitFunctions(ImageLoader::LinkContext const&) (in /usr/lib/dyld)
==20458==    by 0x10001BC1D: ImageLoaderMachO::doInitialization(ImageLoader::LinkContext const&) (in /usr/lib/dyld)
==20458==    by 0x1000174A9: ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, char const*, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) (in /usr/lib/dyld)
==20458==    by 0x100017440: ImageLoader::recursiveInitialization(ImageLoader::LinkContext const&, unsigned int, char const*, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) (in /usr/lib/dyld)
==20458==    by 0x100016523: ImageLoader::processInitializers(ImageLoader::LinkContext const&, unsigned int, ImageLoader::InitializerTimingList&, ImageLoader::UninitedUpwards&) (in /usr/lib/dyld)
==20458==    by 0x1000165B8: ImageLoader::runInitializers(ImageLoader::LinkContext const&, ImageLoader::InitializerTimingList&) (in /usr/lib/dyld)
==20458==  Address 0x10488d62c is on thread 1's stack
==20458==  in frame #2, created by task_set_special_port (???:)
==20458==
--20458-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option
--20458-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 2 times)
--20458-- UNKNOWN mach_msg unhandled MACH_SEND_TRAILER option (repeated 4 times)
UNKNOWN workq_ops option 128
==20458== valgrind: Unrecognised instruction at address 0x103a60b50.
==20458==    at 0x103A60B50: _dispatch_kq_init (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103A5E8FB: _dispatch_client_callout (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103A5E8B8: dispatch_once_f (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103A60A90: _dispatch_kq_update (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103A620CD: _dispatch_kevent_resume (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103A6203D: _dispatch_source_kevent_resume (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103A61E85: _dispatch_source_kevent_register (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103A71651: _dispatch_queue_resume_finalize_activation (in /usr/lib/system/libdispatch.dylib)
==20458==    by 0x103DB13C0: _notify_lib_init (in /usr/lib/system/libsystem_notify.dylib)
==20458==    by 0x103DB19AB: notify_register_dispatch (in /usr/lib/system/libsystem_notify.dylib)
==20458==    by 0x102A108F6: __96-[_CFXPreferences(SourceAdditions) withSourceForIdentifier:user:byHost:container:cloud:perform:]_block_invoke_2 (in /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation)
==20458==    by 0x103A5E8FB: _dispatch_client_callout (in /usr/lib/system/libdispatch.dylib)
==20458== Your program just tried to execute an instruction that Valgrind
==20458== did not recognise.  There are two possible reasons for this.
==20458== 1. Your program has a bug and erroneously jumped to a non-code
==20458==    location.  If you are running Memcheck and you just saw a
==20458==    warning about a bad jump, it's probably your program's fault.
==20458== 2. The instruction is legitimate but Valgrind doesn't handle it,
==20458==    i.e. it's Valgrind's fault.  If you think this is the case or
==20458==    you are not sure, please let us know and we'll try to fix it.
==20458== Either way, Valgrind will now raise a SIGILL signal which will
==20458== probably kill your program.


text:
Q: Pandas - Operate with series and delays I have the following dataframe in Pandas. My doubt is how can I make to operate with series where one has a time delay. For example, I would like to calculate the result of dividing the GDP of a period by the population of the next period.
         GDP     Population
1950     3.31        1
1951     3.5         1
...
2000     15.2        2

A: To do that you can just use:
df['new_col'] = df['GDP'] / df['Population'].shift(1)

A: Have you consider using shift?
import pandas as pd
import numpy as np

df = pd.DataFrame({"GDP": np.random.normal(3,1,51),
                   "Pop":np.random.randint(1,10,51)},
                   index=np.arange(1950,2001))
df["res"] = df.GDP.shift(1)/df.Pop


text:
Q: TextView is cut off when applying BlurMaskFilter I want to blur the text of a TextView, but the text is cut off left and right.
Image of the cut off text

I tried to increase padding, margin. Changed gravity, Enabled/disabled font padding. Set a fixed height, lowered font size etc. All to the same result: The sides were cut off.
The setting of the mask filter is just two lines:
textView.paint.maskFilter = BlurMaskFilter(radius, BlurMaskFilter.Blur.NORMAL)
textView.postInvalidate()

This is how my XML layout looks like:
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="-1dp"
    android:includeFontPadding="false"
    android:layerType="software"
    android:textSize="48sp"
    tools:textColor="@color/solid_white"
    tools:text="132" />

I'm looking for a solution to see the text fully without cutoffs on the edges.

A: Remove this attribute from your <TextView> tag:

android:layerType="software"

Hardware acceleration is required for views to draw outside of their bounds. Note that padding doesn't help here because view contents are clipped by padding as well.

A: After attempting a ton of alternatives, using a LeadingMarginSpan.Standard(margin) to offset the text did the trick. I overrode the class and added the blur mask there rather than using a MaskFilterSpan.


text:
Q: Connection is disconnecting when mobile is going offline and then not getting offline message in Smack (xmpp) I am trying to achieve the offline message when i got online again in Smack
this is my connection code I am able to reconnect and continue the chat also but not getting the offline message in Had use OfflineManager also but it is howing zero message...
    public void connectConnection() {
    AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {

        @Override
        protected Boolean doInBackground(Void... arg0) {

            // Create a connection
            try {
                connection.connect();
                login();
                connected = true;
                scheduleTaskExecutor = Executors.newSingleThreadScheduledExecutor();
                scheduleTaskExecutor.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("xmpp", "inside run()");
                        Log.d("xmpp", "isconnect: " + connection.isConnected() + " Auth: " + connection.isAuthenticated());
                        Log.d("xmpp", "getPacketReplyTimeout: "+String.valueOf(connection.getPacketReplyTimeout()));

                        SettingStore ss=new SettingStore(getApplicationContext());
                        if (ss.getStartChatValue()){

                            try {
                                Presence presence = new Presence(Presence.Type.available);
                                connection.sendPacket(presence);
                            } catch (SmackException.NotConnectedException e) {
                                e.printStackTrace();
                            }

                                if (connection.isConnected()) {
                                sendMessagesToServer();

                            } else {
                                try {
                                    connection.connect();
                                    login();
                                } catch (SmackException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (XMPPException e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                        else {
                            disconnectAndStopTimmer();
                        }

                    }

                }, 0, 2, TimeUnit.SECONDS);

            } catch (IOException e) {
            } catch (SmackException e) {

            } catch (XMPPException e) {
            }

            return null;
        }
    };
    connectionThread.execute();

}

I am gitting connection time out error
09-30 19:07:20.796 10323-10382/? W/AbstractXMPPConnection: Connection closed with error
                                                       javax.net.ssl.SSLException: Read error: ssl=0x60fefe48: I/O error during system call, Connection timed out
                                                           at com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method)
                                                           at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:690)
                                                           at java.io.InputStreamReader.read(InputStreamReader.java:233)
                                                           at java.io.BufferedReader.read(BufferedReader.java:325)
                                                           at org.kxml2.io.KXmlParser.fillBuffer(KXmlParser.java:1506)
                                                           at org.kxml2.io.KXmlParser.peekType(KXmlParser.java:986)
                                                           at org.kxml2.io.KXmlParser.next(KXmlParser.java:346)
                                                           at org.kxml2.io.KXmlParser.next(KXmlParser.java:310)
                                                           at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1164)
                                                           at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$300(XMPPTCPConnection.java:944)
                                                           at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:959)
                                                           at      java.lang.Thread.run(Thread.java:862)
 09-30 19:07:20.796 10323-10382/? D/xmpp: ConnectionClosedOn Error!

A: move your connection to background service so it is always connected.
in openfire, there is option for resending offline messages
server > server settings > offline messages
Store offline messages for later retrieval. Messages will be delivered the next time the recipient logs in.
this will automatically send the message again when the user gets connected to xmpp


text:
Q: Standalone prettier, html formatter isn't properly formatting JS I'm formatting code directly on the browser using the Prettier Standalone version.
Here is my code:
import parserHtml from "prettier/parser-html";
import prettier from "prettier/standalone"

const rawHtml = `

`

const snippet = prettier.format(
    rawHtml,
    { parser: "html", plugins: [parserHtml] }
  );

It will output:

Whereas if I'm pasting the HTML code on my IDE, Prettier will correctly format the JS code:

What am I missing?

A: To format the embedded JavaScript syntax, you also need to load the babel parser:
import parserBabel from "prettier/parser-babel";
// ...
const snippet = prettier.format(
  rawHtml,
  { parser: "html", plugins: [parserHtml, parserBabel] }
);


text:
Q: How can I switch on the data type of an object field? I have a long switch statement that I'm trying to make more efficient.
It parses an xml feed and populates a Java object using the xml values.
There are maybe 30 fields so it's kind of tedious to write a switch case
for each field.
switch (currentTagName) {
    case "longitude" :
        observation.setLongitude(Double.parseDouble(parser.getText()));
        break;
    case "elevation" :
        observation.setElevation(Integer.parseInt(parser.getText()));
        break;
    case "observation_time" :
        observation.setObservation_time(parser.getText());
        break;

You can see, the only difference in how each case is handled is due to the type of data I'm working with.
I'm trying to figure out the syntax for doing something similar to this (pseudocode):
//get the data type of this variable, somehow or other
String inputType = Observation.getMethodInputType("set" + currentTagName);

//switch on that data type
switch(inputType) {
    case "Integer":
        observation.set{currentTagName}(Integer.parseInt(parser.getText()));
        break;
    case "Double":
        observation.set{currentTagName}(Double.parseDouble(parser.getText()));
        break;
    case "String":
        observation.set{currentTagName}(parser.getText());
        break;
}

It's just that my Java syntax is pretty rusty, I'm not sure what the correct way is to do this (or if you even can),
especially for the set{currentTagName} part and getMethodInputType() (is that a thing?).
What's the correct way to do this?

A: Your solution will be pretty unmaintainable. Java has few popular methods of parsing xml in compact way (without tedious string operations).
You should check:

*

*JAXB (recommended) which provides good domain encapsulation and very readable code

*DOM which is semi readable and semi fast

*SAX which is very fast and least maintanable

For JAXB you will have to create object/objects which will recreate xml structure and conversion will happen automatically for you.

A: Don't use a switch. Make an interface for conversion of String to an object by type, populate a Map<Class,Converter> with converters of appropriate type, and use converters from that map to parse your input.
interface Converter {
    Object convert(String s);
}
private static Map<Class,Converter> converterForClass = new HashMap<>();
static {
    converterForClass.put(Integer.TYPE, s -> Integer.parseInt(s));
    converterForClass.put(Double.TYPE, s -> Double.parseDouble(s));
    converterForClass.put(String.class, s -> s);
    converterForClass.put(Long.TYPE, s -> Long.parseLong(s));
};

Now you can convert Strings to Objects of the appropriate type like this:
Object a = converterForClass.get(Integer.TYPE).convert("123");

Here is a demo that uses reflection to access the field:
static class Demo {
    public int a;
    public long b;
    public String c;
    public double d;
    @Override
    public String toString() {
        return a+":"+b+":'"+c+"':"+d;
    }
}

public static void main (String[] args) throws java.lang.Exception
{
    Object a = new Demo();
    Map<String,String> data = new HashMap<>();
    data.put("a", "123");
    data.put("b", "123456678789898");
    data.put("c", "HELLO");
    data.put("d", "123.456");
    for (Field f : Demo.class.getDeclaredFields()) {
        f.setAccessible(true);
        String str = data.get(f.getName());
        Object r = converterForClass.get(f.getType()).convert(str);
        f.set(a, r); // Call set(target, objValue) instead of setInt, setLong, etc.
    }
    System.out.println(a);
}

Running demo.

A: You can simply convert it to an object and get its class name using:
((Object) yourVar).getClass().getName()

Then you can use it in your switch statement:
String typeName =  ((Object) inputType).getClass().getName();

switch(typeName) {

   case "Integer":

            observation.set{currentTagName}(Integer.parseInt(parser.getText()));
   break;

   case "Double":

             observation.set{currentTagName}(Double.parseDouble(parser.getText()));
    break;

    case "String":

              observation.set{currentTagName}(parser.getText());
    break;
 }

Take a look at How to determine the primitive type of a primitive variable? for further information.

A: Convert either the int and double into a string, and then use one if statement. Use the following syntax:
Integer.toString(i)
//Makes an integer into a string

and
Double.toString(i)

//Makes a double into a string

Once you have everything as a string, compare strings. This way the variable type is the same, and it makes the code much easier to deal with.
Good luck!

A: I've written a little Java-8 library called unXml, that might be of help to you. It's open sourced on Github, and available on Maven Central.
You can create an ObjectParser that will pick out a value from an XPath, and put it into a JsonObject as an attribute. Then it uses Jackson's json-mapping to instantiate your class.
Read up on Jacksons Json to Object mapping, to see how to best fit it into your classes.
Example:
<root>
    <entry id="1">
        <observation>100</observation>
        <longitude>150</longitude>
        <observation-time>15 sec</observation-time>
    </entry>
</root>

Lets say your area of expertise is birdspotting, and this is your class:
@JsonIgnoreProperties(ignoreUnknown = true)
public static class BirdSpotting {
    public Integer id;
    public Integer observation;
    public Double longitude;
    public String observationTime;
}

You can create a (reusable) ObjectParser, and apply it to your xml.
public List<BirdSpotting> getData(Document inputXml) {
    Parsing parsing = ParsingFactory.getInstance().create();

    ObjectParser<List<BirdSpotting>> parser =
        parsing.arr("/root/entry", parsing.obj()
            .attribute("id", "@id")
            .attribute("observation", "observation", parsing.with(Integer::parseInt))
            .attribute("longitude", "longitude", parsing.with(Double::parseDouble))
            .attribute("observationTime", "observation-time")
    ).as(BirdSpotting.class);

    List<BirdSpotting> spottings = parser.apply(inputXml);
    return spottings;
}

You can also parse into a single Birdspotting object by dropping the parsing.arr()part. Your parser will then be of type ObjectParser<Birdspotting> (without the List).
Output
BirdSpotting [id=1,observation=100,longitude=150.0,observationTime="15 sec"]


text:
Q: What do the braces "[ ]" in the reputation summary mean? I was taking a look at https://stackoverflow.com/reputation and I saw something like this:
 2   4391811 (10)
 2   4580949 (10)
 2   4580630 [2]

I noticed that I have just another reputation log with [ ] and I wonder what it means. Just curious.
In the case above, I didn't accept any answer nor get un-downvoted, so I'm not sure why I earned two points.

A: It means that you didn't earn the full reputation from that vote as you've hit the reputation cap for the day.
The exception to this is reputation earned from acceptances and bounties. Before the rep cap they are displayed with round brackets, after with square.
Before the rep cap:

2       291 (10)
   1       291 (15)
   2       291 (10)

and after:

2   2676798 [0]
   1   2676798 [15]
   2   2676798 [0]

Basically any reputation changing event after you've hit the rep cap will be displayed with square brackets. The number inside showing how much reputation (if any) you won or lost (i.e. a down-vote).


text:
Q: firebase undefined when working with ReactReduxFirebaseProvider Im trying to migrate from react-redux v2 to v3 and start to use the ReactReduxFirebaseProvider. But I don't know why I get:
Line 22:  'firebase' is not defined  no-undef

This is my code:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { createStore, applyMiddleware, compose } from 'redux'
import rootReducer from './store/reducers/rootReducer'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import { createFirestoreInstance, getFirestore } from 'redux-firestore'
import { ReactReduxFirebaseProvider, getFirebase } from 'react-redux-firebase'
import fbConfig from './config/fbConfig'

const store = createStore(rootReducer,
  compose(
    applyMiddleware(thunk.withExtraArgument({ getFirebase, getFirestore }))
  )
);

const rrfProps = {
  firebase,
  config: fbConfig,
  dispatch: store.dispatch,
  createFirestoreInstance
}

ReactDOM.render(
  <Provider store={store}>
    <ReactReduxFirebaseProvider {...rrfProps}>
      <App />
    </ReactReduxFirebaseProvider>
  </Provider>, document.getElementById('root'));
registerServiceWorker();

Can someone point me in the right direction of what I am doing wrong?

A: Include this in your code:
import firebase from 'firebase/app'


text:
Q: How to use ssl certificate with Swift Alamofire? I am upgrading my iOS apps with HTTPS web services.
I have upgrade my web server with SSL certificate. But don't know what to do from iOS code side?
Do I need to pass any certificate along with the web request?
I am using Alamofire for making web request.
Thanks

A: Simple googling would have given you so many results.
For example, https://infinum.co/the-capsized-eight/how-to-make-your-ios-apps-more-secure-with-ssl-pinning
func configureAlamoFireSSLPinning {
     let pathToCert = NSBundle.mainBundle().pathForResource(githubCert, ofType: "cer")
     let localCertificate:NSData = NSData(contentsOfFile: pathToCert!)!

     self.serverTrustPolicy = ServerTrustPolicy.PinCertificates(
            certificates: [SecCertificateCreateWithData(nil, localCertificate)!],
         validateCertificateChain: true,
         validateHost: true
     )

     self.serverTrustPolicies = [
         "your-api.com": self.serverTrustPolicy!
     ]

     self.afManager = Manager(
         configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
         serverTrustPolicyManager: ServerTrustPolicyManager(policies: self.serverTrustPolicies)
     )
 }

func alamoFireRequestHandler {
     self.afManager.request(.GET, self.urlTextField.text!)
         .response { request, response, data, error in
      // response management code
  }
}


text:
Q: AVAudioRecorder normalize volume I've got an app that records audio.  I'm wondering how I can increase the gain.  is there a way to normalize the audio or amplify it somehow?
thanks,
howie

A: Looks like I found a solution.  According to the documentation the AVAudioPlayer volume can be between 0.0 and 1.0.  Apparently it can be set to a value greater than 1.0.  By increasing the volume I was able to achieve the same desired result.  While it's not normalized, the gain is increased.

A: #import <AudioToolbox/AudioServices.h>

UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                             sizeof (audioRouteOverride),&audioRouteOverride);

It will play your sound in Speaker mode.


text:
Q: Recursive Function to Record Key path in a Python Dictionary good afternoon.
I'm hoping someone can assist me with this function I'm trying to define, I looked through already asked questions that were similar, but this is unfortunately still not clear to me.
My goal is to recursively go through a nested dictionary and record the keypath needed to reach each final key.
So if I have this dic for instance:
    example_dic = {
    "fruitType": 'apple',
    "orderNumber": 12345,
    "links": {
        "self": {
            "href": 'https://foo'
        }
    },
    "customerName": 'bob'
}

The desired output (which for now I'm just printing) would be something like
fruitType
orderNumber
links self href
customerName

This is what I've accomplished so far:
def get_key_path(to_find_keys, key_path):

for key in to_find_keys.keys():

    print key

    key_path.append(key) # Append to list
    try:
        get_key_path(to_find_keys[key], key_path) # About to call function recursively

    except AttributeError:

        print key_path # Found last key, print it.
        key_path = []  # Reset list

Right now it does find each last key in the dic successfully, but I'm having trouble resetting the list. If my dic has a lot of entries and nests, the list resets at the wrong moment.
I'm still learning a lot about Python (and programming in general) so maybe there's a fundamental element about recursion I'm missing.
Many thanks in advance for anyone that can help out!

A: You could make it a recursive generator.  Go throuth keys and values of the dictionary and recurse for values that are dictionaries. just yield the key for values that aren't dictionaries.
def keyPaths(d):
    for k,sd in d.items():
        if isinstance(sd,dict):
            yield from (f"{k} {sub}" for sub in keyPaths(sd))
        else:
            yield k

output:
example_dic = {
    "fruitType": 'apple',
    "orderNumber": 12345,
    "links": {
        "self": {
            "href": 'https://foo'
        }
    },
    "customerName": 'bob'
}

for path in keyPaths(example_dic):
    print(path)

fruitType
orderNumber
links self href
customerName


text:
Q: How the order of arguments works in a reduce helper method? // this is the array
var numbers = [10,20,30];
// Now I want to get the sum of all the elements of numbers array
// this will give 60
numbers.reduce(function(sum,number){
    return sum + number;
},0);

// this also gives 60
numbers.reduce(function(number,sum){
    return sum + number;
},0);

I am just learning ES6, I tried looking at MDN but couldn't find the explanation. I just want to know how javascript detects the argument with initial value to be zero and which it detects to be the array elements.
Or does it arbitrarily chooses the argument values.

A: According to MDN, the first argument will always be the sum/accumulator, and the second will be the value.
Both parameters have no inherit binding to a name, so you can name both the sum and the value whatever you wish.
In your example, the first one works probably as you expected, with the sum as the first parameter and the value as the second parameter. In your second example, it works the exact same way, the only difference being that you named the 'sum' as 'number' and the 'value' as 'sum'.
JS may be weird but it's not messing with your arguments in this case. You're just naming the arguments differently.

A: From MDN:

The first time the callback is called, accumulator and currentValue
  can be one of two values. If initialValue is provided in the call to
  reduce, then accumulator will be equal to initialValue, and
  currentValue will be equal to the first value in the array. If no
  initialValue is provided, then accumulator will be equal to the first
  value in the array, and currentValue will be equal to the second.
Note: If initialValue isn't provided, reduce will execute the callback
  function starting at index 1, skipping the first index. If
  initialValue is provided, it will start at index 0.

The first param, "sum", is the accumulator. The second param, currentValue, is "number".

A: Here's the syntax of the reduce method.
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

where, function is used to reduce the array and will be invoked for each array element.
This function uses first argument passed to it as an accumulator to store the result.
Each element of the array will be passed as the second argument to the function.
Just like other functions in JavaScript, the order of the parameters matter(not their name).
While these two parameters are required to be present in your function, it can have two more optional parameters, viz currentIndex and the array itself.
And finally, the optional initValue passes to reduce function will be used to initialize the accumulator.
You can read more about it here.


text:
Q: how use regex to get from specific point to end of text? I want to know what is the proper regular expression for that :
In an action unprecedented during 12 years of war in Afghanistan, the commandant of the Marine Corps is firing two top generals. See why:

Generals fired over Taliban attack
security.blogs.cnn.com
There were three investigations of the incident.

I want to do the following :
give me string starting of a tag which contains onmouseover="LinkshimAsyncLin.swap() in any position at properties area .. and end with the end of the remain string .. i mean from this a tag to end of the string
MY TRY :-
i used this pattern :
]*?onmouseover\\s*=\\s*['\"]([^'\"]*?)['\"][^>]*?/?>

it got successfully this part
i want to get also all remain tags and text to the end point
Note :
My friends, I know that using regex with html tag is very bad practice and i already have red that alot but i want that for special case
thank in advance :)

A: Is this what you want?
onmouseover.*


text:
Q: How to get input from dynamically created checkboxes and radio buttons in javascript? I need to dynamically create checkboxes and radio buttons in groups of data displayed, then I need to take the user choices and put them in variables.
I have made an example with a few checkboxes and radio buttons, but I don't have a clue how to actually get the input:
Here is the jsfidle

var t = document.getElementById("container");

var data1 = ['TV', 'Newspaper', 'Internet'];
var data2 = ['New York', 'Washington', 'Los Angeles'];

t.innerHTML += checkbutton(data1);
t.innerHTML += radiobutton(data2);

function checkbutton(d) {
  var output = "";

  for (var i = 0; i < d.length; i++) {
    output += '<input type="checkbox" value=' + d[i] + ' name="box2">' + '   ' + d[i] + '   ' + '

';
  }
  return output;
}

function radiobutton(d) {
  var output = "";

  for (var i = 0; i < d.length; i++) {
    output += '<input type="radio" value=' + d[i] + ' name="box2">' + '   ' + d[i] + '   ' + '

';
  }
  return output;
}

A: Like this?
Note the event listeners and the change of names
Also make sure you quote the names and values

function checkbutton(d) {
  var output = "";

  for (var i = 0; i < d.length; i++) {
    output += '<input type="checkbox" value="' + d[i] + '" name="box'+i+'">' + '   ' + d[i] + '   ' + '

';
  }
  return output;
}

function radiobutton(d) {
  var output = "";

  for (var i = 0; i < d.length; i++) {
    output += '<input type="radio" value="' + d[i] + '" name="rad">' + '   ' + d[i] + '   ' + '

';
  }
  return output;
}

window.addEventListener("load", function() {
  var t = document.getElementById("container");
  var b = document.getElementById("but");

  var data1 = ['TV', 'Newspaper', 'Internet'];
  var data2 = ['New York', 'Washington', 'Los Angeles'];

  t.innerHTML += checkbutton(data1);
  t.innerHTML += radiobutton(data2);

  t.addEventListener("change",function(e) {
    var tgt = e.target;
    if (["radio","checkbox"].indexOf(tgt.type) !=-1) { // only look at checkboxes and radios. Change if needed
      console.log(tgt.value);
    }
  });

  b.addEventListener("click",function() {
    var vars = {}
    t.querySelectorAll("input").forEach(inp => {
       if (inp.checked) vars[inp.name]=inp.value
    });
    console.log(vars);
  })

})

<button type="button" id="but">Click</button>

A: Using javascript you can query specific properties of html elements - like the radio buttons and the checkboxes.
To be able to do this, each element should have an unique id - so we can get an element using document.getElementById(id).
The other option is to get elements by their type e.g. document.getElementsByTagName("input"). This will return a html collection - an array - of all the input elements.
With a simple for-loop you can iterate over this array and using the .checked property you can find out if one of those input boxes is selected.

var t = document.getElementById("container");

var data1 = ['TV', 'Newspaper', 'Internet'];
var data2 = ['New York', 'Washington', 'Los Angeles'];

t.innerHTML += checkbutton(data1);
t.innerHTML += radiobutton(data2);

function checkbutton(d) {
  var output = "";

  for (var i = 0; i < d.length; i++) {
    output += '<input type="checkbox" value="' + d[i] + '" name="box2">' + '   ' + d[i] + '   ' + '

';
  }
  return output;
}

function radiobutton(d) {
  var output = "";

  for (var i = 0; i < d.length; i++) {
    output += '<input type="radio" value="' + d[i] + '" name="box2">' + d[i] +  '

';

  }
  return output;
}

function check() {
  var elements = document.getElementsByTagName("input");
  for (var a = 0; a < elements.length; a++) {
        if (elements[a].checked) {
          console.log(elements[a].value + " is checked");
        }
  }
}

<button id="check" onclick="check()">
check
</button>


text:
Q: Pattern matching for properties in a Java-based Spring configuration Is it possible to inject a list of properties matching a specific reg exp pattern from Java-based Spring 4 configuration file.
For example given a property file that contains:
prefix.prop1=value1
prefix.prop2=value2
prefix.prop3=value3
other.property=someothervalue

Ideally something I would like to inject the prefix.* properties into a bean - as a map for example.
@Configuration
public class AppConfiguration{

    public valueMap(@Value(?prefix.*?) Map<String, String> propertyMap) {

        //where propertyMap would contain key/values :
        //prop1, value1 ; prop2, value2 ; prop3, value3

    }
}

I've been looking at Spring EL expressions with no success also at customizing the PropertyPlaceholderConfigurer.
Ideally I don't want to read the file again and process it again if Spring can do it for me.

A: Here is a workaround:
Extend PropertyPlaceholderConfigurer and add a method which gives you the result of mergeProperties().
You can then inject this new bean into your AppConfiguration, iterate over the properties and filter those with the prefix you want.


text:
Q: Cannot upload file to Azure blob storage using Azure functions Node NOTE: There is no issue here, The issue was with my functions.json script file location. It was pointing to an old script file. The minute I pointed to a new one, it started working.
I am not sure why this is happening, I have a try-catch block and the function never hits the catch block but the image I am trying upload never shows up in the container.
I am new to NODEJS. Since I cant achieve the same thing using C# functions, I decided to write it in the node.
Problem: Azure function Service bus topic trigger, take the message payload and grabs a screenshot of the page using puppeteer. The output from the buffer is in form of the buffer, I am trying to upload this to Azure storage blob.
import { AzureFunction, Context } from "@azure/functions";
import { ServiceBusMessage } from "@azure/service-bus";
import * as puppeteer from 'puppeteer';
import * as BlobServiceClient from "azure-storage";
import { Readable } from 'stream';

const serviceBusTopicTrigger: AzureFunction = async function (context: Context, mySbMsg: ServiceBusMessage): Promise<void> {
    try {
        const promotionId = context.bindingData.userProperties.promotionId;
        context.log('Player Screen Grabber ServiceBus topic trigger function processing message started', promotionId);
        const playerURL = process.env['playerURL'] + promotionId + '/';
        let browser = await puppeteer.launch({ headless: true });
        let page = await browser.newPage();
        await page.goto(playerURL, { waitUntil: 'networkidle2' });
        await page.setViewport({ width: 1920, height: 1080 });
        const screenshotBuffer = await page.screenshot({
            encoding: 'binary'
        });
        await page.close();
        await browser.close();
        const newPlayerScreenShotStream = new Readable({
            read() {
                this.push(screenshotBuffer);
            },
        });
        var fileName = promotionId + ".png";
        context.bindings.fileName = fileName;
        context.bindings.storage = screenshotBuffer;
        context.done();
        context.log('Player Screen Grabber ServiceBus topic trigger function processing message ended', promotionId);
    }
    catch (error) {
        throw error;
    }
};

A: According to your infromation you provide, you want to use dymaic name in Azure function blob storage output bining. If so, we cannot use context.bindings.<> to implement it. For more details, please refer to here and here
If you want to implement it, you have the following two choices.

*

*Using Azure Functions binding expression patterns
if you define the message's body as json, we can directly read the value with binding expression in function
For example
My message

function.json
{
  "bindings": [
    {
      "name": "mySbMsg",
      "type": "serviceBusTrigger",
      "direction": "in",
      "topicName": "",
      "subscriptionName": "",
      "connection": "MYSERVICEBUS"
    },
    {
      "type": "blob",
      "direction": "out",
      "name": "outputBlob",
      "path": "outcontainer/{fileName}.png",
      "connection": "AzureWebJobsStorage"
    }
  ],
  "scriptFile": "../dist/ServiceBusTopicTrigger1/index.js"
}

Function code
import { AzureFunction, Context } from "@azure/functions";
import * as puppeteer from "puppeteer";

const serviceBusTopicTrigger: AzureFunction = async function (
  context: Context,
  mySbMsg: any
): Promise<void> {
  try {
    context.log("ServiceBus topic trigger function processed message", mySbMsg);
    const promotionId = context.bindingData.userProperties.promotionId;

    const playerURL =
      "https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?tabs=v2";
    let browser = await puppeteer.launch({ headless: true });
    let page = await browser.newPage();
    await page.goto(playerURL, { waitUntil: "networkidle2" });
    await page.setViewport({ width: 1920, height: 1080 });
    const screenshotBuffer = await page.screenshot({
      encoding: "binary",
    });
    await page.close();
    await browser.close();
    context.bindings.outputBlob = screenshotBuffer;
  } catch (error) {
    throw error;
  }
};

export default serviceBusTopicTrigger;

*

*Using Azure Blob storage sdk
Function code

import { AzureFunction, Context } from "@azure/functions";
import * as puppeteer from "puppeteer";
import { BlobServiceClient } from "@azure/storage-blob";
const serviceBusTopicTrigger: AzureFunction = async function (
  context: Context,
  mySbMsg: any
): Promise<void> {
  try {
    context.log("ServiceBus topic trigger function processed message", mySbMsg);
    const promotionId = context.bindingData.userProperties.promotionId;

    const playerURL =
      "https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?tabs=v2";
    let browser = await puppeteer.launch({ headless: true });
    let page = await browser.newPage();
    await page.goto(playerURL, { waitUntil: "networkidle2" });
    await page.setViewport({ width: 1920, height: 1080 });
    const screenshotBuffer = await page.screenshot({
      encoding: "binary",
    });
    await page.close();
    await browser.close();
    // the storage account connection string
    const constr = process.env["AzureWebJobsStorage"];
    const blobserviceClient = BlobServiceClient.fromConnectionString(constr);
    const containerClient = blobserviceClient.getContainerClient("output");
    const blob = containerClient.getBlockBlobClient(`${promotionId}.png`);
    await blob.uploadData(screenshotBuffer);
  } catch (error) {
    throw error;
  }
};

export default serviceBusTopicTrigger;

My message

Result


text:
Q: How to investigate display problems? I'm running Kubuntu 15.04 and from time to time my display turns completely black. The only thing then that's visible to me is the mouse pointer and after pressing ALT+F2 the "command run dialog".
Since I'm new to Kubuntu I'm not sure where to start looking for hints on the problem that would narrow down possible problem sources. Which log files etc. do I have to look for?

A: Today I encountered the same problem.
Let's do this:

*

*Press Ctrl + Alt + F1

*Log in as root

*Type startx and hit Enter
It should tell you if the X has encountered any problem and where the log file is.
If the X is already running, let's restart it using sudo service sddm restart


text:
Q: Why is my program behaving oddly I have just started work on asmall program that sends text over net (TON) I havent quite started but when I compile this happens when I have a space in my name
Username: Knight Hawk3
LAN (1) or Net (0):
(Here it wont let me enter data)
Process returned 1 (0x1)   execution time : 3.670 s
Press any key to continue.

Here is what normally (should) happen
Username: Knight
LAN (1) or Net (0):
1

Process returned 1 (0x1)   execution time : 2.134 s
Press any key to continue.

Here is my source
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <iostream>
#include <string>

using namespace std;

bool firstrun = true;

int main()  {

    if (firstrun) {
        cout << "Username: ";
        string name = "";
        cin >> name;
        while (name == "") {
            cout << "Invalid Enter a new name: ";
            cin >> name;
            cout << "\n";
        }
    }
    cout << "LAN (1) or Net (0): ";
    int type;
    cout << "\n";
    cin >> type;
    while (type < 0) {
            cout << "Invalid LAN (1) or Net (0): ";
            cin >> type;
    }

    return true;
}

I am running WIN7, Using Code::Blocks
Why is this happening with a space?

A: std::cin reads till the first space but keeps the rest in buffer, which will be used on the following std::cins.
If you want to read till the first '\n'(hitting enter) you have to replace std::cin with
std::getline(std::cin, name);


text:
Q: Is it possible to create container in multiple host using a single docker compose file? I have to create containers in multiple host. I have a dockerfile for each container. I found that docker-compose can be used to run multiple containers from a single yaml file. I have to run containerA in HostA, containerB in HostB and so on.. is it possible to achieve this using docker-compose ? or what is the best way to create container in different host using the dockerfile.

A: No, docker-compose alone won't achieve this. Managing containers across multiple hosts is generally the job of schedulers. The Docker Ecosystem: Scheduling and Orchestration  is an older article, but should give an introduction.
The scheduler provided by Docker is called Swarm. Use Compose with Swarm is a good place to start to understand how to use them together.

This part of the answer is time limited, but during Mentor Week there are a few free courses you can take to learn more about Swarm. In your case Operations Beginner and Intermediate may be interesting.

A: The answer is no.

*

*Docker compose is for multiple containers on a single host.

*Docker swarm is for container(s) at a cluster level.

And, you cannot decide where to run a container, only the docker swarm scheduler decides, but you can influence it. Check the link below, and focus on image affinity. i.e. you put specific images on only some nodes and configure the scheduler to use image affinity.

*

*Filters - Which hosts are chosen

*Strategies - ranking the nodes.

docker filters
Here is a script to create a docker swarm cluster. Play with until you learn the process itself
id=$(docker run swarm create)
docker-machine create -d virtualbox --swarm --swarm-master --swarm-discovery token://$id swarm-master
docker-machine create -d virtualbox --swarm --swarm-discovery token://$id node1
docker-machine create -d virtualbox --swarm --swarm-discovery token://$id node2
docker-machine create -d virtualbox --swarm --swarm-discovery token://$id node3
docker-machine create -d virtualbox --swarm --swarm-discovery token://$id node4

Here is what happened:

*

*A cluster with one master and four nodes is created.

*run eval $(docker-machine env --swarm swarm-master) to configure your shell.

From this point on, creating and running containers is as usual.
running docker ps would show you where the container is running.

A: Docker-compose is exactly what you need. It is a tool for defining and running multi-container Docker applications. A good starting point is official documentation: https://docs.docker.com/compose/gettingstarted/