问:
How to implement a Cloneable template class in C++?
I'm trying to implement a Cloneable base class. Here's the code:

```<code>class Base1 {
public:
    virtual Base1* Clone() const {
        return new Base1(*this);
    }
};

class Derived1 : public Base1 {
public:
    virtual Derived1* Clone() const {
        return new Derived1(*this);
    }
};

template<typename T>
class Cloneable {
public:
    virtual T* Clone() const {
        return new T(dynamic_cast<const T&>(*this));
    }
};

class Base2 : public Cloneable<Base2> {
};

class Derived2 : public Base2, public Cloneable<Derived2> {
};

namespace Lib_UnitTest {
TEST_CLASS(CloneableTest) {
public:
    // Success test
    TEST_METHOD(ShouldClone1) {
        Derived1 derived;
        Base1& base = derived;
        Base1* basePtr = base.Clone();
        Derived1* derivedPtr = dynamic_cast<Derived1*>(basePtr);
        Assert::IsNotNull(derivedPtr);
    }

    // Failed test !!!
    TEST_METHOD(ShouldClone2) {
        Derived2 derived;
        Base2& base = derived;
        Base2* basePtr = base.Clone();
        Derived2* derivedPtr = dynamic_cast<Derived2*>(basePtr);
        Assert::IsNotNull(derivedPtr);
    }
};
}
</code>```

The problem here is the test case 'ShouldClone1' success, but 'ShouldClone2' failed.

It seems that in the 2nd test case, the Clone method doesn't go to the one of Derived class.

Do you know what's the problem? What's the difference between those 2 implementations?

I guess this is because of 'diamond' inheritance problem. But if use 'public virtual' inheritance and implement the Clone method in class Derived2, then I don't need to inherit Cloneable for it at the first place ...

A updated version:

```<code>class Cloneable {
public:
    // Could make this pure virtual
    virtual ~Cloneable() {}

    // Could make this pure virtual
    virtual Cloneable* Clone() const {
        return new Cloneable(*this);
    }
};

template<typename T>
class CloneableBase : public virtual Cloneable {
public:
    virtual ~CloneableBase() {}

    virtual Cloneable* Clone() const {
        return new T(dynamic_cast<const T&>(*this));
    }
};

class Base2 : public virtual CloneableBase<Base2> {
};

class Derived2 : public virtual Base2 {
    virtual Cloneable* Clone() const {
        return new Derived2(*this);
    }
};
</code>```

Update 2：

The article Polymorphic cloning and the CRTP describes the solution quite clear.

答:
It is possible without manually writing Clone() method in every derived class. But we can not get away with just CRTP. Instead of instantiating Derived classes directly we will always indirectly instantiate super derived template class which will deal with diamond problem for us.</p>

```<code>class IClonable
{
    public: virtual IClonable *
    CloneImpl(void) const = 0;

    public: virtual
    ~IClonable(void) {}
};

template< typename TClonable > TClonable *
Construct();

template< typename TBase >
class TheFinalClass final: public TBase, public virtual IClonable
{
    template< typename TClonable > friend TClonable *
    Construct();

    private:
    TheFinalClass(void) {}

    private: explicit
    TheFinalClass(TheFinalClass const & other): TBase(other) {}

    private: IClonable *
    CloneImpl(void) const override
    {
        return(new TheFinalClass(*this));
    }
};

template< typename TClonable > TClonable *
Construct() {return(new TheFinalClass< TClonable >());}

template< typename TDerived >
class Cloneable: public virtual IClonable
{
    public: TDerived *
    Clone() const // notice that this method does not override anything
    {
        return(dynamic_cast< TDerived * >(dynamic_cast< IClonable const * >(this)->CloneImpl()));
    }
};

class Base2: public Cloneable< Base2 > {};

class Derived2: public Cloneable< Derived2 >, public Base2 {};

// Failed test !!!, Now works!!!
TEST_METHOD(ShouldClone2) {
    Derived2 * p_derived{Construct< Derived2 >()};
    Base2 * p_base{p_derived};
    Base2 * p_clone_base{p_base->Clone()};
    Derived2 * p_clone_derived{dynamic_cast< Derived2 * >(p_clone_base)};
    Assert::IsNotNull(p_clone_derived);
}
</code>```

Body:
I'm trying to implement a Cloneable base class. Here's the code:

class Base1 {
public:
    virtual Base1* Clone() const {
        return new Base1(*this);
    }
};

class Derived1 : public Base1 {
public:
    virtual Derived1* Clone() const {
        return new Derived1(*this);
    }
};

template<typename T>
class Cloneable {
public:
    virtual T* Clone() const {
        return new T(dynamic_cast<const T&>(*this));
    }
};

class Base2 : public Cloneable<Base2> {
};

class Derived2 : public Base2, public Cloneable<Derived2> {
};

namespace Lib_UnitTest {
TEST_CLASS(CloneableTest) {
public:
    // Success test
    TEST_METHOD(ShouldClone1) {
        Derived1 derived;
        Base1& base = derived;
        Base1* basePtr = base.Clone();
        Derived1* derivedPtr = dynamic_cast<Derived1*>(basePtr);
        Assert::IsNotNull(derivedPtr);
    }

    // Failed test !!!
    TEST_METHOD(ShouldClone2) {
        Derived2 derived;
        Base2& base = derived;
        Base2* basePtr = base.Clone();
        Derived2* derivedPtr = dynamic_cast<Derived2*>(basePtr);
        Assert::IsNotNull(derivedPtr);
    }
};
}

The problem here is the test case 'ShouldClone1' success, but 'ShouldClone2' failed.

It seems that in the 2nd test case, the Clone method doesn't go to the one of Derived class.

Do you know what's the problem? What's the difference between those 2 implementations?

I guess this is because of 'diamond' inheritance problem. But if use 'public virtual' inheritance and implement the Clone method in class Derived2, then I don't need to inherit Cloneable for it at the first place ...

A updated version:

class Cloneable {
public:
    // Could make this pure virtual
    virtual ~Cloneable() {}

    // Could make this pure virtual
    virtual Cloneable* Clone() const {
        return new Cloneable(*this);
    }
};

template<typename T>
class CloneableBase : public virtual Cloneable {
public:
    virtual ~CloneableBase() {}

    virtual Cloneable* Clone() const {
        return new T(dynamic_cast<const T&>(*this));
    }
};

class Base2 : public virtual CloneableBase<Base2> {
};

class Derived2 : public virtual Base2 {
    virtual Cloneable* Clone() const {
        return new Derived2(*this);
    }
};

Update 2：

The article Polymorphic cloning and the CRTP describes the solution quite clear.

Body:
It is possible without manually writing Clone() method in every derived class. But we can not get away with just CRTP. Instead of instantiating Derived classes directly we will always indirectly instantiate super derived template class which will deal with diamond problem for us.

class IClonable
{
    public: virtual IClonable *
    CloneImpl(void) const = 0;

    public: virtual
    ~IClonable(void) {}
};

template< typename TClonable > TClonable *
Construct();

template< typename TBase >
class TheFinalClass final: public TBase, public virtual IClonable
{
    template< typename TClonable > friend TClonable *
    Construct();

    private:
    TheFinalClass(void) {}

    private: explicit
    TheFinalClass(TheFinalClass const & other): TBase(other) {}

    private: IClonable *
    CloneImpl(void) const override
    {
        return(new TheFinalClass(*this));
    }
};

template< typename TClonable > TClonable *
Construct() {return(new TheFinalClass< TClonable >());}

template< typename TDerived >
class Cloneable: public virtual IClonable
{
    public: TDerived *
    Clone() const // notice that this method does not override anything
    {
        return(dynamic_cast< TDerived * >(dynamic_cast< IClonable const * >(this)->CloneImpl()));
    }
};

class Base2: public Cloneable< Base2 > {};

class Derived2: public Cloneable< Derived2 >, public Base2 {};

// Failed test !!!, Now works!!!
TEST_METHOD(ShouldClone2) {
    Derived2 * p_derived{Construct< Derived2 >()};
    Base2 * p_base{p_derived};
    Base2 * p_clone_base{p_base->Clone()};
    Derived2 * p_clone_derived{dynamic_cast< Derived2 * >(p_clone_base)};
    Assert::IsNotNull(p_clone_derived);
}


来源: stackexchange

问:
Bulk import of Web service vs. import scenario
I've recently come across some code from Github for using a multi-threaded Inventory Item import using web services:

https://github.com/Acumatica/InventoryItemImportMultiThreaded

I'd like to know if this is faster or better than using an import scenario for mass import, and what may be the advantages of one over the other.

答: We have used the multi-threaded inventory import and it is MUCH faster than an import Scenario.  We were importing 250K Stock Items.  Doing via import scenario, which only uses one thread, took 26 hours.  Using the tool on Github brought that down to 6 hours.  Be aware though that Acumatica limits your processing power to the licensed amount of cores.  The license we used was an enterprise license so we could use a lot of cores. Here is a great article that talks about bulk loading: Optomizing Large Import</p>

ContentLicense: CC BY-SA 3.0


问:
Spring Boot Maven Plugin - No BOOT-INF directory
Between version 1.3.8.RELEASE of the spring-boot-maven-plugin and version 1.4.0.RELEASE - there has been a change in the generated package structure (if you extract the uber jar file)
1.3.8.RELEASE com, lib, META-INF and org directories
1.4.0.RELEASE has a BOOT-INF, META-INF and org directories
Basically from 1.4.0.RELEASE onwards - all the classes and libs are in the BOOT-INF directory.
Due to this - when you try to run a Spring Boot project on Amazon Lambda - it says that there is a jar not found as it cannot read the new Spring Boot Uber jar structure

My question is - is it possible in the newer versions of the Spring Boot Maven Plugin to get it to generate the uber jar to be the same structure as in version 1.3.9.RELEASE?

I tried the maven-shade-plugin - but that leads to other issues

Any help is greatly appreciated

Thanks
Damien

答:
The solution was to add the MODULE layout for the plugin in the pom.xml file</p>

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <layout>MODULE</layout>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

Body:
The solution was to add the MODULE layout for the plugin in the pom.xml file

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <layout>MODULE</layout>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>


问:
Delete all domain cookies without knowing the path
I accidentally set some cookies that I shouldn't have. For example, my cookie is called "lang", and my mistake was not setting the domain nor the path of the cookie. So, the browser created the cookie with the defaults, which meant that users who visited the "products" page of my website ended up with a cookie like:

```<code>Name        Value        Domain        Path
lang        en           example.com   /products/
</code>```

When in reality, the cookie should've been:

```<code>Name        Value        Domain        Path
lang        en           example.com   /
</code>```

The bad code was there for a little while, which means that the path of the cookie happens to be whatever page the user was visiting.

My question is, is it possible for me to delete all the cookies under the example.com domain without knowing the paths?

I've tried it in both JS and PHP, but without passing the path of the cookie, the browser refuses to delete it. Given how long the bad code was live, there are possibly thousands of paths. The reason there's so many paths is because most users come from Google, so they land directly on a page like example.com/products/a-product, which means that the path of the cookie will be /products/a-product

