text:
Q: How to change role hierarchy storage in Symfony2? In my project I need to store role hierarchy in database and create new roles dynamically.
In Symfony2 role hierarchy is stored in security.yml by default.
What have I found:
There is a service security.role_hierarchy (Symfony\Component\Security\Core\Role\RoleHierarchy);
This service receives a roles array in constructor:
public function __construct(array $hierarchy)
{
    $this->hierarchy = $hierarchy;

    $this->buildRoleMap();
}

and the $hierarchy property is private.
This argument comes in constructor from \Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension::createRoleHierarchy()
which uses roles from config, as I understood:
$container->setParameter('security.role_hierarchy.roles', $config['role_hierarchy']);
It seems me that the best way is to compile an array of roles from database and set it as an argument for the service. But I haven't yet understood how to do it.
The second way I see is to define my own RoleHierarchy class inherited from the base one. But since in the base RoleHierarchy class the $hierarchy property is defined as private, than I would have to redefine all the functions from the base RoleHierarchy class. But I don't think it is a good OOP and Symfony way...

A: The solution was simple.
First I created a Role entity.
class Role
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $name
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="Role")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
     **/
    private $parent;

    ...
}

after that created a RoleHierarchy service, extended from the Symfony native one. I inherited the constructor, added an EntityManager there and provided an original constructor with a new roles array instead of the old one:
class RoleHierarchy extends Symfony\Component\Security\Core\Role\RoleHierarchy
{
    private $em;

    /**
     * @param array $hierarchy
     */
    public function __construct(array $hierarchy, EntityManager $em)
    {
        $this->em = $em;
        parent::__construct($this->buildRolesTree());
    }

    /**
     * Here we build an array with roles. It looks like a two-levelled tree - just
     * like original Symfony roles are stored in security.yml
     * @return array
     */
    private function buildRolesTree()
    {
        $hierarchy = array();
        $roles = $this->em->createQuery('select r from UserBundle:Role r')->execute();
        foreach ($roles as $role) {
            /** @var $role Role */
            if ($role->getParent()) {
                if (!isset($hierarchy[$role->getParent()->getName()])) {
                    $hierarchy[$role->getParent()->getName()] = array();
                }
                $hierarchy[$role->getParent()->getName()][] = $role->getName();
            } else {
                if (!isset($hierarchy[$role->getName()])) {
                    $hierarchy[$role->getName()] = array();
                }
            }
        }
        return $hierarchy;
    }
}

... and redefined it as a service:
<services>
    <service id="security.role_hierarchy" class="Acme\UserBundle\Security\Role\RoleHierarchy" public="false">
        <argument>%security.role_hierarchy.roles%</argument>
        <argument type="service" id="doctrine.orm.default_entity_manager"/>
    </service>
</services>

That's all.
Maybe, there is something unnecessary in my code. Maybe it is possible to write better. But I think, that main idea is evident now.

A: I developped a bundle.
You can find it at https://github.com/Spomky-Labs/RoleHierarchyBundle

A: My solution was inspired by the solution provided by zls. His solution worked perfectly for me, but the one-to-many relation between the roles meant having one huge role tree, which would become hard to maintain. Also, a problem might occur if two different roles wanted to inherit one same role (as there could only be one parent). That's why I decided to create a many-to-many solution. Instead of having only the parent in the role class, I have first put this in the role class:
/**
 * @ORM\ManyToMany(targetEntity="Role")
 * @ORM\JoinTable(name="role_permission",
 *      joinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="permission_id", referencedColumnName="id")}
 *      )
 */
protected $children;

After that I rewrote the buildRolesTree function like so:
private function buildRolesTree()
{
    $hierarchy = array();
    $roles = $this->em->createQuery('select r, p from AltGrBaseBundle:Role r JOIN r.children p')->execute();

    foreach ($roles as $role)
    {
        /* @var $role Role */
        if (count($role->getChildren()) > 0)
        {
            $roleChildren = array();

            foreach ($role->getChildren() as $child)
            {
                /* @var $child Role */
                $roleChildren[] = $child->getRole();
            }

            $hierarchy[$role->getRole()] = $roleChildren;
        }
    }

    return $hierarchy;
}

The result is the ability to create several easily maintained trees. For instance, you can have a tree of roles defining the ROLE_SUPERADMIN role and entirely separate tree defining a ROLE_ADMIN role with several roles shared between them. Although circular connections should be avoided (roles should be laid out as trees, without any circular connections between them), there should be no problems if it actually happens. I haven't tested this, but going through the buildRoleMap code, it is obvious it dumps any duplicates. This should also mean it won't get stuck in endless loops if the circular connection occurs, but this definitely needs more testing.
I hope this proves helpful to someone.

A: I had do the same thing like zIs (to store the RoleHierarchy in the database) but i cannot load the complete role hierarchy inside the Constructor like zIs did, because i had to load a custom doctrine filter inside the kernel.request event. The Constructor will be called before the kernel.request so it was no option for me.
Therefore I checked the security component and found out that Symfony calls a custom Voter to check the roleHierarchy according to the users role:
namespace Symfony\Component\Security\Core\Authorization\Voter;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;

/**
 * RoleHierarchyVoter uses a RoleHierarchy to determine the roles granted to
 * the user before voting.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class RoleHierarchyVoter extends RoleVoter
{
    private $roleHierarchy;

    public function __construct(RoleHierarchyInterface $roleHierarchy, $prefix = 'ROLE_')
    {
        $this->roleHierarchy = $roleHierarchy;

        parent::__construct($prefix);
    }

    /**
     * {@inheritdoc}
     */
    protected function extractRoles(TokenInterface $token)
    {
        return $this->roleHierarchy->getReachableRoles($token->getRoles());
    }
}

The getReachableRoles Method returns all roles the user can be. For example:
           ROLE_ADMIN
         /             \
     ROLE_SUPERVISIOR  ROLE_BLA
        |               |
     ROLE_BRANCH       ROLE_BLA2
       |
     ROLE_EMP

or in Yaml:
ROLE_ADMIN:       [ ROLE_SUPERVISIOR, ROLE_BLA ]
ROLE_SUPERVISIOR: [ ROLE_BRANCH ]
ROLE_BLA:         [ ROLE_BLA2 ]

If the user has the ROLE_SUPERVISOR role assigned the Method returns the roles ROLE_SUPERVISOR, ROLE_BRANCH and ROLE_EMP (Role-Objects or Classes, which implementing RoleInterface)
Furthermore this custom voter will be disabled if there is no RoleHierarchy defined in the security.yaml
private function createRoleHierarchy($config, ContainerBuilder $container)
    {
        if (!isset($config['role_hierarchy'])) {
            $container->removeDefinition('security.access.role_hierarchy_voter');

            return;
        }

        $container->setParameter('security.role_hierarchy.roles', $config['role_hierarchy']);
        $container->removeDefinition('security.access.simple_role_voter');
    }

To solve my issue I created my own custom Voter and extended the RoleVoter-Class, too:
use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Acme\Foundation\UserBundle\Entity\Group;
use Doctrine\ORM\EntityManager;

class RoleHierarchyVoter extends RoleVoter {

    private $em;

    public function __construct(EntityManager $em, $prefix = 'ROLE_') {

        $this->em = $em;

        parent::__construct($prefix);
    }

    /**
     * {@inheritdoc}
     */
    protected function extractRoles(TokenInterface $token) {

        $group = $token->getUser()->getGroup();

        return $this->getReachableRoles($group);
    }

    public function getReachableRoles(Group $group, &$groups = array()) {

        $groups[] = $group;

        $children = $this->em->getRepository('AcmeFoundationUserBundle:Group')->createQueryBuilder('g')
                        ->where('g.parent = :group')
                        ->setParameter('group', $group->getId())
                        ->getQuery()
                        ->getResult();

        foreach($children as $child) {
            $this->getReachableRoles($child, $groups);
        }

        return $groups;
    }
}

One Note: My Setup is similar to zls ones. My Definition for the role (in my case I called it Group):
Acme\Foundation\UserBundle\Entity\Group:
    type: entity
    table: sec_groups
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    fields:
        name:
            type: string
            length: 50
        role:
            type: string
            length: 20
    manyToOne:
        parent:
            targetEntity: Group

And the userdefinition:
Acme\Foundation\UserBundle\Entity\User:
    type: entity
    table: sec_users
    repositoryClass: Acme\Foundation\UserBundle\Entity\UserRepository
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    fields:
        username:
            type: string
            length: 30
        salt:
            type: string
            length: 32
        password:
            type: string
            length: 100
        isActive:
            type: boolean
            column: is_active
    manyToOne:
        group:
            targetEntity: Group
            joinColumn:
                name: group_id
                referencedColumnName: id
                nullable: false

Maybe this helps someone.

A: Since role hierarchy don't change often, this a quick class to cache to memcached.
<?php

namespace .....;

use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Lsw\MemcacheBundle\Cache\MemcacheInterface;

/**
 * RoleHierarchy defines a role hierarchy.
 */
class RoleHierarchy implements RoleHierarchyInterface
{
    /**
     *
     * @var MemcacheInterface
     */
    private $memcache;

    /**
     *
     * @var array
     */
    private $hierarchy;

    /**
     *
     * @var array
     */
    protected $map;

