text:
Q: Haproxy multiple frontend/IP wrong backend I am facing some logical error when using the following configuration. In the configuration, I am trying to integrate a single haproxy server servicing for both Microsoft Exchange as well as the SkypeForBusiness.
global

        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
        stats timeout 30s
        user haproxy
        group haproxy
        daemon

        ca-base /etc/ssl/certs
        crt-base /etc/ssl/private
        ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
        ssl-default-bind-options no-sslv3
#!!!ENABLIING_MULTITHREADING!!!
  nbproc 1
  nbthread 8
  cpu-map auto:1/1-8 0-7
#!!!!

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
#!!!!!!!
        option  forwardfor      except 127.0.0.0/8
        option  redispatch
        retries 3
        timeout http-request    10s
        timeout queue   1m
        timeout connect 10s
        timeout client  15m # this value should be rather high with Exchange
        timeout server  15m # this value should be rather high with Exchange
        timeout http-keep-alive 10s
        timeout check   10s
        maxconn 100000
#!!!!!!!
        errorfile 400 /etc/haproxy/errors/400.http
        errorfile 403 /etc/haproxy/errors/403.http
        errorfile 408 /etc/haproxy/errors/408.http
        errorfile 500 /etc/haproxy/errors/500.http
        errorfile 502 /etc/haproxy/errors/502.http
        errorfile 503 /etc/haproxy/errors/503.http
        errorfile 504 /etc/haproxy/errors/504.http
#!!!!HAPROXY_STATS!!!!!!
listen  HAPROXY_STATS
        bind 0.0.0.0:1936
        stats enable
        stats refresh 10s
        stats show-node
        stats auth myoo:wuff
        stats hide-version
        stats uri  /stats_haproxy
        log global
        mode http
        maxconn 10
#!!!!!!!!!!!!!!!!!!!!!!!
#!!!!!!!!!!SKYPE_CONFIGURATION!!!!
frontend FE_SKYPE2015
        mode tcp
        bind 192.168.40.65:80
        bind 192.168.40.65:443 ssl crt /etc/ssl/certs/contoso_com_PKI.pem
        default_backend SKP
backend SKP
        mode tcp
        balance roundrobin
        default-server inter 5s fall 3 rise 2
        server SKP_FE01 192.168.40.149:4443 check ssl verify none
        server SKP_FE02 192.168.40.150:4443 check ssl verify none
        server SKP_FE03 192.168.40.151:4443 check ssl verify none
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!!!!!!!EXCHANGE_CONFIGURATION!!!!
frontend FE_EXCHANGE2019
        http-response set-header X-Frame-Options SAMEORIGIN
        http-response set-header X-Content-Type-Options nosniff
        mode http
        bind 192.168.40.64:80
        bind 192.168.40.64:443 ssl crt /etc/ssl/certs/contoso_com_PKI.pem
        redirect scheme https code 301 if !{ ssl_fc }   # redirect 80 -> 443 (for owa)
        acl AUTODISCOVER url_beg /Autodiscover
        acl AUTODISCOVER url_beg /autodiscover
        acl MAPI url_beg /mapi
        acl MAPI url_beg /Mapi
        acl MAPI url_beg /MAPI
        acl RPC url_beg /rpc
        acl RPC url_beg /RPC
        acl RPC url_beg /Rpc
        acl OWA url_beg /owa
        acl OWA url_beg /OWA
        acl OWA url_beg /Owa
        acl EAS url_beg /Microsoft-Server-ActiveSync
        acl EAS url_beg /microsoft-server-activesync
        acl ECP url_beg /ecp
        acl ECP url_beg /Ecp
        acl ECP url_beg /ECP
        acl EWS url_beg /EWS
        acl EWS url_beg /ews
        acl EWS url_beg /Ews
        acl OAB url_beg /OAB
        acl OAB url_beg /Oab
        acl OAB url_beg /oab
        acl IS_ROOT path -i /
        acl IS_DOMAIN_MAIN hdr(host) -i mail.contoso.com
        redirect code 301 location http://mail.contoso.com/owa if IS_DOMAIN_MAIN IS_ROOT
        use_backend BE_EXCHANGE2019_AUTODISCOVER if AUTODISCOVER
        use_backend BE_EXCHANGE2019_MAPI if MAPI
        use_backend BE_EXCHANGE2019_RPC if RPC
        use_backend BE_EXCHANGE2019_OWA if OWA
        use_backend BE_EXCHANGE2019_EAS if EAS
        use_backend BE_EXCHANGE2019_ECP if ECP
        use_backend BE_EXCHANGE2019_EWS if EWS
        use_backend BE_EXCHANGE2019_OAB if OAB
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!!!!!!!!!!!!!!BACKEND_SECTION!!!!
backend BE_EXCHANGE2019_AUTODISCOVER
        mode http
        balance roundrobin
        option httpchk GET /autodiscover/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none

backend BE_EXCHANGE2019_MAPI
        mode http
        balance roundrobin
        option httpchk GET /mapi/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none

backend BE_EXCHANGE2019_RPC
        mode http
        balance roundrobin
        option httpchk GET /rpc/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none

backend BE_EXCHANGE2019_OWA
        mode http
        balance roundrobin
        option httpchk GET /owa/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none

backend BE_EXCHANGE2019_EAS
        mode http
        balance roundrobin
        option httpchk GET /microsoft-server-activesync/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none

backend BE_EXCHANGE2019_ECP
        mode http
        balance roundrobin
        option httpchk GET /ecp/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none

backend BE_EXCHANGE2019_EWS
        mode http
        balance roundrobin
        option httpchk GET /ews/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none

backend BE_EXCHANGE2019_OAB
        mode http
        balance roundrobin
        option httpchk GET /oab/healthcheck.htm
        option log-health-checks
        http-check expect status 200
        default-server inter 5s fall 3 rise 2
        server MBX01 192.168.40.97:443 cookie MBX01 check ssl verify none
        server MBX02 192.168.40.98:443 cookie MBX02 check ssl verify none
        server MBX03 192.168.40.99:443 cookie MBX03 check ssl verify none
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

The problem is when I am browsing the https://meet.contoso.com, with the IP address of 192.168.40.65, it shows the OWA content on the 192.168.40.64 server and the url is being redirected to https://meet.constoso.com/owa where it should serve the 192.168.40.149-151 in 4443. any help is much appreciated. Haproxy version: OS == Debian 10
HA-Proxy version 1.8.19-1+deb10u2 2020/04/01
Copyright 2000-2019 Willy Tarreau <willy@haproxy.org>

Build options :
  TARGET  = linux2628
  CPU     = generic
  CC      = gcc
  CFLAGS  = -O2 -g -O2 -fdebug-prefix-map=/build/haproxy-ap5Gic/haproxy-1.8.19=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fno-strict-aliasing -Wdeclaration-after-statement -fwrapv -Wno-format-truncation -Wno-null-dereference -Wno-unused-label
  OPTIONS = USE_GETADDRINFO=1 USE_ZLIB=1 USE_REGPARM=1 USE_OPENSSL=1 USE_LUA=1 USE_SYSTEMD=1 USE_PCRE2=1 USE_PCRE2_JIT=1 USE_NS=1

Default settings :
  maxconn = 2000, bufsize = 16384, maxrewrite = 1024, maxpollevents = 200

Built with OpenSSL version : OpenSSL 1.1.1d  10 Sep 2019
Running on OpenSSL version : OpenSSL 1.1.1d  10 Sep 2019
OpenSSL library supports TLS extensions : yes
OpenSSL library supports SNI : yes
OpenSSL library supports : TLSv1.0 TLSv1.1 TLSv1.2 TLSv1.3
Built with Lua version : Lua 5.3.3
Built with transparent proxy support using: IP_TRANSPARENT IPV6_TRANSPARENT IP_FREEBIND
Encrypted password support via crypt(3): yes
Built with multi-threading support.
Built with PCRE2 version : 10.32 2018-09-10
PCRE2 library supports JIT : yes
Built with zlib version : 1.2.11
Running on zlib version : 1.2.11
Compression algorithms supported : identity("identity"), deflate("deflate"), raw-deflate("deflate"), gzip("gzip")
Built with network namespace support.

Available polling systems :
      epoll : pref=300,  test result OK
       poll : pref=200,  test result OK
     select : pref=150,  test result OK
Total: 3 (3 usable), will use epoll.

A: sorry, the root cause was the the 192.168.40.65 routing issue. the IP address were duplicated.


text:
Q: Manually calculating PCA rotation using original data and PCA projections (scores) Is there any possibility of calculating PCA rotation similar to R's prcomp function, by that I mean if I do the following
log.ir <- log(iris[, 1:4])
ir.species <- iris[, 5]
ir.pca <- prcomp(log.ir)$x

where ir.pca is a 150 by 4 (row by column) matrix, can I use this information to calculate rotation without using prcomp(log.ir)$rotation?

