text:
<?php

namespace JF\CoreBundle\Controller\Traits;

trait InstallController {

    protected function findPackage($sigla) {
        return $this->findOneBy('JFCoreBundle:Package', array('sigla' => $sigla));
    }

    protected function findGruppo(\JF\CoreBundle\Entity\Package $package, $sigla) {
        return $this->findOneBy('JFCoreBundle:Gruppo', array('package' => $package->getId(), 'sigla' => $sigla));
    }

    protected function findLicenza(\JF\CoreBundle\Entity\Gruppo $gruppo, $sigla) {
        return $this->findOneBy('JFCoreBundle:Licenza', array('gruppo' => $gruppo->getId(), 'sigla' => $sigla));
    }

    protected function installPackage($sigla, $nome, $descrizione) {
        $package = $this->findPackage($sigla);
        if (!$package) {
            $package = new \JF\CoreBundle\Entity\Package();
            $package->setSigla($sigla)
                    ->setNome($nome)
                    ->setDescrizione($this->renderView($descrizione));
            $this->persist($package);
        } else {
            $package->setNome($nome)
                    ->setDescrizione($this->renderView($descrizione));
            $this->persist($package);
        }
    }

    protected function installGruppo($package, $sigla, $nome, $descrizione) {
        $package = $this->findPackage($package);
        $gruppo = $this->findGruppo($package, $sigla);
        if (!$gruppo) {
            $gruppo = new \JF\CoreBundle\Entity\Gruppo();
            $gruppo->setSigla($sigla)
                    ->setPackage($package)
                    ->setNome($nome)
                    ->setDescrizione($this->renderView($descrizione));
            $this->persist($gruppo);
        } else {
            $gruppo->setNome($nome)
                    ->setDescrizione($this->renderView($descrizione));
            $this->persist($gruppo);
        }
    }

    protected function newLicenza($package, $gruppo, $sigla, $ordine, $nome, $descrizione, $durata, $roles, $widgets, $params, $prezzo, $sconto = null, $autoinstall = false, $market = true) {
        $package = $this->findPackage($package);
        $gruppo = $this->findGruppo($package, $gruppo);
        $licenza = $this->findLicenza($gruppo, $sigla);
        if (!$licenza) {
            $licenza = new \JF\CoreBundle\Entity\Licenza();
            $licenza->setGruppo($gruppo)
                    ->setOrdine($ordine)
                    ->setSigla($sigla)
                    ->setNome($nome)
                    ->setDescrizione($this->renderView($descrizione))
                    ->setDurata($durata)
                    ->setRoles($roles)
                    ->setWidgets($widgets)
                    ->setParams($params)
                    ->setPrezzo($prezzo)
                    ->setSconto($sconto ? : $prezzo)
                    ->setAutoinstall($autoinstall)
                    ->setMarket($market)
                    ->setStato($sconto ? \JF\CoreBundle\Entity\Licenza::$S_LIM : \JF\CoreBundle\Entity\Licenza::$S_NEW)
            ;
            if (!$market) {
                $licenza->setStato(\JF\CoreBundle\Entity\Licenza::$S_HID);
            }
            $this->persist($licenza);
        } else {
            $stato = \JF\CoreBundle\Entity\Licenza::$S_NOP;
            $descrizione = $this->renderView($descrizione);
            if ($licenza->getDescrizione() != $descrizione) {
                $licenza->setDescrizione($descrizione);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getOrdine() != $ordine) {
                $licenza->setOrdine($ordine);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getNome() != $nome) {
                $licenza->setNome($nome);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getDurata() != $durata) {
                $licenza->setDurata($durata);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getAutoinstall() != $autoinstall) {
                $licenza->setAutoinstall($autoinstall);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getRoles() != $roles) {
                $licenza->setRoles($roles);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getParams() != $params) {
                $licenza->setParams($params);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getWidgets() != $widgets) {
                $licenza->setWidgets($widgets);
                $stato = \JF\CoreBundle\Entity\Licenza::$S_UPD;
            }
            if ($licenza->getPrezzo() != $prezzo) {
                $stato = $licenza->getPrezzo() > $prezzo ? \JF\CoreBundle\Entity\Licenza::$S_DOW : \JF\CoreBundle\Entity\Licenza::$S_UPD;
                $licenza->setPrezzo($prezzo);
                $licenza->setSconto($prezzo);
            }
            if ($sconto) {
                $stato = \JF\CoreBundle\Entity\Licenza::$S_SAL;
                $licenza->setSconto($sconto);
            }
            if ($licenza->getMarket()) {
                if (!$market) {
                    $licenza->setMarket($market);
                    $stato = \JF\CoreBundle\Entity\Licenza::$S_DEL;
                }
            } else {
                $stato = \JF\CoreBundle\Entity\Licenza::$S_HID;
            }
            $licenza->setStato($stato);
            $this->persist($licenza);
        }

        if ($licenza->getAutoinstall()) {
            foreach ($this->findBy('JFACLBundle:Cliente', array()) as $cliente) {
                if (!$this->findOneBy('JFACLBundle:Licenza', array('gruppo' => $gruppo, 'cliente' => $cliente->getId()))) {
                    $_licenza = new \JF\ACLBundle\Entity\Licenza();
                    $_licenza->setLicenza($licenza);
                    $_licenza->setCliente($cliente);
                    $_licenza->setPagamento(new \DateTime());
                    $this->persist($_licenza);
                }
            }
        }

        return array('codice' => $licenza->getCodiceEsteso(), 'stato' => $licenza->getStatoTestuale());
    }

}


text:
package com.nulabinc.backlog.r2b.exporter.core

import com.nulabinc.backlog.migration.common.conf.BacklogPaths
import com.nulabinc.backlog.migration.common.domain.BacklogProjectKey
import com.nulabinc.backlog.r2b.exporter.conf.ExportConfig
import com.nulabinc.backlog.r2b.exporter.convert._
import com.nulabinc.backlog.r2b.mapping.core.MappingContainer
import com.nulabinc.backlog.r2b.redmine.conf.RedmineApiConfiguration
import com.nulabinc.backlog.r2b.redmine.domain.{PropertyValue, RedmineProjectId}
import com.nulabinc.backlog.r2b.redmine.service.{IssueService, ProjectService, WikiService}

case class ExportContext(
    apiConfig: RedmineApiConfiguration,
    backlogProjectKey: BacklogProjectKey,
    exportConfig: ExportConfig,
    projectId: RedmineProjectId,
    backlogPaths: BacklogPaths,
    propertyValue: PropertyValue,
    mappingContainer: MappingContainer,
    projectService: ProjectService,
    issueService: IssueService,
    wikiService: WikiService,
    issueWrites: IssueWrites,
    journalWrites: JournalWrites,
    userWrites: UserWrites,
    customFieldWrites: CustomFieldWrites,
    customFieldValueWrites: CustomFieldValueWrites,
    attachmentWrites: AttachmentWrites,
    wikiWrites: WikiWrites
)

redpajama_set_name: RedPajamaGithub


text:
Dead simple unit tests that make programming easier.

##Usage

Our function:

```javascript
function addOne(i) {
  return i + 1
}
```

Create a new test:

```javascript
tests.addAssert(addOne(1) == 2, 'Add One');
```

Run test(s):

```javascript
tests.results();
```


text:
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { removeNgStyles, createNewHosts } from '@angularclass/hmr';

/*
 * Platform and Environment providers/directives/pipes
 */
import { ENV_PROVIDERS } from './environment';
import { ROUTES } from './app.routes';
// App is our top level component
import { App } from './app.component';
import { APP_RESOLVER_PROVIDERS } from './app.resolver';
import { AppState, InteralStateType } from './app.service';

import { Navbar } from './navbar';
import { Footer } from './footer/footer.component';

import { Home } from './home';
import { About } from './about';
import { Apply } from './apply';
import { NoContent } from './no-content';

// Application wide providers
const APP_PROVIDERS = [
  ...APP_RESOLVER_PROVIDERS,
  AppState
];

type StoreType = {
  state: InteralStateType,
  disposeOldHosts: () => void
};

/**
 * `AppModule` is the main entry point into Angular2's bootstraping process
 */
@NgModule({
  bootstrap: [ App ],
  declarations: [
    App,
    Navbar,
    Footer,
    Home,
    About,
    Apply,
    NoContent
  ],
  imports: [ // import Angular's modules
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(ROUTES, { useHash: true })
  ],
  providers: [ // expose our Services and Providers into Angular's dependency injection
    ENV_PROVIDERS,
    APP_PROVIDERS
  ]
})
export class AppModule {
  constructor(public appRef: ApplicationRef, public appState: AppState) {}
  hmrOnInit(store: StoreType) {
    if (!store || !store.state) return;
    console.log('HMR store', store);
    this.appState._state = store.state;
    this.appRef.tick();
    delete store.state;
  }
  hmrOnDestroy(store: StoreType) {
    const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
    // recreate elements
    const state = this.appState._state;
    store.state = state;
    store.disposeOldHosts = createNewHosts(cmpLocation);
    // remove styles
    removeNgStyles();
  }
  hmrAfterDestroy(store: StoreType) {
    // display new elements
    store.disposeOldHosts();
    delete store.disposeOldHosts;
  }
}


text:
package org.slc.sli.api.resources.generic.response;

import javax.ws.rs.core.UriInfo;

import org.springframework.beans.factory.annotation.Autowired;

import org.slc.sli.api.resources.generic.representation.Resource;
import org.slc.sli.api.resources.generic.service.ResourceAccessLog;
import org.slc.sli.api.resources.generic.util.ResourceHelper;
import org.slc.sli.api.resources.generic.util.ResourceMethod;
import org.slc.sli.api.resources.generic.util.ResourceTemplate;

/**
 * Base response builder
 *
 * @author srupasinghe
 * @author jstokes
 * @author pghosh
 *
 */

public abstract class ResponseBuilder {

    @Autowired
    protected ResourceHelper resourceHelper;

    @Autowired
    private ResourceAccessLog resourceAccessLog;

    protected Resource constructAndCheckResource(final UriInfo uriInfo, final ResourceTemplate template,
                                                 final ResourceMethod method) {

        Resource resource = resourceHelper.getResourceName(uriInfo, template);

        //log security events
        resourceAccessLog.logAccessToRestrictedEntity(uriInfo, resource, GetResponseBuilder.class.toString());

        return resource;
    }

}


