问:
How to modify the duplicate form in the database manager?
I want to add some other field to this form that can be accessed from the Database Manager in Odoo

The data is sent to this controller:

```<code>@http.route('/web/database/duplicate', type='http', auth="none", methods=['POST'], csrf=False)
def duplicate(self, master_pwd, name, new_name):
    try:
        if not re.match(DBNAME_PATTERN, new_name):
            raise Exception(_('Invalid database name. Only alphanumerical characters, underscore, hyphen and dot are allowed.'))
        dispatch_rpc('db', 'duplicate_database', [master_pwd, name, new_name])
        return http.local_redirect('/web/database/manager')
    except Exception as e:
        error = "Database duplication error: %s" % (str(e) or repr(e))
        return self._render_template(error=error)
</code>```

But the form is plain html, so I cannot inherit and modify any template:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Duplicate Database

        <form id="form-duplicate-db" role="form" action="/web/database/duplicate" method="post">

            {{ master_input() }}

                Database Name
                <input id="name" type="text" name="name" class="form-control" required="required" readonly="readonly"/>

                New Name
                <input id="new_name" type="text" name="new_name" class="form-control" required="required" pattern="{{ pattern }}" title="Only alphanumerical characters, underscore, hyphen and dot are allowed"/>

            <input type="submit" value="Continue" class="btn btn-primary pull-right"/>

        </form>

```

<p>I found a python code where this html is rendered</p>

```class Database(http.Controller):

    def _render_template(self, **d):
        d.setdefault('manage',True)
        d['insecure'] = odoo.tools.config.verify_admin_password('admin')
        d['list_db'] = odoo.tools.config['list_db']
        d['langs'] = odoo.service.db.exp_list_lang()
        d['countries'] = odoo.service.db.exp_list_countries()
        d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
            d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("database_manager.html").render(d)
```

Should I modify this code in order to use another template? Or is there another more appropriate solution?

Is modifying the original code directly in the web module the only way to achieve this? Is there a way to change all this behaviour by inheriting the web module?

答:
Yes, you would need to overwrite the _render_template method of the web module.
And also you would need to create your own HTML template for that and pass it for the rendering.

```<code>from odoo.addons.web.controllers.main import db_monodb, Database as DB, env
import jinja2

loader = jinja2.PackageLoader('odoo.addons.your_custom_module_name', "views")
env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = json.dumps
</code>```

class Database(DB):

```<code>def _render_template(self, **d):
    d.setdefault('manage',True)
    d['insecure'] = odoo.tools.config['admin_passwd'] == 'admin'
    d['list_db'] = odoo.tools.config['list_db']
    d['langs'] = odoo.service.db.exp_list_lang()
    d['countries'] = odoo.service.db.exp_list_countries()
    d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("your_html_template_file_name.html").render(d)
</code>```

This is an example from v10. You can just copy and paste the method from the Odoo module of the version you are working on.

Body:
I want to add some other field to this form that can be accessed from the Database Manager in Odoo

The data is sent to this controller:

@http.route('/web/database/duplicate', type='http', auth="none", methods=['POST'], csrf=False)
def duplicate(self, master_pwd, name, new_name):
    try:
        if not re.match(DBNAME_PATTERN, new_name):
            raise Exception(_('Invalid database name. Only alphanumerical characters, underscore, hyphen and dot are allowed.'))
        dispatch_rpc('db', 'duplicate_database', [master_pwd, name, new_name])
        return http.local_redirect('/web/database/manager')
    except Exception as e:
        error = "Database duplication error: %s" % (str(e) or repr(e))
        return self._render_template(error=error)

But the form is plain html, so I cannot inherit and modify any template:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Duplicate Database

        <form id="form-duplicate-db" role="form" action="/web/database/duplicate" method="post">

            {{ master_input() }}

                Database Name
                <input id="name" type="text" name="name" class="form-control" required="required" readonly="readonly"/>

                New Name
                <input id="new_name" type="text" name="new_name" class="form-control" required="required" pattern="{{ pattern }}" title="Only alphanumerical characters, underscore, hyphen and dot are allowed"/>

            <input type="submit" value="Continue" class="btn btn-primary pull-right"/>

        </form>

I found a python code where this html is rendered

class Database(http.Controller):

    def _render_template(self, **d):
        d.setdefault('manage',True)
        d['insecure'] = odoo.tools.config.verify_admin_password('admin')
        d['list_db'] = odoo.tools.config['list_db']
        d['langs'] = odoo.service.db.exp_list_lang()
        d['countries'] = odoo.service.db.exp_list_countries()
        d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
            d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("database_manager.html").render(d)

Should I modify this code in order to use another template? Or is there another more appropriate solution?

Is modifying the original code directly in the web module the only way to achieve this? Is there a way to change all this behaviour by inheriting the web module?

Body:
Yes, you would need to overwrite the _render_template method of the web module.
And also you would need to create your own HTML template for that and pass it for the rendering.

from odoo.addons.web.controllers.main import db_monodb, Database as DB, env
import jinja2

loader = jinja2.PackageLoader('odoo.addons.your_custom_module_name', "views")
env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = json.dumps

class Database(DB):

def _render_template(self, **d):
    d.setdefault('manage',True)
    d['insecure'] = odoo.tools.config['admin_passwd'] == 'admin'
    d['list_db'] = odoo.tools.config['list_db']
    d['langs'] = odoo.service.db.exp_list_lang()
    d['countries'] = odoo.service.db.exp_list_countries()
    d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("your_html_template_file_name.html").render(d)

This is an example from v10. You can just copy and paste the method from the Odoo module of the version you are working on.


来源: stackexchange

问:
Working with Azure notification hub using IONIC 3
We are currently using azure notification hub which allows us to work with both APN and GCM/FCM. Push notification functionality works properly with our current native apps (both android and iOS).

Now we are developing new apps using IONIC 3 and now trying to implement push notification in the same. There are many articles we have gone through. Some of them are using either ionic 1 or ionic 2. Few are using deprecated packages which are not supported on IONIC 3.

Backend developers have used the variant where the notification hub is the central point for device registrations. Devices are registered with the notification hub directly, rather than through our back-end. The first thing we are trying to achieve is registering our devices with notification hub when app is installed on device and running it for the first time. We are not finding a way to do it. We tried using couple of packages available but it did not work. We already have created project in firebase. Offical website has tutorial for all applications excpet ionic/cordova. Any suggestions will be helpful for implementing it.

答:
I created an Ionic 3 sample in the Azure Notification Hubs Samples repository a few months ago. It uses a third-party Cordova plugin to manage registration. The plugin is active, I've made a couple of contributions and they were accepted by the plugin author.

I'm working on an Ionic 4 sample, which I'll publish in the same repo, but Capacitor has a problem with the Cordova plugin and I've not spent enough time trying to figure it out. I'll try to do so soon.

ContentLicense: CC BY-SA 4.0


问:
RequestMapping cannot be resolved to a type
I'm just starting to study Spring Boot. I installed STS and created an application with Web + JPA + MySQL + DevTools + Security. When I'm creating my Controller and I note it with @RequestMapping, STS says RequestMapping can not be resolved to a type.

```<code>import org.springframework.stereotype.Controller;

@Controller
public class TestController {

    @RequestMapping("/test")
    public String test() {
        return "test";
    }

}
</code>```

EDIT

My pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

```<code><groupId>com.heart</groupId>
<artifactId>echocardiogram</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>echocardiogram</name>
<description>Echocardiogram Management System</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

How do I solve this?

答:
**You should add RequestMethodType as like GET/ POST/ PUT/ DELETE.**Here we use get method for return something</p>

```<code>@Controller
public class TestController {
    @RequestMapping(value="/test",method=RequestMethod.GET)
    public String test() {
        return "test";
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm just starting to study Spring Boot. I installed STS and created an application with Web + JPA + MySQL + DevTools + Security. When I'm creating my Controller and I note it with @RequestMapping, STS says RequestMapping can not be resolved to a type.

import org.springframework.stereotype.Controller;

@Controller
public class TestController {

    @RequestMapping("/test")
    public String test() {
        return "test";
    }

}

EDIT

My pom.xml

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

<groupId>com.heart</groupId>
<artifactId>echocardiogram</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>echocardiogram</name>
<description>Echocardiogram Management System</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

How do I solve this?

Body:
**You should add RequestMethodType as like GET/ POST/ PUT/ DELETE.**Here we use get method for return something

@Controller
public class TestController {
    @RequestMapping(value="/test",method=RequestMethod.GET)
    public String test() {
        return "test";
    }
}


问:
Returning libconfig class Setting object reference from function
I'm trying to use libconfig library to parse variables from an external configuration file.

On libconfig site it says: The class Config represents a configuration, and the class Setting represents a configuration setting. Note that by design, neither of these classes provides a public copy constructor or assignment operator. Therefore, instances of these classes may only be passed between functions via references or pointers.

I'm having difficulty creating a function that will return a Setting class reference (From my understanding returning reference to local object is frowned upon. But I have no idea how to declare a global reference given limitation above). At the bottom I have attached snippet of my attempt at coding this, however they are not working. I'm new to C++ and currently reading a textbook on it, but I'm still shaky on my handling of reference and pointer. I would appreciate if anyone can shed some light into what I'm doing wrong.

config.cfg

```<code>A=
{
  min = 3;
}
</code>```

Code

```<code>libconfig::Setting& GetKey(const char* filename, const char* method)
{
  libconfig::Config cfg;
  cfg.readFile(filename);
  libconfig::Setting &root = cfg.getRoot();
  libconfig::Setting &key = root[method];

  // How can I return key?
}