    /**
     * Constructor.
     *
     * @param array $hierarchy An array defining the hierarchy
     */
    public function __construct(array $hierarchy, MemcacheInterface $memcache)
    {
        $this->hierarchy = $hierarchy;

        $roleMap = $memcache->get('roleMap');

        if ($roleMap) {
            $this->map = unserialize($roleMap);
        } else {
            $this->buildRoleMap();
            // cache to memcache
            $memcache->set('roleMap', serialize($this->map));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getReachableRoles(array $roles)
    {
        $reachableRoles = $roles;
        foreach ($roles as $role) {
            if (!isset($this->map[$role->getRole()])) {
                continue;
            }

            foreach ($this->map[$role->getRole()] as $r) {
                $reachableRoles[] = new Role($r);
            }
        }

        return $reachableRoles;
    }

    protected function buildRoleMap()
    {
        $this->map = array();
        foreach ($this->hierarchy as $main => $roles) {
            $this->map[$main] = $roles;
            $visited = array();
            $additionalRoles = $roles;
            while ($role = array_shift($additionalRoles)) {
                if (!isset($this->hierarchy[$role])) {
                    continue;
                }

                $visited[] = $role;
                $this->map[$main] = array_unique(array_merge($this->map[$main], $this->hierarchy[$role]));
                $additionalRoles = array_merge($additionalRoles, array_diff($this->hierarchy[$role], $visited));
            }
        }
    }
}

A: I hope this will help you.
function getRoles()
{

  //  return array(1=>'ROLE_ADMIN',2=>'ROLE_USER');
   return array(new UserRole($this));
}

You can get a good idea from,
 Where to define security roles?
http://php-and-symfony.matthiasnoback.nl/        ( 2012 July 28 )


text:
Q: "Stay hungry" or "Keep hungry"? If I had two choices, either to "Eat something" or "Stay/Keep hungry", when food is offered to me when I was in a state of hunger.
I want the phrase to be in the same format as "Eat something", I mean two words and in an order(verb) form.
I found out that "Stay hungry" is an idiom which means:

To remain determined, competitive, motivated, and active in one's
  hopes, ambitions, or goals; to keep oneself from becoming complacent
  or self-satisfied with less than one might potentially achieve.

Also, I don't find that "Keep hungry" makes a good fit.
So, what should I say?

A:
Eat something or stay hungry

is the natural way to utter the thought desired in the context specified.
Yes, there is an idiom that "Stay hungry" means "remain determined," etc., but that idiom has not replaced the primary meaning of the word "hungry," which is to "be conscious of not having eaten enough recently." No native speaker would interpret the words above as

Eat some food or else continue being so determined.

The word "eat" would indicate unambiguously that the word "hungry" is to be interpreted in its literal sense rather than a figurative sense.

A: Another option would be remain: "eat something or remain hungry."

A: I suppose your "idiomatic" meaning of stay hungry comes from this page: https://idioms.thefreedictionary.com/hungry. I think this is not really an idiom but rather a logical construction from one of the alternative meanings of hungry listed at the bottom of the same page: "ambitious." In other words, in order to tell someone not to lose their sense of ambition, one could say "stay ambitious" or "stay hungry."
I would further consider this meaning of "hungry" to be a metaphor, that is, it represents a metaphorical hunger for success rather than a hunger for food.
In fact, just about any such phrase using the word "hungry" could have the same metaphorical meaning: in a context where "stay hungry" means "stay ambitious," telling a person to "remain hungry" or "keep yourself hungry" would have the same meaning.
In the context where the alternative is to eat food, however, you could use any of the following phrases to tell someone to remain in a state of hunger:

*

*stay hungry.

*remain hungry.

*be hungry.

The phrase keep hungry does not ring true to my ear. The word keep has various idiomatic uses, such as "keep calm", that have the form keep + (adjective), but this does not seem to be one of them.
The phrase go hungry is another idiom. It has a connotation of involuntary hunger:
from https://www.collinsdictionary.com/us/dictionary/english/go-hungry,

If people go hungry, they do not have enough food to eat.

This does not seem to apply when food is available but one chooses not to eat it.
The definition of the phrase varies from source to source, however:
according to https://www.merriam-webster.com/dictionary/go%20hungry, going hungry is a chronic condition,
but https://idioms.thefreedictionary.com/go+hungry defines it as missing a single meal.
On the other hand, if the circumstances are that food has been set out to be eaten,
but it will be taken away soon, I would understand the phrase

eat something or go hungry

to mean if you do not eat food now, while it is available, you will suffer from not having enough food to eat in the near future.

A: I'm not a native speaker, but I'd rather use "stay hungry". I think the proper usage of keep might be when you leave something in a state, so technically (I guess) you can say like "keep myself hungry", but I've never seen any usage that uses the verb keep to leave the speaker itself in a state, rather leave another object in it.

A: As a native English  speaker, the phrase that comes to mind is "go hungry":
"If you refuse to eat anything, you'll go hungry."

redpajama_set_name: RedPajamaStackExchange


text:
Q: Logical combinations in quanteda dictionaries I'm using the quanteda dictionary lookup. I'll try to formulate entries where i can lookup logical combinations of words.
For example:
Teddybear = (fluffy AND adorable AND soft)

Is this possible? I only found a solution yet to test for phrases like (Teddybear = (soft fluffy adorable)). But then it has to be the exact phrase match in the text. But how can I get results neglecting the order of the words?

A: This is not currently something that is directly possible in quanteda (v1.2.0).  However, there are workarounds in which you create dictionary sequences that are permutations of your desired sequence.  Here is one such solution.
First, I will create some example texts.  Note that the sequences are separated by either "," or "and" in some cases.  Also, the third text has just two of your phrases rather than three.  (More on that in a moment.)
txt <- c("The toy was fluffy, adorable and soft, he said.",
         "The soft, adorable, fluffy toy was on the floor.",
         "The fluffy, adorable toy was shaped like a bear.")

Now, let's generate a pair of functions to generate permutation sequences and subsequences from a vector.  These will use some functions from the combinat package.  The first is an inner function to generate permutations, the second is the main calling function that can generate full-length permutations or any subsample down to subsample_limit.  (To use these more generally, of course, I'd add error checking, but I've skipped that for this example.)
genperms <- function(vec) {
    combs <- combinat::permn(vec)
    sapply(combs, paste, collapse = " ")
}

# vec any vector
# subsample_limit integer from 1 to length(vec), subsamples from
# which to return permutations; default is no subsamples
permutefn <- function(vec, subsample_limit = length(vec)) {
    ret <- character()
    for (i in length(vec):subsample_limit) {
        ret <- c(ret,
                 unlist(lapply(combinat::combn(vec, i, simplify = FALSE),
                               genperms)))
    }
    ret
}

To demonstrate how these work:
fas <- c("fluffy", "adorable", "soft")
permutefn(fas)
# [1] "fluffy adorable soft" "fluffy soft adorable" "soft fluffy adorable"
# [4] "soft adorable fluffy" "adorable soft fluffy" "adorable fluffy soft"

# and with subsampling:
permutefn(fas, 2)
#  [1] "fluffy adorable soft" "fluffy soft adorable" "soft fluffy adorable"
#  [4] "soft adorable fluffy" "adorable soft fluffy" "adorable fluffy soft"
#  [7] "fluffy adorable"      "adorable fluffy"      "fluffy soft"
# [10] "soft fluffy"          "adorable soft"        "soft adorable"

Now apply these to the texts using tokens_lookup().  I've avoided the punctuation issue by setting remove_punct = TRUE.  To show the original tokens not replaced, I have also uses exclusive = FALSE.
tokens(txt, remove_punct = TRUE) %>%
    tokens_lookup(dictionary = dictionary(list(teddybear = permutefn(fas))),
                  exclusive = FALSE)
# tokens from 3 documents.
# text1 :
# [1] "The"      "toy"      "was"      "fluffy"   "adorable" "and"      "soft"
# [8] "he"       "said"
#
# text2 :
# [1] "The"      "TEDDYBEAR" "toy"       "was"       "on"        "the"
# [8] "floor"
#
# text3 :
# [1] "The"      "fluffy"   "adorable" "toy"      "was"      "shaped"   "like"
# [8] "a"        "bear"

The first case here was not caught, because the second and third elements were separated by "and".  We can remove that using tokens_remove(), and then get the match:
tokens(txt, remove_punct = TRUE) %>%
    tokens_remove("and") %>%
    tokens_lookup(dictionary = dictionary(list(teddybear = permutefn(fas))),
                  exclusive = FALSE)
# tokens from 3 documents.
# text1 :
# [1] "The"       "toy"       "was"       "TEDDYBEAR" "he"        "said"
#
# text2 :
# [1] "The"       "TEDDYBEAR" "toy"       "was"       "on"        "the"       "floor"
#
# text3 :
# [1] "The"      "fluffy"   "adorable" "toy"      "was"      "shaped"   "like"
# [8] "a"        "bear"

Finally, to match the third text in which just two of the three dictionary elements exist, we can pass 2 as the subsample_limit argument:
tokens(txt, remove_punct = TRUE) %>%
    tokens_remove("and") %>%
    tokens_lookup(dictionary = dictionary(list(teddybear = permutefn(fas, 2))),
                  exclusive = FALSE)
# tokens from 3 documents.
# text1 :
# [1] "The"       "toy"       "was"       "TEDDYBEAR" "he"        "said"
#
# text2 :
# [1] "The"       "TEDDYBEAR" "toy"       "was"       "on"        "the"       "floor"
#
# text3 :
# [1] "The"       "TEDDYBEAR" "toy"       "was"       "shaped"    "like"      "a"
# [8] "bear"
#

A: If you want to know which documents have all the words, just do:
require(quanteda)

txt <- c("The toy was fluffy, adorable and soft, he said.",
         "The soft, adorable, fluffy toy was on the floor.",
         "The fluffy, adorable toy was shaped like a bear.")
dict <- dictionary(list(teddybear = list(c1 = "fluffy", c2 = "adorable", c3 = "soft")))

mt <- dfm_lookup(dfm(txt), dictionary = dict["teddybear"], levels = 2)

cbind(mt, "teddybear" = as.numeric(rowSums(mt > 0) == length(dict[["teddybear"]])))

# Document-feature matrix of: 3 documents, 4 features (16.7% sparse).
# 3 x 4 sparse Matrix of class "dfm"
# features
# docs    c1 c2 c3 teddybear
# text1  1  1  1         1
# text2  1  1  1         1
# text3  1  1  0         0


text:
Q: I want to set `nodeadkeys`, but where? I want to configure my keyboard to write characters like ^ or ~ with just one click. A friend told me, I have to set nodeadkeys somewhere, but not the place. So, where to change this configuration (preferably manually in a .conf file).
What I already tried:
The only seemingly meaningful documentation I found about setting nodeadkeys, was in this German website. This page describes different ways to get through the GUI menus, but all of them don't work on my freshly setup Ubuntu system (with gnome). Maybe it was written for older versions. It also describes how to set it manually in the xorg.conf, which should be found in /etc/X11/, which is also not the case. I looked for an xorg.conf all over the system (sudo find / -name "xorg.conf") but also didn't find anything. No result yet.

A: Every keyboard layout that uses dead keys by default has a corresponding (eliminate dead keys)-version. To change keyboard layout, go to System Settings > Keyboard Layout and press the +-button to add a new layout.
If, for example, you want a German layout without dead keys, search for "german" in the search field. You should find the option "German (eliminate dead keys)".


text:
Q: Grafana Loki multi cluster setup | Federation we have multiple cluster where we use Loki as logging service. now we are thinking of implement central logging service where we can see logs from all the cluster.
straight forward solution is deploy Loki stack and start pushing logs from all remote cluster. but this will incur data transfer cost.
we are thinking a more optimised solution like each cluster will have their own loki instance and central loki instance will connect to all the cluster. when ever they want to see logs user can login to central one and then can access logs.
Any thoughts or suggestion on this?


text:
Q: Expandable ListView How  we can create Expandable ListView with group icon on Right.have any one implement it...

A: <ExpandableListView android:id="@+id/Exlist"
    android:childDivider="#00000000" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:groupIndicator="transparent Image"
    android:scrollbars="none" android:listSelector="#00000000"
     android:cacheColorHint="#00000000"
    android:layout_marginBottom="10dip" />

Above code "android:groupIndicator="transparent image"" becuase remove left side group indicator icon.
Now used below XML for Group Indicator file.
group.xml
  <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RelativeLayout android:id="@+id/rlheaderName"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:background="@drawable/main_down">
    <TextView android:id="@+id/headerName"
        android:layout_marginLeft="5dip" android:layout_centerVertical="true"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:textColor="#6e6e6e" android:textStyle="bold"></TextView>
    <TextView android:id="@+id/headerCount"
        android:layout_marginLeft="10dip" android:layout_centerVertical="true"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:textColor="#6e6e6e" android:layout_toRightOf="@+id/headerName"></TextView>
</RelativeLayout>
  </LinearLayout>

Above file "android:background="@drawable/main_down"" main_down used as arrow in rightside.
so you problem solved.


text:
Q: Fixing DB Inconsistencies - ID Fields I've inherited a (Microsoft?) SQL database that wasn't very pristine in its original state. There are still some very strange things in it that I'm trying to fix - one of them is inconsistent ID entries.
In the accounts table, each entry has a number called accountID, which is referenced in several other tables (notes, equipment, etc. ). The problem is that the numbers (for some random reason) - range from about -100000 to +2000000 when there are about only 7000 entries.
Is there any good way to re-number them while changing corresponding numbers in the other tables? At my disposal I also have ColdFusion, so any thing that works with SQL and/or that I'll accept.

A: For surrogate keys, they are meant to be meaningless, so unless you actually had a database integrity issue (like there were no foreign key contraints properly defined) or your identity was approaching the maximum for its datatype, I would leave them alone and go after some other low hanging fruit that would have more impact.

A: In this instance, it sounds like "why" is a better question than "how". The OP notes that there is a strange problem that needs to be fixed but doesn't say why it is a problem. Is it causing problems? What positive impact would changing these numbers have? Unless you originally programmed the system and understand precisely why the number is in its current state, you are taking quite a risky making changes like this.

A: I would talk to an accountant (or at least your financial people) before messing in anyway with the numbers in the accounts tables if this is a financial app. The Table of accounts is very critical to how finances are reported. These IDs may have meaning you don't understand. No one puts in a negative id unless they had a reason. I would under no circumstances change that unless I understood why it was negative to begin with. You could truly screw up your tax reporting or some other thing by making an uneeded change.

A: You could probably disable the foreign key relationships (if you're able to take it offline temporarily) and then update the primary keys using a script. I've used this update script before to change values, and you could pretty easily wrap this code in a cursor to go through the key values in question, one by one, and update the arbitrary value to an incrementing value you're keeping track of.
Check out the script here: http://vyaskn.tripod.com/sql_server_search_and_replace.htm
If you just have a list of tables that use the primary key, you could set up a series of UPDATE statements that run inside your cursor, and then you wouldn't need to use this script (which can be a little slow).
It's worth asking, though, why these values appear out of wack. Does this database have values added and deleted constantly? Are the primary key values really arbitrary, or do they just appear to be, but they really have meaning? Though I'm all for consolidating, you'd have to ensure that there's no purpose to those values.

A: With ColdFusion this shouldn't be a herculean task, but it will be messy and you'll have to be careful.  One method you could use would be to script the database and then generate a brand new, blank table schema.  Set the accountID as an identity field in the new database.
Then, using ColdFusion, write a query that will pull all of the old account data and insert them into the new database one by one.  For each row, let the new database assign a new ID.  After each insert, pull the new ID (using either @@IDENTITY or MAX(accountID)) and store the new ID and the old ID together in a temporary table so you know which old IDs belong to which new IDs.
Next, repeat the process with each of the child tables.  For each old ID, pull its child entries and re-insert them into the new database using the new IDs.  If the primary keys on the child tables are fine, you can insert them as-is or let the server assign new ones if they don't matter.
Assigning new IDs in place by disabling relationships temporarily may work, but you might also run into conflicts if one of the entries is assigned an ID that is already being used by the old data which could cause conflicts.

A: Create a new column in the accounts table for your new ID, and new column in each of your related tables to reference the new ID column.
ALTER TABLE accounts
ADD new_accountID int IDENTITY

ALTER TABLE notes
ADD new_accountID int

ALTER TABLE equipment
ADD new_accountID int

Then you can map the new_accountID column on each of your referencing tables to the accounts table.
UPDATE notes
SET new_accountID = accounts.new_accountID
FROM accounts
INNER JOIN notes ON (notes.accountID = accounts.accountID)

UPDATE equipment
SET new_accountID = accounts.new_accountID
FROM accounts
INNER JOIN equipment ON (equipment.accountID = accounts.accountID)

At this point, each table has both accountID with the old keys, and new_accountID with the new keys. From here it should be pretty straightforward.

*

*Break all of the foreign keys on accountID.

*On each table, UPDATE [table] SET accountID = new_accountID.

*Re-add the foreign keys for accountID.

*Drop new_accountID from all of the tables, as it's no longer needed.


text:
Q: Add Logo to LaTeX poster I'm using this template to create a poster. I would like to add a logo to the top right corner of the poster, next to the tittle of the poster.
Is this possible? How?

A: One way is to add this after your \begin{document}:
\addtobeamertemplate{headline}{}
{
\begin{tikzpicture}[remember picture,overlay]
\node [shift={(-10 cm,-5cm)}] at (current page.north east) {\includegraphics[height=5cm]{logo}};
\end{tikzpicture}
}

I had to compile twice.

A: You can use the tikz package to accomplish this easily. Working with the template you mentioned, you have to include:
\usepackage{tikz}

in the preamble. Then, in the body of your document (right after \begin{document}) add the following:
\addtobeamertemplate{headline}{}
{\begin{tikzpicture}[remember picture, overlay]
     \node [anchor=north east, inner sep=3cm]  at (current page.north east)
     {\includegraphics[height=5cm]{logo}};
  \end{tikzpicture}}

which yields the following output (zoomed-in to the top right corner):

You then can of course adjust the dimensions of the logo by specifying different values in the square brackets right after the \includegraphics command.
Lastly, inner sep specifies de diagonal distance to the top right corner.
Hope it helps!


text:
Q: Bot works locally but has issues when deployed I am using the CoreBot template (from here https://marketplace.visualstudio.com/items?itemName=BotBuilder.botbuilderv4)
When testing locally, the  bot works just fine.
After I deployed it and try to Test in Webchat in Azure portal or when testing using emulator I get this error message instead of welcome card:
The bot encounted an error or bug.
To continue to run this bot, please fix the bot source code.
Any ideas?
How to troubleshoot these kind of issues?
Screeenshot of the error

A: I normally debug in this order:

*

*Check the Channel blade in "Test in Webchat" for errors. The info is normally quite sparse.

*Check the "Log stream" under the web app resource in the portal. You need to enable "Application logging (filesystem)" under the "App service logs" in the web app resource first.

*Use ngrok with the bot emulator to debug.

In you specific case, it think that the error message text is defined in your bot code. Maybe near a call to LUIS or similar? Try to locate it in your code.

A: By the looks of it, it seems like to be a deployment issue.

*

*I would suggest you to double check your deployment steps and see if you missed any steps or details(messaging endpoint, appID/password) in the settings.

*A good place to start would be the troubleshooting documentation and the configuration troubleshooting guide.

*As I stated in the comments above, you can go to the channels blade under Bot management to check for the "health" of Web Chat to see the issues.

*

*Download ngrok and debug your bot locally on the emulator and "Test in Web Chat" channel using this blogpost.

Hope this helps.


text:
Q: My UINavigationBar seems to become out of sync with UINavigationController (see gif below) When I try to back out of my Navigation stack using either the back button or swiping back from the left side of the screen, the navigation bar changes but does not dismiss the ViewController (or, in the case of swiping, the navbar animation is not interruptible). Please see the gif below.

I'm implementing my NavigationController with storyboard. It's just a UIViewController embedded into a UINavigationController. I've tried detaching the UIViewController and reattaching it to a different NavControl, manually embedding it, removing the TabBar controller that was also embedded originally. All of these have led to the same result.
Edit: Also relevant is how I'm pushing these ViewControllers to the nav stack. To present these VCs, I'm just using navigationController?.pushViewController(vc, animated: true).
present(_: UIViewController,animated: Bool) gives a modal presentation which is not what I'm looking for.
Any ideas as to what would be causing this odd behavior?

A: I had the following in my rootViewController's viewDidLoad from some earlier experimentation that wasn't being used:
// Setting as delegate might not be necessary right now,
// could become useful in the future?

navigationController?.navigationBar.delegate = self

Evidently it did not become useful in the future. Seems like doing this causes the delegate to become responsible for some of the work navBar usually does for free? Removing it immediately fixed the issue.


text:
Q: How can I make my methods restart my after being executed once? How can I alter my code to make it so that it reruns the if/else-if statements after being run once.
E.g. How can I go:
top menu>prompt for input(which is 2)>submenu>prompt for input(1 or2)>add/delete>back to top menu/subMenu
/**
 * A simple program of a grocery store, which assists
 * the purchases, calculate total price and display bill.
 **/

public class GroceryStore {

    // this method manages the entire shopping process
    public void start() {
        final String UPI = "wcor690";   // a constant for student UPI

        Stock stock = new Stock();
        stock.loadItems("stock.txt");
        Cart cart = new Cart();

        System.out.println("==============================================================");
        System.out.println("------This is a simple grocery store program by " + UPI + ".------");
        topMenu();
        int input = getChoice(1, 3);
        if (input == 1){
            stock.displayItems();
            topMenu();
        }
        else if (input == 2){
            subMenu();
            input = getChoice(1, 4);
            if (input == 1){
                String itemCode = Keyboard.readInput();
                cart.addItem(stock.findItem(itemCode));
                topMenu();
            }
            else if (input == 2){
                String itemCode = Keyboard.readInput();
                cart.deleteItem(itemCode);
                subMenu();
            }
            else if (input == 3){
                cart.checkOut();
            }
            else if (input == 4){
                cart.deleteAll();
                System.out.println("All items are cleared from the shopping cart");
                topMenu();
            }
        }
        else if (input == 3){
            System.out.println("Exit");
        }

        stock.saveItems("stock2.txt");
        System.out.println("--------------------------------------------------------------");
        System.out.println("---------------Thank you for shopping with us!----------------");
        System.out.println("==============================================================");
    }

    // this method displays the top-level menu
    private void topMenu() {
        System.out.println("1. Show items");
        System.out.println("2. Start shopping online");
        System.out.println("3. Exit");
    }

    // this method displays the second-level menu
    private void subMenu() {
        System.out.println("1. Add item");
        System.out.println("2. Remove item");
        System.out.println("3. Checkout");
        System.out.println("4. Exit without buying");
    }

    // this method gets the user's input choice
    private int getChoice(int lower, int upper) {
        String userInput = Keyboard.readInput();
        int input = Integer.parseInt(userInput);
        while (input<lower || input>upper){
            System.out.println("Invalid choice, please enter a valid choice");
            input = Integer.parseInt(Keyboard.readInput());
        }
        return input;
    }

}

A: You can use some sort of loop, which will continue to excecute the code until a condition is met.
Check out this link.
Here is an example:
do {
   code line 1;
   code line 2;
   code line 3;
   ...
} while(yourCondition);

If yourCondition is satisfied (yourCondition == true), the code will go back to code line 1 (will perform the code block between do and while) and it'll stop once the condition isn't satisfied(yourCondition == false).
Now, after you understand how it works, you can easily apply this to your code.


text:
Q: How to clone Gists with their real names and not uuid? When cloning a Github Gist, a local repository named after the gist uuid is created, and this repository contains the gist file:
+---myLocalRepo
    |
    \---uuid
        |
        \---file.md

Is there a way to skip the uuid and clone directly the gist (file.md)?
It would be easier to find and edit local files when working with many gists.

A: git clone <gist-link> <dir-name> will place the gist in 'dir-name'


text:
Q: How to detect swipe between views to make path across them in android java? I am trying to make game for which there are buttons with alphabets and if user swipes over them then it should detect the views as well as make a line across them. I searched many tutorials, examples and questions but unable to get the idea. I have attached image to help understand the question.

Here are the codes:
MainActivity.java
package com.example.detecttouch;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView btn1, btn2;
    TextView txtresult;
    Rect outRect = new Rect();
    int[] location = new int[2];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1 = findViewById(R.id.btn1);
        btn2 =  findViewById(R.id.btn2);
        txtresult = (TextView) findViewById(R.id.txtresult);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {}
        });

        btn1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int)event.getRawX();
                int y = (int)event.getRawY();
                if(event.getAction() == MotionEvent.ACTION_UP){
                    if(isViewInBounds(btn2, x, y))
                        btn2.dispatchTouchEvent(event);
                    else if(isViewInBounds(btn1, x, y)){
                        Log.d("Panauti", "onTouch ViewA");
                        //Here goes code to execute on onTouch ViewA
                    }
                }
                // Further touch is not handled
                return false;
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {}
        });

        btn2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int)event.getRawX();
                int y = (int)event.getRawY();
                if(event.getAction() == MotionEvent.ACTION_UP){
                    if(isViewInBounds(btn1, x, y))
                        btn1.dispatchTouchEvent(event);
                    else if(isViewInBounds(btn2, x, y)){
                        Log.d("Panauti", "onTouch ViewB");
                        //Here goes code to execute on onTouch ViewB
                    }
                }
                // Further touch is not handled
                return false;
            }
        });
    }

    private boolean isViewInBounds(View view, int x, int y){
        view.getDrawingRect(outRect);
        view.getLocationOnScreen(location);
        outRect.offset(location[0], location[1]);
        return outRect.contains(x, y);
    }

}

and activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtresult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="102dp"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:text="A" />

    <TextView
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="160dp"
        android:text="B" />

</RelativeLayout>

Please Help. Thanks in advance.

A: I suggest making a layout that contains the four TextViews and then setting up an onTouchListener to the layout containing them. That way, it can draw a line whenever the layout is touched rather than a specific button and can migrate between views:
private int startX, startY, endX, endY; // fields to determine the coordinates of the Rect
layout.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            startX = event.getRawX();
            startY = event.getRawY();
        } else {
            endX = event.getRawX();
            endY = event.getRawY();
            // set line bounds
        }
    }
});


text:
Q: Getting the id of  tag dynamically I have to create 'a' tags dynamically when the function (lect) get called! And on the onclick() event of this tag, i need to know the id of it. Here is the code that is explaning problem more clearly
function lect(j) {
    var mydiv = document.getElementById("cd" + j);

    var count = 3;
    for (var k = 1; k <= 3; k++) {
      var aTag = document.createElement('a');
      var inn = "analysis" + k;
      var id = "link" + k;
      var hr = "#";
      aTag.setAttribute('id', id);
      aTag.setAttribute('href', hr);
      aTag.innerHTML = inn;
      aTag.onclick = function (e)
      { // here i want to get the id of tag, so that it could be passed to
        // the second html page
        location.href = 'gallery-2.html?lectName=' + //name of id// ;
      };
    mydiv.appendChild(aTag);
    }
}

