text:
package com.intellij.psi.impl.compiled;

import com.intellij.diagnostic.PluginException;
import com.intellij.ide.highlighter.JavaClassFileType;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.lang.ASTNode;
import com.intellij.lang.FileASTNode;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DefaultProjectFactory;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.roots.FileIndexFacade;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.ModificationTracker;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.compiled.ClassFileDecompilers;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.JavaPsiImplementationHelper;
import com.intellij.psi.impl.PsiFileEx;
import com.intellij.psi.impl.java.stubs.PsiClassStub;
import com.intellij.psi.impl.java.stubs.PsiJavaFileStub;
import com.intellij.psi.impl.java.stubs.impl.PsiJavaFileStubImpl;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.PsiFileWithStubSupport;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.scope.ElementClassHint;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.stubs.*;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiUtil;
import com.intellij.reference.SoftReference;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.cls.ClsFormatException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.org.objectweb.asm.Attribute;
import org.jetbrains.org.objectweb.asm.ClassReader;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ClsFileImpl extends ClsRepositoryPsiElement<PsiClassHolderFileStub>
                         implements PsiJavaFile, PsiFileWithStubSupport, PsiFileEx, Queryable, PsiClassOwnerEx, PsiCompiledFile {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.compiled.ClsFileImpl");

  private static final String BANNER =
    "\n" +
    "  // IntelliJ API Decompiler stub source generated from a class file\n" +
    "  // Implementation of methods is not available\n" +
    "\n";

  private static final Key<Document> CLS_DOCUMENT_LINK_KEY = Key.create("cls.document.link");

  /** NOTE: you absolutely MUST NOT hold PsiLock under the mirror lock */
  private final Object myMirrorLock = new Object();
  private final Object myStubLock = new Object();

  private final FileViewProvider myViewProvider;
  private final boolean myIsForDecompiling;
  private volatile SoftReference<StubTree> myStub;
  private volatile TreeElement myMirrorFileElement;
  private volatile ClsPackageStatementImpl myPackageStatement;
  private volatile LanguageLevel myLanguageLevel;
  private boolean myIsPhysical = true;
  private boolean myInvalidated;

  public ClsFileImpl(@NotNull FileViewProvider viewProvider) {
    this(viewProvider, false);
  }

  private ClsFileImpl(@NotNull FileViewProvider viewProvider, boolean forDecompiling) {
    super(null);
    myViewProvider = viewProvider;
    myIsForDecompiling = forDecompiling;
    JavaElementType.CLASS.getIndex();  // initialize Java stubs
  }

  @Override
  public PsiManager getManager() {
    return myViewProvider.getManager();
  }

  @Override
  @NotNull
  public VirtualFile getVirtualFile() {
    return myViewProvider.getVirtualFile();
  }

  @Override
  public boolean processChildren(final PsiElementProcessor<PsiFileSystemItem> processor) {
    return true;
  }

  @Override
  public PsiDirectory getParent() {
    return getContainingDirectory();
  }

  @Override
  public PsiDirectory getContainingDirectory() {
    VirtualFile parentFile = getVirtualFile().getParent();
    if (parentFile == null) return null;
    return getManager().findDirectory(parentFile);
  }

  @Override
  public PsiFile getContainingFile() {
    if (!isValid()) throw new PsiInvalidElementAccessException(this);
    return this;
  }

  @Override
  public boolean isValid() {
    return !myInvalidated && (myIsForDecompiling || getVirtualFile().isValid());
  }

  boolean isForDecompiling() {
    return myIsForDecompiling;
  }

  @Override
  @NotNull
  public String getName() {
    return getVirtualFile().getName();
  }

  @Override
  @NotNull
  public PsiElement[] getChildren() {
    return getClasses(); // TODO : package statement?
  }

  @Override
  @NotNull
  public PsiClass[] getClasses() {
    return getStub().getClasses();
  }

  @Override
  public PsiPackageStatement getPackageStatement() {
    getStub(); // Make sure myPackageStatement initializes.

    ClsPackageStatementImpl statement = myPackageStatement;
    if (statement == null) statement = new ClsPackageStatementImpl(this);
    return statement.getPackageName() != null ? statement : null;
  }

  @Override
  @NotNull
  public String getPackageName() {
    PsiPackageStatement statement = getPackageStatement();
    return statement == null ? "" : statement.getPackageName();
  }

  @Override
  public void setPackageName(final String packageName) throws IncorrectOperationException {
    throw new IncorrectOperationException("Cannot set package name for compiled files");
  }

  @Override
  public PsiImportList getImportList() {
    return null;
  }

  @Override
  public boolean importClass(PsiClass aClass) {
    throw new UnsupportedOperationException("Cannot add imports to compiled classes");
  }

  @Override
  @NotNull
  public PsiElement[] getOnDemandImports(boolean includeImplicit, boolean checkIncludes) {
    return PsiJavaCodeReferenceElement.EMPTY_ARRAY;
  }

  @Override
  @NotNull
  public PsiClass[] getSingleClassImports(boolean checkIncludes) {
    return PsiClass.EMPTY_ARRAY;
  }

  @Override
  @NotNull
  public String[] getImplicitlyImportedPackages() {
    return ArrayUtil.EMPTY_STRING_ARRAY;
  }

  @Override
  public Set<String> getClassNames() {
    return Collections.singleton(getVirtualFile().getNameWithoutExtension());
  }

  @Override
  @NotNull
  public PsiJavaCodeReferenceElement[] getImplicitlyImportedPackageReferences() {
    return PsiJavaCodeReferenceElement.EMPTY_ARRAY;
  }

  @Override
  public PsiJavaCodeReferenceElement findImportReferenceTo(PsiClass aClass) {
    return null;
  }

  @Override
  @NotNull
  public LanguageLevel getLanguageLevel() {
    LanguageLevel level = myLanguageLevel;
    if (level == null) {
      List classes = ApplicationManager.getApplication().runReadAction(new Computable<List>() {
        @Override
        public List compute() {
          return getStub().getChildrenStubs();
        }
      });
      myLanguageLevel = level = !classes.isEmpty() ? ((PsiClassStub<?>)classes.get(0)).getLanguageLevel() : LanguageLevel.HIGHEST;
    }
    return level;
  }

  @Override
  public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
    throw cannotModifyException(this);
  }

  @Override
  public void checkSetName(String name) throws IncorrectOperationException {
    throw cannotModifyException(this);
  }

  @Override
  public boolean isDirectory() {
    return false;
  }

  @Override
  public void appendMirrorText(int indentLevel, @NotNull StringBuilder buffer) {
    buffer.append(BANNER);

    appendText(getPackageStatement(), 0, buffer, "\n\n");

    PsiClass[] classes = getClasses();
    if (classes.length > 0) {
      appendText(classes[0], 0, buffer);
    }
  }

  @Override
  public void setMirror(@NotNull TreeElement element) throws InvalidMirrorException {
    PsiElement mirrorElement = SourceTreeToPsiMap.treeToPsiNotNull(element);
    if (!(mirrorElement instanceof PsiJavaFile)) {
      throw new InvalidMirrorException("Unexpected mirror file: " + mirrorElement);
    }

    PsiJavaFile mirrorFile = (PsiJavaFile)mirrorElement;
    setMirrorIfPresent(getPackageStatement(), mirrorFile.getPackageStatement());
    setMirrors(getClasses(), mirrorFile.getClasses());
  }

  @SuppressWarnings("deprecation")
  @Override
  @NotNull
  public PsiElement getNavigationElement() {
    for (ClsCustomNavigationPolicy customNavigationPolicy : Extensions.getExtensions(ClsCustomNavigationPolicy.EP_NAME)) {
      if (customNavigationPolicy instanceof ClsCustomNavigationPolicyEx) {
        try {
          PsiFile navigationElement = ((ClsCustomNavigationPolicyEx)customNavigationPolicy).getFileNavigationElement(this);
          if (navigationElement != null) {
            return navigationElement;
          }
        }
        catch (IndexNotReadyException ignore) { }
      }
    }

    return CachedValuesManager.getCachedValue(this, new CachedValueProvider<PsiElement>() {
      @Nullable
      @Override
      public Result<PsiElement> compute() {
        PsiElement target = JavaPsiImplementationHelper.getInstance(getProject()).getClsFileNavigationElement(ClsFileImpl.this);
        ModificationTracker tracker = FileIndexFacade.getInstance(getProject()).getRootModificationTracker();
        return Result.create(target, ClsFileImpl.this, target.getContainingFile(), tracker);
      }
    });
  }

  @Override
  public PsiElement getMirror() {
    TreeElement mirrorTreeElement = myMirrorFileElement;
    if (mirrorTreeElement == null) {
      synchronized (myMirrorLock) {
        mirrorTreeElement = myMirrorFileElement;
        if (mirrorTreeElement == null) {
          VirtualFile file = getVirtualFile();
          PsiClass[] classes = getClasses();
          String fileName = (classes.length > 0 ? classes[0].getName() : file.getNameWithoutExtension()) + JavaFileType.DOT_DEFAULT_EXTENSION;

          final Document document = FileDocumentManager.getInstance().getDocument(file);
          assert document != null : file.getUrl();

          CharSequence mirrorText = document.getImmutableCharSequence();
          boolean internalDecompiler = StringUtil.startsWith(mirrorText, BANNER);
          PsiFileFactory factory = PsiFileFactory.getInstance(getManager().getProject());
          PsiFile mirror = factory.createFileFromText(fileName, JavaLanguage.INSTANCE, mirrorText, false, false);
          mirror.putUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY, getLanguageLevel());

          mirrorTreeElement = SourceTreeToPsiMap.psiToTreeNotNull(mirror);
          try {
            final TreeElement finalMirrorTreeElement = mirrorTreeElement;
            ProgressManager.getInstance().executeNonCancelableSection(new Runnable() {
              @Override
              public void run() {
                setMirror(finalMirrorTreeElement);
                putUserData(CLS_DOCUMENT_LINK_KEY, document);
              }
            });
          }
          catch (InvalidMirrorException e) {
            //noinspection ThrowableResultOfMethodCallIgnored
            LOG.error(file.getUrl(), internalDecompiler ? e : wrapException(e, file));
          }

          ((PsiFileImpl)mirror).setOriginalFile(this);
          myMirrorFileElement = mirrorTreeElement;
        }
      }
    }
    return mirrorTreeElement.getPsi();
  }

  @Override
  public String getText() {
    VirtualFile file = getVirtualFile();
    Document document = FileDocumentManager.getInstance().getDocument(file);
    assert document != null : file.getUrl();
    return document.getText();
  }

  @Override
  public int getTextLength() {
    VirtualFile file = getVirtualFile();
    Document document = FileDocumentManager.getInstance().getDocument(file);
    assert document != null : file.getUrl();
    return document.getTextLength();
  }

  private static Exception wrapException(InvalidMirrorException e, VirtualFile file) {
    ClassFileDecompilers.Decompiler decompiler = ClassFileDecompilers.find(file);
    if (decompiler instanceof ClassFileDecompilers.Light) {
      PluginId pluginId = PluginManagerCore.getPluginByClassName(decompiler.getClass().getName());
      if (pluginId != null) {
        return new PluginException(e, pluginId);
      }
    }

    return e;
  }

  @Override
  public PsiFile getDecompiledPsiFile() {
    return (PsiFile)getMirror();
  }

  @Override
  public long getModificationStamp() {
    return getVirtualFile().getModificationStamp();
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitJavaFile(this);
    } else {
      visitor.visitFile(this);
    }
  }

  @NonNls
  public String toString() {
    return "PsiFile:" + getName();
  }

  @Override
  @NotNull
  public PsiFile getOriginalFile() {
    return this;
  }

  @Override
  @NotNull
  public FileType getFileType() {
    return JavaClassFileType.INSTANCE;
  }

  @Override
  @NotNull
  public PsiFile[] getPsiRoots() {
    return new PsiFile[]{this};
  }

  @Override
  @NotNull
  public FileViewProvider getViewProvider() {
    return myViewProvider;
  }

  @Override
  public void subtreeChanged() {
  }

  @Override
  public PsiElement getContext() {
    return FileContextUtil.getFileContext(this);
  }

  @Override
  @NotNull
  public PsiClassHolderFileStub<?> getStub() {
    return (PsiClassHolderFileStub)getStubTree().getRoot();
  }

  @Override
  public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
                                     @NotNull ResolveState state,
                                     PsiElement lastParent,
                                     @NotNull PsiElement place) {
    processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, this);
    final ElementClassHint classHint = processor.getHint(ElementClassHint.KEY);
    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) {
      final PsiClass[] classes = getClasses();
      for (PsiClass aClass : classes) {
        if (!processor.execute(aClass, state)) return false;
      }
    }
    return true;
  }

  @Override
  @NotNull
  public StubTree getStubTree() {
    ApplicationManager.getApplication().assertReadAccessAllowed();

    StubTree stubTree = SoftReference.dereference(myStub);
    if (stubTree != null) return stubTree;

    // build newStub out of lock to avoid deadlock
    StubTree newStubTree = (StubTree)StubTreeLoader.getInstance().readOrBuild(getProject(), getVirtualFile(), this);
    if (newStubTree == null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("No stub for class file in index: " + getVirtualFile().getPresentableUrl());
      }
      newStubTree = new StubTree(new PsiJavaFileStubImpl("corrupted_class_files", true));
    }

    synchronized (myStubLock) {
      stubTree = SoftReference.dereference(myStub);
      if (stubTree != null) return stubTree;

      stubTree = newStubTree;

      @SuppressWarnings("unchecked") PsiFileStubImpl<PsiFile> fileStub = (PsiFileStubImpl)stubTree.getRoot();
      fileStub.setPsi(this);

      myStub = new SoftReference<StubTree>(stubTree);
    }

    return stubTree;
  }

  @Override
  public ASTNode findTreeForStub(final StubTree tree, final StubElement<?> stub) {
    return null;
  }

  @Override
  public boolean isContentsLoaded() {
    return myStub != null;
  }

  @Override
  public void onContentReload() {
    ApplicationManager.getApplication().assertWriteAccessAllowed();

    synchronized (myStubLock) {
      StubTree stubTree = SoftReference.dereference(myStub);
      myStub = null;
      if (stubTree != null) {
        //noinspection unchecked
        ((PsiFileStubImpl)stubTree.getRoot()).clearPsi("cls onContentReload");
      }
    }

    ClsPackageStatementImpl packageStatement = new ClsPackageStatementImpl(this);
    synchronized (myMirrorLock) {
      putUserData(CLS_DOCUMENT_LINK_KEY, null);
      myMirrorFileElement = null;
      myPackageStatement = packageStatement;
    }

    myLanguageLevel = null;
  }

  @Override
  public void markInvalidated() {
    myInvalidated = true;
    DebugUtil.onInvalidated(this);
  }

  @Override
  public void putInfo(@NotNull Map<String, String> info) {
    PsiFileImpl.putInfo(this, info);
  }

  @Override
  public FileASTNode getNode() {
    return null;
  }

  @Override
  public boolean isPhysical() {
    return myIsPhysical;
  }

  /** @deprecated override {@link #isPhysical()} instead (to be removed in IDEA 17) */
  @SuppressWarnings("UnusedDeclaration")
  public void setPhysical(boolean isPhysical) {
    myIsPhysical = isPhysical;
  }

  // default decompiler implementation

  @NotNull
  public static CharSequence decompile(@NotNull VirtualFile file) {
    PsiManager manager = PsiManager.getInstance(DefaultProjectFactory.getInstance().getDefaultProject());
    final ClsFileImpl clsFile = new ClsFileImpl(new ClassFileViewProvider(manager, file), true);
    final StringBuilder buffer = new StringBuilder();
    ApplicationManager.getApplication().runReadAction(new Runnable() {
      @Override
      public void run() {
        clsFile.appendMirrorText(0, buffer);
      }
    });
    return buffer;
  }

  @Nullable
  public static PsiJavaFileStub buildFileStub(@NotNull VirtualFile file, @NotNull byte[] bytes) throws ClsFormatException {
    return buildFileStub(file, bytes, new Function<String, PsiJavaFileStub>() {
      @Override
      public PsiJavaFileStub fun(String packageName) {
        return new PsiJavaFileStubImpl(packageName, true);
      }
    });
  }

  @Nullable
  public static PsiJavaFileStub buildFileStub(@NotNull VirtualFile file,
                                              @NotNull byte[] bytes,
                                              @NotNull Function<String, PsiJavaFileStub> stubBuilder) throws ClsFormatException {
    try {
      if (ClassFileViewProvider.isInnerClass(file, bytes)) {
        return null;
      }

      ClassReader reader = new ClassReader(bytes);
      String className = file.getNameWithoutExtension();
      String packageName = getPackageName(reader.getClassName());
      PsiJavaFileStub stub = stubBuilder.fun(packageName);

      try {
        StubBuildingVisitor<VirtualFile> visitor = new StubBuildingVisitor<VirtualFile>(file, STRATEGY, stub, 0, className);
        reader.accept(visitor, EMPTY_ATTRIBUTES, ClassReader.SKIP_FRAMES);
        PsiClassStub<?> result = visitor.getResult();
        if (result == null) return null;
      }
      catch (OutOfOrderInnerClassException e) {
        return null;
      }

      return stub;
    }
    catch (Exception e) {
      throw new ClsFormatException(file.getPath() + ": " + e.getMessage(), e);
    }
  }

  private static String getPackageName(String internalName) {
    int p = internalName.lastIndexOf('/');
    return p > 0 ? internalName.substring(0, p).replace('/', '.') : "";
  }

  private static final InnerClassSourceStrategy<VirtualFile> STRATEGY = new InnerClassSourceStrategy<VirtualFile>() {
    @Nullable
    @Override
    public VirtualFile findInnerClass(String innerName, VirtualFile outerClass) {
      String baseName = outerClass.getNameWithoutExtension();
      VirtualFile dir = outerClass.getParent();
      assert dir != null : outerClass;
      return dir.findChild(baseName + '$' + innerName + ".class");
    }

    @Override
    public void accept(VirtualFile innerClass, StubBuildingVisitor<VirtualFile> visitor) {
      try {
        byte[] bytes = innerClass.contentsToByteArray(false);
        new ClassReader(bytes).accept(visitor, EMPTY_ATTRIBUTES, ClassReader.SKIP_FRAMES);
      }
      catch (IOException ignored) { }
    }
  };

  public static final Attribute[] EMPTY_ATTRIBUTES = new Attribute[0];
}