text:
package util

import (
	"fmt"
	"io"
	"os"
	"time"
)

// Until endlessly loops the provided function until a message is received on the done channel.
// The function will wait the duration provided in sleep between function calls. Errors will be sent on provider Writer.
func Until(fn func() error, w io.Writer, name string, sleep time.Duration, done <-chan struct{}) {
	var exitErr error
	for {
		select {
		case <-done:
			return
		default:
			exitErr = fn()
			if exitErr == nil {
				fmt.Fprintf(w, Pad("%s: Exited with no errors.\n"), name)
			} else {
				fmt.Fprintf(w, Pad("%s: Exit with error: %v"), name, exitErr)
			}

			// wait provided duration before trying again
			time.Sleep(sleep)
		}
	}
}

func Pad(str string) string {
	return fmt.Sprint("\n%s\n", str)
}

// If the file represented by path exists and
// readable, return true otherwise return false.
func CanReadFile(path string) bool {
	f, err := os.Open(path)
	if err != nil {
		return false
	}

	defer f.Close()

	return true
}

func Retry(attempts int, callback func() error) (err error) {
	return RetryAfter(attempts, callback, 0)
}

func RetryAfter(attempts int, callback func() error, d time.Duration) (err error) {
	for i := 0; i < attempts; i++ {
		err = callback()
		if err == nil {
			return nil
		}
		time.Sleep(d)
	}
	return err
}


text:
<?php

namespace CoderStudios\LP\Http\Controllers;

use App\Http\Controllers\Controller;

class LPController extends Controller
{
	public function lp()
	{
        	$vars = [];
        	return view('vendor.lp.lp', compact('vars'))->render();
	}
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Marketing;
using Vevo.Domain.Products;
using Vevo.WebUI;
using Vevo.Deluxe.Domain;
using Vevo.Domain.Orders;
using Vevo.Domain.Users;
using Vevo.Deluxe.Domain.GiftRegistry;

public partial class GiftRegistryItemList : Vevo.Deluxe.WebUI.Base.BaseDeluxeLanguagePage
{
    private string GiftRegistryID
    {
        get
        {
            return Request.QueryString["GiftRegistryID"];
        }
    }

    private bool IsExitsInCurrentStore( string productID )
    {
        Product product = DataAccessContext.ProductRepository.GetOne(
            StoreContext.Culture, productID, DataAccessContext.StoreRetriever.GetCurrentStoreID() );

        string rootID = DataAccessContext.Configurations.GetValue(
                "RootCategory",
                DataAccessContext.StoreRepository.GetOne( DataAccessContext.StoreRetriever.GetCurrentStoreID() ) );

        return product.IsAvailable( rootID );
    }

    private void PopulateControls()
    {
        GiftRegistry giftRegistry = DataAccessContextDeluxe.GiftRegistryRepository.GetOne( GiftRegistryID );
        uxEventNameLable.Text = giftRegistry.EventName;
        uxEventDateLabel.Text = giftRegistry.EventDate.ToShortDateString();

        IList<GiftRegistryItem> itemList = DataAccessContextDeluxe.GiftRegistryItemRepository.GetAllByGiftRegistryID( GiftRegistryID );

        for (int i = 0; i < itemList.Count; i++)
        {
            if (!IsExitsInCurrentStore( itemList[i].ProductID ))
                itemList.RemoveAt( i );
        }

        uxGrid.DataSource = itemList;
        uxGrid.DataBind();

        if (uxGrid.Rows.Count == 0)
        {
            uxUpdateQuantityButton.Visible = false;
        }
    }

    private void UpdateQuantity()
    {
        ArrayList productNameList = new ArrayList();
        int rowIndex;
        for (rowIndex = 0; rowIndex < uxGrid.Rows.Count; rowIndex++)
        {
            GridViewRow row = uxGrid.Rows[rowIndex];
            if (row.RowType == DataControlRowType.DataRow)
            {
                string wantQuantityText = ((TextBox) row.FindControl( "uxWantQuantityText" )).Text;
                string hasQuantityText = ((Label) row.FindControl( "uxHasQuantityLabel" )).Text.Trim();
                int wantQuantity, hasQuantity;
                if (int.TryParse( wantQuantityText, out wantQuantity ) && int.TryParse( hasQuantityText, out hasQuantity ))
                {
                    GiftRegistryItem item = DataAccessContextDeluxe.GiftRegistryItemRepository.GetOne( uxGrid.DataKeys[rowIndex].Value.ToString() );

                    if (wantQuantity >= hasQuantity)
                    {
                        item.WantQuantity = wantQuantity;
                        DataAccessContextDeluxe.GiftRegistryItemRepository.Save( item );
                    }
                    else
                    {
                        productNameList.Add( item.ProductName );
                    }
                }
                else
                {
                    uxMessage.DisplayError( "Quantity is invalid." );
                    return;
                }
            }
        }

        if (productNameList.Count > 0)
        {
            System.Text.StringBuilder errorMessage = new System.Text.StringBuilder();
            errorMessage.Append( "Cannot update quantity. Want Quantity cannot be less than Has Quantity.
" );
            errorMessage.Append( "Please correct the following product quantity:" );
            errorMessage.Append( "
" );
            for (int i = 0; i < productNameList.Count; i++)
            {
                errorMessage.Append( "
" );
                errorMessage.Append( productNameList[i].ToString() );
                errorMessage.Append( "
" );
            }
            errorMessage.Append( "
" );

            uxMessage.DisplayError( errorMessage.ToString() );
        }
        else
        {
            uxMessage.DisplayMessage( "Update quantity successfully." );
        }
    }

    private bool IsValidUserName( string userName )
    {
        return Page.User.Identity.IsAuthenticated &&
            String.Compare( userName, Page.User.Identity.Name, true ) == 0;
    }

    private void RegisterJavaScript()
    {
        string script = "var win=null;" +
            "function NewWindow(mypage,myname,w,h,pos,infocus){" +
            "if(pos==\"random\"){myleft=(screen.width)?Math.floor(Math.random()*" +
            "(screen.width-w)):100;mytop=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}" +
            "if(pos==\"center\"){myleft=(screen.width)?(screen.width-w)/2:100;mytop=(screen.height)?(screen.height-h)/2:100;}" +
            "else if((pos!='center' && pos!=\"random\") || pos==null){myleft=0;mytop=20}" +
            "settings=\"width=\" + w + \",height=\" + h + \",top=\" + mytop + \",left=\" + myleft + \",scrollbars=yes," +
            "location=yes,directories=no,status=no,menubar=no,toolbar=no,resizable=yes\";win=window.open(mypage,myname,settings);" +
            "win.focus();}";

        ScriptManager.RegisterStartupScript( this, this.GetType(), "PopupWindow", script, true );
    }

    protected void Page_Load( object sender, EventArgs e )
    {
        RegisterJavaScript();
    }

    protected void Page_PreRender( object sender, EventArgs e )
    {
        string userName = DataAccessContextDeluxe.GiftRegistryRepository.GetOne( GiftRegistryID ).UserName;
        if (!IsValidUserName( userName ))
        {
            uxErrorLiteral.Visible = true;
            uxGiftRegistryItemListPanel.Visible = false;
            uxUpdateQuantityButton.Visible = false;
        }
        else
            PopulateControls();
    }

    protected void uxGrid_RowDeleting( object sender, GridViewDeleteEventArgs e )
    {
        string giftRegistryItemID = uxGrid.DataKeys[e.RowIndex].Value.ToString();
        DataAccessContextDeluxe.GiftRegistryItemRepository.Delete( giftRegistryItemID );
        PopulateControls();
    }

    protected void uxUpdateQuantityButton_Click( object sender, EventArgs e )
    {
        UpdateQuantity();
        PopulateControls();
    }

    protected void uxAddNewItemButton_Click( object sender, EventArgs e )
    {
        Session["GiftRegistryID"] = GiftRegistryID;
        Response.Redirect( "~/Catalog.aspx" );
    }

    protected string GetUrl( string productID )
    {
        return "ProductPopUp.aspx?ProductID=" + productID;
    }

    protected void uxNameLink_PreRender( object sender, EventArgs e )
    {
        HyperLink link = (HyperLink) sender;
        string strRedirect = link.NavigateUrl;
        link.NavigateUrl = "javascript:NewWindow('" + strRedirect + "','acepopup','700','500','center','front');";
    }

    protected string GetPrice( string giftregistryItemID )
    {
        GiftRegistryItem giftRegistryItem = DataAccessContextDeluxe.GiftRegistryItemRepository.GetOne( giftregistryItemID );

        return StoreContext.Currency.FormatPrice(
            giftRegistryItem.GetUnitPrice( StoreContext.WholesaleStatus) );
    }

    protected bool IsVisble( string giftRegistryItemID )
    {
        return DataAccessContextDeluxe.GiftRegistryItemRepository.CanBeDeletedByGiftRegistryItemID( giftRegistryItemID );
    }

}


text:
import java.nio.channels.AsynchronousChannelGroup;
import java.util.concurrent.*;

/**
 * Test that arbitrary tasks can be submitted to a channel group's thread pool.
 */

public class AsExecutor {

    public static void main(String[] args) throws Exception {
        // create channel groups
        ThreadFactory factory = new PrivilegedThreadFactory();
        AsynchronousChannelGroup group1 = AsynchronousChannelGroup
            .withFixedThreadPool(5, factory);
        AsynchronousChannelGroup group2 = AsynchronousChannelGroup
            .withCachedThreadPool(Executors.newCachedThreadPool(factory), 0);
        AsynchronousChannelGroup group3 = AsynchronousChannelGroup
            .withThreadPool(Executors.newFixedThreadPool(10, factory));

        try {
            // execute simple tasks
            testSimpleTask(group1);
            testSimpleTask(group2);
            testSimpleTask(group3);

            // install security manager and test again
            System.setSecurityManager( new SecurityManager() );
            testSimpleTask(group1);
            testSimpleTask(group2);
            testSimpleTask(group3);

            // attempt to execute tasks that run with only frames from boot
            // class loader on the stack.
            testAttackingTask(group1);
            testAttackingTask(group2);
            testAttackingTask(group3);
        } finally {
            group1.shutdown();
            group2.shutdown();
            group3.shutdown();
        }
    }

    static void testSimpleTask(AsynchronousChannelGroup group) throws Exception {
        Executor executor = (Executor)group;
        final CountDownLatch latch = new CountDownLatch(1);
        executor.execute(new Runnable() {
            public void run() {
                latch.countDown();
            }
        });
        latch.await();
    }

    static void testAttackingTask(AsynchronousChannelGroup group) throws Exception {
        Executor executor = (Executor)group;
        Attack task = new Attack();
        executor.execute(task);
        task.waitUntilDone();
        if (!task.failedDueToSecurityException())
            throw new RuntimeException("SecurityException expected");
    }

}


text:
#include "webrtc/video_engine/vie_render_manager.h"

#include "webrtc/engine_configurations.h"
#include "webrtc/modules/video_render/include/video_render.h"
#include "webrtc/modules/video_render/include/video_render_defines.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/rw_lock_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/video_engine/vie_renderer.h"

namespace webrtc {

ViERenderManagerScoped::ViERenderManagerScoped(
    const ViERenderManager& vie_render_manager)
    : ViEManagerScopedBase(vie_render_manager) {
}

ViERenderer* ViERenderManagerScoped::Renderer(int32_t render_id) const {
  return static_cast<const ViERenderManager*>(vie_manager_)->ViERenderPtr(
           render_id);
}

ViERenderManager::ViERenderManager(int32_t engine_id)
    : list_cs_(CriticalSectionWrapper::CreateCriticalSection()),
      engine_id_(engine_id),
      use_external_render_module_(false) {
  WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideo, ViEId(engine_id),
               "ViERenderManager::ViERenderManager(engine_id: %d) - "
               "Constructor", engine_id);
}

ViERenderManager::~ViERenderManager() {
  WEBRTC_TRACE(webrtc::kTraceMemory, webrtc::kTraceVideo, ViEId(engine_id_),
               "ViERenderManager Destructor, engine_id: %d", engine_id_);
  for (RendererMap::iterator it = stream_to_vie_renderer_.begin();
       it != stream_to_vie_renderer_.end();
       ++it) {
    // The renderer is deleted in RemoveRenderStream.
    RemoveRenderStream(it->first);
  }
}

int32_t ViERenderManager::RegisterVideoRenderModule(
    VideoRender* render_module) {
  // See if there is already a render module registered for the window that
  // the registrant render module is associated with.
  VideoRender* current_module = FindRenderModule(render_module->Window());
  if (current_module) {
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(engine_id_),
                 "A module is already registered for this window (window=%p, "
                 "current module=%p, registrant module=%p.",
                 render_module->Window(), current_module, render_module);
    return -1;
  }

  // Register module.
  render_list_.push_back(render_module);
  use_external_render_module_ = true;
  return 0;
}

int32_t ViERenderManager::DeRegisterVideoRenderModule(
    VideoRender* render_module) {
  // Check if there are streams in the module.
  uint32_t n_streams = render_module->GetNumIncomingRenderStreams();
  if (n_streams != 0) {
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(engine_id_),
                 "There are still %d streams in this module, cannot "
                 "de-register", n_streams);
    return -1;
  }

  for (RenderList::iterator iter = render_list_.begin();
       iter != render_list_.end(); ++iter) {
    if (render_module == *iter) {
      // We've found our renderer. Erase the render module from the map.
      render_list_.erase(iter);
      return 0;
    }
  }
  WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(engine_id_),
               "Module not registered");
  return -1;
}

ViERenderer* ViERenderManager::AddRenderStream(const int32_t render_id,
                                               void* window,
                                               const uint32_t z_order,
                                               const float left,
                                               const float top,
                                               const float right,
                                               const float bottom) {
  CriticalSectionScoped cs(list_cs_.get());

  if (stream_to_vie_renderer_.find(render_id) !=
      stream_to_vie_renderer_.end()) {
    // This stream is already added to a renderer, not allowed!
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(engine_id_),
                 "Render stream already exists");
    return NULL;
  }

  // Get the render module for this window.
  VideoRender* render_module = FindRenderModule(window);
  if (render_module == NULL) {
    // No render module for this window, create a new one.
    render_module = VideoRender::CreateVideoRender(ViEModuleId(engine_id_, -1),
                                                  window, false);
    if (!render_module) {
      WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo, ViEId(engine_id_),
                   "Could not create new render module");
      return NULL;
    }
    render_list_.push_back(render_module);
  }