libconfig::Setting &key = GetKey("config.cfg","A");
key.lookupValue("min",min);
</code>```

答:
The values returned from the various methods in libconfig::Config are references to objects held within the libconfig::Config object.

It isn't clear from the documentation how long these references will be valid for but they will certainly be invalid when the cfg object is destroyed. They might be invalidated if you make changes to the cfg object but that isn't stated in the documentation.

Restructuring your code to the following should work:

```<code>libconfig::Setting& GetKey(libconfig::Config& cfg, const char* method)
{
  libconfig::Setting &root = cfg.getRoot();
  libconfig::Setting &key = root[method];

  // How can I return key?
}

libconfig::Config cfg;
cfg.readFile("config.cfg");
libconfig::Setting &key = GetKey(cfg,"A");
key.lookupValue("min",min);
</code>```

cfg is not not destroyed until after you stop using key so you shouldn't get dangling references.

Body:
I'm trying to use libconfig library to parse variables from an external configuration file.

On libconfig site it says: The class Config represents a configuration, and the class Setting represents a configuration setting. Note that by design, neither of these classes provides a public copy constructor or assignment operator. Therefore, instances of these classes may only be passed between functions via references or pointers.

I'm having difficulty creating a function that will return a Setting class reference (From my understanding returning reference to local object is frowned upon. But I have no idea how to declare a global reference given limitation above). At the bottom I have attached snippet of my attempt at coding this, however they are not working. I'm new to C++ and currently reading a textbook on it, but I'm still shaky on my handling of reference and pointer. I would appreciate if anyone can shed some light into what I'm doing wrong.

config.cfg

A=
{
  min = 3;
}

Code

libconfig::Setting& GetKey(const char* filename, const char* method)
{
  libconfig::Config cfg;
  cfg.readFile(filename);
  libconfig::Setting &root = cfg.getRoot();
  libconfig::Setting &key = root[method];

  // How can I return key?
}

libconfig::Setting &key = GetKey("config.cfg","A");
key.lookupValue("min",min);

Body:
The values returned from the various methods in libconfig::Config are references to objects held within the libconfig::Config object.

It isn't clear from the documentation how long these references will be valid for but they will certainly be invalid when the cfg object is destroyed. They might be invalidated if you make changes to the cfg object but that isn't stated in the documentation.

Restructuring your code to the following should work:

libconfig::Setting& GetKey(libconfig::Config& cfg, const char* method)
{
  libconfig::Setting &root = cfg.getRoot();
  libconfig::Setting &key = root[method];

  // How can I return key?
}

libconfig::Config cfg;
cfg.readFile("config.cfg");
libconfig::Setting &key = GetKey(cfg,"A");
key.lookupValue("min",min);

cfg is not not destroyed until after you stop using key so you shouldn't get dangling references.


问:
Singularity; get a github repo into the users home directory

Aim

The aim is to create a singularity container that installs some packages, then clones a custom package from a git repo and makes it. The user needs to have permission to do things with the custom package, and ideally it would sit in the home directory of the singularity user, but that seems more difficult than I had anticipated.

The singularity will be almost always launched as a shell, it is to contain a group of troublesome custom packages and generate results from them in a repeatable, sharable manner.

Problem

Cloning the git repo seems fine, but the only place I can put it that the user can even see it is /github_repo and it is always owned by root.

I can't get it to the user's home directory because during %post the variable $HOME does not seem to point to the users home directory, it points to /root, and object that are created then belong to root. In fact while /home does exist it is empty, it seems like the user doesn't exist yet.

I have tried cloning to /github_repo then adding

```<code>chown -R $USER /github_repo
chmod -R 766 /github_repo
</code>```

to %post.
The container can be built and run, and when it is running;

```<code>$ ls -lh /github_repo
ls: cannot access '/github_repo': Permission denied
total 0
d????????? ? ? ? ?           ? CorrectNameOfGithubFolder
-????????? ? ? ? ?           ? CorrectNameOfGithubFile
</code>```

So it can see the names of the files and folders, but not their permissions? I didn't even know that was possible. If I don't mess around with permissions in %post it is a perfectly normal file owned by root.

Recipe

This is what I have so far, you should find it builds and runs.
If you want to run it save the recipy as example.def then do

```<code>sudo singularity build example.sif example.def
singularity run --containall example.sif
</code>```

and then try

```<code>$ ls -lh /packages
</code>```

example.def

```<code>
BootStrap: docker
From: ubuntu:18.04

# commands on the host system
%setup
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    echo "${GREEN}~~~ Getting modified packages from github ~~~ ${NOCOLOUR}"
    export PACKAGES_TMP=/tmp/packages
    rm -fr $PACKAGES_TMP
    mkdir -p $PACKAGES_TMP
    git clone https://github.com/rootpy/rootpy-tutorials.git $PACKAGES_TMP
    cp -R ${PACKAGES_TMP} ${SINGULARITY_ROOTFS}

# get files from the host (but we dont need any)
%files

# what is done when the container is built
%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    # start
    echo "${GREEN}~~~ install apt packages ~~~ ${NOCOLOUR}"
    apt -y update
    # for fetching from repos if needed
    apt -y install git
    # for getting anything else from the net
    apt -y install wget
    # text editors
    apt -y install vim-tiny
    apt -y install nano
    # for making downloaded packages
    apt -y install make

    echo "${GREEN}~~~ Set up a .bashrc ~~~ ${NOCOLOUR}"
    BASHRC=/home/.bashrc
    touch $BASHRC
    echo "alias vim=vim.tiny\n" >> $BASHRC
    # will be called in run

    ## Not working???
    ## the /home/ directory appears empty
    # echo "${GREEN}~~~ Move packages to home dir ~~~ ${NOCOLOUR}"
    MY_HOME=$(ls -l /home/)
    echo in post home is $MY_HOME
    touch ~/test
    touch $HOME/test
    mkdir $HOME/test_dir
    # PACKAGES=$MY_HOME/packages/
    # mv /packages $PACKAGES

    echo "${GREEN}~~~ Give the user permission and control ~~~ ${NOCOLOUR}"
    # this bit does odd things
    PACKAGES=/packages
    chown -R $USER $PACKAGES
    chmod -R 766 $PACKAGES

    echo "${GREEN}~~~ Making the packages ~~~ ${NOCOLOUR}"
    # need to implement

# enviroment variabels instide the container
# sourced at run time not build time
%environment
    export PACKAGES=/packages/
    export BASHRC=/home/.bashrc

# this is executed when the contain is launched with
# singularity run example.sif
%runscript
    MY_HOME=$(ls -l /home/)
    echo at run home is $MY_HOME
    touch ~/runtest1
    touch $HOME/runtest2
    mkdir $HOME/runtest_dir
    ls -lh /
    ls -lh $HOME
    ls -lh $HOME/runtest_dir/
    # source the .bashrc
    echo $BASHRC
    /bin/bash --rcfile $BASHRC

# this would be executed just after build
%test
    echo I havent written any tests

# metadata
%labels
    Author ClumsyCat
    Version v1.0

%help
    to build me
    > sudo singularity build example.sif example.def
    to run me do
    > singularity run --containall --bind /my/out/dir/ example.sif
        the "--containall" flag prevents interactions with your system
        the "--bind /my/out/dir/" mounts a directory in your system
        this allows scripts in that directory to be accessed from the image
        and results from the image to persist in the directory
        It also allows the run script to call .bashrc
</code>```

答:
There are a few things going on here.

Unless there's something you really need on the host system, don't use %setup. It's running as root on the host OS and it's really easy to break things in ways you don't expect.

By default singularity mounts the running user's $HOME into the container, so anything you put in /home/... is going to be overwritten unless the user uses --no-home. Best practices recommend against installing to $HOME for this reason

All the steps in %post when you're referencing $USER is setting it to root, because that is the user when it is being run (sudo singularity build ...), so it's actually doing anything

chmod -R 664 - this is breaking your directories. You need the execute bit in order to actually access the directory, not just read

I've adjusted your sample definition file to work more as you intend. Comments explain why.

```<code>BootStrap: docker
From: ubuntu:18.04

%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    PACKAGES=/packages

    # give all files 774 and directories 775 by default
    umask 002

    # start
    echo "${GREEN}~~~ install apt packages ~~~ ${NOCOLOUR}"
    # install everything at once and use apt-get for non-interactive installs
    apt-get -y update && apt-get install -y git wget vim-tiny nano make

    # create a symlink to vim instead of an alias
    ln -s $(which vim.tiny) /usr/local/bin/vim

    echo "${GREEN}~~~ Getting modified packages from github ~~~ ${NOCOLOUR}"
    # git clone in %post instead of %setup
    mkdir $PACKAGES
    cd $PACKAGES
    git clone https://github.com/rootpy/rootpy-tutorials.git

    echo "${GREEN}~~~ Making the packages ~~~ ${NOCOLOUR}"
    # need to implement
    echo do something here

%environment
    export PACKAGES=/packages

%runscript
    echo I am $(whoami)
    echo

    cd $PACKAGES
    echo I am in $PWD
    ls -la --color=auto
    echo

    echo vim is: $(which vim)

</code>```

Running singularity run --containall example.sif gives:

```<code>I am tsnowlan

I am in /packages
total 0
drwxrwxr-x 3 root     root      39 May 28 12:23 .
drwxr-xr-x 1 tsnowlan tsnowlan  60 May 28 12:24 ..
drwxrwxr-x 6 root     root     117 May 28 12:23 rootpy-tutorials