redpajama_set_name: RedPajamaGithub


The tiny French-Dutch island of Saint-Martin, covering just 88km², is nestled between the Atlantic Ocean and the Caribbean Sea.
Much more than a beach, the island of Saint Martin is teeming with wildlife cultural and human riches. Thanks to its climate and untouched natural heritage, the island offers unparalleled year-round water-sports and outdoor activities.
The capital of shopping, St. Martin is also renowned for its friendly welcome, restaurants and night bars.
Saint Martin has its own unique identity, making it THE perfect sunshine getaway.


Buy a Kilo of climbing chalk and we'll include a FREE Lycan Brush with your order!
Have the cold sweats? Worried about running out of chalk? Buy a Kilo of Guerrilla Grind and say goodbye to your withdrawal pangs.
Net weight 1kg/35.28oz packaged in four individually wrapped Quarter bags.


What app or dating site did you use?
How long did you use it for?
I used the app for two months.
What was your intent for using the app/site? For instance, dating or hooking up?
I used the app with the intent of meeting more people and trying to find a date.
How would you describe your overall experiences?
It was OK overall. I got a couple of numbers but nothing came from it.
Casually for about two years.
My experience was not bad, end result was great. Some dates were definitely worse with little chemistry in person.
I've used Tinder, OkCupid, and Badoo.
I've used Tinder and OKC since April of 2015. I only started Badoo in September of 2015.
I am in an open relationship, which allows me to hook up with people outside of my relationship. My intent is solely hooking up with people, but I've also met some really good friends through the apps. The latter was super unexpected.
Overall, I've had better luck with Tinder during the summer (yay, tourists!) and Badoo with people that are further away than the local area. I've met up with eight people from Tinder and one meet-up planned through Badoo. I've had a lot of flakes on OKC, but I've got one meet-up planned ASAP.
Tinder caters toward the younger crowd. I have better luck, at nearly 28, with the 18-25 group, versus the 26 [and older] group. I think that people are looking to settle down at the upper ages, and my situation isn't what they're looking for. That's OK.
OKC seems to be catered toward dating and relationships, but I am less worried about those. I've made a few friends based on compatability.
Badoo has a Tinder feel, but is a bit less local. It's more for fun than actually meeting people, but I've run into a few people that are local, and I've bloomed friendships with people I probably wouldn't have met, otherwise.
My overall experience has been positive. Yes, I have had one or two not so good experiences, but I can say that the good outweigh the bad.


text:
cd ../core && ^
mvn clean install && ^
cd ../services && ^
mvn clean install && ^
cd ../example && ^
mvn clean install


text:
Q: Method to add row to sqlite3 table is not working - with SQLalchemy I have built an app using flask, and am using flask-user to handle my users.
I am using a sqlite3 database. There is a problem with the functions to delete and add new users:
def delete_user(username):
    if User.query.filter(User.username == username).first():
        user = User.query.filter(User.username == username).first()
        db.session.delete(user)
        db.session.commit()
delete_user('bobby')