A: The principal components of your $N\times p$ (centered) data matrix $\mathbf{X}$ are given by
$$
\mathbf{Z} = \mathbf{X V}
$$
So you have that
$$
\mathbf{V}' = \mathbf Z'\mathbf X (\mathbf X'\mathbf X) ^ {-1}.
$$
You can compare the output of the second and third command:
X <- matrix(rnorm(1000), nrow = 100) # simulate some data
prcomp(X)$rotation
t(t(prcomp(X)$x) %*% X %*% solve(cov(X)))

redpajama_set_name: RedPajamaStackExchange


text:
Q: template many-to-many id django how can i get an id of a many-to-many object?
i have three models, media, image and slideshow.
how can i get the id of a media through my slideshow object?
class Media(models.Model):
    CONTENT_TYPE_CHOICES = (
        ('photos', _('Photos')),
        ('videos', _('Videos')),
        ('audio', _('Audio')),
        ('Object360', _('360 Object')),
        ('Object3D', _('3D Object')),

    )

    source = models.FileField(upload_to='magazine')
    filename = models.CharField(max_length=50)
    content_type = models.CharField(max_length=10, choices=CONTENT_TYPE_CHOICES)
    created = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = _('Media')
        verbose_name_plural = _('Media')

class ImageComponent(BaseComponent):
    media = models.ForeignKey(Media)
    is_embed = models.BooleanField(default=True)
    is_slideshow =models.BooleanField(default=False)

    def __unicode__(self):
        return u'Image Component'

class SlideshowComponent(BaseComponent):
    image = models.ManyToManyField(ImageComponent)
    is_autoplay = models.BooleanField(default=True)
    is_embed = models.BooleanField(default=True)

    def __unicode__(self):
        return u'Slideshow Component'

in my view.py i have: slideshow = SlideshowComponent.objects.all()
in template i try:
{% for slide in slideshow %}
{{ slide.image.media.id}}

but not works..
edit: how can aceess in view.py to the slideshow object through the media.id

A: Well, since image is a ManyToManyField it links to many images (it should really be called 'images'). So, you'll need to iterate through it:
{% for slide in slideshow %}
    {% for image in slide.image.all %}
    {{ image.media.id }}
    {% endfor %}
{% endfor %}


text:
Q: Make user create 775 permission folders I typed out the command chfn -o umask=002 souser and expected that souser user would create folders with 775 permission then but he did not. How to get that each new folder created by a certain user would have write  permission for the group? Here you are my test:
s@lokal:~$ sudo adduser souser
Adding user `souser' ...
Adding new group `souser' (1002) ...
Adding new user `souser' (1002) with group `souser' ...
The home directory `/home/souser' already exists.  Not copying from `/etc/skel'.
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for souser
Enter the new value, or press ENTER for the default
  Full Name []:
  Room Number []:
  Work Phone []:
  Home Phone []:
  Other []:
Is the information correct? [Y/n] y
s@lokal:~$ sudo usermod -aG sudo souser

s@lokal:~$ su souser
Password:
souser@lokal:/home/s$ cd
souser@lokal:~$ mkdir test
souser@lokal:~$ ls -ld test/
drwxr-xr-x 2 souser souser 4096 Sep  3 14:23 test/

souser@lokal:~$ chfn -o umask=002
chfn: Permission denied.
souser@lokal:~$ sudo chfn -o umask=002 souser
souser@lokal:~$ mkdir test2
souser@lokal:~$ ls -ld test2
drwxr-xr-x 2 souser souser 4096 Sep  3 14:24 test2
souser@lokal:~$ sudo cat /etc/passwd |grep souser
souser:x:1002:1002:,,,,umask=002:/home/souser:/bin/bash
souser@lokal:~$

Update #1
After relogin is the same:
souser@lokal:~$ mkdir test3
souser@lokal:~$ ls -ld test3
drwxr-xr-x 2 souser souser 4096 Sep  3 14:42 test3
souser@lokal:~$

Update #2
This also did not help:
s@lokal:~/Dropbox$ su - souser
Password:
souser@lokal:~$ mkdir test4
souser@lokal:~$ ls -ld test4
drwxr-xr-x 2 souser souser 4096 Sep  3 14:51 test4
souser@lokal:~$

NOTE: The distro is Debian 9.

A: The possibilities to set umask's strongly differ between Linux and Unix distro's.
The way you are trying to do it (in the "gecos" field in /etc/passwd) depends on pam_umask being installed and configured. AFAIK this is at least the case by default on Debian and probably distro's based on Debian like Ubuntu, Mint, etc...
Without pam_umask, you could put a line umask 002 in the shell's profile or rc-file in the users home directory (e.g.: .bashrc or .profile). Or something like this in the system-wide config file, e.g. /etc/profile (for sh, and bash) or /etc/bashrc (for bash only):
if [ "$USER" = "souser" ] ; then
    umask 0002
else
    umask 0022
fi

You can check if it was successful either way with just a plain umask command which will output the current effective umask.
Note that it is still up to the application to actually set the permissions. If you use some other program or command which in its code hardwires to never set group write permissions on folder it creates, you'll either have to change the code of that program or set permissions manually afterwards. That is just the way UNIX/Linux is supposed to work.


text:
Q: Connected host failed to respond (internal NAT address) I'm writing my first C# web application that connects to an XML based service.  It requires that I present a certificate and feed the XML stream.  It seems to authenticate properly but then it gives the following error:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 10.1.10.4:3128

The funny thing is that I'm not on a proxy or anything like that.  I'm connecting directly to the internet.  At one point I we did use a proxy that with internal NAT address.
So my question is: Does Visual Studio have some sort of default proxy setting that I need to change?  This IP is no longer used for anything, so I know that I don't need to use any proxy authentication code.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Uri requestURI = new Uri("*site omitted*");

            //Create the Request Object
            HttpWebRequest pageRequest = (HttpWebRequest)WebRequest.Create(requestURI);

            //After installing the cert on the server export a client cert to the working directory as Deluxe.cer
            string certFile = "*certificate omitted*";
            X509Certificate cert = X509Certificate.CreateFromCertFile(certFile);

            //Pull in your Data, if it is from an external xml as below or create an xml string with variables if a dynamic post is required.
            string xmlPath = "*XML omitted*";
            System.Xml.XmlDocument passXML = new System.Xml.XmlDocument();
            passXML.Load(xmlPath);

            //XML String with the data needed to pass
            string postData = passXML.OuterXml;

            //Set the Request Object parameters
            pageRequest.ContentType = "application/x-www-form-urlencoded";
            pageRequest.Method = "POST";
            pageRequest.AllowWriteStreamBuffering = false;
            pageRequest.AllowAutoRedirect = false;
            pageRequest.ClientCertificates.Add(cert);
            postData = "xml_data=" + Server.UrlEncode(postData);
            pageRequest.ContentLength = postData.Length;

            //Create the Post Stream Object
            System.IO.StreamWriter postStream = new System.IO.StreamWriter(pageRequest.GetRequestStream());

            //Write the data to the post stream
            postStream.Write(postData);
            postStream.Flush();
            postStream.Close();

            //Set the Response Object
            HttpWebResponse postResponse = (HttpWebResponse)pageRequest.GetResponse();

A: The only way you're going to find out what's going on is to look at the network traffic with Fiddler or maybe Microsoft Network Monitor.


text:
Q: How to Output CSV and Tab Delimited files With Different Fields in SSRS Is there a way to output two separate data outputs in SSRS 2008 R2 from the report server with different columns?
Thanks in advance.

A: You could investigate using XSLT to transform the XML output into a desired format. This is really the only option I know of, other than making another bespoke report with the actual output you want.
http://msdn.microsoft.com/en-us/library/ms159716(v=sql.90).aspx
(Probably more up to date links out there, just Google/Bing "SSRS XSLT" etc)


text:
Q: Silverlight Refresh data I don't know what is the best way to force a browser refresh when using silverlight.
The scenario is like this:

*

*We have a silverlight application hosted on IIS

*Two users opens the same page and that page contains a grid with some records.

*Only one of the users modify one record and save the data in the database

How can the other user see that the data has been modified unless he refreshes the page manually?
Should I implement some automatic refresh?
Thanks in advance

A: I would think long and hard about the requirements here before you open up a can of worms.  Is the grid editable?  With the automatic refresh idea what happens to the user who is in the middle of an edit?  Think about alternatives.  Could you possilbly check whether the data has changed at the point of saving data and then provide an appropriate message to the user?  If you want the data to automatically refresh you are going to get into looking at server to client notifications e.g WCF duplex calls or constant polling and refreshing of the underlying bound observablecollection


text:
Q: how to pass session id in the email notification - laravel Am trying to login users through a link in email sent after registration.
In my registration method I have the following code
$user_id = $user->id;
Session::put('userId', $user_id);
Auth::login($user_id);
Auth::attempt(['email' => $request->email, 'password' => $request->password]);
$email = $request->email;
if($email != ''){
  $send = app()->make(\Snowfire\Beautymail\Beautymail::class);
  $send->send('emails.welcome', compact('r_message', 'username', 'passwordcode', 'user_id'), function($r_message) use ($email, $username) {
  $r_message
  ->from('adun@demovalley.com')
  ->to($email, $username)
  ->subject('Welcome to Admiralty University!');
  });
}

while I passed the session like this on the like
Click here

My route
Route::get('jamb/{user}', ['as' => 'jamb', 'uses' => 'CandidateController@jamb']);

but I get this error message.
 ErrorException (E_ERROR)
 Route [jamb/66] not defined.

How can I make this to work?

A: Try to fix your routing to how you declared it to your configuration.
This:

must be like

wherein in your web.php you declared something like:
Route::get('jamb/{user}', 'yourController@yourMethod')->name('jamb');


text:
Q: ngForOf' since it isn't a known property of 'tr' I've been stuck since this afternoon, and I don't understand my problem.
I created a service, in this file I have an object and I would like to display the data in a loop.
I have an error message:
NG0303: Can't bind to 'ngForOf' since it isn't a known property of 'tr'.

img
I searched on google, and it is proposed to add imports: [BrowserModule] in app.module.ts.
The problem is not solved...
I removed the Portfolio component 10 times and redid the code and still have the same problem.
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

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

portfolio.component.html

Portfolio page

               Name
               Firstname
               Address
               City
               Country

                {{ portfolio.portfolioName }}

portfolio.component.ts
import { Component, OnInit } from '@angular/core';
import { PortfolioService } from './portfolio.service';

@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.css']
})
export class PortfolioComponent implements OnInit {

  portfolios : any;

  constructor(private servicePortfolio: PortfolioService) { }

  ngOnInit(): void {
    this.portfolios = this.servicePortfolio.portfolios;
    console.log("Test => " + JSON.stringify(this.portfolios));
  }

}

img
portfolio.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class PortfolioService {

  portfolios = [
    {
      portfolioName: 'Lenglet',
      portfolioFirstName: 'Alison',
      portfolioAddress: '15, Fleurs',
      portfolioCity: '1300',
      portfolioCountry: 'Alost',
    },
    {
      portfolioName: 'Rome',
      portfolioFirstName: 'Fredy',
      portfolioAddress: '15, Cerises',
      portfolioCity: '1700',
      portfolioCountry: 'Anvers',
    },
  ]

  constructor() { }
}

I don't retrieve the datas in the portfolio page.
img
I can share you the problem on Stackblitz.
If you find the problem, I will be infinitely grateful to you.

A: If you declare your portfolioComponent in app.module.ts its going to work. What that means is your portfolio.module.ts doesnt seems to be imported.
Your routing is weird and not really working properly, your path don't work in multiple places so I would start by making sure your routing is properly working and then make sure you are importing your module correctly(lazy loaded or not).
You can see that the module is not imported by trying to import BrowserModule in portfolio.module.ts and not having an error telling you its already imported.

A: Quick solution:
Add PortfolioComponent in AdministrationModule like this
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdministrationRoutingModule } from './administration-routing.module';
import { AdministrationComponent } from './administration.component';
import { PortfolioComponent } from './views/portfolio/portfolio.component';

