问:
Yii2 sending email to gmail account via swift mailer
I am trying to send email via swift mailer.I know there is a lot if similar questions but can't understand where is my problem. I did it just like i saw it in tutorial video in youtube (don't know shall i post the link here) but like always it is ok on the video but not on my project :D I tried with port 465 and encryption ssl also but without result. Will please you for some advice! Thank you in advance!

actionContact:

```<code>public function actionContact()
    {
        $model = new ContactForm();

        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }
</code>```

mailer config:

```<code>'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@app/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',
                'username' => 'tomaivanovtomov@gmail.com',
                'password' => 'password',
                'port' => '587',
                'encryption' => 'tls',
            ],
        ],
</code>```

and params:

```<code>return [
    'adminEmail' => 'tomaivanovtomov@gmail.com',
];
</code>```

I am pretty far from familiar with those emails things and i am still learning so please do not get mad at me for the pathetic question :)

EDIT:
ContactForm model:

```<code><?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * ContactForm is the model behind the contact form.
 */
class ContactForm extends Model
{
    public $name;
    public $email;
    public $title;
    public $body;
    public $verifyCode;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // name, email, subject and body are required
            [['name', 'email', 'title', 'body'], 'required'],
            // email has to be a valid email address
            ['email', 'email'],
            // verifyCode needs to be entered correctly
            ['verifyCode', 'captcha'],
        ];
    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Name:',
            'email' => 'Email:',
            'title' => 'Title:',
            'body' => 'Connect with us :)',
            'verifyCode' => 'Verification Code'
        ];
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     * @param string $email the target email address
     * @return bool whether the model passes validation
     */
    public function contact($email)
    {
        if ($this->validate()) {
            Yii::$app->mailer->compose()
                ->setTo($email)
                ->setFrom([$this->email => $this->name])
                ->setSubject($this->subject)
                ->setTextBody($this->body)
                ->send();

            return true;
        }
        return false;
    }
}
</code>```

答:
I wont boggle you with terms and code at the beginning.Just check whether security for less secure apps is OFF in your google account or not.If it is ON then turn it OFF.If all your settings are correct then this could be the unexpected glitch. Revert to me if that doesn't help.
After adding the smtp configuration in config I used this to send my emails(also I don't remember adding any extra params to my config):

```<code> $value=Yii::$app->mailer->compose()
->setFrom('tomaivanovtomov@gmail.com')
->setTo($model->emailAddress)
->setSubject($model->subject)
->setHtmlBody($model->content)
->attach($model->attachment)
->send();
</code>```

where the emailAddress will be filled by various users when they fill out the form, if u have one.If that is not the case and you have the emails stored elsewhere then you will have to fetch them in a php variable and replace $model->emailAddress with that variable.

Body:
I am trying to send email via swift mailer.I know there is a lot if similar questions but can't understand where is my problem. I did it just like i saw it in tutorial video in youtube (don't know shall i post the link here) but like always it is ok on the video but not on my project :D I tried with port 465 and encryption ssl also but without result. Will please you for some advice! Thank you in advance!

actionContact:

public function actionContact()
    {
        $model = new ContactForm();

        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

mailer config:

'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@app/mail',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => 'smtp.gmail.com',
                'username' => 'tomaivanovtomov@gmail.com',
                'password' => 'password',
                'port' => '587',
                'encryption' => 'tls',
            ],
        ],

and params:

return [
    'adminEmail' => 'tomaivanovtomov@gmail.com',
];

I am pretty far from familiar with those emails things and i am still learning so please do not get mad at me for the pathetic question :)

EDIT:
ContactForm model:

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * ContactForm is the model behind the contact form.
 */
class ContactForm extends Model
{
    public $name;
    public $email;
    public $title;
    public $body;
    public $verifyCode;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // name, email, subject and body are required
            [['name', 'email', 'title', 'body'], 'required'],
            // email has to be a valid email address
            ['email', 'email'],
            // verifyCode needs to be entered correctly
            ['verifyCode', 'captcha'],
        ];
    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Name:',
            'email' => 'Email:',
            'title' => 'Title:',
            'body' => 'Connect with us :)',
            'verifyCode' => 'Verification Code'
        ];
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     * @param string $email the target email address
     * @return bool whether the model passes validation
     */
    public function contact($email)
    {
        if ($this->validate()) {
            Yii::$app->mailer->compose()
                ->setTo($email)
                ->setFrom([$this->email => $this->name])
                ->setSubject($this->subject)
                ->setTextBody($this->body)
                ->send();

            return true;
        }
        return false;
    }
}