def create_user(username,password,role):
    if not User.query.filter(User.username == username).first():
        user = User(
            username=username,
            password=user_manager.hash_password(password)
        )
        user.roles.append(Role(name=role))
        db.session.add(user)
        db.session.commit()
create_user('ollie','password','admin')

It successfully deletes 'bobby' but doesn't add 'ollie'.
The create_user() does work, if the database is removed before the code is run. But not otherwise. I have also tried to comment out # db.create_all()
Before the functions above, is the models section:
class User(db.Model, UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1')

    username =.Column(db.String(50, collation='NOCASE'), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False, server_default='')

    # Define the relationship to Role via UserRoles
    roles = db.relationship('Role', secondary='user_roles')

# Define the Role data-model
class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(50), unique=True)

# Define the UserRoles association table
class UserRoles(db.Model):
    __tablename__ = 'user_roles'
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))
    role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))

# Setup Flask-User
user_manager = UserManager(app, db, User)
db.create_all()

redpajama_set_name: RedPajamaStackExchange


Camper and Nicholsons International has several yachts in its charter fleet offering incentive rates for Caribbean yacht charter during the next few months.
First is the 164-foot Westport motoryacht Trending, which takes 12 guests in six staterooms. She's dropping her weekly base rate by 15 percent, taking the lowest rate down to $178,500.
Next is the 114-foot Benetti motoryacht Brunello, which accommodates eight or nine guests in four staterooms. She's also giving a 15 percent price break through February, making her lowest weekly base rate $63,750.
And last but not least is the 118-foot Intermarine Savannah motoryacht Savannah, which is giving a 10 percent price break on February charter date. Her lowest weekly base rate is now $47,600.
Any reputable charter broker can tell you more about these charter yachts or help you book a week of Caribbean yacht charter at the newly announced incentive rates.


text:
Some of the notable names at George H.W. Bush's funeral
By Christina Prignano Globe staff,December 5, 2018, 12:15 p.m.
(MANDEL NGAN / AFP/ Getty Images)
The National Cathedral in Washington, D.C., was the center of powerful names in American politics on Wednesday as mourners gathered to honor former president George H.W. Bush.
Bush was being eulogized by historian Jon Meacham, former Canadian prime minister Brian Mulroney, former president George W. Bush, and Senator Alan Simpson.
Here's a look at the other notable faces at the funeral service.
RELATED: 5 of the most powerful quotes from George H.W. Bush's funeral
President Trump, Melania Trump, Vice President Mike Pence, and Karen Pence
Vice President Mike Pence (left), (center from L-R) President Donald Trump and First Lady Melania Trump, former president Barack Obama and Michelle Obama, former president Bill Clinton and Hillary Clinton, and former president Jimmy Carter and Rosalynn Carter. (AFP/Getty Images)
Four former presidents and first ladies
Barack and Michelle Obama, Bill and Hillary Clinton, and Jimmy and Rosalynn Carter joined George and Laura Bush at the funeral service.
From left: President Trump, Melania Trump, Bill Clinton and Hillary Clinton, and Jimmy Carter and Rosalynn Carter. (AFP/Getty Images)
Former vice presidents and their spouses
Dan and Marilyn Quayle, Dick and Lynne Cheney, Joe and Jill Biden, and Al Gore sat behind the row of former presidents.
From left, second row: Dan and Marilyn Quayle, Dick and Lynne Cheney, Joe and Jill Biden, and Al Gore. (BRENDAN SMIALOWSKI/AFP/Getty Images)
Congressional leadership
A bipartisan group of Congressional leaders took part in the departure of Bush's casket from the US Capitol.
From left: Janna Ryan, Speaker of the House Paul Ryan, Transportation Secretary Elaine Chao, Senate Majority Leader Mitch McConnell, Iris Weinshall, Senate Minority Leader Chuck Schumer, House Minority Leader Nancy Pelosi and Paul Pelosi. (Drew Angerer/Getty Images)
Prince Charles and Angela Merkel
A number of foreign officials were in attendance, including the German chancellor and British prince.
Britain's Prince Charles.(Evan Vucci/Associated Press)
German Chancellor Angela Merkel. (AP Photo)(Evan Vucci/Associated Press)
Former Attorney General Jeff Sessions
Former Attorney General Jeff Sessions.(ALEX BRANDON/AFP/Getty Images)
Former President Bill Clinton, former secretary of state Hillary Clinton, and daughter Chelsea Clinton (center).(BRENDAN SMIALOWSKI/AFP/Getty Images)
Brent Scowcroft
Former national security advisor Brent Scowcroft walked out of the cathedral behind the casket of George H.W. Bush.
Former national security advisor Brent Scowcroft.(Doug Mills/Getty Images)
Former Bush (43) administration officials
Republican strategist and former White House senior adviser Karl Rove, left, and former White House press secretary for President George W. Bush Dana Perino.
Karl Rove, left, and Dana Perino. (Andrew Harnik-Pool/Getty Images)

redpajama_set_name: RedPajamaCommonCrawl


So you've heard all the drama surrounding the President's cancelled visit to Ogoni land. You've read the dirty details of the fight involving Skales, his manager and Baseline Records. You've seen the twists and turns in the case of Runtown and Eric Manny Entertainment. These are just some of the events presenting an opportunity for us to solve PR problems and take learnings. Join us on Facebook, on Tuesday June 7, 2016, to discuss the PR lessons from these and more.
On the other side of the world, rapper, JayZ is not ashamed of his drug dealing past as he responded to critics on Pusha T's new track, Drug Dealers Anonymous. Brands have a lot to learn from celebrities like JayZ, on managing reputations and building brands. Our in-house hip-hop heads will add their own perspectives during our Facebook Live chat next week.
Speaking of hip hop, did you see NET's amazing Democracy Day Rap Report? Watch it here.
Beat FM's Toolz had her white wedding to Tunde Demuren last weekend in Dubai, Gbemi Olateru-Olagbegi celebrated the first anniversary of her shoe line, Gbemisoke Shoes, and Tosyn Bucknor got married in France. Three of our favourite women right there!
So Nigeria's President Buhari has announced the Ogoniland Clean-up, stating that oil theft, illegal refining must stop. But his no-show in the Niger Delta appeared to be a bad PR move. Especially since this is the second cancelled trip in less than 2 weeks. Is Aso Rock getting communication right?
The Shuga limb Foundation Empowerment Project tagged the Gifted and Talented held on the 30th of May with Bimbo Ashiru, Abimbola Fashola, amongst others in attendance. Akin Shuga is one of the many Nigerians showing that physically-challenged people don't have to be disabled.
In PR news, Chief Executive Officer of CMC Connect, Mr. Yomi Badejo-Okusanya, has been elected President of Africa Public Relations Association (APRA), the continent's Public Relations Professionals Association.
Google now controls 12% of all global media spend! Here's what you need to know about that.
Meanwhile, Healthcare in Nigeria is about to be transformed as Interswitch enhances the health sector with the launch of Interswitch Hospital Management Solutions (IHMS).
Looking to hire a creative agency?
Read what you should look for in PR and creative agencies here. It was written by ID Africa COO, Femi Falodun. You can follow him on Twitter @hephef.
Riding that creativity train, we're looking forward to attending the #DMWF in London later this month. #DMWF is a digital and social marketing conference which brings the world's marketing community together to tackle the challenges and opportunities the digital future presents. Follow us on IG and Snapchat for inside access – @bhmng.
Our CEO, Ayeni Adekunle, taught, this week, at Chris Ihidero's creative master class series, Story Story. He advised participants to see beyond the present and prepare for the future by predicting and following digital trends. You can watch the video here.
Ayeni is also the keynote speaker at the 80th birthday of Fela's first manager and Burna Boy's grandfather, Benson Idonije, on the 19th of June. More details here.


1st Coastal Commercial Capital Gas Station Financing Program includes convenience store financing or c-store financing in all 50 states and the District of Columbia. Gas station commercial loans or gas station mortgages are available for the purchase or refinancing of Gas stations, convenience stores, and the combination of both.
It is no secret that with a struggling economy and the current scarcity of funds, finding funding for your purchase or to refinance the mortgage on your gas station has become quite a challenge.
Banks are reluctant to lend mostly due to their lack of understanding of this industry. This is why there is a need to fill this gap to be able to finance gas stations and convenience stores.
Gas station financing has become more and more difficult due to new regulations and environmental concerns as more gas station mortgage providers have departed the industry.
1st Coastal Commercial Capital understands the challenges of Gas Station financing and Convenience Store financing and has tailored its gas station financing program to tailor the petro industry and their needs for financing.
We understand the unique considerations required by gas stations, and how gas station loans are underwritten and whether you are acquiring a single station or refinancing a nationwide portfolio, you can expect us to be able to provide the timely financing you deserve.
Properties eligible for gas station commercial real estate loan program should be gas stations and convenience stores of above average condition, environmentally compliant (no tank violations or overdue inspections) and located in medium and above market sectors.
What do you need to obtain Gas Station Financing?


Indulge in our chef's perfectly created culinary creations. The palm paradise villas, offers you a vast selection of local and international cuisines. Dine by the pool in the evenings with the lights reflecting on the waters creating awe inspiring and romantic settings for you and your loved ones.
The Palm Paradise Cabanas and Villas Resort offers you a vast selection of local and international cuisines.Indulge in our chef's perfectly created culinary creations anddine by the pool in the evenings with lights reflecting on the waters creating awe inspiring and romantic settings for you and your loved ones.
The Pavilion is an invitation to all food enthusiasts to experience the best of the Deep South cuisine that Sri Lanka has to offer – where locally sourced produce takes centre stage and dishes are created with the essence of Sri Lankan authenticity packed into bags of flavour.


Maybe you have seen yourself within the mirror and asked that which was missing? Your clothing is stylish, your socks match, and you're sporting freshly polished footwear, but nonetheless something is missing. The reply to your jewelry. A simple bit of jewelry can pull your outfit together.
If you're searching for silver jewelry, be sure to have a magnet together with you. You are able to identify fake silver using the magnet, as non-gold and silver are attracted through the magnet. You are able to identify silver by its markings, for instance "sterling, it could simply say," or ". 925. " In case your silver isn't marked, it might not be silver.
Have a very close consider the piece you want, then place it alongside other pieces you are looking at. Remember that some seller's uses cheap tactics to create a gemstone look bigger or better.
Give consideration towards the types, white gold or platinum or yellow, and colors of jewelry the person wears. This should help you advisable of jewelry for the one you love.
Keep the jewelry from getting damaged to preserve its best as possible. Keep your jewelry when you're around water. Water can dull and rust some metals to get rid of their luster in order to become damaged or rusty. If you wish to provide your jewelry a stride of defense against this element, get it ready with the addition of some obvious nail polish at first glance.
A brooch can also add just a little character for your belt. Pin it near your stylish or perhaps you're stylish.
It can save you immeasurable money should you take time to search for better prices. Certain that your, within the store home windows, as well as in stores to find the best deals. If you purchase fashion products in the finish of the season, you may save 50% or even more from the original cost.
A diamond's cut and clearness are frequently occasions more essential than the usual bigger gemstone of lower quality. You should also consider who definitely are putting on the jewelry.
This rule is applicable to dry bathhouses which are steam or dry. Various kinds of jewelry are affected damage if they're uncovered to extreme temps and humidity.
Each and every gemstone is exclusive and features its own group of defects. Some defects might not bother you.
A matched up jewelry set bakes an excellent gift for any lady in your list. You will notice that a much better cost if you purchase a whole set. You can always break creates and gift a bit to the one you love every holidays. This can be a fabulous method to also have a present that somebody will forget.
Brand shouldn't be the only real consideration when buying jewelry. You will find superior quality brands.
Because this article shows, jewelry is definitely the right accessory to accomplish your outfit. You should use various kinds of jewelry to ensure that you gaze professional, classy or perhaps fun. Regardless of what the copyright notice occasion, the best jewelry is definitely appropriate and flattering copyright notice.