  ViERenderer* vie_renderer = ViERenderer::CreateViERenderer(render_id,
                                                             engine_id_,
                                                             *render_module,
                                                             *this, z_order,
                                                             left, top, right,
                                                             bottom);
  if (!vie_renderer) {
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                 ViEId(engine_id_, render_id),
                 "Could not create new render stream");
    return NULL;
  }
  stream_to_vie_renderer_[render_id] = vie_renderer;
  return vie_renderer;
}

int32_t ViERenderManager::RemoveRenderStream(
    const int32_t render_id) {
  // We need exclusive right to the items in the render manager to delete a
  // stream.
  ViEManagerWriteScoped scope(this);
  CriticalSectionScoped cs(list_cs_.get());
  RendererMap::iterator it = stream_to_vie_renderer_.find(render_id);
  if (it == stream_to_vie_renderer_.end()) {
    // No such stream
    WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo, ViEId(engine_id_),
                 "No renderer for this stream found, channel_id");
    return 0;
  }

  // Get the render module pointer for this vie_render object.
  VideoRender& renderer = it->second->RenderModule();

  // Delete the vie_render.
  // This deletes the stream in the render module.
  delete it->second;

  // Remove from the stream map.
  stream_to_vie_renderer_.erase(it);

  // Check if there are other streams in the module.
  if (!use_external_render_module_ &&
      renderer.GetNumIncomingRenderStreams() == 0) {
    // Erase the render module from the map.
    for (RenderList::iterator iter = render_list_.begin();
         iter != render_list_.end(); ++iter) {
      if (&renderer == *iter) {
        // We've found our renderer.
        render_list_.erase(iter);
        break;
      }
    }
    // Destroy the module.
    VideoRender::DestroyVideoRender(&renderer);
  }
  return 0;
}

VideoRender* ViERenderManager::FindRenderModule(void* window) {
  for (RenderList::iterator iter = render_list_.begin();
       iter != render_list_.end(); ++iter) {
    if ((*iter)->Window() == window) {
      // We've found the render module.
      return *iter;
    }
  }
  return NULL;
}

ViERenderer* ViERenderManager::ViERenderPtr(int32_t render_id) const {
  RendererMap::const_iterator it = stream_to_vie_renderer_.find(render_id);
  if (it == stream_to_vie_renderer_.end())
    return NULL;

  return it->second;
}

}  // namespace webrtc


text:
<?php

class Ess_M2ePro_Model_Listing_Auto_Actions_Mode_Website
    extends Ess_M2ePro_Model_Listing_Auto_Actions_Mode_Abstract
{
    //########################################

    public function synchWithAddedWebsiteId($websiteId)
    {
        if ($websiteId == 0) {
            $storeIds = array(Mage_Core_Model_App::ADMIN_STORE_ID);
        } else {
            /** @var $websiteObject Mage_Core_Model_Website */
            $websiteObject = Mage::getModel('core/website')->load((string)$websiteId);
            $storeIds = (array)$websiteObject->getStoreIds();
        }

        if (empty($storeIds)) {
            return;
        }

        /** @var Mage_Core_Model_Resource_Db_Collection_Abstract $collection */
        $collection = Mage::getModel('M2ePro/Listing')->getCollection();

        $collection->addFieldToFilter('auto_mode', Ess_M2ePro_Model_Listing::AUTO_MODE_WEBSITE);
        $collection->addFieldToFilter(
            'auto_website_adding_mode',
            array('neq'=>Ess_M2ePro_Model_Listing::ADDING_MODE_NONE)
        );
        $collection->addFieldToFilter('store_id', array('in'=>$storeIds));

        foreach ($collection->getItems() as $listing) {

            /** @var Ess_M2ePro_Model_Listing $listing */

            if (!$listing->isAutoWebsiteAddingAddNotVisibleYes()) {
                if ($this->getProduct()->getVisibility()
                    == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE) {
                    continue;
                }
            }

            $this->getListingObject($listing)->addProductByWebsiteListing($this->getProduct(), $listing);
        }
    }

    public function synchWithDeletedWebsiteId($websiteId)
    {
        /** @var $websiteObject Mage_Core_Model_Website */
        $websiteObject = Mage::getModel('core/website')->load((string)$websiteId);
        $storeIds = (array)$websiteObject->getStoreIds();

        if (empty($storeIds)) {
            return;
        }

        /** @var Mage_Core_Model_Resource_Db_Collection_Abstract $collection */
        $collection = Mage::getModel('M2ePro/Listing')->getCollection();

        $collection->addFieldToFilter('auto_mode', Ess_M2ePro_Model_Listing::AUTO_MODE_WEBSITE);
        $collection->addFieldToFilter(
            'auto_website_deleting_mode',
            array('neq'=>Ess_M2ePro_Model_Listing::DELETING_MODE_NONE)
        );

        $collection->addFieldToFilter('store_id', array('in'=>$storeIds));

        foreach ($collection->getItems() as $listing) {

            /** @var Ess_M2ePro_Model_Listing $listing */

            $this->getListingObject($listing)->deleteProduct(
                $this->getProduct(),
                $listing->getAutoWebsiteDeletingMode()
            );
        }
    }

    //########################################
}


text:
#ifndef GOOPY_BASE_SINGLETON_H_
#define GOOPY_BASE_SINGLETON_H_
#pragma once

#include "base/at_exit.h"
#include "base/atomicops.h"
#include "base/threading/platform_thread.h"

// Default traits for Singleton<Type>. Calls operator new and operator delete on
// the object. Registers automatic deletion at process exit.
// Overload if you need arguments or another memory allocation function.
template<typename Type>
struct DefaultSingletonTraits {
  // Allocates the object.
  static Type* New() {
    // The parenthesis is very important here; it forces POD type
    // initialization.
    return new Type();
  }

  // Destroys the object.
  static void Delete(Type* x) {
    delete x;
  }