Body:
I wont boggle you with terms and code at the beginning.Just check whether security for less secure apps is OFF in your google account or not.If it is ON then turn it OFF.If all your settings are correct then this could be the unexpected glitch. Revert to me if that doesn't help.
After adding the smtp configuration in config I used this to send my emails(also I don't remember adding any extra params to my config):

 $value=Yii::$app->mailer->compose()
->setFrom('tomaivanovtomov@gmail.com')
->setTo($model->emailAddress)
->setSubject($model->subject)
->setHtmlBody($model->content)
->attach($model->attachment)
->send();

where the emailAddress will be filled by various users when they fill out the form, if u have one.If that is not the case and you have the emails stored elsewhere then you will have to fetch them in a php variable and replace $model->emailAddress with that variable.


来源: stackexchange

问:
Change of property with numbered name in Java
I have a huge field of graphic elements in my GUI, and I need to change their property according to value I have.

I want to avoid writing out switch, although it will work, it seems stupid.
I have graphic properties in HBox named r0 - r200, and I want to change opacity of element corresponding with returned value from other functions.

Is there some clever way, better than:

```<code>switch(note.offGraphic()){

    case 0:
        flat6.setOpacity(1);
        break;
    case 1:
        flat5.setOpacity(1);
        break;
    case 2:
        flat4.setOpacity(1);
        break;
    case 3:
        flat3.setOpacity(1);
        break;
    case 4:
        flat2.setOpacity(1);
        break;
    case 5:
        flat1.setOpacity(1);
    case 6:
        ok.setOpacity(1);
        break;
` and on and on
</code>```

答:
Create java array and insert each variable on corresponding index. Like this:

```<code>Object[] flats = new Object[numberOfFlats];
</code>```

To fill it do:

```<code>    flats[0]=flat6;
        flats[1]=flat5;
        flats[2]=flat4;
    .....................
.........................
........
</code>```

Now to get it use:

```<code>((Flat)flats[note.offGraphic()]).setOpacity(1);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a huge field of graphic elements in my GUI, and I need to change their property according to value I have.

I want to avoid writing out switch, although it will work, it seems stupid.
I have graphic properties in HBox named r0 - r200, and I want to change opacity of element corresponding with returned value from other functions.

Is there some clever way, better than:

switch(note.offGraphic()){

    case 0:
        flat6.setOpacity(1);
        break;
    case 1:
        flat5.setOpacity(1);
        break;
    case 2:
        flat4.setOpacity(1);
        break;
    case 3:
        flat3.setOpacity(1);
        break;
    case 4:
        flat2.setOpacity(1);
        break;
    case 5:
        flat1.setOpacity(1);
    case 6:
        ok.setOpacity(1);
        break;
` and on and on

Body:
Create java array and insert each variable on corresponding index. Like this:

Object[] flats = new Object[numberOfFlats];

To fill it do:

    flats[0]=flat6;
        flats[1]=flat5;
        flats[2]=flat4;
    .....................
.........................
........

Now to get it use:

((Flat)flats[note.offGraphic()]).setOpacity(1);


问:
C# equivalent HGlobal Pascal
I'm converting the pascal interface into C#. What is the C# equivalent of the HGlobal data type?

```<code>type
  SomeFunction= function(var global : HGlobal) : integer; cdecl;
</code>```

How would SomeFunction be declared in C#?

答:
What is the C# equivalent of the HGlobal data type?

The equivalent type is IntPtr.

How would SomeFunction be declared in C#?

```<code>[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int SomeFunction(ref IntPtr global);
</code>```

Title: C# equivalent HGlobal Pascal

Body:
I'm converting the pascal interface into C#. What is the C# equivalent of the HGlobal data type?

type
  SomeFunction= function(var global : HGlobal) : integer; cdecl;

How would SomeFunction be declared in C#?

Body:
What is the C# equivalent of the HGlobal data type?

The equivalent type is IntPtr.

How would SomeFunction be declared in C#?

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int SomeFunction(ref IntPtr global);


问:
How to configure Unity 2.0 at runtime to intercept INotifyPropertyChanged?
http://msdn.microsoft.com/en-us/library/ff660851(v=PandP.20).aspx provides a sample of how to implement IInterceptionBehavior to add INotifyPropertyChanged support. What the sample does not include is how to configure NotifyPropertyChangedBehavior to be used at runtime. All the googling I've done has not given me a working answer.

I'm new to AOP and IoC so maybe I've got the concept wrong as well. This is what I want to do:

```<code>using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

static class AppMain
{
    public static void Main()
    {
        // Configure Unity.
        var container = new UnityContainer();

        container.AddNewExtension<Interception>();

        // todo: Register an interface instead of a type.
        container.RegisterType<Customer>(new Interceptor<VirtualMethodInterceptor>(),
                                         new InterceptionBehavior<NotifyPropertyChangedBehavior>());

        var propertyChangedCount = 0;
        var customer = new Customer();

        customer.PropertyChanged += (s, e) => propertyChangedCount += 1;

        // Update customer and send property changed event.
        customer.FirstName = "what ever";

        if (propertyChangedCount != 1)
        {
            Console.Write("Failed!");
        }
        else
        {
            Console.WriteLine("Success!");
        }

        Console.WriteLine();
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();

    }

    static void customer_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        throw new NotImplementedException();
    }

    public class Customer : MarshalByRefObject, INotifyPropertyChanged
    {

        private string _firstName;
        public event PropertyChangedEventHandler PropertyChanged;

        // todo: Does the property have to be virtual (overridable).
        public virtual string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                // Unity Interception to do the following RaiseEvent
                //if (PropertyChanged != null)
                //{
                //    PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
                //}
            }
        }

    }

    // Copied from http://msdn.microsoft.com/en-us/library/ff660851(v=PandP.20).aspx
    class NotifyPropertyChangedBehavior : IInterceptionBehavior
    {
        private event PropertyChangedEventHandler propertyChanged;

        private static readonly MethodInfo addEventMethodInfo =
            typeof(INotifyPropertyChanged).GetEvent("PropertyChanged").GetAddMethod();

        private static readonly MethodInfo removeEventMethodInfo =
            typeof(INotifyPropertyChanged).GetEvent("PropertyChanged").GetRemoveMethod();

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase == addEventMethodInfo)
            {
                return AddEventSubscription(input, getNext);
            }
            if (input.MethodBase == removeEventMethodInfo)
            {
                return RemoveEventSubscription(input, getNext);
            }
            if (IsPropertySetter(input))
            {
                return InterceptPropertySet(input, getNext);
            }
            return getNext()(input, getNext);
        }

        public bool WillExecute
        {
            get { return true; }
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return new[] { typeof(INotifyPropertyChanged) };
        }

        private IMethodReturn AddEventSubscription(IMethodInvocation input,
                                                   GetNextInterceptionBehaviorDelegate getNext)
        {
            var subscriber = (PropertyChangedEventHandler)input.Arguments[0];

            propertyChanged += subscriber;
            return input.CreateMethodReturn(null);
        }

        private IMethodReturn RemoveEventSubscription(IMethodInvocation input,
                                                      GetNextInterceptionBehaviorDelegate getNext)
        {
            var subscriber = (PropertyChangedEventHandler)input.Arguments[0];

            propertyChanged -= subscriber;
            return input.CreateMethodReturn(null);
        }

        private static bool IsPropertySetter(IMethodInvocation input)
        {
            return input.MethodBase.IsSpecialName && input.MethodBase.Name.StartsWith("set_");
        }

        private IMethodReturn InterceptPropertySet(IMethodInvocation input,
                                                   GetNextInterceptionBehaviorDelegate getNext)
        {
            var propertyName = input.MethodBase.Name.Substring(4);
            var returnValue = getNext()(input, getNext);
            var subscribers = propertyChanged;

            if (subscribers != null)
            {
                subscribers(input.Target, new PropertyChangedEventArgs(propertyName));
            }

            return returnValue;
        }
    }
}
</code>```

答:
Tim

Wouldn't some IL weaving make this easier?

NotifyPropertyWeaver Or http://www.sharpcrafters.com/ ?

ContentLicense: CC BY-SA 2.5

Body:
http://msdn.microsoft.com/en-us/library/ff660851(v=PandP.20).aspx provides a sample of how to implement IInterceptionBehavior to add INotifyPropertyChanged support. What the sample does not include is how to configure NotifyPropertyChangedBehavior to be used at runtime. All the googling I've done has not given me a working answer.

I'm new to AOP and IoC so maybe I've got the concept wrong as well. This is what I want to do:

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

static class AppMain
{
    public static void Main()
    {
        // Configure Unity.
        var container = new UnityContainer();

        container.AddNewExtension<Interception>();

        // todo: Register an interface instead of a type.
        container.RegisterType<Customer>(new Interceptor<VirtualMethodInterceptor>(),
                                         new InterceptionBehavior<NotifyPropertyChangedBehavior>());

        var propertyChangedCount = 0;
        var customer = new Customer();

        customer.PropertyChanged += (s, e) => propertyChangedCount += 1;

        // Update customer and send property changed event.
        customer.FirstName = "what ever";

        if (propertyChangedCount != 1)
        {
            Console.Write("Failed!");
        }
        else
        {
            Console.WriteLine("Success!");
        }

        Console.WriteLine();
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();

    }

    static void customer_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        throw new NotImplementedException();
    }

    public class Customer : MarshalByRefObject, INotifyPropertyChanged
    {

        private string _firstName;
        public event PropertyChangedEventHandler PropertyChanged;

        // todo: Does the property have to be virtual (overridable).
        public virtual string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                // Unity Interception to do the following RaiseEvent
                //if (PropertyChanged != null)
                //{
                //    PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
                //}
            }
        }

    }

    // Copied from http://msdn.microsoft.com/en-us/library/ff660851(v=PandP.20).aspx
    class NotifyPropertyChangedBehavior : IInterceptionBehavior
    {
        private event PropertyChangedEventHandler propertyChanged;

        private static readonly MethodInfo addEventMethodInfo =
            typeof(INotifyPropertyChanged).GetEvent("PropertyChanged").GetAddMethod();

        private static readonly MethodInfo removeEventMethodInfo =
            typeof(INotifyPropertyChanged).GetEvent("PropertyChanged").GetRemoveMethod();

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (input.MethodBase == addEventMethodInfo)
            {
                return AddEventSubscription(input, getNext);
            }
            if (input.MethodBase == removeEventMethodInfo)
            {
                return RemoveEventSubscription(input, getNext);
            }
            if (IsPropertySetter(input))
            {
                return InterceptPropertySet(input, getNext);
            }
            return getNext()(input, getNext);
        }

        public bool WillExecute
        {
            get { return true; }
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return new[] { typeof(INotifyPropertyChanged) };
        }

        private IMethodReturn AddEventSubscription(IMethodInvocation input,
                                                   GetNextInterceptionBehaviorDelegate getNext)
        {
            var subscriber = (PropertyChangedEventHandler)input.Arguments[0];

            propertyChanged += subscriber;
            return input.CreateMethodReturn(null);
        }

        private IMethodReturn RemoveEventSubscription(IMethodInvocation input,
                                                      GetNextInterceptionBehaviorDelegate getNext)
        {
            var subscriber = (PropertyChangedEventHandler)input.Arguments[0];

            propertyChanged -= subscriber;
            return input.CreateMethodReturn(null);
        }

        private static bool IsPropertySetter(IMethodInvocation input)
        {
            return input.MethodBase.IsSpecialName && input.MethodBase.Name.StartsWith("set_");
        }

        private IMethodReturn InterceptPropertySet(IMethodInvocation input,
                                                   GetNextInterceptionBehaviorDelegate getNext)
        {
            var propertyName = input.MethodBase.Name.Substring(4);
            var returnValue = getNext()(input, getNext);
            var subscribers = propertyChanged;

            if (subscribers != null)
            {
                subscribers(input.Target, new PropertyChangedEventArgs(propertyName));
            }

            return returnValue;
        }
    }
}


问:
An ejected project cannot use the build command anymore
I am new in Angular. I accidentally ejected my project using command-line, i don't remember which command i used. but when i try to run command

ng serve --open

it throws me an error of

An ejected project cannot use the build command anymore.

I also re-installed angular-cli as said in this Stackoverflow Question but no use.

Can anyone help me with this?

答:
open the angular-cli.json, you should see this at the top

```<code>"project": {
   "name": "proj-name",
   "ejected": true,
}
</code>```

remove the ejected part and it should work

Body:
open the angular-cli.json, you should see this at the top

"project": {
   "name": "proj-name",
   "ejected": true,
}

remove the ejected part and it should work

ContentLicense: CC BY-SA 4.0


问:
Javascript - Changing string to match regex
I have a text area which I’m getting the value from and want to format this using a regex expression.My regex expression requires a number first space then characters then a multiline break.

```<code>This is my string = "282 MDJSL   889 MSHS 888 MSSH";
</code>```

(This string could be random each time ).

So I want to turn this string this so its formated and eventurally put into a JSObject

```<code>282 MDJSL
889 MSHS
888 MSSH
</code>```

This is my current code:

```<code>var textValue = $('#texbox2').val().toString();
var regex = new RegExp('/^[\s\S]*[\d\s]+[a-zA-Z0-9_-]+[\n]+$/');
var str = textValue;
 if (regex.test(textValue) === true) {

  // Match found
  console.log('Regex match');

  if ((m = regex.exec(textValue)) !== null) {

   // The result can be accessed through the `m`-variable.
   m.forEach((match, groupIndex) => {
      console.log(`Found match, group ${groupIndex}: ${match}`);
   });

  }
 }

 // Match not found
 else {
  // Not replacing it into the format i want
  str = str.replace(regex, str);
 }
</code>```

thanks

答:
You could split by whitespace and a positive lookahead of a number.

var string = "282 MDJSL \n\n  889 MSHS 888 MSSH",
    array = string.split(/\s+(?=\d)/);

console.log(array);```

Body:
I have a text area which I’m getting the value from and want to format this using a regex expression.My regex expression requires a number first space then characters then a multiline break.

This is my string = "282 MDJSL   889 MSHS 888 MSSH";

(This string could be random each time ).

So I want to turn this string this so its formated and eventurally put into a JSObject

282 MDJSL
889 MSHS
888 MSSH

This is my current code:

var textValue = $('#texbox2').val().toString();
var regex = new RegExp('/^[\s\S]*[\d\s]+[a-zA-Z0-9_-]+[\n]+$/');
var str = textValue;
 if (regex.test(textValue) === true) {

  // Match found
  console.log('Regex match');

  if ((m = regex.exec(textValue)) !== null) {

   // The result can be accessed through the `m`-variable.
   m.forEach((match, groupIndex) => {
      console.log(`Found match, group ${groupIndex}: ${match}`);
   });

  }
 }

 // Match not found
 else {
  // Not replacing it into the format i want
  str = str.replace(regex, str);
 }

thanks


问:
Docker image with R (rocker/r.base) and python does not work when running on EC2, but local is fine
I have started using docker recently. Seems pretty exciting, the fact that you can build apps once and run them in any machine, sounds amazing!

The truth is that I have experienced something else. I have an R image as a base (rocker/r.base) and I want to install python to it, so I can run a flask app on the image which will expose an endpoint that once called, it will run an R script and log some results.

The whole thing is a part of a docker-compose file (there are 3-4 more images on the compose, all do a separate operation).

So I manage to build the image and run it locally with docker-compose.

The weird things starts when I try to deploy the image to an AWS EC2 instance. So far, I have managed to run the other images on AWS. But for this specific image, the build failed because of some library dependency errors that I get, and after fixing this, the execution is failing. To get into a few more details:

Initially, I was getting dependencies errors on AWS while building (no such errors locally). So, in order to overcome that, I modified my Dockerfile so it installs these dependencies individually. This worked! My image was finally built. But then:

I manage to get the web app exposed to an endpoint. I try then to invoke the R script, and I get that the system cannot find the Rscript command (I explicity define it to /usr/bin/Rscript which works fine locally - and I use python's subprocess.call to run the R script).

So it seems that Rscript is not installed on my container at AWS!! This could be because of the manual installs that I did, in which I have used --allow-downgrades so the proper versions will be installed. I suspect that these downgrades perhaps remove some libraries?

Anyway, I can't really figure out what is going wrong. It just sounds terrible to me. I thought that once you get something running locally, then you can run it anywhere with docker, but it seems that either this is NOT the case, or I am missing something VERY BAD.

BTW, my local an production (AWS) server use same version of docker (1.12.3, build 6b644ec) and docker-compose (version 1.7.0, build 0d7bf73) and I have enabled i386 architecture to both machines (just in case this was the issue, both are actually using amd64).

Not sure if I expect some answer from this post, so far I have not found similar situations while googling, but if anyone has faced such situation before, speak freely! :)

Cheers,
Babis

UPDATE:

You are absolutely right Yaron. I attach some more info. First, the docker-compose.yml:

```<code>version: '2'
services:
  recommend.service:    # This service is fine both locally and on AWS
    build:
      context: .
      dockerfile: ./docker/recommend.service.Dockerfile
    ports:
     - "8081:8081"
    restart: always
    env_file: .env
  cltv.service:     # This is the service that has problems to be built and run on AWS. Locally is fine
    build:
      context: .
      dockerfile: ./docker/cltv.service.Dockerfile
    ports:
     - "8082:8082"
    restart: always
    env_file: .env
  rabbit:       # Works everywhere
    image: rabbitmq
    hostname: smart.rabbitmq
    restart: always
    volumes:
      - rabbit.data:/var/lib/rabbitmq
  celery:       # Works everywhere
    build:
      context: .
      dockerfile: ./docker/smart.celery.Dockerfile
    depends_on:
     - rabbit
    restart: always
    env_file: .env
volumes:
  rabbit.data:
    driver: local
</code>```

And the ./docker/cltv.service.Dockerfile:

```<code>## Adapted from zamora/r-devtools
## Start with the official rocker image (lightweight Debian)
FROM rocker/r-base:latest

MAINTAINER Babis <cparavalos@gmail.com>

ENV DEBIAN_FRONTEND noninteractive

RUN mkdir -p /usr/src/cltv_app
WORKDIR      /usr/src/cltv_app

COPY requirements.txt           /usr/src/cltv_app/requirements.txt
COPY requirements-cltv.txt      /usr/src/cltv_app/requirements-cltv.txt
COPY cltv/                      /usr/src/cltv_app/cltv/
COPY services/                  /usr/src/cltv_app/services/

# Install external dependencies
RUN apt-get update -qq \
 && apt-get install -y --no-install-recommends --allow-downgrades \
 libcurl3=7.50.1-1 \        # I added that because of dependencies issue while building in the server. Locally I didn't need it
 libcurl4-openssl-dev \
 libssl-dev \
 libsqlite3-dev \
 libxml2-dev \
 qpdf \
 vim \
 libgsl-dev \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/ \
 && rm -rf /tmp/downloaded_packages/ /tmp/*.rds

# Install devtools and testthat
RUN install2.r --error \
    devtools \
    testthat \
    gsl

# Install some required libraries
RUN Rscript -e 'devtools::install_github("mplatzer/BTYDplus", dependencies=TRUE)'

## Note: I had added the below in order to get a succesful build because of the dependencies errors. In my local, the image is built and run without these!!!
#RUN apt-get update
#RUN apt-get install -y --allow-downgrades libkrb5support0=1.14.3+dfsg-2
#RUN apt-get install -y libkrb5-3=1.14.3+dfsg-2
#RUN apt-get install -y libk5crypto3=1.14.3+dfsg-2
#RUN apt-get install -y libgssapi-krb5-2=1.14.3+dfsg-2
#RUN apt-get update
#RUN apt-get install -y krb5-multidev

# Install python and postgres required packages
RUN apt-get update
RUN apt-get install -y python3.4 python3-dev libpq-dev python-pip

RUN pip install --no-cache-dir -r requirements.txt
RUN pip install --no-cache-dir -r requirements-cltv.txt
RUN pip install -e cltv/.

EXPOSE 8082

# Set a big timeout
CMD ["/usr/local/bin/gunicorn", "--log-config", "cltv/logging.conf",  "cltv.wsgi:app", "--bind", "0.0.0.0:8082", "--timeout", "86400"]
</code>```

And I trigger the whole process with:

```<code>docker-compose up --build -d
</code>```

Thanks, please suggest if you need to see something else on the setup!

答:
Reason was that r.base had conflicts with some python packages, and could not use python with this R image.

I ended up with a solution of a docker-inside-docker image, that had ubuntu as base. I installed the required python libraries in the ubuntu image, installed docker on it and inside this image I used docker to build this r.base image. Then I used docker run from inside ubuntu container, and manage to do my work :)

Body:
I have started using docker recently. Seems pretty exciting, the fact that you can build apps once and run them in any machine, sounds amazing!

The truth is that I have experienced something else. I have an R image as a base (rocker/r.base) and I want to install python to it, so I can run a flask app on the image which will expose an endpoint that once called, it will run an R script and log some results.

The whole thing is a part of a docker-compose file (there are 3-4 more images on the compose, all do a separate operation).

So I manage to build the image and run it locally with docker-compose.

The weird things starts when I try to deploy the image to an AWS EC2 instance. So far, I have managed to run the other images on AWS. But for this specific image, the build failed because of some library dependency errors that I get, and after fixing this, the execution is failing. To get into a few more details:

Initially, I was getting dependencies errors on AWS while building (no such errors locally). So, in order to overcome that, I modified my Dockerfile so it installs these dependencies individually. This worked! My image was finally built. But then:

I manage to get the web app exposed to an endpoint. I try then to invoke the R script, and I get that the system cannot find the Rscript command (I explicity define it to /usr/bin/Rscript which works fine locally - and I use python's subprocess.call to run the R script).

So it seems that Rscript is not installed on my container at AWS!! This could be because of the manual installs that I did, in which I have used --allow-downgrades so the proper versions will be installed. I suspect that these downgrades perhaps remove some libraries?

Anyway, I can't really figure out what is going wrong. It just sounds terrible to me. I thought that once you get something running locally, then you can run it anywhere with docker, but it seems that either this is NOT the case, or I am missing something VERY BAD.

BTW, my local an production (AWS) server use same version of docker (1.12.3, build 6b644ec) and docker-compose (version 1.7.0, build 0d7bf73) and I have enabled i386 architecture to both machines (just in case this was the issue, both are actually using amd64).

Not sure if I expect some answer from this post, so far I have not found similar situations while googling, but if anyone has faced such situation before, speak freely! :)

Cheers,
Babis

UPDATE:

You are absolutely right Yaron. I attach some more info. First, the docker-compose.yml:

version: '2'
services:
  recommend.service:    # This service is fine both locally and on AWS
    build:
      context: .
      dockerfile: ./docker/recommend.service.Dockerfile
    ports:
     - "8081:8081"
    restart: always
    env_file: .env
  cltv.service:     # This is the service that has problems to be built and run on AWS. Locally is fine
    build:
      context: .
      dockerfile: ./docker/cltv.service.Dockerfile
    ports:
     - "8082:8082"
    restart: always
    env_file: .env
  rabbit:       # Works everywhere
    image: rabbitmq
    hostname: smart.rabbitmq
    restart: always
    volumes:
      - rabbit.data:/var/lib/rabbitmq
  celery:       # Works everywhere
    build:
      context: .
      dockerfile: ./docker/smart.celery.Dockerfile
    depends_on:
     - rabbit
    restart: always
    env_file: .env
volumes:
  rabbit.data:
    driver: local

And the ./docker/cltv.service.Dockerfile:

## Adapted from zamora/r-devtools
## Start with the official rocker image (lightweight Debian)
FROM rocker/r-base:latest

MAINTAINER Babis <cparavalos@gmail.com>

ENV DEBIAN_FRONTEND noninteractive

RUN mkdir -p /usr/src/cltv_app
WORKDIR      /usr/src/cltv_app

COPY requirements.txt           /usr/src/cltv_app/requirements.txt
COPY requirements-cltv.txt      /usr/src/cltv_app/requirements-cltv.txt
COPY cltv/                      /usr/src/cltv_app/cltv/
COPY services/                  /usr/src/cltv_app/services/