Thank you

答:
The following is a possible solution in PHP... We just unset the cookies by changing the expiration time. Please report to documentation.

Delete ALL cookies

```<code>if (isset($_SERVER['HTTP_COOKIE'])) {
    // We get the server cookies
    $server_cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    // We set the expiration time
    $expiration_time = time() - 3600;
    // And the default _path
    $default_path = '/';

    foreach ($server_cookies as $cookie) {
        // We explode given cookie in order to simply get the cookie name
        $all_parts = explode('=', $cookie);
        // We get the cookie name
        $name = trim($all_parts[0]);

        // We set the expiration time & empty the value
        setcookie($name, '', $expiration_time);

        // We set the path, empty the value and set the expiration time
        setcookie($name, '', $expiration_time, $default_path);
    }
}
</code>```

Delete specific cookie when we know its name & informations

```<code>// We set the cookie name we wand to delete
$name = 'lang'; // According to OP
// We set the path of the cookie
$path = '/products/';
// We set the domain of the cookie
$domain = 'exemple.com';
// We set the expiration time
$expiration_time = time() - 3600;

// We set the expiration time & empty the value
setcookie($name, '', $expiration_time);
// We set the path, empty the value and set the expiration time
setcookie($name, '', $expiration_time, $path, $domain);
</code>```

Body:
I accidentally set some cookies that I shouldn't have. For example, my cookie is called "lang", and my mistake was not setting the domain nor the path of the cookie. So, the browser created the cookie with the defaults, which meant that users who visited the "products" page of my website ended up with a cookie like:

Name        Value        Domain        Path
lang        en           example.com   /products/

When in reality, the cookie should've been:

Name        Value        Domain        Path
lang        en           example.com   /

The bad code was there for a little while, which means that the path of the cookie happens to be whatever page the user was visiting.

My question is, is it possible for me to delete all the cookies under the example.com domain without knowing the paths?

I've tried it in both JS and PHP, but without passing the path of the cookie, the browser refuses to delete it. Given how long the bad code was live, there are possibly thousands of paths. The reason there's so many paths is because most users come from Google, so they land directly on a page like example.com/products/a-product, which means that the path of the cookie will be /products/a-product

Thank you

Body:
The following is a possible solution in PHP... We just unset the cookies by changing the expiration time. Please report to documentation.

Delete ALL cookies

if (isset($_SERVER['HTTP_COOKIE'])) {
    // We get the server cookies
    $server_cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    // We set the expiration time
    $expiration_time = time() - 3600;
    // And the default _path
    $default_path = '/';

    foreach ($server_cookies as $cookie) {
        // We explode given cookie in order to simply get the cookie name
        $all_parts = explode('=', $cookie);
        // We get the cookie name
        $name = trim($all_parts[0]);

        // We set the expiration time & empty the value
        setcookie($name, '', $expiration_time);

        // We set the path, empty the value and set the expiration time
        setcookie($name, '', $expiration_time, $default_path);
    }
}

Delete specific cookie when we know its name & informations

// We set the cookie name we wand to delete
$name = 'lang'; // According to OP
// We set the path of the cookie
$path = '/products/';
// We set the domain of the cookie
$domain = 'exemple.com';
// We set the expiration time
$expiration_time = time() - 3600;

// We set the expiration time & empty the value
setcookie($name, '', $expiration_time);
// We set the path, empty the value and set the expiration time
setcookie($name, '', $expiration_time, $path, $domain);


问:
How to retrieve all values in serialized array
i'm trying to get all values in this array stored in wp_option table.
The array is:

```<code>a:3:{i:0;s:11:"development";i:1;s:4:"apps";i:2;s:10:"creativity";}
</code>```

What i need is just to get the values: development, apps, creativity.

I was trying:

```<code>$myOptions = get_option('hashtag');
foreach($myOptions as $option) {
echo $option;
}
</code>```

but the output is:

```<code>developmentappscreativitydevelopmentappscreativitydevelopmentappscreativity
</code>```

If i write:

```<code>var_dump ($option);
</code>```

the output is:

```<code>string(11) "development" string(4) "apps" string(10) "creativity" string(11) "development" string(4) "apps" string(10) "creativity" string(11) "development" string(4) "apps" string(10) "creativity"
</code>```

Thanks in advance.

答:
$myOptions = get_option('hashtag');

echo $myOptions[0]

Body:
i'm trying to get all values in this array stored in wp_option table.
The array is:

a:3:{i:0;s:11:"development";i:1;s:4:"apps";i:2;s:10:"creativity";}

What i need is just to get the values: development, apps, creativity.

I was trying:

$myOptions = get_option('hashtag');
foreach($myOptions as $option) {
echo $option;
}

but the output is:

developmentappscreativitydevelopmentappscreativitydevelopmentappscreativity

If i write:

var_dump ($option);

the output is:

string(11) "development" string(4) "apps" string(10) "creativity" string(11) "development" string(4) "apps" string(10) "creativity" string(11) "development" string(4) "apps" string(10) "creativity"

Thanks in advance.


问:
How can I log users activity
I'm using default ASP.NET user controls and SQL user provider.

How can I log somewhere when users login to web and when logout ?

Is there some tricks for it or just write to some .log file manually each time after user login. (Also , how can I check user IP adress ?)

Thank you.

答:
To log the logins you will need to handle the LoggedIn event and write to your log there. You can either manually set up a log or use an existing framework.

You have a few different options for getting the users IP:

```<code>Request.ServerVariables("REMOTE_ADDR");
Request.ServerVariables("HTTP_X_FORWARDED_FOR");
Request.UserHostAddress();
</code>```

ContentLicense: CC BY-SA 2.5

Title: How can I log users activity

Body:
To log the logins you will need to handle the LoggedIn event and write to your log there. You can either manually set up a log or use an existing framework.

You have a few different options for getting the users IP:

Request.ServerVariables("REMOTE_ADDR");
Request.ServerVariables("HTTP_X_FORWARDED_FOR");
Request.UserHostAddress();


问:
Is there a list of reserved words for Cloud Spanner?
Is there a documented list of keywords for Cloud Spanner?

For example, is CONTAINS a reserved word?

答: Yes, there is a list of keywords, documented at Reserved Keywords.</p>


问:
What is the proper way of using Set property in an angular2 model
In one of my models I wish to have a numbers property with unique numbers. Numbers are selectable checkboxes and I wish to use 2 way data binding with a set. What is the correct way to do it? Here's my code

Model

```<code>export class User {
    constructor(
        public id: number,
        public numbers: any
    ){}
}
</code>```

Component

```<code>import {Component} from '@angular/core';
import {User} from "./user.model";

@Component({
  selector: 'my-page-user',
  styleUrls: ['./user.component.scss'],
  templateUrl: './user.component.html',
})

export class PageUserComponent {
numbers: number[];
model: User;
constructor() { }

ngOnInit() {
    this.model = new User(0, new Set());
    this.numbers = Array.from(new Array(10), (x,i) => i+1);

}
</code>```

Template

```<code><form role="form" #userForm="ngForm" (ngSubmit)="onSubmit()">
   <div class="row">
      <div class="col-4 cell" *ngFor="let num of numbers; let i=index" >
         <md-checkbox [(ngModel)]="model.numbers[i]" name="numbers">{{i}}</md-checkbox>
      </div>
  </div>
</form>
{{model.numbers | json}} <!-- {"1": true, "2": true, "3": false } -->
{{model.numbers.size}} <!-- 0 -->
</code>```

答:
You could listen to the change even and run some custom code when the checkbox changes. e.g.</p>

```<code><md-checkbox (change)="$event.checked ? mySet.add(num) : mySet.delete(num)">...</md-checkbox>
</code>```

Body:
In one of my models I wish to have a numbers property with unique numbers. Numbers are selectable checkboxes and I wish to use 2 way data binding with a set. What is the correct way to do it? Here's my code

Model

export class User {
    constructor(
        public id: number,
        public numbers: any
    ){}
}

Component

import {Component} from '@angular/core';
import {User} from "./user.model";

@Component({
  selector: 'my-page-user',
  styleUrls: ['./user.component.scss'],
  templateUrl: './user.component.html',
})

export class PageUserComponent {
numbers: number[];
model: User;
constructor() { }

ngOnInit() {
    this.model = new User(0, new Set());
    this.numbers = Array.from(new Array(10), (x,i) => i+1);

}

Template

<form role="form" #userForm="ngForm" (ngSubmit)="onSubmit()">