@NgModule({
  imports: [CommonModule, AdministrationRoutingModule],
  declarations: [AdministrationComponent, PortfolioComponent],
})
export class AdministrationModule {}

Explanation:
The component PortfolioComponent was not in the declarations of the administration.module.ts the rule is:

*

*if you use a component in another component

*They have to be in the same module OR the module in which the parent component is must import the child's component

in your case, I don't think you need a module for PortfolioComponent it's just a component.
it should be working in stackBlitz


text:
Q: Как объединить два разных массивав один? Есть два массива
Первый массив
    array
      0 =>
        array (size=4)
          'bonus' => string '5.625' (length=5)
          'date' => string '2016-01' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '1' (length=1)
      1 =>
        array (size=4)
          'bonus' => string '2.5' (length=3)
          'date' => string '2016-02' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '2' (length=1)
      2 =>
        array (size=4)
          'bonus' => string '2.5' (length=3)
          'date' => string '2016-08' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '8' (length=1)
      3 =>
        array (size=4)
          'bonus' => string '10.625' (length=6)
          'date' => string '2016-08' (length=7)
          'year' => string '2016' (length=4)
          'month' => null
      4 =>
        array (size=4)
          'bonus' => string '22.125' (length=6)
          'date' => string '2016-08' (length=7)
          'year' => null
          'month' => null

Второй массив
    array
      0 =>
        array (size=4)
          'amount' => string '5' (length=1)
          'date' => string '2016-07' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '7' (length=1)
      1 =>
        array (size=4)
          'amount' => string '6' (length=1)
          'date' => string '2016-08' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '8' (length=1)
      2 =>
        array (size=4)
          'amount' => string '21' (length=2)
          'date' => string '2016-08' (length=7)
          'year' => string '2016' (length=4)
          'month' => null
      3 =>
        array (size=4)
          'amount' => string '21' (length=2)
          'date' => string '2016-08' (length=7)
          'year' => null
          'month' => null

Необходимо объединить массивы, что бы получилось следующим образом
    array
      0 =>
        array (size=4)
          'amount' => string '0' (length=1)
          'bonus' => string '5.625' (length=5)
          'date' => string '2016-01' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '1' (length=1)
      1 =>
        array (size=4)
          'amount' => string '0' (length=1)
          'bonus' => string '2.5' (length=3)
          'date' => string '2016-02' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '2' (length=1)
      2 =>
        array (size=4)
          'amount' => string '5' (length=1)
          'bonus' => string '0' (length=3)
          'date' => string '2016-07' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '7' (length=1)
      3 =>
        array (size=4)
          'amount' => string '6' (length=1)
          'bonus' => string '2.5' (length=3)
          'date' => string '2016-08' (length=7)
          'year' => string '2016' (length=4)
          'month' => string '8' (length=1)
      4 =>
        array (size=4)
          'amount' => string '21' (length=1)
          'bonus' => string '10.625' (length=6)
          'date' => string '2016-08' (length=7)
          'year' => string '2016' (length=4)
          'month' => null
      5 =>
        array (size=4)
          'amount' => string '21' (length=1)
          'bonus' => string '22.125' (length=6)
          'date' => string '2016-08' (length=7)
          'year' => null
          'month' => null

Размеры массивов постоянно разные. Всю голову уже сломал, не могу понять как их объединить таким образом.

A: если вам необходимо слить оба массива в один нужно использовать php функцию array_merge
Вот тут есть документация - array_merge

A: Вам необходим функция array_map. В callback функции сливайте оба вложенных массива в один. Подробнее тут: http://php.net/manual/ru/function.array-map.php


text:
Q: select only un-selected grids using jquery ui I am using selectable jquery ui for selecting grids(5000 grids in a page), the code is bellow:
     $( ".sell-grid" ).selectable({
    // cancel:'div.al-selected',
    // filter: "div.al-unselected",
    // disabled: false,

    stop: function() {
        var pixed_selected  = $( "#pixed_selected" ).empty();
        var tpixel          =   $("#tpixel").empty();
        var totalPrice      =   $("#totalPrice").empty();
        var tprice          =   $("#tprice").empty();
        var count = 0;
        var SelectedPrice   =   0;

        $( ".ui-selected", this ).each(function() {

            var index = $( "#selectable li" ).index( this );
            count ++ ;
            var id = $(this).attr('id');
            selectedpixel.push(id);

        });
        SelectedPrice = (count * 20);

        tpixel.val(count);
        pixed_selected.html(count);

        tprice.val(SelectedPrice);
        totalPrice.html(SelectedPrice);
    }

});

using above code when i select the grid it is also selecting previous selected grid.
Problem is that, i want to stop grid selection if previously selected grids meat
Answer if any one knows.


text:
Q: Can I get a List from an object, add a String to it, and set it back to the object in one line? I was wondering if one can get a List from an object, add an item to it, and set the List to the object in one line.
I would normally do it this way:
List<String> tempList = someObject.getList();
tempList.add("some string value");
someObject.setList(tempList);

What I tried doing was this:
someObject.setList(someObject.getList().add("some string value"));

But then I realized that the method add() would return a boolean while the method setList() takes a List<String>
Any ideas?

A: As far as I know there is no nice way to do this in one line.
If you need to do this a lot, you could modify the class of someObject to have an addItem method to do this directly.
Alternatively, if you cannot modify the class, you could write a method for adding to a list and returning the list:
static <E> List<E> add(List<E> list, E extra) {
    list.add(extra);
    return list;
}

A: Assuming you aren't returning a copy in getList it should be the same reference, so you can say
someObject.getList().add("some string value");

And you should not need to setList back, because there is only one List.

A: Just because you can do something in one statement, doesn't mean you should!
But it's certainly possible if you don't mind abusing the streams a little bit:
    Stream.of(someObject.getList())
            .map(list -> new Pair<>(list.add(new Object()), list))
            .forEach(pair -> someObject.setList(pair.getValue()));

Of course the real answer is, if you want to do things like this in one line you should simply write a method with as many lines as needed for clarity, then call it (in one line).


text:
Q: Copying file from server is slow but is fast when copying to server I have a Samsung 970 Evo+ in the built-in M.2 slot of the HP 290-p0043w and have a gigabit network cable connection directly between it and an gigabit port on an Asus X99 Deluxe motherboard. Both systems are running Windows 10.
I noticed that when I copy a large file from the Asus to the HP, I get consistent 113 MBps (904 Mbps) transfer speeds, as I would expect from a gigabit connection. However, when I copy a large file from the HP to the Asus, I only get 69-73 MBps (552-584 Mbps) on average. This is not what I would expect, this is significantly slower than gigabit.
The Asus machine has a Samsung 860 Pro SATA SSD as its target drive, while the HP has the Samsung 970 Evo+ its target drive. I have tried multiple Cat 6 Ethernet cables to connect the two machines and get the same results with both, so it's not the cable. I also tried copying from the boot HDD that came with the HP in place of the 970 Evo+ and get very similar results (113 MBps when writing to the HP's HDD from the Asus SSD, and 73 MBps when writing from the HP's HDD to the Asus SSD). So clearly it is network limited somehow. It's not the drives, it's not the cable, and it's not the M2 interface the 970 Evo+ is hooked into since I get the same results with the HDD. Same results after restarting both computers.
For all of these tests, the copy is initiated through Windows File Explorer from the Asus machine. The folders are shared using Windows' default drive sharing feature (right click a drive → sharing → advanced sharing → network).
My guess is it has something to do with the network adapter. In device manager, if I go to Realtek PCIe GBE Family Controller, I see "Transmit Buffers" having a value of 128 (I can't make it higher) and receive buffers of 512 (also can't make it higher). I have Speed and Duplex set to "1.0 Gbps Full Duplex." I'm not sure what these values mean and if they are responsible for the slower speeds when transferring from the HP to the Asus.
Considering all of this, does anybody know what is wrong here or what I can do to fix it? Why is the transfer speed from the HP to the Asus so much slower than the other way around?
Edit: I ran iperf as suggested:
PS C:\Users\USERNAME\Downloads\iperf-3.1.3-win64> .\iperf3.exe -c HP-HOSTNAME -p 577
Connecting to host HP-HOSTNAME, port 577
[  4] local fe80::.........:4609 port 58675 connected to fe80::.......:f560 port 577
[ ID] Interval           Transfer     Bandwidth
[  4]   0.00-1.00   sec   112 MBytes   936 Mbits/sec
[  4]   1.00-2.00   sec   112 MBytes   936 Mbits/sec
[  4]   2.00-3.00   sec   112 MBytes   936 Mbits/sec
[  4]   3.00-4.00   sec   112 MBytes   936 Mbits/sec
[  4]   4.00-5.00   sec   112 MBytes   936 Mbits/sec
[  4]   5.00-6.00   sec   112 MBytes   935 Mbits/sec
[  4]   6.00-7.00   sec   112 MBytes   936 Mbits/sec
[  4]   7.00-8.00   sec   111 MBytes   935 Mbits/sec
[  4]   8.00-9.00   sec   112 MBytes   936 Mbits/sec
[  4]   9.00-10.00  sec   112 MBytes   935 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth
[  4]   0.00-10.00  sec  1.09 GBytes   936 Mbits/sec                  sender
[  4]   0.00-10.00  sec  1.09 GBytes   936 Mbits/sec                  receiver

iperf Done.
PS C:\Users\USERNAME\Downloads\iperf-3.1.3-win64> .\iperf3.exe -s -p 577
-----------------------------------------------------------
Server listening on 577
-----------------------------------------------------------
Accepted connection from fe80::.......:f560, port 49676
[  5] local fe80::.........:4609 port 577 connected to fe80::1d0:6eda:a58:f560 port 49677
[ ID] Interval           Transfer     Bandwidth
[  5]   0.00-1.00   sec  71.3 MBytes   598 Mbits/sec
[  5]   1.00-2.00   sec  71.3 MBytes   598 Mbits/sec
[  5]   2.00-3.00   sec  72.1 MBytes   605 Mbits/sec
[  5]   3.00-4.00   sec  72.0 MBytes   604 Mbits/sec
[  5]   4.00-5.00   sec  72.2 MBytes   606 Mbits/sec
[  5]   5.00-6.00   sec  72.1 MBytes   605 Mbits/sec
[  5]   6.00-7.00   sec  72.2 MBytes   605 Mbits/sec
[  5]   7.00-8.00   sec  72.1 MBytes   605 Mbits/sec
[  5]   8.00-9.00   sec  71.6 MBytes   600 Mbits/sec
[  5]   9.00-10.00  sec  71.4 MBytes   599 Mbits/sec
[  5]  10.00-10.01  sec  1023 KBytes   591 Mbits/sec
- - - - - - - - - - - - - - - - - - - - - - - - -
[ ID] Interval           Transfer     Bandwidth
[  5]   0.00-10.01  sec  0.00 Bytes  0.00 bits/sec                  sender
[  5]   0.00-10.01  sec   719 MBytes   602 Mbits/sec                  receiver