# Install external dependencies
RUN apt-get update -qq \
 && apt-get install -y --no-install-recommends --allow-downgrades \
 libcurl3=7.50.1-1 \        # I added that because of dependencies issue while building in the server. Locally I didn't need it
 libcurl4-openssl-dev \
 libssl-dev \
 libsqlite3-dev \
 libxml2-dev \
 qpdf \
 vim \
 libgsl-dev \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/ \
 && rm -rf /tmp/downloaded_packages/ /tmp/*.rds

# Install devtools and testthat
RUN install2.r --error \
    devtools \
    testthat \
    gsl

# Install some required libraries
RUN Rscript -e 'devtools::install_github("mplatzer/BTYDplus", dependencies=TRUE)'

## Note: I had added the below in order to get a succesful build because of the dependencies errors. In my local, the image is built and run without these!!!
#RUN apt-get update
#RUN apt-get install -y --allow-downgrades libkrb5support0=1.14.3+dfsg-2
#RUN apt-get install -y libkrb5-3=1.14.3+dfsg-2
#RUN apt-get install -y libk5crypto3=1.14.3+dfsg-2
#RUN apt-get install -y libgssapi-krb5-2=1.14.3+dfsg-2
#RUN apt-get update
#RUN apt-get install -y krb5-multidev

# Install python and postgres required packages
RUN apt-get update
RUN apt-get install -y python3.4 python3-dev libpq-dev python-pip

RUN pip install --no-cache-dir -r requirements.txt
RUN pip install --no-cache-dir -r requirements-cltv.txt
RUN pip install -e cltv/.

EXPOSE 8082

# Set a big timeout
CMD ["/usr/local/bin/gunicorn", "--log-config", "cltv/logging.conf",  "cltv.wsgi:app", "--bind", "0.0.0.0:8082", "--timeout", "86400"]

And I trigger the whole process with:

docker-compose up --build -d

Thanks, please suggest if you need to see something else on the setup!


问:
Create both static and shared library with GNU libtool?
I am using the GNU autotools (including automake!) for my project. I would like to know if I could create a static and a shared library using libtool? Or would the declarations be separate? Would this:

```<code>LT_INIT(shared static)
</code>```

work?

答:
Nothing besides LT_INIT is needed, it defaults to building both static and shared libraries. If you like, you can again explicitly state the defaults (but it is sort of redundant)

```LT_INIT
AC_ENABLE_SHARED
AC_ENABLE_STATIC```

edit: manual says LT_INIT([shared]) and LT_INIT([static]) (combined to LT_INIT([shared static]) shall also work. Also manual's more precise wording on what's default when LT_INIT is given:
this macro turns on shared libraries if they are
     available, and also enables static libraries if they don't
     conflict with the shared libraries.

Body:
I am using the GNU autotools (including automake!) for my project. I would like to know if I could create a static and a shared library using libtool? Or would the declarations be separate? Would this:

LT_INIT(shared static)

work?

Body:
Nothing besides LT_INIT is needed, it defaults to building both static and shared libraries. If you like, you can again explicitly state the defaults (but it is sort of redundant)

LT_INIT
AC_ENABLE_SHARED
AC_ENABLE_STATIC

edit: manual says LT_INIT([shared]) and LT_INIT([static]) (combined to LT_INIT([shared static]) shall also work. Also manual's more precise wording on what's default when LT_INIT is given:
this macro turns on shared libraries if they are
     available, and also enables static libraries if they don't
     conflict with the shared libraries.


问:
Best way to pass objects between controller actions in grails
I want a link to open up another view in my webapp to display information about the specified object.
What is the best way to pass objects between controllers actions in grail?</p>

答:
The earlier answers are incomplete. So, I am compiling them along with my inputs and making them clearer.

You have two options:

Chaining the actions:

```<code>def action1() = {
    DomainClass domainInstance = DomainClass.findById(params.id);
    chain (action: 'action2', model: [domainInstance: domainInstance]);
}

def action2() = {
    DomainClass domainInstance = chainModel?.domainInstance ?: DomainClass.findById(params.id);
    [domainInstance: domainInstance];
}
</code>```

However, the successor action seems to use a fresh database session
instead of reusing that of the predecessor (which may also be
configurable in Grails, I don't know how though). So any lazily
loaded entity may not be fully loaded in the successor action and
may give LazyInitializationException (depending on your ORM configuration of course).

Forwarding the request:

```<code>def action1() = {
    DomainClass domainInstance = DomainClass.findById(params.id);
    forward (action: 'action2', model: [domainInstance: domainInstance]);
}

def action2() = {
    DomainClass domainInstance = request?.domainInstance ?: DomainClass.findById(params.id);
    [domainInstance: domainInstance];
}
</code>```

Unlike in the previous case, request forwarding reuses the existing session so lazy loading issues will not occur.

As you can see, the syntax for both is almost identical. But one should prefer request forwarding as per the requirement in question due to the issue mentioned above. Another important detail is regarding the URL viewed in the address bar on/after page loading. Forwarding the requests will PRESERVE the page URL while chaining the actions will CHANGE the page URL to that of the latest action.

Body:
The earlier answers are incomplete. So, I am compiling them along with my inputs and making them clearer.

You have two options:

Chaining the actions:

def action1() = {
    DomainClass domainInstance = DomainClass.findById(params.id);
    chain (action: 'action2', model: [domainInstance: domainInstance]);
}

def action2() = {
    DomainClass domainInstance = chainModel?.domainInstance ?: DomainClass.findById(params.id);
    [domainInstance: domainInstance];
}

However, the successor action seems to use a fresh database session
instead of reusing that of the predecessor (which may also be
configurable in Grails, I don't know how though). So any lazily
loaded entity may not be fully loaded in the successor action and
may give LazyInitializationException (depending on your ORM configuration of course).

Forwarding the request:

def action1() = {
    DomainClass domainInstance = DomainClass.findById(params.id);
    forward (action: 'action2', model: [domainInstance: domainInstance]);
}

def action2() = {
    DomainClass domainInstance = request?.domainInstance ?: DomainClass.findById(params.id);
    [domainInstance: domainInstance];
}

Unlike in the previous case, request forwarding reuses the existing session so lazy loading issues will not occur.

As you can see, the syntax for both is almost identical. But one should prefer request forwarding as per the requirement in question due to the issue mentioned above. Another important detail is regarding the URL viewed in the address bar on/after page loading. Forwarding the requests will PRESERVE the page URL while chaining the actions will CHANGE the page URL to that of the latest action.


问:
How to get all month record count in laravel
I have applied group by with with created_at column using DB query but like to do it by laravel eloquent

Output should be like this:-

```<code>Array
(
  [1] => 2
  [2] => 3
  [3] => 7
  [4] => 4
  [5] => 5
  [6] => 7
  [7] => 2
  [8] => 9
  [9] => 0
  [10] => 4
  [11] => 0
  [12] => 0
)
</code>```

Please provide any help me to do this.

答:
Please try the below steps:-

Run composer to install package:  composer require nesbot/carbon

On top of your code: use Carbon\Carbon;

Suppose i have Model User,

```<code>$users = User::select('id', 'created_at')
->get()
->groupBy(function($date) {
    //return Carbon::parse($date->created_at)->format('Y'); // grouping by years
    return Carbon::parse($date->created_at)->format('m'); // grouping by months
});

$usermcount = [];
$userArr = [];

foreach ($users as $key => $value) {
    $usermcount[(int)$key] = count($value);
}

for($i = 1; $i <= 12; $i++){
    if(!empty($usermcount[$i])){
        $userArr[$i] = $usermcount[$i];
    }else{
        $userArr[$i] = 0;
    }
}
</code>```

Hope it will help you to make array like that.

Body:
I have applied group by with with created_at column using DB query but like to do it by laravel eloquent

Output should be like this:-

Array
(
  [1] => 2
  [2] => 3
  [3] => 7
  [4] => 4
  [5] => 5
  [6] => 7
  [7] => 2
  [8] => 9
  [9] => 0
  [10] => 4
  [11] => 0
  [12] => 0
)

Please provide any help me to do this.

Body:
Please try the below steps:-

Run composer to install package:  composer require nesbot/carbon

On top of your code: use Carbon\Carbon;

Suppose i have Model User,

$users = User::select('id', 'created_at')
->get()
->groupBy(function($date) {
    //return Carbon::parse($date->created_at)->format('Y'); // grouping by years
    return Carbon::parse($date->created_at)->format('m'); // grouping by months
});

$usermcount = [];
$userArr = [];

foreach ($users as $key => $value) {
    $usermcount[(int)$key] = count($value);
}

for($i = 1; $i <= 12; $i++){
    if(!empty($usermcount[$i])){
        $userArr[$i] = $usermcount[$i];
    }else{
        $userArr[$i] = 0;
    }
}

Hope it will help you to make array like that.


问:
Your password does not satisfy the current policy requirements
I want to create a new user in MySQL with the syntax:

```<code>create user 'demo'@'localhost' identified by 'password';
</code>```

But it returns an error:

Your password does not satisfy the current policy requirements.

I have tried many passwords but they don't work. How can I fix this?

答:
Because of your password. You can see password validate configuration metrics using the following query in MySQL client:

SHOW VARIABLES LIKE 'validate_password%';
```
<p>The output should be something like that :</p>
```+--------------------------------------+-------+
| Variable_name                        | Value |
+--------------------------------------+-------+
| validate_password.check_user_name    | ON    |
| validate_password.dictionary_file    |       |
| validate_password.length             | 6     |
| validate_password.mixed_case_count   | 1     |
| validate_password.number_count       | 1     |
| validate_password.policy             | LOW   |
| validate_password.special_char_count | 1     |
+--------------------------------------+-------+
```
<p>then you can set the password policy level lower, for example:</p>
```SET GLOBAL validate_password.length = 6;
SET GLOBAL validate_password.number_count = 0;
```

Check the MySQL Documentation.

Body:
I want to create a new user in MySQL with the syntax:

create user 'demo'@'localhost' identified by 'password';

But it returns an error:

Your password does not satisfy the current policy requirements.

I have tried many passwords but they don't work. How can I fix this?

Body:
Because of your password. You can see password validate configuration metrics using the following query in MySQL client:

SHOW VARIABLES LIKE 'validate_password%';

The output should be something like that :

+--------------------------------------+-------+
| Variable_name                        | Value |
+--------------------------------------+-------+
| validate_password.check_user_name    | ON    |
| validate_password.dictionary_file    |       |
| validate_password.length             | 6     |
| validate_password.mixed_case_count   | 1     |
| validate_password.number_count       | 1     |
| validate_password.policy             | LOW   |
| validate_password.special_char_count | 1     |
+--------------------------------------+-------+

then you can set the password policy level lower, for example:

SET GLOBAL validate_password.length = 6;
SET GLOBAL validate_password.number_count = 0;

Check the MySQL Documentation.


问:
Q Lookups TypeError Django
In my Car model I have the following fields: name, manufacturer, body, car_type and description.

I've implemented a search bar but when I search it's complaining:

```<code>Related Field got invalid lookup: icontains
</code>```

on Q(car_type__icontains=query)

Whats the issue here exactly?

```<code>query = request.GET.get("q")
if query:
    car = car.filter(
        Q(name__icontains=query) |
        Q(manufacturer__icontains=query) |
        Q(body__icontains=query) |
        Q(car_type__icontains=query)
    ).distinct()
</code>```

Models.py

```<code>class CarModelBase(models.Model):

    class Meta:
        abstract = True
    name = models.CharField(max_length=100)

class CarType(CarModelBase, SortableModelBase):
    class Meta(CarModelBase.Meta):
        ordering = ['order']
        verbose_name = 'Car Type'
        verbose_name_plural = 'Car Types'

    def __str__(self):
        return self.name

class Car(CarModelBase):
    manufacturer = SortableForeignKey(Manufacturer)
    car_type = SortableForeignKey(CarType)
    body = SortableForeignKey(Body)
    description = models.TextField()
</code>```

答:
If car_type is a foreign key, then you can't do Q(car_type__icontains=query). You need to specify the field on the CarTyoe model that you wish to search, for example:

```<code>Q(car_type__name__icontains=query)
</code>```

Title: Q Lookups TypeError Django

Body:
In my Car model I have the following fields: name, manufacturer, body, car_type and description.

I've implemented a search bar but when I search it's complaining:

Related Field got invalid lookup: icontains

on Q(car_type__icontains=query)

Whats the issue here exactly?

query = request.GET.get("q")
if query:
    car = car.filter(
        Q(name__icontains=query) |
        Q(manufacturer__icontains=query) |
        Q(body__icontains=query) |
        Q(car_type__icontains=query)
    ).distinct()

Models.py

class CarModelBase(models.Model):

    class Meta:
        abstract = True
    name = models.CharField(max_length=100)

class CarType(CarModelBase, SortableModelBase):
    class Meta(CarModelBase.Meta):
        ordering = ['order']
        verbose_name = 'Car Type'
        verbose_name_plural = 'Car Types'

    def __str__(self):
        return self.name

class Car(CarModelBase):
    manufacturer = SortableForeignKey(Manufacturer)
    car_type = SortableForeignKey(CarType)
    body = SortableForeignKey(Body)
    description = models.TextField()

Body:
If car_type is a foreign key, then you can't do Q(car_type__icontains=query). You need to specify the field on the CarTyoe model that you wish to search, for example:

Q(car_type__name__icontains=query)


问:
else branch of a swrl rule
I want to ask if it is possible to express the else branch of a rule in SWRL?
I know it can express p->q but i want to be able to assert r if non(p)

example
HeavyPrecipitation(?x) -> hasObservationTag(?x,FalsePositiveOutlier)

and now i want to say else hasObservationTag(?x,TruePositiveOutlier)

How can this be done?

thanks

答:
In a rule like (p->q) there is no way to say (not(p) -> ...); in OWL-DL+SWRL it will never be possible.

BUT, you can do things that may a be a workaround for your specific usage:

OWL : ComplementOf(ClassExpression) : work like a negation of
the ClassExpression

SWRL : DifferentIndividualsAtom(Arg1,Arg2) : useful to exclude
a Value or a Range

They are is the only way to express something that look like negation.

On your example :

```<code>then-rule   ClassAtom(HeavyPrecipitation,?x) -> propertyAtom(hasObservationTag,?x,FalsePositiveOutlier)

else-rule   ClassAtom(ComplementOf(HeavyPrecipitation),?x) -> propertyAtom(hasObservationTag,?x,TruePositiveOutlier)
</code>```

Note : the negation is tricky with Open World Assumption and DL; sometime both rules (the 'then' and 'else') can be true at the same time (mainly depend on how your class are defined). Sometime none of your rules will apply : it totaly depend on how you declare classes on your individuals.

Title: else branch of a swrl rule

Body:
In a rule like (p->q) there is no way to say (not(p) -> ...); in OWL-DL+SWRL it will never be possible.

BUT, you can do things that may a be a workaround for your specific usage:

OWL : ComplementOf(ClassExpression) : work like a negation of
the ClassExpression

SWRL : DifferentIndividualsAtom(Arg1,Arg2) : useful to exclude
a Value or a Range

They are is the only way to express something that look like negation.

On your example :

then-rule   ClassAtom(HeavyPrecipitation,?x) -> propertyAtom(hasObservationTag,?x,FalsePositiveOutlier)

else-rule   ClassAtom(ComplementOf(HeavyPrecipitation),?x) -> propertyAtom(hasObservationTag,?x,TruePositiveOutlier)

Note : the negation is tricky with Open World Assumption and DL; sometime both rules (the 'then' and 'else') can be true at the same time (mainly depend on how your class are defined). Sometime none of your rules will apply : it totaly depend on how you declare classes on your individuals.


问:
Data mining termin "fledged"?
Please tell what is termin "full fledged KI"? As i understand it is part of data mining for text analyzing. Am i right? Some interesting and useful links will be fine!

Thank you!!!

答: My guess is that it is a typo of AI or a near-synonym, given the context, and my knowledge of the topic.</p>

Title: Data mining termin "fledged"?


问:
Eclipse Not Opening. Worked fine yesterday. Not opening today. Getting error log message
Here's the error log that it directed me to. I'm very new to coding and have no idea what it's asking me to fix. I tried to look it up but the few solutions I could find didnt't help. I changed the environment variable HOME to %USERPROFILE% but I don't think that was the right thing to do. Please help!

I've tried re-installing Eclipse but it still won't work.

```<code>   !SESSION 2017-03-28 10:56:50.318 -----------------------------------------------
    eclipse.buildId=4.6.2.M20161124-1400
    java.version=1.8.0_112
    java.vendor=Oracle Corporation
    BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_CA
    Framework arguments:  -product org.eclipse.epp.package.java.product C:\Users\ssfro\OneDrive\Fanshawe\INFO-1150 Programming\workspace\School     Projects\src\Spencer_Frost_INFO1150_Project.java
    Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product C:\Users\ssfro\OneDrive\Fanshawe\INFO-1150 Programming\workspace\School Projects\src\Spencer_Frost_INFO1150_Project.java

    !ENTRY org.eclipse.core.resources 2 10035 2017-03-28 10:56:52.694
    !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

!ENTRY org.eclipse.osgi 4 0 2017-03-28 10:56:52.842
!MESSAGE An error occurred while automatically activating bundle org.eclipse.core.resources (84).
</code>```

答:
Your problem is described here, too: http://www.eclipse.org/forums/index.php/t/156204/

You could also try this:
rename your current workspace folder. Open eclipse again and create an new one. Then either try to load your old one from the menu or try to put your project folders into the new workspace via your OS-filemanager (explorer / finder / whatever). Then refresh the workspace.

Hope this helped. Googeling your error sometimes does wonders, too...

Body:
Here's the error log that it directed me to. I'm very new to coding and have no idea what it's asking me to fix. I tried to look it up but the few solutions I could find didnt't help. I changed the environment variable HOME to %USERPROFILE% but I don't think that was the right thing to do. Please help!

I've tried re-installing Eclipse but it still won't work.

   !SESSION 2017-03-28 10:56:50.318 -----------------------------------------------
    eclipse.buildId=4.6.2.M20161124-1400
    java.version=1.8.0_112
    java.vendor=Oracle Corporation
    BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_CA
    Framework arguments:  -product org.eclipse.epp.package.java.product C:\Users\ssfro\OneDrive\Fanshawe\INFO-1150 Programming\workspace\School     Projects\src\Spencer_Frost_INFO1150_Project.java
    Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.java.product C:\Users\ssfro\OneDrive\Fanshawe\INFO-1150 Programming\workspace\School Projects\src\Spencer_Frost_INFO1150_Project.java

    !ENTRY org.eclipse.core.resources 2 10035 2017-03-28 10:56:52.694
    !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

!ENTRY org.eclipse.osgi 4 0 2017-03-28 10:56:52.842
!MESSAGE An error occurred while automatically activating bundle org.eclipse.core.resources (84).


问:
Devexpress XtraGrid columns Text Alignment
Devexpress XtraGrid columns Text  Alignment .?

Example:

答:
The VAlignment property that you are referring to will simply vertically align the column header text, not rotate it to be displayed vertically.

There are several example tickets in the DevExpress support center with sample projects demonstrating how to achieve this behavior via the GridView's GridView.CustomDrawColumnHeader event.

See:

How to rotate BandedGridColumn or GridColumn caption ?

Xtra Grid Vertical Headers

Display a GridView column header text vertically


问:
Debugging: Trouble stepping into external source code (nuget)
Problem

Attempting to debug why my configuration isn't binding to my object the way I want it to and I can't seem to step into ConfigurationRoot.Get();. It either breaks inside the method or steps over when I try to step into it.

I believe my debugger settings are correct and I've verified the correct modules and symbols are loaded as well. Any suggestions on what to check for next?

Running Visual Studio 2017

Relevant Packages:

Microsoft.Extensions.Configuration (1.1.1)

Microsoft.Extensions.Configuration.Binder (1.1.1)

答: Using information from this question, I deleted the symbols for the Microsoft.Extensions.Configuration* from my symbol cache. I then double checked my debug settings and discovered that they had been reset to default somehow. After choosing the correct settings again, deleting the symbols from cache, and only enabling dotPeek as my symbol server, VS was able to load the PDB files and then step into the source as I wanted.


问:
PropertyChangedEventHandler PropertyChanged is null
i am implementing PropertyChangedEventHandler PropertyChanged and it's always null.
property string is right donno where is the problem
here is the code i am using

```<code>public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

public bool _playerGridVisibility ;
        public bool PlayerGridVisibility
        {
            get { return _playerGridVisibility; }
            set
            {
                _playerGridVisibility = value;
                this.OnPropertyChanged(Strings.PlayerGridVisibilityString);
            }
</code>```

and in the xaml

```<code>Visibility="{Binding Path=AdsGridVisibility, Converter={StaticResource VC}}"
        }
</code>```

so can anyone knows the problem ?

答: One reason this could be happening is if your code does not deal with the original data context.  You might have two copies of the view model and you might be updating the one that is not bound.</p>

Body:
i am implementing PropertyChangedEventHandler PropertyChanged and it's always null.
property string is right donno where is the problem
here is the code i am using

public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

public bool _playerGridVisibility ;
        public bool PlayerGridVisibility
        {
            get { return _playerGridVisibility; }
            set
            {
                _playerGridVisibility = value;
                this.OnPropertyChanged(Strings.PlayerGridVisibilityString);
            }

and in the xaml

Visibility="{Binding Path=AdsGridVisibility, Converter={StaticResource VC}}"
        }

so can anyone knows the problem ?


问:
Center a column using Twitter Bootstrap
How do I center a div of one column size within the container (12 columns) in Twitter Bootstrap 3?

.centered {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<body class="container">
  <div class="col-lg-1 col-offset-6 centered">
    <img data-src="holder.js/100x100" alt="" />
  </div>
</body></code>```

I want a div, with a class .centered to be centered within the container. I may use a row if there are multiple divs, but for now I just want a div with the size of one column centered within the container (12 columns).

I am also not sure the above approach is good enough as the intention is not to offset the div by half. I do not need free spaces outside the div and the contents of the div shrink in proportion. I want to empty space outside the div to be evenly distributed (shrink till the container width is equal to one column).

答:
To center more than one column in a Bootstrap row - and the number of cols are odd, simply add this css class to all the columns in that row:

```<code>.many-cols-centered {  // To horizontally center bootstrap odd cols, eg col-lg-9, col-md-3, works well in lg
  display:inline-block;
  float:none;
}
</code>```

So in your HTML you have something like:

```<code><div class="row text-center"> <!-- text-center centers all text in that row -->
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image1.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image2.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image3.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
</div>
</code>```

Title: Center a column using Twitter Bootstrap

Body:
How do I center a div of one column size within the container (12 columns) in Twitter Bootstrap 3?

.centered {
  background-color: red;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

I want a div, with a class .centered to be centered within the container. I may use a row if there are multiple divs, but for now I just want a div with the size of one column centered within the container (12 columns).

I am also not sure the above approach is good enough as the intention is not to offset the div by half. I do not need free spaces outside the div and the contents of the div shrink in proportion. I want to empty space outside the div to be evenly distributed (shrink till the container width is equal to one column).

Body:
To center more than one column in a Bootstrap row - and the number of cols are odd, simply add this css class to all the columns in that row:

.many-cols-centered {  // To horizontally center bootstrap odd cols, eg col-lg-9, col-md-3, works well in lg
  display:inline-block;
  float:none;
}

So in your HTML you have something like:

<div class="row text-center"> <!-- text-center centers all text in that row -->
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image1.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image2.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 many-cols-centered">
        <img src='assets/image3.jpg'>
        <h3>You See</h3>
        <p>I love coding.</p>
    </div>
</div>


问:
VBoxManage: error: Failed to create the host-only adapter
I am running vagrant 1.4 and virtual box 4.3 on fedora 17 machine. When I do "vagrant up", I get this error:

```<code>Bringing machine 'default' up with 'virtualbox' provider...

[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["hostonlyif", "create"]

Stderr: 0%...
Progress state: NS_ERROR_FAILURE
VBoxManage: error: Failed to create the host-only adapter
VBoxManage: error: VBoxNetAdpCtl: Error while adding new interface: VBoxNetAdpCtl: ioctl failed for /dev/vboxnetctl: Inappropriate ioctl for devic
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component HostNetworkInterface, interface IHostNetworkInterface
VBoxManage: error: Context: "int handleCreate(HandlerArg*, int, int*)" at line 66 of file VBoxManageHostonly.cpp
</code>```

答:
I encountered this problem on Windows 8.1, VirtualBox 5.1.18 and Vagrant 1.9.3.

Deleting the VirtualBox Hosts-only Ethernet Adapter from VirtualBox Preferences (Network --> Hosts-only networks) fixed this for me, and vagrant up could continue and start the VM.

Body:
I am running vagrant 1.4 and virtual box 4.3 on fedora 17 machine. When I do "vagrant up", I get this error:

Bringing machine 'default' up with 'virtualbox' provider...

[default] Clearing any previously set forwarded ports...
[default] Clearing any previously set network interfaces...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.

Command: ["hostonlyif", "create"]

Stderr: 0%...
Progress state: NS_ERROR_FAILURE
VBoxManage: error: Failed to create the host-only adapter
VBoxManage: error: VBoxNetAdpCtl: Error while adding new interface: VBoxNetAdpCtl: ioctl failed for /dev/vboxnetctl: Inappropriate ioctl for devic
VBoxManage: error: Details: code NS_ERROR_FAILURE (0x80004005), component HostNetworkInterface, interface IHostNetworkInterface
VBoxManage: error: Context: "int handleCreate(HandlerArg*, int, int*)" at line 66 of file VBoxManageHostonly.cpp


问:
How to link docker images to their composing layers on the disk?
Since Docker v1.10, with the introduction of the content addressable storage, Docker has completely changed the way image data are handled on the disk. I understand that now layers and images are separated. Layers merely become collections of files and directories that have no notion of images and can be freely shared across images. See the update and a blog with better explanation.

During docker push and docker pull, via stdout it can be seen the layers are transported, though the resulting SHA hashes are completely regenerated on the destination.

With a locally built image from ubuntu:14.04 base, when I use the docker history command, I can see a chain of intermediary images used during the build process, and the disk space usage they contributed.

```<code>root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff# docker history image_size
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
9ae1f372d83c        11 weeks ago        /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin/   0 B
aaf66e9fa85b        11 weeks ago        /bin/sh -c chown -R martian /home/martian       6.299 MB
9568768134c1        11 weeks ago        /bin/sh -c rm -rf /home/martian/potatoes        0 B
2f40f3f58306        11 weeks ago        /bin/sh -c mv /home/martian/water_tanks /home   6.289 MB
062e2702ffa2        11 weeks ago        /bin/sh -c mv /home/martian/potatoes /home/ma   5.394 kB
7b2d8b4c1dd0        11 weeks ago        /bin/sh -c chown -R martian /home/martian       6.299 MB
8fd47fed98d6        11 weeks ago        /bin/sh -c #(nop) COPY dir:421da6c71a1f252881   6.289 MB
...
</code>```

And I can use the docker inspect command to get the underlying layers.

```<code>root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff# docker inspect image_size | jq -r '.[].RootFS'
{
  "Layers": [
    "sha256:a85f35566a268e6f4411c5157ffcffe4f5918b068b04d79fdd80003901ca39da",
    "sha256:eaaf7298332642da0f8190fa4b96ad46c04b9c1d1682bc3a35d77bded2b1e0a9",
    "sha256:33a212e8aa5642d3a2ddead146e85912407fc5bbb2a896dab11fcf329177a999",
    "sha256:f1f25d8c6e56dc4891df147a77f57e756873b57f33ce95e6a0acbe47117c0c8a",
    "sha256:67852b7d2cf5f0885293fa9df91ebfd8ef0c42ba11a5155f94806f3a96c5e916",
    "sha256:480d48b7e2864a44c1b2fca0c7e32fbab505f7526ccb25bbfed191c04a9bb7b0",
    "sha256:18d270fe64aa423e0ffdf24faf0103432027da3d5c12f4505e7daedad9fe2195",
    "sha256:a73c3f5eb83790bc6d03381a43a20aef7d0d9d97de0cff4b040e8e4c01a3aee5",
    "sha256:e8d1b67ace73cb92cc00725354e84024153bedae4280149c03fcb52f34d83757",
    "sha256:19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280",
    "sha256:77d412270fbdd9baba1fe73028b786c3a1709feefa9b03be74b8e9f9ce148635",
    "sha256:2ad21e37389addd577161c981d0c69ab60aa47945172f41f9ec71ada1c1dd4ee",
    "sha256:771d1e47ca8d8dcf55069786e4c499894fba86f704c808413df00f4f980564e1",
    "sha256:f9c02c6fa436213c0f220d49c4ee1b913372081010d4506757ec75d3e788847c"
  ],
  "Type": "layers"
}
</code>```

My question is, how do I link these layers marked with SHA hashes to the images listed in the IMAGE column of the previous command output? And is there a way to find out the actual location and size of these layers on the disk?

If I am not wrong, the layers should be kept at /var/lib/docker/aufs/diff if the storage driver selection is aufs. But the contents in that folder are named with randomly generated IDs that do not match any of the layer literally. It seems the match is only kept within Docker Engine for security concerns.

答:
Based on the inspiration given by larsks in the answer, I managed to find the location of the layers.

For example, suppose we want to find the location of the layer contributed by the COPY step, which corresponds to an intermediate image with id 8fd47fed98d6, we can inspect it first.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# docker inspect 8fd47fed98d6 | jq -r '.[].RootFS'
{
  "Layers": [
    "sha256:a85f35566a268e6f4411c5157ffcffe4f5918b068b04d79fdd80003901ca39da",
    "sha256:eaaf7298332642da0f8190fa4b96ad46c04b9c1d1682bc3a35d77bded2b1e0a9",
    "sha256:33a212e8aa5642d3a2ddead146e85912407fc5bbb2a896dab11fcf329177a999",
    "sha256:f1f25d8c6e56dc4891df147a77f57e756873b57f33ce95e6a0acbe47117c0c8a",
    "sha256:67852b7d2cf5f0885293fa9df91ebfd8ef0c42ba11a5155f94806f3a96c5e916",
    "sha256:480d48b7e2864a44c1b2fca0c7e32fbab505f7526ccb25bbfed191c04a9bb7b0",
    "sha256:18d270fe64aa423e0ffdf24faf0103432027da3d5c12f4505e7daedad9fe2195",
    "sha256:a73c3f5eb83790bc6d03381a43a20aef7d0d9d97de0cff4b040e8e4c01a3aee5",
    "sha256:e8d1b67ace73cb92cc00725354e84024153bedae4280149c03fcb52f34d83757",
    "sha256:19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280"
  ],
  "Type": "layers"
}
</code>```

Now we try to look for the last layer.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# find . -name '*19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280*'
root@ruifeng-VirtualBox:/var/lib/docker#
</code>```

But there is nothing on the disk. Perhaps there is some reference tree going on there. We can check the file contents in the layerdb.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# grep -rl 19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280 image/aufs/layerdb/
image/aufs/layerdb/sha256/f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449/diff
</code>```

We can see that this layer is actually a diff of f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449. Let's find it.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# find . -name '*f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449*'
./image/aufs/layerdb/sha256/f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449
</code>```

And find the cache-id that will direct us into the actual location in the aufs/diff folder.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# cat image/aufs/layerdb/sha256/f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449/cache-id
c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637
</code>```

Let's go into the location and check.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# cd aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637
root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637# find .
.
./home
./home/martian
./home/martian/water_tanks
./home/martian/water_tanks/IMG_0052.JPG
root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637#
</code>```

It contains all files and directories that were intended to be copied into the image by the COPY step. The size of the layer can be checked as well.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# du -sh aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637
6.1M    aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637
</code>```

This will provide quite some insight into the Union File System and the Copy-on-Write mechanism used by Docker, if subsequent layers are also inspected in the same manner.

This can also be done in a reverse order. We can look for a file or directory that is intended to be inside the image, which should be somewhere inside aufs/diff, and then use the cache-id to trace back to the layers.

```<code>root@ruifeng-VirtualBox:/var/lib/docker# find . -name '*water_tanks*'
./aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637/home/martian/water_tanks
</code>```

Body:
Since Docker v1.10, with the introduction of the content addressable storage, Docker has completely changed the way image data are handled on the disk. I understand that now layers and images are separated. Layers merely become collections of files and directories that have no notion of images and can be freely shared across images. See the update and a blog with better explanation.

During docker push and docker pull, via stdout it can be seen the layers are transported, though the resulting SHA hashes are completely regenerated on the destination.

With a locally built image from ubuntu:14.04 base, when I use the docker history command, I can see a chain of intermediary images used during the build process, and the disk space usage they contributed.

root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff# docker history image_size
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
9ae1f372d83c        11 weeks ago        /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin/   0 B
aaf66e9fa85b        11 weeks ago        /bin/sh -c chown -R martian /home/martian       6.299 MB
9568768134c1        11 weeks ago        /bin/sh -c rm -rf /home/martian/potatoes        0 B
2f40f3f58306        11 weeks ago        /bin/sh -c mv /home/martian/water_tanks /home   6.289 MB
062e2702ffa2        11 weeks ago        /bin/sh -c mv /home/martian/potatoes /home/ma   5.394 kB
7b2d8b4c1dd0        11 weeks ago        /bin/sh -c chown -R martian /home/martian       6.299 MB
8fd47fed98d6        11 weeks ago        /bin/sh -c #(nop) COPY dir:421da6c71a1f252881   6.289 MB
...

And I can use the docker inspect command to get the underlying layers.

root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff# docker inspect image_size | jq -r '.[].RootFS'
{
  "Layers": [
    "sha256:a85f35566a268e6f4411c5157ffcffe4f5918b068b04d79fdd80003901ca39da",
    "sha256:eaaf7298332642da0f8190fa4b96ad46c04b9c1d1682bc3a35d77bded2b1e0a9",
    "sha256:33a212e8aa5642d3a2ddead146e85912407fc5bbb2a896dab11fcf329177a999",
    "sha256:f1f25d8c6e56dc4891df147a77f57e756873b57f33ce95e6a0acbe47117c0c8a",
    "sha256:67852b7d2cf5f0885293fa9df91ebfd8ef0c42ba11a5155f94806f3a96c5e916",
    "sha256:480d48b7e2864a44c1b2fca0c7e32fbab505f7526ccb25bbfed191c04a9bb7b0",
    "sha256:18d270fe64aa423e0ffdf24faf0103432027da3d5c12f4505e7daedad9fe2195",
    "sha256:a73c3f5eb83790bc6d03381a43a20aef7d0d9d97de0cff4b040e8e4c01a3aee5",
    "sha256:e8d1b67ace73cb92cc00725354e84024153bedae4280149c03fcb52f34d83757",
    "sha256:19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280",
    "sha256:77d412270fbdd9baba1fe73028b786c3a1709feefa9b03be74b8e9f9ce148635",
    "sha256:2ad21e37389addd577161c981d0c69ab60aa47945172f41f9ec71ada1c1dd4ee",
    "sha256:771d1e47ca8d8dcf55069786e4c499894fba86f704c808413df00f4f980564e1",
    "sha256:f9c02c6fa436213c0f220d49c4ee1b913372081010d4506757ec75d3e788847c"
  ],
  "Type": "layers"
}

My question is, how do I link these layers marked with SHA hashes to the images listed in the IMAGE column of the previous command output? And is there a way to find out the actual location and size of these layers on the disk?

If I am not wrong, the layers should be kept at /var/lib/docker/aufs/diff if the storage driver selection is aufs. But the contents in that folder are named with randomly generated IDs that do not match any of the layer literally. It seems the match is only kept within Docker Engine for security concerns.

Body:
Based on the inspiration given by larsks in the answer, I managed to find the location of the layers.

For example, suppose we want to find the location of the layer contributed by the COPY step, which corresponds to an intermediate image with id 8fd47fed98d6, we can inspect it first.

root@ruifeng-VirtualBox:/var/lib/docker# docker inspect 8fd47fed98d6 | jq -r '.[].RootFS'
{
  "Layers": [
    "sha256:a85f35566a268e6f4411c5157ffcffe4f5918b068b04d79fdd80003901ca39da",
    "sha256:eaaf7298332642da0f8190fa4b96ad46c04b9c1d1682bc3a35d77bded2b1e0a9",
    "sha256:33a212e8aa5642d3a2ddead146e85912407fc5bbb2a896dab11fcf329177a999",
    "sha256:f1f25d8c6e56dc4891df147a77f57e756873b57f33ce95e6a0acbe47117c0c8a",
    "sha256:67852b7d2cf5f0885293fa9df91ebfd8ef0c42ba11a5155f94806f3a96c5e916",
    "sha256:480d48b7e2864a44c1b2fca0c7e32fbab505f7526ccb25bbfed191c04a9bb7b0",
    "sha256:18d270fe64aa423e0ffdf24faf0103432027da3d5c12f4505e7daedad9fe2195",
    "sha256:a73c3f5eb83790bc6d03381a43a20aef7d0d9d97de0cff4b040e8e4c01a3aee5",
    "sha256:e8d1b67ace73cb92cc00725354e84024153bedae4280149c03fcb52f34d83757",
    "sha256:19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280"
  ],
  "Type": "layers"
}

Now we try to look for the last layer.

root@ruifeng-VirtualBox:/var/lib/docker# find . -name '*19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280*'
root@ruifeng-VirtualBox:/var/lib/docker#

But there is nothing on the disk. Perhaps there is some reference tree going on there. We can check the file contents in the layerdb.

root@ruifeng-VirtualBox:/var/lib/docker# grep -rl 19a4b80afc677825fec94adf8b6a45a866f42a38675f87f86e50171ff5e0a280 image/aufs/layerdb/
image/aufs/layerdb/sha256/f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449/diff

We can see that this layer is actually a diff of f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449. Let's find it.

root@ruifeng-VirtualBox:/var/lib/docker# find . -name '*f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449*'
./image/aufs/layerdb/sha256/f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449

And find the cache-id that will direct us into the actual location in the aufs/diff folder.

root@ruifeng-VirtualBox:/var/lib/docker# cat image/aufs/layerdb/sha256/f1824ce70e6d1e8f140b9ba637b7447c00d8158d3bbc1f72b491766ab54dd449/cache-id
c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637

Let's go into the location and check.

root@ruifeng-VirtualBox:/var/lib/docker# cd aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637
root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637# find .
.
./home
./home/martian
./home/martian/water_tanks
./home/martian/water_tanks/IMG_0052.JPG
root@ruifeng-VirtualBox:/var/lib/docker/aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637#

It contains all files and directories that were intended to be copied into the image by the COPY step. The size of the layer can be checked as well.

root@ruifeng-VirtualBox:/var/lib/docker# du -sh aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637
6.1M    aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637

This will provide quite some insight into the Union File System and the Copy-on-Write mechanism used by Docker, if subsequent layers are also inspected in the same manner.

This can also be done in a reverse order. We can look for a file or directory that is intended to be inside the image, which should be somewhere inside aufs/diff, and then use the cache-id to trace back to the layers.

root@ruifeng-VirtualBox:/var/lib/docker# find . -name '*water_tanks*'
./aufs/diff/c097799b7946231fb60511b442c10cd0b56ee17a12b376149f305adda67e7637/home/martian/water_tanks


问:
Osirix database errors
I am trying to use Osirix 5.8.5 on Mac El Capitan OS 10.11.3 and when I try and load Osirix I get an error message:

OsiriX Database

  Osiris cannot understand the model of current saved database... The database index will be deleted and reconstructed (no images are lost).

I am given 2 options --> Quit or OK

However when I click on OK the message keeps repeating and I cannot access the program. Thus I only quit. Does anyone have a solution for this problem please!!

答:
Quit OsiriX

Rename your "OsiriX Data" folder to "OsiriX Data 2"

Relaunch OsiriX : your database is now empty (in the background, OsiriX created a new and empty "OsiriX Data" folder)

Quit OsiriX

Move your "OsiriX Data 2" folder into "OsiriX Data/INCOMING.noindex/"

Relaunch OsiriX: your images will be re-indexed into the new database

Title: Osirix database errors


问:
Code Sign Error in macOS Monterey, Xcode - resource fork, Finder information, or similar detritus not allowed
Already tried : Code Sign Error on macOS Sierra, Xcode 8

Please see image showing error

```<code>CodeSign /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app
    cd "/Volumes/Development/Project/Top Best Games/19. Lets Flow/35/let's FLOW - source/proj.ios_mac"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "iPhone Distribution: New Free Games (2CHN583K4J)"
Provisioning Profile: "Super Flow Flipp AppStore"
                      (c6c30d2a-1025-4a23-8d12-1863ff684a05)

    /usr/bin/codesign --force --sign E48B98966150110E55EAA9B149F731901A41B37F --entitlements /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Intermediates/Flow.build/Debug-iphoneos/Super\ Flow\ Flip.build/Super\ Flow\ Flip.app.xcent --timestamp=none /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app

/Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super Flow Flip.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1
</code>```

In Code Sign section its allowing me to select profile and certificate...but still giving error.

How to fix this problem ?

答:
The easiest way to handle attributes on your source files is to have Xcode clear up the archive before it runs codesign. To do this:

Select your target in XCode

Select the Build Phases tab

Press the + symbol

Select New Run Script Phase

Enter the following for the script:

xattr -cr ~/Library/Developer/Xcode/DerivedData || echo Clear

Now when you build your target it will clear out any attributes that would have broken codesign. By clearing out at this stage you don't have to alter your source code / project directory.

The "|| echo Clear" part of the script ensures that the project build continues even if xattr errors.

This method is good if you use programs such as DropBox on your code repository that add the attributes, as it doesn't change your source project, only the built archive.

You may need to change the path to match your DerivedData directory - this path will be shown next to the codesign error.

Body:
Already tried : Code Sign Error on macOS Sierra, Xcode 8

Please see image showing error

CodeSign /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app
    cd "/Volumes/Development/Project/Top Best Games/19. Lets Flow/35/let's FLOW - source/proj.ios_mac"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "iPhone Distribution: New Free Games (2CHN583K4J)"
Provisioning Profile: "Super Flow Flipp AppStore"
                      (c6c30d2a-1025-4a23-8d12-1863ff684a05)

    /usr/bin/codesign --force --sign E48B98966150110E55EAA9B149F731901A41B37F --entitlements /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Intermediates/Flow.build/Debug-iphoneos/Super\ Flow\ Flip.build/Super\ Flow\ Flip.app.xcent --timestamp=none /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app

/Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super Flow Flip.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1

In Code Sign section its allowing me to select profile and certificate...but still giving error.

How to fix this problem ?


问:
This is possible to using bash script for User Authentication Banner in SSH?
I want to ask something.

I make user for Linux, and there create User Authentication Banner (If you use Bitvise, you will know). I tried to use bash script.

This is /etc/mybanner

```<code>#!/bin/bash
MYIP=`wget icanhazip.com -qO -`
echo -e "Selamat datang, berikut informasi akun anda:"
echo -e "IP: $MYIP"
</code>```

In my dropbear config

```<code>OPTIONS="-p 22 -b /etc/mybanner"
</code>```

I try to login and see, but I get it in my banner:

So, this is possible to use banner using shell script ?

Thanks

答:
You can put your customized bash script in motd. Actually, the contents of /etc/motd are displayed after a successful login but just before it executes the login shell.

You can read about motd on Debian wiki and also you can read  CUSTOMIZE YOUR MOTD tutorial.

Body:
I want to ask something.

I make user for Linux, and there create User Authentication Banner (If you use Bitvise, you will know). I tried to use bash script.

This is /etc/mybanner

#!/bin/bash
MYIP=`wget icanhazip.com -qO -`
echo -e "Selamat datang, berikut informasi akun anda:"
echo -e "IP: $MYIP"

In my dropbear config

OPTIONS="-p 22 -b /etc/mybanner"

I try to login and see, but I get it in my banner:

So, this is possible to use banner using shell script ?

Thanks


问:
MySQL and UNIQUE columns: how to avoid duplicates?
I have a table with the following column:

```<code>(id, col_1, col_2)
</code>```

where "id" is the primary key (auto-inc).

I would like to make col_1 and col_2 a "unique combo".

For example, if I insert the data...

```<code>(.., col_1, col_2 ) = (.., 'A', 'B')
</code>```

...Next, I shouldn't be allowed to insert the following:

```<code>(.., col_1, col_2 ) = (.., 'A', 'B')
(.., col_1, col_2 ) = (.., 'B', 'A') #because it already exists, in another order:('A','B')
</code>```

I successfully blocked the first case with the use of UNIQUE(col_1, col_2)...

But it seems that the "reverse combo" (.., 'B', 'A') is permitted.

How can I stop this?

答:
As said by fancyPants, the solution is to ensure one column is always lower than the other. MySQL does not support CHECK constraints, but you can enforce this with a trigger, which will allow you to catch application bugs:

Can a MySQL trigger simulate a CHECK constraint?

Beware: depending on MySQL version, raising an error with your trigger will use different methods.

On newer MySQL versions, you can also create virtual columns and index them. Perhaps you could create a UNIQUE(least(a,b), greatest(a,b))... but it would be kinda clunky.

Also, knowing that a<=b is a constraint will speed up search. If you need to search for either (x,y) or (y,x) then you know that the only one in your table will be the one with proper order, which simplifies your WHERE and makes index use much better.

Body:
I have a table with the following column:

(id, col_1, col_2)

where "id" is the primary key (auto-inc).

I would like to make col_1 and col_2 a "unique combo".

For example, if I insert the data...

(.., col_1, col_2 ) = (.., 'A', 'B')

...Next, I shouldn't be allowed to insert the following:

(.., col_1, col_2 ) = (.., 'A', 'B')
(.., col_1, col_2 ) = (.., 'B', 'A') #because it already exists, in another order:('A','B')

I successfully blocked the first case with the use of UNIQUE(col_1, col_2)...

But it seems that the "reverse combo" (.., 'B', 'A') is permitted.

How can I stop this?


问:
Android customized adapter with both editText and textView
I'm trying to implement an Android app for sudoku game, and i created a customized adapter for that. i want make edit text for cells the user is allowed to modify, and textview for cell filled by the program, the number of ediTexts and textViews will be random. how do specify that in the adapter ?

This is my adapter :

```<code>public class SodukuAdapter extends BaseAdapter {

    ArrayList<String> items;

    static Activity mActivity;

    private static LayoutInflater inflater = null;

    public SodukuAdapter (Activity activity, ArrayList<String> tempTitle,) {
        mActivity = activity;
        items = tempTitle;

        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public final int getCount() {

        return items.size();

    }

    @Override
    public final Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public final long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v = null;

        v = inflater.inflate(R.layout.item, null);

        EditText et = (EditText) v.findViewById(R.id.et);
        et.setText(items.get(position));

        return v;
    }

}
</code>```

答:
You can place both views in the same parent (e. g. parent is a RelativeLayout or a FrameLayout) so they are on top of each other. Than you simply hide one of them and show the other using setVisibility() in your getView() method of the adapter.

Of course you would need a datasource object which keeps track of whether a view should show the TextView or the EditText:

```<code>class SodokuItem {
    public boolean isStatic;
    public String text;
}

...

@Override
public View getView(final int position, View convertView, ViewGroup parent)     {

    View v = inflater.inflate(R.layout.item, null);

    SodokuItem item = items.get(position);

    EditText et = (EditText) v.findViewById(R.id.et);
    TextView tv = (TextView) v.findViewById(R.id.tv);

    if(item.isStatic){
        et.setVisibility(GONE);
        tv.setText(item.text);
    }else{
        tv.setVisibility(GONE);
        et.setText(item.text);
    }

    return v;
}
</code>```

Body:
I'm trying to implement an Android app for sudoku game, and i created a customized adapter for that. i want make edit text for cells the user is allowed to modify, and textview for cell filled by the program, the number of ediTexts and textViews will be random. how do specify that in the adapter ?

This is my adapter :

public class SodukuAdapter extends BaseAdapter {

    ArrayList<String> items;

    static Activity mActivity;

    private static LayoutInflater inflater = null;

    public SodukuAdapter (Activity activity, ArrayList<String> tempTitle,) {
        mActivity = activity;
        items = tempTitle;

        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public final int getCount() {

        return items.size();

    }

    @Override
    public final Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public final long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v = null;

        v = inflater.inflate(R.layout.item, null);

        EditText et = (EditText) v.findViewById(R.id.et);
        et.setText(items.get(position));

        return v;
    }

}

Body:
You can place both views in the same parent (e. g. parent is a RelativeLayout or a FrameLayout) so they are on top of each other. Than you simply hide one of them and show the other using setVisibility() in your getView() method of the adapter.

Of course you would need a datasource object which keeps track of whether a view should show the TextView or the EditText:

class SodokuItem {
    public boolean isStatic;
    public String text;
}

...

@Override
public View getView(final int position, View convertView, ViewGroup parent)     {

    View v = inflater.inflate(R.layout.item, null);

    SodokuItem item = items.get(position);

    EditText et = (EditText) v.findViewById(R.id.et);
    TextView tv = (TextView) v.findViewById(R.id.tv);

    if(item.isStatic){
        et.setVisibility(GONE);
        tv.setText(item.text);
    }else{
        tv.setVisibility(GONE);
        et.setText(item.text);
    }

    return v;
}


问:
Python- How to fix failed testcase on a has repeat function?
I've built a function that checks for repeats of a specific number in a list named xs. V is the number to check for repeats of. It needs to return True if there are more than one occurrences of the number and if there are none, it needs to return False.

I'm failing one test case which is input xs=[1,2,1] v=1, this function needs to return True, but my code is making it False. Can you see where I went wrong?

Here is my current code:

```<code>def has_repeat(xs, v):
    count=0
    for num in range(len(xs)):
        if num == v:
            count+=1
    if count>1:
       return True
    else:
       return False
</code>```

答:
You're actually iterating over the range of the length of the list, not the items in the list.

The range function returns a list of numbers from 0 (by default) to the number you provide, in this case 3 (not inclusive). See Python documentation.

As an example if you try:

```<code>l = [1, 2, 3]
print(range(len(l)))
</code>```

It will print out [0, 1, 2]

What you should do is instead of

```<code>for num in range(len(xs))
</code>```

do

```<code>for num in xs:
</code>```

You can try it out on PyFiddle here

As an added tasty bonus, you  could change this to use the .count method on your list of items to check how many occurrences of that number are in the list, removing the need to iterate the list at all, like so:

```<code>count = xs.count(v)
</code>```

Body:
I've built a function that checks for repeats of a specific number in a list named xs. V is the number to check for repeats of. It needs to return True if there are more than one occurrences of the number and if there are none, it needs to return False.

I'm failing one test case which is input xs=[1,2,1] v=1, this function needs to return True, but my code is making it False. Can you see where I went wrong?

Here is my current code:

def has_repeat(xs, v):
    count=0
    for num in range(len(xs)):
        if num == v:
            count+=1
    if count>1:
       return True
    else:
       return False

Body:
You're actually iterating over the range of the length of the list, not the items in the list.

The range function returns a list of numbers from 0 (by default) to the number you provide, in this case 3 (not inclusive). See Python documentation.

As an example if you try:

l = [1, 2, 3]
print(range(len(l)))

It will print out [0, 1, 2]

What you should do is instead of

for num in range(len(xs))

do

for num in xs:

You can try it out on PyFiddle here

As an added tasty bonus, you  could change this to use the .count method on your list of items to check how many occurrences of that number are in the list, removing the need to iterate the list at all, like so:

count = xs.count(v)


问:
Is there a 'drop to frame' command in the Ruby debugger
The Java debugger has a command called 'drop to frame' that takes you back to the beginning of the current method, resetting the stack as if you had just entered the method call. Static or instance variables won't be reset, but it's still pretty useful for when you stepped over a line and want to try it again. Is there the equivalent in the Ruby debugger? I suspect the answer is 'no', but if there's a good reason based on how Ruby methods are implemented, I'd be curious to know why.</p>

答: In the Ruby 1.9 debugger, there is a jump command that is pretty close to the Java drop to frame. It won't reset the stack like drop to frame does, but for most cases, it will let you re-test code without starting over.</p>