text:
'MADAM BUTTERFLY'
National Programme Daventry, 3 December 1938 14.30
Acts 1 and 2 of the Opera by Puccini from the Sadler's Wells Theatre
The action takes place in the town of Nagasaki, Japan
Act 1, A Japanese house overlooking the harbour of Nagasaki
Cast in order of appearance
Relatives and friends of Cho-Cho-San
The Sadler's Wells Orchestra
Leader, Joseph Shadwick
Conductor, Warwick Braithwaite
Chorus Master, Geoffrey Corbett
Producer, John Gordon
Lieutenant Pinkerton, an officer of the United States Navy, arrives at Nagasaki in the course of his duties. It is here that he meets Cho-Cho-San, known as Madam Butterfly.
Goro is a Japanese marriage broker, to whom Pinkerton goes ro draw up an agreement concerning his forthcoming marriage to Butterfly, for whom he has a passing infatuation. Goro assures him that the marriage is only binding so long as he continues to live with his wife.
In the meantime Madam Butterfly has forsaken her gods to become Christian and is scorned by her relations, who finally renounce her.
To Pinkerton comes Sharpless, the American Consul at Nagasaki, who tries to dissuade him from this marriage, and points out that Butterfly is very serious and is under the impression that she is entering a life contract-hut Pinkerton does not listen to him. The marriage takes place and is followed by a feast, where her uncle, the Bonze, finally curses her. - The Act ends with mutual protestations of love.
Leader: Joseph Shadwick
Conductor: Warwick Braithwaite
Chorus Master: Geoffrey Corbett
Producer: John Gordon
Lieutenant Pinkerton: John Wright
Goro: Powell Lloyd
Suzuki: Rose Morris
Sharpless: Redvers Llewellyn
Butterfly (Cho-Cho-San): Jeanne Dusseau
High Commissioner: John Greenwood
Registrar: Frank Brook
Bonze: Roderick Lloyd
Yamadori: John Hargreaves
National Programme is a radio service which began broadcasting on 9 March 1930 and ended on 9 September 1939. It was replaced by BBC Home Service Basic.
Feedback about 'MADAM BUTTERFLY', National Programme Daventry, 14.30, 3 December 1938
Please leave this link here so we can find the programme you're referring to: http://genome.ch.bbc.co.uk/142277c1718d4af6a27709dd443c22b0


text:
How One Play Finally Made It to Broadway
By Tony Vellela Special to The Christian Science Monitor
Even though it's only 40 blocks from the Joseph Papp Public Theater in lower Manhattan to Broadway's Longacre Theatre, it took David Henry Hwang's new play, "Golden Child," two years to make the journey. Along the way, it made stops in San Francisco, Washington, and Singapore - thus being a good example of how long it can take to develop a drama. The play is now up for a Tony Award for best play.
After winning a Tony Award and a Pulitzer Prize for his acclaimed "M. Butterfly" 10 years ago, Mr. Hwang set out to continue his playwriting career, but he hit some bumps along the way. When his controversial play "Face Value," about stereotyping of Asian-Americans, failed a few years back, Hwang turned to a story he had been nurturing for years.
"I interviewed my grandmother when I was 10," the boyish Hwang relates backstage at the Longacre. "She told me these stories, and I turned them into a 90-page novel." It was this saga that became "Golden Child," the story of a Chinese businessman's decision in the early part of this century to turn his back on tradition and embrace Christianity and Western thinking.
"The play is very much about family," he says, "and how we decide what it is we're going to pass on, what it is we're going to keep, the sacrifices we make for our children - and then, as a child, how you have to both respect your parents, appreciating what they've done for you, and also find a way to disown them."
Though the story is set in 1918, audiences find themselves transported back to a time that seems even more distant. The lead character has three wives, common in China then. "It was a feudal culture," Hwang says. "Europe went through this whole middle period between feudalism and modern democracy. Of course, China's not a modern democracy, but all its changes have been within this century."
Onstage, characters wear silken robes, observe ritualized behavior among the man and his three wives, and honor their ancestors in religious rites. Women spend their childhood enduring pain from having their feet bound to achieve the culture's idealized feminine beauty. The young girl at the center of the story, drawn from the experiences of Hwang's grandmother, is freed from the custom when her father rejects Chinese traditions in favor of Western mores.
Hwang wrote the first version of "Golden Child" as part of a commission from South Coast Repertory in Costa Mesa, Calif., where he did a reading in spring 1996. In the fall, it went into production at New York's Papp Public Theater. When that run ended, "we were happy with a lot of things we'd done but felt the story wasn't as clear as it could be."
The production returned in January 1997 to the South Coast Repertory, where work continued on the script. Then, in March, the production went to the Kennedy Center.
"I frankly feel we took a step backwards in Washington," Hwang says. "This play has always had a complicated balance between humor and tragedy, and I probably pushed James [Lapine, the director] to make the show funnier. So we got a show that was too funny and compromised the dramatic aspects, especially the tragic things that happen in the second act. After that, we took some time off."
"Golden Child," rewritten again, resurfaced in January 1998 - this time out of the country in Singapore, a move developing plays don't often make. "I'd worked there a number of times before," he says, "and it seemed important to bring it to Asia, because it's the first play I'd ever done that takes place primarily in China, and certainly in period. And in a funny way, it's a play about assimilation - not assimilation in America, but Western assimilation happening to a man in China. Asians are dealing with that at a remarkable pace right now.
"In Singapore, I could see if it was meaningful to an Asian audience, and they confirmed for me that it was authentic, realistic. It was a good test for the play."
Then, following an American tryout for a month in San Francisco, "Golden Child" opened on Broadway in April. Though the audiences have been small, the production received a Tony nomination for best play, beating out plays by Neil Simon and David Mamet. The awards will be presented June 7.
"After 'M. Butterfly,' " Hwang says, "I wanted to be able to bring a drama with a mostly or all-Asian cast to Broadway, which hadn't been done since 'Rashomon' in the late '50s. Of course, there were musicals [that had Asian casts]. This was a conscious motivation of mine in creating 'Golden Child.'
"The subject matter is a little unusual for Broadway, so it's been harder to get people to buy tickets. When they see the show, they seem to really like it, because the whole idea of heritage is incredibly universal."
Marvin Hamlisch remembered for musical scores on Broadway and film
'Into the Woods' trailer: Take a peek at the fairy tale musical
New musical 'Waitress' is heading to Broadway this spring