         <md-checkbox [(ngModel)]="model.numbers[i]" name="numbers">{{i}}</md-checkbox>

</form>
{{model.numbers | json}}
{{model.numbers.size}}

Body:
You could listen to the change even and run some custom code when the checkbox changes. e.g.

<md-checkbox (change)="$event.checked ? mySet.add(num) : mySet.delete(num)">...</md-checkbox>


问:
Pass an object attribute as Parameter java spring
Can I pass an attribute as parameter in a method from my Repository?

Example:

```<code>@Query("select a from Account a where :attr = :value")
public Page<Account> searchByFilter(@Param("attr")
       String attribute,@Param("value")String value,Pageable pageable);
</code>```

Call example :

```<code>searchByFilter("status","Active",....);
</code>```

Thanks

答:
No, it is not possible.

Basically your query can be compiled and successfully executed, however it will be translated not the way you like.

At the end you'll have sql like this

```<code>select a.* from account a where 'status' = 'Active';
</code>```

Note: status is translated to string value, not the column name.

Body:
Can I pass an attribute as parameter in a method from my Repository?

Example:

@Query("select a from Account a where :attr = :value")
public Page<Account> searchByFilter(@Param("attr")
       String attribute,@Param("value")String value,Pageable pageable);

Call example :

searchByFilter("status","Active",....);

Thanks

Body:
No, it is not possible.

Basically your query can be compiled and successfully executed, however it will be translated not the way you like.

At the end you'll have sql like this

select a.* from account a where 'status' = 'Active';

Note: status is translated to string value, not the column name.


问:
ASP.NET DATA TABLE Traverse Problem
I am getting the Data table a output from my DataAccess Layer.

In My Datatable I am getting users Name,Number,Qualification

I want to assign a users name,number,qualification to a textbox for a particular user id,

How can i do that.

Help

答:
assuming the datatable has 1 row:

```<code>DataRow row = table.Rows[0];
textbox1.text = row["Name"];
textbox2.text = row["Number"];
</code>```

and so on

if there are multiple rows in the datatable, you need to select the row with that particular used id

```<code>DataRow row = table.Select("ID=" + UserID.ToString());
</code>```

Title: ASP.NET DATA TABLE Traverse Problem

Body:
assuming the datatable has 1 row:

DataRow row = table.Rows[0];
textbox1.text = row["Name"];
textbox2.text = row["Number"];

and so on

if there are multiple rows in the datatable, you need to select the row with that particular used id

DataRow row = table.Select("ID=" + UserID.ToString());


问:
How to import Seaborn on EC2 t2.micro instance?
I am trying to import seaborn as sns on EC2 AWS ipython notebook.

But I am getting the following error. Please help

```<code>import seaborn as sns
</code>```

ImportError                               Traceback (most recent call last)
 in ()
----> 1 import seaborn as sns

ImportError: No module named seaborn

答:
You may first want to download seaborn package. It is not available by default with python installation.

Use pip to download :

```<code>pip install seaborn
</code>```

Additionaly, you can try installing anaconda

```<code>$ curl -O https://repo.continuum.io/archive/Anaconda3-4.3.1-Linux-x86_64.sh
$ chmod 777 Anaconda3-4.3.1-Linux-x86_64.sh
$ ./Anaconda3-4.3.1-Linux-x86_64.sh
... (Press enter/yes where ever required )
$ conda install seaborn
</code>```

Body:
I am trying to import seaborn as sns on EC2 AWS ipython notebook.

But I am getting the following error. Please help

import seaborn as sns

ImportError                               Traceback (most recent call last)
 in ()
----> 1 import seaborn as sns

ImportError: No module named seaborn

Body:
You may first want to download seaborn package. It is not available by default with python installation.

Use pip to download :

pip install seaborn

Additionaly, you can try installing anaconda

$ curl -O https://repo.continuum.io/archive/Anaconda3-4.3.1-Linux-x86_64.sh
$ chmod 777 Anaconda3-4.3.1-Linux-x86_64.sh
$ ./Anaconda3-4.3.1-Linux-x86_64.sh
... (Press enter/yes where ever required )
$ conda install seaborn


问:
How to include integer constraint in MatLab's 'linprog( )' function?
So I'm using linprog on matlab in order to solve an optimization problem and one of the constraints is that all the numbers are multiples of 0.5 or in other terms, every number doubled is an integer.
Because of the form that all the constraints must be in (they must all be in linear equations), I'm struggling to find a way to set this rule as a constraint.

How can I write a constraint to linprog to ensure all the numbers in the return array are multiples of 0.5?

Thanks in advance!

答:
You can do it easily using intlinprog.
https://www.mathworks.com/help/optim/ug/intlinprog.html

For this, you would have to declare an integer variable x_int.

If x was your initial continuous variable, then the following constraint ensures that x is always a multiple of 0.5

2x = x_int


问:
pytz localize vs datetime replace
I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:

.localize behaviour:

```<code>>>> tz
<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
>>> d
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421)

>>> tz.localize(d)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
>>> tz.normalize(tz.localize(d))
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code>```

As you can see, time has not been changed as a result of localize/normalize operations.
However, if .replace is used:

```<code>>>> d.replace(tzinfo=tz)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>)
>>> tz.normalize(d.replace(tzinfo=tz))
datetime.datetime(2009, 9, 2, 15, 1, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
</code>```

Which seems to make adjustments into datetime.

Question is - which is correct and why other's wrong?

答:
localize is the correct function to use for creating datetime aware objects with an initial fixed datetime value. The resulting datetime aware object will have the original datetime value. A very common usage pattern in my view, and one that perhaps pytz can better document.

replace(tzinfo = ...) is unfortunately named. It is a function that is random in its behaviour. I would advise avoiding the use of this function to set timezones unless you enjoy self-inflicted pain. I have already suffered enough from using this function.

Title: pytz localize vs datetime replace

Body:
I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime:

.localize behaviour:

>>> tz
<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>
>>> d
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421)

>>> tz.localize(d)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)
>>> tz.normalize(tz.localize(d))
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)

As you can see, time has not been changed as a result of localize/normalize operations.
However, if .replace is used:

>>> d.replace(tzinfo=tz)
datetime.datetime(2009, 9, 2, 14, 45, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>)
>>> tz.normalize(d.replace(tzinfo=tz))
datetime.datetime(2009, 9, 2, 15, 1, 42, 91421,
                  tzinfo=<DstTzInfo 'Africa/Abidjan' GMT0:00:00 STD>)

Which seems to make adjustments into datetime.

Question is - which is correct and why other's wrong?


问:
Need to reset fields in PHP edit form somehow
I have a DB-based AMCharts form/page that graphs figures that are entered in a separate edit form accessed from that main page. This latter php edit form is set up to always bring up the present set of entries in every field. This edit form serves two purposes: one is to be able to correct earlier mistakes, and the other is to enter a whole set of new ones. The new figures are entered in this edit page and then submitted. A series of four sets of previous generations are saved in identical tables, which are also graphed on the same main page. A JS div slider script allows the user to compare among 5 generations of separate graphs in the same space. A trigger built into MySql allows each new set to be passed on to older sets, 5 gen deep. Without getting into too many details, the trigger is written so that it is activated if two specific fields in the form are different from the previous. Thus allowing mistakes to be corrected without activating the trigger. With me so far? My question does not concern the structure of the thing, it works fine, but just one problem that does not seem to be available on SO or any other google search result. Specifically, in the case that the edit form is used to enter a brand new set of numbers, how could you use a reset button that activates  a script that clears all the old figures from the inputs? I've found numerous answers on SO that use either pure JS or JQuery, but they are not used on PHP forms, rather HMTL forms. Some posters point out that this is anyhow not possible, as edit forms contain DB values cannot be replaced unless the SUBMIT button is used. This simple device is to make entry of new figures easier when they are empty, but I haven't found any scripts so far that succeed in clearing them. The simple reset code that works in HTML forms but in my php one:

```<code>   <script>function resetform() {
   document.getElementById("myform").reset();}</script>

   <form action="" method="post" id="myform">

   <input value="RESET" onclick="resetform()">
</code>```

答:
As no one answered this question, I assume, as I conjectured in the question, that this is not possible. My solution is to circumvent this problem by having two forms. Since you can recall DB values with this line-

```<code>  value="<?php echo $var;?>"
</code>```

I created another form almost exactly as the edit form minus the echo info:

```<code>  value=""
</code>```

so that I end up with two forms-the "edit" one with echo which is used to correct mistakes, and a "new" form without the echo instruction. So, one form recalls the DB values, the other doesn't. Keep in mind both submit to the table with the same ID, since I want the latest values, and older ones of more than 5 gens become irrelevant. Hope this is useful to anyone with similar problems. Post questions and maybe I'll be able to answer them.

EDIT: Also thanks to @miken32's suggestion, the following article does the trick, but my solution, though not 100% addressing the issues in initial post, is the best for my purposes:
How can I use a reset button for php form?

Body:
I have a DB-based AMCharts form/page that graphs figures that are entered in a separate edit form accessed from that main page. This latter php edit form is set up to always bring up the present set of entries in every field. This edit form serves two purposes: one is to be able to correct earlier mistakes, and the other is to enter a whole set of new ones. The new figures are entered in this edit page and then submitted. A series of four sets of previous generations are saved in identical tables, which are also graphed on the same main page. A JS div slider script allows the user to compare among 5 generations of separate graphs in the same space. A trigger built into MySql allows each new set to be passed on to older sets, 5 gen deep. Without getting into too many details, the trigger is written so that it is activated if two specific fields in the form are different from the previous. Thus allowing mistakes to be corrected without activating the trigger. With me so far? My question does not concern the structure of the thing, it works fine, but just one problem that does not seem to be available on SO or any other google search result. Specifically, in the case that the edit form is used to enter a brand new set of numbers, how could you use a reset button that activates  a script that clears all the old figures from the inputs? I've found numerous answers on SO that use either pure JS or JQuery, but they are not used on PHP forms, rather HMTL forms. Some posters point out that this is anyhow not possible, as edit forms contain DB values cannot be replaced unless the SUBMIT button is used. This simple device is to make entry of new figures easier when they are empty, but I haven't found any scripts so far that succeed in clearing them. The simple reset code that works in HTML forms but in my php one:

   <form action="" method="post" id="myform">

   <input value="RESET" onclick="resetform()">

Body:
As no one answered this question, I assume, as I conjectured in the question, that this is not possible. My solution is to circumvent this problem by having two forms. Since you can recall DB values with this line-

  value="<?php echo $var;?>"

I created another form almost exactly as the edit form minus the echo info:

  value=""

so that I end up with two forms-the "edit" one with echo which is used to correct mistakes, and a "new" form without the echo instruction. So, one form recalls the DB values, the other doesn't. Keep in mind both submit to the table with the same ID, since I want the latest values, and older ones of more than 5 gens become irrelevant. Hope this is useful to anyone with similar problems. Post questions and maybe I'll be able to answer them.

EDIT: Also thanks to @miken32's suggestion, the following article does the trick, but my solution, though not 100% addressing the issues in initial post, is the best for my purposes:
How can I use a reset button for php form?


问:
UIScrollView Scrolling Up
I'm trying to get a UIScrollView to scroll upwards instead of downwards.I have everything set up except I don't know what line I should use to accomplish this. What should I do?

Niall

答:
What I think you mean by this is that you want a scrollView that starts at the bottom and your content can be accessed by scrolling up.

In this case you simply need to figure out how large your content is, and set the setContentOffset of your scrollView to the height of your content:

```<code>override func viewDidLoad() {
    // other code here...

    // set the contentSize of the scrollView somewhere in here...

    // get the offset based on the size of the content
    let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
    // do not animate because we want to immediately scroll to the bottom
    scrollView.setContentOffset(bottomOffset, animated: false)
</code>```

This code is adapted from this answer.

Title: UIScrollView Scrolling Up

Body:
What I think you mean by this is that you want a scrollView that starts at the bottom and your content can be accessed by scrolling up.

In this case you simply need to figure out how large your content is, and set the setContentOffset of your scrollView to the height of your content:

override func viewDidLoad() {
    // other code here...

    // set the contentSize of the scrollView somewhere in here...

    // get the offset based on the size of the content
    let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
    // do not animate because we want to immediately scroll to the bottom
    scrollView.setContentOffset(bottomOffset, animated: false)

This code is adapted from this answer.


问:
EC2 IAM policy to require tags
AWS just released required tag support for EC2/EBS:
New – Tag EC2 Instances & EBS Volumes on Creation.

However, the example given only checks if tags have a fixed value which isn't useful to us because our users can enter free form values for required tags. How can a policy be written to check tags are present?

For example, we need something like this:

```<code>"Statement": [
    {
      "Sid": "DenyMissingTags",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:us-east-1:accountid:instance/*",
      "Condition": {
        "StringExists": [
          "aws:RequestTag/costcenter",
          "aws:RequestTag/stack",
         ]
       }
     }
]
</code>```

Obviously, I made up StringExists

答:
You could do something using StringLike or StringNotLike, but it's limited to wildcards if that works for you.

String Conditional Operators

StringLike - Case-sensitive matching. The values can include a multi-character match wildcard (*) or a single-character match wildcard (?) anywhere in the string.

Example:

```<code>"Statement": [
{
  "Sid": "DenyMissingTags",
  "Effect": "Deny",
  "Action": "ec2:RunInstances",
  "Resource": "arn:aws:ec2:us-east-1:accountid:instance/*",
  "Condition": {
    "StringLike": [
      "aws:RequestTag/costcenter": "*",
      "aws:RequestTag/stack": "*"
      ]
    }
  }
]
</code>```

I haven't tested it, but it should work.

Title: EC2 IAM policy to require tags

Body:
AWS just released required tag support for EC2/EBS:
New – Tag EC2 Instances & EBS Volumes on Creation.

However, the example given only checks if tags have a fixed value which isn't useful to us because our users can enter free form values for required tags. How can a policy be written to check tags are present?

For example, we need something like this:

"Statement": [
    {
      "Sid": "DenyMissingTags",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:us-east-1:accountid:instance/*",
      "Condition": {
        "StringExists": [
          "aws:RequestTag/costcenter",
          "aws:RequestTag/stack",
         ]
       }
     }
]

Obviously, I made up StringExists

Body:
You could do something using StringLike or StringNotLike, but it's limited to wildcards if that works for you.

String Conditional Operators

StringLike - Case-sensitive matching. The values can include a multi-character match wildcard (*) or a single-character match wildcard (?) anywhere in the string.

Example:

"Statement": [
{
  "Sid": "DenyMissingTags",
  "Effect": "Deny",
  "Action": "ec2:RunInstances",
  "Resource": "arn:aws:ec2:us-east-1:accountid:instance/*",
  "Condition": {
    "StringLike": [
      "aws:RequestTag/costcenter": "*",
      "aws:RequestTag/stack": "*"
      ]
    }
  }
]

I haven't tested it, but it should work.


问:
Java TreeSet contains() gives false results
I am trying to code a little bit of math with java. What I am trying to do, is to put cyclotomic cosets to the TreeSet. A coset has an index and a set of integer numbers. A coset is equal to other coset if the set has the same elements. If sets differ, then coset is ordered by its index.

For example:

```<code>C1 = [1, 2, 4, 8]
C3 = [3, 6, 9, 12]
C9 = [3, 6, 9, 12]

C1 is less than C3
C3 is equal to C9
</code>```

Well enough math. I chose to put cosets to TreeSet because I do not need duplicate elements and I need to have them sorted by index.

The problem is even TreeSet.contains() returns false, I can still find one element in the TreeSet which is equal when using compareTo() and equals() methods.

This is the actual printout of the program:

```<code>cosets = [C0, C1, C3, C5, C7]
cosets.contains(C9) = false
C0.compareTo(C9) = -1, C0.equals(C9) = false
C1.compareTo(C9) = -1, C1.equals(C9) = false
C3.compareTo(C9) = 0, C3.equals(C9) = true
C5.compareTo(C9) = -1, C5.equals(C9) = false
C7.compareTo(C9) = -1, C7.equals(C9) = false
</code>```

I am attaching the code below. I did not want to make code any simplier, because I found that it does some magic. If you change MAGIC_INDEX value to 7 or less in the code, it starts to work. It seems like a JVM bug to me.

http://2m.lt/files/Main.java

http://2m.lt/files/Coset.java

Any suggestions?

答:
Your Comparable implementation in Coset does not provide a total ordering.

Looks like you should define an order on the value TreeSet. Either before or after checking index.

Body:
I am trying to code a little bit of math with java. What I am trying to do, is to put cyclotomic cosets to the TreeSet. A coset has an index and a set of integer numbers. A coset is equal to other coset if the set has the same elements. If sets differ, then coset is ordered by its index.

For example:

C1 = [1, 2, 4, 8]
C3 = [3, 6, 9, 12]
C9 = [3, 6, 9, 12]

C1 is less than C3
C3 is equal to C9

Well enough math. I chose to put cosets to TreeSet because I do not need duplicate elements and I need to have them sorted by index.

The problem is even TreeSet.contains() returns false, I can still find one element in the TreeSet which is equal when using compareTo() and equals() methods.

This is the actual printout of the program:

cosets = [C0, C1, C3, C5, C7]
cosets.contains(C9) = false
C0.compareTo(C9) = -1, C0.equals(C9) = false
C1.compareTo(C9) = -1, C1.equals(C9) = false
C3.compareTo(C9) = 0, C3.equals(C9) = true
C5.compareTo(C9) = -1, C5.equals(C9) = false
C7.compareTo(C9) = -1, C7.equals(C9) = false

I am attaching the code below. I did not want to make code any simplier, because I found that it does some magic. If you change MAGIC_INDEX value to 7 or less in the code, it starts to work. It seems like a JVM bug to me.

http://2m.lt/files/Main.java

http://2m.lt/files/Coset.java

Any suggestions?


问:
Docker Networking - nginx: [emerg] host not found in upstream
I have recently started migrating to Docker 1.9 and Docker-Compose 1.5's networking features to replace using links.

So far with links there were no problems with nginx connecting to my php5-fpm fastcgi server located in a different server in one group via docker-compose. Newly though when I run docker-compose --x-networking up my php-fpm, mongo and nginx containers boot up, however nginx quits straight away with [emerg] 1#1: host not found in upstream "waapi_php_1" in /etc/nginx/conf.d/default.conf:16

However, if I run the docker-compose command again while the php and mongo containers are running (nginx exited), nginx starts and works fine from then on.

This is my docker-compose.yml file:

```<code>nginx:
  image: nginx
  ports:
    - "42080:80"
  volumes:
    - ./config/docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro

php:
  build: config/docker/php
  ports:
    - "42022:22"
  volumes:
    - .:/var/www/html
  env_file: config/docker/php/.env.development

mongo:
  image: mongo
  ports:
    - "42017:27017"
  volumes:
    - /var/mongodata/wa-api:/data/db
  command: --smallfiles
</code>```

This is my default.conf for nginx:

```<code>server {
    listen  80;

    root /var/www/test;

    error_log /dev/stdout debug;
    access_log /dev/stdout;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/.+\.php(/|$) {
        # Referencing the php service host (Docker)
        fastcgi_pass waapi_php_1:9000;

        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;

        # We must reference the document_root of the external server ourselves here.
        fastcgi_param SCRIPT_FILENAME /var/www/html/public$fastcgi_script_name;

        fastcgi_param HTTPS off;
    }
}
</code>```

How can I get nginx to work with only a single docker-compose call?

答:
I believe Nginx dont take in account Docker resolver (127.0.0.11), so please, can you try adding:

```<code>resolver 127.0.0.11
</code>```

in your nginx configuration file?

Body:
I have recently started migrating to Docker 1.9 and Docker-Compose 1.5's networking features to replace using links.

So far with links there were no problems with nginx connecting to my php5-fpm fastcgi server located in a different server in one group via docker-compose. Newly though when I run docker-compose --x-networking up my php-fpm, mongo and nginx containers boot up, however nginx quits straight away with [emerg] 1#1: host not found in upstream "waapi_php_1" in /etc/nginx/conf.d/default.conf:16

However, if I run the docker-compose command again while the php and mongo containers are running (nginx exited), nginx starts and works fine from then on.

This is my docker-compose.yml file:

nginx:
  image: nginx
  ports:
    - "42080:80"
  volumes:
    - ./config/docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro

php:
  build: config/docker/php
  ports:
    - "42022:22"
  volumes:
    - .:/var/www/html
  env_file: config/docker/php/.env.development

mongo:
  image: mongo
  ports:
    - "42017:27017"
  volumes:
    - /var/mongodata/wa-api:/data/db
  command: --smallfiles

This is my default.conf for nginx:

server {
    listen  80;

    root /var/www/test;

    error_log /dev/stdout debug;
    access_log /dev/stdout;

    location / {
        # try to serve file directly, fallback to app.php
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/.+\.php(/|$) {
        # Referencing the php service host (Docker)
        fastcgi_pass waapi_php_1:9000;

        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;

        # We must reference the document_root of the external server ourselves here.
        fastcgi_param SCRIPT_FILENAME /var/www/html/public$fastcgi_script_name;

        fastcgi_param HTTPS off;
    }
}

How can I get nginx to work with only a single docker-compose call?

Body:
I believe Nginx dont take in account Docker resolver (127.0.0.11), so please, can you try adding:

resolver 127.0.0.11

in your nginx configuration file?


问:
Using only string with Flex/Bison
I am new in Flex/Bison. I want to use only strings for values (is a language translator). I have this for test:

example.l:

```<code>%option noyywrap nodefault

%{
#include <string.h>
#include "example.tab.h"
%}

%%

[ \t\n] {;}
"<="    {return LEFT;}
"=>"    {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }

%%
</code>```

example.y:

```<code>%{
#include <stdio.h>
#define YYSTYPE char const *
%}

%token NUMBER
%token LEFT "<=" RIGHT "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); }
     | NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); }
     | NUMBER '>' NUMBER  { printf("%s > %s\n",$1,$3); }
     | NUMBER '<' NUMBER  { printf("%s < %s\n",$1,$3); }

%%

main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }
</code>```

When I compiled:

```<code>bison -d example.y
flex example.l
cc -o example example.tab.c lex.yy.c -lfl
example.l: In function ‘yylex’:
example.l:13:9: warning: assignment makes integer from pointer without a cast
 [0-9]+ { yylval=strdup(yytext); return NUMBER; }
         ^
</code>```

But work as awaited.

If I don't use #define YYSTYPE char const * and use instead the %union:

```<code>%union {
   char * txt;
}

%token <txt> NUMBER
</code>```

And change the assignation to [0-9]+ { yylval.txt=strdup(yytext); return NUMBER; }, it has no warning and works.

I tried thing like define the same YYSTYPE in flex file and cast the assignation without success. What is wrong? How to fix without using %union?

Thanks.

答:
The final working example is:

example.l:

```<code>%option noyywrap nodefault

%{
#include <string.h>
#define YYSTYPE char *
#include "example.tab.h"
%}

%%

[ \t\n] {;}
"<="    {return LEFT;}
"=>"    {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }

%%
</code>```

example.y:

```<code>%{
#include <stdio.h>
#define YYSTYPE char *
%}

%token NUMBER
%token LEFT "<=" RIGHT "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER {
          printf("%s <= %s\n",$1,$3);
          free($1);
          free($3);
       }
     | NUMBER "=>" NUMBER {
          printf("%s => %s\n",$1,$3);
          free($1);
          free($3);
       }
     | NUMBER '>' NUMBER  {
          printf("%s > %s\n",$1,$3);
          free($1);
          free($3);
       }
     | NUMBER '<' NUMBER  {
          printf("%s < %s\n",$1,$3);
          free($1);
          free($3);
       }

%%

main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }
</code>```

Title: Using only string with Flex/Bison

Body:
I am new in Flex/Bison. I want to use only strings for values (is a language translator). I have this for test:

example.l:

%option noyywrap nodefault

%{
#include <string.h>
#include "example.tab.h"
%}

%%

[ \t\n] {;}
"<="    {return LEFT;}
"=>"    {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }

%%

example.y:

%{
#include <stdio.h>
#define YYSTYPE char const *
%}

%token NUMBER
%token LEFT "<=" RIGHT "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); }
     | NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); }
     | NUMBER '>' NUMBER  { printf("%s > %s\n",$1,$3); }
     | NUMBER '<' NUMBER  { printf("%s < %s\n",$1,$3); }

%%

main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }

When I compiled:

bison -d example.y
flex example.l
cc -o example example.tab.c lex.yy.c -lfl
example.l: In function ‘yylex’:
example.l:13:9: warning: assignment makes integer from pointer without a cast
 [0-9]+ { yylval=strdup(yytext); return NUMBER; }
         ^

But work as awaited.

If I don't use #define YYSTYPE char const * and use instead the %union:

%union {
   char * txt;
}

%token <txt> NUMBER

And change the assignation to [0-9]+ { yylval.txt=strdup(yytext); return NUMBER; }, it has no warning and works.

I tried thing like define the same YYSTYPE in flex file and cast the assignation without success. What is wrong? How to fix without using %union?

Thanks.

Body:
The final working example is:

example.l:

%option noyywrap nodefault

%{
#include <string.h>
#define YYSTYPE char *
#include "example.tab.h"
%}

%%

[ \t\n] {;}
"<="    {return LEFT;}
"=>"    {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }

%%

example.y:

%{
#include <stdio.h>
#define YYSTYPE char *
%}

%token NUMBER
%token LEFT "<=" RIGHT "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER {
          printf("%s <= %s\n",$1,$3);
          free($1);
          free($3);
       }
     | NUMBER "=>" NUMBER {
          printf("%s => %s\n",$1,$3);
          free($1);
          free($3);
       }
     | NUMBER '>' NUMBER  {
          printf("%s > %s\n",$1,$3);
          free($1);
          free($3);
       }
     | NUMBER '<' NUMBER  {
          printf("%s < %s\n",$1,$3);
          free($1);
          free($3);
       }

%%

main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }


问:
Differentiating between compressed .gz files and archived tar.gz files properly?
What is the proper way to deal with differentiating between a plain compressed file in gzip or bzip2 format (eg. .gz) and a tarball compressed with gzip or bzip2 (eg. .tar.gz)  Identification using suffix extensions is not a reliable option as it's possible files may end up renamed.

Now on the command line I am able to do something like this:

```<code>bzip2 -dc test.tar.bz2 |head|file -
</code>```

So I attempted something similar in python with the following function:

```<code>def get_magic(self, store_file, buffer=False, look_deeper=False):
    # see what we're indexing
    if look_deeper == True:
        m = magic.Magic(mime=True, uncompress=True)
    else:
        m = magic.Magic(mime=True)

    if buffer == False:
        try:
            file_type = m.from_file(store_file)

        except Exception, e:
            raise e

    else:
        try:
            file_type = m.from_buffer(store_file)

        except Exception, e:
            raise e

    return file_type
</code>```

Then when trying to read a compressed tarball I'll pass in the buffer from elsewhere via:

```<code>    file_buffer = open(file_name).read(8096)
    archive_check = self.get_magic(file_buffer, True, True)
</code>```

Unfortunately this then becomes problematic using the uncompress flag in python-magic because it appears that python-magic is expecting me to pass in the entire file even though I only want it to read the buffer.  I end up with the exception:

```<code>bzip2 ERROR: Compressed file ends unexpectedly
</code>```

Seeing as the the files I am looking at can end up being 2M to 20GB in size this becomes rather problematic. I don't want to read the entire file.

Can it be hacked and chop the end of the compressed file off and append it to the buffer?  Is it better to ignore the idea of uncompressing the file using python-magic and instead do it before I pass in a buffer to identify via:

```<code>    file_buffer = open(file_name, "r:bz2").read(8096)
</code>```

Is there a better way?

答:
I'm actually going to mark Mark's answer as the correct one as it gave me the hint.

I ended up dumping the project to do other things for a good six months and was stumped as the bz2.BZ2Decompressor didn't seem to be doing as it was supposed to. It turns out the problem isn't solvable in 1024 bytes.

```<code>#!/usr/bin/env python

import os
import bz2
import magic

store_file = "10mb_test_file.tar.bz2"
m = magic.Magic(mime=True)

file_buffer = open(store_file, "rb").read(1000000)
buffer_chunk = ""

decompressor = bz2.BZ2Decompressor()
print ( "encapsulating bz2" )
print ( type(file_buffer) )
print ( len(file_buffer) )
file_type = m.from_buffer(file_buffer)
print ( "file type: %s :" % file_type)

buffer_chunk += decompressor.decompress( file_buffer )
print ( "compressed file contents" )
print ( type(buffer_chunk) )
print ( len(buffer_chunk) )

file_type = m.from_buffer(buffer_chunk)
print ( "file type: %s :" % file_type)
</code>```

Strangely, with a 20MB tar.bz2 file I can use a value of 200,000 bytes rather than 1,000,000 bytes but this value won't work on the 10MB test file.  I don't know if it is specific to the tar.bz2 archive involved and I haven't looked into the algorithms involved to see if they are at specific points but reading roughly 10MB of data so far seems to work on every archive file up to 5GB. An open().read(buffer) will read up to the size of the buffer or EOF so this is okay.

Body:
What is the proper way to deal with differentiating between a plain compressed file in gzip or bzip2 format (eg. .gz) and a tarball compressed with gzip or bzip2 (eg. .tar.gz)  Identification using suffix extensions is not a reliable option as it's possible files may end up renamed.

Now on the command line I am able to do something like this:

bzip2 -dc test.tar.bz2 |head|file -

So I attempted something similar in python with the following function:

def get_magic(self, store_file, buffer=False, look_deeper=False):
    # see what we're indexing
    if look_deeper == True:
        m = magic.Magic(mime=True, uncompress=True)
    else:
        m = magic.Magic(mime=True)

    if buffer == False:
        try:
            file_type = m.from_file(store_file)

        except Exception, e:
            raise e

    else:
        try:
            file_type = m.from_buffer(store_file)

        except Exception, e:
            raise e

    return file_type

Then when trying to read a compressed tarball I'll pass in the buffer from elsewhere via:

    file_buffer = open(file_name).read(8096)
    archive_check = self.get_magic(file_buffer, True, True)

Unfortunately this then becomes problematic using the uncompress flag in python-magic because it appears that python-magic is expecting me to pass in the entire file even though I only want it to read the buffer.  I end up with the exception:

bzip2 ERROR: Compressed file ends unexpectedly

Seeing as the the files I am looking at can end up being 2M to 20GB in size this becomes rather problematic. I don't want to read the entire file.

Can it be hacked and chop the end of the compressed file off and append it to the buffer?  Is it better to ignore the idea of uncompressing the file using python-magic and instead do it before I pass in a buffer to identify via:

    file_buffer = open(file_name, "r:bz2").read(8096)

Is there a better way?

Body:
I'm actually going to mark Mark's answer as the correct one as it gave me the hint.

I ended up dumping the project to do other things for a good six months and was stumped as the bz2.BZ2Decompressor didn't seem to be doing as it was supposed to. It turns out the problem isn't solvable in 1024 bytes.

#!/usr/bin/env python

import os
import bz2
import magic

store_file = "10mb_test_file.tar.bz2"
m = magic.Magic(mime=True)

file_buffer = open(store_file, "rb").read(1000000)
buffer_chunk = ""

decompressor = bz2.BZ2Decompressor()
print ( "encapsulating bz2" )
print ( type(file_buffer) )
print ( len(file_buffer) )
file_type = m.from_buffer(file_buffer)
print ( "file type: %s :" % file_type)

buffer_chunk += decompressor.decompress( file_buffer )
print ( "compressed file contents" )
print ( type(buffer_chunk) )
print ( len(buffer_chunk) )

file_type = m.from_buffer(buffer_chunk)
print ( "file type: %s :" % file_type)

Strangely, with a 20MB tar.bz2 file I can use a value of 200,000 bytes rather than 1,000,000 bytes but this value won't work on the 10MB test file.  I don't know if it is specific to the tar.bz2 archive involved and I haven't looked into the algorithms involved to see if they are at specific points but reading roughly 10MB of data so far seems to work on every archive file up to 5GB. An open().read(buffer) will read up to the size of the buffer or EOF so this is okay.


问:
Align google maps with another div next to it
The idea is to achieve this, without fixed heights. Before the validation they are both divs like 600px, but I want the google maps div to grow as the contact form div does. I tried the display: flex thing but I dont know if I am doing something wrong.

答:
If you submit the underlying code to the problem we could check if you used the "flex property" right. For a generally really good explanation on that topic you can take a read at: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

The easiest way of archieving this however would be using a height property of 100% on both, while wrapping them inside a div.


问:
Prefix in recursion does not work correctly
This is my code:

```<code>class Backwards {
    String str;
    Backwards(String s) {
        str = s;
    }

    void backward(int idx) {
        if(idx != str.length()-1) {
            System.out.println(idx);
            backward(++idx);
        }
        System.out.print(str.charAt(idx));
    }
}

class StrBackDemo {
    public static void main(String args[]) {
        Backwards s = new Backwards("This is a test");
        s.backward(0);
    }
}
</code>```

when I call function itself with expression idx +1 it works nicely, but with ++idx, it prints first character twice and doesn't print last character at all.

```<code>With <+idx> output: ttset a si sih
With <idx +1> output: tset a si sihT
</code>```

答:
++i will increment the value of i, and then return the incremented value.

```<code> i = 1;
 j = ++i;
 (i is 2, j is 2)
</code>```

i++ will increment the value of i, but return the original value that i held before being incremented.

```<code> i = 1;
 j = i++;
 (i is 2, j is 1)
</code>```

So in your code cosider for idx =0 ;

```<code>System.out.println(idx); //idx = 0;
            backward(++idx); //its changed idx = 1 and passed 1 to this function
 System.out.print(str.charAt(idx));//After all recursion call here idx =1 not idx =0;
</code>```

Hence you are getting wrong result

but in case of idx+1;

```<code>System.out.println(idx); //idx = 0;
                backward(idx+1); //its changed idx = 0 but passed 1 to this function
     System.out.print(str.charAt(idx));//After all recursion call here idx =0
</code>```

Body:
This is my code:

class Backwards {
    String str;
    Backwards(String s) {
        str = s;
    }

    void backward(int idx) {
        if(idx != str.length()-1) {
            System.out.println(idx);
            backward(++idx);
        }
        System.out.print(str.charAt(idx));
    }
}

class StrBackDemo {
    public static void main(String args[]) {
        Backwards s = new Backwards("This is a test");
        s.backward(0);
    }
}

when I call function itself with expression idx +1 it works nicely, but with ++idx, it prints first character twice and doesn't print last character at all.

With <+idx> output: ttset a si sih
With <idx +1> output: tset a si sihT

Body:
++i will increment the value of i, and then return the incremented value.

 i = 1;
 j = ++i;
 (i is 2, j is 2)

i++ will increment the value of i, but return the original value that i held before being incremented.

 i = 1;
 j = i++;
 (i is 2, j is 1)

So in your code cosider for idx =0 ;

System.out.println(idx); //idx = 0;
            backward(++idx); //its changed idx = 1 and passed 1 to this function
 System.out.print(str.charAt(idx));//After all recursion call here idx =1 not idx =0;

Hence you are getting wrong result

but in case of idx+1;

System.out.println(idx); //idx = 0;
                backward(idx+1); //its changed idx = 0 but passed 1 to this function
     System.out.print(str.charAt(idx));//After all recursion call here idx =0


问:
link is not working in IE8
i am using the jquery for developing my system.
for particular functionality i am sending link through json data to have link for each row
of jqgrid table.
as

```<code>"<a href='#' class='ui-icon ui-icon-pencil' onclick='EditClick(\"" + {MYPRIMARY KEY}+ "\");return false;'>Edit</a>"
</code>```

in javasript i have function as

```<code>function EditClick(param)
{
    $('#mainDiv').load('/contoller/action/' + param, function() {
    });
    return false;
}
</code>```

here action returns the view().

in this EditClick function i am loading another page in my main div.

This runs on IE7,firefox smoothly,but using it on IE8 sometimes its works sometimes not.
i mean sometime required page loads in main div sometimes not.
i realy dont understand the problem.
please guide me through this.
thank you.

答:
I had a few problems working with jgGrid events a row.
What I did was to add a custom button:

```<code>jQuery("myGrid").navGrid('#myPager', { edit: false, add: false, del: false, search: false }, {}, {}, {})
    .navButtonAdd('#myPager', { caption: "Do something", buttonicon: "ui-icon-note",
        onClickButton: function() { var rowid = jQuery("myGrid").jqGrid('getGridParam', 'selrow');
            if ((rowid == null) || (rowid == 0)) {
                alert("Select a row before!"); }
            else {
                EditClick(rowid);
                }
                }, position: "last" })
</code>```

As you can see the function EditClick is triggered only if you've selected one row in the grid. rowid should be your primary key.

Hope it helps.

Title: link is not working in IE8

Body:
i am using the jquery for developing my system.
for particular functionality i am sending link through json data to have link for each row
of jqgrid table.
as

"Edit"

in javasript i have function as

function EditClick(param)
{
    $('#mainDiv').load('/contoller/action/' + param, function() {
    });
    return false;
}

here action returns the view().

in this EditClick function i am loading another page in my main div.

This runs on IE7,firefox smoothly,but using it on IE8 sometimes its works sometimes not.
i mean sometime required page loads in main div sometimes not.
i realy dont understand the problem.
please guide me through this.
thank you.

Body:
I had a few problems working with jgGrid events a row.
What I did was to add a custom button:

jQuery("myGrid").navGrid('#myPager', { edit: false, add: false, del: false, search: false }, {}, {}, {})
    .navButtonAdd('#myPager', { caption: "Do something", buttonicon: "ui-icon-note",
        onClickButton: function() { var rowid = jQuery("myGrid").jqGrid('getGridParam', 'selrow');
            if ((rowid == null) || (rowid == 0)) {
                alert("Select a row before!"); }
            else {
                EditClick(rowid);
                }
                }, position: "last" })

As you can see the function EditClick is triggered only if you've selected one row in the grid. rowid should be your primary key.

Hope it helps.


问:
Efficient way to replace int in list with first occurrence index
I am looking for a way to replace every int element in a list with the index of its first occurrence in a separate Distinct list. For example, take the following list:

```<code><50, 2, 4, 5, 43, 42, 44, 14, 50, 44, 23, 2, 16, 4, 5, 23, 33 ... >
</code>```

The distinct list would read like this:

```<code><50, 2, 4, 5, 43, 42, 44, 14, 50, 23, 33 ... >
</code>```

I would like for the list to read as follows:

```<code><0, 1, 2, 3, 4, 5, 6, 7, 0, 6, 8, 1, 9, 3, 4, 8, 10 ...>
</code>```

I am new to LINQ operators, but I have the following code:

```<code>//Retrieve original list:
List<int> SubFaceList = FaceList.GetRange (faceBounds [fb], faceBounds [fb + 1]);

// Get unique face list entries:
List<int> UniqueFaceList = SubFaceList.Distinct ().ToList ();

//Replace values with first ocurrence:
List<int> RestructuredList = SubFaceList.Select ((vx,ix) => UniqueFaceList.IndexOf(vx)).ToList();
</code>```

I am doing this, in order to split up a large Collada triangular 3D mesh, into smaller submeshes. The arrays are face construction order, which reference an index of vertices in a separate array, so numbers could be referenced multiple times in the face array. However, upon executing my code, some meshes take upwards of 30 minutes to process.

I also have the following code, which extracts the given vertices from the main vertex array, which does not seem to suffer from the same crippling inefficiency:

```<code>List<Vector3> subVertices = Vertices.Where ((vx, ix) => UniqueFaceList.Contains (ix)).Select (vx => vx).ToList();
</code>```

Am I going about this wrong, and is there a potential way that I could extract the index based on the current vertex being processed in this statement? I know there has to be a more efficient way to get the information that I need, but I am not quite sure how.

答:
Store value and index to dictionary.</p>

```<code>var faceList = new List<int>{ 50, 2, 4, 5, 43, 42, 44, 14, 50, 44, 23, 2, 16, 4, 5, 23, 33};
var uniqueList = new Dictionary<int,int>();
var restructuredList = new List<int>();
var i = 0;
faceList.ForEach(f =>
{
  if (uniqueList.ContainsKey(f))
  {
    restructuredList.Add(uniqueList[f]);
    return;
  }
restructuredList.Add(i);
uniqueList.Add(f, i++);
});
</code>```

Body:
I am looking for a way to replace every int element in a list with the index of its first occurrence in a separate Distinct list. For example, take the following list:

<50, 2, 4, 5, 43, 42, 44, 14, 50, 44, 23, 2, 16, 4, 5, 23, 33 ... >

The distinct list would read like this:

<50, 2, 4, 5, 43, 42, 44, 14, 50, 23, 33 ... >

I would like for the list to read as follows:

<0, 1, 2, 3, 4, 5, 6, 7, 0, 6, 8, 1, 9, 3, 4, 8, 10 ...>

I am new to LINQ operators, but I have the following code:

//Retrieve original list:
List<int> SubFaceList = FaceList.GetRange (faceBounds [fb], faceBounds [fb + 1]);

// Get unique face list entries:
List<int> UniqueFaceList = SubFaceList.Distinct ().ToList ();

//Replace values with first ocurrence:
List<int> RestructuredList = SubFaceList.Select ((vx,ix) => UniqueFaceList.IndexOf(vx)).ToList();

I am doing this, in order to split up a large Collada triangular 3D mesh, into smaller submeshes. The arrays are face construction order, which reference an index of vertices in a separate array, so numbers could be referenced multiple times in the face array. However, upon executing my code, some meshes take upwards of 30 minutes to process.

I also have the following code, which extracts the given vertices from the main vertex array, which does not seem to suffer from the same crippling inefficiency:

List<Vector3> subVertices = Vertices.Where ((vx, ix) => UniqueFaceList.Contains (ix)).Select (vx => vx).ToList();

Am I going about this wrong, and is there a potential way that I could extract the index based on the current vertex being processed in this statement? I know there has to be a more efficient way to get the information that I need, but I am not quite sure how.

Body:
Store value and index to dictionary.

var faceList = new List<int>{ 50, 2, 4, 5, 43, 42, 44, 14, 50, 44, 23, 2, 16, 4, 5, 23, 33};
var uniqueList = new Dictionary<int,int>();
var restructuredList = new List<int>();
var i = 0;
faceList.ForEach(f =>
{
  if (uniqueList.ContainsKey(f))
  {
    restructuredList.Add(uniqueList[f]);
    return;
  }
restructuredList.Add(i);
uniqueList.Add(f, i++);
});


问:
SQL Server Convert case for letter that comes after - (hyphen)
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

```<code>Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123
</code>```

to

```<code>Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123
</code>```

Please help!

答:
This might help. </p>

```<code>DECLARE @InputString VARCHAR(MAX) = 'Aaa - aaa';
DECLARE @Index INT = CharIndex('-', @InputString);
DECLARE @StringToReplace VARCHAR(3) = SUBSTRING ( @InputString ,@Index , 3 );

SELECT REPLACE(@InputString,@StringToReplace,UPPER(@StringToReplace));
</code>```

Body:
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123

to

Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123

Please help!

Body:
This might help.

DECLARE @InputString VARCHAR(MAX) = 'Aaa - aaa';
DECLARE @Index INT = CharIndex('-', @InputString);
DECLARE @StringToReplace VARCHAR(3) = SUBSTRING ( @InputString ,@Index , 3 );

SELECT REPLACE(@InputString,@StringToReplace,UPPER(@StringToReplace));


问:
Relationship of Service and Module in Angular (2)
What is the relationship of a service with a feature module. After my research at high level, to me it feels like module is a way of just keeping components and pipes together (UI) with their dependencies.

I also felt services have can still stay outside and can be injected in any module and they don't come as packaged in any modules as components and pipes do ?

eg Take a feature module BaseModule and a service class BaseService. Can I ship BaseService to another module by having my BaseModule Imported or do I have to inject the base service every time to a new module, I need base service to be used ?

答:
Service added in a module has application scope by default. So it is visible everywhere.

https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-module-provider-visibility


问:
Resizing items which are rotated css
Wondering if someone can help.

I'm a beginner learning website development and have been playing around with different styles for a particular project. The one I'm trying at the moment has a background colour, on top of this is a central wrapper of 60% width which contains all the website gumph. on the sides of the wrapper I have text turned 90/270 running down the wrapper with the website name.

When I go to resize the website the text jumps, how do I get the text to stay in it's original position? Also a secondary question, the text I have put as a % in CSS, however it doesn't seem to resize with the screen, even if I try em, here is the css:

```<code>*{
                                                                        background-color:#085C08;
max-width:100%;
    max-height:100%;
    min-width:200px;
    margin:0 auto;
    }

.wrapper{
    width: 60%;
    background-color: #FDF3EC;
    margin:0 auto;
    margin-top:-1%;
    margin-bottom:-1.5%;
    }

.artwork-r{
    transform:rotate(90deg);
    white-space:nowrap;
    transform-origin:bottom;
    margin-top:-52.5%;
    margin-left:78.65%;
    position:absolute;
    width:0%;
    height:0%;
    clear:both;
    }

.artwork-r p{
    padding:0%;
    font-size:490%;
    font-family:Verdana, Geneva, Tahoma, sans-serif;
    color:#FDF3EC;
    }

.artwork-l{
    transform:rotate(270deg);
    white-space:nowrap;
    transform-origin:top left;
    margin-left:15.1%;
    margin-top:0.4%;
    position:absolute;
    width:0%;
    height:0%;
    clear:both;
    }

.artwork-l p{
    padding:0%;
    font-size:490%;
    font-family:Verdana, Geneva, Tahoma, sans-serif;
    color:#FDF3EC;
    }
</code>```

答:
when position the text, don't use margin-left or margin-top, those will change as the screen size changes. You should use top, bottom, left and/or right.

For the font size, em's and % are both based NOT on the screen size, but instead it's parent's font size. Without seeing your markup I am not 100% sure, but you will probably want the position of .artwork-l to be set as right: 100%;

Title: Resizing items which are rotated css

Body:
Wondering if someone can help.

I'm a beginner learning website development and have been playing around with different styles for a particular project. The one I'm trying at the moment has a background colour, on top of this is a central wrapper of 60% width which contains all the website gumph. on the sides of the wrapper I have text turned 90/270 running down the wrapper with the website name.

When I go to resize the website the text jumps, how do I get the text to stay in it's original position? Also a secondary question, the text I have put as a % in CSS, however it doesn't seem to resize with the screen, even if I try em, here is the css:

*{
                                                                        background-color:#085C08;
max-width:100%;
    max-height:100%;
    min-width:200px;
    margin:0 auto;
    }

.wrapper{
    width: 60%;
    background-color: #FDF3EC;
    margin:0 auto;
    margin-top:-1%;
    margin-bottom:-1.5%;
    }

.artwork-r{
    transform:rotate(90deg);
    white-space:nowrap;
    transform-origin:bottom;
    margin-top:-52.5%;
    margin-left:78.65%;
    position:absolute;
    width:0%;
    height:0%;
    clear:both;
    }

.artwork-r p{
    padding:0%;
    font-size:490%;
    font-family:Verdana, Geneva, Tahoma, sans-serif;
    color:#FDF3EC;
    }

.artwork-l{
    transform:rotate(270deg);
    white-space:nowrap;
    transform-origin:top left;
    margin-left:15.1%;
    margin-top:0.4%;
    position:absolute;
    width:0%;
    height:0%;
    clear:both;
    }

.artwork-l p{
    padding:0%;
    font-size:490%;
    font-family:Verdana, Geneva, Tahoma, sans-serif;
    color:#FDF3EC;
    }


问:
Realm on Swift - Creating Relationship
I have two classes that form a one to many relationship:

```<code>class FooA: Object {
    dynamic var someAValue: String

    let fooBList = List<FooB>()
}

class FooB: Object {
    dynamic var someBValue: String
}
</code>```

I add the object into Realm in this fashion:

```<code>let fooA = FooA()

fooA.someAValue = 'a value'

let fooB = FooB()

fooB.someBValue = 'a value'

fooA.fooBList.append(fooB)

let realm = try! Realm()

try! realm.write {
   realm.add(fooA)
}
</code>```

Everything goes well, the object is inserted into Realm.  However, when I attempt to access the FooB object like this:

```<code>fooA.fooBList[0]
</code>```

It goes BOOM and the app crashes!  So, obviously, I did not insert the relationship object into Realm correctly and the relationship is corrupted.  What did I miss in the Realm documentation? Must I create the Array first and add it to the parent object in another fashion?

To update on my question, this is the operation that wants to blow up:

```<code>FooApiClient.getFooAObjects()
        .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default))
        .observeOn(MainScheduler.instance)
        .subscribe { [weak self] in
            switch $0 {
            case .next(let fooAObjects):
                self?.fooAObjects = fooAObjects
            case .completed:

                self?.fooTableView.reloadData()

                loadingView?.hide()

            case .error(let error):
                loadingView?.hide()

                self?.handleError(error)

                self?.showNoFooView()
            }
        }
        .addDisposableTo(disposeBag)
</code>```

The invocation: self?.fooTableView.reloadData() causes to the table view to attempt to display the foo objects retrieved and where it goes BOOM.

答:
Try something like this. It may have some mistakes.

```<code>class SomeTableViewController: UITableViewController {

var fooA  : FooA?

override func viewDidLoad() {
        super.viewDidLoad()
        let realm = try! Realm()
        if let aFooA = realm.objects(FooA.self).first{
            fooA = aFooA
            self.reloadTableView()
        }
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if let _ = fooA{
        return fooA!.fooBList.count
    }

    return 0
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "SomeCell", for: indexPath)
    // Configure the cell...
    let fooB = fooA!.fooBList[indexPath.row]
    cell.titleLabel.text = fooB.someBValue

    return cell
}
</code>```

}

Title: Realm on Swift - Creating Relationship

Body:
I have two classes that form a one to many relationship:

class FooA: Object {
    dynamic var someAValue: String

    let fooBList = List<FooB>()
}

class FooB: Object {
    dynamic var someBValue: String
}

I add the object into Realm in this fashion:

let fooA = FooA()

fooA.someAValue = 'a value'

let fooB = FooB()

fooB.someBValue = 'a value'

fooA.fooBList.append(fooB)

let realm = try! Realm()

try! realm.write {
   realm.add(fooA)
}

Everything goes well, the object is inserted into Realm.  However, when I attempt to access the FooB object like this:

fooA.fooBList[0]

It goes BOOM and the app crashes!  So, obviously, I did not insert the relationship object into Realm correctly and the relationship is corrupted.  What did I miss in the Realm documentation? Must I create the Array first and add it to the parent object in another fashion?

To update on my question, this is the operation that wants to blow up:

FooApiClient.getFooAObjects()
        .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .default))
        .observeOn(MainScheduler.instance)
        .subscribe { [weak self] in
            switch $0 {
            case .next(let fooAObjects):
                self?.fooAObjects = fooAObjects
            case .completed:

                self?.fooTableView.reloadData()

                loadingView?.hide()

            case .error(let error):
                loadingView?.hide()

                self?.handleError(error)

                self?.showNoFooView()
            }
        }
        .addDisposableTo(disposeBag)

The invocation: self?.fooTableView.reloadData() causes to the table view to attempt to display the foo objects retrieved and where it goes BOOM.

Body:
Try something like this. It may have some mistakes.

class SomeTableViewController: UITableViewController {

var fooA  : FooA?

override func viewDidLoad() {
        super.viewDidLoad()
        let realm = try! Realm()
        if let aFooA = realm.objects(FooA.self).first{
            fooA = aFooA
            self.reloadTableView()
        }
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if let _ = fooA{
        return fooA!.fooBList.count
    }

    return 0
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "SomeCell", for: indexPath)
    // Configure the cell...
    let fooB = fooA!.fooBList[indexPath.row]
    cell.titleLabel.text = fooB.someBValue

    return cell
}

}


问:
Column normalization behaves differently in higher dimensions
I am trying to subtract the minimum value of an ndarray for an arbitrary dimension. It seems to work with 3 dimensions, but not 4

3 Dimensional Case:

```<code>x1 = np.arange(27.0).reshape((3, 3, 3))
# x1 is (3,3,3)
x2 = x1.min(axis=(1,2))
# x2 is (3,)
(x1 - x2).shape
#Output: (3, 3, 3)

(x1 - x2).shape == x1.shape
#As expected: True
</code>```

4 Dimnesional Case:

```<code>mat1 = np.random.rand(10,5,2,1)
# mat1 is (10,5,2,1)
mat2 = mat1.min(axis = (1,2,3))
# mat2 is (10,)
(mat1 - mat2).shape == mat1.shape
# Should be True, but
#Output: False
</code>```

答:
Your first example is misleading because all dimensions are the same size.  That hides the kind of error that you see in the 2nd. Examples with different size dimensions are better at catching errors:

```<code>In [530]: x1 = np.arange(2*3*4).reshape(2,3,4)
In [531]: x2 = x1.min(axis=(1,2))
In [532]: x2.shape
Out[532]: (2,)
In [533]: x1-x2
...
ValueError: operands could not be broadcast together with shapes (2,3,4) (2,)
</code>```

Compare that with a case where I tell it to keep dimensions:

```<code>In [534]: x2 = x1.min(axis=(1,2),keepdims=True)
In [535]: x2.shape
Out[535]: (2, 1, 1)
In [536]: x1-x2
Out[536]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

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

The basic rule of broadcasting: a (2,) array can expand to (1,1,2) if needed, but not to (2,1,1).

But why doesn't the 2nd case produce an error?

```<code>In [539]: mat1.shape
Out[539]: (10, 5, 2, 1)
In [540]: mat2.shape
Out[540]: (10,)
In [541]: (mat1-mat2).shape
Out[541]: (10, 5, 2, 10)
</code>```

It's that trailing size 1, which can broadcast with the (10,):

```<code>(10,5,2,1) (10,) => (10,5,2,1)(1,1,1,10) => (10,5,2,10)
</code>```

It's as though you'd added a newaxis to a 3d array:

```<code>mat1 = np.random.rand(10,5,2)
mat1[...,None] - mat2
</code>```

Body:
I am trying to subtract the minimum value of an ndarray for an arbitrary dimension. It seems to work with 3 dimensions, but not 4

3 Dimensional Case:

x1 = np.arange(27.0).reshape((3, 3, 3))
# x1 is (3,3,3)
x2 = x1.min(axis=(1,2))
# x2 is (3,)
(x1 - x2).shape
#Output: (3, 3, 3)

(x1 - x2).shape == x1.shape
#As expected: True

4 Dimnesional Case:

mat1 = np.random.rand(10,5,2,1)
# mat1 is (10,5,2,1)
mat2 = mat1.min(axis = (1,2,3))
# mat2 is (10,)
(mat1 - mat2).shape == mat1.shape
# Should be True, but
#Output: False

Body:
Your first example is misleading because all dimensions are the same size.  That hides the kind of error that you see in the 2nd. Examples with different size dimensions are better at catching errors:

In [530]: x1 = np.arange(2*3*4).reshape(2,3,4)
In [531]: x2 = x1.min(axis=(1,2))
In [532]: x2.shape
Out[532]: (2,)
In [533]: x1-x2
...
ValueError: operands could not be broadcast together with shapes (2,3,4) (2,)

Compare that with a case where I tell it to keep dimensions:

In [534]: x2 = x1.min(axis=(1,2),keepdims=True)
In [535]: x2.shape
Out[535]: (2, 1, 1)
In [536]: x1-x2
Out[536]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]]])

The basic rule of broadcasting: a (2,) array can expand to (1,1,2) if needed, but not to (2,1,1).

But why doesn't the 2nd case produce an error?

In [539]: mat1.shape
Out[539]: (10, 5, 2, 1)
In [540]: mat2.shape
Out[540]: (10,)
In [541]: (mat1-mat2).shape
Out[541]: (10, 5, 2, 10)

It's that trailing size 1, which can broadcast with the (10,):

(10,5,2,1) (10,) => (10,5,2,1)(1,1,1,10) => (10,5,2,10)

It's as though you'd added a newaxis to a 3d array:

mat1 = np.random.rand(10,5,2)
mat1[...,None] - mat2


问:
ChartJS with ajax is not working
I am creating a chart with (chartjs.org). I have a database and in my php document I retrieved the data into a json file:

```<code>print json_encode($result->fetch_all());
</code>```

and the result is this, which is fine:

```<code>[["1.1","59.7701"],["1.2","66.6667"],["1.3","65.5172"],["1.4","65.5172"],  ["1.5","56.3218"],["1.6","58.6207"],["1.7","58.1395"],["1.8","58.6207"],["1.9","61.6279"],["2.1","65.1163"],["2.2","70.1149"],["2.3","57.4713"],["2.4","54.0230"],["2.5","60.9195"],["3.1","52.3256"],["3.2","60.4651"],["3.3","69.7674"],["3.4","52.3256"],["4.1","52.3256"]]
</code>```

The problem is when I am trying to get these:

```<code>    $(function () {
  $('#go').click(function(){
    $.ajax({url: '../output.php', data: {MOD_CODE: $('#MOD_CODE').val()}, dataType: 'json',
      success: function(d){
        console.log(d);
        var data = { labels:[], datasets:[{label:$('#MOD_CODE').val() + ' results', data:[], }]};
        for (var i = 0; i < d.length; i++) {
          data.labels.push(d[i][0]);
          data.datasets[0].data.push(parseFloat(d[i][1]));
        }
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
          type: 'radar',
          data: data,
          options:{
            responsive:false,
            scale:{ticks: {beginAtZero: true}}}});//.for
      }//.success
    }); //.ajax
  })//.click
});//.function
</code>```

This is the folder structure, maybe I putting the path wrong.

```<code>/folder
-js/chart.js
-doc.php
</code>```

It is strange that is not passing through the "success" of the ajax. I cannot see the console.log(d);

答:
The problem was, that the php file generate with this code:

```<code>print json_encode($result->fetch_all());
</code>```

It was not plain PHP, it contained HTML and content in general.

In order to generate a json doc it must be plain PHP, and the call in jquery then can collect the data.

For that reason when I check the error request, it was giving me the whole HTML page.

Title: ChartJS with ajax is not working

Body:
I am creating a chart with (chartjs.org). I have a database and in my php document I retrieved the data into a json file:

print json_encode($result->fetch_all());

and the result is this, which is fine:

[["1.1","59.7701"],["1.2","66.6667"],["1.3","65.5172"],["1.4","65.5172"],  ["1.5","56.3218"],["1.6","58.6207"],["1.7","58.1395"],["1.8","58.6207"],["1.9","61.6279"],["2.1","65.1163"],["2.2","70.1149"],["2.3","57.4713"],["2.4","54.0230"],["2.5","60.9195"],["3.1","52.3256"],["3.2","60.4651"],["3.3","69.7674"],["3.4","52.3256"],["4.1","52.3256"]]

The problem is when I am trying to get these:

    $(function () {
  $('#go').click(function(){
    $.ajax({url: '../output.php', data: {MOD_CODE: $('#MOD_CODE').val()}, dataType: 'json',
      success: function(d){
        console.log(d);
        var data = { labels:[], datasets:[{label:$('#MOD_CODE').val() + ' results', data:[], }]};
        for (var i = 0; i < d.length; i++) {
          data.labels.push(d[i][0]);
          data.datasets[0].data.push(parseFloat(d[i][1]));
        }
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
          type: 'radar',
          data: data,
          options:{
            responsive:false,
            scale:{ticks: {beginAtZero: true}}}});//.for
      }//.success
    }); //.ajax
  })//.click
});//.function

This is the folder structure, maybe I putting the path wrong.

/folder
-js/chart.js
-doc.php

It is strange that is not passing through the "success" of the ajax. I cannot see the console.log(d);

Body:
The problem was, that the php file generate with this code:

print json_encode($result->fetch_all());

It was not plain PHP, it contained HTML and content in general.

In order to generate a json doc it must be plain PHP, and the call in jquery then can collect the data.

For that reason when I check the error request, it was giving me the whole HTML page.


问:
Must logins be a https page
Several security experts have said in the past that the login page should be on ssl https. So what if my login is a block that's displayed on all pages. Does that mean that my entire website has to be https?

I read it's possible to put the form on http but post it to https, but I read someone saying that it can be exploited with a man in the middle attack. Can someone confirm this? I have a 100 point bounty for someone who can confirm this (and help me with a practical answer how to securely solve this). My login form is on every page, do I need to make the whole website on https? Please feel free to question anything I said here. They're only things I read but don't have experience with and didn't try it myself.

Edit: to those who asked, when I was posting the question, I tried setting the bounty but the system wouldn't let me. I checked the FAQ and saw that bounty can be posted after 2 days from posting the question. That's why you see no bounty yet. But I will not select an answer until I set a bounty in 2 days. Sorry for any confusion.

答:
Simple answer "Yes" your login page and rest of the websites should be served over SSL

And here is why from SSL Implementation FAQ:

Can I put my Login form to HTTP and target my form to HTTPS?

Is it secure switch back to HTTP after login over HTTPS?

Title: Must logins be a https page


问:
Changing array element?
My aim is there is an array like this int arrMarks[] = {10,-15,25,102,30} and I need to make it equal to zero when an element is below zero or higher than 100. Then these elements should be in the last place of the array and the other one's position removed one place. So how can I do this without using any package or shortages?</p>

```<code>public void validateMarks(int [] array){
        int [] array1 = new int[5];

        for(int i = 0; i<array.length; i++){
            if(array[i] < 0 || array[i] > 100){
                int f= array1.length-1;

                array1[f] = array[i];
                array1[f] = 0;
                f--;
            }

            else if(array[i] > 0 || array[i] < 100){

                array1[i] = array[i];

            }
            System.out.println(array1[i]);
        }
    }
</code>```

答:
you could use the method swap.</p>

```<code>public void swap(int i, int j, int[] arr) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
</code>```

Title: Changing array element?

Body:
My aim is there is an array like this int arrMarks[] = {10,-15,25,102,30} and I need to make it equal to zero when an element is below zero or higher than 100. Then these elements should be in the last place of the array and the other one's position removed one place. So how can I do this without using any package or shortages?

public void validateMarks(int [] array){
        int [] array1 = new int[5];

        for(int i = 0; i<array.length; i++){
            if(array[i] < 0 || array[i] > 100){
                int f= array1.length-1;

                array1[f] = array[i];
                array1[f] = 0;
                f--;
            }

            else if(array[i] > 0 || array[i] < 100){

                array1[i] = array[i];

            }
            System.out.println(array1[i]);
        }
    }

Body:
you could use the method swap.

public void swap(int i, int j, int[] arr) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;


问:
Bootstrap Equal Column Heights
I am trying to make my Bootstrap column's all the same height. Right now if one column has more content than another the columns float around and things don't look "square".

Here is a fiddle example of what I mean:

https://jsfiddle.net/jjq9gygr/

I have tried the display: flex approach but since my html does not have a new .row container for every 3 col-xs-4 columns, all the columns go on the same row instead of wrapping to the next line after 3 columns. I hope that makes sense.

If there is a way to keep the HTML as is and get the result I am after that would be great. Any ideas or recommendations are helpful.

```<code><div class="container">
<div class="row">
    <div class="col-xs-4 red">
  <h3>
  Column 1
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 pink">
<h3>
  Column 2
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 yellow">
  <h3>
  Column 3
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 orange">
  <h3>
  Column 4
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 blue">
  <h3>
  Column 5
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 green">
  <h3>
  Column 6
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 navy">
  <h3>
  Column 7
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
</div>
</code>```

答:
You can just use JQ plugin jquery.matchHeight.js that works also on other html frameworks and it is simply to use:

https://github.com/liabru/jquery-match-height

You can use via JS:

```<code>$('.row .col-xs-4').matchHeight();
</code>```

Or use data:

```<code><div class="col-xs-4 red" data-mh="my-group">Red</div>
<div class="col-xs-4 blue" data-mh="my-group">Blue</div>
</code>```

Title: Bootstrap Equal Column Heights

Body:
I am trying to make my Bootstrap column's all the same height. Right now if one column has more content than another the columns float around and things don't look "square".

Here is a fiddle example of what I mean:

https://jsfiddle.net/jjq9gygr/

I have tried the display: flex approach but since my html does not have a new .row container for every 3 col-xs-4 columns, all the columns go on the same row instead of wrapping to the next line after 3 columns. I hope that makes sense.

If there is a way to keep the HTML as is and get the result I am after that would be great. Any ideas or recommendations are helpful.

  Column 1

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 2

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 3

Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 4

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 5

Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 6

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 7

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

Body:
You can just use JQ plugin jquery.matchHeight.js that works also on other html frameworks and it is simply to use:

https://github.com/liabru/jquery-match-height

You can use via JS:

$('.row .col-xs-4').matchHeight();

Or use data:

<div class="col-xs-4 red" data-mh="my-group">Red</div>
<div class="col-xs-4 blue" data-mh="my-group">Blue</div>


问:
Python palindrome code doesn't return anything
Why?
It returns:

```<code>  if word[0] != word[-1]:
IndexError: list index out of range
</code>```

If I change "print "Palindrome"" to "return True" and "return False" it returns nothing at all.

```<code>import sys

exstring = "f"
data = list(exstring)

def palindrome(word):
    if len(word) < 2:
        print "Palindrome"
    if word[0] != word[-1]:
        print "Not Palindrome"
    return palindrome(word[1:-1])

palindrome(data)
</code>```

答:
First, you need an elif in there like Hypnic Jerk mentioned. Second you need to return after your prints.

Working code:

```<code>import sys

exstring = "radar"
data = list(exstring)

def palindrome(word):
    if len(word) < 2:
        print "Palindrome"
        return True
    elif word[0] != word[-1]:
        print "Not Palindrome"
        return False
    return palindrome(word[1:-1])

palindrome(data)
</code>```

Body:
Why?
It returns:

  if word[0] != word[-1]:
IndexError: list index out of range

If I change "print "Palindrome"" to "return True" and "return False" it returns nothing at all.

import sys

exstring = "f"
data = list(exstring)

def palindrome(word):
    if len(word) < 2:
        print "Palindrome"
    if word[0] != word[-1]:
        print "Not Palindrome"
    return palindrome(word[1:-1])

palindrome(data)

Body:
First, you need an elif in there like Hypnic Jerk mentioned. Second you need to return after your prints.

Working code:

import sys

exstring = "radar"
data = list(exstring)

def palindrome(word):
    if len(word) < 2:
        print "Palindrome"
        return True
    elif word[0] != word[-1]:
        print "Not Palindrome"
        return False
    return palindrome(word[1:-1])

palindrome(data)


问:
How to find out in which Wiki software a website is built on?
Some websites have a small logo or something at the bottom of their web page indicating that for example, that website is powered by MediaWiki.

How to find out what Wiki software does a website use in case of the owner removing the "Powered by ..." logo?

答: Find out, which technologies a particular website is using with w3techs.com</p>