vim is: /usr/local/bin/vim
</code>```

Body:
Aim

The aim is to create a singularity container that installs some packages, then clones a custom package from a git repo and makes it. The user needs to have permission to do things with the custom package, and ideally it would sit in the home directory of the singularity user, but that seems more difficult than I had anticipated.

The singularity will be almost always launched as a shell, it is to contain a group of troublesome custom packages and generate results from them in a repeatable, sharable manner.

Problem

Cloning the git repo seems fine, but the only place I can put it that the user can even see it is /github_repo and it is always owned by root.

I can't get it to the user's home directory because during %post the variable $HOME does not seem to point to the users home directory, it points to /root, and object that are created then belong to root. In fact while /home does exist it is empty, it seems like the user doesn't exist yet.

I have tried cloning to /github_repo then adding

chown -R $USER /github_repo
chmod -R 766 /github_repo

to %post.
The container can be built and run, and when it is running;

$ ls -lh /github_repo
ls: cannot access '/github_repo': Permission denied
total 0
d????????? ? ? ? ?           ? CorrectNameOfGithubFolder
-????????? ? ? ? ?           ? CorrectNameOfGithubFile

So it can see the names of the files and folders, but not their permissions? I didn't even know that was possible. If I don't mess around with permissions in %post it is a perfectly normal file owned by root.

Recipe

This is what I have so far, you should find it builds and runs.
If you want to run it save the recipy as example.def then do

sudo singularity build example.sif example.def
singularity run --containall example.sif

and then try

$ ls -lh /packages

example.def

BootStrap: docker
From: ubuntu:18.04

# commands on the host system
%setup
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    echo "${GREEN}~~~ Getting modified packages from github ~~~ ${NOCOLOUR}"
    export PACKAGES_TMP=/tmp/packages
    rm -fr $PACKAGES_TMP
    mkdir -p $PACKAGES_TMP
    git clone https://github.com/rootpy/rootpy-tutorials.git $PACKAGES_TMP
    cp -R ${PACKAGES_TMP} ${SINGULARITY_ROOTFS}

# get files from the host (but we dont need any)
%files

# what is done when the container is built
%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    # start
    echo "${GREEN}~~~ install apt packages ~~~ ${NOCOLOUR}"
    apt -y update
    # for fetching from repos if needed
    apt -y install git
    # for getting anything else from the net
    apt -y install wget
    # text editors
    apt -y install vim-tiny
    apt -y install nano
    # for making downloaded packages
    apt -y install make

    echo "${GREEN}~~~ Set up a .bashrc ~~~ ${NOCOLOUR}"
    BASHRC=/home/.bashrc
    touch $BASHRC
    echo "alias vim=vim.tiny\n" >> $BASHRC
    # will be called in run

    ## Not working???
    ## the /home/ directory appears empty
    # echo "${GREEN}~~~ Move packages to home dir ~~~ ${NOCOLOUR}"
    MY_HOME=$(ls -l /home/)
    echo in post home is $MY_HOME
    touch ~/test
    touch $HOME/test
    mkdir $HOME/test_dir
    # PACKAGES=$MY_HOME/packages/
    # mv /packages $PACKAGES

    echo "${GREEN}~~~ Give the user permission and control ~~~ ${NOCOLOUR}"
    # this bit does odd things
    PACKAGES=/packages
    chown -R $USER $PACKAGES
    chmod -R 766 $PACKAGES

    echo "${GREEN}~~~ Making the packages ~~~ ${NOCOLOUR}"
    # need to implement

# enviroment variabels instide the container
# sourced at run time not build time
%environment
    export PACKAGES=/packages/
    export BASHRC=/home/.bashrc

# this is executed when the contain is launched with
# singularity run example.sif
%runscript
    MY_HOME=$(ls -l /home/)
    echo at run home is $MY_HOME
    touch ~/runtest1
    touch $HOME/runtest2
    mkdir $HOME/runtest_dir
    ls -lh /
    ls -lh $HOME
    ls -lh $HOME/runtest_dir/
    # source the .bashrc
    echo $BASHRC
    /bin/bash --rcfile $BASHRC

# this would be executed just after build
%test
    echo I havent written any tests

# metadata
%labels
    Author ClumsyCat
    Version v1.0

%help
    to build me
    > sudo singularity build example.sif example.def
    to run me do
    > singularity run --containall --bind /my/out/dir/ example.sif
        the "--containall" flag prevents interactions with your system
        the "--bind /my/out/dir/" mounts a directory in your system
        this allows scripts in that directory to be accessed from the image
        and results from the image to persist in the directory
        It also allows the run script to call .bashrc

Body:
There are a few things going on here.

Unless there's something you really need on the host system, don't use %setup. It's running as root on the host OS and it's really easy to break things in ways you don't expect.

By default singularity mounts the running user's $HOME into the container, so anything you put in /home/... is going to be overwritten unless the user uses --no-home. Best practices recommend against installing to $HOME for this reason

All the steps in %post when you're referencing $USER is setting it to root, because that is the user when it is being run (sudo singularity build ...), so it's actually doing anything

chmod -R 664 - this is breaking your directories. You need the execute bit in order to actually access the directory, not just read

I've adjusted your sample definition file to work more as you intend. Comments explain why.

BootStrap: docker
From: ubuntu:18.04

%post
    # make print colour #
    GREEN='\033[0;32m'
    NOCOLOUR='\033[0m'
    PACKAGES=/packages

    # give all files 774 and directories 775 by default
    umask 002

    # start
    echo "${GREEN}~~~ install apt packages ~~~ ${NOCOLOUR}"
    # install everything at once and use apt-get for non-interactive installs
    apt-get -y update && apt-get install -y git wget vim-tiny nano make

    # create a symlink to vim instead of an alias
    ln -s $(which vim.tiny) /usr/local/bin/vim

    echo "${GREEN}~~~ Getting modified packages from github ~~~ ${NOCOLOUR}"
    # git clone in %post instead of %setup
    mkdir $PACKAGES
    cd $PACKAGES
    git clone https://github.com/rootpy/rootpy-tutorials.git

    echo "${GREEN}~~~ Making the packages ~~~ ${NOCOLOUR}"
    # need to implement
    echo do something here

%environment
    export PACKAGES=/packages

%runscript
    echo I am $(whoami)
    echo

    cd $PACKAGES
    echo I am in $PWD
    ls -la --color=auto
    echo

    echo vim is: $(which vim)

Running singularity run --containall example.sif gives:

I am tsnowlan

I am in /packages
total 0
drwxrwxr-x 3 root     root      39 May 28 12:23 .
drwxr-xr-x 1 tsnowlan tsnowlan  60 May 28 12:24 ..
drwxrwxr-x 6 root     root     117 May 28 12:23 rootpy-tutorials

vim is: /usr/local/bin/vim


问:
View package documentation locally in a browser
I want to see locally how my package documentation will look.  That is, I want to see the same kind of thing you see on godoc.org, but locally.

I have a simple example folder locally, but I can't get it to work.  It correctly outputs text documentation:

```<code>~/code/go/gonotes (master) $ godoc .
PACKAGE DOCUMENTATION

package gonotes
    import "."

FUNCTIONS

func Blah()
    Here is header

    Blah is function being use to test:

    - go documentation
    - blah like things

    It is nice