text:
Pharmacological MRI approaches to understanding mechanisms of drug action
Michael J. Minzenberg
Research Training Program Scholars
Functional neuroimaging is a novel technique for the study of drug action in the brain. The emerging role of this method is intimately tied to the unique challenges to advancing drug development for neuropsychiatric disorders. This chapter first presents a brief overview of the important treatment needs that remain to be met, which serve as clinical targets for drug development. Important factors that hinder progress in drug development, which arise from clinical, scientific and economic issues, are acknowledged. This sets the stage for the unique advantages of functional neuroimaging modalities such as functional MRI (fMRI) as a biomarker and drug development tool, in both clinical and preclinical phases. The physiological basis of the fMRI signal is briefly outlined, and aspects of neural signaling related to this signal change, with emphasis on implications for pharmacology studies. The utility of fMRI for evaluating the full anatomic extent of central neurotransmitter systems in a dynamic manner is then described. This is a critical advantage, and particularly important for studies of how systems such as the monoamines modulate distributed neural networks during cognitive processes in both health and illness, and how these actions are modified with pharmacological intervention. Central catecholamine systems are seen as paradigmatic targets amenable to pharmacologic fMRI. fMRI is observed to occupy a unique position in the armamentarium of methods available to the pharmacologist and the drug development process, and poised to play an expanding role in basic and clinical neuroscience.
Current Topics in Behavioral Neurosciences
https://doi.org/10.1007/7854_2011_177
10.1007/7854_2011_177
Dive into the research topics of 'Pharmacological MRI approaches to understanding mechanisms of drug action'. Together they form a unique fingerprint.
Drug Development Medicine & Life Sciences 100%
Magnetic Resonance Imaging Medicine & Life Sciences 69%
Functional Neuroimaging Medicine & Life Sciences 51%
Neurosciences Medicine & Life Sciences 22%
Catecholamines Medicine & Life Sciences 19%
Neurotransmitter Agents Medicine & Life Sciences 18%
Minzenberg, M. J. (2012). Pharmacological MRI approaches to understanding mechanisms of drug action. Current Topics in Behavioral Neurosciences, 11, 365-388. https://doi.org/10.1007/7854_2011_177
Pharmacological MRI approaches to understanding mechanisms of drug action. / Minzenberg, Michael J.
In: Current Topics in Behavioral Neurosciences, Vol. 11, 2012, p. 365-388.
Minzenberg, MJ 2012, 'Pharmacological MRI approaches to understanding mechanisms of drug action', Current Topics in Behavioral Neurosciences, vol. 11, pp. 365-388. https://doi.org/10.1007/7854_2011_177
Minzenberg MJ. Pharmacological MRI approaches to understanding mechanisms of drug action. Current Topics in Behavioral Neurosciences. 2012;11:365-388. https://doi.org/10.1007/7854_2011_177
Minzenberg, Michael J. / Pharmacological MRI approaches to understanding mechanisms of drug action. In: Current Topics in Behavioral Neurosciences. 2012 ; Vol. 11. pp. 365-388.
@article{ce1bdcbd0ef64538bf76b9d0f8b38ee5,
title = "Pharmacological MRI approaches to understanding mechanisms of drug action",
abstract = "Functional neuroimaging is a novel technique for the study of drug action in the brain. The emerging role of this method is intimately tied to the unique challenges to advancing drug development for neuropsychiatric disorders. This chapter first presents a brief overview of the important treatment needs that remain to be met, which serve as clinical targets for drug development. Important factors that hinder progress in drug development, which arise from clinical, scientific and economic issues, are acknowledged. This sets the stage for the unique advantages of functional neuroimaging modalities such as functional MRI (fMRI) as a biomarker and drug development tool, in both clinical and preclinical phases. The physiological basis of the fMRI signal is briefly outlined, and aspects of neural signaling related to this signal change, with emphasis on implications for pharmacology studies. The utility of fMRI for evaluating the full anatomic extent of central neurotransmitter systems in a dynamic manner is then described. This is a critical advantage, and particularly important for studies of how systems such as the monoamines modulate distributed neural networks during cognitive processes in both health and illness, and how these actions are modified with pharmacological intervention. Central catecholamine systems are seen as paradigmatic targets amenable to pharmacologic fMRI. fMRI is observed to occupy a unique position in the armamentarium of methods available to the pharmacologist and the drug development process, and poised to play an expanding role in basic and clinical neuroscience.",
author = "Minzenberg, {Michael J.}",
doi = "10.1007/7854_2011_177",
journal = "Current Topics in Behavioral Neurosciences",
T1 - Pharmacological MRI approaches to understanding mechanisms of drug action
AU - Minzenberg, Michael J.
N2 - Functional neuroimaging is a novel technique for the study of drug action in the brain. The emerging role of this method is intimately tied to the unique challenges to advancing drug development for neuropsychiatric disorders. This chapter first presents a brief overview of the important treatment needs that remain to be met, which serve as clinical targets for drug development. Important factors that hinder progress in drug development, which arise from clinical, scientific and economic issues, are acknowledged. This sets the stage for the unique advantages of functional neuroimaging modalities such as functional MRI (fMRI) as a biomarker and drug development tool, in both clinical and preclinical phases. The physiological basis of the fMRI signal is briefly outlined, and aspects of neural signaling related to this signal change, with emphasis on implications for pharmacology studies. The utility of fMRI for evaluating the full anatomic extent of central neurotransmitter systems in a dynamic manner is then described. This is a critical advantage, and particularly important for studies of how systems such as the monoamines modulate distributed neural networks during cognitive processes in both health and illness, and how these actions are modified with pharmacological intervention. Central catecholamine systems are seen as paradigmatic targets amenable to pharmacologic fMRI. fMRI is observed to occupy a unique position in the armamentarium of methods available to the pharmacologist and the drug development process, and poised to play an expanding role in basic and clinical neuroscience.
AB - Functional neuroimaging is a novel technique for the study of drug action in the brain. The emerging role of this method is intimately tied to the unique challenges to advancing drug development for neuropsychiatric disorders. This chapter first presents a brief overview of the important treatment needs that remain to be met, which serve as clinical targets for drug development. Important factors that hinder progress in drug development, which arise from clinical, scientific and economic issues, are acknowledged. This sets the stage for the unique advantages of functional neuroimaging modalities such as functional MRI (fMRI) as a biomarker and drug development tool, in both clinical and preclinical phases. The physiological basis of the fMRI signal is briefly outlined, and aspects of neural signaling related to this signal change, with emphasis on implications for pharmacology studies. The utility of fMRI for evaluating the full anatomic extent of central neurotransmitter systems in a dynamic manner is then described. This is a critical advantage, and particularly important for studies of how systems such as the monoamines modulate distributed neural networks during cognitive processes in both health and illness, and how these actions are modified with pharmacological intervention. Central catecholamine systems are seen as paradigmatic targets amenable to pharmacologic fMRI. fMRI is observed to occupy a unique position in the armamentarium of methods available to the pharmacologist and the drug development process, and poised to play an expanding role in basic and clinical neuroscience.
U2 - 10.1007/7854_2011_177
DO - 10.1007/7854_2011_177
JO - Current Topics in Behavioral Neurosciences
JF - Current Topics in Behavioral Neurosciences


Editable via smart object – The background and items on scene are editable via smart object. Simply copy and paste your design and you are finished with a click of a mouse! You can experiment with different backgrounds or add custom textures etc.
Foil Stamping – Our foil stamping option allows you to input your desired foil stamping design and also manage the color of the foil. The choices are limitless!
Paper Texture Control – We've included coated and uncoated paper. Additionally, you can also alter the intensity of the reflections with Levels and Opacity.
Global Illumination – Global illumination is an option that allows you to control the shadow intensity by taking into account light reflected from surfaces on scene. Darker objects reflect less light and project darker shadows than lighter objects and now you have an option to simulate that effect.


New police recruits could be trained on the site of the former Maze prison in County Antrim.
The proposal to move police training to a new college on the site near Lisburn was made by the Northern Ireland Policing Board.
At a meeting on Wednesday, board members considered key criteria for such a college and agreed the extensive site at the former prison fulfilled all the requirements.
The prison, which held many of the province's most notorious paramilitaries during the Troubles, closed in September 2000.
Board chairman Desmond Rea: "The board believes the Maze site would be ideal"
It was shut as a result of the Good Friday Agreement peace accord's early prisoner release scheme.
The Patten report on police reform recommended the PSNI should have a new purpose built college which would provide a training facility of world class standard.
Commenting on the proposals, Board Chairman Professor Desmond Rea said: "Despite some refurbishment, the Garnerville site offers a poor facility for police training and we have been working with the PSNI to find a suitable alternative.
"The difficulty has been finding a location which fulfils the numerous requirements of a new police college.
"The board believes the Maze site would be ideal and could be developed as a training facility of world class standard.
"This view is fully endorsed by the acting Chief Constable Colin Cramphorn and the recently appointed Chief Constable Hugh Orde."
Chairman of the Police Federation Irwin Montgomery said at the moment, police training was scattered between Garnerville, Londonderry and Fermanagh.
He said he did not really care where the new facility was placed but said the Maze would be ideal.
"Geographically it is outside Belfast which means that travelling to it is much easier and there is easy communication from all directions," he said.
"As long as the government provide the money to replace our present one, and it is relatively centrally located, I am not bothered where they build it as long as they do it."
Lisburn council has asked to be kept informed of any decision.
"We in Lisburn council were thinking of a national sports centre for there," said former Ulster Unionist mayor Jim Dillon.
However, Sinn Fein councillor Micheal Ferguson, who is a former Maze inmate, is opposed to the plan.
"It would be insensitive to some and insulting to many that this area is proposed to be used for a training ground for a new police force when really what we need is a new police service," he said.
"Personally I think it should be retained as a museum to remember that we lived in a state where there were no democratic or civil liberties and as a symbol to ensure that we move into a society where we can guarantee democratic and civil liberties for everybody."
The decision of the board and the views of the acting chief constable and new chief constable will now be passed to the Northern Secretary of State.
The Chancellor has said money raised by the sale of the Maze will be given to the assembly for the benefit of the community.


Currency Today Helps You Find the best Indian Rupee Exchange Rates Online. Buying Rupees online shouldn't be complicated; there should be no need to shop around for hours on end just to find the best deal. If you're smart enough to purchase INR Rupees online, then you're probably smart enough to realise that there is a simple way to getting the best rates online – using a comparison site. At Currencytoday.co.uk we offer a FREE comparison service to help you procure the most up-to-date, most competitive Indian Rupee currency rates – all tailored exactly to your requirements.
The Indian rupee is the currency of India and is symbolised by the code INR. It is abbreviated as 'Rs'', '□' or in Hindi as 'rupiah'. A rupee is subdivided into 100 paise. India is believed to be one of the first issuers of coins dating back to the 6th Century BC.
Coins that are used at present are in the denominations of 50p, 1, 2 and 5 rupee coins. The 50 paisa coin is the only paise denomination in circulation today but very few can be seen doing the rounds. As for banknotes the denominations in circulation are 5, 10, 20, 50, 100, 500 and 1000 rupee notes.
Almost all the banks in India offer foreign currency conversions apart from which hotels and a mass of authorised exchange offices provide this facility. Traveller's cheques are also easy to cash here.
Credit and debit cards are widely accepted throughout India with most of your expenses being paid off through your cards. ATM's can be found in abundance in banks or as standalone machines. Indians depend widely on credit and debit cards to make payments at most places.
The import of Indian currency is prohibited other than a 100 rupee note. A resident of India is allowed to take an amount not exceeding Rs5000 to be used on return if going on a short journey abroad. There is no limit to the amount of foreign currency that can be brought in but if the amount including traveller's cheques is above $10,000 then it has to be declared at the customs and the necessary document be procured.
India is a country of vast diversity with a healthy mix of various cultures and traditions fused with the vibrant colours of each region. A fascinating array of the most sumptuous foods, with every region boasting of a more unique feast fit for a food connoisseur; are all to be found in India. India also has a tremendous historical background and you can see its history through the many monuments and ruins that are scattered all over the country. The exotic palaces of the Maharajas and the Nawabs now turned into grand hotels, the forts, beaches, the beautiful hills and many other attractions draw tourists year after year.
The cost of living in India as compared to the west is comparatively low. A three star hotel room in Goa would cost about Rs9032/$180/£126 per night. A three-course meal would cost you a mere Rs200/£4/£3 and a bottle of wine about Rs100/$2/£1.40. An average cost per day can be placed at Rs500/$10/£7 per head at the minimum.


text:
The TVweek: Saturday 16th – Friday 22nd January 2021
by Custard TV Staff | Jan 12, 2021 | All, TV Week
9.30pm Wallis Before Edward Channel 5 – A profile of Wallis Simpson, focusing on her early years before she met the future king, asking whether she was a scheming seductress or one of the most maligned women in history.
Notable Continuing Series: A Perfect Planet, 8.00pm, BBC One
The Great, 9.00pm, Channel 4
8.00pm Who Wants to Be A Millionaire? ITV – Six more contestants have 15 questions, four lifelines and one chance to win £1million as the quiz hosted by Jeremy Clarkson returns. Donald Fear became the series' sixth jackpot winner in 2020, but it remains to be seen whether any of the latest players have what it takes to become the seventh millionaire.
9.00pm Finding Alice ITV – Six-part drama starring Keeley Hawes, Gemma Jones and Kenneth Cranham from acclaimed writer Simon Nye. For Alice, Harry and their daughter, Charlotte, moving into their new home should have been a dream come true. But it turns into a nightmare when Alice discovers Harry dead at the bottom of the stairs in the property he designed.
9.00pm Charley Boorman: Ireland to Sydney by any Means BBC Four – Series following the adventurer through 25 countries, as he tries to travel by land and sea from his home in Co Wicklow to Australia on more than 100 local forms of transport. After deciding on a route that avoids the most dangerous places on Earth, he, his producer and his cameraman begin the first leg of the journey across the Irish Sea to England.
9.00pm Rich Holiday, Poor Holiday Channel 5 – Return of the documentary in which two families with different incomes exchange holidays to see if money can buy happiness. Just who really has the time of their lives when faced with windy campsites and basic bedrooms in Benidorm or luxury foreign villas and private yachts? And does the top 10 per cent ever want to share their loungers with the bottom 10 per cent?
9.00pm The Case Died With Her Sky Crime – Documentary about the case of Emilie Morris, a woman in her 30s who suffered an untimely death just after bringing charges against Jim Wilder for sexually inappropriate behaviour when she was a minor.
9.00pm Expecting Amy Sky Documentaries – Cameras follow Amy Schumer as she prepares for a stand-up special, while also coping with a difficult pregnancy. The first episode follows the second trimester.
8.00pm Devon & Cornwall Channel 4 – The return of the documentary examining life in the two counties, beginning by meeting the people who live and work along the beautiful and rugged coastline. In Looe on the south coast of Cornwall, the whole community gears up for one of the biggest events of the year – the one-mile wild swim from St George's Island back to the town beach.
9.00pm Cornwall: This Fishing Life BBC Two – The return of the documentary about the county's fishing communities, beginning in the popular tourist resort of Newquay as restrictions begin to ease after the coronavirus lockdown.
9.00pm Long Lost Family ITV – Davina McCall and Nicky Campbell return to help more people reunite with long-lost relatives. Phyllis and Kevin Haran fought in vain to get their son back through the courts after putting him up for adoption when they were homeless, jobless and desperate to put their baby's interests first.
9.00pm Made for Murder Sky Crime – The crimes of Stephen Hough, who was arrested for sexually assaulting a schoolgirl in 2016, linking him to the killing of another 15-year-old 40 years earlier in 1976.
9.00pm A.P. Bio Sky Comedy – Third season of the US comedy.
9.30pm Real Time with Bill Maher Sky Comedy – Comedian Bill Maher invites three guests from different parts of the political spectrum to discuss the week's events.
9.00pm The Murdoch Murders Alibi – A vaudeville comic's death leads Murdoch to suspect that Charlie Chaplin was the intended target.
10.00pm Shut-Ins: Britain's Fattest People Channel 4 – The return of the documentary revealing what life is like for the UK's most overweight people, following two of them as they attempt to regain control of their lives.
10.45pm Ru Paul's Drag Race UK BBC One – Second series of the reality competition.
8.00pm Winterwatch BBC Two – Winter wildlife stories from around the UK. Chris Packham will be in the New Forest watching winter transform his home, and Iolo Williams is at the Centre for Alternative Technology in Wales, hoping to see some murmurations.
8.00pm Lose Weight Like Me Channel 4 – Jordan Banjo and Dr Sara Kayat present two members of the public with four weight loss success stories, and invite them to pick one health regimen to follow for eight weeks – without meeting the person behind it. The two volunteers are Jamie from Yorkshire, who is trying to be a better role model for his children, and Londoner Kathleen, who wants to regain control of her weight before she experiences the menopause.
9.00pm Silenced: The Hidden Story of Disabled Britain BBC Two – Cerrie Burnell presents a history of disabled people's struggle for human rights in Britain. The film looks back to the policies in place in Victorian workhouses, uncovering the original records of an institution created to segregate disabled people and stop them from having children. She also shares inspiring stories of pioneering campaigners for social change, and looks at the challenges still to be faced in the future.
9.00pm Outbreak: The Virus That Shooked the World ITV – Documentary exploring the spread of Covid-19 across four continents during 2020. Featuring contributions from medical professionals, a look at the initial outbreak in China and suggestions that the authorities attempted to cover up the danger, and an examination of how the decisions taken by governments and public health officials helped shape the course of the infection.
Notable Continuing Series: 24 Hours in A&E, 9.00pm, Channel 4
9.00pm Till Kingdom Come BBC Four – Documentary exploring the close ties between US evangelicals and Israel's foremost philanthropic organisation, and its influence on both nations' foreign policies.
10.00pm First Dates Channel 4 – A parliamentary assistant fears talking politics scares men away, but may have met her match in an outspoken journalist. A 69-year-old former roadie is looking for someone to settle down with after surviving cancer, while a Lithuanian spa therapist searches for an older man who she can start a family with.
10.00pm Royal Antique Repairers More4 – Victoria Coren Mitchell meets restoration experts working on pieces of royal history, including King George IV's piano and a very rare copy of King Louis XV's roll-top desk.
9.00pm Disability Hate Crime BBC Two – Disabled filmmaker Richard Butchins' brutally honest film explores the abuse and aggression faced by disabled people in everyday life, from verbal insults to violent physical attacks. The film features a wide range of testimony from survivors themselves as they share their own experiences of the abuse they have faced.
9.00pm The Bay ITV – Second series of the Morecombe set crime drama starring Morven Christie and Daniel Ryan. After dealing with the repercussions of her actions from last year, DC Lisa Armstrong is given the opportunity to step up when asked to assist a murder investigation in Morecambe. Tensions remain high as Lisa struggles to do her job whilst following the orders of her previously lower ranking colleague, Med. As the team tries to uncover why the victim was targeted, Lisa and her children are unknowingly stalked by a mysterious figure.
Notable Continuing Series: Grand Designs, 9.00pm, Channel 4
9.00pm Bulletproof Sky One – Third series of the crime drama, starring Ashley Walters and Noel Clarke.Pike and Bishop escape London for a much-deserved break in South Africa, but the fun does not last as they are drawn into a new case.
7.00pm Inside Culture with Mary Beard BBC Two – The classicist returns with the cultural review show, and hot on the heels of Joe Biden's inauguration, she talks to Veep and The Thick of It creator Armando Iannucci to ask how comedians and satirists adjust to a new regime. She is also joined by David Olusoga, who recently interviewed Barack Obama, to explore succession through the ages.
9.00pm The Chasers Road Trip: Trains, Brains and Automobiles ITV – Anne Hegerty, Mark Labbett and Shaun Wallace – three of the biggest brains of the quizzing world – travel the world to uncover the cognitive abilities of animals and artificial intelligence. They start out in the USA, where they pit their wits against Kanzi, a bonobo ape who is able to communicate with humans using a series of pictures and symbols – and is also thought to be one of the first apes to show an understanding of spoken English. They also meet a chimpanzee memory wizard, a 25-year-old orang-utan that enjoys playing video games and that well-known genius of the ocean, the dolphin.
10.00pm Back Channel 4 – Return of the comedy series starring David Mitchell and Robert Webb. After a long absence, a rejuvenated Stephen heads back to the John Barleycorn, just as Andrew is starting to feel restricted and weighed down by the mundanities of being a provincial pub landlord. However, the opening of a rival pub just up the road evokes curiosity – especially when it becomes apparent that the new establishment needs a manager.
Notable Continuing Series: Would I Lie To You?, 9.00pm, BBC One
9.00pm The Investigation BBC Two – Danish drama in Danish and Sweedish. Copenhagen chief of homicide Jens Moller learns of a missing Swedish journalist who has not returned from interviewing the designer of a home-made submarine. Initial garbled reports indicate that she and the designer have returned to harbour, but this proves to be false, as only the designer is rescued before the vessel sinks. A search for the woman is launched, but Moller decides to charge his suspect with murder, despite the lack of a body. Months of intricate detective work follow to ensure that justice is obtained. Soren Malling stars in this drama based on a true story.
9.00pm It's a Sin Channel 4 – Russell T Davies' drama, set in the 1980s during the Aids crisis, following the lives of a group of young gay men. September 1981 finds 18-year-old Ritchie leaving the Isle of Wight to go to university. In London, Roscoe walks out of parents' home, while Colin arrives from Wales to start a new career on Savile Row. The three boys meet, and along with fellow student Ash and best friend Jill form a gang and move into a flat, christened the Pink Palace. However, a distant threat on the horizon means that life in the '80s might be all too precious. Olly Alexander, Omari Douglas and Callum Scott Howells star.
9.00pm Tiger Sky Documentaries – First of a two-part documentary profiling golf's Tiger Woods.


text:
"""
PyTorch policy class used for APPO.

Adapted from VTraceTFPolicy to use the PPO surrogate loss.
Keep in sync with changes to VTraceTFPolicy.
"""

import gym
import numpy as np
import logging
from typing import Any, Dict, List, Optional, Type, Union

import ray
from ray.rllib.algorithms.appo.utils import make_appo_models
import ray.rllib.algorithms.impala.vtrace_torch as vtrace
from ray.rllib.algorithms.impala.impala_torch_policy import (
    make_time_major,
    VTraceOptimizer,
)
from ray.rllib.evaluation.episode import Episode
from ray.rllib.evaluation.postprocessing import (
    compute_gae_for_sample_batch,
    Postprocessing,
)
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.torch.torch_action_dist import (
    TorchDistributionWrapper,
    TorchCategorical,
)
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.policy.torch_mixins import (
    EntropyCoeffSchedule,
    LearningRateSchedule,
    KLCoeffMixin,
    ValueNetworkMixin,
    TargetNetworkMixin,
)
from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_torch
from ray.rllib.utils.numpy import convert_to_numpy
from ray.rllib.utils.torch_utils import (
    apply_grad_clipping,
    explained_variance,
    global_norm,
    sequence_mask,
)
from ray.rllib.utils.typing import TensorType

torch, nn = try_import_torch()

logger = logging.getLogger(__name__)

# We need this builder function because we want to share the same
# custom logics between TF1 dynamic and TF2 eager policies.
class APPOTorchPolicy(
    VTraceOptimizer,
    LearningRateSchedule,
    EntropyCoeffSchedule,
    KLCoeffMixin,
    ValueNetworkMixin,
    TargetNetworkMixin,
    TorchPolicyV2,
):
    """PyTorch policy class used with APPO."""

    def __init__(self, observation_space, action_space, config):
        config = dict(ray.rllib.algorithms.appo.appo.APPOConfig().to_dict(), **config)

        # Although this is a no-op, we call __init__ here to make it clear
        # that base.__init__ will use the make_model() call.
        VTraceOptimizer.__init__(self)
        LearningRateSchedule.__init__(self, config["lr"], config["lr_schedule"])

        TorchPolicyV2.__init__(
            self,
            observation_space,
            action_space,
            config,
            max_seq_len=config["model"]["max_seq_len"],
        )

        EntropyCoeffSchedule.__init__(
            self, config["entropy_coeff"], config["entropy_coeff_schedule"]
        )
        ValueNetworkMixin.__init__(self, config)
        KLCoeffMixin.__init__(self, config)

        # TODO: Don't require users to call this manually.
        self._initialize_loss_from_dummy_batch()

        # Initiate TargetNetwork ops after loss initialization.
        TargetNetworkMixin.__init__(self)

    @override(TorchPolicyV2)
    def init_view_requirements(self):
        self.view_requirements = self._get_default_view_requirements()

    @override(TorchPolicyV2)
    def make_model(self) -> ModelV2:
        return make_appo_models(self)

    @override(TorchPolicyV2)
    def loss(
        self,
        model: ModelV2,
        dist_class: Type[ActionDistribution],
        train_batch: SampleBatch,
    ) -> Union[TensorType, List[TensorType]]:
        """Constructs the loss for APPO.

        With IS modifications and V-trace for Advantage Estimation.

        Args:
            model (ModelV2): The Model to calculate the loss for.
            dist_class (Type[ActionDistribution]): The action distr. class.
            train_batch: The training data.

        Returns:
            Union[TensorType, List[TensorType]]: A single loss tensor or a list
                of loss tensors.
        """
        target_model = self.target_models[model]

        model_out, _ = model(train_batch)
        action_dist = dist_class(model_out, model)

        if isinstance(self.action_space, gym.spaces.Discrete):
            is_multidiscrete = False
            output_hidden_shape = [self.action_space.n]
        elif isinstance(self.action_space, gym.spaces.multi_discrete.MultiDiscrete):
            is_multidiscrete = True
            output_hidden_shape = self.action_space.nvec.astype(np.int32)
        else:
            is_multidiscrete = False
            output_hidden_shape = 1

        def _make_time_major(*args, **kwargs):
            return make_time_major(
                self, train_batch.get(SampleBatch.SEQ_LENS), *args, **kwargs
            )

        actions = train_batch[SampleBatch.ACTIONS]
        dones = train_batch[SampleBatch.DONES]
        rewards = train_batch[SampleBatch.REWARDS]
        behaviour_logits = train_batch[SampleBatch.ACTION_DIST_INPUTS]

        target_model_out, _ = target_model(train_batch)

        prev_action_dist = dist_class(behaviour_logits, model)
        values = model.value_function()
        values_time_major = _make_time_major(values)

        drop_last = self.config["vtrace"] and self.config["vtrace_drop_last_ts"]

        if self.is_recurrent():
            max_seq_len = torch.max(train_batch[SampleBatch.SEQ_LENS])
            mask = sequence_mask(train_batch[SampleBatch.SEQ_LENS], max_seq_len)
            mask = torch.reshape(mask, [-1])
            mask = _make_time_major(mask, drop_last=drop_last)
            num_valid = torch.sum(mask)

            def reduce_mean_valid(t):
                return torch.sum(t[mask]) / num_valid

        else:
            reduce_mean_valid = torch.mean

        if self.config["vtrace"]:
            logger.debug(
                "Using V-Trace surrogate loss (vtrace=True; " f"drop_last={drop_last})"
            )

            old_policy_behaviour_logits = target_model_out.detach()
            old_policy_action_dist = dist_class(old_policy_behaviour_logits, model)

            if isinstance(output_hidden_shape, (list, tuple, np.ndarray)):
                unpacked_behaviour_logits = torch.split(
                    behaviour_logits, list(output_hidden_shape), dim=1
                )
                unpacked_old_policy_behaviour_logits = torch.split(
                    old_policy_behaviour_logits, list(output_hidden_shape), dim=1
                )
            else:
                unpacked_behaviour_logits = torch.chunk(
                    behaviour_logits, output_hidden_shape, dim=1
                )
                unpacked_old_policy_behaviour_logits = torch.chunk(
                    old_policy_behaviour_logits, output_hidden_shape, dim=1
                )

            # Prepare actions for loss.
            loss_actions = (
                actions if is_multidiscrete else torch.unsqueeze(actions, dim=1)
            )

            # Prepare KL for loss.
            action_kl = _make_time_major(
                old_policy_action_dist.kl(action_dist), drop_last=drop_last
            )

            # Compute vtrace on the CPU for better perf.
            vtrace_returns = vtrace.multi_from_logits(
                behaviour_policy_logits=_make_time_major(
                    unpacked_behaviour_logits, drop_last=drop_last
                ),
                target_policy_logits=_make_time_major(
                    unpacked_old_policy_behaviour_logits, drop_last=drop_last
                ),
                actions=torch.unbind(
                    _make_time_major(loss_actions, drop_last=drop_last), dim=2
                ),
                discounts=(1.0 - _make_time_major(dones, drop_last=drop_last).float())
                * self.config["gamma"],
                rewards=_make_time_major(rewards, drop_last=drop_last),
                values=values_time_major[:-1] if drop_last else values_time_major,
                bootstrap_value=values_time_major[-1],
                dist_class=TorchCategorical if is_multidiscrete else dist_class,
                model=model,
                clip_rho_threshold=self.config["vtrace_clip_rho_threshold"],
                clip_pg_rho_threshold=self.config["vtrace_clip_pg_rho_threshold"],
            )

            actions_logp = _make_time_major(
                action_dist.logp(actions), drop_last=drop_last
            )
            prev_actions_logp = _make_time_major(
                prev_action_dist.logp(actions), drop_last=drop_last
            )
            old_policy_actions_logp = _make_time_major(
                old_policy_action_dist.logp(actions), drop_last=drop_last
            )
            is_ratio = torch.clamp(
                torch.exp(prev_actions_logp - old_policy_actions_logp), 0.0, 2.0
            )
            logp_ratio = is_ratio * torch.exp(actions_logp - prev_actions_logp)
            self._is_ratio = is_ratio

            advantages = vtrace_returns.pg_advantages.to(logp_ratio.device)
            surrogate_loss = torch.min(
                advantages * logp_ratio,
                advantages
                * torch.clamp(
                    logp_ratio,
                    1 - self.config["clip_param"],
                    1 + self.config["clip_param"],
                ),
            )

            mean_kl_loss = reduce_mean_valid(action_kl)
            mean_policy_loss = -reduce_mean_valid(surrogate_loss)

            # The value function loss.
            value_targets = vtrace_returns.vs.to(values_time_major.device)
            if drop_last:
                delta = values_time_major[:-1] - value_targets
            else:
                delta = values_time_major - value_targets
            mean_vf_loss = 0.5 * reduce_mean_valid(torch.pow(delta, 2.0))

            # The entropy loss.
            mean_entropy = reduce_mean_valid(
                _make_time_major(action_dist.entropy(), drop_last=drop_last)
            )

        else:
            logger.debug("Using PPO surrogate loss (vtrace=False)")

            # Prepare KL for Loss
            action_kl = _make_time_major(prev_action_dist.kl(action_dist))

            actions_logp = _make_time_major(action_dist.logp(actions))
            prev_actions_logp = _make_time_major(prev_action_dist.logp(actions))
            logp_ratio = torch.exp(actions_logp - prev_actions_logp)

            advantages = _make_time_major(train_batch[Postprocessing.ADVANTAGES])
            surrogate_loss = torch.min(
                advantages * logp_ratio,
                advantages
                * torch.clamp(
                    logp_ratio,
                    1 - self.config["clip_param"],
                    1 + self.config["clip_param"],
                ),
            )

            mean_kl_loss = reduce_mean_valid(action_kl)
            mean_policy_loss = -reduce_mean_valid(surrogate_loss)

            # The value function loss.
            value_targets = _make_time_major(train_batch[Postprocessing.VALUE_TARGETS])
            delta = values_time_major - value_targets
            mean_vf_loss = 0.5 * reduce_mean_valid(torch.pow(delta, 2.0))

            # The entropy loss.
            mean_entropy = reduce_mean_valid(_make_time_major(action_dist.entropy()))

        # The summed weighted loss
        total_loss = (
            mean_policy_loss
            + mean_vf_loss * self.config["vf_loss_coeff"]
            - mean_entropy * self.entropy_coeff
        )

        # Optional additional KL Loss
        if self.config["use_kl_loss"]:
            total_loss += self.kl_coeff * mean_kl_loss

        # Store values for stats function in model (tower), such that for
        # multi-GPU, we do not override them during the parallel loss phase.
        model.tower_stats["total_loss"] = total_loss
        model.tower_stats["mean_policy_loss"] = mean_policy_loss
        model.tower_stats["mean_kl_loss"] = mean_kl_loss
        model.tower_stats["mean_vf_loss"] = mean_vf_loss
        model.tower_stats["mean_entropy"] = mean_entropy
        model.tower_stats["value_targets"] = value_targets
        model.tower_stats["vf_explained_var"] = explained_variance(
            torch.reshape(value_targets, [-1]),
            torch.reshape(
                values_time_major[:-1] if drop_last else values_time_major, [-1]
            ),
        )

        return total_loss

    @override(TorchPolicyV2)
    def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]:
        """Stats function for APPO. Returns a dict with important loss stats.

        Args:
            policy: The Policy to generate stats for.
            train_batch: The SampleBatch (already) used for training.

        Returns:
            Dict[str, TensorType]: The stats dict.
        """
        stats_dict = {
            "cur_lr": self.cur_lr,
            "total_loss": torch.mean(torch.stack(self.get_tower_stats("total_loss"))),
            "policy_loss": torch.mean(
                torch.stack(self.get_tower_stats("mean_policy_loss"))
            ),
            "entropy": torch.mean(torch.stack(self.get_tower_stats("mean_entropy"))),
            "entropy_coeff": self.entropy_coeff,
            "var_gnorm": global_norm(self.model.trainable_variables()),
            "vf_loss": torch.mean(torch.stack(self.get_tower_stats("mean_vf_loss"))),
            "vf_explained_var": torch.mean(
                torch.stack(self.get_tower_stats("vf_explained_var"))
            ),
        }

        if self.config["vtrace"]:
            is_stat_mean = torch.mean(self._is_ratio, [0, 1])
            is_stat_var = torch.var(self._is_ratio, [0, 1])
            stats_dict["mean_IS"] = is_stat_mean
            stats_dict["var_IS"] = is_stat_var

        if self.config["use_kl_loss"]:
            stats_dict["kl"] = torch.mean(
                torch.stack(self.get_tower_stats("mean_kl_loss"))
            )
            stats_dict["KL_Coeff"] = self.kl_coeff

        return convert_to_numpy(stats_dict)

    @override(TorchPolicyV2)
    def extra_action_out(
        self,
        input_dict: Dict[str, TensorType],
        state_batches: List[TensorType],
        model: TorchModelV2,
        action_dist: TorchDistributionWrapper,
    ) -> Dict[str, TensorType]:
        out = {}
        if not self.config["vtrace"]:
            out[SampleBatch.VF_PREDS] = model.value_function()
        return out

    @override(TorchPolicyV2)
    def postprocess_trajectory(
        self,
        sample_batch: SampleBatch,
        other_agent_batches: Optional[Dict[Any, SampleBatch]] = None,
        episode: Optional["Episode"] = None,
    ):
        # Call super's postprocess_trajectory first.
        sample_batch = super().postprocess_trajectory(
            sample_batch, other_agent_batches, episode
        )
        if not self.config["vtrace"]:
            # Do all post-processing always with no_grad().
            # Not using this here will introduce a memory leak
            # in torch (issue #6962).
            with torch.no_grad():
                sample_batch = compute_gae_for_sample_batch(
                    self, sample_batch, other_agent_batches, episode
                )
        return sample_batch

    @override(TorchPolicyV2)
    def extra_grad_process(
        self, optimizer: "torch.optim.Optimizer", loss: TensorType
    ) -> Dict[str, TensorType]:
        return apply_grad_clipping(self, optimizer, loss)

    @override(TorchPolicyV2)
    def get_batch_divisibility_req(self) -> int:
        return self.config["rollout_fragment_length"]