Please help me how should i do it!

A: You can do:
aTag.onclick = function (e)
{
   location.href = 'gallery-2.html?lectName=' + this.id;
};

Within your onclick event, this will refer to the aTag object.


text:
Q: Spring boot tables in database not updated when entity field is modified When using Spring boot to create an API, I've created an entity User with some fields like firstname, lastname, ...
The first time I've launched the application, the table is created in the database with all the fields.
Then I update one field adding @Column(nullable = false) to it.
And then, when I run the application again the field is not updated with the new attribute I've added to it.
In my application.properties i use this param: spring.jpa.hibernate.ddl-auto=update but it's not updating anything i don't know why

A: Ensures that a column cannot have NULL value. If the column have null value then SQL query is not executing. You can delete the column first then create it again.


text:
Q: Can I tell or hint to RubyMine what type a local or instance variable is? I'm trying to leverage the RubyMine quick-docs and code completion.  I was pleased to discover how well it integrated the YARD-style comments:
# @param [Numeric] width
# @param [Array<String>] values
# @return [Widget]
def foo(width, values)

... these comments work great for parameters, return-types, even typed collections.  But I can't find any similar tags for instance or local variables, and am pretty sure there's no type casting available in Ruby (Did I mention I'm new to this?)
Is there any way to clue RubyMine in to the types of local and/or instance variables?

A: It's not 100% answer for this particular question, but could point to other useful trick.
In tests I'm doing it this way to trick RubyMine (5.0.2)
user = users(:normal) || User.new

since with fixtures I'm sure that the users(:first) will return the object, and because of Use.new - IDE thinks it should be User instance.

A: It appears not. I'd recommend looking in the issue tracker for existing feature requests, and add make your voice heard there. For example:
http://youtrack.jetbrains.com/issue/RUBY-9142
Update
This feature is now shipping with RubyMine 7.0 (Tsubaki) EAP (138.1968) and higher (but note that Rubymine 7.0 is currently in EAP (i.e. beta) and there's always a chance this might not make it to the final distro.)

A: It appears this is forthcoming, based on a recent comment posted to the issue tracker referenced by Matt Connolly: http://youtrack.jetbrains.com/issue/RUBY-9142#comment=27-787975
"local variables can be annotated with or without variable name:"
# @type [String]
my_var = magic_method

# @type my_var [String]
my_var = magic_method

# @type [String] my_var
my_var = magic_method

# @type [String] my_var And some documentation is allowed
my_var = magic_method

"Also multi-assignments are supported:"
# @type my_var [String] The first part
# @type other_var [Range] The second part
my_var, other_var = magic_method

"But in the case of a multi-assignment the form without var name would not work (this is arguable, but I incline to that it may lead to some errors)
Also block parameters can be annotated:"
method_with_block do
  # @type [String] param1
  # @type [Range] param2
  | param1, param2 |
  # some code...
end

"The thing to note is that type annotations are to be placed after do or { and before block parameters list, to help avoiding probable ambiguity. In the case of one-liners it looks cumbersome, but I am not sure they are to be heavily annotated. Anyway, any suggestions are very welcome."


text:
Q: How to change user of windows authentication connection string in C# When I want to connect to SQL Server 2008 via SSMS in windows authentication mode I get the following error:
login failed for user UserDomainName\UserName

I installed my SQL Server in mix mode and set user to NT Authority\system , how can I create a connection string with "UserDomainName\UserName" user not with "NT Authority\system" user in C#?

A: Store the connection string in Web.Config or App.Config file
<connectionStrings>
<Add name="CS" ConnectionString="DataSource=.;Database=Sample;Integrated Security=SSPI" ProviderName="System.Data.SqlClient"/>
</connectionStrings>

then you can read the connection string property using System.Configuration namespace (dll)
string conStr = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;

how can I create a connection string with "UserDomainName\UserName"
  user not with "NT Authority\system" user in C#?

Then use SQL Authentication mode and not windows authentication
ConnectionString="DataSource=.;Database=Sample;user id = test; password=test"

A: It should something like this:
string address = "data source=(local);initial catalog=yourDB;user id=sa;password=yourPass";

Or:
string address = "Data Source=(local);Initial Catalog=yourDB;Integrated Security=True";

You can check this for more: SQL Server 2008 connection strings
Edit: Integrated Security will always use the current identity. So you won't be able to establish a connection with Windows Authentication with credentials from another domain. You need to create an SQL Server login for UserDomainName\UserName like this:
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=UserDomainName\UserName;Password=myPassword;


text:
Q: PHP Session not functioning A YUM update was ran on the server of one of my clients yesterday and suddenly all session-functionality has stopped working. I've brought it down to the absolute basics and I can't figure out why it's not working. I have these two files:
File1.php
<?php
session_start();

echo "Session ID: " . session_id();

$abbo = "freemium";

$_SESSION['abbo'] = $abbo;

echo "abbo: ".$_SESSION['abbo']."";

exit;

?>

File2.php
<?php
session_start();

echo "Session ID: " . session_id();

echo "abbo: ".$_SESSION['abbo']."";

?>

Both are in the ROOT directory of the domain. Both files dispaly the same session_id so the session actually exists. However, the second page doesn't display the variable, where the first one does. What's going wrong?


text:
Q: Bookmarklets in Chrome's Bookmark Bar A bookmarklet I've developed and use in other browsers does not work in Chrome. More specifically, I've added it to the Chrome Bookmarks Bar, and it will not fire on Chrome's default home screen, regardless of whether I click it on the Bookmarks Bar, or in the drop down Bookmarks menu. Yet, when I use it when Chrome is on any other page, it works just fine. Here is the redacted bookmarklet:
javascript:window.location.href="http://part.of."+prompt("Website:")+".the.web.site.com";

Simple, right? Yet, why doesn't this work within Chrome? Safari, even when it's on its Top Sites "meta page" responds to this bookmarklet without issue.

A: Looks like it's a deliberate security feature of Chrome, according to this posting:
http://code.google.com/p/chromium/issues/detail?id=98871#c2

A: Try this, tailor it to meet your needs, it works in the standard new tab page.
javascript:search_terms=prompt('Search terms?');window.location='http://www.google.com/search?q='+search_terms+'site:history.com';


text:
Q: backup with Dèja Dup and Duplicity returns an error I'm using Ubuntu 18.10 and the backup tool Dèja Dup
It returns the following error:
File "/usr/bin/duplicity", line 453, in <lambda> vol_num: put(tdp, dest_filename, vol_num),
File "/usr/bin/duplicity", line 342, in put backend.put(tdp, dest_filename)
File "/usr/lib/python2.7/dist-packages/duplicity/backend.py", line 395, in inner_retry % (n, e.__class__.__name__, util.uexc(e)))
File "/usr/lib/python2.7/dist-packages/duplicity/util.py", line 79, in uexc
return ufn(unicode(e).encode('utf-8'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 37: ordinal not in range(128)

A: (Partial answer and extended comment)
I have run into the same error. It's a Unicode vs. ascii encoding issue and the bug report can be found here, with more info in the comments.
A fix has already been committed in duplicity 0.8. However, unfortunately the Ubuntu repositories only contain duplicity 0.7 as of now; here's the version running on my machine:
$ duplicity --version
duplicity 0.7.17

So looks like for now we are stuck with the bug until duplicity 0.8. (But does anyone know how to update to the development version of duplicity?)
Also, it looks like the error is actually raised when attempting to report a different error. So there is an error somewhere in one of the files to be backed up; it's just that the error is not being reported, since it has some special character which isn't processed correctly.


text:
Q: Quotient set univocally defined I know that what I am going to ask is pretty basic, borderline stupid, nevertheless it is bugging me. By definition I know that given a set $A$ and a equivalence relation $\rho$, then the items $[\alpha]_{\rho}$ and $A/\rho$ are defined as follows:
$[\alpha]_{\rho} = \{x \in A : \alpha\;\rho\; x\} \\A/\rho = \{[\alpha]_{\rho}:\alpha \in A\}$
let's consider the relation $\sim$ so defined in $J=\{0,1,2,3,4,5,6,7,8,9\}$:
$$\begin{align} a\sim b \Leftrightarrow a^2-1 \equiv b^2-1 \mod 3\end{align}$$
then given that if I had to determine  $[5]_{\sim}$ and $[9]_{\sim}$, I would write
$[5]_{\sim} = \{1,2,4,5,7,8\} \\
[9]_{\sim} = \{0,3,9\}$
is it correct stating:
$J/\sim=\{[0], [1]\} = \{[2],[3]\}=\{[6],[8]\} =\; ...$
and so basically $J/\sim$ isn't univocally defined?

A: $J/\sim = \{[0], [1]\}$ is unambigiously defined. It doens't change the definition of $J/\sim$ at all, if you write its elements in another form. Note, that $[0]$ and $[3]$ are the same set, namely
$$ [0]  = \{x \mid x \sim 0\} = \{0,3,9\} = \{x \mid x \sim 3\} = [3] $$
an the same for $[1]$ and $[2]$. So the sets $\{[0], [1]\}$ and $\{[2], [3]\}$ have the very same elements and hence are equal, they both equal moreover the set
$$ J/\sim = \bigl\{\{0,3,9\}, \{1,2,4,5,6,7,8\}\bigr\} $$
To give another example note that $\{\frac12\} = \{0.5\}$ also its elements are written in another form. But this doesn't change the elements, and hence not the set.


text:
Q: How to pass props between functions within a React component I'm looking to pass a prop to a component in the header of the navigation option.  Is there a way to pass itemId to SaveButton from within the component without using something like Context API or Redux?
export default PostingDetail = ({ navigation }) => {
    const itemId = navigation.getParam('itemId', null)
    return (
        <SafeAreaView >
        </SafeAreaView>
    )
}

PostingDetail.navigationOptions = ({ navigation }) => ({
    title: "Posting Detail",
    headerRight: (
        <PleaseSignIn navigation={navigation} >
            <SaveButton id={itemId} />
        </PleaseSignIn>
    )
})

A: You can pass param as below :
export default PostingDetail = ({ navigation }) => {
    const itemId = navigation.getParam('itemId', null);
    navigation.setParams({ itemId }); // Pass itemId to navigation state
    return (
        <SafeAreaView >
        </SafeAreaView>
    )
}

And then you can get itemId as below :
PostingDetail.navigationOptions = ({ navigation }) => ({
    title: "Posting Detail",
    headerRight: (
        <PleaseSignIn navigation={navigation} >
            <SaveButton id={navigation.state.params.itemId} />
        </PleaseSignIn>
    )
})


text:
Q: Why isn't onSectionRendered being called on my List? For some reason onSectionRendered is not being called on my List.  Everything else is working fine.  Not sure If i'm passing it in right.  It doesn't render when i initially load the Grid List nor when different rows become visible.

<AutoSizer>
    {({ width, height }) =>
    <List
        ref={this.set_reference}
        className={stylesheet.nestedVirtualizedList}
        width={width}
        height={height}
        onSectionRendered={()=>{console.log('Please show up ;(')}}
        onScroll={this.update_scroller_position}
        rowCount={this.props.data.length}
        rowHeight={(this.props.get_dynamic_height) ? this.props.get_dynamic_height : height}
        rowRenderer={this.render_row}
        overscanRowCount={this.props.overscan_row_count}

        />
    }
</AutoSizer>

I have also tried this...

<AutoSizer>
      {({ width, height }) =>
      <List
          {...{onSectionRendered:this.on_section_rendered}}
          ref={this.set_reference}
          className={stylesheet.nestedVirtualizedList}
          width={width}
          height={height}
          onScroll={this.update_scroller_position}
          rowCount={this.props.data.length}
          rowHeight={(this.props.get_dynamic_height) ? this.props.get_dynamic_height : height}
          rowRenderer={this.render_row}
          overscanRowCount={this.props.overscan_row_count}

          />
      }
  </AutoSizer>

A: The List property is named onRowsRendered (check the docs):

onRowsRendered
Callback invoked with information about the slice of rows that were just rendered: ({ overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }): void


text:
Q: (Topological quantum field theory) identifying objects of cobordism category I am beginning the study of Topological quantum field theory(TQFT) and I am confused with the basic notions. Before writing down the question, to check if I understood the definition correctly, I state what I learned as follows. Also I will only deal with the $2$-dimensional TQFT here.
$1$. TQFT assigns a $\mathbb{C}$-vector space $Z(M)$ to each $1$-dim closed oriented manifold $M$.
$2$. TQFT assigns a vector $Z(L)\in Z(\partial L)$ to each $2$-dim closed oriented manifold with boundary $L$.
$3$. $Z(M1\cup M2)=Z(M1)\otimes Z(M2), Z(M^*)=Z(M)^*$
($M^*$ is the orientation reversal of $M$, $Z(M)^*$ is the dual of $Z(M)$)
$4$. For orientation preserving diffeomorphism $\phi : M_1\rightarrow M_2 (M_1,M_2 : \text{1 dim closed manifold})$ there is an induced vector space isomorphism $\phi_{*} : Z(M_1)\rightarrow Z(M_2)$.(plus some naturality)
I omitted other axioms because these seems to be enough for my question. Using 3, we can interpret a vector as a linear map between vector spaces. With this,
The theory says that the TQFT assigns Id$_{Z(S^1)}$to the cylinder $S^1\times$I, whose boundary is disjoint union of two $S^1$. Of course they are diffeomorphic, but for later convenience, let's call them $S^1_a $and $S^1_b$. Next I thought as below.
$1$. "every closed oriented $1$-dim manifold is diffeomorphic to each other ($\sim S^1$), even up to orientation preserving diffeomorphism. so there exists isomorphism $Z(S^1_a)\sim Z(S^1_b)\sim Z(S^1)\sim Z(S^{1*})$. But we are not identifying the objects itself via orientation preserving diffeomorphism because both notion $Z(S^1)$ and $Z(S^{1*})$ are appearing in the texts."
$2$. "A choice of the orientation of the cylinder induces orientation($\mu$) on its boundary. since $S^1_a$ and $S^1_b$ are already oriented manifold, comparing this with induced orientation $\mu$ will determine wheter to write each $S^1_a, S^1_b$ as oriented the same way($S^1_i$), or reversely oriented($S^{1*}_i$)."
Because $S^1_a$ and $S^1_b$ are not equal to $S^1$ set theoretically,(yet we do not mod out by diffeomorphism because of "1"?!) so to say this cylinder $(S^1\times I)$ gives a vector in $Z(S^1)\bigotimes Z(S^{1*})$, I thought that I need to choose a diffeomorphism of cylinder and use some naturality axiom to identify $Z(S^1_a)\bigotimes Z(S^1_b)$ with $Z(S^1)\bigotimes Z(S^{1*})$. But I'm not sure this method makes sense since there are lots of (orientation preserving)diffeomorphisms between closed oriented 1 dim manifold.
Considering all this, I am also suspicious that why it corresponds to an element of $Z(S^{1*})\bigotimes Z(S^1)$ but not an element of $Z(S^1)\bigotimes Z(S^1)$.
I hope my word was understandable. In short, would anyone help me with the identification problem of $Z(S^1_a)\bigotimes Z(S^1_b)$ and determining its orientation compared to specified $S^1$?
Great Thanks.

I followed the defintion of TQFT in
Atiyah M., Topological quantum field theory , p177-181
Lawrence R.J. , Introduction to topological quantum field theory , p5-7.
Thank you for your attention.


text:
Q: Set a shortcut key for Windows 8.1 Start screen I have currently set the behavior of  Windows button to go automatically to "Apps view" instead of the original Start screen.

But sometimes I want to go to the main Start screen (not the App view) by pressing a single key or a shortcut. Is there there a way to do this so that my current setting of navigation will not change?


text:
Q: Can't link dynamic library when running C language with root privileges? I have a C language file named testFunc.c that uses the dynamic library libCfunc.so. This library is placed under the path /home/cuiyujie/workspace/library/lib.
I added this path to library path export LD_LIBRARY_PATH=/home/cuiyujie/workspace/library/lib:$LD_LIBRARY_PATH
When I use the following command to compile, it can be compiled normally.
gcc testFunc.c  -lCfunc -lm -O0 -g -o testFunc

But when I run it, if I use ./testFunc, it can run normally.
But if I use sudo ./testFunc, he will get the following error.

./testFunc: error while loading shared libraries: libCfunc.so: cannot
open shared object file: No such file or directory

I found on Google that when root is used, the value of the LD_LIBRARY_PATH variable is ignored.
I used the following command to recompile. Specify the library path when compiling.
gcc testFunc.c  -L/home/cuiyujie/workspace/library/lib -lCfunc -lm -O0 -g -o testFunc

When I continue to run with the sudo ./testFunc command, the same error still appears.
The reason why I need to execute with root is because I need to read some inquiries that only root privileges can read. I want to get the physical address of certain variables, so I need to read the mapping file of the process, which requires root privileges.

A: The linker flag -L just tells the linker where to look for the library (or a library stub, if such is used) at link time. It does not influence the library search path at runtime.
For a system wide installed library you'd place the library in a place that's been configured in the global linker search path, set through /etc/ld.so.conf and files in /etc/ld.so.conf.d.
However it is perfectly possible to specify additional search paths specific to certain binaries by means of the so callled rpath. The rpath  is set using the (you guessed it) rpath extra linker flag -Wl,-rpath.
Linking the program with
gcc -o … -Wl,-rpath='${ORIGIN}' …

would make the ELF interpreter (the piece of code that loads ELF binaries and does dynamic linkage) to also look for additional libraries right next to the program binary. You can read up on the details of rpaths in the ld.so manpage.
Be aware that rpaths invoke certain security considerations.

A: LD_LIBRARY_PATH is an environment variable, and all environment variables exist separately for each user.
When you export it under your regular user, but then run the executable as root using sudo, the export does not exist for the new process.
You can preserve the environment of your user with the -E parameter:
sudo -E ./testFunc

or you can specifically preserve the LD_LIBRARY_PATH variable like this:
sudo LD_LIBRARY_PATH=/home/cuiyujie/workspace/library/lib:$LD_LIBRARY_PATH ./testFunc


text:
Q: Why aws cli is executing old docker image when run from gitlab ci? I'm pushing my docker image to my private docker hub account and then I run aws cli to start an instance from the docker image. However, aws cli always executes the previous version of the image, not the most up-to-date one. So in order to execute the most up-to-date I need to manually re-deploy or even restart the instance sometimes. I checked that aws cli starts 45 seconds after docker hub image is updated in docker hub. Then just as a test I added sleep 300 seconds before_script in gitlab yaml file in the deploy stage before I run aws cli.
It seems like there's some kind of cache in Elastic beanstalk which is not updating the environment properly.
Has anyone ever run into such issue?
This is my gitlab yaml config in my subproject:
.build-docker-image:
  image: docker:18
  stage: build
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  services:
    - docker:dind
  script:
    - echo branch $CI_COMMIT_REF_NAME tag $CI_COMMIT_TAG
    - docker build .
    - docker push "$CI_REGISTRY_IMAGE"
  except:
    variables:
      - $SKIP_BUILD == "1"

docker-build-staging:
  extends: .build-docker-image
  environment:
    name: subprojectname
  only:
    variables:
      - $CI_COMMIT_REF_NAME == "staging"
  variables:
    CI_REGISTRY_IMAGE: myproject/subproject:staging

amazon_beanstalk_staging:
  extends: .amazon_beanstalk
  environment:
    name: subprojectname
    url: 'https://subprojectname.com'
  variables:
    AWS_VERSION: $STAGING_AWS_VERSION_BETA
    AWS_ENV_NAME: $STAGING_AWS_ENV_BETA
  only:
    variables:
      - $CI_COMMIT_REF_NAME == "staging"

and this is the gitlab yaml in the root folder which contains all subprojects:
image: node

stages:
  - build
  - deploy

# sleep 300 seconds in order to prevent aws running old docker image
.amazon_beanstalk:
  stage: deploy
  image: garland/aws-cli-docker:latest
  before_script:
    - sleep 300
  script:
    - sh -c  "aws configure set region '$AWS_REGION' && aws elasticbeanstalk update-environment --environment-name '$AWS_ENV_NAME' --version-label '$AWS_VERSION'"

include:
  - local: 'pathToMySubproject/.gitlab-ci.yml'

A: (updated after comment from @hitchhiker): For clear troubleshooting output, be sure CloudWatch Logs are enabled for your environment, and view the log for ecs-agent.log and you can see the PULL steps performed by the agent.   I was able to see very specific PULL steps when the environment was updated, or if the environment was restarted.
So sorry to hear you are still having problems.    Thank you for confirming you are running v2.   I did try to make guesses about your task setup and reproduce it. Upon running update-environment, the system automatically performed a PULL of my updated image, even if I used the exact same version-label.  Also, upon restarting the instance (from the Elastic Beanstalk console), a new image was pulled.

Original response:
If you are using a single container approach:
Inside your Dockerrun.aws.json file, please confirm you have "Update": "true" inside your "Image" section.  This instructs Elastic Beanstalk to always check your Docker Hub repository for new images.   If this setting is "false", then the Elastic Beanstalk service will prefer to use the previously downloaded image.
From the documentation:

When you specify an image in the Dockerrun.aws.json file, each
  instance in your Elastic Beanstalk environment will run docker pull on
  that image and run it. Optionally, include the Update key. The default
  value is true and instructs Elastic Beanstalk to check the repository,
  pull any updates to the image, and overwrite any cached images.

{
  "AWSEBDockerrunVersion": "1",
  "Image": {
    "Name": "janedoe/image",
    "Update": "true"
  },
  "Ports": [
    {
      "ContainerPort": "1234"
    }
  ],
  "Volumes": [
    {
      "HostDirectory": "/var/app/mydb",
      "ContainerDirectory": "/etc/mysql"
    }
  ],
  "Logging": "/var/log/nginx",
  "Entrypoint": "/app/bin/myapp",
  "Command": "--argument"
}

Please also note from the ECS container definition documentation, if you have old tasks running, they will not be automatically updated:

When a new task starts, the Amazon ECS container agent pulls the
  latest version of the specified image and tag for the container to
  use. However, subsequent updates to a repository image are not
  propagated to already running tasks.


text:
Q: mysql_query producing ERR_EMPTY_RESPONSE We recently had PHP version upgraded to 5.3.3 on our server (running Wordpress) and since then the mysql_query  function started hanging the server, producing the error Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data in Google Chrome.
The connection parameters are correct and error logging is also turned on but nothing appears.
What could be wrong? What should I check?
UPDATE:
The code:
function query( $query ) {
    if ( ! $this->ready )
        return false;

    // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
    if ( function_exists( 'apply_filters' ) )
        $query = apply_filters( 'query', $query );

    $return_val = 0;
    $this->flush();

    // Log how the function was called
    $this->func_call = "\$db->query(\"$query\")";

    // Keep track of the last query for debug..
    $this->last_query = $query;

    if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
        $this->timer_start();

    // use $this->dbh for read ops, and $this->dbhwrite for write ops
    // use $this->dbhglobal for gloal table ops
    unset( $dbh );
    if( defined( 'WP_USE_MULTIPLE_DB' ) && WP_USE_MULTIPLE_DB ) {
        if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
            if( false == isset( $this->dbhglobal ) ) {
                $this->db_connect( $query );
            }
            $dbh =& $this->dbhglobal;
            $this->last_db_used = "global";
        } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
            if( false == isset( $this->dbhwrite ) ) {
                $this->db_connect( $query );
            }
            $dbh =& $this->dbhwrite;
            $this->last_db_used = "write";
        } else {
            $dbh =& $this->dbh;
            $this->last_db_used = "read";
        }
    } else {
        $dbh =& $this->dbh;
        $this->last_db_used = "other/read";
    }

    $this->result = @mysql_query( $query, $dbh );
    $this->num_queries++;

    if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
        $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );

    // If there is an error then take note of it..
    if ( $this->last_error = mysql_error( $dbh ) ) {
        $this->print_error();
        return false;
    }

    if ( preg_match( "/^\\s*(insert|delete|update|replace|alter) /i", $query ) ) {
        $this->rows_affected = mysql_affected_rows( $dbh );
        // Take note of the insert_id
        if ( preg_match( "/^\\s*(insert|replace) /i", $query ) ) {
            $this->insert_id = mysql_insert_id($dbh);
        }
        // Return number of rows affected
        $return_val = $this->rows_affected;
    } else {
        $i = 0;
        while ( $i < @mysql_num_fields( $this->result ) ) {
            $this->col_info[$i] = @mysql_fetch_field( $this->result );
            $i++;
        }
        $num_rows = 0;
        while ( $row = @mysql_fetch_object( $this->result ) ) {
            $this->last_result[$num_rows] = $row;
            $num_rows++;
        }

        @mysql_free_result( $this->result );

        // Log number of rows the query returned
        // and return number of rows selected
        $this->num_rows = $num_rows;
        $return_val     = $num_rows;
    }

    return $return_val;
}