As you can see, it is the exact same result.


text:
Q: Multiple using directives in function Instead of including a whole namespace in a given function, I like to only include the stuff I'm going to use, like:
void doStuff() {
    using std::sin;
    using std::cos;
    ...
    // do stuff
}

Sometimes this list grows longer. I wanted to slim it down to the following (similar to how it's possible with variable declarations):
void doStuff() {
    using std::sin, std::cos;
    // do stuff
}

I was surprised to find that this was not possible
(error: expected ';' after using declaration). Is there a reason for why the using is defined this way? Is there another way to include a number of functions from a given namespace consisely (except doing using namespace ...;)?

A: What I want does not seem to be possible currently. However, from en.cppreference.com:

A using-declaration with more than one using-declarator is equivalent to a corresponding sequence of using-declarations with one using-declarator.
  (since C++17)

With the following example:
namespace X {
    using A::g, A::g; // (C++17) OK: double declaration allowed at namespace scope
}

This seems to suggest that it might be possible in the future.


text:
Q: Can we calculate real time memory and storage utilization for ESXi host using Ansible Module? I need to calculate the real-time memory and datastore utilization of an ESXi. Registering ansible facts captures the data once and does not change. The captured data needs to be for a conditional loop hence the utilization needs to be checked after loop execution. Is this achievable using Ansible?

A: For a real-time memory utilization you may want to use nagios or other monitoring tools.
If you use ansible you will only get a snapshot at the time you ran the playbook.
Here is an example.
---
- name: cluster usage
  hosts: vcenter
  gather_facts: no

  tasks:
  - name: Gather cluster info from given datacenter
    vmware_host_facts:
      hostname: 10.10.10.20  (should be the IP address of your ESXi server)
      username: username
      password: verysecretpass
      validate_certs: False
    delegate_to: localhost
    register: esxis

  - set_fact:
      esxifacts: "{{ esxis.ansible_facts }}"

  - debug:
      var: esxifacts.ansible_datastore

  - debug:
      msg: "Free Memory available on {{esxifacts.ansible_hostname }} = {{ (esxifacts.ansible_memfree_mb * 100 / esxifacts.ansible_memtotal_mb)|int }}%"

Output will be:
 TASK [debug]  ok: [vcenter] => {
     "esxifacts.ansible_datastore": [
         {
             "free": "266.69 GB",
             "name": "datastore1",
             "total": "271.75 GB"
         },
         {
             "free": "34.89 TB",
             "name": "datastore_main",
             "total": "45.85 TB"
         },

     ] }

 TASK [debug]  ok: [vcenter] => {
     "msg": "Free Memory available on ESXi-01 = 8%" }


text:
Q: VSZ vs RSS memory and swap space I am trying to understand the memory usage of a large scale simulation that we are trying to run. When I run it "ps" reports
USER    PID %CPU %MEM     VSZ    RSS TTY    STAT START   TIME COMMAND
myuser 5252 97.7  0.5 5751412 377392 ?      Rs   19:49   1:15 myprogram

We have three arrays in that simulation that each occupy 1.6gb (200 million doubles). Based on the information in
What is RSS and VSZ in Linux memory management
I expected that memory to be listed under RSS, but RSS is only 377MB. Based on the information in the stackoverflow thread I concluded that the memory must be swapped out and looked at "free -m"
             total       used       free     shared    buffers     cached
Mem:         64391       5985      58406          0        463       1295
-/+ buffers/cache:       4226      60164
Swap:         4766          0       4766

and swap is not used at all! Aside from the fact that it is too small anyway. So where is this difference in RSS vs VSZ coming from? Why are the arrays that we allocate part of VSZ and not part of RSS?
I appreciate all help

A: Simple answer to your question is that arrays are defined in virtual space thats why memory for array is shown in VSZ only when you will use array it wil become part of RSS.
in my view by keeping your thinking simple will give you explanation. VSZ is virtual memory which a process can use while RSS is physical memory actually allocated at the moment. When a virtual memory is actually used OS will allocate the memory which will increase the RSS.


text:
Q: Update UI in UIAlertAction handler Could you try to help me to solve the problem of updating the UI of my program while showing the UIAlertView instance?
That's the situation:

*

*I'm pressing the toolbar "hide-button" and the alertView is opening;

*In the handler of UIAlertAction (OK button) i have a code, where i make several operations:

*

*remove the toolbar "hide-button" pressed and set the button item with activity indicator instead;

*making the indicator rolling;

*THEN AND ONLY AFTER PREVIOUS STEPS next part of code should start and the data model is being updated, and because it's connected to the tableView by means of NSFetchedResultsControllerDelegate, the tableView's data is gonna be updated automatically. This step can take some time, so it's extremely needed to hold it asynchronously, and while it's being processed the activity indicator should roll;

*after that the activity indicator rolling faults, the toolbar button item with it is being removed and the "hide-button" (removed at the 1st step) comes back.
FINISH.

The problem's with updating the UI, when i exchange "hide-button" and "activity-button".
private var hideDataBarButtonItem: UIBarButtonItem?
private var indicatorBarButtonItem = UIBarButtonItem(customView: UIActivityIndicatorView(activityIndicatorStyle: .Gray))

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    hideDataBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: #selector(hideAllLoginData))
    toolbarItems?.insert(hideDataBarButtonItem!, atIndex: 2)
}

That's the action for hideDataBarButtonItem:
@IBAction func hideAllLoginData(sender: AnyObject) {
    let confirmAlert = UIAlertController(title: "Hide all data?", message: "", preferredStyle: .Alert)

    confirmAlert.addAction( UIAlertAction(title: "OK", style: .Default, handler: { action in
        // remove the clear-button, set the indicator button instead and start indicator rolling
        self.toolbarItems?.removeAtIndex(2)
        self.toolbarItems?.insert(self.indicatorBarButtonItem, atIndex: 2)
        (self.indicatorBarButtonItem.customView as! UIActivityIndicatorView).startAnimating()
        print("button with indicator added")

        sleep(5) // -> CHECK: this moment indicator should be visible and rolling!

        dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) {
            for section in self.resources {
                for resource in section {
                    if resource.defRecord != nil {
                        resource.defRecord = nil
                    }
                }
            }
            print("data cleared")

            dispatch_async(dispatch_get_main_queue()) {
                // remove indicator and set the clear-button back
                print("button with indicator removed")
                (self.indicatorBarButtonItem.customView as! UIActivityIndicatorView).stopAnimating()
                self.toolbarItems?.removeAtIndex(2)
                self.toolbarItems?.insert(self.hideDataBarButtonItem!, atIndex: 2)
            }
        }
    }) )
    confirmAlert.addAction( UIAlertAction(title: "Cancel", style: .Cancel, handler: nil ) )

    self.presentViewController(confirmAlert, animated: true, completion: nil)
}

The result of the execution:
button with indicator added
// -> 5 sec of awaiting, but that's nothing in interface changed!
data cleared
button with indicator removed

If i don't remove the indicator button, i can see it after all, but it has to appear earlier. What do i make wrong?
Thank you!

A: The problem's solved.
It was because the NSFetchedResultsController updated the UI not in the main thread. I had to deactivate it's delegate while my model was updating. Then, in the main thread i has to activate it again and update the tableView data. The solution is here (look at the comments):
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) {
            // clear the delegate in order to not to allow UI update by fetchedResultsController
            self.resourceModel.nullifyFetchedResultsControllerDelegate()
            for section in self.resources {
                for resource in section {
                    if resource.defRecord != nil {
                        resource.defRecord = nil
                    }
                }
            }
            print("data cleared")

            dispatch_async(dispatch_get_main_queue()) {
                // set the delegate back and update the tableView
                self.resourceModel.setFetchedResultsControllerDelegate(self)
                self.reloadResources()
                self.tableView.reloadData()

                // remove indicator and set the clear-button back
                print("button with indicator removed")
                (self.indicatorBarButtonItem.customView as! UIActivityIndicatorView).stopAnimating()
                self.toolbarItems?.removeAtIndex(2)
                self.toolbarItems?.insert(self.hideDataBarButtonItem!, atIndex: 2)
            }
        }

PeterK, thank you for your advices!


text:
Q: Speeding up iterations joining to df Stock stats data.
date        mkt_cap    income    sales   ...
2019-08-15    ###        ###      ###    ...
2019-08-16    ###        ###      ###    ...
...           ...        ...      ...    ...

This code takes a column from each stocks' stat file. Say "mkt_cap" and changes the header to the stock name then adds it to the main_df. Once the main_df has been populated with all stock's stats from the same sector it writes a new file "mkt_cap.csv", then continues onto the next stat and eventually the next sector.
def compile_sector_stats():
    for sector,name in zip(list_all_sectors, sector_names):
        main_df = pd.DataFrame()
        for item in items_averages:
            main_df = main_df[0:0]
            for value in sector:

                df = pd.read_csv('.../stocks/{}.csv'.format(value))
                df.set_index('date', inplace=True)
                df.rename(columns = {'{}'.format(item):'{}'.format(value)}, inplace=True)
                df.drop(df.columns.difference([value]),1,inplace=True)

                if main_df.empty:
                    main_df = df
                else:
                    main_df = main_df.join(df, how='outer')

        main_df.to_csv('.../sectors/{}/{}.csv'.format(name,item))

This code works perfectly but it starts to slow down ALOT when the main_df gets big. Each sector actually has 500-700 stocks. Is there a way to make this process faster or am I just going to have to make the sector lists smaller?
EDIT:
The ouput CSV file is supposed to look like the following for each stat:
mkt_cap.csv

date        stock1  stock2  stock 3 ...
2019-08-15   ###      ###    ###
2019-08-16   ###      ###    ###
...          ...      ...    ...


text:
Q: Why my front view of the Linked list is not printing So i was trying this question in which I have written the below code:-
#include <bits/stdc++.h>
using namespace std;

struct Node
{
  char data;
  struct Node* next;
};

  struct Node *reverseList(struct Node *head)
  {
    Node *current = head;
    Node *prev = NULL, *next = NULL;
    while (current != NULL)
    {
      next = current->next;
      current->next = prev;
      prev = current;
      current = next;
    }
    head = prev;
    return head;
  }