</code>```

But if I run godoc -http=:6060, and navigate to http://localhost:6060/, I see essentially the same content I'd see on the golang.com homepage.  http://localhost:6060/gonotes displays

```<code>lstat $GOROOT/gonotes: no such file or directory
</code>```

Am I misunderstanding how the -http works?  Is there any way to preview the http version of my docs locally?

UPDATE

I was able to get it to appear by copying the files into src/gonotes and then running:

```<code>GOPATH=/Users/jonah/code/go/gonotes godoc -http=:6060
</code>```

so that the actual files were available at /Users/jonah/code/go/gonotes/src/gonotes.

This has the side effect of not showing any of the Third part libs installed in my default GOPATH, so I'd still like to find a solution that just allows me to add the current directory, as is, without adding src/curdir to it, and still have it show up.

答:
In GOPATH mode

godoc -http will serve doc of all available packages, including the standard library. Worry not, your own packages are amongst them, just look again. As a shortcut, just type http://localhost:6060/pkg/your/package.

In module-aware mode

GOPATH and modules are mutually exclusive, see Go Modules does not recognize files under GOPATH. The godoc tool is not module-aware, and it is being deprecated (see deprecation warning), so for now if you want to see your package docs of modules locally in godoc, you have to resort to putting their sources in an src folder.

"Workaround" for seeing docs of module's:

Put the repo in a folder like /some/folder/src

Start godocs with godoc -goroot=/some/folder -http=:6060

See related issue: support Go modules

Also groups discussion: Is the go 1.11 godoc tool 'module-aware'?

Body:
I want to see locally how my package documentation will look.  That is, I want to see the same kind of thing you see on godoc.org, but locally.

I have a simple example folder locally, but I can't get it to work.  It correctly outputs text documentation:

~/code/go/gonotes (master) $ godoc .
PACKAGE DOCUMENTATION

package gonotes
    import "."

FUNCTIONS

func Blah()
    Here is header

    Blah is function being use to test:

    - go documentation
    - blah like things

    It is nice

But if I run godoc -http=:6060, and navigate to http://localhost:6060/, I see essentially the same content I'd see on the golang.com homepage.  http://localhost:6060/gonotes displays

lstat $GOROOT/gonotes: no such file or directory

Am I misunderstanding how the -http works?  Is there any way to preview the http version of my docs locally?

UPDATE

I was able to get it to appear by copying the files into src/gonotes and then running:

GOPATH=/Users/jonah/code/go/gonotes godoc -http=:6060

so that the actual files were available at /Users/jonah/code/go/gonotes/src/gonotes.

This has the side effect of not showing any of the Third part libs installed in my default GOPATH, so I'd still like to find a solution that just allows me to add the current directory, as is, without adding src/curdir to it, and still have it show up.


问:
How to fix: Required request body is missing: [org.springframework.http.converter.HttpMessageNotReadableException:]
I am updating a boolean column on my database for approving customer accounts via an angular front-end button. Once I send my request, my controller throws the Resolved [org.springframework.http.converter.HttpMessageNotReadableException:Required request body is missing: error. Have struggled debugging it and would appreciate some guidance on this.

My code so far is as follows:

controller:

```<code>@RequestMapping(value = "/customers/afisapprove", method =
RequestMethod.POST)
public ResponseEntity<?> updCustAfisStatus(@RequestBody Customer
customer) throws Exception {
    try {
        System.out.println("account no##" +
customer.getAccountNumber());
        System.out.println("afis no##" +
customer.getAfisStatus());
        System.out.println("afis id##" + customer.getId());

        int approveCust =
customerService.approveAfisCustomer(customer.isActive());

        // begin saving audit trail
        auditTrail = new AuditTrail((customer.getCreatedBy()), "Approved Customer " + customer.getFullName(), date,
                "Approve Customer");
        auditTrailService.saveAuditTrail(auditTrail);
        System.out.println("approved##" + approveCust);
        if (approveCust > 0) {
            // int trash = customerService.trashAfisBio(customer.getId());
            // if(trash <= 0 ) {
            // return new ResponseEntity<>(new CustomResponse(CustomResponse.APIV,
            // 200,false,
            // "failed to trash raw images"),HttpStatus.OK);
            // }
            return new ResponseEntity<>(
                    new CustomResponse(CustomResponse.APIV, 200, true, "customer approved successfully"),
                    HttpStatus.OK);

        }
        return new ResponseEntity<>(
                new CustomResponse(CustomResponse.APIV, 200, false, "failed to approve customer"), HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(
                new CustomResponse(CustomResponse.APIV, 200, false, "Server error processing request"),
                HttpStatus.OK);
    }
}
</code>```

entity class:

```<code>@Entity
@Table(name="Customerr")
public class Customer extends BaseModel implements Serializable{

    private static final long serialVersionUID = 1L;

    @Column(name="account_number")
    private String accountNumber;

    @Column(name="teller_id")
    private String tellerId;

    @Column(name="active")
    private boolean active=false;

    @Column(name="branchId")
    private String branchId;

    @Column(name="dateOfBirth")
    private String dateOfBirth;

    @Column(name ="emailAddress")
    private String emailAddress;

    @Column(name="fullName")
    private String fullName;

    @Column(name="gender")
    private String gender;

    @Column(name="idNumber")
    private String idNumber;

    @Column(name="phoneNumber")
    private String phoneNumber;

    @Column(name="postalAddress")
    private String postalAddress;

    @Column(name="postalCode")
    private String postalCode;

    @Column(name="postalTown")
    private String postalTown;

    @Column(name="created_on",columnDefinition="datetime default getDate()")
    private Date createdOn;

    @Column(name="afisid")
    private String pbuno;

    @Column(name="userProfile",columnDefinition="varchar(max)")
    private String profilePic;

    @Column(name="verified")
    private String approved;

    @Column(name="verified_by")
    private int approvedBy;

    @Column(name="created_by", nullable = false)
    private int createdBy;

    @Column(name="verified_on")
    private Date approvedOn;

    @Column(name="afis_status")
    private String afisStatus;

    @OneToMany(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name="customer_id")
    private List<CustomerBio> bios;

    @OneToMany(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name="customer_id")
    private List<RawImages> raws;

    public Customer() {
        super();

    }

    public Customer(String accountNumber, String tellerId, boolean active, String branchId, String dateOfBirth, String emailAddress,
            String fullName, String gender, String idNumber, String phoneNumber, String postalAddress,
            String postalCode, String postalTown, Date createdOn, String pbuno, String profilePic, String approved,
            int approvedBy, Date approvedOn, List<CustomerBio> bios,String afisStatus,List<RawImages> raws,int createdBy) {
        super();
        this.tellerId = tellerId;
        this.accountNumber = accountNumber;
        this.active = active;
        this.branchId = branchId;
        this.dateOfBirth = dateOfBirth;
        this.emailAddress = emailAddress;
        this.fullName = fullName;
        this.gender = gender;
        this.idNumber = idNumber;
        this.phoneNumber = phoneNumber;
        this.postalAddress = postalAddress;
        this.postalCode = postalCode;
        this.postalTown = postalTown;
        this.createdOn = createdOn;
        this.pbuno = pbuno;
        this.profilePic = profilePic;
        this.approved = approved;
        this.approvedBy = approvedBy;
        this.approvedOn = approvedOn;
        this.bios = bios;
        this.afisStatus=afisStatus;
        this.raws=raws;
        this.createdBy=createdBy;
    }

    public int getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(int createdBy) {
        this.createdBy = createdBy;
    }

    public String getAfisStatus() {
        return afisStatus;
    }

    public void setAfisStatus(String afisStatus) {
        this.afisStatus = afisStatus;
    }

    public String getApproved() {
        return approved;
    }

    public void setApproved(String approved) {
        this.approved = approved;
    }

    public int getApprovedBy() {
        return approvedBy;
    }

    public void setApprovedBy(int approvedBy) {
        this.approvedBy = approvedBy;
    }

    public Date getApprovedOn() {
        return approvedOn;
    }

    public void setApprovedOn(Date approvedOn) {
        this.approvedOn = approvedOn;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public String getTellerId() {
        return tellerId;
    }

    public void setTellerRef(String tellerId) {
        this.tellerId = tellerId;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public String getBranchId() {
        return branchId;
    }

    public void setBranchId(String branchId) {
        this.branchId = branchId;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getPostalAddress() {
        return postalAddress;
    }

    public void setPostalAddress(String postalAddress) {
        this.postalAddress = postalAddress;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getPostalTown() {
        return postalTown;
    }

    public void setPostalTown(String postalTown) {
        this.postalTown = postalTown;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

//    @PrePersist
    public void setCreatedOn() {
        this.createdOn = new Date();
    }

//    public List<CustomerBio> getBios() {
//        return bios;
//    }
//
//    public List<RawImages> getRaws() {
//        return raws;
//    }
//
//    public void addBio(CustomerBio bio) {
//        bio.setCustomer(this);
//        bios.add(bio);
//    }
//
//    public void addRaw(RawImages raw) {
//        raw.setCustomer(this);
//        raws.add(raw);
//    }

    public String getPbuno() {
        return pbuno;
    }

    public void setPbuno(String pbuno) {
        this.pbuno = pbuno;
    }

    public int getColumnCount() {
        return 7;
    }

    public String getProfilePic() {
        return profilePic;
    }

    public void setProfilePic(String profilePic) {
        this.profilePic = profilePic;
    }

    @Override
    public String toString() {
        return "Customer{" + "accountNumber=" + accountNumber + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + '}';
    }
}
</code>```

json:

```<code>       {
            "Id": 13,
            "name": "KABALIISA SCOVIA",
            "afisid": "PBU433369",
            "active": false,
            "branchId": "1",
            "dateOfBirth": "2019-03-07",
            "emailAddress": "johndoe@gmail.com",
            "fullName": "Nelson",
            "gender": "Male",
            "idNumber": "90785634",
            "phoneNumber": "0721234567",
            "postalAddress": "8445",
            "postalCode": "00200",
            "postalTown": "Mombasa",
            "userProfile": "",
            "createdBy": 0
        },
</code>```

service:

```<code>public int approveAfisCustomer(boolean active) {
        // TODO Auto-generated method stub
        return Customerrepository.approveAfisCustomer(active);
    }
</code>```

I really don't know what I am doing wrong. How i can fix it and understand the cause of the error?

答:
In your posted JSON, the following attributes doesn't matched with the @RequestBody Customer .Change accordingly

```<code>  {
            "Id": 13,
            "name": "KABALIISA SCOVIA",
            "afisid": "PBU433369",

            "userProfile": "",

        },
</code>```

Body:
I am updating a boolean column on my database for approving customer accounts via an angular front-end button. Once I send my request, my controller throws the Resolved [org.springframework.http.converter.HttpMessageNotReadableException:Required request body is missing: error. Have struggled debugging it and would appreciate some guidance on this.

My code so far is as follows:

controller:

@RequestMapping(value = "/customers/afisapprove", method =
RequestMethod.POST)
public ResponseEntity<?> updCustAfisStatus(@RequestBody Customer
customer) throws Exception {
    try {
        System.out.println("account no##" +
customer.getAccountNumber());
        System.out.println("afis no##" +
customer.getAfisStatus());
        System.out.println("afis id##" + customer.getId());

        int approveCust =
customerService.approveAfisCustomer(customer.isActive());

        // begin saving audit trail
        auditTrail = new AuditTrail((customer.getCreatedBy()), "Approved Customer " + customer.getFullName(), date,
                "Approve Customer");
        auditTrailService.saveAuditTrail(auditTrail);
        System.out.println("approved##" + approveCust);
        if (approveCust > 0) {
            // int trash = customerService.trashAfisBio(customer.getId());
            // if(trash <= 0 ) {
            // return new ResponseEntity<>(new CustomResponse(CustomResponse.APIV,
            // 200,false,
            // "failed to trash raw images"),HttpStatus.OK);
            // }
            return new ResponseEntity<>(
                    new CustomResponse(CustomResponse.APIV, 200, true, "customer approved successfully"),
                    HttpStatus.OK);

        }
        return new ResponseEntity<>(
                new CustomResponse(CustomResponse.APIV, 200, false, "failed to approve customer"), HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(
                new CustomResponse(CustomResponse.APIV, 200, false, "Server error processing request"),
                HttpStatus.OK);
    }
}

entity class:

@Entity
@Table(name="Customerr")
public class Customer extends BaseModel implements Serializable{

    private static final long serialVersionUID = 1L;

    @Column(name="account_number")
    private String accountNumber;

    @Column(name="teller_id")
    private String tellerId;

    @Column(name="active")
    private boolean active=false;

    @Column(name="branchId")
    private String branchId;

    @Column(name="dateOfBirth")
    private String dateOfBirth;

    @Column(name ="emailAddress")
    private String emailAddress;

    @Column(name="fullName")
    private String fullName;

    @Column(name="gender")
    private String gender;

    @Column(name="idNumber")
    private String idNumber;

    @Column(name="phoneNumber")
    private String phoneNumber;

    @Column(name="postalAddress")
    private String postalAddress;

    @Column(name="postalCode")
    private String postalCode;

    @Column(name="postalTown")
    private String postalTown;

    @Column(name="created_on",columnDefinition="datetime default getDate()")
    private Date createdOn;

    @Column(name="afisid")
    private String pbuno;

    @Column(name="userProfile",columnDefinition="varchar(max)")
    private String profilePic;

    @Column(name="verified")
    private String approved;

    @Column(name="verified_by")
    private int approvedBy;

    @Column(name="created_by", nullable = false)
    private int createdBy;

    @Column(name="verified_on")
    private Date approvedOn;

    @Column(name="afis_status")
    private String afisStatus;

    @OneToMany(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name="customer_id")
    private List<CustomerBio> bios;

    @OneToMany(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name="customer_id")
    private List<RawImages> raws;

    public Customer() {
        super();

    }

    public Customer(String accountNumber, String tellerId, boolean active, String branchId, String dateOfBirth, String emailAddress,
            String fullName, String gender, String idNumber, String phoneNumber, String postalAddress,
            String postalCode, String postalTown, Date createdOn, String pbuno, String profilePic, String approved,
            int approvedBy, Date approvedOn, List<CustomerBio> bios,String afisStatus,List<RawImages> raws,int createdBy) {
        super();
        this.tellerId = tellerId;
        this.accountNumber = accountNumber;
        this.active = active;
        this.branchId = branchId;
        this.dateOfBirth = dateOfBirth;
        this.emailAddress = emailAddress;
        this.fullName = fullName;
        this.gender = gender;
        this.idNumber = idNumber;
        this.phoneNumber = phoneNumber;
        this.postalAddress = postalAddress;
        this.postalCode = postalCode;
        this.postalTown = postalTown;
        this.createdOn = createdOn;
        this.pbuno = pbuno;
        this.profilePic = profilePic;
        this.approved = approved;
        this.approvedBy = approvedBy;
        this.approvedOn = approvedOn;
        this.bios = bios;
        this.afisStatus=afisStatus;
        this.raws=raws;
        this.createdBy=createdBy;
    }

    public int getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(int createdBy) {
        this.createdBy = createdBy;
    }

    public String getAfisStatus() {
        return afisStatus;
    }

    public void setAfisStatus(String afisStatus) {
        this.afisStatus = afisStatus;
    }

    public String getApproved() {
        return approved;
    }

    public void setApproved(String approved) {
        this.approved = approved;
    }

    public int getApprovedBy() {
        return approvedBy;
    }

    public void setApprovedBy(int approvedBy) {
        this.approvedBy = approvedBy;
    }

    public Date getApprovedOn() {
        return approvedOn;
    }

    public void setApprovedOn(Date approvedOn) {
        this.approvedOn = approvedOn;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public String getTellerId() {
        return tellerId;
    }

    public void setTellerRef(String tellerId) {
        this.tellerId = tellerId;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public String getBranchId() {
        return branchId;
    }

    public void setBranchId(String branchId) {
        this.branchId = branchId;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getPostalAddress() {
        return postalAddress;
    }

    public void setPostalAddress(String postalAddress) {
        this.postalAddress = postalAddress;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    public String getPostalTown() {
        return postalTown;
    }

    public void setPostalTown(String postalTown) {
        this.postalTown = postalTown;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

//    @PrePersist
    public void setCreatedOn() {
        this.createdOn = new Date();
    }

//    public List<CustomerBio> getBios() {
//        return bios;
//    }
//
//    public List<RawImages> getRaws() {
//        return raws;
//    }
//
//    public void addBio(CustomerBio bio) {
//        bio.setCustomer(this);
//        bios.add(bio);
//    }
//
//    public void addRaw(RawImages raw) {
//        raw.setCustomer(this);
//        raws.add(raw);
//    }

    public String getPbuno() {
        return pbuno;
    }

    public void setPbuno(String pbuno) {
        this.pbuno = pbuno;
    }

    public int getColumnCount() {
        return 7;
    }

    public String getProfilePic() {
        return profilePic;
    }

    public void setProfilePic(String profilePic) {
        this.profilePic = profilePic;
    }

    @Override
    public String toString() {
        return "Customer{" + "accountNumber=" + accountNumber + ", fullName=" + fullName + ", dateOfBirth=" + dateOfBirth + '}';
    }
}

json:

       {
            "Id": 13,
            "name": "KABALIISA SCOVIA",
            "afisid": "PBU433369",
            "active": false,
            "branchId": "1",
            "dateOfBirth": "2019-03-07",
            "emailAddress": "johndoe@gmail.com",
            "fullName": "Nelson",
            "gender": "Male",
            "idNumber": "90785634",
            "phoneNumber": "0721234567",
            "postalAddress": "8445",
            "postalCode": "00200",
            "postalTown": "Mombasa",
            "userProfile": "",
            "createdBy": 0
        },

service:

public int approveAfisCustomer(boolean active) {
        // TODO Auto-generated method stub
        return Customerrepository.approveAfisCustomer(active);
    }

I really don't know what I am doing wrong. How i can fix it and understand the cause of the error?

Body:
In your posted JSON, the following attributes doesn't matched with the @RequestBody Customer .Change accordingly

  {
            "Id": 13,
            "name": "KABALIISA SCOVIA",
            "afisid": "PBU433369",

            "userProfile": "",

        },


问:
How can i use the value to calculate? "10/10"
Hi i was wondering if i can make the value 10/10 and 90/100 in 4 different var so i can calculate the avarge?

I tried calling the var with innerHTML, but it doesn't seem to work.

This are the div's:

```<code><div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div>

</code>```

example: 10 + 90 / 10 + 100 => 90.9%. Any suggestion/ideas on how to become this solution?

答:
var matches = document.querySelectorAll(".course_eval_cell");

let up = 0;
let down = 0;

matches.forEach(function(fraction) {
  var divided = fraction.innerHTML.split("/");
  up += parseInt(divided[0]);
  down += parseInt(divided[1]);
});

console.log((up / down ) * 100 + "%");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div></code>```

Body:
Hi i was wondering if i can make the value 10/10 and 90/100 in 4 different var so i can calculate the avarge?

I tried calling the var with innerHTML, but it doesn't seem to work.

This are the div's:

10/10

90/100

example: 10 + 90 / 10 + 100 => 90.9%. Any suggestion/ideas on how to become this solution?

Body:
var matches = document.querySelectorAll(".course_eval_cell");

let up = 0;
let down = 0;

matches.forEach(function(fraction) {
  var divided = fraction.innerHTML.split("/");
  up += parseInt(divided[0]);
  down += parseInt(divided[1]);
});

console.log((up / down ) * 100 + "%");

<div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div>


问:
How do I get Doctrine class metadata for a test?
A coworker wants to mock the entity manager in a test. He has this code:

```<code>    ...
    $em = $this->createMock(EntityManager::class);
    $myRepository = new NewslettersStatisticSnapshotRepository(
        $em,
        NewslettersStatisticSnapshot::class
    );

    $em->method('getRepository')->willReturn($myRepository);
    ...
</code>```

... and when I run his test, I get this:

TypeError: Argument 2 passed to
  Doctrine\ORM\EntityRepository::__construct() must be an instance of
  Doctrine\ORM\Mapping\ClassMetadata, string given

How can I dig up metadata for this class?

答: We ended up just mocking the repository.</p>

Body:
A coworker wants to mock the entity manager in a test. He has this code:

    ...
    $em = $this->createMock(EntityManager::class);
    $myRepository = new NewslettersStatisticSnapshotRepository(
        $em,
        NewslettersStatisticSnapshot::class
    );

    $em->method('getRepository')->willReturn($myRepository);
    ...

... and when I run his test, I get this:

TypeError: Argument 2 passed to
  Doctrine\ORM\EntityRepository::__construct() must be an instance of
  Doctrine\ORM\Mapping\ClassMetadata, string given

How can I dig up metadata for this class?


问:
Impact of index on different columns while join
lets say we have two tables- table A and table B and both tables have 5 million records each. They have common fields, id and name. i want to check that what would be the impact of index if we apply on join field while joining the tables and what would be the impact of index on select column while joining the tables. below is query

```<code>select t1.name from table A t1 inner join table B t2 on t1.id=t2.id;
</code>```

on which field shall i create index in order to have faster result. shall i put index on id or name? please help

my expectation is if we put index on id column, then query will give result in shorter duration rather if we put index on name field.

looking for performance improvement

my expectation is if we put index on id column, then query will give result in shorter duration rather if we put index on name field.

答:
For this query:

```<code>select t1.name
from tableA t1 inner join
     tableB t2
     on t1.id = t2.id;
</code>```

I would expect the best index to be tableB(id).  This is the key used for the JOIN.

Under some circumstances, an index on tableA(id, name) might be the best alternative. This would be particularly true if tableA were much larger than tableB.

Body:
lets say we have two tables- table A and table B and both tables have 5 million records each. They have common fields, id and name. i want to check that what would be the impact of index if we apply on join field while joining the tables and what would be the impact of index on select column while joining the tables. below is query

select t1.name from table A t1 inner join table B t2 on t1.id=t2.id;

on which field shall i create index in order to have faster result. shall i put index on id or name? please help

my expectation is if we put index on id column, then query will give result in shorter duration rather if we put index on name field.

looking for performance improvement

my expectation is if we put index on id column, then query will give result in shorter duration rather if we put index on name field.

Body:
For this query:

select t1.name
from tableA t1 inner join
     tableB t2
     on t1.id = t2.id;

I would expect the best index to be tableB(id).  This is the key used for the JOIN.

Under some circumstances, an index on tableA(id, name) might be the best alternative. This would be particularly true if tableA were much larger than tableB.


问:
'If statements' in function are outputting too many characters based on while loop set duration
I am creating an encryptor for simple text files but am having trouble with the output.

Below I have provided code with random hashes I just came up with so the ones I have created can stay private (if that even matters). The if statements in the while loop produce way too many characters. I have tried setting a while loop with an iteration so that it doesn't run more than the amount of times that it needs to but nothing seems to work.

encryptor code

```<code>iteration = 0

def encryptor(to_encrypt):

    global iteration

    while iteration < len(to_encrypt):
        if "a" in to_encrypt:
            generated_hash.insert(to_encrypt.index("a"),"sdhf789HSjff9j")
        if "b" in to_encrypt:
            generated_hash.insert(to_encrypt.index("b"),"9hf98hJd7hg59h")
        if "c" in to_encrypt:
            generated_hash.insert(to_encrypt.index("c"),"kJShy48jJYUS24")
        iteration += 1

    return generated_hash

print("Enter data to encrypt")
to_encrypt = list(input())
generated_hash = []
hashvar = encryptor(to_encrypt)
print(hashvar)
</code>```

decryptor code

```<code>def decryptor(to_decrypt):

    while len(generated_response) < len(to_decrypt):
        if "sdhf789HSjff9j" in to_decrypt:
            generated_response.insert(to_decrypt.index("sdhf789HSjff9j"),"a")
        if "9hf98hJd7hg59h" in to_decrypt:
            generated_response.insert(to_decrypt.index("9hf98hJd7hg59h"),"b")
        if "kJShy48jJYUS24" in to_decrypt:
            generated_response.insert(to_decrypt.index("kJShy48jJYUS24"),"c")

    return generated_response

print("Enter encrypted data to decrypt")
to_decrypt = str(input())
generated_response = []
hashvar = decryptor(to_decrypt)
print(hashvar)
</code>```

If I were to enter my name "dylan" into the encryptor I would expect to recieve 5 hashes all correlating to the letters in my name. Instead I recieve many many hashes of duplicates of the letters in my name. When I put this in the decryptor, it seems to multiply even more and I get all the characters in my name, and only the characters in my name, but hundreds or even thousands of them in a random order. I will include an output of the encryptor and decryptor below for my name, "dylan".

Encryptor output for "dylan":

```<code>['IsDzQk2SHVgobRwiufSR', '08X4oPvziUZGmpttXuiT', 'IsDzQk2SHVgobRwiufSR', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'IsDzQk2SHVgobRwiufSR', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'IsDzQk2SHVgobRwiufSR', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'IsDzQk2SHVgobRwiufSR', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'r83WNsrpjlpEsMUzZq43', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', 'swAcOwEI5j6RNq7J7X2l']
</code>```

Decryptor output after putting in the encryptor output:

```<code>['a', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'a', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'n', 'n', 'a', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'n', 'n', 'a', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
</code>```

答:
So if I understand your goal correctly, you want to substitute all letters in a string with longer strings (e.g "sdhf789HSjff9j")? Besides that not being a good way to encrypt anything as it can be trivially defeated (just google breaking substitution cipher), your code has some problems.

Move all iteration counters inside of the function definitions

Initialize the results (i.e. generated_response, generated_hash) inside the functions

Iterate over your string via for char in to_encrypt:

The decryptor takes a string as an input via input() but you treat it as a list. This will treat each char of the input as a list item. Use ast.literal_eval(x) to import the string to a list if you really need this in your code. Be sure to understand why this is most likely dangerous

So below there is a simple fixed version, without the input of the encrypted text. I've replaced the substitution with a dict, to reduce the length of the if statement.

def encryptor(to_encrypt):
    generated_hash = []
    subst_encrypt = {
        "a": "sdhf789HSjff9j",
        "b": "9hf98hJd7hg59h",
        "c": "kJShy48jJYUS24",
    }
    for char in to_encrypt:
        if char in subst_encrypt:
            generated_hash.append(subst_encrypt[char])
    return generated_hash

to_encrypt = "abc"
hashvar = encryptor(to_encrypt)
print(hashvar)

def decryptor(to_decrypt):
    generated_response = []
    subst_decrypt = {
        "sdhf789HSjff9j": "a",
        "9hf98hJd7hg59h": "b",
        "kJShy48jJYUS24": "c",
    }
    for elem in to_decrypt:
        if elem in subst_decrypt:
            generated_response.append(subst_decrypt[elem])
    return generated_response

unhashed = decryptor(hashvar)
print(unhashed)
```

<p>For string <code>abc</code> this will return</p>

```['sdhf789HSjff9j', '9hf98hJd7hg59h', 'kJShy48jJYUS24']
['a', 'b', 'c']
```

Body:
I am creating an encryptor for simple text files but am having trouble with the output.

Below I have provided code with random hashes I just came up with so the ones I have created can stay private (if that even matters). The if statements in the while loop produce way too many characters. I have tried setting a while loop with an iteration so that it doesn't run more than the amount of times that it needs to but nothing seems to work.

encryptor code

iteration = 0

def encryptor(to_encrypt):

    global iteration

    while iteration < len(to_encrypt):
        if "a" in to_encrypt:
            generated_hash.insert(to_encrypt.index("a"),"sdhf789HSjff9j")
        if "b" in to_encrypt:
            generated_hash.insert(to_encrypt.index("b"),"9hf98hJd7hg59h")
        if "c" in to_encrypt:
            generated_hash.insert(to_encrypt.index("c"),"kJShy48jJYUS24")
        iteration += 1

    return generated_hash

print("Enter data to encrypt")
to_encrypt = list(input())
generated_hash = []
hashvar = encryptor(to_encrypt)
print(hashvar)

decryptor code

def decryptor(to_decrypt):

    while len(generated_response) < len(to_decrypt):
        if "sdhf789HSjff9j" in to_decrypt:
            generated_response.insert(to_decrypt.index("sdhf789HSjff9j"),"a")
        if "9hf98hJd7hg59h" in to_decrypt:
            generated_response.insert(to_decrypt.index("9hf98hJd7hg59h"),"b")
        if "kJShy48jJYUS24" in to_decrypt:
            generated_response.insert(to_decrypt.index("kJShy48jJYUS24"),"c")

    return generated_response

print("Enter encrypted data to decrypt")
to_decrypt = str(input())
generated_response = []
hashvar = decryptor(to_decrypt)
print(hashvar)

If I were to enter my name "dylan" into the encryptor I would expect to recieve 5 hashes all correlating to the letters in my name. Instead I recieve many many hashes of duplicates of the letters in my name. When I put this in the decryptor, it seems to multiply even more and I get all the characters in my name, and only the characters in my name, but hundreds or even thousands of them in a random order. I will include an output of the encryptor and decryptor below for my name, "dylan".

Encryptor output for "dylan":

['IsDzQk2SHVgobRwiufSR', '08X4oPvziUZGmpttXuiT', 'IsDzQk2SHVgobRwiufSR', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'IsDzQk2SHVgobRwiufSR', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'IsDzQk2SHVgobRwiufSR', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'IsDzQk2SHVgobRwiufSR', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', '08X4oPvziUZGmpttXuiT', 'swAcOwEI5j6RNq7J7X2l', 'r83WNsrpjlpEsMUzZq43', 'r83WNsrpjlpEsMUzZq43', 'omCcVZArJASFahZym6vj', 'swAcOwEI5j6RNq7J7X2l']

Decryptor output after putting in the encryptor output:

['a', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'd', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'y', 'n', 'l', 'l', 'a', 'y', 'n', 'l', 'n', 'a', 'y', 'n', 'l', 'y', 'a', 'y', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'l', 'a', 'a', 'l', 'n', 'l', 'n', 'a', 'a', 'n', 'l', 'l', 'a', 'n', 'n', 'a', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'n', 'n', 'a', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'n', 'n', 'a', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'n', 'n', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']

Body:
So if I understand your goal correctly, you want to substitute all letters in a string with longer strings (e.g "sdhf789HSjff9j")? Besides that not being a good way to encrypt anything as it can be trivially defeated (just google breaking substitution cipher), your code has some problems.

Move all iteration counters inside of the function definitions

Initialize the results (i.e. generated_response, generated_hash) inside the functions

Iterate over your string via for char in to_encrypt:

The decryptor takes a string as an input via input() but you treat it as a list. This will treat each char of the input as a list item. Use ast.literal_eval(x) to import the string to a list if you really need this in your code. Be sure to understand why this is most likely dangerous

So below there is a simple fixed version, without the input of the encrypted text. I've replaced the substitution with a dict, to reduce the length of the if statement.

def encryptor(to_encrypt):
    generated_hash = []
    subst_encrypt = {
        "a": "sdhf789HSjff9j",
        "b": "9hf98hJd7hg59h",
        "c": "kJShy48jJYUS24",
    }
    for char in to_encrypt:
        if char in subst_encrypt:
            generated_hash.append(subst_encrypt[char])
    return generated_hash

to_encrypt = "abc"
hashvar = encryptor(to_encrypt)
print(hashvar)

def decryptor(to_decrypt):
    generated_response = []
    subst_decrypt = {
        "sdhf789HSjff9j": "a",
        "9hf98hJd7hg59h": "b",
        "kJShy48jJYUS24": "c",
    }
    for elem in to_decrypt:
        if elem in subst_decrypt:
            generated_response.append(subst_decrypt[elem])
    return generated_response

unhashed = decryptor(hashvar)
print(unhashed)

For string abc this will return

['sdhf789HSjff9j', '9hf98hJd7hg59h', 'kJShy48jJYUS24']
['a', 'b', 'c']


问:
How to generate APN certificate so that it should handle to support both old as well as new application after ios app transfer
I have transferd my ios app from my account(AA) to client account(BB).for push notification in fire-base server we uploaded APN (private key) which is generated by AA. But now account is changed and also i am updating app with new account. So if i upload new APN generate from new account, older app will not support push notification. But however i read like " we can generate a APN which will support older and new app"

But how to achieve that..?

With old APN i tried to push notifn to new app which is signed/updated with new account i.e BB , notification is failing..

答:
If you are creating a new APNS certificate in (BB) account and you have to make your application live, in that case, you have to update application and firebase certificate with latest APNS.

Your existing application will have no impact, if you are creating new APNS certificate or not, it will work without any fail - until you update the APNS to Firebase server

Note: If you change Push notification certificate in backend server / Firebase server, your existing live application won't receive any push notification.


问:
Cumulative sum by bins in obiee
I want to generate a report in obiee , by grouping countries and showing there cumulative sum

I tried creating bins like for china I created a bin which contains singapore, taiwan and china. another bin for japan containing some countries. using pivot table i can show the sum of customers in a region by dates for these two bins. but when I need a cumulative sum for every bin it is giving weird values

Number of employee by region and date where china and japan are bins

```<code>           china  japan
</code>```

01-Nov-18       1  3

02-Nov-18       2         4

03-Nov-18       1   1

04-Nov-18   2   5

05-Nov-18   4   7

06-Nov-18   5   7

where as result i want( how can I achieve this)

```<code>     China    Japan
</code>```

01-Nov-18   1   3

02-Nov-18   3   7

03-Nov-18   4   8

04-Nov-18   6   13

05-Nov-18   10  20

06-Nov-18   15  27

答: Make a duplicate layer of the measure column. Click on the duplicated column and select the option 'Display as Running Sum'.</p>

Title: Cumulative sum by bins in obiee

Body:
I want to generate a report in obiee , by grouping countries and showing there cumulative sum

I tried creating bins like for china I created a bin which contains singapore, taiwan and china. another bin for japan containing some countries. using pivot table i can show the sum of customers in a region by dates for these two bins. but when I need a cumulative sum for every bin it is giving weird values

Number of employee by region and date where china and japan are bins

           china  japan

01-Nov-18       1  3

02-Nov-18       2         4

03-Nov-18       1   1

04-Nov-18   2   5

05-Nov-18   4   7

06-Nov-18   5   7

where as result i want( how can I achieve this)

     China    Japan

01-Nov-18   1   3

02-Nov-18   3   7

03-Nov-18   4   8

04-Nov-18   6   13

05-Nov-18   10  20

06-Nov-18   15  27


问:
Syntactic sugar in C/C++
I have been looking into Ruby and find its keywords "until" and "unless" very interesting. So I thought what was a good way to add similar keywords into C/C++. This is what I came up with:

```<code>#define until(x)    while(!(x))
#define unless(x)   if(!(x))
</code>```

I am looking for some suggestions on this. Can anyone suggest a better alternative?

Here is an example of a program that I wrote to illustrate what I intended to do:

```<code>#include <stdio.h>
#include <stdlib.h>

#define until(x)    while(!(x))
#define unless(x)   if(!(x))

unsigned int factorial(unsigned int n) {
    unsigned int fact=1, i;
    until ( n==0 )
        fact *= n--;
    return fact;
}

int main(int argc, char*argv[]) {
    unless (argc==2)
        puts("Usage: fact <num>");
    else {
        int n = atoi(argv[1]);
        if (n<0)
            puts("please give +ve number");
        else
            printf("factorial(%u) = %u\n",n,factorial(n));
    }
    return 0;
}
</code>```

It would be great if you could point me to some references for similar tricks that can be employed in C or C++.

答:
The way you did it seems to me the correct way to do it, if you're going to do it at all. Because the expansion of the macro is so similar to what you'd expect[1], I think it's valid to make the macro look like syntax (), rather than the usually recommended SCARY_UPPERCASE_MACROS() which are used to show that this code doesn't follow usual syntax and you should only use it carefully.

[1] The only flaw being the inability to declare variables, which is unlikely anyway, and likely to produce an error in the right place when used incorrectly, rather than doing something weird.

Furthermore, even small increases in readability are important, so being able to say until ( instead of while (! really does make it easier to read many loops. If the ending condition is more easily thought of as an exceptional condition (regardless of whether it is or not) writing the loop that way round makes it easier to read. So even though it is only syntactic sugar, I think there's reason to consider it.

However I don't think it's worth it. The benefit is small, since most programmers are used to reading if (! and the cost is real: Anyone reading the code will have to check whether this a macro, or a custom compiler, and whether or no it does what they think. And it may misleadingly make you think you can do things like i=5 unless xxxx;. Such little improvements, if widespread, would fragment the language, so often it's best to do things the standard way, and adopt improvements slowly.

However, it can be done well: the entirety of boost and tr1, especially the stuff done with templates to look like extensions to the library, involves extending C++ in various ways, many of which aren't adopted as they didn't seem worth it, but many of which have small or very widespread take-up because they made real improvements.

Title: Syntactic sugar in C/C++

Body:
I have been looking into Ruby and find its keywords "until" and "unless" very interesting. So I thought what was a good way to add similar keywords into C/C++. This is what I came up with:

#define until(x)    while(!(x))
#define unless(x)   if(!(x))

I am looking for some suggestions on this. Can anyone suggest a better alternative?

Here is an example of a program that I wrote to illustrate what I intended to do:

#include <stdio.h>
#include <stdlib.h>

#define until(x)    while(!(x))
#define unless(x)   if(!(x))

unsigned int factorial(unsigned int n) {
    unsigned int fact=1, i;
    until ( n==0 )
        fact *= n--;
    return fact;
}

int main(int argc, char*argv[]) {
    unless (argc==2)
        puts("Usage: fact <num>");
    else {
        int n = atoi(argv[1]);
        if (n<0)
            puts("please give +ve number");
        else
            printf("factorial(%u) = %u\n",n,factorial(n));
    }
    return 0;
}

It would be great if you could point me to some references for similar tricks that can be employed in C or C++.


问:
Populate Array With Data From RecordSet
I have a query which holds the data I need, but I need to get the data from the query in the format of

entity number - employee id

entity number - employee id

entity number - employee id

And so on...I tried to write my code to be the below, but I get a compile error of
 'Compile error:
Type mismatch'

This error is thrown on the &

What is the proper way to get data from a query set-up in the format I need?  Full picture, I am wanting to get the data from the query in the XXXX - XXXX format so I can use it in the body of an email I am generating in my VBA code.

```<code>Dim en() As String
Dim ei() As String
Set rs = db.OpenRecordset("qryData")
If Not (rs.BOF And rs.EOF) Then
rs.MoveLast
rs.MoveFirst
While (Not rs.EOF)
    en = en & vbCrLF & Space(7) & rs![public systems.entity number]
    ei = ei & vbCrLF & Space(7) & rs![public systems.employee id]
    rs.MoveNext
  Wend
End If
</code>```

答:
I am wanting to get the data from the query in the XXXX - XXXX format
  so I can use it in the body of an email

That's not an array, so use a string:

```<code>Dim rs As DAO.Recordset
Dim en As String
Dim ei As String

Set rs = CurrentDb.OpenRecordset("qryData")
If Not (rs.BOF And rs.EOF) Then
    rs.MoveLast
    rs.MoveFirst
    While Not rs.EOF
        en = en & vbCrLF & Space(7) & rs![public systems.entity number].Value
        ei = ei & vbCrLF & Space(7) & rs![public systems.employee id].Value
        rs.MoveNext
    Wend
End If
rs.Close
</code>```

Title: Populate Array With Data From RecordSet

Body:
I have a query which holds the data I need, but I need to get the data from the query in the format of

entity number - employee id

entity number - employee id

entity number - employee id

And so on...I tried to write my code to be the below, but I get a compile error of
 'Compile error:
Type mismatch'

This error is thrown on the &

What is the proper way to get data from a query set-up in the format I need?  Full picture, I am wanting to get the data from the query in the XXXX - XXXX format so I can use it in the body of an email I am generating in my VBA code.

Dim en() As String
Dim ei() As String
Set rs = db.OpenRecordset("qryData")
If Not (rs.BOF And rs.EOF) Then
rs.MoveLast
rs.MoveFirst
While (Not rs.EOF)
    en = en & vbCrLF & Space(7) & rs![public systems.entity number]
    ei = ei & vbCrLF & Space(7) & rs![public systems.employee id]
    rs.MoveNext
  Wend
End If

Body:
I am wanting to get the data from the query in the XXXX - XXXX format
  so I can use it in the body of an email

That's not an array, so use a string:

Dim rs As DAO.Recordset
Dim en As String
Dim ei As String

Set rs = CurrentDb.OpenRecordset("qryData")
If Not (rs.BOF And rs.EOF) Then
    rs.MoveLast
    rs.MoveFirst
    While Not rs.EOF
        en = en & vbCrLF & Space(7) & rs![public systems.entity number].Value
        ei = ei & vbCrLF & Space(7) & rs![public systems.employee id].Value
        rs.MoveNext
    Wend
End If
rs.Close


问:
Replace expression with macro using clang AST
I am looking to change the following code, with the help of the clang ast matcher.

```<code>foo(NUM << DEV_SHIFT | DEVICE);
</code>```

to

```<code>foo(ADDR(NUM, DEVICE));
</code>```

with

```<code>#define ADDR(a, b) (((a) << NUM_SHIFT) | (b))
</code>```

I have the following AST-matcher that seems to identify the code pretty well.

```<code>Finder->addMatcher(
       callExpr(hasArgument(
           0, binaryOperator(hasOperatorName("|"),
                             hasLHS(ignoringParenImpCasts(
                                 binaryOperator(hasOperatorName("<<")))))
                  .bind("replaceWithMacro"))),
       this);
</code>```

But I have a problem to understand how to write the check and the translation. I am currently stuck with this code:

```<code>void FirstCheckCheck::check(const MatchFinder::MatchResult &Result) {
  // FIXME: Add callback implementation.
  if (const auto MatchedDecl =
          Result.Nodes.getNodeAs<CallExpr>("replaceWithMacro")) {
    diag(MatchedDecl->getExprLoc(), "CallExp");
  } else if (const auto MatchedDecl =
                 Result.Nodes.getNodeAs<Expr>("replaceWithMacro")) {
    diag(MatchedDecl->getExprLoc(), "Expr");
    diag(MatchedDecl->getBeginLoc(), "BeginLOC");
    diag(MatchedDecl->getEndLoc(), "EndLOC");
  }

</code>```

I don't know how to extract the two variables as strings.
I was looking at the documentation for the Expr class (http://clang.llvm.org/doxygen/classclang_1_1Expr.html), but I couldn't find something useful.

If somebody could point me into the right direction it would be appreciated.

Add edit's.

答:
This is the solution that I am quite happy with. It is based on boq's suggestion from the comments. </p>

```<code>//===--- FirstCheckCheck.cpp - clang-tidy ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "FirstCheckCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace misc {

void FirstCheckCheck::registerMatchers(MatchFinder *Finder) {
  // FIXME: Add matchers.
  //
  Finder->addMatcher(
      callExpr(hasArgument(
          1,
          binaryOperator(
              hasOperatorName("|"),
              hasRHS(ignoringImplicit(
                  anyOf(declRefExpr().bind("moduleNum"), integerLiteral().bind(
                      "moduleNum")))),
              hasLHS(ignoringParens(
                  binaryOperator(hasOperatorName("<<"),
                                 hasLHS(ignoringImplicit(anyOf(
                                     declRefExpr().bind("deviceNum"),
                                     integerLiteral().bind("deviceNum"))))))))
              .bind("replaceWithMacro"))),
      this);
}

void FirstCheckCheck::check(const MatchFinder::MatchResult &Result) {
  // FIXME: Add callback implementation.
    std::string deviceNumString;
    std::string moduleNumString;
    std::string ReplacementText;

  if (const auto MatchedDecl =
          Result.Nodes.getNodeAs<Expr>("deviceNum")) {

    const LangOptions &Opts = getLangOpts();

    /* get device string */
    deviceNumString = Lexer::getSourceText(
        CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
        *Result.SourceManager, Opts);
  }
  /* ((uint16_t)(deviceNum << 8 | moduleNum)) */
  if (const auto MatchedDecl =
          Result.Nodes.getNodeAs<Expr>("moduleNum")) {

    const LangOptions &Opts = getLangOpts();

    moduleNumString = Lexer::getSourceText(
        CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
        *Result.SourceManager, Opts);
  }
  if (const auto MatchedDecl =
                 Result.Nodes.getNodeAs<Expr>("replaceWithMacro")) {
    const LangOptions &Opts = getLangOpts();

    ReplacementText = Lexer::getSourceText(
        CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
        *Result.SourceManager, Opts);

    std::string replacementString =
        "ADDR(" + deviceNumString + ", " + moduleNumString + ")";

    FixItHint Hint = FixItHint::CreateReplacement(
        MatchedDecl->getSourceRange(), replacementString);

    diag(MatchedDecl->getBeginLoc(), "Replace with ADDR() macro") << Hint;
  }

  /* diag(MatchedDecl->getLocation(), "insert 'awesome'", DiagnosticIDs::Note)
   */
  /*     << FixItHint::CreateInsertion(MatchedDecl->getLocation(), "awesome_");
   */
}

} // namespace misc
} // namespace tidy
} // namespace clang
</code>```

Body:
I am looking to change the following code, with the help of the clang ast matcher.

foo(NUM << DEV_SHIFT | DEVICE);

to

foo(ADDR(NUM, DEVICE));

with

#define ADDR(a, b) (((a) << NUM_SHIFT) | (b))

I have the following AST-matcher that seems to identify the code pretty well.

Finder->addMatcher(
       callExpr(hasArgument(
           0, binaryOperator(hasOperatorName("|"),
                             hasLHS(ignoringParenImpCasts(
                                 binaryOperator(hasOperatorName("<<")))))
                  .bind("replaceWithMacro"))),
       this);

But I have a problem to understand how to write the check and the translation. I am currently stuck with this code:

void FirstCheckCheck::check(const MatchFinder::MatchResult &Result) {
  // FIXME: Add callback implementation.
  if (const auto MatchedDecl =
          Result.Nodes.getNodeAs<CallExpr>("replaceWithMacro")) {
    diag(MatchedDecl->getExprLoc(), "CallExp");
  } else if (const auto MatchedDecl =
                 Result.Nodes.getNodeAs<Expr>("replaceWithMacro")) {
    diag(MatchedDecl->getExprLoc(), "Expr");
    diag(MatchedDecl->getBeginLoc(), "BeginLOC");
    diag(MatchedDecl->getEndLoc(), "EndLOC");
  }

I don't know how to extract the two variables as strings.
I was looking at the documentation for the Expr class (http://clang.llvm.org/doxygen/classclang_1_1Expr.html), but I couldn't find something useful.

If somebody could point me into the right direction it would be appreciated.

Add edit's.

Body:
This is the solution that I am quite happy with. It is based on boq's suggestion from the comments.

//===--- FirstCheckCheck.cpp - clang-tidy ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "FirstCheckCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace misc {

void FirstCheckCheck::registerMatchers(MatchFinder *Finder) {
  // FIXME: Add matchers.
  //
  Finder->addMatcher(
      callExpr(hasArgument(
          1,
          binaryOperator(
              hasOperatorName("|"),
              hasRHS(ignoringImplicit(
                  anyOf(declRefExpr().bind("moduleNum"), integerLiteral().bind(
                      "moduleNum")))),
              hasLHS(ignoringParens(
                  binaryOperator(hasOperatorName("<<"),
                                 hasLHS(ignoringImplicit(anyOf(
                                     declRefExpr().bind("deviceNum"),
                                     integerLiteral().bind("deviceNum"))))))))
              .bind("replaceWithMacro"))),
      this);
}

void FirstCheckCheck::check(const MatchFinder::MatchResult &Result) {
  // FIXME: Add callback implementation.
    std::string deviceNumString;
    std::string moduleNumString;
    std::string ReplacementText;

  if (const auto MatchedDecl =
          Result.Nodes.getNodeAs<Expr>("deviceNum")) {

    const LangOptions &Opts = getLangOpts();

    /* get device string */
    deviceNumString = Lexer::getSourceText(
        CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
        *Result.SourceManager, Opts);
  }
  /* ((uint16_t)(deviceNum << 8 | moduleNum)) */
  if (const auto MatchedDecl =
          Result.Nodes.getNodeAs<Expr>("moduleNum")) {

    const LangOptions &Opts = getLangOpts();

    moduleNumString = Lexer::getSourceText(
        CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
        *Result.SourceManager, Opts);
  }
  if (const auto MatchedDecl =
                 Result.Nodes.getNodeAs<Expr>("replaceWithMacro")) {
    const LangOptions &Opts = getLangOpts();

    ReplacementText = Lexer::getSourceText(
        CharSourceRange::getTokenRange(MatchedDecl->getSourceRange()),
        *Result.SourceManager, Opts);

    std::string replacementString =
        "ADDR(" + deviceNumString + ", " + moduleNumString + ")";

    FixItHint Hint = FixItHint::CreateReplacement(
        MatchedDecl->getSourceRange(), replacementString);

    diag(MatchedDecl->getBeginLoc(), "Replace with ADDR() macro") << Hint;
  }

  /* diag(MatchedDecl->getLocation(), "insert 'awesome'", DiagnosticIDs::Note)
   */
  /*     << FixItHint::CreateInsertion(MatchedDecl->getLocation(), "awesome_");
   */
}

} // namespace misc
} // namespace tidy
} // namespace clang