The line that causes the error is $this->result = @mysql_query( $query, $dbh );
I am currently investigating the value of $dbh.
mysql_query without parameters produced a warning, so at least it is working.


text:
Q: Wrong initial intuition about the limit of $\frac{\sin(x)}{x}$ as $x$ goes to 0 I'm following the MIT OpenCourseware course on calculus, and when proving the derivative of $\sin(x)$ the following assumption is needed
$\lim\limits_{x\to0}  \frac{\sin(x)}{x} = 1$
The proof for this is given and I can follow it.
My question however relates to my initial intuition. Which is that the limit of $\sin(x)$ at 0 is defined: $\sin(0) = 0$. So Why is it wrong to just plug that in
$ \frac{\sin(0)}{0} = 0$
I would have never looked further because this seems like a simple problem. What is wrong with my intuition here?

A: You are making two fundamental mistakes:
First: after substituting $x=0$, you wind up dividing by $0$.
This is an undefined expression;
so, you should suspect that things have gone awry.
In your example, an even worse thing happens: you wind up with $0\over0$;
which (if it makes any sense) is even more "undefined" than, say, $1\over 0$.
For instance $\lim\limits_{x\rightarrow 0}{2x\over x}=2$
and $\lim\limits_{x\rightarrow 0}{ x\over 2x}={1\over2}$.
In fact a 0/0 form could possibly be anything.
Secondly, when taking limits, you should really avoid just plugging in the limit point into the expression.
This only works in certain cases (when the  limit exists and the function is continuous at the limit point),
and, more importantly,  hides the true nature of what a limit is:
Informally,
you write $$\lim_{x \rightarrow a} f(x)=L$$ if the values of $f(x)$ get closer and closer to $L$ as $x$ gets
closer and closer to, but not equal to, $a$.
Note the phrase "not equal to" in the above. This is an important restriction and is the reason why just
substituting the limit point into what you're taking the limit of can lead to trouble.
As an example of determining the limit of a 0/0 form,  let's try to find
$$
\tag{1} \lim_{x\rightarrow 1}{(x+1)(x-1)\over (x-1)}
$$
Formally substitutiing $x=1$ in the above gives $0/0$.
If, however, $x$ is close to one, but different from 1, then  substitution into the
right hand side of (1) gives a well-defined number;   moreover, the $(x-1)$ terms will cancel and the final result will be just $x+1$.
Thus, if $x$ is close to 1, but different from 1,
the expression ${(x+1)(x-1)\over (x-1)}$ is close to 2.
As it turns out, the closer $x$ is to 1, but different from 1, the closer
${(x+1)(x-1)\over (x-1)}$ is to 2; and thus
$\lim\limits_{x\rightarrow 1}{(x+1)(x-1)\over (x-1)}=2$.
Finding your limit ($\thinspace\lim\limits_{x\rightarrow0}{\sin x\over x} \thinspace$)
is a bit more complicated than the above. You can find the standard derivation of this limit, which utilizes the
Squeeze Theorem
and simple geometry here (or at your course site, as you said).