bool isPalindrome(struct Node* head)
{
  Node* frontHead = head;
  Node* reverseHead = reverseList(head);
  Node* temp = reverseHead;
  cout<<"back view"<<endl;
  while(temp)
  {
      cout<<temp->data<<"->";
      temp = temp ->next;
  }
  cout<<endl;
    cout<<"front view"<<endl;
  temp = frontHead;
  while(temp)
  {
      cout<<temp->data<<"->";
      temp = temp ->next;
  }
  cout<<endl;
  bool flag = true;
//   while(frontHead && reverseHead)
//   {
//     // cout<<frontHead->data<<"-->"<<reverseHead->data<<endl;
//     if(frontHead->data !=reverseHead->data)
//     {
//       flag=false;
//       break;
//     }
//     frontHead = frontHead->next;
//     reverseHead = reverseHead->next;
//   }
  return flag;
}

void push(struct Node** head_ref, char new_data)
{
  struct Node* new_node = (struct Node*)malloc(
    sizeof(struct Node));
  new_node->data = new_data;
  new_node->next = (*head_ref);
  (*head_ref) = new_node;
}

void printList(struct Node* ptr)
{
  while (ptr != NULL)
  {
    cout << ptr->data << "->";
    ptr = ptr->next;
  }
  cout << "NULL" << "\n";
}

// Driver code
int main()
{
  struct Node* head = NULL;
  char str[] = "abacba";
  int i;
  for (i = 0; i<strlen(str); i++)
    push(&head, str[i]);
//   printList(head);
  isPalindrome(head) ? cout << "Is Palindrome" << "\n\n" : cout << "Not Palindrome" << "\n\n";
  return 0;
}

When I try to print the node form the front as well as from the backward(after reversing the linked list I got this output:-
back view
a->b->a->c->b->a->
front view
a->
Is Palindrome

can Anyone tell me why i am not able to get the front view of the linked list .
Any help will be appreciated


text:
Q: R: upload images to imgur I have a folder with some images (in .png and .jpg). My goal is to upload them all to imgur.com and get back the links or ids from each one.
I tried to install both packages imguR and imgur_upload but failled to install them.
Is there any quick workouround?

A: You can do this with knitr. This will upload an image and return your URL:
setwd("yourWD")
install.packages(knitr)
install.packages("RCurl")
install.packages("XML")
knitr::imgur_upload("fish2.jpg", key = "Yourimguraccountkey")

A: First of all, if you are logged in your imgur account in your default browser, log out. In R, try
tkn <- imgur_login()

Your browser will try to open:
https://api.imgur.com/oauth2/authorize?response_type=code&client_id=1babd0decbb90f2&redirect_uri=http%3A%2F%2Flocalhost%3A1410%2F&state=yVKVeDejjB

and give the error:
{"data":{"error":"redirect_uri_mismatch","request":"\/oauth2\/authorize","method":"GET"},"success":false,"status":400}

Delete the end of the url, leaving:
https://api.imgur.com/oauth2/authorize?response_type=code&client_id=1babd0decbb90f2

Now you will have the screen to log in with your username and password, then you will get:

Authentication complete. Please close this page and return to R.

#upload images
listoffileIDs <- character()
mylistf <- list.files(pattern = ".jpg|.png")

lapply(seq_along(mylistf), function(i)
{
  y <- upload_image(mylistf[[i]], token = tkn)
  Sys.sleep(5)
  listoffileIDs[[i]] <<- paste(unlist(account_images(token = tkn))[[1]])
  y
})
data.frame(mylistf = mylistf, listoffileIDs = listoffileIDs)

#add images to new album
firstalbum <-  create_album(listoffileIDs, title = "firstalbum",
               privacy = "hidden" , token = tkn)
firstalbum$id # album id

# add images to extant album https://imgur.com/a/ALBUMID
# example: get ID of first album
firstalbum <- account_albums(token = tkn)[[1]]#
add_album_images(firstalbum, listoffileIDs, token = tkn)


text:
Q: Text left and image right I'm trying to make text left and image right in the div. I found many examples in Stackoverflow where image is left and text right, then i tried to switch them but can't make it work.
I found that on stackoverflow but doesn't make sense for me.
I've tried this JSFIDDLE but you'll see that it wont works.
.main-topic {
    border: 2px solid green;
    width: 1541px;
    margin: 0 auto;
    clear: both;
}

.left-text{
    vertical-align:middle;
}

.right-picture{
    float: right;
}

.right-picture > img{
    display: block;
}

.clear{
    clear: both;
}

My goal is this (sorry can't post image i haven't enough reputation). I want that text be left side on the bordered div and picture in the right side

A: Just add display: flex; to .main-topic will do the trick.
And remove following css. There is no need of it now.
.right-picture{
    float: right;
}

Working Fiddle
Edit:
If don't required static width and height then, remove static height from section and static width from .main-topic will make result better.
Which is width: 1541px; from .main-topic And height: 500px; from section
Updated Fiddle

A: Remove float:right from img and put float: left in .left-text

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
 margin: 0;
 padding: 0;
 border: 0;
 font-size: 100%;
 font: inherit;
 vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
 display: block;
}
body {
 line-height: 1;
}
ol, ul {
 list-style: none;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
 content: '';
 content: none;
}
table {
 border-collapse: collapse;
 border-spacing: 0;
}

ul.topnav {
 list-style-type: none;
 /*position: fixed; */
 overflow: hidden;
 margin: 0;
 padding: 0 0 0 400px;
 background-color: #110E0C;
   /*width: 100%;
   top: 0; */
}

ul.topnav li {
 float: left;
}

ul.topnav li a {
 display: block;
 color: white;
 text-align: center;
 text-decoration: none;
 padding: 14px 30px;
 text-transform: uppercase;
 /*background-color: #3F4345;*/
}

ul.topnav li a:hover {
 background-color: #C8D0D7;
 color: #D8610C;
 border-bottom: 1px solid #D8610C;
}

ul.topnav li a.active {
 background-color: #C8D0D7;
 color: #D8610C;
 border-bottom: 1px solid #D8610C;
}

header {
 width: 100%;
 padding: 2px;
 color:black;
 background-color: #C8D0D7;
 text-align: center;
 overflow: hidden;
}

header img {

 height: 150px;
 width: 150px;
 margin-left: 900px;
 float:left;

}
header p {
 padding: 40px;
}

section {
 background-color: #333333;
 height: 500px;
}

section img {
 border: 1px solid white;
 height: 400px;
 width: 500px;
}

section h3 {
 color: white;
}

section p {
 color: white;
 height: 170px;
 width: 600px;
 padding: 0;
 margin: 0;
 line-height: 20px;
 vertical-align: top;
}

.main-topic {
 border: 2px solid green;
 width: 1541px;
 margin: 0 auto;
 clear: both;
}

.left-text{
 vertical-align:middle;
  float:left;
}

.right-picture{

}

.right-picture > img{
 display: block;
}

.clear{
 clear: both;
}

Deadpool Fans Petition 'SNL' for Superhero to Host

     Deadpool fans want its superhero to host Saturday Night Live — Deadpool, that is, not Ryan Reynolds. Fans of the Merc With a Mouth, who led the Marvel film to a history-making debut at the box office, have launched a Change.org petition calling for the antihero to host an upcoming episode of the NBC sketch comedy show. "We've all seen the trailers, the magazine covers, the viral videos, and the billboards by now, so what's left for Deadpool (Ryan Reynolds) to do?" creator Andrew Stege asks in the petition, which is directed to SNL, creator Lorne Michaels, parent.

A: How about this: http://jsbin.com/yenuxajode
Just float the text div left with width 50% (or whatever you want) and float the image div right with the remaining width. Make the img have max-width:100%; to keep it all on the page.

A: I updated your fiddle, removed some height/width settings and adjusted the following CSS rules, so now it looks good
.main-topic {
    display: table;
    border: 2px solid green;
    margin: 0 auto;
}

.left-text{
    display: table-cell;
    vertical-align:middle;
}

.right-picture{
    display: table-cell;
}


text:
Q: How to display mysql_select result in servlet I've tried a few things but i'm not able to get the output and its taking too much time just to show the output screen....
For ex: in my situation the output should consist of a table with its output which is generated according to my program but instead its taking too much time just to perform the operation and after that its just showing table headers....
I've googled this but i'm not able to find the appropriate idea about this...
Thanks a million for anyone who can help..
This is my Code:
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
ResultSet result;
String dat,d,s,i,r;
int numcols,index,ans = 0;
ResultSetMetaData resultMd;
String rs = null;
d= request.getParameter("name");
s= request.getParameter("gen");
i= request.getParameter("indi");
r= request.getParameter("rea");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if(d!=null && i==null && r==null)
    ans=1;
else if(d!=null && i==null && r!=null)
    ans=2;
else if(d!=null && i!=null && r!=null)
    ans=3;
else if(d==null && i!=null && r!=null)
    ans=4;
else if(d==null && i==null && r!=null)
    ans=5;
else if(d!=null && i!=null && r==null)
    ans=6;
else if(d==null && i!=null && r==null)
    ans=7;