Why visit Cordes sur Ciel?
The Gothic architecture of a bastide packed with legends.
Its Fêtes du Grand Fauconnier Festival in July.
Neighbouring medieval towns: Castelnau-de-Montmiral, Puycelsi, Penne, Bruniquel.
Close to Albi (30 mins).
« Travellers watching the summer night sky from the Cordes terrace realise they don't need to go any further and that, if they want, the beauty here will lift them out of their solitude day after day » - Albert Camus.
Explore Cordes sur Ciel on foot. Take your time climbing up its steep cobbled lanes with your head in the clouds. Soak up every inch of the colourful medieval setting with elaborate Gothic buildings.
25km from Albi in the Tarn, this is one of the oldest bastides in Occitania, founded in 1222 by Raymond IV, Count of Toulouse. Nestled on the rocky Puech de Mordagne ridge, Cordes brings you unforgettable views of Cérou Valley from the top of its ramparts.
Cordes sur Ciel is a gem carved into stone. Admire the sculpted walls of the Maison du Grand Fauconnier, Maison du Grand Ecuyer and Maison du Grand Veneur. It is famous for the hunting scene sculpted on the 2nd floor. Be sure to stop at the Maison Prunet on Place de la Bride and its staggering panorama.
As a town for wealthy traders, Cordes has inherited their luxury houses. Every period of Gothic architecture appears here: from primitive and 13th century to the dawn of the 14th century and the flamboyant 15th century.
Cordes is famous for its legends that are literally written in stone: sculpted creatures, St James signs, alchemist symbols and Cathar references. Open your eyes!
Cordes-sur-Ciel has always attracted artists and artisans to its magical setting. Step into workshops home to potters, painters and jewellery makers. Quiz the artisans about wood and leather. There are also art galleries and museums in the town. Visit the Museum of Modern and Contemporary Art or the Sugar and Chocolate Art Museum by Yves Thuriès! Be sure not to miss the Medieval Festivals: you'll join the rest of the village and its locals in the Middle Ages!
Try a Croquant de Cordes, the ultimate local speciality made from flour, egg white, sugar, almonds and a dash of mystery to make it unique!
There are countless medieval towns in Cordes Country, often on the hilltops. The fortified town of Puycelsi is listed as one of the Most Beautiful Villages in France alongside the bastide of Castelnau-de-Montmiral.
Two gems lie 40 mins from Cordes sur Ciel in the Gorges de l'Aveyron: Penne and its 10th century château (under renovation) and Bruniquel. Sitting on the top of a cliff, Bruniquel châteaus, where The Old Gun was filmed, are the first things that grab your attention. The magic continues as you wander around the medieval town built in stages. Absolutely unmissable!
In 2017, structures dating back 176,500 years were discovered in Bruniquel Cave making them the oldest in the history of mankind to date! The cave isn't open to visitors but there's a room devoted to it at the Bruniquel châteaus.
Join Margot from the youMAKEfashion blog and Romain Costa as they visit Cordes sur Ciel, named France's Favourite Village in 2014 during a famous TV show. Video 1:03 © TarnTourisme.
The AOC Gaillac vineyards span from the Tarn's banks to the foot of Cordes sur Ciel. There are vineyards and wineries where it's a joy to stop and heighten the pleasure of exploring the town and its surrounding villages.
Charming guest house nestled against the southern ramparts.
Cordes sur Ciel is 85km north-east of Toulouse in the Tarn.
By car : from Toulouse, take the A68 to Gaillac then the D922 to Cordes. Take the A20 from Paris and exit at Caussade. It's a 3 hr drive from Montpellier via Rodez and Carmaux.
By plane : from Toulouse-Blagnac Airport (approximately 90km). Rodez-Marcillac Airport is 75 mins away on the main road.
By train : Cordes-Vindrac station is 5km from the old town with daily TER regional train connections from Toulouse, Albi and Brive.