  // Set to true to automatically register deletion of the object on process
  // exit. See below for the required call that makes this happen.
  static const bool kRegisterAtExit = true;

  // Set to false to disallow access on a non-joinable thread.  This is
  // different from kRegisterAtExit because StaticMemorySingletonTraits allows
  // access on non-joinable threads, and gracefully handles this.
  static const bool kAllowedToAccessOnNonjoinableThread = false;
};

// Alternate traits for use with the Singleton<Type>.  Identical to
// DefaultSingletonTraits except that the Singleton will not be cleaned up
// at exit.
template<typename Type>
struct LeakySingletonTraits : public DefaultSingletonTraits<Type> {
  static const bool kRegisterAtExit = false;
  static const bool kAllowedToAccessOnNonjoinableThread = true;
};

// Alternate traits for use with the Singleton<Type>.  Allocates memory
// for the singleton instance from a static buffer.  The singleton will
// be cleaned up at exit, but can't be revived after destruction unless
// the Resurrect() method is called.
//
// This is useful for a certain category of things, notably logging and
// tracing, where the singleton instance is of a type carefully constructed to
// be safe to access post-destruction.
// In logging and tracing you'll typically get stray calls at odd times, like
// during static destruction, thread teardown and the like, and there's a
// termination race on the heap-based singleton - e.g. if one thread calls
// get(), but then another thread initiates AtExit processing, the first thread
// may call into an object residing in unallocated memory. If the instance is
// allocated from the data segment, then this is survivable.
//
// The destructor is to deallocate system resources, in this case to unregister
// a callback the system will invoke when logging levels change. Note that
// this is also used in e.g. Chrome Frame, where you have to allow for the
// possibility of loading briefly into someone else's process space, and
// so leaking is not an option, as that would sabotage the state of your host
// process once you've unloaded.
template <typename Type>
struct StaticMemorySingletonTraits {
  // WARNING: User has to deal with get() in the singleton class
  // this is traits for returning NULL.
  static Type* New() {
    if (base::subtle::NoBarrier_AtomicExchange(&dead_, 1))
      return NULL;
    Type* ptr = reinterpret_cast<Type*>(buffer_);

    // We are protected by a memory barrier.
    new(ptr) Type();
    return ptr;
  }

  static void Delete(Type* p) {
    base::subtle::NoBarrier_Store(&dead_, 1);
    base::subtle::MemoryBarrier();
    if (p != NULL)
      p->Type::~Type();
  }

  static const bool kRegisterAtExit = true;
  static const bool kAllowedToAccessOnNonjoinableThread = true;

  // Exposed for unittesting.
  static void Resurrect() {
    base::subtle::NoBarrier_Store(&dead_, 0);
  }

 private:
  static const size_t kBufferSize = (sizeof(Type) +
                                     sizeof(intptr_t) - 1) / sizeof(intptr_t);
  static intptr_t buffer_[kBufferSize];

  // Signal the object was already deleted, so it is not revived.
  static base::subtle::Atomic32 dead_;
};

template <typename Type> intptr_t
    StaticMemorySingletonTraits<Type>::buffer_[kBufferSize];
template <typename Type> base::subtle::Atomic32
    StaticMemorySingletonTraits<Type>::dead_ = 0;

// The Singleton<Type, Traits, DifferentiatingType> class manages a single
// instance of Type which will be created on first use and will be destroyed at
// normal process exit). The Trait::Delete function will not be called on
// abnormal process exit.
//
// DifferentiatingType is used as a key to differentiate two different
// singletons having the same memory allocation functions but serving a
// different purpose. This is mainly used for Locks serving different purposes.
//
// Example usage:
//
// In your header:
//   #include "base/singleton.h"
//   class FooClass {
//    public:
//     static FooClass* GetInstance();  <-- See comment below on this.
//     void Bar() { ... }
//    private:
//     FooClass() { ... }
//     friend struct DefaultSingletonTraits<FooClass>;
//
//     DISALLOW_COPY_AND_ASSIGN(FooClass);
//   };
//
// In your source file:
//  FooClass* FooClass::GetInstance() {
//    return Singleton<FooClass>::get();
//  }
//
// And to call methods on FooClass:
//   FooClass::GetInstance()->Bar();
//
// NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance
// and it is important that FooClass::GetInstance() is not inlined in the
// header. This makes sure that when source files from multiple targets include
// this header they don't end up with different copies of the inlined code
// creating multiple copies of the singleton.
//
// Singleton<> has no non-static members and doesn't need to actually be
// instantiated.
//
// This class is itself thread-safe. The underlying Type must of course be
// thread-safe if you want to use it concurrently. Two parameters may be tuned
// depending on the user's requirements.
//
// Glossary:
//   RAE = kRegisterAtExit
//
// On every platform, if Traits::RAE is true, the singleton will be destroyed at
// process exit. More precisely it uses base::AtExitManager which requires an
// object of this type to be instantiated. AtExitManager mimics the semantics
// of atexit() such as LIFO order but under Windows is safer to call. For more
// information see at_exit.h.
//
// If Traits::RAE is false, the singleton will not be freed at process exit,
// thus the singleton will be leaked if it is ever accessed. Traits::RAE
// shouldn't be false unless absolutely necessary. Remember that the heap where
// the object is allocated may be destroyed by the CRT anyway.
//
// Caveats:
// (a) Every call to get(), operator->() and operator*() incurs some overhead
//     (16ns on my P4/2.8GHz) to check whether the object has already been
//     initialized.  You may wish to cache the result of get(); it will not
//     change.
//
// (b) Your factory function must never throw an exception. This class is not
//     exception-safe.
//
template <typename Type,
          typename Traits = DefaultSingletonTraits<Type>,
          typename DifferentiatingType = Type>
class Singleton {
 private:
  // Classes using the Singleton<T> pattern should declare a GetInstance()
  // method and call Singleton::get() from within that.
  friend Type* Type::GetInstance();

  // This class is safe to be constructed and copy-constructed since it has no
  // member.

  // Return a pointer to the one true instance of the class.
  static Type* get() {
    // Modified by haicsun@google.com
    // Remove thread restriction
    // if (!Traits::kAllowedToAccessOnNonjoinableThread)
    //  base::ThreadRestrictions::AssertSingletonAllowed();

    // Our AtomicWord doubles as a spinlock, where a value of
    // kBeingCreatedMarker means the spinlock is being held for creation.
    static const base::subtle::AtomicWord kBeingCreatedMarker = 1;

    base::subtle::AtomicWord value = base::subtle::NoBarrier_Load(&instance_);
    if (value != 0 && value != kBeingCreatedMarker) {
      return reinterpret_cast<Type*>(value);
    }

    // Object isn't created yet, maybe we will get to create it, let's try...
    if (base::subtle::Acquire_CompareAndSwap(&instance_,
                                             0,
                                             kBeingCreatedMarker) == 0) {
      // instance_ was NULL and is now kBeingCreatedMarker.  Only one thread
      // will ever get here.  Threads might be spinning on us, and they will
      // stop right after we do this store.
      Type* newval = Traits::New();

      base::subtle::Release_Store(
          &instance_, reinterpret_cast<base::subtle::AtomicWord>(newval));

      if (newval != NULL && Traits::kRegisterAtExit)
        base::AtExitManager::RegisterCallback(OnExit, NULL);

      return newval;
    }

    // We hit a race.  Another thread beat us and either:
    // - Has the object in BeingCreated state
    // - Already has the object created...
    // We know value != NULL.  It could be kBeingCreatedMarker, or a valid ptr.
    // Unless your constructor can be very time consuming, it is very unlikely
    // to hit this race.  When it does, we just spin and yield the thread until
    // the object has been created.
    while (true) {
      value = base::subtle::NoBarrier_Load(&instance_);
      if (value != kBeingCreatedMarker)
        break;
      base::PlatformThread::YieldCurrentThread();
    }

    return reinterpret_cast<Type*>(value);
  }

  // Adapter function for use with AtExit().  This should be called single
  // threaded, so don't use atomic operations.
  // Calling OnExit while singleton is in use by other threads is a mistake.
  static void OnExit(void* /*unused*/) {
    // AtExit should only ever be register after the singleton instance was
    // created.  We should only ever get here with a valid instance_ pointer.
    Traits::Delete(
        reinterpret_cast<Type*>(base::subtle::NoBarrier_Load(&instance_)));
    instance_ = 0;
  }
  static base::subtle::AtomicWord instance_;
};

template <typename Type, typename Traits, typename DifferentiatingType>
base::subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::
    instance_ = 0;

#endif  // GOOPY_BASE_SINGLETON_H_


text:
package org.jayield.primitives.intgr;

import org.jayield.Traverser;
import org.jayield.Yield;
import org.jayield.primitives.dbl.DoubleTraverser;
import org.jayield.primitives.lng.LongTraverser;

import java.util.function.DoubleToIntFunction;
import java.util.function.LongToIntFunction;
import java.util.function.ToIntFunction;

/**
 * Bulk traversal.
 * Jayield uses traverse method as its first choice to
 * implement Query operations.
 * This is a special kind of traversal that disallows individually access.
 */
public interface IntTraverser extends Traverser<Integer> {
    /**
     * Yields elements sequentially in the current thread,
     * until all elements have been processed or an
     * exception is thrown.
     */
    void traverse(IntYield yield);

    static IntTraverser empty() {
        return yield -> { };
    }
    /**
     * Default traverse implementation that calls the
     * primitive version of it
     */
    @Override
    default void traverse(Yield<? super Integer> yield) {
        IntYield yld = yield::ret;
        this.traverse(yld);
    }
    /**
     * An IntTraverser object from a generic {@link Traverser} mapped by a {@link ToIntFunction}.
     *
     * @param source
     *         {@link Traverser} with the source elements for this {@code IntTraverser}.
     * @param mapper
     *         {@link ToIntFunction} that specifies how to map the source elements into int values.
     */
    static <T> IntTraverser from(Traverser<T> source, ToIntFunction<? super T> mapper) {
        return yield -> source.traverse(item -> yield.ret(mapper.applyAsInt(item)));
    }