switch(ans)
{
case 1:
    rs="SELECT d.gndr_cod,d.age,d.wt,d.reporter_country,dr.drug_name,i.indi_pt,o.outc_cod,r.pt from demo d,drug dr,indi i,outc o,reac r where dr.drug_name='"+d+"' and d.gndr_cod='"+s+"' limit 25";
    break;
case 2:
    rs="SELECT d.gndr_cod,d.age,d.wt,d.reporter_country,dr.drug_name,i.indi_pt,o.outc_cod,r.pt from demo d,drug dr,indi i,outc o,reac r where dr.drug_name='"+d+"' and r.pt='"+r+"' and d.gndr_cod='"+s+"' limit 25";
    break;
case 3:
    rs="SELECT d.gndr_cod,d.age,d.wt,d.reporter_country,dr.drug_name,i.indi_pt,o.outc_cod,r.pt from demo d,drug dr,indi i,outc o,reac r where dr.drug_name='"+d+"' and r.pt='"+r+"' and i.indi_pt='"+i+"' and d.gndr_cod='"+s+"' limit 25";
    break;
case 4:
    rs="SELECT d.gndr_cod,d.age,d.wt,d.reporter_country,dr.drug_name,i.indi_pt,o.outc_cod,r.pt from demo d,drug dr,indi i,outc o,reac r where r.pt='"+r+"' and i.indi_pt='"+i+"' and d.gndr_cod='"+s+"' limit 25";
    break;
case 5:
    rs="SELECT d.gndr_cod,d.age,d.wt,d.reporter_country,dr.drug_name,i.indi_pt,o.outc_cod,r.pt from demo d,drug dr,indi i,outc o,reac r where r.pt='"+r+"' and d.gndr_cod='"+s+"' limit 25";
    break;
case 6:
    rs="SELECT d.gndr_cod,d.age,d.wt,d.reporter_country,dr.drug_name,i.indi_pt,o.outc_cod,r.pt from demo d,drug dr,indi i,outc o,reac r where dr.drug_name='"+d+"' and i.indi_pt='"+i+"' and d.gndr_cod='"+s+"' limit 25";
    break;
case 7:
    rs="SELECT d.gndr_cod,d.age,d.wt,d.reporter_country,dr.drug_name,i.indi_pt,o.outc_cod,r.pt from demo d,drug dr,indi i,outc o,reac r where i.indi_pt='"+i+"' and d.gndr_cod='"+s+"' limit 25";
    break;
}
out.print("");
out.print("<title>Results</title>");
out.print("");
try
{
    result=mystmt.executeQuery(rs);
    resultMd=result.getMetaData();
    numcols=resultMd.getColumnCount();
    out.print("
");
    out.print("
Drug Name	Sex	Age	Weight	Country	");
    out.print("Indication	Reaction	Outcome	");
    out.print("
");
    while(result.next())
    {
        out.print("
");
        for(index=0; index<=numcols;index++)
        {
            dat=result.getString(index);
            out.print("" +dat+"	");
        }
        out.print("
");
    }
    out.print("
");
}
catch(Exception e)
{
    e.printStackTrace();
}
out.print("");}

A: Fist of all, test your queries and if there are any performance issue, try to solve it. There could be huge amount of data as well what can not handle the runtime. See some log for RuntimeExceptions or Errors.
If your SQL query runs fast and returns not much rows then please edit your question  and make it simpliest as you can. Thanks. ;)
EDIT:
Try not to concatenate SQL queries, use binding instead, because database can not use statistics if you execute a brand new query, and you may running into SQLInjection issues.
EDIT2:
Please close your resources in finally block, and increase your connection thread limit if you have. Try only one SQL, try to make it siple to find out the source of the problem.


text:
Q: Limiting access to Assets .pdf .jpg I want to have users be able to upload .pdf and images and restrict the access to these files based on user's privileges.
The basic plan of attach I thought of is a controller checks if the user has privileges to view the document or file. If they have the privileges the document is retrieved and displayed.
My .htaccess file would include
 #Removes access to the secure_files folder by users.
 RewriteCond %{REQUEST_URI} ^secure_files.*
 RewriteRule ^(.*)$ /index.php?/$1 [L]

    ------
    -SQL
    ------

    ------
    - create files table
    -----
    CREATE TABLE `files` (
    id INT NOT NULL AUTO_INCREMENT,
    file_name VARCHAR(50) NOT NULL,
    PRIMARY KEY('id')
    );

    ------
    - create files table
    -----
    CREATE TABLE `privileges` (
    uesr_id INT NOT NULL,
    file_id INT NOT NULL,
    );

    ------
    - create users table
    -----
    CREATE TABLE `users` (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    email VARCHAR(50) NOT NULL,
    password CHAR(40) NOT NULL,
    PRIMARY KEY('id')
    );

    /*
    * pseudo-Codeigniter code. I can edit this to make
    * it pure PHP if that would be more helpful
    *
    */
    public function get_user_files($filename)
    {
       //this is set during login
       $user_id = $this->session->userdata('user_id');

      //check to see if the user has privileges to access the file and gets the file name
      $query = $this->db->join('privileges','privileges.id = files.id')
                     ->select('files.file_name')
                     ->where('privileges.user_id',$user_id)
                     ->where('files.file_name',$file_name)
                     ->limit(1)
                     ->get('files');

    $file = $query->row()->files.file_name;

   if($file)
   {
    //user has privileges to access the file so include it

    //WHAT DO I DO HERE!?!
    //start Would this work?
    $handle = fopen($file, "rb");
    $data['file'] = fread($handle, filesize($file));
    fclose($handle);
    //end would this work?
   }
  $this->load->view('files',$data);
}

A: An easy and secure solution would be to use the following schema.   This will allow you to restrict access to the uploaded files and avoid the problem of uploading .php files.  File sizes are capped by the size of a longblob which is 16mb in size.
CREATE TABLE `files` (
id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
file_name text NOT NULL,
file LONGBLOB NOT NULL,
PRIMARY KEY('id')
);

Here is php code to upload the file:
$user_file=file_get_contents($_FILES['user_file']['tmp_name']);
//Make the file binary safe
$user_file=mysql_real_escape_string($user_file);
$file_name=mysql_real_escape_string($_FILES['user_file']['name']);
$user_file=mysql_real_escape_string($user_file);

mysql_query("insert into files (user_id,file_name,file)values ("$_SESSION[user_id]","$file_name","$user_file");

Access control can be enforced by checking the user_id of a file.   The content-type of a users file is easy to spoof so don't trust $_FILE[name][type],  However this must be the correct type when you are letting the user download the file.  For instance pdf should have this content-type.
header('Content-type: application/pdf');

A: Why not just put them in a directory with a .htaccess blocking all access and use a php script to send the appropriate headers, check permissions then spit out file contents with the readfile function?


text:
Q: Corresponding or associated? Which to use? I want to write a sentence wherein the context is that there is a group 'T' which has fields T1, T2, … Tn.
Should I write fields corresponding to 'T' or fields associated with 'T'?
What exactly is the difference between the two? Any help will be highly appreciated.

A: In the context of a scientific paper, I would read 'associated with' as meaning 'related to in some way'. 'Corresponding to' on the other hand is more strictly defined - it implies a one-to-one relationship. x and y values on a graph would be a good example - for every value of x, there is a corresponding value y.
In your example:

group 'T' which has fields T1, T2, … Tn.

Neither seems to be the case. I would suggest something along the lines of:

...group 'T' which is comprised of fields T1, T2, … Tn.
...group 'T' which is composed of fields T1, T2, … Tn.
...group 'T' which ranges from T1, T2, … Tn.

A: I would write:

The fields comprising group 'T'...

See comprise:

*

*to include; contain


text:
Q: Compiling issues when deriving from a class nested in a template I am writing template class for a sudoku puzzle, where the template parameters define the size of the rows and columns. I am using g++-4.8 with C++11 enabled.
I have one compiling issue that I worked around, but I would like to understand why it is not working as expected:
My RowIteratorImpl class derives from VirtualLineIteratorImpl, but I cannot access its fields virtualLineIdx and cellInVirtualLineIdx although this should be possible:
    class VirtualLineIteratorImpl : public CellIteratorImpl
    {
    protected:
        size_t virtualLineIdx;
        size_t cellInVirtualLineIdx;

    public:
        VirtualLineIteratorImpl(size_t virtualLineIdx)
            : virtualLineIdx(virtualLineIdx), cellInVirtualLineIdx(0)
        {}

        virtual void increment(size_t offset)
        {
            virtualLineIdx += offset;
        }
    };

    class RowIteratorImpl : public VirtualLineIteratorImpl
    {
    public:
        using VirtualLineIteratorImpl::VirtualLineIteratorImpl;

        virtual size_t getCellIdx() const
        {
            // TODO: does not compile
            // return mivTSudoku::getCellIdxInRow(virtualLineIdx, cellInVirtualLineIdx);
            return mivTSudoku::getCellIdxInRow(VirtualLineIteratorImpl::virtualLineIdx, VirtualLineIteratorImpl::cellInVirtualLineIdx);
        }
    };

The compiler generates the following message:
mivSudoku.h: In member function 'virtual size_t mivTSudoku::RowIteratorImpl::getCellIdx() const':
mivSudoku.h:85:39: error: 'virtualLineIdx' was not declared in this scope
    return mivTSudoku::getCellIdxInRow(virtualLineIdx, cellInVirtualLineIdx);
This is the entire class definition:
#ifndef MIVSUDOKU_H
#define MIVSUDOKU_H

#include <bitset>
#include <iterator>
#include <memory>

template<size_t n, size_t m=n>
class mivTSudoku
{
public:
    class Cell
    {};

    static constexpr size_t getCellIdx(size_t rowIdx, size_t colIdx)
    {
        return rowIdx * dim + colIdx;
    }
    static constexpr size_t getCellIdxInRow(size_t rowIdx, size_t cellInRowIdx)
    {
        return getCellIdx(rowIdx, cellInRowIdx);
    }
    static constexpr size_t getCellIdxInColumn(size_t columnIdx, size_t cellInColumnIdx)
    {
        return getCellIdx(cellInColumnIdx, columnIdx);
    }
    static constexpr size_t getCellIdxInBlock(size_t blockIdx, size_t cellInBlockIdx)
    {
        return getCellIdx((blockIdx / n) * n + (cellInBlockIdx / m), (blockIdx % n) * m + (cellInBlockIdx % m));
    }

    class CellIteratorImpl
    {
    public:
        virtual CellIteratorImpl* clone() = 0;
        virtual void increment(size_t) = 0;
        virtual void getCellIdx() const = 0;
    };

    class AllCellIteratorImpl : public CellIteratorImpl
    {
    private:
        size_t m_cellIdx;

    public:
        AllCellIteratorImpl()
            : m_cellIdx(0)
        {}

        virtual void increment(size_t offset)
        {
            m_cellIdx += offset;
        }
        virtual void getCellIdx() const
        {
            return m_cellIdx;
        }
    };

    class VirtualLineIteratorImpl : public CellIteratorImpl
    {
    protected:
        size_t virtualLineIdx;
        size_t cellInVirtualLineIdx;

    public:
        VirtualLineIteratorImpl(size_t virtualLineIdx)
            : virtualLineIdx(virtualLineIdx), cellInVirtualLineIdx(0)
        {}

        virtual void increment(size_t offset)
        {
            virtualLineIdx += offset;
        }
    };

    class RowIteratorImpl : public VirtualLineIteratorImpl
    {
    public:
        using VirtualLineIteratorImpl::VirtualLineIteratorImpl;

        virtual size_t getCellIdx() const
        {
            // TODO: does not compile
            //return mivTSudoku::getCellIdxInRow(virtualLineIdx, cellInVirtualLineIdx);
            return mivTSudoku::getCellIdxInRow(VirtualLineIteratorImpl::virtualLineIdx, VirtualLineIteratorImpl::cellInVirtualLineIdx);
        }
    };

    typedef std::bidirectional_iterator_tag CellIterator_tag;
    typedef std::iterator<CellIterator_tag, Cell> CellIteratorBase;
    class Cellterator : public CellIteratorBase
    {
    private:
        typedef CellIteratorBase baseclass;

    protected:
        mivTSudoku* pSudoku;
        CellIteratorImpl* m_pIterImpl;

    public:
        Cellterator(mivTSudoku* pSudoku, CellIteratorImpl* impl) noexcept
            : pSudoku(pSudoku), m_pIterImpl(impl)
        {
        }

        ~Cellterator()
        {
            delete m_pIterImpl;
            m_pIterImpl = nullptr;
        }

        Cellterator(const Cellterator& rhs) noexcept
            : pSudoku(pSudoku), m_pIterImpl(rhs.m_pIterImpl->clone())
        {}

        Cellterator(Cellterator&& rhs) noexcept
            : pSudoku(pSudoku), m_pIterImpl(rhs.m_pIterImpl)
        {
            rhs.m_pIterImpl = nullptr;
        }

        Cellterator& operator=(const Cellterator& rhs) noexcept
        {
            if (this == &rhs) return *this;
            this->pSudoku = rhs.pSudoku;
            this->m_pIterImpl = rhs.m_pIterImpl->clone();
        }

        Cellterator& operator=(Cellterator&& rhs) noexcept
        {
            if (this == &rhs) return *this;
            this->pSudoku = rhs.pSudoku;
            this->m_pIterImpl = rhs.m_pIterImpl;
            rhs.m_pIterImpl = 0;
        }

        size_t getCellIdx() const
        {
            return m_pIterImpl->getCellIdx();
        }

        typedef typename baseclass::reference reference;
        reference operator*()
        {
            return pSudoku->m_field[getCellIdx()];
        }

        reference const operator*() const
        {
            return pSudoku->m_field[getCellIdx()];
        }

        typedef typename baseclass::pointer pointer;
        pointer operator->()
        {
            return pSudoku->m_field + getCellIdx();
        }

        pointer const operator->() const
        {
            return pSudoku->m_field + getCellIdx();
        }

        Cellterator& operator++()
        {
            m_pIterImpl->increment(1);
            return *this;
        }
        Cellterator operator++(int)
        {
            Cellterator iter;
            this->operator++();
            return iter;
        }
        bool operator==(const Cellterator& rhs) const
        {
            return getCellIdx()==rhs.getCellIdx();
        }
        bool operator!=(const Cellterator& rhs) const
        {
            return !operator==(rhs);
        }
    };

public:
    static const size_t dim = n*m;
    static const size_t ncells = dim*dim;

private:
    Cell m_field[dim];
};

typedef mivTSudoku<3,3> mivSudoku;

#endif // MIVSUDOKU_H

Can some explain to me why?

A: The issue is that names not depending on a template argument are looked up only when the template arguments are not known. Since your base class depends on a template argument (implicitly by being nested inside a template) the compiler diesn't look at the base class, yet: until the template is instantiated it could get specialuzed, resulting in a completely different class.
The fix is to make the reference to the base member depend on the template argument, e.g., by using this->virtualLineIdx.


text:
Q: ng serve error: "Cannot read property '0' of undefined" I'm new to Angular. I downloaded the Angular 2 quick-start template from https://github.com/angular/quickstart (app folder is inside an src folder), and then used VS code to modify packages.json content and manually create files/folders inside the app folder for components/services/etc.. based on tutorials that I found online. The application runs and works fine when I kick it off using npm start but I'm stuck creating the DIST folder which I need in order to upload a minified version of my application to azure web app. Whenever I run ng build from the root of my angular 2 project, I get the below error:
Cannot read property '0' of undefined
TypeError: Cannot read property '0' of undefined
at Class.run (C:\AngularTestProject\node_modules\angular-cli\tasks\build-webpack.js:15:98)
at Class.run (C:\AngularTestProject\node_modules\angular-cli\commands\build.js:51:26)
at Class.<anonymous> (C:\AngularTestProject\node_modules\angular-cli\angular-cli\lib\models\command.js:152:17)
at process._tickCallback (internal/process/next_tick.js:103:7)

This is the content of packages.json:
{
  "name": "EventRecorder",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",
"angular-cli": {},
  "scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "build:e2e": "tsc -p e2e/",
    "serve": "lite-server -c=bs-config.json",
    "serve:e2e": "lite-server -c=bs-config.e2e.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
    "pree2e": "npm run build:e2e",
    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",
    "preprotractor": "webdriver-manager update",
    "protractor": "protractor protractor.config.js",
    "pretest": "npm run build",
    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",
    "pretest:once": "npm run build",
    "test:once": "karma start karma.conf.js --single-run",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",

    "angular-in-memory-web-api": "~0.2.4",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4",
    "bootstrap": "^3.3.6"
  },
  "devDependencies": {
    "@angular/compiler-cli": "2.2.1",
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.0.10",
    "angular-cli": "1.0.0-beta.21",
    "canonical-path": "0.0.2",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",
    "ts-node": "1.2.1",
    "@types/node": "^6.0.46",
    "@types/jasmine": "2.5.36",
    "webdriver-manager": "10.2.5"
  },
  "repository": {}
}

And lastly this is the folder structure of my app:
App Folder Structure

A: Issue was resolved by installing the latest version of Angular CLI (1.0.0-rc.1) and recreating the Angular project (using ng new projectname command) and copying my TS files from my old project over.


text:
Q: Provide local currency format i18n on server and process is on client We need to display the amounts/numbers in different formats based on user's locale. The information is provided though a REST API.
fr = 1 234 567,89
en-us = 1,234,567.89
de = 1.234.567,89

One way is to process it fully on the server-side. Another way is to process it fully on the client-side using a library such dojo/i18n .
However I'm wondering if it's possible to provide somehow the number format (the format only not the number itself) through the API and then format the number on the client-side (using javascript). Any idea how that can be done ? I mean how the "format" should look like and how it can be rendered/processed so that it can be used as a pattern to format the number on the client side.

A: It can be done. Many javascript frameworks have localized formatters for dates and numbers. Usually the formats are static, so you could hardcode them in a config.js. And if that isn't enough you can render them in the config.js on the server. You could even localize that resource server side to reduce the amount of code sent over the wire.
You could also provide an API where you can GET the format for the clients locale, but that seems overkill to me.

A: Take a look at Globalize. It can be done, all you have to do is define (or override) the culture. Take a look at French culture file to see how it can be done:
Globalize.addCultureInfo( "fr", "default", {
// (...)
    numberFormat: {
        ",": " ",
        ".": ",",
        "NaN": "Non Numérique",
        negativeInfinity: "-Infini",
        positiveInfinity: "+Infini",
        percent: {
            ",": " ",
            ".": ","
        },
        currency: {
        pattern: ["-n $","n $"],
            ",": " ",
            ".": ",",
        symbol: "€"
    }
// (...)

Depending on the source of your format, you might need to transform the data to something understandable by Globalize, but yes, it can be done.


text:
Q: CPLEX - define variables with expressions I'm working on fleet assignment problem, and I'm building a model in xpress-Mosel. However, I need to build it too in OPL - Cplex.
I'm new at OPL, so I've some doubts. I can't define variables by some expression that aren't constraints or given by input.
I've the following vectors in my .dat file, this is a part of all the data file:
proc_low=[...];
cof=[...];
cov_km=[...];
dist_km=[...];
penalty=[...];

Defined on this way:
range N0=0..n;
range N=1..n;
range Fleet=1..3;
range liga=1..30;
range POSS=1..poss;
int legs[N]=...;
int org[N]=...;
int dest[N]=...;
int proc_low[N]=...;
int tp_cod[Fleet]=...;
int cap[Fleet]=...;
int test1[Fleet]=...;
int cof[Fleet]=...;
int cov_km[Fleet]=...;
int cod_org[lig]=...;
int cod_dest[lig]=...;
int penalty[lig]=...;
float dist_km[lig]=...;
int leg_atual[POSS]=...;
int leg_after[POSS]=...;
int tp_fleet[POSS]=...;

tuple T {
  int atual;
  int after;
  int type_f;
}

//Decicion variables
{T} tuples = { <leg_atual[k], leg_after[k], tp_fleet[k]> | k in POSS };
dvar boolean x[tuples];

So, here is my doubt: I cant define this expressions... spill passengers for each leg, that depends of sells (proc_low) and fleet capacity if the leg was flew by some aircraft. The code above isn't in cplex format... is in xpress mosel, and it's here that I need help for write in cplex format...
forall(l in 1..n2) pass_out(l):= spill(l)>=proc_low(l)-sum(f in Fleet)cap(f)*(sum(i in n3..n)x(i,l,f)+x(0,l,f))
forall(l in n3..n) pass_in(l) := spill(l)>=proc_low(l)-sum(f in Fleet)cap(f)*sum(i in 1..n2)x(i,l,f)

Then, the penalty on the objective function per spill passengers
forall(j in N,i in lig|org(j)=cod_org(i) and dest(j)=cod_dest(i))do
pen(j):=penalty(i)*spill(j)
end-do

And last, the cost of assignment of some aircraft at some leg
forall(j in N,i in ligs,  f in Fleet|org(j)=cod_org(i) and dest(j)=cod_dest(i))do
cost(j,f):=cof(f)+cov_km(f)*dist_km(i)
end-do

I've defined this variables, on the way shown above, but I'm not sure... Perhaps it's with dexpr. I really don't know...
dvar int spill[N];
dvar float+ pen[N];
dvar float+ cost[N][Fleet];

Thanks!
Regards


text:
Q: How do rootkits get installed on to a ubuntu server? I've seen a few posts on checking for rootkits but haven't been able to find any information on how they get onto a linux system. In particular if you exploit a bug in a php web site (yes I'm talking about drupageddon here) is it possible to install a rootkit even though you can only run as the web-server (www-data) and not as root. The very little information I've found about how these are installed suggests you have to be root to install them (see here).

A: If it was me I would persue the following method:

*

*Get a user to download and install a piece of software (#1). Have that software install the intended software. Hide a binairy blob inside that application lets you download software (ie. a tool you can use to ftp, wget etc).

*Prompt for the admin account (#2) and use that to use an ftp, wget instance to download and install the rootkit.

Regarding #1: a user should never download random software when using Linux; use the appropriate channels (Ubuntu Software Center) to install software. If it is software that needs to be downloaded outside the appropriate channels make sure the source of the download can be trusted. Think latest versions of Apache software or MySQL. Do not go around downloading random software without checking out different social media about the integrity of that application. Microsoft never centralized software; it resulted in lots of people dabbling with software so their user base is hugh, but that also made it easy to get into computers and start gathering data they can sell.
Regarding #2: fatal user flaw. Never ever ever ever type in your admin password unless you know why it is asked.

A: Yes, in general root permission are required to install a rootkit.
Many of the rootkits contain a module that is loaded into the kernel, other just overwrite tool typically used by root. In a properly set and perfect system there would be no way to install the root kit without root privileges, but...
...there might be problems with the system configuration making the system unsafe.
...there might be security bugs that allow a privilege elevation
...there might be ways to trick a user with root permissions to run something evil.
The ways are as unlimited as the imagination of the intruder.


text:
Q: k3s ctr images import to different dir I am having tar of my service specific images. I am importing it in containerd so that it will be used by k3s to deploy PODs. command used to import image's tar is-
k3s ctr images import XXX.tar
By default it loads images in /var/lib/rancher/data dir. However, I would like to load images in different directory. Anyone know, how to specify custom directory while loading images?

A: I didn't find anything that may natively allow for changing this directory.
This doesn't mean nothing can be done. You can always create a symlink like this:
ln -s target_path /var/lib/rancher/data

Let me know if it helped.


text:
Q: Control structures are failing me I am trying to make a simple Arduino game that keeps track of the number of times a button has been pressed. There are two buttons, one for each user, and whoever is closest to the random number that the Arduino picks, wins. "winning" being a light comes on next to the winers button. However I am stuck in what seems to be a rut—before I go further, I will divulge that I am just barely two weeks old into the whole arduino/C++ environment so my knowledge is pretty low.
Basically what I want to happen is that the game lasts a certain amount of time, lets say 5 seconds, then after the five seconds, all the button pushes are tallied and compared and a winner is picked. Then the game resets itself and we can play again. Where I am getting stuck at is in the timing function. I originally was subtracting a gameClock variable from the millis() function however I have read that it is bad practice to reset the millis() function. Perhaps my code will give you a better understanding of what I am trying to accomplish.
#include <Bounce.h>
  //Using Arduino UNO
  #define RBUTTON 2
  #define RRLED 3
  #define RGLED 4
  #define MBLED 5
  #define LGLED 6
  #define RLLED 7
  #define LBUTTON 8

  Bounce BounceR = Bounce(RBUTTON, 5);
  Bounce BounceL = Bounce(LBUTTON, 5);

  int lastStateR = 0;
  int lastStateL = 0;
  int switchLCount = 0;
  int switchRCount = 0;
  long gameClock = 5000;

  void setup() {
    //LED from left to right
    pinMode(RBUTTON, INPUT);
    pinMode(RRLED, OUTPUT); //Red
    pinMode(RGLED, OUTPUT); //Green
    pinMode(MBLED, OUTPUT); //Blue
    pinMode(LGLED, OUTPUT); //Green
    pinMode(RLLED, OUTPUT); //Red
    pinMode(LBUTTON, INPUT);
    Serial.begin(9600);

  }

  void loop() {
    BounceR.update();
    BounceL.update();
    int total = switchRCount + switchLCount;

    int valueR = BounceR.read();
    int valueL = BounceL.read();

if (valueL != lastStateL) {
  if (valueL == HIGH) {
      switchLCount++;
      Serial.print("Left button:");
      Serial.println(switchLCount);
      Serial.print("Total: ");
      Serial.println(total);
    }
}
  lastStateL = valueL;

if (valueR != lastStateR) {
  if (valueR == HIGH) {
      switchRCount++;
      Serial.print("Right button: ");
      Serial.println(switchRCount);
      Serial.print("Total: ");
      Serial.println(total);

    }
}
  lastStateR = valueR;

  }

A: You really should look at the arduino.cc forums for help on this stuff. There's a whole archive of knowledge, plus many people who have a lot of arduino experience.
There are basically 3 problems with your sketch.  First, as you said, the gameClock is not working like you want it to.  Just using a counter isn't going to cut it, even at only 16Mhz, the arduino is going to zip right through it in a lot less that 5 seconds. You need to actually time it.
Second, your button 'debouncing' is broken.  Debouncing buttons is actually quite tricky.  Fortunately, many many people have already solved the problem.  Check the arduino libraries, the forum and the playground.  The problem here is that you never set the lastDebounceTime variables to anything.
Finally, your sketch only reads the buttons once per game.  That throws everything else off.
It kills your debouncing and messes up the button press count.
I'll stop now to give you a chance to work it out.  Post another comment if you want more help.


text:
Q: Declare custom xml attributes namespace globally Is it possible to add custom attributes namespace to every xml/layout files in android project rather than having to declare this at the header of every single file?
xmlns:namespace="http://schemas.android.com/apk/res-auto"


text:
Q: dynamic text box in zend form me created a zend form and want to add dynamic text box in it.
created it using javascript.
but on submit of the form, only data in the last created text box is posted.
please help.
<script type="text/javascript">
    var count1 = 0;
    var count2 = 0;
    var count3 = 0;
    var count4 = 0;
    var count5 = 0;
    var count6 = 0;
    $('#addone').click(function() {
        $('#link-element').append($('<input id="link" class="link" type="text" name="link"/>').hide().slideDown(100));
        count1++;
    });
    $('#addtwo').click(function() {
        $('#youtube-element').append($('<input id="yahoo'+count2+'" class="link" type="text" name="yahoo"/>').hide().slideDown(100));
        count2++;
    });
    $('#addthree').click(function() {
        $('#gamepuzzle-element').append($('<input id="gamepuzzle'+count3+'" class="link" type="text" name="gamepuzzle"/>').hide().slideDown(100));
        count3++;
    });
    $('#addfour').click(function() {
        $('#flashgame-element').append($('<input id="flashgame'+count4+'" class="link" type="text" name="flashgame"/>').hide().slideDown(100));
        count4++;
    });
    $('#addfive').click(function() {
        $('#moketest-element').append($('<input id="moketest'+count5+'" class="link" type="text" name="moketest"/>').hide().slideDown(100));
        count5++;
    });
    $('#addsix').click(function() {
        $('#indigenousintegration-element').append($('<input id="indigenousintegration'+count6+'" class="link" type="text" name="indigenousintegration"/>').hide().slideDown(100));
        count6++;
    });
</script>

A: Try to send the form inputs as an array.
E.g.
$('#addsix').click(function() {
    $('#indigenousintegration-element').append($('<input id="indigenousintegration'+count6+'" class="link" type="text" name="indigenousintegration[]"/>').hide().slideDown(100));
    count6++;
});

Notice the [] at the end of the name of the input.


text:
Q: If I'm using a For Loop, how can I include the list item as part of the results? I apologize in advance for misused terminology and description, but I'm able to describe it well enough:
I'm making requests to an API, while using a 'for loop' to iterate through a list of subdirectories I've identified for a domain.
responses = list() ##defining that responses is a list
responses.clear() ##clearing the list each time I run the script

ids = ['XXXXXXid1XXXXXX', 'XXXXXXid2XXXXXX', 'XXXXXXid3XXXXXX']  ##defining list of ids

for id in ids:
    url = 'https://api.website/PartOfWebsite/{}'.format(id)
    rr = requests.get(url, params= {'apikey': 'my-api-key'})
    data = json.loads(rr.text)
    responses.append(data)

When looking at 'responses' after this succesffully runs, the results look like:
[{'python_rules': [{'ad': 'some result',
    'ret': 23908092093094808203,
    'shure': 2.5},
   {'ad': 'some result',
    'ret': 902830894023342,
    'share': 2.32},
   {'ad': 'some result',
    'ret': 98209283049820,
    'shure': 21.3}]

I would like the results to include the id that is associated to the search, in the 'ids' list. So, the results would look like:
[{'python_rules': [{'ad': 'some result',
    'ret': 23908092093094808203,
    'shure': 2.5,
    'id': XXXXXXid1XXXXXX},
   {'ad': 'some result',
    'ret': 902830894023342,
    'share': 2.32
    'id': XXXXXXid2XXXXXX},
   {'ad': 'some result',
    'ret': 98209283049820,
    'shure': 21.3
    'id': XXXXXXid3XXXXXX}]

Please let me know if I need to be more specific about what I'm looking for. Thanks!

A: You can simply add the id manually to the resulting data dictionary:
responses = list() ##defining that responses is a list
responses.clear() ##clearing the list each time I run the script

ids = ['XXXXXXid1XXXXXX', 'XXXXXXid2XXXXXX', 'XXXXXXid3XXXXXX']  ##defining list of ids

for id in ids:
    url = 'https://api.website/PartOfWebsite/{}'.format(id)
    rr = requests.get(url, params= {'apikey': 'my-api-key'})
    data = json.loads(rr.text)

    data['id'] = id    # <-- add id manually

    responses.append(data)


text:
Q: jQuery hide elements when new element selected I have a series of icons which when clicked reveal a small arrow and a list of products. I can get the arrow to display and the list to slide down but what I'd like to do is hide the currently visible list and arrow when another icon is clicked.
Can anyone help or point me in the right direction please?
HTML:

product-title1

product-title2

product-title3

product-title4

product-title1

product-title2

product-title3

product-title4

product-title1

product-title2

product-title3

product-title4

jQuery:
$(document).ready(function() {
    $ (".stockist-icon").on('click', function(){
        $(this).children('.stockist-arrow').css('visibility','visible');
        var elementid = $(this).attr("id");
        $("div." + elementid).stop().slideDown(400);
    });
});

A: you can slideUp all other divs except current one using class selector of jquery. Here you can use class attribute with values starting as STORE, see below code
NOTE: jQuery has .show() and .hide() functions to show and hide html elements so no need to use .css()
$(document).ready(function() {
    $ (".stockist-icon").on('click', function(){
        //$(this).children('.stockist-arrow').css('visibility','visible'); -- use .show()
        $(this).children('.stockist-arrow').show();
        var elementid = $(this).attr("id");
        var selector = "div.stockist-block-dropdown." + elementid;
        $("div.stockist-block-dropdown").not(selector).stop().slideUp(400); // slidup other divs
        $(selector).stop().slideDown(400);
    });
});