Android 4.2 Jelly Bean brought quite a few new features to the ASUS Nexus 7, but it also brought a number of bugs along as well. Many users have been having trouble with significant lag (possibly the fault of Google Currents) after the update, although I haven't had a problem yet, but a smaller subset of users has discovered an even more odd bug. According to at least two separate accounts, when using a secondary user account on the Nexus 7, the homescreen appears to bleed through other fullscreen apps such as games.
As you can see above, the problem makes games nearly unplayable, and certainly looks quite odd. There are different reports as to what causes the bug, but overall most agree that it is common when logged into a second user account. Resetting the tablet sometimes seems to solve the problem, while others have decided that the issue is related to hardware and gotten replacement devices from Google. I haven't been able to replicate the issue, but it clearly exists. While the reports and details are quite varied, then, there is plenty of evidence to suggest that this is a real problem, and one that Google will hopefully address.
For now, the simple solution for anyone experiencing this problem is to switch to the tablet's primary user account (and in some cases, disable the other account), but a solution that takes away the new feature really doesn't do too much good. It seems likely that this problem is simply a software multitasking issue that Google could fix with an update, which would certainly be the best case scenario for both consumers and Google. I doubt either wants another bunch of tablets sent back for repairs.


text:
Ministry of Education, Culture, Sports, Science and Technology Web Site. Top of the page.
Jump to Main Contents
About MEXT
MEXT
List of Senior Officials
MEXT Logo
Address of MEXT
Museum of MEXT
National Councils
Report&Statistics
June 17th, 2019 109th Japan Academy Award Ceremony
The 109th Japan Academy Award Ceremony was held at the Japan Academy in Ueno, Tokyo, with their Majesties in attendance.
This award has a long history dating back to 1911 and is Japan's most prestigious award. For this year's 109th ceremony, nine researchers were awarded for their outstanding research achievements.
In a complimentary address, MEXT Minister Shibayama Masahiko paid his deep respects to the awardees for their achievements, and to their families and relevant parties who supported their research activities. The minister said MEXT aims to build a society that continuously creates innovation, and will work to strengthen Japan's research prowess by advancing academic research based on researcher's unconventional thinking, and enhance support to cultivate and assist researchers who take leadership on the global stage.
https://www.japan-acad.go.jp/japanese/news/2019/031201.html
Top of MEXT Homepage
MEXT Homepage Privacy Policy
MEXT Website Linking Policy and Copyrights
MEXT Website Usage Policy
Ministry of Education, Culture, Sports, Science and Technology (MEXT)
3-2-2 Kasumigaseki, Chiyoda-ku, Tokyo 100-8959, Japan
Tel : +81-(0)3-5253-4111(Reception)