A: You can just use L'Hôpital's rule.
$$\begin{align*}
\frac{d}{dx} \sin(x) &=\cos(x) \\
\frac{d}{dx} x &= 1 \\
\lim_{x\rightarrow0} \frac{\sin(x)}{x}&=\lim_{x\rightarrow0}\frac{\cos(x)}{1}=1
\end{align*}$$
Edit: I think this rule is very helpful to evaluate limits involving indeterminate forms. Not as proof but as a sanity check of an intuitive answer.


text:
Q: How can I add a dynamic class to an HTML tag? For example, in the following example I want to add a class called "noDisplay" based on a certain condition. (1==1, for simplicity's sake.)
I tried:

And:
@if (1 == 1) {
 @: class="noDisplay"
}>

A: What you posted is working but the Html.Raw section is just being treated as a function call, not as something to be rendered. The simple solution is to prefix the call with an @ symbol (which will make Razor render the output of the function) or remove the call to Html.Raw and use <text> blocks:

Or:
<tr class='@if (1== 1) { <text>noDisplay</text> }'>

A: This is what you need to do:
@{
    var myClass = (1 == 1 ? "noDisplay" : "");
}

Or, just:

A: @{
    if(1 == 1)
    {
        var theClass = "noDisplay";
    }
}

The @: is an operator that outputs a single line of content containing plain text or unmatched HTML tags. The @{ ... } defines a block of code. Using @ lets you access a variable that you may have defined in your code or other C# constructs.
Plenty more info and examples here: http://www.asp.net/web-pages/overview/getting-started/introducing-razor-syntax-c


text:
Q: Is there common street addresses database design for all addresses of the world? I am a programmer and need a practical approach to storing street address structures of the world in a database. So which is the best and common database design for storing street addresses? It should be simple to use, fast to query and dynamic to store all street addresses of the world.

A: Have a look at Database Answers. Specifically, this covers many cases:
(All variable length character datatype)
AddressId
Line1
Line2
Line3
City
ZipOrPostcode
StateProvinceCounty
CountryId
OtherAddressDetails

A: Maybe this is useful:
https://gist.github.com/259744
For a project I collected a table of informations about all countries of the world, including ISO codes, top level domain, phone code, car sign, length and regex of zip.
Country names and comments unfortunately only in German...

A: Differently of other answers here, I believe it's possible to have an structured address database.
Just out of the hat, I can think of the following structure:

*

*Country

*Region (State / Province)

*Locality (City / Municipality)

*Sub-Locality (County / other sub-division of a locality)

*Street

But how to query it fast enough?
One way I always think it can be accomplished is to ask for the ZIP Code (or Postal Code) which varies from country to country, but is solid within the country.
This way you can structure your data around the information provided by the postal offices around the world.

A: Ask yourself what is the main purpose of storing this data? Do you intend to actually send mail to the person at the address? Track demographics, populations? Be able to ask callers for their correct address as part of some basic authentication/verification? All of the above? None of the above?
Depending on your actual need, you will determine either a) it doesn't really matter, and you can go for a free-text approach, or b) structured/specific fields for all countries, or c) country specific architecture.