    /**
     * An IntTraverser object from a {@link DoubleTraverser} mapped by a {@link DoubleToIntFunction}.
     *
     * @param source
     *         {@link DoubleTraverser} with the source elements for this {@code IntTraverser}.
     * @param mapper
     *         {@link DoubleToIntFunction} that specifies how to map the source elements into int values.
     */
    static IntTraverser from(DoubleTraverser source, DoubleToIntFunction mapper) {
        return from((Traverser<Double>) source, mapper::applyAsInt);
    }

    /**
     * An IntTraverser object from a {@link LongTraverser} mapped by a {@link LongToIntFunction}.
     *
     * @param source
     *         {@link LongTraverser} with the source elements for this {@code DoubleTraverser}.
     * @param mapper
     *         {@link LongToIntFunction} that specifies how to map the source elements into int values.
     */
    static IntTraverser from(LongTraverser source, LongToIntFunction mapper) {
        return from((Traverser<Long>) source, mapper::applyAsInt);
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Get Started with Map 2D</title>
    <link rel="stylesheet" href="https://js.arcgis.com/4.5/esri/css/main.css">
    <link rel="stylesheet" href="app/main.css">


text:
package com.insane.proslasher.plugins;

public class PluginManager {

	public static PluginManager instance = null;

	public static PluginManager getInstance() {
		if(instance == null) {
			instance = new PluginManager();
		}
		return instance;
	}

	private PluginManager() {
		// needs to be private so everyone is forced to use getInstance
	}

	public IPlugin getPlugin(String className) throws PluginException {
		try {
		Class pc = Class.forName("com.insane.proslasher.plugins." + className);
		if(pc != null) {
			IPlugin plugin = (IPlugin)pc.newInstance();
			if(plugin != null) {
				return plugin;
			} else {
				throw new PluginException("Unable to load plugin");
			}
		} else {
			throw new PluginException("Couldn't find plugin");
		}
		} catch(ClassNotFoundException e) {
			throw new PluginException(e);
		} catch(InstantiationException e) {
			throw new PluginException(e);
		} catch(IllegalAccessException e) {
			throw new PluginException(e);
		}
	}
}


text:
import pymongo
from datetime import datetime
import time

class JobQueue:

    def __init__(self, db, silent=False):
        """ Return an instance of a JobQueue.
        Initialization requires one argument, the database,
        since we use one jobqueue collection to cover all
        sites in an installation/database. The second
        argument specifies if to print status while waiting
        for new job, the default value is False"""
        self.db = db
        self.silent=silent
        if not self._exists():
            print ('Creating jobqueue collection.')
            self._create()
        self.q = self.db['jobqueue']

    def _create(self, capped=True):
        """ Creates a Capped Collection. """
        # TODO - does the size parameter mean number of docs or bytesize?
        try:
            self.db.create_collection('jobqueue',
                                      capped=capped, max=100000,
                                      size=100000, autoIndexId=True)
        except:
            raise Exception('Collection "jobqueue" already created')

    def _exists(self):
        """ Ensures that the jobqueue collection exists in the DB. """
        return 'jobqueue' in self.db.collection_names()

    def valid(self):
        """ Checks to see if the jobqueue is a capped collection. """
        opts = self.db['jobqueue'].options()
        if opts.get('capped', False):
            return True
        return False

    def next(self):
        """ Runs the next job in the queue. """
        cursor = self.q.find({'status': 'waiting'},
                             tailable=True)
        if cursor:
            row = cursor.next()
            row['status'] = 'done'
            row['ts']['started'] = datetime.now()
            row['ts']['done'] = datetime.now()
            self.q.save(row)
            try:
                return row
            except:
                raise Exception('There are no jobs in the queue')

    def pub(self, data=None):
        """ Publishes a doc to the work queue. """
        doc = dict(
            ts={'created': datetime.now(),
                'started': datetime.now(),
                'done': datetime.now()},
            status='waiting',
            data=data)
        try:
            self.q.insert(doc, manipulate=False)
        except:
            raise Exception('could not add to queue')
        return True

    def __iter__(self):
        """ Iterates through all docs in the queue
            andw aits for new jobs when queue is empty. """
        cursor = self.q.find({'status': 'waiting'}, tailable=True)
        while 1:
            try:
                row = cursor.next()
                try:
                    result = self.q.update({'_id': row['_id'],
                                            'status': 'waiting'},
                                           {'$set': {
                                                'status': 'working',
                                                'ts.started': datetime.now()
                                                }
                                            })
                except OperationFailure:
                    print ('Job Failed!!')
                    continue
                print ('---')
                print ('Working on job:')
                yield row
                row['status'] = 'done'
                row['ts']['done'] = datetime.now()
                self.q.save(row)
            except:
                time.sleep(5)
                if not self.silent:
                    print ('waiting!')

    def queue_count(self):
        """ Returns the number of jobs waiting in the queue. """
        cursor = self.q.find({'status': 'waiting'})
        if cursor:
            return cursor.count()

    def clear_queue(self):
        """ Drops the queue collection. """
        self.q.drop()


text:
/**
 * Default settings for urls.json and it's path
 */
urlmanager.constant('UrlDefaults', {
    'FILE_NAME' : 'urls.json',
    'PATH_NAME' : 'json/',
    'DEBUG'     : true
});


text:
package com.github.sbellus.fitnesse.graphviz;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.io.FilenameUtils;

import fitnesse.plugins.PluginException;
import fitnesse.plugins.PluginFeatureFactoryBase;
import fitnesse.wikitext.parser.SymbolProvider;

/**
 * Register graphviz symbol.
 */
public class GraphvizPlugin extends PluginFeatureFactoryBase {
    private Properties properties;

    public GraphvizPlugin() {
        this.properties = makeProperties();
    }

    public void registerSymbolTypes(SymbolProvider symbolProvider) throws PluginException {
        symbolProvider.add(GraphvizDotSymbol.make(properties));
    }

    private Properties makeProperties() {
        Properties pluginProperties = new Properties();

        try {
            File currentJarFile = new File(
                    GraphvizPlugin.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
            String currentJarPath = FilenameUtils.getFullPath(currentJarFile.getAbsolutePath());
            File pluginPropertiesFile = new File(currentJarPath + "fitnesse-graphviz-plugin.properties");
            if (pluginPropertiesFile.exists()) {
                InputStream is = new FileInputStream(pluginPropertiesFile);
                pluginProperties.load(is);
                is.close();
            }
        } catch (Exception e) {
            // do nothing
        }

        if (pluginProperties.getProperty("dotExecutable") == null) {
            GraphvizDotFinder finder = new GraphvizDotFinder();
            String dotExecutable = finder.findDot();

            if (dotExecutable != null) {
                pluginProperties.setProperty("dotExecutable", dotExecutable);
            }
        }

        return pluginProperties;
    }
}


text:
import logging
from logging import Filter
import os
from os import PathLike
from typing import Union

import sys

class AllenNlpLogger(logging.Logger):
    """
    A custom subclass of 'logging.Logger' that keeps a set of messages to
    implement {debug,info,etc.}_once() methods.
    """

    def __init__(self, name):
        super().__init__(name)
        self._seen_msgs = set()

    def debug_once(self, msg, *args, **kwargs):
        if msg not in self._seen_msgs:
            self.debug(msg, *args, **kwargs)
            self._seen_msgs.add(msg)

    def info_once(self, msg, *args, **kwargs):
        if msg not in self._seen_msgs:
            self.info(msg, *args, **kwargs)
            self._seen_msgs.add(msg)

    def warning_once(self, msg, *args, **kwargs):
        if msg not in self._seen_msgs:
            self.warning(msg, *args, **kwargs)
            self._seen_msgs.add(msg)

    def error_once(self, msg, *args, **kwargs):
        if msg not in self._seen_msgs:
            self.error(msg, *args, **kwargs)
            self._seen_msgs.add(msg)

    def critical_once(self, msg, *args, **kwargs):
        if msg not in self._seen_msgs:
            self.critical(msg, *args, **kwargs)
            self._seen_msgs.add(msg)

logging.setLoggerClass(AllenNlpLogger)
logger = logging.getLogger(__name__)

FILE_FRIENDLY_LOGGING: bool = False
"""
If this flag is set to `True`, we add newlines to tqdm output, even on an interactive terminal, and we slow
down tqdm's output to only once every 10 seconds.

By default, it is set to `False`.
"""

class ErrorFilter(Filter):
    """
    Filters out everything that is at the ERROR level or higher. This is meant to be used
    with a stdout handler when a stderr handler is also configured. That way ERROR
    messages aren't duplicated.
    """

    def filter(self, record):
        return record.levelno < logging.ERROR

def prepare_global_logging(
    serialization_dir: Union[str, PathLike],
    rank: int = 0,
    world_size: int = 1,
) -> None:
    root_logger = logging.getLogger()

    # create handlers
    if world_size == 1:
        log_file = os.path.join(serialization_dir, "out.log")
        formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s")
    else:
        log_file = os.path.join(serialization_dir, f"out_worker{rank}.log")
        formatter = logging.Formatter(
            f"{rank} | %(asctime)s - %(levelname)s - %(name)s - %(message)s"
        )
    file_handler: logging.Handler = logging.FileHandler(log_file)
    stdout_handler: logging.Handler = logging.StreamHandler(sys.stdout)
    stderr_handler: logging.Handler = logging.StreamHandler(sys.stderr)

    handler: logging.Handler
    for handler in [file_handler, stdout_handler, stderr_handler]:
        handler.setFormatter(formatter)

    # Remove the already set handlers in root logger.
    # Not doing this will result in duplicate log messages
    root_logger.handlers.clear()

    if os.environ.get("ALLENNLP_DEBUG"):
        LEVEL = logging.DEBUG
    else:
        level_name = os.environ.get("ALLENNLP_LOG_LEVEL", "INFO")
        LEVEL = logging._nameToLevel.get(level_name, logging.INFO)

    file_handler.setLevel(LEVEL)
    stdout_handler.setLevel(LEVEL)
    stdout_handler.addFilter(ErrorFilter())  # Make sure errors only go to stderr
    stderr_handler.setLevel(logging.ERROR)
    root_logger.setLevel(LEVEL)

    # put all the handlers on the root logger
    root_logger.addHandler(file_handler)
    if rank == 0:
        root_logger.addHandler(stdout_handler)
        root_logger.addHandler(stderr_handler)

    from allennlp.common.util import SigTermReceived

    # write uncaught exceptions to the logs
    def excepthook(exctype, value, traceback):
        # For interruptions, call the original exception handler.
        if issubclass(exctype, (KeyboardInterrupt, SigTermReceived)):
            sys.__excepthook__(exctype, value, traceback)
            return
        root_logger.critical("Uncaught exception", exc_info=(exctype, value, traceback))

    sys.excepthook = excepthook

    # also log tqdm
    from allennlp.common.tqdm import logger as tqdm_logger

    tqdm_logger.handlers.clear()
    tqdm_logger.addHandler(file_handler)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Elaeosticta gracilis Kamelin & Pimenov

### Remarks
null


text:
__all__ = ('BlockStorageRAM',)

import os
import struct
import logging
import errno
from multiprocessing.pool import ThreadPool

import pyoram
from pyoram.storage.block_storage import \
    (BlockStorageInterface,
     BlockStorageTypeFactory)
from pyoram.storage.block_storage_mmap import \
    (BlockStorageMMap,
     _BlockStorageMemoryImpl)

import tqdm
import six
from six.moves import xrange

log = logging.getLogger("pyoram")

class BlockStorageRAM(_BlockStorageMemoryImpl,
                      BlockStorageInterface):
    """
    A class implementing the block storage interface where all data is
    kept in RAM. This class uses the same storage format as
    BlockStorageFile. Thus, a block storage space can be created using
    this class and then, after saving the raw storage data to disk,
    reopened with any other class compatible with BlockStorageFile
    (and visa versa).
    """

    _index_struct_string = BlockStorageMMap._index_struct_string
    _index_offset = struct.calcsize(_index_struct_string)

    def __init__(self,
                 storage_data,
                 threadpool_size=None,
                 ignore_lock=False):

        self._bytes_sent = 0
        self._bytes_received = 0
        self._ignore_lock = ignore_lock
        self._f = None
        self._pool = None
        self._close_pool = True
        if type(storage_data) is not bytearray:
            raise TypeError(
                "BlockStorageRAM requires input argument of type "
                "'bytearray'. Invalid input type: %s"
                % (type(storage_data)))
        self._f = storage_data
        self._block_size, self._block_count, user_header_size, locked = \
            struct.unpack(
                BlockStorageRAM._index_struct_string,
                self._f[:BlockStorageRAM._index_offset])

        if locked and (not self._ignore_lock):
            raise IOError(
                "Can not open block storage device because it is "
                "locked by another process. To ignore this check, "
                "initialize this class with the keyword 'ignore_lock' "
                "set to True.")
        self._user_header_data = bytes()
        if user_header_size > 0:
            self._user_header_data = \
                bytes(self._f[BlockStorageRAM._index_offset:\
                              (BlockStorageRAM._index_offset+user_header_size)])
        assert len(self._user_header_data) == user_header_size
        self._header_offset = BlockStorageRAM._index_offset + \
                              len(self._user_header_data)

        if not self._ignore_lock:
            # turn on the locked flag
            self._f[:BlockStorageRAM._index_offset] = \
                struct.pack(BlockStorageRAM._index_struct_string,
                            self.block_size,
                            self.block_count,
                            len(self._user_header_data),
                            True)

        # Although we do not use the threadpool we still
        # create just in case we are the first
        if threadpool_size != 0:
            self._pool = ThreadPool(threadpool_size)

    #
    # Add some methods specific to BlockStorageRAM
    #

    @staticmethod
    def fromfile(file_,
                 threadpool_size=None,
                 ignore_lock=False):
        """
        Instantiate BlockStorageRAM device from a file saved in block
        storage format. The file_ argument can be a file object or a
        string that represents a filename. If called with a file
        object, it should be opened in binary mode, and the caller is
        responsible for closing the file.

        This method returns a BlockStorageRAM instance.
        """
        close_file = False
        if not hasattr(file_, 'read'):
            file_ = open(file_, 'rb')
            close_file = True
        try:
            header_data = file_.read(BlockStorageRAM._index_offset)
            block_size, block_count, user_header_size, locked = \
                struct.unpack(
                    BlockStorageRAM._index_struct_string,
                    header_data)
            if locked and (not ignore_lock):
                raise IOError(
                    "Can not open block storage device because it is "
                    "locked by another process. To ignore this check, "
                    "call this method with the keyword 'ignore_lock' "
                    "set to True.")
            header_offset = len(header_data) + \
                            user_header_size
            f = bytearray(header_offset + \
                          (block_size * block_count))
            f[:header_offset] = header_data + file_.read(user_header_size)
            f[header_offset:] = file_.read(block_size * block_count)
        finally:
            if close_file:
                file_.close()

        return BlockStorageRAM(f,
                               threadpool_size=threadpool_size,
                               ignore_lock=ignore_lock)

    def tofile(self, file_):
        """
        Dump all storage data to a file. The file_ argument can be a
        file object or a string that represents a filename. If called
        with a file object, it should be opened in binary mode, and
        the caller is responsible for closing the file.

        The method should only be called after the storage device has
        been closed to ensure that the locked flag has been set to
        False.
        """
        close_file = False
        if not hasattr(file_, 'write'):
            file_ = open(file_, 'wb')
            close_file = True
        file_.write(self._f)
        if close_file:
            file_.close()

    @property
    def data(self):
        """Access the raw bytearray"""
        return self._f

    #
    # Define BlockStorageInterface Methods
    #

    def clone_device(self):
        f = BlockStorageRAM(self._f,
                            threadpool_size=0,
                            ignore_lock=True)
        f._pool = self._pool
        f._close_pool = False
        return f

    @classmethod
    def compute_storage_size(cls, *args, **kwds):
        return BlockStorageMMap.compute_storage_size(*args, **kwds)

    @classmethod
    def setup(cls,
              storage_name,
              block_size,
              block_count,
              initialize=None,
              header_data=None,
              ignore_existing=False,
              threadpool_size=None):

        # We ignore the 'storage_name' argument
        # We ignore the 'ignore_existing' flag
        if (block_size <= 0) or (block_size != int(block_size)):
            raise ValueError(
                "Block size (bytes) must be a positive integer: %s"
                % (block_size))
        if (block_count <= 0) or (block_count != int(block_count)):
            raise ValueError(
                "Block count must be a positive integer: %s"
                % (block_count))
        if (header_data is not None) and \
           (type(header_data) is not bytes):
            raise TypeError(
                "'header_data' must be of type bytes. "
                "Invalid type: %s" % (type(header_data)))

        if initialize is None:
            zeros = bytes(bytearray(block_size))
            initialize = lambda i: zeros

        # create_index
        index_data = None
        if header_data is None:
            index_data = struct.pack(BlockStorageRAM._index_struct_string,
                                     block_size,
                                     block_count,
                                     0,
                                     False)
            header_data = bytes()
        else:
            index_data = struct.pack(BlockStorageRAM._index_struct_string,
                                     block_size,
                                     block_count,
                                     len(header_data),
                                     False)
        header_offset = len(index_data) + len(header_data)
        f = bytearray(header_offset + \
                      (block_size * block_count))
        f[:header_offset] = index_data + header_data
        progress_bar = tqdm.tqdm(total=block_count*block_size,
                                 desc="Initializing File Block Storage Space",
                                 unit="B",
                                 unit_scale=True,
                                 disable=not pyoram.config.SHOW_PROGRESS_BAR)
        for i in xrange(block_count):
            block = initialize(i)
            assert len(block) == block_size, \
                ("%s != %s" % (len(block), block_size))
            pos_start = header_offset + i * block_size
            pos_start = header_offset + i * block_size
            pos_stop = pos_start + block_size
            f[pos_start:pos_stop] = block[:]
            progress_bar.update(n=block_size)
        progress_bar.close()

        return BlockStorageRAM(f, threadpool_size=threadpool_size)

    @property
    def header_data(self):
        return self._user_header_data

    @property
    def block_count(self):
        return self._block_count

    @property
    def block_size(self):
        return self._block_size

    @property
    def storage_name(self):
        return None

    def update_header_data(self, new_header_data):
        if len(new_header_data) != len(self.header_data):
            raise ValueError(
                "The size of header data can not change.\n"
                "Original bytes: %s\n"
                "New bytes: %s" % (len(self.header_data),
                                   len(new_header_data)))
        self._user_header_data = bytes(new_header_data)
        self._f[BlockStorageRAM._index_offset:\
                (BlockStorageRAM._index_offset+len(new_header_data))] = \
            self._user_header_data

    def close(self):
        if self._close_pool and (self._pool is not None):
            self._pool.close()
            self._pool.join()
            self._pool = None
        if not self._ignore_lock:
            # turn off the locked flag
            self._f[:BlockStorageRAM._index_offset] = \
                struct.pack(BlockStorageRAM._index_struct_string,
                            self.block_size,
                            self.block_count,
                            len(self._user_header_data),
                            False)
            self._ignore_lock = True

    #
    # We must cast from bytearray to bytes
    # when reading from a bytearray so that this
    # class works with the encryption layer.
    #

    def read_blocks(self, indices):
        return [bytes(block) for block
                in super(BlockStorageRAM, self).read_blocks(indices)]

    def yield_blocks(self, indices):
        for block in super(BlockStorageRAM, self).yield_blocks(indices):
            yield bytes(block)

    def read_block(self, i):
        return bytes(super(BlockStorageRAM, self).read_block(i))

    #def write_blocks(...)

    #def write_block(...)

    @property
    def bytes_sent(self):
        return self._bytes_sent

    @property
    def bytes_received(self):
        return self._bytes_received

BlockStorageTypeFactory.register_device("ram", BlockStorageRAM)


text:
import { Component, Event, EventEmitter, Prop, State, Watch } from '@stencil/core';

import { DatetimeData, LocaleData, convertFormatToKey, convertToArrayOfNumbers, convertToArrayOfStrings, dateDataSortValue, dateSortValue, dateValueRange, daysInMonth, getValueFromFormat, parseDate, parseTemplate, renderDatetime, renderTextFormat, updateDate } from './datetime-util';

import { CssClassMap, PickerColumn, PickerOptions, StyleEvent } from '../../interface';
import { clamp, deferEvent } from '../../utils/helpers';

@Component({
  tag: 'ion-datetime',
  styleUrls: {
    ios: 'datetime.ios.scss',
    md: 'datetime.md.scss'
  },
  host: {
    theme: 'datetime'
  }
})
export class Datetime {
  [key: string]: any;

  private inputId = `ion-dt-${datetimeIds++}`;
  private labelId = `${this.inputId}-lbl`;

  private picker?: HTMLIonPickerElement | null;

  locale: LocaleData = {};
  datetimeMin: DatetimeData = {};
  datetimeMax: DatetimeData = {};
  datetimeValue: DatetimeData = {};

  @State() text: any;

  @Prop({ connect: 'ion-picker-controller' }) pickerCtrl!: HTMLIonPickerControllerElement;

  /**
   * If true, the user cannot interact with the datetime. Defaults to `false`.
   */
  @Prop() disabled = false;

  @Watch('disabled')
  protected disabledChanged() {
    this.emitStyle();
  }

  /**
   * The minimum datetime allowed. Value must be a date string
   * following the
   * [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
   * such as `1996-12-19`. The format does not have to be specific to an exact
   * datetime. For example, the minimum could just be the year, such as `1994`.
   * Defaults to the beginning of the year, 100 years ago from today.
   */
  @Prop({ mutable: true }) min: string | undefined;

  /**
   * The maximum datetime allowed. Value must be a date string
   * following the
   * [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
   * `1996-12-19`. The format does not have to be specific to an exact
   * datetime. For example, the maximum could just be the year, such as `1994`.
   * Defaults to the end of this year.
   */
  @Prop({ mutable: true }) max: string | undefined;

  /**
   * The display format of the date and time as text that shows
   * within the item. When the `pickerFormat` input is not used, then the
   * `displayFormat` is used for both display the formatted text, and determining
   * the datetime picker's columns. See the `pickerFormat` input description for
   * more info. Defaults to `MMM D, YYYY`.
   */
  @Prop() displayFormat = 'MMM D, YYYY';

  /**
   * The format of the date and time picker columns the user selects.
   * A datetime input can have one or many datetime parts, each getting their
   * own column which allow individual selection of that particular datetime part. For
   * example, year and month columns are two individually selectable columns which help
   * choose an exact date from the datetime picker. Each column follows the string
   * parse format. Defaults to use `displayFormat`.
   */
  @Prop() pickerFormat?: string;

  /**
   * The text to display on the picker's cancel button. Default: `Cancel`.
   */
  @Prop() cancelText = 'Cancel';

  /**
   * The text to display on the picker's "Done" button. Default: `Done`.
   */
  @Prop() doneText = 'Done';

  /**
   * Values used to create the list of selectable years. By default
   * the year values range between the `min` and `max` datetime inputs. However, to
   * control exactly which years to display, the `yearValues` input can take a number, an array
   * of numbers, or string of comma separated numbers. For example, to show upcoming and
   * recent leap years, then this input's value would be `yearValues="2024,2020,2016,2012,2008"`.
   */
  @Prop() yearValues?: number[] | number | string;

  /**
   * Values used to create the list of selectable months. By default
   * the month values range from `1` to `12`. However, to control exactly which months to
   * display, the `monthValues` input can take a number, an array of numbers, or a string of
   * comma separated numbers. For example, if only summer months should be shown, then this
   * input value would be `monthValues="6,7,8"`. Note that month numbers do *not* have a
   * zero-based index, meaning January's value is `1`, and December's is `12`.
   */
  @Prop() monthValues?: number[] | number | string;

  /**
   * Values used to create the list of selectable days. By default
   * every day is shown for the given month. However, to control exactly which days of
   * the month to display, the `dayValues` input can take a number, an array of numbers, or
   * a string of comma separated numbers. Note that even if the array days have an invalid
   * number for the selected month, like `31` in February, it will correctly not show
   * days which are not valid for the selected month.
   */
  @Prop() dayValues?: number[] | number | string;

  /**
   * Values used to create the list of selectable hours. By default
   * the hour values range from `0` to `23` for 24-hour, or `1` to `12` for 12-hour. However,
   * to control exactly which hours to display, the `hourValues` input can take a number, an
   * array of numbers, or a string of comma separated numbers.
   */
  @Prop() hourValues?: number[] | number | string;

  /**
   * Values used to create the list of selectable minutes. By default
   * the mintues range from `0` to `59`. However, to control exactly which minutes to display,
   * the `minuteValues` input can take a number, an array of numbers, or a string of comma
   * separated numbers. For example, if the minute selections should only be every 15 minutes,
   * then this input value would be `minuteValues="0,15,30,45"`.
   */
  @Prop() minuteValues?: number[] | number | string;

  /**
   * Full names for each month name. This can be used to provide
   * locale month names. Defaults to English.
   */
  @Prop() monthNames?: string[] | string;

  /**
   * Short abbreviated names for each month name. This can be used to provide
   * locale month names. Defaults to English.
   */
  @Prop() monthShortNames?: string[] | string;

  /**
   * Full day of the week names. This can be used to provide
   * locale names for each day in the week. Defaults to English.
   */
  @Prop() dayNames?: string[] | string;

  /**
   * Short abbreviated day of the week names. This can be used to provide
   * locale names for each day in the week. Defaults to English.
   */
  @Prop() dayShortNames?: string[] | string;

  /**
   * Any additional options that the picker interface can accept.
   * See the [Picker API docs](../../picker/Picker) for the picker options.
   */
  @Prop() pickerOptions: PickerOptions = {
    buttons: [],
    columns: []
  };

  /**
   * The text to display when there's no date selected yet.
   * Using lowercase to match the input attribute
   */
  @Prop() placeholder?: string;

  /**
   * the value of the datetime.
   */
  @Prop({ mutable: true }) value?: string;

  /**
   * Update the datetime value when the value changes
   */
  @Watch('value')
  protected valueChanged() {
    this.updateValue();
    this.emitStyle();
  }

  /**
   * Emitted when the datetime selection was cancelled.
   */
  @Event() ionCancel!: EventEmitter<void>;

  /**
   * Emitted when the styles change.
   */
  @Event() ionStyle!: EventEmitter


text:
<?php

namespace app\modules\setting\models;

use Yii;

/**
 * This is the model class for table "cb_gl_gam".
 *
 * @property string $account_no
 * @property string $product_code
 * @property string $customer_no
 * @property string $account_name
 * @property string $branch_id
 * @property string $date_opened
 * @property string $balance_is_DR_CR
 * @property double $cleared_balance
 * @property double $DR_int_rate
 * @property double $CR_int_rate
 * @property string $currency_code
 * @property double $accr_dr_amount
 * @property double $accr_cr_amount
 * @property double $applied_dr_int_todate
 * @property double $applied_cr_int_todate
 * @property string $freez_status
 * @property string $freez_date
 * @property string $account_close_flag
 * @property string $account_close_date
 * @property string $last_tran_date
 * @property double $total_dr_trans
 * @property double $total_cr_trans
 * @property string $source_of_funds
 * @property string $wtax_flag
 * @property double $wtax_percent
 * @property double $wtax_amount
 * @property string $source_account
 * @property string $IBAN
 * @property string $freez_reason
 * @property string $portifolio
 * @property string $documents_attached
 *
 * @property CbGlBranch $branch
 * @property CbCrmCustomerMaster $customerNo
 * @property CbGlAccountType $productCode
 * @property CbGlGamContribution $cbGlGamContribution
 * @property CbGlGamLoan $cbGlGamLoan
 * @property CbGlGamShareMaster $cbGlGamShareMaster
 * @property CbGlGamTransAccount $cbGlGamTransAccount
 * @property CbGlGamTranx[] $cbGlGamTranxes
 */
class Gam extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cb_gl_gam';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['account_no', 'customer_no', 'account_name', 'branch_id', 'date_opened', 'currency_code', 'applied_dr_int_todate', 'applied_cr_int_todate', 'freez_status', 'freez_date', 'account_close_flag', 'account_close_date', 'last_tran_date', 'total_dr_trans', 'total_cr_trans', 'source_of_funds', 'wtax_flag', 'source_account', 'IBAN', 'freez_reason', 'portifolio', 'documents_attached'], 'required'],
            [['date_opened', 'freez_date', 'account_close_date', 'last_tran_date'], 'safe'],
            [['cleared_balance', 'DR_int_rate', 'CR_int_rate', 'accr_dr_amount', 'accr_cr_amount', 'applied_dr_int_todate', 'applied_cr_int_todate', 'total_dr_trans', 'total_cr_trans', 'wtax_percent', 'wtax_amount'], 'number'],
            [['freez_reason'], 'string'],
            [['account_no', 'source_account', 'IBAN'], 'string', 'max' => 12],
            [['product_code', 'branch_id', 'currency_code'], 'string', 'max' => 3],
            [['customer_no'], 'string', 'max' => 7],
            [['account_name'], 'string', 'max' => 50],
            [['balance_is_DR_CR'], 'string', 'max' => 20],
            [['freez_status', 'wtax_flag'], 'string', 'max' => 10],
            [['account_close_flag'], 'string', 'max' => 6],
            [['source_of_funds', 'documents_attached'], 'string', 'max' => 100],
            [['portifolio'], 'string', 'max' => 5]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'account_no' => Yii::t('app', 'Account No'),
            'product_code' => Yii::t('app', 'Product Code'),
            'customer_no' => Yii::t('app', 'Customer No'),
            'account_name' => Yii::t('app', 'Account Name'),
            'branch_id' => Yii::t('app', 'Branch ID'),
            'date_opened' => Yii::t('app', 'Date Opened'),
            'balance_is_DR_CR' => Yii::t('app', 'Balance Is  Dr  Cr'),
            'cleared_balance' => Yii::t('app', 'Cleared Balance'),
            'DR_int_rate' => Yii::t('app', 'Dr Int Rate'),
            'CR_int_rate' => Yii::t('app', 'Cr Int Rate'),
            'currency_code' => Yii::t('app', 'Currency Code'),
            'accr_dr_amount' => Yii::t('app', 'Accr Dr Amount'),
            'accr_cr_amount' => Yii::t('app', 'Accr Cr Amount'),
            'applied_dr_int_todate' => Yii::t('app', 'Applied Dr Int Todate'),
            'applied_cr_int_todate' => Yii::t('app', 'Applied Cr Int Todate'),
            'freez_status' => Yii::t('app', 'Freez Status'),
            'freez_date' => Yii::t('app', 'Freez Date'),
            'account_close_flag' => Yii::t('app', 'Account Close Flag'),
            'account_close_date' => Yii::t('app', 'Account Close Date'),
            'last_tran_date' => Yii::t('app', 'Last Tran Date'),
            'total_dr_trans' => Yii::t('app', 'Total Dr Trans'),
            'total_cr_trans' => Yii::t('app', 'Total Cr Trans'),
            'source_of_funds' => Yii::t('app', 'Source Of Funds'),
            'wtax_flag' => Yii::t('app', 'Wtax Flag'),
            'wtax_percent' => Yii::t('app', 'Wtax Percent'),
            'wtax_amount' => Yii::t('app', 'Wtax Amount'),
            'source_account' => Yii::t('app', 'Source Account'),
            'IBAN' => Yii::t('app', 'Iban'),
            'freez_reason' => Yii::t('app', 'Freez Reason'),
            'portifolio' => Yii::t('app', 'Portifolio'),
            'documents_attached' => Yii::t('app', 'Documents Attached'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBranch()
    {
        return $this->hasOne(CbGlBranch::className(), ['branch_no' => 'branch_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCustomerNo()
    {
        return $this->hasOne(CbCrmCustomerMaster::className(), ['cust_no' => 'customer_no']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductCode()
    {
        return $this->hasOne(CbGlAccountType::className(), ['account_type_code' => 'product_code']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCbGlGamContribution()
    {
        return $this->hasOne(CbGlGamContribution::className(), ['account_no' => 'account_no']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCbGlGamLoan()
    {
        return $this->hasOne(CbGlGamLoan::className(), ['loan_account_no' => 'account_no']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCbGlGamShareMaster()
    {
        return $this->hasOne(CbGlGamShareMaster::className(), ['account_no' => 'account_no']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCbGlGamTransAccount()
    {
        return $this->hasOne(CbGlGamTransAccount::className(), ['account_no' => 'account_no']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCbGlGamTranxes()
    {
        return $this->hasMany(CbGlGamTranx::className(), ['trans_account' => 'account_no']);
    }

    /**
     * @inheritdoc
     * @return GamQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new GamQuery(get_called_class());
    }
}


text:
<?php get_template_part('partials/page-header'); ?>

<?php if (!have_posts()) : ?>
  <div class="alert alert-warning">
    <?php _e('Sorry, no results were found.', 'sage'); ?>
  </div>
<?php endif; ?>

<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('partials/content', get_post_type() != 'post' ? get_post_type() : get_post_format()); ?>
<?php endwhile; ?>

<?php the_posts_navigation(); ?>


text:
#ifndef JUCE_ACTIONLISTENER_H_INCLUDED
#define JUCE_ACTIONLISTENER_H_INCLUDED

//==============================================================================
/**
    Interface class for delivery of events that are sent by an ActionBroadcaster.

    @see ActionBroadcaster, ChangeListener
*/
class JUCE_API  ActionListener
{
public:
    /** Destructor. */
    virtual ~ActionListener()  {}

    /** Overridden by your subclass to receive the callback.

        @param message  the string that was specified when the event was triggered
                        by a call to ActionBroadcaster::sendActionMessage()
    */
    virtual void actionListenerCallback (const String& message) = 0;
};

#endif   // JUCE_ACTIONLISTENER_H_INCLUDED


text:
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web.Models;

namespace Umbraco.Web.Mvc
{
    /// <summary>
    /// Allows for Model Binding any IPublishedContent or IRenderModel
    /// </summary>
	public class RenderModelBinder : DefaultModelBinder, IModelBinder, IModelBinderProvider
    {
		/// <summary>
		/// Binds the model to a value by using the specified controller context and binding context.
		/// </summary>
		/// <returns>
		/// The bound value.
		/// </returns>
		/// <param name="controllerContext">The controller context.</param><param name="bindingContext">The binding context.</param>
		public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
            object model;
            if (controllerContext.RouteData.DataTokens.TryGetValue(Core.Constants.Web.UmbracoDataToken, out model) == false)
                return null;

            //This model binder deals with IRenderModel and IPublishedContent by extracting the model from the route's
            // datatokens. This data token is set in 2 places: RenderRouteHandler, UmbracoVirtualNodeRouteHandler
            // and both always set the model to an instance of `RenderModel`. So if this isn't an instance of IRenderModel then
            // we need to let the DefaultModelBinder deal with the logic.
            var renderModel = model as IRenderModel;
            if (renderModel == null)
            {
                model = base.BindModel(controllerContext, bindingContext);
                if (model == null) return null;
            }

            //if for any reason the model is not either IRenderModel or IPublishedContent, then we return since those are the only
            // types this binder is dealing with.
		    if ((model is IRenderModel) == false && (model is IPublishedContent) == false) return null;

		    //default culture
		    var culture = CultureInfo.CurrentCulture;

		    var umbracoContext = controllerContext.GetUmbracoContext()
		                         ?? UmbracoContext.Current;

		    if (umbracoContext != null && umbracoContext.PublishedContentRequest != null)
		    {
		        culture = umbracoContext.PublishedContentRequest.Culture;
		    }

		    return BindModel(model, bindingContext.ModelType, culture);
		}

        // source is the model that we have
        // modelType is the type of the model that we need to bind to
        // culture is the CultureInfo that we have, used by RenderModel
        //
        // create a model object of the modelType by mapping:
        // { RenderModel, RenderModel<TContent>, IPublishedContent }
        // to
        // { RenderModel, RenderModel<TContent>, IPublishedContent }
        //
        public static object BindModel(object source, Type modelType, CultureInfo culture)
        {
            // null model, return
            if (source == null) return null;

            // if types already match, return
            var sourceType = source.GetType();
            if (sourceType.Inherits(modelType)) // includes ==
                return source;

            // try to grab the content
            var sourceContent = source as IPublishedContent; // check if what we have is an IPublishedContent
            if (sourceContent == null && sourceType.Implements<IRenderModel>())
            {
                // else check if it's an IRenderModel, and get the content
                sourceContent = ((IRenderModel)source).Content;
            }
            if (sourceContent == null)
            {
                // else check if we can convert it to a content
                var attempt1 = source.TryConvertTo<IPublishedContent>();
                if (attempt1.Success) sourceContent = attempt1.Result;
            }

            // if we have a content
            if (sourceContent != null)
            {
                // try to grab the culture
                // using supplied culture by default
                var sourceRenderModel = source as RenderModel;
                if (sourceRenderModel != null)
                    culture = sourceRenderModel.CurrentCulture;

                // if model is IPublishedContent, check content type and return
                if (modelType.Implements<IPublishedContent>())
                {
                    if ((sourceContent.GetType().Inherits(modelType)) == false)
                        ThrowModelBindingException(true, false, sourceContent.GetType(), modelType);
                    return sourceContent;
                }

                // if model is RenderModel, create and return
                if (modelType == typeof(RenderModel))
                {
                    return new RenderModel(sourceContent, culture);
                }

                // if model is RenderModel<TContent>, check content type, then create and return
                if (modelType.IsGenericType && modelType.GetGenericTypeDefinition() == typeof(RenderModel<>))
                {
                    var targetContentType = modelType.GetGenericArguments()[0];
                    if ((sourceContent.GetType().Inherits(targetContentType)) == false)
                        ThrowModelBindingException(true, true, sourceContent.GetType(), targetContentType);
                    return Activator.CreateInstance(modelType, sourceContent, culture);
                }
            }

            // last chance : try to convert
            var attempt2 = source.TryConvertTo(modelType);
            if (attempt2.Success) return attempt2.Result;

            // fail
            ThrowModelBindingException(false, false, sourceType, modelType);
            return null;
        }

	    private static void ThrowModelBindingException(bool sourceContent, bool modelContent, Type sourceType, Type modelType)
	    {
	        var msg = new StringBuilder();

	        msg.Append("Cannot bind source");
	        if (sourceContent) msg.Append(" content");
	        msg.Append(" type ");
	        msg.Append(sourceType.FullName);
	        msg.Append(" to model");
	        if (modelContent) msg.Append(" content");
	        msg.Append(" type ");
            msg.Append(modelType.FullName);
            msg.Append(".");

            // compare FullName for the time being because when upgrading ModelsBuilder,
            // Umbraco does not know about the new attribute type - later on, can compare
            // on type directly (ie after v7.4.2).
	        var sourceAttr = sourceType.Assembly.CustomAttributes.FirstOrDefault(x =>
                x.AttributeType.FullName == "Umbraco.ModelsBuilder.PureLiveAssemblyAttribute");
	        var modelAttr = modelType.Assembly.CustomAttributes.FirstOrDefault(x =>
                x.AttributeType.FullName == "Umbraco.ModelsBuilder.PureLiveAssemblyAttribute");

            // bah.. names are App_Web_all.generated.cs.8f9494c4.jjuvxz55 so they ARE different, fuck!
            // we cannot compare purely on type.FullName 'cos we might be trying to map Sub to Main = fails!
            if (sourceAttr != null && modelAttr != null
                && sourceType.Assembly.GetName().Version.Revision != modelType.Assembly.GetName().Version.Revision)
	        {
	            msg.Append(" Types come from two PureLive assemblies with different versions,");
                msg.Append(" this usually indicates that the application is in an unstable state.");
                msg.Append(" The application is restarting now, reload the page and it should work.");
                var context = HttpContext.Current;
                if (context == null)
                    AppDomain.Unload(AppDomain.CurrentDomain);
                else
                    ApplicationContext.Current.RestartApplicationPool(new HttpContextWrapper(context));
            }

	        throw new ModelBindingException(msg.ToString());
	    }

        public IModelBinder GetBinder(Type modelType)
        {
            // can bind to RenderModel (exact type match)
            // You might be tempted to change this to IRenderModel but do not change this: http://issues.umbraco.org/issue/U4-8216
            if (modelType == typeof(RenderModel)) return this;

            // can bind to RenderModel<TContent> (exact generic type match)
            if (modelType.IsGenericType && modelType.GetGenericTypeDefinition() == typeof(RenderModel<>)) return this;

            // can bind to TContent where TContent : IPublishedContent (any IPublishedContent implementation)
            if (typeof(IPublishedContent).IsAssignableFrom(modelType)) return this;
            return null;
        }
    }
}