text:
Getting to know: Kidsgrove Athletic FC
Some clubs don't do a lot for their community, some do more than their fair share. One club that's looking to do more is today's 'getting to know' Kidsgrove Athletic FC.
It was announced in November last year that the club were exploring ways to renovate the current site of the club at the Autonet Insurance Stadium to create a community hub and become a social centre for the local area, thereby providing more for their community than they already do.
'The Grove' currently run junior sides from under 7's upwards to under 17's, not bad for a side that was originally formed in December 1952 purely for local men to play in the side. The club are set to host mini tournaments for their junior sides on the first team pitch, an experience we are sure the youngsters won't forget.
Wow. Pitches ready for tomorrow which will see our Under 10s play at a mini tournamount at our first team ground. Our under 8s and 7s having games as well. Kick off starts at 9.30 in the morning. Fancy coming watch ? It's all free a festival of football @officialkafc home pic.twitter.com/sRhYRq0TBc
— KidsgroveAthleticYth (@KidsgroveAthAc) May 4, 2019
Kidsgrove currently play at Hollinwood Road, a ground which they took a year out of the game in 1961 to build. Having originally played games at the Vickers and Goodwin pitch next to the A50. Improvements to the stadium were made in throughout the 80's and 90's such as new floodlights in 1992, which were opened with a game against Stoke City.
On the pitch now, and Kidsgrove do have a long successful history winning a whole host of cups and leagues on their rise from amateur football. They've won the North West Counties League twice and the Mid Cheshire League, add this to the 5 Stafforshire Senior Cups and 'The Grove' have quite a rich history.
Hollinwood Road, Home of Kidsgrove Athletic FC
In the present day, Kidsgrove have just finished a long campaign in the Evo-Stick Division One West in 10th place, solidly mid-table and have made a drastic improvement on their 18th place finish last season, this along with being one win away from the FA Cup first round shows just what progress is being made.
From everyone here at 'Climbing The Ladder' we would just like to wish everyone at Kidsgrove all the best for next season.
Author Alex ScottPosted on May 9, 2019 Categories Club Profiles, Getting to knowTags English Football, Evo Stick, football, Hollinwood Road, Kidsgrove Athletic, Mid Cheshire League, Non-League, NWCL, Semi-pro, Staffordshire, Stoke, Twitter
Previous Previous post: Match Report: Penrith Academy vs Burneside FC (Peter Daws Memorial Shield)
Next Next post: Getting to know: The Peoples FC
Climbing The Ladder Blog at WordPress.com.


This race series consists of 8 road races, all on summer evenings. For 2019 only, only the first 7 races will count towards the series results. The overall series prizes will be awarded at Milton Keynes.
Each runner's finishing position is calculated by age category, aggregated, & carried forward to the next race in the series. Only the best 5 results are counted, & prizes are awarded both by the promoting Club on each race night, & by the sponsors after the final race, covering age categories & teams. You can register for all eight road races in one go (£58 for England Athletics affiliated Members and £68 for unaffiliated runners) when you enter the first race at Blisworth. This offer closes on 14 May 2019.
Series Team results: Each event organizer can determine his/her prize structure, including team awards. However, for the Grand Prix Series, teams (Men/Vet Men – 4 to score, and Women/Vet Women – 3 to score) must consist of first-claim members of the same England Athletics affiliated club.
More details can be obtained from Mick Bromilow.
You can enter the whole series online here. Most of the races below encourage online entries. If you can't enter online you can complete an editable pdf file here for the whole series, or here to enter individual races in the series.
All races start at 7:45pm except Silverstone (which starts at 6:30pm).
The race at Silverstone has to be in September this year because of maintenance work on the course. New numbers for chip timing will be used at Silverstone.
On 27 July 2019, Marshall Milton Keynes will be holding a series of 5000m races – the MK5000 PB Special – at their Stantonbury Athletics Track. Entries are now being taken online for this event, for U20s and Seniors. There will be a beer tent and street food throughout the event. Only 350 places are available. Entry standards are sub 22 minutes for both men and women.