A: No, absolutely not.  If you compare the way US and Japanese addresses work, you'll see that it's not possible.
UPDATE:
On second thought, anything can be done, but there's a trade-off.
One approach is to model the problem with address and address_attribute tables, with a 1:m relationship between them, anything can be modeled.  The address_attribute table would have a pk, a name, a value, and an fk that points back to its address parent's pk.  It's almost like using a Map with name, value pairs.
The trade-off is having to do a JOIN every time you want an address.  You also have to interrogate the names of the address_attributes to figure out what you're dealing with each time.
Another approach would be to do more comprehensive research on how addresses are modeled around the world.  In an object-oriented world you might have the western Address class (street1/street2/city/state/zip) and others for Japan, China, as many as needed to tile the address space.  Then you'd have a master Address table and child tables to the other types with a 1:1 relationship between them.
How does Amazon or eBay do it?  They ship internationally.  Do they have locale-specific UI features?  I've only used the US locale.

A: Depends on how free-form you are prepared to go with the fields. One free-form address field will obviously always do, but be of relatively little help narrowing down geography.
The problem you'll have is that there is too much variation in the level of geographical hierarchy across countries. Heck, some countries do not even have 'street addresses' everywhere.
I recommend you don't try to make it too clever.

A: Len Silverston of Universal Data Model fame recommends a separate hierarchy of GEOGRAPHIC BOUNDARIES and depending on how much free-formed-ness you're willing to accept either simple STREET ADDRESS LINEs or per-country derivatives.

A: No, there are no standard addressing scheme. It usually varies from country-to-country.
Even the Universal Postal Union said on Adressing the world, an address for everyone that there is none. The best solution for this is to use the 2/3-letter country code standards known as ISO 3166 and treat everything else by country's standards.
However, if you really are desperate to use easily accessible tools for your project, you can try Google Place API.

A: It is possible to represent addresses from lots of different countries in a standard set of fields. The basic idea of a named access route (thoroughfare) which the named or numbered buildings are located on is fairly standard, except in China sometimes. Other near universal concepts include: naming the settlement (city/town/village), which can be generically referred to as a locality; naming the region and assigning an alphanumeric postcode. Note that postcodes, also known as zip codes, are purely numeric only in some countries. You will need lots of fields if you really want to be generic.
The Universal Postal Union (UPU) provides address data for lots of countries in a standard format. Note that the UPU format holds all addresses (down to the available field precision) for a whole country, it is therefore relational. If storing customer addresses, where only a small fraction of all possible addresses will be stored, its better to use a single table (or flat format) containing all fields and one address per row.
A reasonable format for storing addresses would be as follows:

*

*Address Lines 1-4

*Locality

*Region

*Postcode (or zipcode)

*Country

Address lines 1-4 can hold components such as:

*

*Building

*Sub-Building

*Premise number (house number)

*Premise Range

*Thoroughfare

*Sub-Thoroughfare

*Double-Dependent Locality

*Sub-Locality

Frequently only 3 address lines are used, but this is often insufficient. It is of course possible to require more lines to represent all addresses in the official format, but commas can always be used as line separators, meaning the information can still be captured.
Usually analysis of the data would be performed by locality, region, postcode and country and these elements are fairly easy for users to understand when entering data. This is why these elements should be stored as separate fields. However, don't force users to supply postcode or region, they may not be used locally.
Locality can be unclear, particularly the distinction between map locality and postal-locality. The postal locality is the one deemed by a postal authority which may sometimes be a nearby large town. However, the postcode will usually resolve any problems or discrepancies there, to allow correct delivery even if the official post-locality is not used.

A: Sometimes the closest you can get to a street address is the city.
I once had a project to put all the Secondary Schools in India in Google Maps.  I wrote a spiffy program using the Google API and thought it would be quite easy.
Then I got the data from the client. Some school addresses were things like "Across from the market, next to the barber" or "Near old bus stand".
It made my task much harder since, unfortunately, the Google API does not support that format.

A: For international addresses, it is remarkably hard to find a way to format the information if it is broken down into fields.  As a for instance, an Italian address uses:
<street address>
<zip> <town> <region>
<country>

Such as
Via Eroi della Repubblica
89861 Tropea VV
Italy

That is rather different from the order for US addresses - on the second line.
See also the SO questions:

*

*How many address fields would you use for a UK database?

*Do you break up addresses into street / city / state / zip?

*How do you deal with duplicate street suffixes?

*Best practices for storing postal addresses in a database (RDBMS)?
Also check out tag 'postal-code'.

Edit: Reverse order of region and town - per UPU

A: Your design should strongly depend from your purpose. Some people have posted how to structure data. So if you simply want to send s-mail to someone, it will do. Things begin to complicate if you want to use this data for navigation. Car navigation will require additional structures to contain traffic info (eg one-way roads), while foot navigation will require a lot of additional data. Here is small example: in my city, my neighborhood is near the park. Next to the park is former airfield (in fact, one of the oldest in Europe) turned into aviation museum. Next to aviation museum is a business park.  Street number for museum is 39, while business park numbers start with 39A. So it may seem that 39 and 39A are close – but it takes about a mile to walk from one to another (and even longer if going by car) .
This is just a small example taken from my city, I think you can probably find a lot of exceptions (especially in rural or wilder parts of every country).


text:
Q: Wrapper hierarchies with Java generics Is there any way using Java generics to express a type hierarchy like the following?
class A { ... }

class B extends A { ... }

interface Wraps<T> {
  T getWrapped();
}

class WrapsA implements Wraps<A> {
  A getWrapped();
}

class WrapsB extends WrapsA /* implements Wraps<B> */ {
  B getWrapped();
}

I understand that as written Java's type system will reject this code, but is there any way I can specify the type parameters or inheritance hierarchy that will get this working?
EDIT: I realized that the real issue I'm having is I'm trying to enforce type safety in my API for a method like
<T extends A> T unwrap(Wraps<T> wrapper, Class<T> wrappedClass);

I'm not able to call it with unwrap(wrapsB, B.class). Is this something that Java will handle?

A: You can just use
class WrapsB extends WrapsA {
    B getWrapped();
}

Since you're allowed to return subclasses in overriden methods (it's possible from Java SE6, as far as I remember)

A: Check out self-bounded types.
interface Wraps<T, W extends Wraps<T, W>> { ... }

abstract class AbstractWrapsA< T extends A, W extends AbstractWrapsA< T, W > implements Wraps< T, W > { ... }
class WrapsA extends AbstractWrapsA< A, WrapsA > {}
class WrapsB extends AbstractWrapsA< B, WrapsB > { ... }

EDIT:  Actually to satisfy the OP's need we can dispense with self-bounded types and just migrate the guts of WrapsA to an abstract class.  We still do not have that WrapsB both is-a WrapsA and is-a Wraps<B>.


text:
Q: Testing Laravel Inside Legacy Application Chances are pretty high that it's impossible to help me without being able to see this codebase I'm in but I though I'd ask here just in case someone has done something similar
I'll go into more specific details about the situation I'm in below, but the main question I'm asking is: Has anyone had to write tests for a legacy codebase that uses Laravel as a dependancy and were you able to use Laravel's TestCase or did you have to role your own testing environment?
I'm working in a 15+ year old legacy php app... About a year ago they started writing a bunch of their new API in Laravel. The legacy app includes the Laravel app as a dependency. So what happens is, via htaccess rewrite rule, requests going to api/v2 hit an index file that boots the Laravel app. This index file includes an init.inc.php which does a ton of setup for the legacy app, then when the Laravel app gets booted, it actually boots a custom class which extends Laravel's Illuminate\Foundation\Application. It does this because there's a bunch of legacy configurations that get passed to Zend_Config and then sets the storage directory to point inside of the legacy app instead of the laravel app.
The Laravel app is a private packagist that gets symlinked to a local copy of the repo during development. During production, it's just a vendor package.
I'm trying to set up tests for this damn thing... and it is not going well lol
I was really hoping to be able to have a test suite within the Laravel app itself but it doesn't look like I'll be able to do so, because the bootstrap flow is created under the assumption that the legacy app does all of its set up before spinning up Laravel, and of course, the Laravel app has dependencies on the legacy app too.
So what I've been trying to settle on is setting up the tests inside the legacy app, and run the standard boot sequence, followed by spinning up Laravel. I can actually get this to work with a BaseTestCase class the extends PHPUnit\Framework\TestCase and I can get my Eloquent models instantiated inside of a test, I can hit endpoints with Guzzle and assert on responses etc... all seems to work fine
Problem is I don't have an easy way to test anything in isolation at this point, so touching the database is kind of my first go-to method for now. However, I also don't have an easy way for seeding test data, and I don't have an easy way to wrap my tests in transactions that rollback after each test. (I may have to go this route honestly, but it seems like it could lead to a lot of work) What would be amazing is if I could just use the Illuminate\Foundation\Testing\TestCase then I'd have all the Laravel goodies like not having to work directly with Guzzle for one, but also traits like DatabaseTransactions and WithoutEvents or WithoutMiddleware etc.
Something is not right though. When I try extending the Laravel TestCase I get weird errors like Argument 1 passed to Illuminate\Database\Eloquent\Model::setEventDispatcher() must implement interface Illuminate\Contracts\Events\Dispatcher, null given,
Diving through some source code it looks like TestCase checks if the app has been instantiated, and if not calls the abstract createApplication() method which is defined on my custom TestCase but the error I'm getting is telling me that $app['events'] is null. Ugh, and of course, I can't get Xdebug working in their environment either so I'm not able to properly step through and see exactly what's going on.
Basically, my main goal right now is to figure out how to get debugging working with their setup, so I can actually step through code but I figured I would put a question out here on StackOverflow in case someone has any advice. Anything that gets me closer to being able to use the Laravel TestCase would be an amazing feeling right now.
I know it's a long shot but anyone ever try anything like this before? Were you able to get a Laravel test suite working in a legacy app?
Edit
Here's what my createApplication override looks like after removing actual paths with fake ones:
public function createApplication()
{
    @set_include_path(implode(PATH_SEPARATOR, array(
        dirname(__FILE__) . "/../../www-root/core",
        dirname(__FILE__) . "/../../www-root/core/includes",
        dirname(__FILE__) . "/../../www-root/core/library",
        dirname(__FILE__) . "/../../www-root/core/library/vendor",
        get_include_path(),
    )));

    require_once("init.inc.php");

    $this->app = require_once 'private-packagist-package/src/bootstrap/app.php';

    $kernel = $this->app->make(\Illuminate\Contracts\Http\Kernel::class);

    $response = $kernel->handle(
        $request = \Illuminate\Http\Request::capture()
    );

    $response->send();

    $kernel->terminate($request, $response);
}

That same code works in my barebones test case where I simply extend PHPUnit's test case.


text:
Q: Why is the Gold on Fire? I've recently been trying to find a Texture-Pack for MineCraft that I'm happy with, and I seem to have run into a problem with some of them.  In 3 of the 4 packs I've tried, Gold Blocks don't display correctly.   Here's a sample:

Does anyone have any idea why this might be occurring?

For reference, this is the GeruDoku fantasy/adventurer texture pack.

A: On closer inspection, it seems likely to have something to do with this:

It appears that this is an HD texture pack, which means I need to run some sort of fixer for it.

A: This question and answer apply to Minecraft 1.4.7 and earlier. Minecraft 1.5 and later support high-resolution textures automatically, and do not exhibit the misplaced animations described below.
Minecraft versions before 1.5 were not written to support different-resolution textures.
The default Minecraft terrain texture in these versions is a 256×256 image with 16×16 tiles in it (a texture atlas).
The code which animates the animated textures in Minecraft (fire, water, lava, and portals) writes onto specific pixel offsets according to 16×16 tiles, which are wrong for larger textures, so you get small fire/water/portal images occupying other blocks. Presumably the patchers replace the 16× factors with 32×, or whatever fits the actual texture resolution.
The reason the textures mostly work is that the OpenGL 3D API used by Minecraft mostly takes coordinates in textures in terms of numbers between 0 and 1, rather than 0 and whatever the pixel size of the image is, so the main rendering doesn't care; only the animated textures, which are actually defined in terms of recalculating individual pixels and modifying the data of the texture in memory, are affected.
Also, tiles over a certain size (128×128, I think) will crash Minecraft. Below that size, you can still use HD textures and it will work except for the misplaced animations. The animated items will not animate, and (for a 32× pack) these will have animations on them: bricks, gold blocks, Netherrack, and pumpkins.