code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/**
*============================================================================
* The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC,
* and Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-workflow/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.portal.portlet.workflow.mvc;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowExecutionService;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowRegistryService;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SessionEprs;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SubmitWorkflowCommand;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowDescription;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowSubmitted;
import gov.nih.nci.cagrid.portal.portlet.workflow.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.PortletRequestUtils;
import org.springframework.web.portlet.mvc.SimpleFormController;
@Controller
@RequestMapping(params={"action=newInstance"})
@SuppressWarnings("deprecation")
public class NewInstanceFormController extends SimpleFormController {
protected final Log log = LogFactory.getLog(getClass());
@Autowired
private WorkflowExecutionService workflowService;
@Autowired
@Qualifier("MyExperiment")
private WorkflowRegistryService registry;
@Autowired
private SessionEprs eprs;
@Autowired
private Utils utilities;
/* @see org.springframework.web.portlet.mvc.SimpleFormController#processFormSubmission(javax.portlet.ActionRequest, javax.portlet.ActionResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected void processFormSubmission(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.debug("processFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id - " + id);
SubmitWorkflowCommand cmd = (SubmitWorkflowCommand)command;
log.debug("Command Object: " + cmd.getTheWorkflow());
try {
WorkflowDescription selectedWorkflow = registry.getWorkflow(id);
log.info("Submitting the selected workflow.. #" + id);
String tempFilePath = saveWorkflowDefinition(selectedWorkflow);
EndpointReferenceType epr = workflowService.submitWorkflow(selectedWorkflow.getName(), tempFilePath, cmd.getInputValues());
UUID uuid = UUID.randomUUID();
log.debug("Will submit UUID : " + uuid.toString());
eprs.put(uuid.toString(), new WorkflowSubmitted(epr, selectedWorkflow, "Submitted"));
cmd.setResult("The Workflow was submitted successfully.");
log.info("The Workflow was submitted successfully.");
} catch(Throwable e) {
log.error("Error submitting workflow", e);
Throwable ex = e.getCause();
while(ex.getCause() !=null ) {
ex = ex.getCause();
}
cmd.setResult(e.getClass().getSimpleName() + " submitting workflow: " + e.getMessage());
}
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#renderFormSubmission(javax.portlet.RenderRequest, javax.portlet.RenderResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected ModelAndView renderFormSubmission(RenderRequest request, RenderResponse response, Object cmd, BindException errors) throws Exception {
log.debug("renderFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN"));
return new ModelAndView("json", "contents", ((SubmitWorkflowCommand)cmd).getResult());
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#showForm(javax.portlet.RenderRequest, javax.portlet.RenderResponse, org.springframework.validation.BindException) */
@Override
protected ModelAndView showForm(RenderRequest request, RenderResponse response, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.info("showForm. Action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id: " + id);
SubmitWorkflowCommand cmd = new SubmitWorkflowCommand();
cmd.setTheWorkflow(registry.getWorkflow(id));
return new ModelAndView("newInstance", "cmd", cmd);
}
/**
* Download the workflow definition to local filesystem
* @param wd Workflow Definition
* @return path of temporary file
* @throws IOException
* @throws HttpException
*/
private String saveWorkflowDefinition(WorkflowDescription wd) throws HttpException, IOException {
File tmpPath = new File( System.getProperty("java.io.tmpdir")+"/taverna" );
tmpPath.mkdirs();
String defPath = tmpPath.getAbsolutePath()+"/myexperiment_"+wd.getId()+"_v"+wd.getVersion()+".t2flow";
if(new File(defPath).exists()) { log.debug("Definition temporary file already exists so not downloading again."); return defPath; }
getUtilities().saveFile(defPath, getUtilities().download(wd.getContentURI()) );
return defPath;
}
public SessionEprs getSessionEprs() {return eprs;}
public void setSessionEprs(SessionEprs sessionEprs) {this.eprs = sessionEprs;}
public WorkflowExecutionService getWorkflowService() {return workflowService;}
public void setWorkflowService(WorkflowExecutionService workflowService) {this.workflowService = workflowService;}
public WorkflowRegistryService getRegistry() {return registry;}
public void setRegistry(WorkflowRegistryService registry) {this.registry = registry;}
public Utils getUtilities() {return utilities;}
public void setUtilities(Utils utilities) {this.utilities = utilities;}
}
| NCIP/cagrid-workflow | workflow-portlet/src/main/java/gov/nih/nci/cagrid/portal/portlet/workflow/mvc/NewInstanceFormController.java | Java | bsd-3-clause | 6,693 |
<?php
namespace PayrollCalculator;
use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface;
use Zend\Console\Adapter\AdapterInterface as Console;
class Module
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConsoleUsage(Console $console)
{
return array(
// Describe available commands
'outputpaydays FileName.csv' => 'Show pay days for the remainder of the year',
// Describe expected parameters
array( 'FileName.csv', 'A file where you would like your output saved' ),
);
}
}
| ugniusr/PayrollCalculator | module/PayrollCalculator/Module.php | PHP | bsd-3-clause | 944 |
# -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
| opticode/eve | eve/io/media.py | Python | bsd-3-clause | 2,207 |
<!-- %BD_HTML%/SearchResult.htm -->
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<TITLE>úåöàú àéðèøðè - Takanot File</TITLE>
</HEAD>
<style>
<!--
TR.A_Table {font-color:#3e6ea6; background-color: #f7f9fb; font-size:11;font-family: Arial,}
TR.B_Table {font-color:#3e6ea6; background-color: #ecf1f6; font-size:11;font-family: Arial,}
TR.C {font-color:#1e4a7a; background-color: #A9CAEF;font-weight:bold; font-size:11;font-family: Arial,}
TR.clear { font-color:#1e4a7a; background-color: #FFFFFF;}
H5 { font-family:Arial, Helvetica, sans-serif; font-size: 14px;}
H3 { font-family:Arial, Helvetica, sans-serif; font-size: 16px;}
TD.A_Row { font-family: Arial, Helvetica, sans-serif; font-weight:bold; font-style: normal; color: #093300; font-size: 10px}
.defaultFont { color:#1f4a7b;font-family: Arial, Helvetica, sans-serif; font-size: 12px}
-->
</style>
<BODY dir=rtl class="defaultFont">
<CENTER>
<IMG src="/budget/Images/title1.jpg" align=bottom alt="ú÷öéá äîãéðä">
<TABLE align="center" border=0 cellspacing=0 cellpadding=0>
<TR align="center">
<TD><H3>úåöàú çéôåù ìùðú 2007</H3></TD>
</TR>
<TR align="center">
<!--<TD><H3>ðúåðé áéöåò ðëåðéí ìñåó çåãù 04/2008</H3></TD>-->
<TD><H3>ðúåðé áéöåò ëôé ùðøùîå áñôøé äðäìú äçùáåðåú ùì äîùøãéí - 04/2008<br></H3></TD>
</TR>
</TR align="center">
<TD><H3>àéï àçéãåú áéï äñòéôéí ìâáé îåòã òãëåï äðúåðéí</H3></TD>
</TR>
</TABLE>
<H5>äñëåîéí äéðí ùì çå÷ äú÷öéá äî÷åøé åáàìôé ù÷ìéí <BR>
</H5>
</CENTER>
<table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee">
<TR class="C" align="center">
<TD valign=top width=50>ñòéó</TD>
<TD valign=top align="right" width=120>ùí ñòéó</TD>
<TD valign=top width=65>äåöàä ðèå</TD>
<TD valign=top width=65>äåöàä îåúðéú áäëðñä</TD>
<TD valign=top width=65>ñä"ë äåöàä</TD>
<TD valign=top width=65>äøùàä ìäúçééá</TD>
<TD valign=top width=65>ùéà ë"à</TD>
<TD valign=top width=40>ñä"ë ðåöì</TD>
<TD valign=top width=40>àçåæ ðåöì</TD>
</TR>
</TABLE>
<table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee">
<TR class="B_Table" align="center">
<TD valign=top width=50> 60</TD>
<TD valign=top align="right" width=120> çéðåê</TD>
<TD valign=top width=65> 543,226</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 543,226</TD>
<TD valign=top width=65> 453,365</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 461,148</TD>
<TD valign=top width=40> 84.89</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 6002</TD>
<TD valign=top align="right" width=120> úëðéú ôéúåç çéðåê</TD>
<TD valign=top width=65> 454,800</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 454,800</TD>
<TD valign=top width=65> 384,339</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 364,590</TD>
<TD valign=top width=40> 80.16</TD>
</TR>
<TR class="B_Table" align="center">
<TD valign=top width=50> 600210</TD>
<TD valign=top align="right" width=120> áðééú ëéúåú ìéîåã</TD>
<TD valign=top width=65> 440,316</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 440,316</TD>
<TD valign=top width=65> 369,855</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 350,527</TD>
<TD valign=top width=40> 79.61</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 600215</TD>
<TD valign=top align="right" width=120> úùúéåú äé÷ôéåú ìîáðé çéðåê</TD>
<TD valign=top width=65> 14,484</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 14,484</TD>
<TD valign=top width=65> 14,484</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 14,063</TD>
<TD valign=top width=40> 97.09</TD>
</TR>
<TR class="B_Table" align="center">
<TD valign=top width=50> 6003</TD>
<TD valign=top align="right" width=120> äöèéãåú îáðé çéðåê</TD>
<TD valign=top width=65> 10,505</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 10,505</TD>
<TD valign=top width=65> 10,505</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 10,336</TD>
<TD valign=top width=40> 98.39</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 600301</TD>
<TD valign=top align="right" width=120> îòð÷éí ìäöèéãåú</TD>
<TD valign=top width=65> 10,505</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 10,505</TD>
<TD valign=top width=65> 10,505</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 10,336</TD>
<TD valign=top width=40> 98.39</TD>
</TR>
<TR class="B_Table" align="center">
<TD valign=top width=50> 6006</TD>
<TD valign=top align="right" width=120> çéãåù îáðéí</TD>
<TD valign=top width=65> 61,624</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 61,624</TD>
<TD valign=top width=65> 42,224</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 63,558</TD>
<TD valign=top width=40> 103.14</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 600601</TD>
<TD valign=top align="right" width=120> çéãåù îáðéí áîòøëú</TD>
<TD valign=top width=65> 61,624</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 61,624</TD>
<TD valign=top width=65> 42,224</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 63,558</TD>
<TD valign=top width=40> 103.14</TD>
</TR>
<TR class="B_Table" align="center">
<TD valign=top width=50> 6007</TD>
<TD valign=top align="right" width=120> ôéúåç îëììåú ìäëùøú îåøéí</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 193</TD>
<TD valign=top width=40> 0.00</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 600701</TD>
<TD valign=top align="right" width=120> ôéúåç îëììåú ìäëùøú îåøéí</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 193</TD>
<TD valign=top width=40> 0.00</TD>
</TR>
<TR class="B_Table" align="center">
<TD valign=top width=50> 6008</TD>
<TD valign=top align="right" width=120> øæøáä</TD>
<TD valign=top width=65> 16,297</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 16,297</TD>
<TD valign=top width=65> 16,297</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 16,297</TD>
<TD valign=top width=40> 100.00</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 600801</TD>
<TD valign=top align="right" width=120> øæøáä ìòîéãä áéòãéí</TD>
<TD valign=top width=65> 16,297</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 16,297</TD>
<TD valign=top width=65> 16,297</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 16,297</TD>
<TD valign=top width=40> 100.00</TD>
</TR>
<TR class="B_Table" align="center">
<TD valign=top width=50> 6009</TD>
<TD valign=top align="right" width=120> øæøáä ìééùåí îñ÷ðåú ëç</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 6,174</TD>
<TD valign=top width=40> 0.00</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 600901</TD>
<TD valign=top align="right" width=120> øæøáä ìééùåí îñ÷ðåú ëç</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 6,174</TD>
<TD valign=top width=40> 0.00</TD>
</TR>
</TABLE>
</CENTER>
<BR>
<CENTER>
<table border="0" cellspacing="1" cellpadding="3" bgcolor="#8fbcee" dir="rtl">
<TR class="C" align="center">
<TD class="A_Row" valign=top width=80>ñéëåí ãå"ç</TD>
<TD class="A_Row" valign=top width=60>äåöàä ðèå</TD>
<TD class="A_Row" valign=top width=60>äåöàä îåúðéú áäëðñä</TD>
<TD class="A_Row" valign=top width=60>ñä"ë äåöàä</TD>
<TD class="A_Row" valign=top width=60>äøùàä ìäúçééá</TD>
<TD class="A_Row" valign=top width=60>ùéà ë"à</TD>
<TD class="A_Row" valign=top width=50>ñä"ë ðåöì</TD>
<TD class="A_Row" valign=top width=50>àçåæ ðåöì</TD>
</TR>
<TR class="clear" align="center">
<TD class="A_Row" valign=top width=80> ú÷öéá î÷åøé</TD>
<TD class="A_Row" valign=top width=60> 543,226</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=60> 543,226</TD>
<TD class="A_Row" valign=top width=60> 453,365</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=50> </TD>
<TD class="A_Row" valign=top width=50> </TD>
</TR>
<!--<TR class="clear" align="center">
<TD class="A_Row" valign=top width=80> ú÷öéá òì ùéðåééå</TD>
<TD class="A_Row" valign=top width=60> 792,146</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=60> 792,146</TD>
<TD class="A_Row" valign=top width=60> 563,518</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=50> 461,148</TD>
<TD class="A_Row" valign=top width=50> 84.89</TD>
</TR>-->
</TABLE>
<CENTER>
<TABLE WIDTH="100" >
<TR>
<TD align="center" nowrap>
<IMG SRC="/budget/Images/semel.gif" HEIGHT=37 WIDTH=30 border = "0"><BR>
<FONT SIZE=-2>
<A HREF="http://www.mof.gov.il/rights.htm">
ëì äæëåéåú
©
.ùîåøåú,2005,îãéðú éùøàì<BR></A>
ðùîç ì÷áì àú äòøåúéëí åäöòåúéëí ìëúåáú:
</FONT>
<FONT SIZE=-2 dir=ltr>
<A HREF="mailto:[email protected]">[email protected]</A><BR>
</FONT>
</TD>
</TR>
</TABLE>
</CENTER>
</CENTER>
</BODY>
</HTML>
| daonb/obudget | data/queries/results/result-2007-60.html | HTML | bsd-3-clause | 13,076 |
from django.utils.translation import ugettext as _
from django.db import models
from jmbo.models import ModelBase
class Superhero(ModelBase):
name = models.CharField(max_length=256, editable=False)
class Meta:
verbose_name_plural = _("Superheroes")
| praekelt/jmbo-superhero | superhero/models.py | Python | bsd-3-clause | 269 |
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
export default {"viewBox":"0 0 100 100","xmlns":"http://www.w3.org/2000/svg","path":{"d":"M50.6 52.9c2.6-3.7 5.3-5.6 7.1-8.4 3.2-4.8 3.9-11.6 1.8-16.8-2.1-5.3-7-8.4-12.7-8.3S36.5 23 34.7 28.3c-2.1 5.8-1.2 12.8 3.5 17.2 1.9 1.8 3.7 4.7 2.7 7.4-.9 2.6-4 3.7-6.2 4.8-5 2.2-11.1 5.3-12.1 11.2-1 4.9 2.3 10 7.6 10h23.3c1 0 1.9-1.2 1.3-1.9-3.2-3.7-6.6-8.7-6.6-13.6-.3-3.5.7-7.4 2.4-10.5zm14.2 13.5c-2.7 0-5-2.2-5-4.9s2.2-4.9 5-4.9c2.7 0 5 2.2 5 4.9.1 2.7-2.3 4.9-5 4.9zm0-16.8c-6.6 0-11.9 5.3-11.9 11.9 0 8.1 8.5 15.8 11.1 17.7.4.4 1 .4 1.6 0 2.6-2.1 11.1-9.6 11.1-17.7 0-6.6-5.3-11.9-11.9-11.9z"}};
| salesforce/design-system-react | icons/standard/visits.js | JavaScript | bsd-3-clause | 746 |
<?php
namespace common\widgets;
use yii\helpers\VarDumper;
/**
* Created by PhpStorm.
* User: Александр Чернявенко
* Date: 25.11.2014
* Time: 14:09
*/
class PredictionAsset extends \yii\web\AssetBundle
{
public $depends = [
'yii\web\JqueryAsset',
];
public $css = [
];
public $js = [
];
public function init()
{
$this->setSourcePath(__DIR__ . '/assets/prediction');
parent::init();
}
/**
* Sets the source path if empty
*
* @param string $path the path to be set
*/
protected function setSourcePath($path)
{
if (empty($this->sourcePath)) {
$this->sourcePath = $path;
}
}
} | AleksandrChernyavenko/hintbox | common/widgets/PredictionAsset.php | PHP | bsd-3-clause | 728 |
/*@author gihan tharanga*/
#include <iostream>
#include <string>
//video capturing methods
int videoCapturing();
int videoCapOriginal();
/*detect the faces display the frames and number of face*/
int FaceDetector(std::string&);
| yekaylee/capstone | capstoneRepo/FacialRecognition/C++/projectcV/VideoCap.h | C | bsd-3-clause | 237 |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
''' Processor functions for images '''
import numpy as np
def squeeze_image(img):
''' Return image, remove axes length 1 at end of image shape
For example, an image may have shape (10,20,30,1,1). In this case
squeeze will result in an image with shape (10,20,30). See doctests
for further description of behavior.
Parameters
----------
img : ``SpatialImage``
Returns
-------
squeezed_img : ``SpatialImage``
Copy of img, such that data, and data shape have been squeezed,
for dimensions > 3rd, and at the end of the shape list
Examples
--------
>>> import nipype.externals.pynifti as nf
>>> shape = (10,20,30,1,1)
>>> data = np.arange(np.prod(shape)).reshape(shape)
>>> affine = np.eye(4)
>>> img = nf.Nifti1Image(data, affine)
>>> img.get_shape()
(10, 20, 30, 1, 1)
>>> img2 = squeeze_image(img)
>>> img2.get_shape()
(10, 20, 30)
If the data are 3D then last dimensions of 1 are ignored
>>> shape = (10,1,1)
>>> data = np.arange(np.prod(shape)).reshape(shape)
>>> img = nf.ni1.Nifti1Image(data, affine)
>>> img.get_shape()
(10, 1, 1)
>>> img2 = squeeze_image(img)
>>> img2.get_shape()
(10, 1, 1)
Only *final* dimensions of 1 are squeezed
>>> shape = (1, 1, 5, 1, 2, 1, 1)
>>> data = data.reshape(shape)
>>> img = nf.ni1.Nifti1Image(data, affine)
>>> img.get_shape()
(1, 1, 5, 1, 2, 1, 1)
>>> img2 = squeeze_image(img)
>>> img2.get_shape()
(1, 1, 5, 1, 2)
'''
klass = img.__class__
shape = img.get_shape()
slen = len(shape)
if slen < 4:
return klass.from_image(img)
for bdim in shape[3::][::-1]:
if bdim == 1:
slen-=1
else:
break
if slen == len(shape):
return klass.from_image(img)
shape = shape[:slen]
data = img.get_data()
data = data.reshape(shape)
return klass(data,
img.get_affine(),
img.get_header(),
img.extra)
def concat_images(images):
''' Concatenate images in list to single image, along last dimension '''
n_imgs = len(images)
img0 = images[0]
i0shape = img0.get_shape()
affine = img0.get_affine()
header = img0.get_header()
out_shape = (n_imgs, ) + i0shape
out_data = np.empty(out_shape)
for i, img in enumerate(images):
if not np.all(img.get_affine() == affine):
raise ValueError('Affines do not match')
out_data[i] = img.get_data()
out_data = np.rollaxis(out_data, 0, len(i0shape)+1)
klass = img0.__class__
return klass(out_data, affine, header)
| satra/NiPypeold | nipype/externals/pynifti/funcs.py | Python | bsd-3-clause | 2,788 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__short_rand_postdec_07.c
Label Definition File: CWE191_Integer_Underflow.label.xml
Template File: sources-sinks-07.tmpl.c
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: rand Set data to result of rand()
* GoodSource: Set data to a small, non-zero number (negative two)
* Sinks: decrement
* GoodSink: Ensure there will not be an underflow before decrementing data
* BadSink : Decrement data, which can cause an Underflow
* Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
*
* */
#include "std_testcase.h"
/* The variable below is not declared "const", but is never assigned
any other value so a tool should be able to identify that reads of
this will always give its initialized value. */
static int staticFive = 5;
#ifndef OMITBAD
void CWE191_Integer_Underflow__short_rand_postdec_07_bad()
{
short data;
data = 0;
if(staticFive==5)
{
/* POTENTIAL FLAW: Use a random value */
data = (short)RAND32();
}
if(staticFive==5)
{
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
short result = data;
printIntLine(result);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second staticFive==5 to staticFive!=5 */
static void goodB2G1()
{
short data;
data = 0;
if(staticFive==5)
{
/* POTENTIAL FLAW: Use a random value */
data = (short)RAND32();
}
if(staticFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Add a check to prevent an underflow from occurring */
if (data > SHRT_MIN)
{
data--;
short result = data;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
short data;
data = 0;
if(staticFive==5)
{
/* POTENTIAL FLAW: Use a random value */
data = (short)RAND32();
}
if(staticFive==5)
{
/* FIX: Add a check to prevent an underflow from occurring */
if (data > SHRT_MIN)
{
data--;
short result = data;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first staticFive==5 to staticFive!=5 */
static void goodG2B1()
{
short data;
data = 0;
if(staticFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */
data = -2;
}
if(staticFive==5)
{
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
short result = data;
printIntLine(result);
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
short data;
data = 0;
if(staticFive==5)
{
/* FIX: Use a small, non-zero value that will not cause an underflow in the sinks */
data = -2;
}
if(staticFive==5)
{
{
/* POTENTIAL FLAW: Decrementing data could cause an underflow */
data--;
short result = data;
printIntLine(result);
}
}
}
void CWE191_Integer_Underflow__short_rand_postdec_07_good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE191_Integer_Underflow__short_rand_postdec_07_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE191_Integer_Underflow__short_rand_postdec_07_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE191_Integer_Underflow/s04/CWE191_Integer_Underflow__short_rand_postdec_07.c | C | bsd-3-clause | 4,979 |
<?php
namespace VKBansal\Test\Spectrum\Plugin;
class PlugTest extends \PHPUnit_Framework_TestCase{
protected $plugin;
protected $plug;
public function setUp()
{
$this->plugin = $this->getMockForAbstractClass('VKBansal\Spectrum\Plugin\AbstractPlugin');
$this->plugin
->method('getName')->will($this->returnValue('test-plugin'));
$this->plugin
->method('add')->will($this->returnValue(true));
$this->plugin
->method('remove')->will($this->returnValue(true));
$this->plug = $this->getMockForTrait('VKBansal\Spectrum\Plugin\PluggableTrait', [], 'Spectrum');
}
/**
* @expectedException \VKBansal\Spectrum\Plugin\PluginNotFoundException
*/
public function testRemoveException()
{
$this->markTestSkipped();
$this->plug->addPlugin($this->plugin);
$this->plug->removePlugin('test-plugin');
$this->plug->removePlugin('test-plugin');
}
}
| vkbansal/spectrum | test/Plugin/PlugTest.php | PHP | bsd-3-clause | 996 |
<div>
<div class="os-page-commands">
<div class="left" os-imaging>
<button show-if-allowed="specimenResource.updateOpts" class="default" ui-sref="specimen-addedit"
ng-if="!!visit.id && !specimen.reserved && (!specimen.activityStatus || specimen.activityStatus == 'Active')"
ng-switch on="!!specimen.id">
<span ng-switch-when="true">
<span class="fa fa-pencil"></span>
<span translate="common.buttons.edit">Edit</span>
</span>
<span ng-switch-default>
<span class="fa fa-plus"></span>
<span translate="specimens.buttons.collect">Collect</span>
</span>
</button>
<span ng-if="!!specimen.id">
<div ng-if="!specimen.reserved && specimen.activityStatus == 'Active' && specimen.status == 'Collected'"
show-if-allowed="specimenResource.allUpdateOpts" dropdown class="os-inline-btn">
<button class="btn btn-default dropdown-toggle default">
<span class="fa fa-plus"></span>
<span translate="common.buttons.create">Create</span>
<span class="fa fa-caret-down"></span>
</button>
<ul class="dropdown-menu">
<li>
<a ui-sref="specimen-create-derivative(
{eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})">
<span class="fa fa-flask"></span>
<span translate="specimens.ctx_menu.create_derivative">Create Derivative</span>
</a>
</li>
<li>
<a ui-sref="specimen-create-aliquots(
{eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})">
<span class="fa fa-share-alt"></span>
<span translate="specimens.ctx_menu.create_aliquots">Create Aliquots</span>
</a>
</li>
</ul>
</div>
<os-assign-to-spmn-list menu-align="left" on-add-to-list="addSpecimensToSpecimenList(list)">
</os-assign-to-spmn-list>
<button show-if-allowed="specimenResource.updateOpts" class="default"
ng-if="!cpViewCtx.isCoordinator && specimen.activityStatus == 'Active' && specimen.status == 'Collected'"
ng-click="printSpecimenLabels()">
<span class="fa fa-print"></span>
<span translate="specimens.buttons.print">Print</span>
</button>
<button show-if-allowed="specimenResource.deleteOpts" class="default" ng-click="deleteSpecimen()">
<span class="fa fa-trash"></span>
<span translate="common.buttons.delete">Delete</span>
</button>
<div dropdown os-show-if-menu-items-present class="os-inline-btn">
<button class="btn btn-default dropdown-toggle default">
<span translate="common.buttons.more">More</span>
<span class="fa fa-caret-down"></span>
</button>
<ul class="dropdown-menu dropdown-menu-right">
<li ng-if="!!specimen.imageId">
<os-view-image image-id="specimen.imageId" show-text="true"></os-view-image>
</li>
<li show-if-allowed="specimenResource.updateOpts"
ng-if="!cpViewCtx.isCoordinator && !specimen.reserved && specimen.activityStatus == 'Active'
&& specimen.status == 'Collected'">
<a ui-sref="specimen-detail.events(
{eventId: visit.eventId, visitId: visit.id, specimenId: specimen.id, srId: specimen.reqId})">
<span class="fa fa-calendar-o"></span>
<span translate="specimens.ctx_menu.add_event">Add Event</span>
</a>
</li>
<li show-if-allowed="specimenResource.updateOpts"
ng-if="!cpViewCtx.isCoordinator && !specimen.reserved && specimen.activityStatus == 'Active'
&& specimen.status == 'Collected'">
<a ng-click="closeSpecimen()">
<span class="fa fa-remove"></span>
<span translate="common.buttons.close">Close</span>
</a>
</li>
<li show-if-allowed="specimenResource.updateOpts"
ng-if="!cpViewCtx.isCoordinator && specimen.activityStatus == 'Closed'">
<a ng-click="reopen()">
<span class="fa fa-check"></span>
<span translate="specimens.buttons.reopen">Reopen</span>
</a>
</li>
</ul>
</div>
</span>
</div>
<div class="right">
<button class="default" os-right-drawer-toggle ng-switch on="spmnCtx.showActivity" ng-click="toggleShowActivity()">
<span ng-switch-when="true" translate="common.buttons.hide_activity">Hide Events</span>
<span ng-switch-when="false" translate="common.buttons.show_activity">Show Events</span>
</button>
</div>
</div>
<div class="clearfix os-container-wrapper">
<div class="container os-col" style="width: 100%;">
<div ng-switch on="fieldsCtx.hasDict">
<div ng-switch-when="true">
<sde-fields-overview base-fields="fieldsCtx.sysDict" fields="fieldsCtx.cpDict"
obj="spmnCtx.obj" in-objs="spmnCtx.inObjs" ex-objs="spmnCtx.exObjs" watcher="spmnCtx.watcher">
</sde-fields-overview>
</div>
<div ng-switch-default>
<div ng-include="'modules/biospecimen/participant/specimen/static-fields.html'"></div>
</div>
</div>
<span show-if-allowed="specimenResource.allReadOpts" style="display: inline-block; width: 100%;">
<os-specimen-tree cp="cp" cpr="cpr" visit="visit" specimens="treeSpecimens"
allowed-ops="specimenAllowedOps" reload="reload()"
pending-spmns-disp-interval="pendingSpmnsDispInterval">
</os-specimen-tree>
</span>
</div>
<div class="os-col os-no-border" os-right-drawer open-width="34" style="position: static;">
<div ng-if="!!specimen.id">
<os-audit-overview class="os-no-top-margin" object-name="'specimen'" object-id="specimen.id"></os-audit-overview>
</div>
<div ng-include="'modules/biospecimen/participant/specimen/activities.html'"></div>
</div>
</div>
</div>
<script type="text/ng-template" id="modules/biospecimen/participant/specimen/static-fields.html">
<div>
<ul class="os-key-values os-two-cols">
<li class="item">
<strong class="key key-sm" translate="specimens.lineage">Lineage</strong>
<span class="value value-md">{{specimen.lineage | osNoValue}}</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.collection_status">Status</strong>
<ng-switch on="!specimen.distributionStatus">
<ng-switch ng-switch-when="true" on="specimen.status">
<span ng-switch-when="Collected" class="value value-md os-status-collected">Collected</span>
<span ng-switch-when="Missed Collection" class="value value-md os-status-missed">Missed Collection</span>
<span ng-switch-when="Not Collected" class="value value-md os-status-missed">Not Collected</span>
<span ng-switch-default class="value value-md os-status-pending">Pending</span>
</ng-switch>
<ng-switch ng-switch-when="false" on="specimen.distributionStatus">
<span ng-switch-when="Distributed">
<span class="value value-md" ng-class="specimen.availableQty > 0 ? 'os-status-part-distributed' : 'os-status-distributed'">
Distributed
</span>
</span>
<span ng-switch-when="Returned" class="value value-md os-status-returned">Returned</span>
</ng-switch>
</ng-switch>
</li>
<li class="item" ng-if="barcodingEnabled">
<strong class="key key-sm" translate="specimens.barcode">Barcode</strong>
<span class="value value-md">{{specimen.barcode | osNoValue}}</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.type">Specimen Type</strong>
<span class="value value-md">
<span>{{specimen.type | osNoValue}}</span>
<span ng-if="specimen.specimenClass">({{specimen.specimenClass}})</span>
</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.anatomic_site">Anatomic Site</strong>
<span class="value value-md">{{specimen.anatomicSite | osNoValue}}</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.laterality">Laterality</strong>
<span class="value value-md">{{specimen.laterality | osNoValue}}</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.initial_qty">Initial Quantity</strong>
<os-spmn-measure-val value="specimen.initialQty" specimen="specimen"></os-spmn-measure-val>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.available_qty">Available Quantity</strong>
<os-spmn-measure-val value="specimen.availableQty" specimen="specimen"></os-spmn-measure-val>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.concentration">Concentration</strong>
<os-spmn-measure-val value="specimen.concentration" measure="'concentration'" specimen="specimen">
</os-spmn-measure-val>
</li>
<li class="item" ng-if="!!specimen.parentId">
<strong class="key key-sm" translate="specimens.parent_specimen">Parent Specimen</strong>
<span class="value value-md">
<a ui-sref="specimen-detail.overview(
{eventId: visit.eventId, visitId: visit.id, specimenId: specimen.parentId, srId: specimen.reqId})">
<span ng-if="!!specimen.parentLabel">{{specimen.parentLabel}}</span>
<span ng-if="!specimen.parentLabel" translate="specimens.parent_specimen">Parent Specimen</span>
</a>
</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.pathology">Pathology Status</strong>
<span class="value value-md">{{specimen.pathology | osNoValue}}</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.storage_location">Storage Location</strong>
<ng-switch on="!!specimen.storageLocation.id && specimen.storageLocation.id != -1">
<span class="value value-md" ng-switch-when="true">
<a ui-sref="container-detail.locations({containerId: specimen.storageLocation.id})">
<os-disp-storage-position position="specimen.storageLocation"></os-disp-storage-position>
</a>
</span>
<span class="value value-md" ng-switch-default translate="specimens.virtually_located">
Virtual
</span>
</ng-switch>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.biohazards">Biohazards</strong>
<span class="value value-md">{{specimen.biohazards | osArrayJoin | osNoValue}}</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.created_on">Created On</strong>
<span class="value value-md">{{specimen.createdOn | date: global.dateTimeFmt | osNoValue}}</span>
</li>
<li class="item" ng-if="specimen.lineage != 'New'">
<strong class="key key-sm" translate="specimens.created_by">Created By</strong>
<span class="value value-md">{{specimen.createdBy | osUserDisplayName | osNoValue}}</span>
</li>
<li class="item">
<strong class="key key-sm" translate="specimens.freeze_thaw_cycles">Freeze/Thaw Cycles</strong>
<span class="value value-md">{{specimen.freezeThawCycles | osNoValue}}</span>
</li>
</ul>
<div ng-if="!!specimen.extensionDetail">
<div os-extension-overview ext-object="specimen.extensionDetail" show-column="2"></div>
</div>
<div class="os-section os-line-section" ng-if="!!specimen.comments">
<strong class="key key-sm">
<span translate="specimens.comments">Comments</span>
<span> </span>
</strong>
<span class="value value-md">{{specimen.comments}}</span>
</div>
<div ng-include="'modules/biospecimen/participant/specimen/external-ids.html'"></div>
<div class="os-section" ng-init="opCollapsed=false" ng-if="specimen.specimensPool.length >= 1">
<button class="os-btn-section-collapse os-btn-transparent" ng-click="opCollapsed=!opCollapsed">
<span ng-if="!opCollapsed" class="fa fa-chevron-circle-down"></span>
<span ng-if="opCollapsed" class="fa fa-chevron-circle-right"></span>
</button>
<h3 class="os-sub-section-title">
<span translate="specimens.pooled_from">Pooled From</span>
</h3>
<div collapse="opCollapsed">
<span ng-repeat="p in specimen.specimensPool">
<a ui-sref="specimen-detail.overview({cpId: p.cpId, cprId: p.cprId, visitId: p.visitId, specimenId: p.id})">
<span>{{p.label}}{{$last ? '' : ','}}</span>
</a>
</span>
</div>
</div>
<div class="os-section" ng-init="opCollapsed=false" ng-if="specimen.pooledSpecimens.length >= 1">
<button class="os-btn-section-collapse os-btn-transparent" ng-click="opCollapsed=!opCollapsed">
<span ng-if="!opCollapsed" class="fa fa-chevron-circle-down"></span>
<span ng-if="opCollapsed" class="fa fa-chevron-circle-right"></span>
</button>
<h3 class="os-sub-section-title">
<span translate="specimens.pooled_in">Pooled In</span>
</h3>
<div collapse="opCollapsed">
<span ng-repeat="p in specimen.pooledSpecimens">
<a ui-sref="specimen-detail.overview({cpId: p.cpId, cprId: p.cprId, visitId: p.visitId, specimenId: p.id})">
<span>{{p.label}}{{$last ? '' : ','}}</span>
</a>
</span>
</div>
</div>
</div>
</script>
<script type="text/ng-template" id="modules/biospecimen/participant/specimen/activities.html">
<div>
<h3 class="os-sub-section-title" translate="specimens.recent_events">
Recent Activity
</h3>
<span ng-if="activities.length == 0" translate="common.none">None</span>
<ul class="os-activity-list" ng-if="activities.length > 0">
<li class="os-activity" ng-repeat="activity in activities">
<div class="title" ng-switch on="activity.isEditable">
<a ui-sref="specimen-detail.event-overview({recordId: activity.id, formId: activity.formId})">
<ng-include src="'modules/biospecimen/participant/specimen/activity-info.html'"></ng-include>
</a>
</div>
<div class="info">
<span>
{{activity.updatedBy | osUserDisplayName}} -
{{activity.updateTime | date: global.dateTimeFmt}}
</span>
</div>
</li>
</ul>
</div>
</script>
<script type="text/ng-template" id="modules/biospecimen/participant/specimen/activity-info.html">
<span>
<span ng-if="!!activity.user && !!activity.time">
{{'specimens.activity_full_info' | translate: activity}}
</span>
<span ng-if="!!activity.user && !activity.time">
{{'specimens.activity_user_info' | translate: activity}}
</span>
<span ng-if="!activity.user && !!activity.time">
{{'specimens.activity_time_info' | translate: activity}}
</span>
<span ng-if="!activity.user && !activity.time">
{{'specimens.activity_info' | translate: activity}}
</span>
</span>
</script>
<script type="text/ng-template" id="modules/biospecimen/participant/specimen/confirm-print.html">
<div class="os-modal">
<div class="os-modal-header">
<span translate="specimens.confirm_print">Confirm Print</span>
</div>
<div class="os-modal-body">
<span translate="specimens.confirm_print_q">Do you want to print child specimen labels as well?</span>
</div>
<div class="os-modal-footer">
<button class="btn os-btn-text" ng-click="cancel()">
<span translate="common.buttons.discard">Cancel</span>
</button>
<button class="btn os-btn-secondary" ng-click="printSpecimenLabels(false)">
<span translate="specimens.buttons.print_current">No, only current specimen</span>
</button>
<button class="btn btn-primary" ng-click="printSpecimenLabels(true)">
<span translate="common.yes">Yes</span>
</button>
</div>
</div>
</script>
<script type="text/ng-template" id="modules/biospecimen/participant/specimen/external-ids.html">
<div class="os-section" ng-init="extIdsCollapsed=false" ng-if="specimen.externalIds.length > 0">
<button class="os-btn-section-collapse os-btn-transparent" ng-click="extIdsCollapsed=!extIdsCollapsed">
<span class="fa" ng-class="{true: 'fa-chevron-circle-right', false: 'fa-chevron-circle-down'}[extIdsCollapsed]"></span>
</button>
<h3 class="os-sub-section-title" translate="specimens.external_ids">External IDs</h3>
<div collapse="extIdsCollapsed">
<table class="os-table os-table-muted-hdr os-border">
<thead class="os-table-head">
<tr class="row">
<th class="col col-xs-6">
<span translate="common.name">Name</span>
</th>
<th class="col col-xs-6">
<span translate="common.value">Value</span>
</th>
</tr>
</thead>
<tbody class="os-table-body">
<tr class="row" ng-repeat="extId in specimen.externalIds">
<td class="col col-xs-6">
<span>{{extId.name | osNoValue}}</span>
</td>
<td class="col col-xs-6">
<span>{{extId.value | osNoValue}}</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</script>
| krishagni/openspecimen | www/app/modules/biospecimen/participant/specimen/overview.html | HTML | bsd-3-clause | 17,947 |
/*
Copyright (C) 2009-2010 ProFUSION embedded systems
Copyright (C) 2009-2010 Samsung Electronics
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "ewk_history.h"
#include "BackForwardList.h"
#include "CairoUtilitiesEfl.h"
#include "HistoryItem.h"
#include "IconDatabaseBase.h"
#include "Image.h"
#include "IntSize.h"
#include "Page.h"
#include "PageGroup.h"
#include "ewk_history_private.h"
#include "ewk_private.h"
#include <Eina.h>
#include <eina_safety_checks.h>
#include <wtf/text/CString.h>
struct _Ewk_History {
WebCore::BackForwardList* core;
};
#define EWK_HISTORY_CORE_GET_OR_RETURN(history, core_, ...) \
if (!(history)) { \
CRITICAL("history is NULL."); \
return __VA_ARGS__; \
} \
if (!(history)->core) { \
CRITICAL("history->core is NULL."); \
return __VA_ARGS__; \
} \
if (!(history)->core->enabled()) { \
ERR("history->core is disabled!."); \
return __VA_ARGS__; \
} \
WebCore::BackForwardList* core_ = (history)->core
struct _Ewk_History_Item {
WebCore::HistoryItem* core;
const char* title;
const char* alternateTitle;
const char* uri;
const char* originalUri;
};
#define EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core_, ...) \
if (!(item)) { \
CRITICAL("item is NULL."); \
return __VA_ARGS__; \
} \
if (!(item)->core) { \
CRITICAL("item->core is NULL."); \
return __VA_ARGS__; \
} \
WebCore::HistoryItem* core_ = (item)->core
static inline Eina_List* _ewk_history_item_list_get(const WebCore::HistoryItemVector& coreItems)
{
Eina_List* result = 0;
unsigned int size;
size = coreItems.size();
for (unsigned int i = 0; i < size; i++) {
Ewk_History_Item* item = ewk_history_item_new_from_core(coreItems[i].get());
if (item)
result = eina_list_append(result, item);
}
return result;
}
Eina_Bool ewk_history_clear(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
WebCore::Page* page = core->page();
if (page && page->groupPtr())
page->groupPtr()->removeVisitedLinks();
const int limit = ewk_history_limit_get(history);
ewk_history_limit_set(history, 0);
ewk_history_limit_set(history, limit);
return true;
}
Eina_Bool ewk_history_forward(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
if (core->forwardListCount() < 1)
return false;
core->goForward();
return true;
}
Eina_Bool ewk_history_back(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
if (core->backListCount() < 1)
return false;
core->goBack();
return true;
}
Eina_Bool ewk_history_history_item_add(Ewk_History* history, const Ewk_History_Item* item)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false);
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false);
history_core->addItem(item_core);
return true;
}
Eina_Bool ewk_history_history_item_set(Ewk_History* history, const Ewk_History_Item* item)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false);
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false);
history_core->goToItem(item_core);
return true;
}
Ewk_History_Item* ewk_history_history_item_back_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return ewk_history_item_new_from_core(core->backItem());
}
Ewk_History_Item* ewk_history_history_item_current_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItem* currentItem = core->currentItem();
if (currentItem)
return ewk_history_item_new_from_core(currentItem);
return 0;
}
Ewk_History_Item* ewk_history_history_item_forward_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return ewk_history_item_new_from_core(core->forwardItem());
}
Ewk_History_Item* ewk_history_history_item_nth_get(const Ewk_History* history, int index)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return ewk_history_item_new_from_core(core->itemAtIndex(index));
}
Eina_Bool ewk_history_history_item_contains(const Ewk_History* history, const Ewk_History_Item* item)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false);
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false);
return history_core->containsItem(item_core);
}
Eina_List* ewk_history_forward_list_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
int limit = core->forwardListCount();
core->forwardListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
Eina_List* ewk_history_forward_list_get_with_limit(const Ewk_History* history, int limit)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
core->forwardListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
int ewk_history_forward_list_length(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return core->forwardListCount();
}
Eina_List* ewk_history_back_list_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
int limit = core->backListCount();
core->backListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
Eina_List* ewk_history_back_list_get_with_limit(const Ewk_History* history, int limit)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
core->backListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
int ewk_history_back_list_length(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return core->backListCount();
}
int ewk_history_limit_get(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return core->capacity();
}
Eina_Bool ewk_history_limit_set(const Ewk_History* history, int limit)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
core->setCapacity(limit);
return true;
}
Ewk_History_Item* ewk_history_item_new_from_core(WebCore::HistoryItem* core)
{
Ewk_History_Item* item;
if (!core) {
ERR("WebCore::HistoryItem is NULL.");
return 0;
}
core->ref();
item = new Ewk_History_Item;
memset(item, 0, sizeof(*item));
item->core = core;
return item;
}
Ewk_History_Item* ewk_history_item_new(const char* uri, const char* title)
{
WTF::String historyUri = WTF::String::fromUTF8(uri);
WTF::String historyTitle = WTF::String::fromUTF8(title);
WTF::RefPtr<WebCore::HistoryItem> core = WebCore::HistoryItem::create(historyUri, historyTitle, 0);
Ewk_History_Item* item = ewk_history_item_new_from_core(core.release().leakRef());
return item;
}
static inline void _ewk_history_item_free(Ewk_History_Item* item, WebCore::HistoryItem* core)
{
core->deref();
delete item;
}
void ewk_history_item_free(Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core);
_ewk_history_item_free(item, core);
}
void ewk_history_item_list_free(Eina_List* history_items)
{
void* deleteItem;
EINA_LIST_FREE(history_items, deleteItem) {
Ewk_History_Item* item = (Ewk_History_Item*)deleteItem;
_ewk_history_item_free(item, item->core);
}
}
const char* ewk_history_item_title_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item);
eina_stringshare_replace(&historyItem->title, core->title().utf8().data());
return historyItem->title;
}
const char* ewk_history_item_title_alternate_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item);
eina_stringshare_replace(&historyItem->alternateTitle,
core->alternateTitle().utf8().data());
return historyItem->alternateTitle;
}
void ewk_history_item_title_alternate_set(Ewk_History_Item* item, const char* title)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core);
if (!eina_stringshare_replace(&item->alternateTitle, title))
return;
core->setAlternateTitle(WTF::String::fromUTF8(title));
}
const char* ewk_history_item_uri_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>((item));
eina_stringshare_replace(&historyItem->uri, core->urlString().utf8().data());
return historyItem->uri;
}
const char* ewk_history_item_uri_original_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item);
eina_stringshare_replace(&historyItem->originalUri,
core->originalURLString().utf8().data());
return historyItem->originalUri;
}
double ewk_history_item_time_last_visited_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0.0);
return core->lastVisitedTime();
}
cairo_surface_t* ewk_history_item_icon_surface_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
RefPtr<cairo_surface_t> icon = WebCore::iconDatabase().synchronousNativeIconForPageURL(core->url(), WebCore::IntSize(16, 16));
if (!icon)
ERR("icon is NULL.");
return icon.get();
}
Evas_Object* ewk_history_item_icon_object_add(const Ewk_History_Item* item, Evas* canvas)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
EINA_SAFETY_ON_NULL_RETURN_VAL(canvas, 0);
RefPtr<cairo_surface_t> surface = WebCore::iconDatabase().synchronousNativeIconForPageURL(core->url(), WebCore::IntSize(16, 16));
if (!surface) {
ERR("icon is NULL.");
return 0;
}
return surface ? WebCore::evasObjectFromCairoImageSurface(canvas, surface.get()).leakRef() : 0;
}
Eina_Bool ewk_history_item_page_cache_exists(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, false);
return core->isInPageCache();
}
int ewk_history_item_visit_count(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
return core->visitCount();
}
Eina_Bool ewk_history_item_visit_last_failed(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, true);
return core->lastVisitWasFailure();
}
/* internal methods ****************************************************/
/**
* @internal
*
* Creates history for given view. Called internally by ewk_view and
* should never be called from outside.
*
* @param core WebCore::BackForwardList instance to use internally.
*
* @return newly allocated history instance or @c NULL on errors.
*/
Ewk_History* ewk_history_new(WebCore::BackForwardList* core)
{
Ewk_History* history;
EINA_SAFETY_ON_NULL_RETURN_VAL(core, 0);
DBG("core=%p", core);
history = new Ewk_History;
history->core = core;
core->ref();
return history;
}
/**
* @internal
*
* Destroys previously allocated history instance. This is called
* automatically by ewk_view and should never be called from outside.
*
* @param history instance to free
*/
void ewk_history_free(Ewk_History* history)
{
DBG("history=%p", history);
history->core->deref();
delete history;
}
namespace EWKPrivate {
WebCore::HistoryItem* coreHistoryItem(const Ewk_History_Item* ewkHistoryItem)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(ewkHistoryItem, core, 0);
return core;
}
} // namespace EWKPrivate
| klim-iv/phantomjs-qt5 | src/webkit/Source/WebKit/efl/ewk/ewk_history.cpp | C++ | bsd-3-clause | 13,646 |
<?php
/**
* Yasc.
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://github.com/nebiros/yasc/raw/master/LICENSE
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Yasc
* @package Yasc
* @subpackage Yasc_App
* @copyright Copyright (c) 2010 - 2014 Juan Felipe Alvarez Sadarriaga. (http://juan.im)
* @version $Id$
* @license http://github.com/nebiros/yasc/raw/master/LICENSE New BSD License
*/
/**
* Configuration.
*
* @package Yasc
* @subpackage Yasc_App
* @copyright Copyright (c) 2010 - 2014 Juan Felipe Alvarez Sadarriaga. (http://juan.im)
* @license http://github.com/nebiros/yasc/raw/master/LICENSE New BSD License
* @author nebiros
*/
class Yasc_App_Config {
/**
*
* @var array
*/
protected $_options = array();
/**
*
* @var bool
*/
protected $_useViewStream = false;
/**
* Layout.
*
* @var string
*/
protected $_layoutScript = null;
/**
*
*/
public function __construct() {
$this->_addDefaultPaths();
}
/**
*
* @param array $options
* @return Yasc_App_Config
*/
public function setOptions(Array $options) {
$this->_options = $options;
return $this;
}
/**
*
* @return array
*/
public function getOptions() {
return $this->_options;
}
/**
*
* @param mixed $key
* @param mixed $default
* @return mixed|null
*/
public function getOption($key, $default = null) {
if (true === isset($this->_options[$key])) {
return $this->_options[$key];
}
return $default;
}
/**
*
* @param array $options
* @return Yasc_App_Config
*/
public function addOptions(Array $options) {
$this->_options = array_merge($this->_options, $options);
return $this;
}
/**
*
* @param mixed $key
* @param mixed $value
* @return Yasc_App_Config
*/
public function addOption($key, $value = null) {
$this->_options[$key] = $value;
return $this;
}
/**
*
* @param bool $flag
* @return Yasc_App_Config
*/
public function setViewStream($flag = false) {
$this->_useViewStream = $flag;
return $this;
}
/**
*
* @return bool
*/
public function useViewStream() {
return $this->_useViewStream;
}
/**
*
* @return array
*/
public function getViewsPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW);
}
/**
*
* @param string $path
* @return Yasc_App_Config
*/
public function setViewsPath($path) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path);
return $this;
}
/**
*
* @param string $path
* @return Yasc_App_Config
*/
public function addViewsPath($path) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW, $path);
return $this;
}
/**
*
* @return string
*/
public function getLayoutScript() {
return $this->_layoutScript;
}
/**
*
* @param string $layout
* @return Yasc_App_Config
*/
public function setLayoutScript($layout) {
if (false === is_string($layout)) {
return false;
}
$layout = realpath($layout);
if (false === is_file($layout)) {
throw new Yasc_App_Exception("Layout file '{$layout}' not found");
}
$this->_layoutScript = $layout;
// Cause a layout is a view too, we going to add layout script folder
// to the views folders.
$this->addViewsPath(dirname($this->_layoutScript));
return $this;
}
/**
*
* @return array
*/
public function getViewHelperPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER);
}
/**
*
* @param string $classPrefix
* @return string
*/
public function getViewHelpersPath($classPrefix = null) {
return Yasc_Autoloader_Manager::getInstance()->getPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $classPrefix);
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function setViewHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->setPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function addViewHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @return array
*/
public function getFunctionHelperPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER);
}
/**
*
* @param string $classPrefix
* @return string
*/
public function getFunctionHelpersPath($classPrefix = null) {
return Yasc_Autoloader_Manager::getInstance()->getPath(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $classPrefix);
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function setFunctionHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->setPath(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function addFunctionHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @return array
*/
public function getModelPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL);
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function setModelsPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->setPath(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $path, $classPrefix);
return $this;
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function addModelsPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $path, $classPrefix);
return $this;
}
/**
*
* @return void
*/
protected function _addDefaultPaths() {
$views = realpath(APPLICATION_PATH . "/views");
$helpers = realpath(APPLICATION_PATH . "/views/helpers");
$models = realpath(APPLICATION_PATH . "/models");
// default paths, if they exist.
if (true === is_dir($views)) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW, $views);
}
if (true === is_dir($helpers)) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $helpers, "Helper");
}
if (true === is_dir($models)) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $models, "Model");
}
}
}
| nebiros/yasc | src/Yasc/App/Config.php | PHP | bsd-3-clause | 8,643 |
//===-- lib/Evaluate/fold-real.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "fold-implementation.h"
namespace Fortran::evaluate {
template <int KIND>
Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
FoldingContext &context,
FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) {
using T = Type<TypeCategory::Real, KIND>;
using ComplexT = Type<TypeCategory::Complex, KIND>;
ActualArguments &args{funcRef.arguments()};
auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
CHECK(intrinsic);
std::string name{intrinsic->name};
if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" ||
(name == "atan" && args.size() == 1) || name == "atanh" ||
name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" ||
name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" ||
name == "erfc" || name == "erfc_scaled" || name == "exp" ||
name == "gamma" || name == "log" || name == "log10" ||
name == "log_gamma" || name == "sin" || name == "sinh" ||
name == "sqrt" || name == "tan" || name == "tanh") {
CHECK(args.size() == 1);
if (auto callable{context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, T>(name)}) {
return FoldElementalIntrinsic<T, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(real(kind=%d)) cannot be folded on host"_en_US, name, KIND);
}
} else if (name == "atan" || name == "atan2" || name == "hypot" ||
name == "mod") {
std::string localName{name == "atan2" ? "atan" : name};
CHECK(args.size() == 2);
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, T, T>(localName)}) {
return FoldElementalIntrinsic<T, T, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(real(kind=%d), real(kind%d)) cannot be folded on host"_en_US,
name, KIND, KIND);
}
} else if (name == "bessel_jn" || name == "bessel_yn") {
if (args.size() == 2) { // elemental
// runtime functions use int arg
using Int4 = Type<TypeCategory::Integer, 4>;
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, Int4, T>(name)}) {
return FoldElementalIntrinsic<T, Int4, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_en_US,
name, KIND);
}
}
} else if (name == "abs") {
// Argument can be complex or real
if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
return FoldElementalIntrinsic<T, T>(
context, std::move(funcRef), &Scalar<T>::ABS);
} else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, ComplexT>("abs")}) {
return FoldElementalIntrinsic<T, ComplexT>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"abs(complex(kind=%d)) cannot be folded on host"_en_US, KIND);
}
} else {
common::die(" unexpected argument type inside abs");
}
} else if (name == "aimag") {
return FoldElementalIntrinsic<T, ComplexT>(
context, std::move(funcRef), &Scalar<ComplexT>::AIMAG);
} else if (name == "aint" || name == "anint") {
// ANINT rounds ties away from zero, not to even
common::RoundingMode mode{name == "aint"
? common::RoundingMode::ToZero
: common::RoundingMode::TiesAwayFromZero};
return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
ScalarFunc<T, T>([&name, &context, mode](
const Scalar<T> &x) -> Scalar<T> {
ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)};
if (y.flags.test(RealFlag::Overflow)) {
context.messages().Say("%s intrinsic folding overflow"_en_US, name);
}
return y.value;
}));
} else if (name == "dprod") {
if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) {
return Fold(context,
Expr<T>{Multiply<T>{
Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}});
}
} else if (name == "epsilon") {
return Expr<T>{Scalar<T>::EPSILON()};
} else if (name == "huge") {
return Expr<T>{Scalar<T>::HUGE()};
} else if (name == "max") {
return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
} else if (name == "merge") {
return FoldMerge<T>(context, std::move(funcRef));
} else if (name == "min") {
return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
} else if (name == "real") {
if (auto *expr{args[0].value().UnwrapExpr()}) {
return ToReal<KIND>(context, std::move(*expr));
}
} else if (name == "sign") {
return FoldElementalIntrinsic<T, T, T>(
context, std::move(funcRef), &Scalar<T>::SIGN);
} else if (name == "tiny") {
return Expr<T>{Scalar<T>::TINY()};
}
// TODO: cshift, dim, dot_product, eoshift, fraction, matmul,
// maxval, minval, modulo, nearest, norm2, pack, product,
// reduce, rrspacing, scale, set_exponent, spacing, spread,
// sum, transfer, transpose, unpack, bessel_jn (transformational) and
// bessel_yn (transformational)
return Expr<T>{std::move(funcRef)};
}
template <int KIND>
Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
FoldingContext &context, ComplexComponent<KIND> &&x) {
using Operand = Type<TypeCategory::Complex, KIND>;
using Result = Type<TypeCategory::Real, KIND>;
if (auto array{ApplyElementwise(context, x,
std::function<Expr<Result>(Expr<Operand> &&)>{
[=](Expr<Operand> &&operand) {
return Expr<Result>{ComplexComponent<KIND>{
x.isImaginaryPart, std::move(operand)}};
}})}) {
return *array;
}
using Part = Type<TypeCategory::Real, KIND>;
auto &operand{x.left()};
if (auto value{GetScalarConstantValue<Operand>(operand)}) {
if (x.isImaginaryPart) {
return Expr<Part>{Constant<Part>{value->AIMAG()}};
} else {
return Expr<Part>{Constant<Part>{value->REAL()}};
}
}
return Expr<Part>{std::move(x)};
}
FOR_EACH_REAL_KIND(template class ExpressionBase, )
template class ExpressionBase<SomeReal>;
} // namespace Fortran::evaluate
| endlessm/chromium-browser | third_party/llvm/flang/lib/Evaluate/fold-real.cpp | C++ | bsd-3-clause | 6,929 |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*/
class LoginForm extends Model
{
public $login;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['login', 'password'], 'required'],
['login', 'exist', 'targetClass' => '\app\models\UserModel', 'message' => Yii::t('app', 'A specified login does not exist')],
['rememberMe', 'boolean'],
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, Yii::t('app', 'Incorrect password'));
}
}
}
/**
* Logs in a user using the provided username and password.
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = UserModel::findByLogin($this->login);
}
return $this->_user;
}
}
| Per1phery/wholetthedogout | models/LoginForm.php | PHP | bsd-3-clause | 1,861 |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#if SK_SUPPORT_GPU
#include "GrReducedClip.h"
#endif
#include "SkClipStack.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRect.h"
#include "SkRegion.h"
static void test_assign_and_comparison(skiatest::Reporter* reporter) {
SkClipStack s;
bool doAA = false;
REPORTER_ASSERT(reporter, 0 == s.getSaveCount());
// Build up a clip stack with a path, an empty clip, and a rect.
s.save();
REPORTER_ASSERT(reporter, 1 == s.getSaveCount());
SkPath p;
p.moveTo(5, 6);
p.lineTo(7, 8);
p.lineTo(5, 9);
p.close();
s.clipDevPath(p, SkRegion::kIntersect_Op, doAA);
s.save();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
SkRect r = SkRect::MakeLTRB(1, 2, 3, 4);
s.clipDevRect(r, SkRegion::kIntersect_Op, doAA);
r = SkRect::MakeLTRB(10, 11, 12, 13);
s.clipDevRect(r, SkRegion::kIntersect_Op, doAA);
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(14, 15, 16, 17);
s.clipDevRect(r, SkRegion::kUnion_Op, doAA);
// Test that assignment works.
SkClipStack copy = s;
REPORTER_ASSERT(reporter, s == copy);
// Test that different save levels triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
REPORTER_ASSERT(reporter, s != copy);
// Test that an equal, but not copied version is equal.
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(14, 15, 16, 17);
s.clipDevRect(r, SkRegion::kUnion_Op, doAA);
REPORTER_ASSERT(reporter, s == copy);
// Test that a different op on one level triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(14, 15, 16, 17);
s.clipDevRect(r, SkRegion::kIntersect_Op, doAA);
REPORTER_ASSERT(reporter, s != copy);
// Test that different state (clip type) triggers not equal.
// NO LONGER VALID: if a path contains only a rect, we turn
// it into a bare rect for performance reasons (working
// around Chromium/JavaScript bad pattern).
/*
s.restore();
s.save();
SkPath rp;
rp.addRect(r);
s.clipDevPath(rp, SkRegion::kUnion_Op, doAA);
REPORTER_ASSERT(reporter, s != copy);
*/
// Test that different rects triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
s.save();
REPORTER_ASSERT(reporter, 3 == s.getSaveCount());
r = SkRect::MakeLTRB(24, 25, 26, 27);
s.clipDevRect(r, SkRegion::kUnion_Op, doAA);
REPORTER_ASSERT(reporter, s != copy);
// Sanity check
s.restore();
REPORTER_ASSERT(reporter, 2 == s.getSaveCount());
copy.restore();
REPORTER_ASSERT(reporter, 2 == copy.getSaveCount());
REPORTER_ASSERT(reporter, s == copy);
s.restore();
REPORTER_ASSERT(reporter, 1 == s.getSaveCount());
copy.restore();
REPORTER_ASSERT(reporter, 1 == copy.getSaveCount());
REPORTER_ASSERT(reporter, s == copy);
// Test that different paths triggers not equal.
s.restore();
REPORTER_ASSERT(reporter, 0 == s.getSaveCount());
s.save();
REPORTER_ASSERT(reporter, 1 == s.getSaveCount());
p.addRect(r);
s.clipDevPath(p, SkRegion::kIntersect_Op, doAA);
REPORTER_ASSERT(reporter, s != copy);
}
static void assert_count(skiatest::Reporter* reporter, const SkClipStack& stack,
int count) {
SkClipStack::B2TIter iter(stack);
int counter = 0;
while (iter.next()) {
counter += 1;
}
REPORTER_ASSERT(reporter, count == counter);
}
// Exercise the SkClipStack's bottom to top and bidirectional iterators
// (including the skipToTopmost functionality)
static void test_iterators(skiatest::Reporter* reporter) {
SkClipStack stack;
static const SkRect gRects[] = {
{ 0, 0, 40, 40 },
{ 60, 0, 100, 40 },
{ 0, 60, 40, 100 },
{ 60, 60, 100, 100 }
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) {
// the union op will prevent these from being fused together
stack.clipDevRect(gRects[i], SkRegion::kUnion_Op, false);
}
assert_count(reporter, stack, 4);
// bottom to top iteration
{
const SkClipStack::Element* element = NULL;
SkClipStack::B2TIter iter(stack);
int i;
for (i = 0, element = iter.next(); element; ++i, element = iter.next()) {
REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType());
REPORTER_ASSERT(reporter, element->getRect() == gRects[i]);
}
SkASSERT(i == 4);
}
// top to bottom iteration
{
const SkClipStack::Element* element = NULL;
SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart);
int i;
for (i = 3, element = iter.prev(); element; --i, element = iter.prev()) {
REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType());
REPORTER_ASSERT(reporter, element->getRect() == gRects[i]);
}
SkASSERT(i == -1);
}
// skipToTopmost
{
const SkClipStack::Element* element = NULL;
SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart);
element = iter.skipToTopmost(SkRegion::kUnion_Op);
REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType());
REPORTER_ASSERT(reporter, element->getRect() == gRects[3]);
}
}
// Exercise the SkClipStack's getConservativeBounds computation
static void test_bounds(skiatest::Reporter* reporter, bool useRects) {
static const int gNumCases = 20;
static const SkRect gAnswerRectsBW[gNumCases] = {
// A op B
{ 40, 40, 50, 50 },
{ 10, 10, 50, 50 },
{ 10, 10, 80, 80 },
{ 10, 10, 80, 80 },
{ 40, 40, 80, 80 },
// invA op B
{ 40, 40, 80, 80 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
{ 40, 40, 50, 50 },
// A op invB
{ 10, 10, 50, 50 },
{ 40, 40, 50, 50 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
{ 0, 0, 100, 100 },
// invA op invB
{ 0, 0, 100, 100 },
{ 40, 40, 80, 80 },
{ 0, 0, 100, 100 },
{ 10, 10, 80, 80 },
{ 10, 10, 50, 50 },
};
static const SkRegion::Op gOps[] = {
SkRegion::kIntersect_Op,
SkRegion::kDifference_Op,
SkRegion::kUnion_Op,
SkRegion::kXOR_Op,
SkRegion::kReverseDifference_Op
};
SkRect rectA, rectB;
rectA.iset(10, 10, 50, 50);
rectB.iset(40, 40, 80, 80);
SkPath clipA, clipB;
clipA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5));
clipB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5));
SkClipStack stack;
SkRect devClipBound;
bool isIntersectionOfRects = false;
int testCase = 0;
int numBitTests = useRects ? 1 : 4;
for (int invBits = 0; invBits < numBitTests; ++invBits) {
for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) {
stack.save();
bool doInvA = SkToBool(invBits & 1);
bool doInvB = SkToBool(invBits & 2);
clipA.setFillType(doInvA ? SkPath::kInverseEvenOdd_FillType :
SkPath::kEvenOdd_FillType);
clipB.setFillType(doInvB ? SkPath::kInverseEvenOdd_FillType :
SkPath::kEvenOdd_FillType);
if (useRects) {
stack.clipDevRect(rectA, SkRegion::kIntersect_Op, false);
stack.clipDevRect(rectB, gOps[op], false);
} else {
stack.clipDevPath(clipA, SkRegion::kIntersect_Op, false);
stack.clipDevPath(clipB, gOps[op], false);
}
REPORTER_ASSERT(reporter, !stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID());
stack.getConservativeBounds(0, 0, 100, 100, &devClipBound,
&isIntersectionOfRects);
if (useRects) {
REPORTER_ASSERT(reporter, isIntersectionOfRects ==
(gOps[op] == SkRegion::kIntersect_Op));
} else {
REPORTER_ASSERT(reporter, !isIntersectionOfRects);
}
SkASSERT(testCase < gNumCases);
REPORTER_ASSERT(reporter, devClipBound == gAnswerRectsBW[testCase]);
++testCase;
stack.restore();
}
}
}
// Test out 'isWideOpen' entry point
static void test_isWideOpen(skiatest::Reporter* reporter) {
{
// Empty stack is wide open. Wide open stack means that gen id is wide open.
SkClipStack stack;
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
SkRect rectA, rectB;
rectA.iset(10, 10, 40, 40);
rectB.iset(50, 50, 80, 80);
// Stack should initially be wide open
{
SkClipStack stack;
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out case where the user specifies a union that includes everything
{
SkClipStack stack;
SkPath clipA, clipB;
clipA.addRoundRect(rectA, SkIntToScalar(5), SkIntToScalar(5));
clipA.setFillType(SkPath::kInverseEvenOdd_FillType);
clipB.addRoundRect(rectB, SkIntToScalar(5), SkIntToScalar(5));
clipB.setFillType(SkPath::kInverseEvenOdd_FillType);
stack.clipDevPath(clipA, SkRegion::kReplace_Op, false);
stack.clipDevPath(clipB, SkRegion::kUnion_Op, false);
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out union w/ a wide open clip
{
SkClipStack stack;
stack.clipDevRect(rectA, SkRegion::kUnion_Op, false);
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out empty difference from a wide open clip
{
SkClipStack stack;
SkRect emptyRect;
emptyRect.setEmpty();
stack.clipDevRect(emptyRect, SkRegion::kDifference_Op, false);
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
// Test out return to wide open
{
SkClipStack stack;
stack.save();
stack.clipDevRect(rectA, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, !stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID != stack.getTopmostGenID());
stack.restore();
REPORTER_ASSERT(reporter, stack.isWideOpen());
REPORTER_ASSERT(reporter, SkClipStack::kWideOpenGenID == stack.getTopmostGenID());
}
}
static int count(const SkClipStack& stack) {
SkClipStack::Iter iter(stack, SkClipStack::Iter::kTop_IterStart);
const SkClipStack::Element* element = NULL;
int count = 0;
for (element = iter.prev(); element; element = iter.prev(), ++count) {
;
}
return count;
}
static void test_rect_inverse_fill(skiatest::Reporter* reporter) {
// non-intersecting rectangles
SkRect rect = SkRect::MakeLTRB(0, 0, 10, 10);
SkPath path;
path.addRect(rect);
path.toggleInverseFillType();
SkClipStack stack;
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
SkRect bounds;
SkClipStack::BoundsType boundsType;
stack.getBounds(&bounds, &boundsType);
REPORTER_ASSERT(reporter, SkClipStack::kInsideOut_BoundsType == boundsType);
REPORTER_ASSERT(reporter, bounds == rect);
}
static void test_rect_replace(skiatest::Reporter* reporter) {
SkRect rect = SkRect::MakeWH(100, 100);
SkRect rect2 = SkRect::MakeXYWH(50, 50, 100, 100);
SkRect bound;
SkClipStack::BoundsType type;
bool isIntersectionOfRects;
// Adding a new rect with the replace operator should not increase
// the stack depth. BW replacing BW.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Adding a new rect with the replace operator should not increase
// the stack depth. AA replacing AA.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipDevRect(rect, SkRegion::kReplace_Op, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipDevRect(rect, SkRegion::kReplace_Op, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Adding a new rect with the replace operator should not increase
// the stack depth. BW replacing AA replacing BW.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipDevRect(rect, SkRegion::kReplace_Op, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Make sure replace clip rects don't collapse too much.
{
SkClipStack stack;
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
stack.clipDevRect(rect2, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.save();
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, bound == rect);
stack.restore();
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.save();
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.restore();
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.save();
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
stack.clipDevRect(rect2, SkRegion::kIntersect_Op, false);
stack.clipDevRect(rect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.restore();
REPORTER_ASSERT(reporter, 1 == count(stack));
}
}
// Simplified path-based version of test_rect_replace.
static void test_path_replace(skiatest::Reporter* reporter) {
SkRect rect = SkRect::MakeWH(100, 100);
SkPath path;
path.addCircle(50, 50, 50);
// Replace operation doesn't grow the stack.
{
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == count(stack));
stack.clipDevPath(path, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipDevPath(path, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
// Replacing rect with path.
{
SkClipStack stack;
stack.clipDevRect(rect, SkRegion::kReplace_Op, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.clipDevPath(path, SkRegion::kReplace_Op, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
}
}
// Test out SkClipStack's merging of rect clips. In particular exercise
// merging of aa vs. bw rects.
static void test_rect_merging(skiatest::Reporter* reporter) {
SkRect overlapLeft = SkRect::MakeLTRB(10, 10, 50, 50);
SkRect overlapRight = SkRect::MakeLTRB(40, 40, 80, 80);
SkRect nestedParent = SkRect::MakeLTRB(10, 10, 90, 90);
SkRect nestedChild = SkRect::MakeLTRB(40, 40, 60, 60);
SkRect bound;
SkClipStack::BoundsType type;
bool isIntersectionOfRects;
// all bw overlapping - should merge
{
SkClipStack stack;
stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, false);
stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// all aa overlapping - should merge
{
SkClipStack stack;
stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, true);
stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// mixed overlapping - should _not_ merge
{
SkClipStack stack;
stack.clipDevRect(overlapLeft, SkRegion::kReplace_Op, true);
stack.clipDevRect(overlapRight, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, !isIntersectionOfRects);
}
// mixed nested (bw inside aa) - should merge
{
SkClipStack stack;
stack.clipDevRect(nestedParent, SkRegion::kReplace_Op, true);
stack.clipDevRect(nestedChild, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// mixed nested (aa inside bw) - should merge
{
SkClipStack stack;
stack.clipDevRect(nestedParent, SkRegion::kReplace_Op, false);
stack.clipDevRect(nestedChild, SkRegion::kIntersect_Op, true);
REPORTER_ASSERT(reporter, 1 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, isIntersectionOfRects);
}
// reverse nested (aa inside bw) - should _not_ merge
{
SkClipStack stack;
stack.clipDevRect(nestedChild, SkRegion::kReplace_Op, false);
stack.clipDevRect(nestedParent, SkRegion::kIntersect_Op, true);
REPORTER_ASSERT(reporter, 2 == count(stack));
stack.getBounds(&bound, &type, &isIntersectionOfRects);
REPORTER_ASSERT(reporter, !isIntersectionOfRects);
}
}
static void test_quickContains(skiatest::Reporter* reporter) {
SkRect testRect = SkRect::MakeLTRB(10, 10, 40, 40);
SkRect insideRect = SkRect::MakeLTRB(20, 20, 30, 30);
SkRect intersectingRect = SkRect::MakeLTRB(25, 25, 50, 50);
SkRect outsideRect = SkRect::MakeLTRB(0, 0, 50, 50);
SkRect nonIntersectingRect = SkRect::MakeLTRB(100, 100, 110, 110);
SkPath insideCircle;
insideCircle.addCircle(25, 25, 5);
SkPath intersectingCircle;
intersectingCircle.addCircle(25, 40, 10);
SkPath outsideCircle;
outsideCircle.addCircle(25, 25, 50);
SkPath nonIntersectingCircle;
nonIntersectingCircle.addCircle(100, 100, 5);
{
SkClipStack stack;
stack.clipDevRect(outsideRect, SkRegion::kDifference_Op, false);
// return false because quickContains currently does not care for kDifference_Op
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Replace Op tests
{
SkClipStack stack;
stack.clipDevRect(outsideRect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false);
stack.save(); // To prevent in-place substitution by replace OP
stack.clipDevRect(outsideRect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
stack.restore();
}
{
SkClipStack stack;
stack.clipDevRect(outsideRect, SkRegion::kIntersect_Op, false);
stack.save(); // To prevent in-place substitution by replace OP
stack.clipDevRect(insideRect, SkRegion::kReplace_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
stack.restore();
}
// Verify proper traversal of multi-element clip
{
SkClipStack stack;
stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false);
// Use a path for second clip to prevent in-place intersection
stack.clipDevPath(outsideCircle, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Intersect Op tests with rectangles
{
SkClipStack stack;
stack.clipDevRect(outsideRect, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipDevRect(insideRect, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipDevRect(intersectingRect, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipDevRect(nonIntersectingRect, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Intersect Op tests with circle paths
{
SkClipStack stack;
stack.clipDevPath(outsideCircle, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipDevPath(insideCircle, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipDevPath(intersectingCircle, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
stack.clipDevPath(nonIntersectingCircle, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
// Intersect Op tests with inverse filled rectangles
{
SkClipStack stack;
SkPath path;
path.addRect(outsideRect);
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path;
path.addRect(insideRect);
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path;
path.addRect(intersectingRect);
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path;
path.addRect(nonIntersectingRect);
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
// Intersect Op tests with inverse filled circles
{
SkClipStack stack;
SkPath path = outsideCircle;
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path = insideCircle;
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path = intersectingCircle;
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, false == stack.quickContains(testRect));
}
{
SkClipStack stack;
SkPath path = nonIntersectingCircle;
path.toggleInverseFillType();
stack.clipDevPath(path, SkRegion::kIntersect_Op, false);
REPORTER_ASSERT(reporter, true == stack.quickContains(testRect));
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
#if SK_SUPPORT_GPU
// Functions that add a shape to the clip stack. The shape is computed from a rectangle.
// AA is always disabled since the clip stack reducer can cause changes in aa rasterization of the
// stack. A fractional edge repeated in different elements may be rasterized fewer times using the
// reduced stack.
typedef void (*AddElementFunc) (const SkRect& rect,
bool invert,
SkRegion::Op op,
SkClipStack* stack);
static void add_round_rect(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) {
SkPath path;
SkScalar rx = rect.width() / 10;
SkScalar ry = rect.height() / 20;
path.addRoundRect(rect, rx, ry);
if (invert) {
path.setFillType(SkPath::kInverseWinding_FillType);
}
stack->clipDevPath(path, op, false);
};
static void add_rect(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) {
if (invert) {
SkPath path;
path.addRect(rect);
path.setFillType(SkPath::kInverseWinding_FillType);
stack->clipDevPath(path, op, false);
} else {
stack->clipDevRect(rect, op, false);
}
};
static void add_oval(const SkRect& rect, bool invert, SkRegion::Op op, SkClipStack* stack) {
SkPath path;
path.addOval(rect);
if (invert) {
path.setFillType(SkPath::kInverseWinding_FillType);
}
stack->clipDevPath(path, op, false);
};
static void add_elem_to_stack(const SkClipStack::Element& element, SkClipStack* stack) {
switch (element.getType()) {
case SkClipStack::Element::kRect_Type:
stack->clipDevRect(element.getRect(), element.getOp(), element.isAA());
break;
case SkClipStack::Element::kPath_Type:
stack->clipDevPath(element.getPath(), element.getOp(), element.isAA());
break;
case SkClipStack::Element::kEmpty_Type:
SkDEBUGFAIL("Why did the reducer produce an explicit empty.");
stack->clipEmpty();
break;
}
}
static void add_elem_to_region(const SkClipStack::Element& element,
const SkIRect& bounds,
SkRegion* region) {
SkRegion elemRegion;
SkRegion boundsRgn(bounds);
switch (element.getType()) {
case SkClipStack::Element::kRect_Type: {
SkPath path;
path.addRect(element.getRect());
elemRegion.setPath(path, boundsRgn);
break;
}
case SkClipStack::Element::kPath_Type:
elemRegion.setPath(element.getPath(), boundsRgn);
break;
case SkClipStack::Element::kEmpty_Type:
//
region->setEmpty();
return;
}
region->op(elemRegion, element.getOp());
}
static void test_reduced_clip_stack(skiatest::Reporter* reporter) {
// We construct random clip stacks, reduce them, and then rasterize both versions to verify that
// they are equal.
// All the clip elements will be contained within these bounds.
static const SkRect kBounds = SkRect::MakeWH(100, 100);
enum {
kNumTests = 200,
kMinElemsPerTest = 1,
kMaxElemsPerTest = 50,
};
// min/max size of a clip element as a fraction of kBounds.
static const SkScalar kMinElemSizeFrac = SK_Scalar1 / 5;
static const SkScalar kMaxElemSizeFrac = SK_Scalar1;
static const SkRegion::Op kOps[] = {
SkRegion::kDifference_Op,
SkRegion::kIntersect_Op,
SkRegion::kUnion_Op,
SkRegion::kXOR_Op,
SkRegion::kReverseDifference_Op,
SkRegion::kReplace_Op,
};
// Replace operations short-circuit the optimizer. We want to make sure that we test this code
// path a little bit but we don't want it to prevent us from testing many longer traversals in
// the optimizer.
static const int kReplaceDiv = 4 * kMaxElemsPerTest;
// We want to test inverse fills. However, they are quite rare in practice so don't over do it.
static const SkScalar kFractionInverted = SK_Scalar1 / kMaxElemsPerTest;
static const AddElementFunc kElementFuncs[] = {
add_rect,
add_round_rect,
add_oval,
};
SkRandom r;
for (int i = 0; i < kNumTests; ++i) {
// Randomly generate a clip stack.
SkClipStack stack;
int numElems = r.nextRangeU(kMinElemsPerTest, kMaxElemsPerTest);
for (int e = 0; e < numElems; ++e) {
SkRegion::Op op = kOps[r.nextULessThan(SK_ARRAY_COUNT(kOps))];
if (op == SkRegion::kReplace_Op) {
if (r.nextU() % kReplaceDiv) {
--e;
continue;
}
}
// saves can change the clip stack behavior when an element is added.
bool doSave = r.nextBool();
SkSize size = SkSize::Make(
SkScalarFloorToScalar(SkScalarMul(kBounds.width(), r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac))),
SkScalarFloorToScalar(SkScalarMul(kBounds.height(), r.nextRangeScalar(kMinElemSizeFrac, kMaxElemSizeFrac))));
SkPoint xy = {SkScalarFloorToScalar(r.nextRangeScalar(kBounds.fLeft, kBounds.fRight - size.fWidth)),
SkScalarFloorToScalar(r.nextRangeScalar(kBounds.fTop, kBounds.fBottom - size.fHeight))};
SkRect rect = SkRect::MakeXYWH(xy.fX, xy.fY, size.fWidth, size.fHeight);
bool invert = r.nextBiasedBool(kFractionInverted);
kElementFuncs[r.nextULessThan(SK_ARRAY_COUNT(kElementFuncs))](rect, invert, op, &stack);
if (doSave) {
stack.save();
}
}
SkRect inflatedBounds = kBounds;
inflatedBounds.outset(kBounds.width() / 2, kBounds.height() / 2);
SkIRect inflatedIBounds;
inflatedBounds.roundOut(&inflatedIBounds);
typedef GrReducedClip::ElementList ElementList;
// Get the reduced version of the stack.
ElementList reducedClips;
int32_t reducedGenID;
GrReducedClip::InitialState initial;
SkIRect tBounds(inflatedIBounds);
SkIRect* tightBounds = r.nextBool() ? &tBounds : NULL;
GrReducedClip::ReduceClipStack(stack,
inflatedIBounds,
&reducedClips,
&reducedGenID,
&initial,
tightBounds);
REPORTER_ASSERT(reporter, SkClipStack::kInvalidGenID != reducedGenID);
// Build a new clip stack based on the reduced clip elements
SkClipStack reducedStack;
if (GrReducedClip::kAllOut_InitialState == initial) {
// whether the result is bounded or not, the whole plane should start outside the clip.
reducedStack.clipEmpty();
}
for (ElementList::Iter iter = reducedClips.headIter(); NULL != iter.get(); iter.next()) {
add_elem_to_stack(*iter.get(), &reducedStack);
}
// GrReducedClipStack assumes that the final result is clipped to the returned bounds
if (NULL != tightBounds) {
reducedStack.clipDevRect(*tightBounds, SkRegion::kIntersect_Op);
}
// convert both the original stack and reduced stack to SkRegions and see if they're equal
SkRegion region;
SkRegion reducedRegion;
region.setRect(inflatedIBounds);
const SkClipStack::Element* element;
SkClipStack::Iter iter(stack, SkClipStack::Iter::kBottom_IterStart);
while ((element = iter.next())) {
add_elem_to_region(*element, inflatedIBounds, ®ion);
}
reducedRegion.setRect(inflatedIBounds);
iter.reset(reducedStack, SkClipStack::Iter::kBottom_IterStart);
while ((element = iter.next())) {
add_elem_to_region(*element, inflatedIBounds, &reducedRegion);
}
REPORTER_ASSERT(reporter, region == reducedRegion);
}
}
#if defined(WIN32)
#define SUPPRESS_VISIBILITY_WARNING
#else
#define SUPPRESS_VISIBILITY_WARNING __attribute__((visibility("hidden")))
#endif
static void test_reduced_clip_stack_genid(skiatest::Reporter* reporter) {
{
SkClipStack stack;
stack.clipDevRect(SkRect::MakeXYWH(0, 0, 100, 100), SkRegion::kReplace_Op, true);
stack.clipDevRect(SkRect::MakeXYWH(0, 0, SkScalar(50.3), SkScalar(50.3)), SkRegion::kReplace_Op, true);
SkIRect inflatedIBounds = SkIRect::MakeXYWH(0, 0, 100, 100);
GrReducedClip::ElementList reducedClips;
int32_t reducedGenID;
GrReducedClip::InitialState initial;
SkIRect tightBounds;
GrReducedClip::ReduceClipStack(stack,
inflatedIBounds,
&reducedClips,
&reducedGenID,
&initial,
&tightBounds);
REPORTER_ASSERT(reporter, reducedClips.count() == 1);
// Clips will be cached based on the generation id. Make sure the gen id is valid.
REPORTER_ASSERT(reporter, SkClipStack::kInvalidGenID != reducedGenID);
}
{
SkClipStack stack;
// Create a clip with following 25.3, 25.3 boxes which are 25 apart:
// A B
// C D
stack.clipDevRect(SkRect::MakeXYWH(0, 0, SkScalar(25.3), SkScalar(25.3)), SkRegion::kReplace_Op, true);
int32_t genIDA = stack.getTopmostGenID();
stack.clipDevRect(SkRect::MakeXYWH(50, 0, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true);
int32_t genIDB = stack.getTopmostGenID();
stack.clipDevRect(SkRect::MakeXYWH(0, 50, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true);
int32_t genIDC = stack.getTopmostGenID();
stack.clipDevRect(SkRect::MakeXYWH(50, 50, SkScalar(25.3), SkScalar(25.3)), SkRegion::kUnion_Op, true);
int32_t genIDD = stack.getTopmostGenID();
#define XYWH SkIRect::MakeXYWH
SkIRect unused;
unused.setEmpty();
SkIRect stackBounds = XYWH(0, 0, 76, 76);
// The base test is to test each rect in two ways:
// 1) The box dimensions. (Should reduce to "all in", no elements).
// 2) A bit over the box dimensions.
// In the case 2, test that the generation id is what is expected.
// The rects are of fractional size so that case 2 never gets optimized to an empty element
// list.
// Not passing in tighter bounds is tested for consistency.
static const struct SUPPRESS_VISIBILITY_WARNING {
SkIRect testBounds;
int reducedClipCount;
int32_t reducedGenID;
GrReducedClip::InitialState initialState;
SkIRect tighterBounds; // If this is empty, the query will not pass tighter bounds
// parameter.
} testCases[] = {
// Rect A.
{ XYWH(0, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(0, 0, 25, 25) },
{ XYWH(0, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused },
{ XYWH(0, 0, 27, 27), 1, genIDA, GrReducedClip::kAllOut_InitialState, XYWH(0, 0, 27, 27)},
{ XYWH(0, 0, 27, 27), 1, genIDA, GrReducedClip::kAllOut_InitialState, unused },
// Rect B.
{ XYWH(50, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(50, 0, 25, 25) },
{ XYWH(50, 0, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused },
{ XYWH(50, 0, 27, 27), 1, genIDB, GrReducedClip::kAllOut_InitialState, XYWH(50, 0, 26, 27) },
{ XYWH(50, 0, 27, 27), 1, genIDB, GrReducedClip::kAllOut_InitialState, unused },
// Rect C.
{ XYWH(0, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(0, 50, 25, 25) },
{ XYWH(0, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused },
{ XYWH(0, 50, 27, 27), 1, genIDC, GrReducedClip::kAllOut_InitialState, XYWH(0, 50, 27, 26) },
{ XYWH(0, 50, 27, 27), 1, genIDC, GrReducedClip::kAllOut_InitialState, unused },
// Rect D.
{ XYWH(50, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, unused },
{ XYWH(50, 50, 25, 25), 0, SkClipStack::kWideOpenGenID, GrReducedClip::kAllIn_InitialState, XYWH(50, 50, 25, 25)},
{ XYWH(50, 50, 27, 27), 1, genIDD, GrReducedClip::kAllOut_InitialState, unused },
{ XYWH(50, 50, 27, 27), 1, genIDD, GrReducedClip::kAllOut_InitialState, XYWH(50, 50, 26, 26)},
// Other tests:
{ XYWH(0, 0, 100, 100), 4, genIDD, GrReducedClip::kAllOut_InitialState, unused },
{ XYWH(0, 0, 100, 100), 4, genIDD, GrReducedClip::kAllOut_InitialState, stackBounds },
// Rect in the middle, touches none.
{ XYWH(26, 26, 24, 24), 0, SkClipStack::kEmptyGenID, GrReducedClip::kAllOut_InitialState, unused },
{ XYWH(26, 26, 24, 24), 0, SkClipStack::kEmptyGenID, GrReducedClip::kAllOut_InitialState, XYWH(26, 26, 24, 24) },
// Rect in the middle, touches all the rects. GenID is the last rect.
{ XYWH(24, 24, 27, 27), 4, genIDD, GrReducedClip::kAllOut_InitialState, unused },
{ XYWH(24, 24, 27, 27), 4, genIDD, GrReducedClip::kAllOut_InitialState, XYWH(24, 24, 27, 27) },
};
#undef XYWH
for (size_t i = 0; i < SK_ARRAY_COUNT(testCases); ++i) {
GrReducedClip::ElementList reducedClips;
int32_t reducedGenID;
GrReducedClip::InitialState initial;
SkIRect tightBounds;
GrReducedClip::ReduceClipStack(stack,
testCases[i].testBounds,
&reducedClips,
&reducedGenID,
&initial,
testCases[i].tighterBounds.isEmpty() ? NULL : &tightBounds);
REPORTER_ASSERT(reporter, reducedClips.count() == testCases[i].reducedClipCount);
SkASSERT(reducedClips.count() == testCases[i].reducedClipCount);
REPORTER_ASSERT(reporter, reducedGenID == testCases[i].reducedGenID);
SkASSERT(reducedGenID == testCases[i].reducedGenID);
REPORTER_ASSERT(reporter, initial == testCases[i].initialState);
SkASSERT(initial == testCases[i].initialState);
if (!testCases[i].tighterBounds.isEmpty()) {
REPORTER_ASSERT(reporter, tightBounds == testCases[i].tighterBounds);
SkASSERT(tightBounds == testCases[i].tighterBounds);
}
}
}
}
static void test_reduced_clip_stack_no_aa_crash(skiatest::Reporter* reporter) {
SkClipStack stack;
stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 100, 100), SkRegion::kReplace_Op);
stack.clipDevRect(SkIRect::MakeXYWH(0, 0, 50, 50), SkRegion::kReplace_Op);
SkIRect inflatedIBounds = SkIRect::MakeXYWH(0, 0, 100, 100);
GrReducedClip::ElementList reducedClips;
int32_t reducedGenID;
GrReducedClip::InitialState initial;
SkIRect tightBounds;
// At the time, this would crash.
GrReducedClip::ReduceClipStack(stack,
inflatedIBounds,
&reducedClips,
&reducedGenID,
&initial,
&tightBounds);
REPORTER_ASSERT(reporter, 0 == reducedClips.count());
}
#endif
DEF_TEST(ClipStack, reporter) {
SkClipStack stack;
REPORTER_ASSERT(reporter, 0 == stack.getSaveCount());
assert_count(reporter, stack, 0);
static const SkIRect gRects[] = {
{ 0, 0, 100, 100 },
{ 25, 25, 125, 125 },
{ 0, 0, 1000, 1000 },
{ 0, 0, 75, 75 }
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gRects); i++) {
stack.clipDevRect(gRects[i], SkRegion::kIntersect_Op);
}
// all of the above rects should have been intersected, leaving only 1 rect
SkClipStack::B2TIter iter(stack);
const SkClipStack::Element* element = iter.next();
SkRect answer;
answer.iset(25, 25, 75, 75);
REPORTER_ASSERT(reporter, NULL != element);
REPORTER_ASSERT(reporter, SkClipStack::Element::kRect_Type == element->getType());
REPORTER_ASSERT(reporter, SkRegion::kIntersect_Op == element->getOp());
REPORTER_ASSERT(reporter, element->getRect() == answer);
// now check that we only had one in our iterator
REPORTER_ASSERT(reporter, !iter.next());
stack.reset();
REPORTER_ASSERT(reporter, 0 == stack.getSaveCount());
assert_count(reporter, stack, 0);
test_assign_and_comparison(reporter);
test_iterators(reporter);
test_bounds(reporter, true); // once with rects
test_bounds(reporter, false); // once with paths
test_isWideOpen(reporter);
test_rect_merging(reporter);
test_rect_replace(reporter);
test_rect_inverse_fill(reporter);
test_path_replace(reporter);
test_quickContains(reporter);
#if SK_SUPPORT_GPU
test_reduced_clip_stack(reporter);
test_reduced_clip_stack_genid(reporter);
test_reduced_clip_stack_no_aa_crash(reporter);
#endif
}
| trevorlinton/skia | tests/ClipStackTest.cpp | C++ | bsd-3-clause | 42,846 |
<?php
namespace app\models;
use Yii;
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
/**
* This is the model class for table "tbl_six_step".
*
* @property integer $six_step_id
* @property integer $atlet_id
* @property string $stage
* @property string $status
*/
class SixStepBiomekanik extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_six_step_biomekanik';
}
public function behaviors()
{
return [
'bedezign\yii2\audit\AuditTrailBehavior',
[
'class' => \yii\behaviors\BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
[
'class' => \yii\behaviors\TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => 'updated',
'value' => new \yii\db\Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['atlet_id', 'stage', 'status', 'tarikh'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
[['atlet_id', 'kategori_atlet', 'sukan', 'acara'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
[['stage', 'status'], 'string', 'max' => 30, 'tooLong' => GeneralMessage::yii_validation_string_max],
[['stage', 'status'], function ($attribute, $params) {
if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
$this->addError($attribute, GeneralMessage::yii_validation_xss);
}
}],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'six_step_id' => GeneralLabel::six_step_id,
'atlet_id' => GeneralLabel::atlet_id,
'kategori_atlet' => GeneralLabel::kategori_atlet,
'sukan' => GeneralLabel::sukan,
'acara' => GeneralLabel::acara,
'stage' => GeneralLabel::stage,
'status' => GeneralLabel::status,
'tarikh' => GeneralLabel::tarikh,
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getAtlet(){
return $this->hasOne(Atlet::className(), ['atlet_id' => 'atlet_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRefSixstepBiomekanikStage(){
return $this->hasOne(RefSixstepBiomekanikStage::className(), ['id' => 'stage']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRefSixstepBiomekanikStatus(){
return $this->hasOne(RefSixstepBiomekanikStatus::className(), ['id' => 'status']);
}
}
| hung101/kbs | frontend/models/SixStepBiomekanik.php | PHP | bsd-3-clause | 2,953 |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
from qiime2.plugin import SemanticType
from ..plugin_setup import plugin
from . import AlphaDiversityDirectoryFormat
SampleData = SemanticType('SampleData', field_names='type')
AlphaDiversity = SemanticType('AlphaDiversity',
variant_of=SampleData.field['type'])
plugin.register_semantic_types(SampleData, AlphaDiversity)
plugin.register_semantic_type_to_format(
SampleData[AlphaDiversity],
artifact_format=AlphaDiversityDirectoryFormat
)
| qiime2/q2-types | q2_types/sample_data/_type.py | Python | bsd-3-clause | 832 |
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Serialization;
using JetBat.Client.Entities;
using JetBat.Client.Metadata.Abstract;
using JetBat.Client.Metadata.Definitions;
using JetBat.Client.Metadata.Misc;
using JetBat.Client.Metadata.Simple;
namespace JetBat.Client.SqlServer.Concrete
{
public class PlainObjectListViewDefinitionSqlLoader : IObjectDefinitionSqlLoader
{
private const int PlainObjectListViewObjectTypeID = 2;
private readonly string _connectionString;
private readonly bool _enableCaching;
public PlainObjectListViewDefinitionSqlLoader(string connectionString, bool enableCaching)
{
_connectionString = connectionString;
_enableCaching = enableCaching;
}
#region IObjectDefinitionSqlLoader Members
public Type TargetObjectType
{
get { return typeof(PlainObjectListViewDefinition); }
}
public int TargetObjectID
{
get { return PlainObjectListViewObjectTypeID; }
}
public ObjectDefinition LoadImmutable(string objectNamespace, string objectName)
{
return new PlainObjectListViewDefinition((PlainObjectListView)Load(objectNamespace, objectName));
}
#endregion
public BusinessObject Load(string objectNamespace, string objectName)
{
#region Load from cache
string cacheDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StaticHelper.MetadataCacheDirectoryName + @"\PlainObjectListView");
string cacheFileName = string.Format(@"{0}\{1}.{2}.xml", cacheDirectory, objectNamespace, objectName);
if (_enableCaching)
{
if (File.Exists(cacheFileName))
{
XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView));
using (FileStream stream = new FileStream(cacheFileName, FileMode.Open, FileAccess.Read))
return (PlainObjectListView)serializer.Deserialize(stream);
}
}
#endregion
string uiListCaption;
string basicObjectNamespace;
string basicObjectName;
string objectActionNameLoadList;
string objectMethodNameLoadList;
string namespaceName;
string name;
int objectType;
string friendlyName;
string description;
NamedObjectCollection<ObjectAttribute> attributes;
NamedObjectCollection<ObjectComplexAttribute> complexAttributes;
NamedObjectCollection<ObjectAction> actions;
NamedObjectCollection<ObjectMethod> methods;
using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
{
sqlConnection.Open();
SqlCommand command = new SqlCommand("MetadataEngine_LoadPlainObjectListViewDescriptor", sqlConnection) { CommandType = CommandType.StoredProcedure };
command.Parameters.AddWithValue("@Namespace", objectNamespace);
command.Parameters.AddWithValue("@Name", objectName);
SqlDataReader reader = command.ExecuteReader();
if (reader == null) throw new NullReferenceException("DataReader is null while must not be.");
using (reader)
{
reader.Read();
uiListCaption = reader["UIListCaption"].ToString();
basicObjectNamespace = Convert.ToString(reader["EntityNamespaceName"]);
basicObjectName = Convert.ToString(reader["EntityName"]);
objectActionNameLoadList = reader["ObjectActionNameLoadList"].Equals(DBNull.Value)
? ""
: Convert.ToString(reader["ObjectActionNameLoadList"]);
objectMethodNameLoadList = reader["ObjectMethodNameLoadList"].Equals(DBNull.Value)
? ""
: Convert.ToString(reader["ObjectMethodNameLoadList"]);
objectType = Convert.ToInt32(reader["ObjectTypeID"]);
namespaceName = Convert.ToString(reader["NamespaceName"]);
name = Convert.ToString(reader["Name"]);
friendlyName = Convert.ToString(reader["FriendlyName"]);
description = Convert.ToString(reader["Description"]);
reader.NextResult();
attributes = StaticHelper.getAttributesFormReader(reader);
reader.NextResult();
complexAttributes = StaticHelper.getComplexAttributesFromReader(reader);
reader.NextResult();
StaticHelper.getComplexAttributeAttributePairsFromReader(reader, complexAttributes);
reader.NextResult();
actions = StaticHelper.getActionsFormReader(reader);
reader.NextResult();
methods = StaticHelper.getMethodsFromReader(reader);
reader.NextResult();
StaticHelper.getMethodParametersFromReader(reader, methods);
}
}
BusinessObject definition = new PlainObjectListView
{
UIListCaption = uiListCaption,
BasicObjectNamespace = basicObjectNamespace,
BasicObjectName = basicObjectName,
ObjectActionNameLoadList = objectActionNameLoadList,
ObjectMethodNameLoadList = objectMethodNameLoadList,
ObjectNamespace = namespaceName,
ObjectName = name,
ObjectType = objectType,
FriendlyName = friendlyName,
Description = description,
Attributes = attributes,
ComplexAttributes = complexAttributes,
Actions = actions,
Methods = methods
};
#region Save to cache
if (_enableCaching)
{
if (!Directory.Exists(cacheDirectory))
Directory.CreateDirectory(cacheDirectory);
XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView));
using (FileStream stream = new FileStream(cacheFileName, FileMode.OpenOrCreate, FileAccess.Write))
serializer.Serialize(stream, definition);
}
#endregion
return definition;
}
}
} | shestakov/jetbat | JetBat.Client/SqlServer/Concrete/PlainObjectListViewDefinitionSqlLoader.cs | C# | bsd-3-clause | 5,650 |
from ..base import BaseTopazTest
class TestMarshal(BaseTopazTest):
def test_version_constants(self, space):
w_res = space.execute("return Marshal::MAJOR_VERSION")
assert space.int_w(w_res) == 4
w_res = space.execute("return Marshal::MINOR_VERSION")
assert space.int_w(w_res) == 8
w_res = space.execute("return Marshal.dump('test')[0].ord")
assert space.int_w(w_res) == 4
w_res = space.execute("return Marshal.dump('test')[1].ord")
assert space.int_w(w_res) == 8
def test_dump_constants(self, space):
w_res = space.execute("return Marshal.dump(nil)")
assert space.str_w(w_res) == "\x04\b0"
w_res = space.execute("return Marshal.dump(true)")
assert space.str_w(w_res) == "\x04\bT"
w_res = space.execute("return Marshal.dump(false)")
assert space.str_w(w_res) == "\x04\bF"
def test_load_constants(self, space):
w_res = space.execute("return Marshal.load('\x04\b0')")
assert w_res == space.w_nil
w_res = space.execute("return Marshal.load('\x04\bT')")
assert w_res == space.w_true
w_res = space.execute("return Marshal.load('\x04\bF')")
assert w_res == space.w_false
def test_constants(self, space):
w_res = space.execute("return Marshal.load(Marshal.dump(nil))")
assert w_res == space.w_nil
w_res = space.execute("return Marshal.load(Marshal.dump(true))")
assert w_res == space.w_true
w_res = space.execute("return Marshal.load(Marshal.dump(false))")
assert w_res == space.w_false
def test_dump_tiny_integer(self, space):
w_res = space.execute("return Marshal.dump(5)")
assert space.str_w(w_res) == "\x04\bi\n"
w_res = space.execute("return Marshal.dump(100)")
assert space.str_w(w_res) == "\x04\bii"
w_res = space.execute("return Marshal.dump(0)")
assert space.str_w(w_res) == "\x04\bi\x00"
w_res = space.execute("return Marshal.dump(-1)")
assert space.str_w(w_res) == "\x04\bi\xFA"
w_res = space.execute("return Marshal.dump(-123)")
assert space.str_w(w_res) == "\x04\bi\x80"
w_res = space.execute("return Marshal.dump(122)")
assert space.str_w(w_res) == "\x04\bi\x7F"
def test_load_tiny_integer(self, space):
w_res = space.execute("return Marshal.load('\x04\bi\n')")
assert space.int_w(w_res) == 5
w_res = space.execute("return Marshal.load('\x04\bii')")
assert space.int_w(w_res) == 100
#w_res = space.execute('return Marshal.load("\x04\bi\x00")')
w_res = space.execute('return Marshal.load(Marshal.dump(0))')
assert space.int_w(w_res) == 0
w_res = space.execute("return Marshal.load('\x04\bi\xFA')")
assert space.int_w(w_res) == -1
w_res = space.execute("return Marshal.load('\x04\bi\x80')")
assert space.int_w(w_res) == -123
w_res = space.execute("return Marshal.load('\x04\bi\x7F')")
assert space.int_w(w_res) == 122
def test_dump_array(self, space):
w_res = space.execute("return Marshal.dump([])")
assert space.str_w(w_res) == "\x04\b[\x00"
w_res = space.execute("return Marshal.dump([nil])")
assert space.str_w(w_res) == "\x04\b[\x060"
w_res = space.execute("return Marshal.dump([nil, true, false])")
assert space.str_w(w_res) == "\x04\b[\b0TF"
w_res = space.execute("return Marshal.dump([1, 2, 3])")
assert space.str_w(w_res) == "\x04\b[\x08i\x06i\x07i\x08"
w_res = space.execute("return Marshal.dump([1, [2, 3], 4])")
assert space.str_w(w_res) == "\x04\b[\bi\x06[\ai\ai\bi\t"
w_res = space.execute("return Marshal.dump([:foo, :bar])")
assert space.str_w(w_res) == "\x04\b[\a:\bfoo:\bbar"
def test_load_array(self, space):
#w_res = space.execute("return Marshal.load('\x04\b[\x00')")
w_res = space.execute("return Marshal.load(Marshal.dump([]))")
assert self.unwrap(space, w_res) == []
w_res = space.execute("return Marshal.load('\x04\b[\x060')")
assert self.unwrap(space, w_res) == [None]
w_res = space.execute("return Marshal.load('\x04\b[\b0TF')")
assert self.unwrap(space, w_res) == [None, True, False]
w_res = space.execute("return Marshal.load('\x04\b[\x08i\x06i\x07i\x08')")
assert self.unwrap(space, w_res) == [1, 2, 3]
w_res = space.execute("return Marshal.load('\x04\b[\bi\x06[\ai\ai\bi\t')")
assert self.unwrap(space, w_res) == [1, [2, 3], 4]
w_res = space.execute("return Marshal.load('\x04\b[\a:\bfoo:\bbar')")
assert self.unwrap(space, w_res) == ["foo", "bar"]
def test_dump_symbol(self, space):
w_res = space.execute("return Marshal.dump(:abc)")
assert space.str_w(w_res) == "\x04\b:\babc"
w_res = space.execute("return Marshal.dump(('hello' * 25).to_sym)")
assert space.str_w(w_res) == "\x04\b:\x01}" + "hello" * 25
w_res = space.execute("return Marshal.dump(('hello' * 100).to_sym)")
assert space.str_w(w_res) == "\x04\b:\x02\xF4\x01" + "hello" * 100
def test_load_symbol(self, space):
w_res = space.execute("return Marshal.load('\x04\b:\babc')")
assert space.symbol_w(w_res) == "abc"
w_res = space.execute("return Marshal.load('\x04\b:\x01}' + 'hello' * 25)")
assert space.symbol_w(w_res) == "hello" * 25
def test_dump_hash(self, space):
w_res = space.execute("return Marshal.dump({})")
assert space.str_w(w_res) == "\x04\b{\x00"
w_res = space.execute("return Marshal.dump({1 => 2, 3 => 4})")
assert self.unwrap(space, w_res) == "\x04\b{\ai\x06i\ai\bi\t"
w_res = space.execute("return Marshal.dump({1 => {2 => 3}, 4 => 5})")
assert self.unwrap(space, w_res) == "\x04\b{\ai\x06{\x06i\ai\bi\ti\n"
w_res = space.execute("return Marshal.dump({1234 => {23456 => 3456789}, 4 => 5})")
assert self.unwrap(space, w_res) == "\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n"
def test_load_hash(self, space):
#w_res = space.execute("return Marshal.load('\x04\b{\x00')")
w_res = space.execute("return Marshal.load(Marshal.dump({}))")
assert self.unwrap(space, w_res) == {}
w_res = space.execute("return Marshal.load('\x04\b{\ai\x06i\ai\bi\t')")
assert self.unwrap(space, w_res) == {1: 2, 3: 4}
w_res = space.execute("return Marshal.load('\x04\b{\ai\x06{\x06i\ai\bi\ti\n')")
assert self.unwrap(space, w_res) == {1: {2: 3}, 4: 5}
w_res = space.execute("return Marshal.load('\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n')")
assert self.unwrap(space, w_res) == {1234: {23456: 3456789}, 4: 5}
def test_dump_integer(self, space):
w_res = space.execute("return Marshal.dump(123)")
assert space.str_w(w_res) == "\x04\bi\x01{"
w_res = space.execute("return Marshal.dump(255)")
assert space.str_w(w_res) == "\x04\bi\x01\xFF"
w_res = space.execute("return Marshal.dump(256)")
assert space.str_w(w_res) == "\x04\bi\x02\x00\x01"
w_res = space.execute("return Marshal.dump(2 ** 16 - 2)")
assert space.str_w(w_res) == "\x04\bi\x02\xFE\xFF"
w_res = space.execute("return Marshal.dump(2 ** 16 - 1)")
assert space.str_w(w_res) == "\x04\bi\x02\xFF\xFF"
w_res = space.execute("return Marshal.dump(2 ** 16)")
assert space.str_w(w_res) == "\x04\bi\x03\x00\x00\x01"
w_res = space.execute("return Marshal.dump(2 ** 16 + 1)")
assert space.str_w(w_res) == "\x04\bi\x03\x01\x00\x01"
w_res = space.execute("return Marshal.dump(2 ** 30 - 1)")
assert space.str_w(w_res) == "\x04\bi\x04\xFF\xFF\xFF?"
# TODO: test tooo big numbers (they give a warning and inf)
def test_load_integer(self, space):
w_res = space.execute("return Marshal.load('\x04\bi\x01{')")
assert space.int_w(w_res) == 123
w_res = space.execute("return Marshal.load('\x04\bi\x01\xFF')")
assert space.int_w(w_res) == 255
#w_res = space.execute("return Marshal.load('\x04\bi\x02\x00\x01')")
w_res = space.execute("return Marshal.load(Marshal.dump(256))")
assert space.int_w(w_res) == 256
w_res = space.execute("return Marshal.load('\x04\bi\x02\xFE\xFF')")
assert space.int_w(w_res) == 2 ** 16 - 2
w_res = space.execute("return Marshal.load('\x04\bi\x02\xFF\xFF')")
assert space.int_w(w_res) == 2 ** 16 - 1
#w_res = space.execute("return Marshal.load('\x04\bi\x03\x00\x00\x01')")
w_res = space.execute("return Marshal.load(Marshal.dump(2 ** 16))")
assert space.int_w(w_res) == 2 ** 16
#w_res = space.execute("return Marshal.load('\x04\bi\x03\x01\x00\x01')")
w_res = space.execute("return Marshal.load(Marshal.dump(2 ** 16 + 1))")
assert space.int_w(w_res) == 2 ** 16 + 1
w_res = space.execute("return Marshal.load('\x04\bi\x04\xFF\xFF\xFF?')")
assert space.int_w(w_res) == 2 ** 30 - 1
def test_dump_negative_integer(self, space):
w_res = space.execute("return Marshal.dump(-1)")
assert space.str_w(w_res) == "\x04\bi\xFA"
w_res = space.execute("return Marshal.dump(-123)")
assert space.str_w(w_res) == "\x04\bi\x80"
w_res = space.execute("return Marshal.dump(-124)")
assert space.str_w(w_res) == "\x04\bi\xFF\x84"
w_res = space.execute("return Marshal.dump(-256)")
assert space.str_w(w_res) == "\x04\bi\xFF\x00"
w_res = space.execute("return Marshal.dump(-257)")
assert space.str_w(w_res) == "\x04\bi\xFE\xFF\xFE"
w_res = space.execute("return Marshal.dump(-(2 ** 30))")
assert space.str_w(w_res) == "\x04\bi\xFC\x00\x00\x00\xC0"
def test_load_negative_integer(self, space):
w_res = space.execute("return Marshal.load('\x04\bi\xFA')")
assert space.int_w(w_res) == -1
w_res = space.execute("return Marshal.load('\x04\bi\x80')")
assert space.int_w(w_res) == -123
w_res = space.execute("return Marshal.load('\x04\bi\xFF\x84')")
assert space.int_w(w_res) == -124
#w_res = space.execute("return Marshal.load('\x04\bi\xFF\x00')")
w_res = space.execute("return Marshal.load(Marshal.dump(-256))")
assert space.int_w(w_res) == -256
w_res = space.execute("return Marshal.load('\x04\bi\xFE\xFF\xFE')")
assert space.int_w(w_res) == -257
#w_res = space.execute("return Marshal.load('\x04\bi\xFE\x00\x00')")
w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 16)))")
assert space.int_w(w_res) == -(2 ** 16)
w_res = space.execute("return Marshal.load('\x04\bi\xFD\xFF\xFF\xFE')")
assert space.int_w(w_res) == -(2 ** 16 + 1)
#w_res = space.execute("return Marshal.load('\x04\bi\xFC\x00\x00\x00')")
w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 24)))")
assert space.int_w(w_res) == -(2 ** 24)
w_res = space.execute("return Marshal.load('\x04\bi\xFC\xFF\xFF\xFF\xFE')")
assert space.int_w(w_res) == -(2 ** 24 + 1)
#w_res = space.execute("return Marshal.load('\x04\bi\xFC\x00\x00\x00\xC0')")
w_res = space.execute("return Marshal.load(Marshal.dump(-(2 ** 30)))")
assert space.int_w(w_res) == -(2 ** 30)
def test_dump_float(self, space):
w_res = space.execute("return Marshal.dump(0.0)")
assert space.str_w(w_res) == "\x04\bf\x060"
w_res = space.execute("return Marshal.dump(0.1)")
assert space.str_w(w_res) == "\x04\bf\b0.1"
w_res = space.execute("return Marshal.dump(1.0)")
assert space.str_w(w_res) == "\x04\bf\x061"
w_res = space.execute("return Marshal.dump(1.1)")
assert space.str_w(w_res) == "\x04\bf\b1.1"
w_res = space.execute("return Marshal.dump(1.001)")
assert space.str_w(w_res) == "\x04\bf\n1.001"
#w_res = space.execute("return Marshal.dump(123456789.123456789)")
#assert space.str_w(w_res) == "\x04\bf\x17123456789.12345679"
#w_res = space.execute("return Marshal.dump(-123456789.123456789)")
#assert space.str_w(w_res) == "\x04\bf\x18-123456789.12345679"
#w_res = space.execute("return Marshal.dump(-0.0)")
#assert space.str_w(w_res) == "\x04\bf\a-0"
def test_load_float(self, space):
w_res = space.execute("return Marshal.load('\x04\bf\x060')")
assert space.float_w(w_res) == 0.0
w_res = space.execute("return Marshal.load('\x04\bf\b0.1')")
assert space.float_w(w_res) == 0.1
w_res = space.execute("return Marshal.load('\x04\bf\x061')")
assert space.float_w(w_res) == 1.0
w_res = space.execute("return Marshal.load('\x04\bf\b1.1')")
assert space.float_w(w_res) == 1.1
w_res = space.execute("return Marshal.load('\x04\bf\n1.001')")
assert space.float_w(w_res) == 1.001
#w_res = space.execute("return Marshal.load('\x04\bf\x17123456789.12345679')")
#assert space.float_w(w_res) == 123456789.123456789
#w_res = space.execute("return Marshal.load('\x04\bf\x18-123456789.12345679')")
#assert space.float_w(w_res) == -123456789.123456789
#w_res = space.execute("return Marshal.load('\x04\bf\a-0')")
#assert repr(space.float_w(w_res)) == repr(-0.0)
def test_dump_string(self, space):
w_res = space.execute("return Marshal.dump('')")
assert space.str_w(w_res) == "\x04\bI\"\x00\x06:\x06ET"
w_res = space.execute("return Marshal.dump('abc')")
assert space.str_w(w_res) == "\x04\bI\"\babc\x06:\x06ET"
w_res = space.execute("return Marshal.dump('i am a longer string')")
assert space.str_w(w_res) == "\x04\bI\"\x19i am a longer string\x06:\x06ET"
def test_load_string(self, space):
#w_res = space.execute("return Marshal.load('\x04\bI\"\x00\x06:\x06ET')")
w_res = space.execute("return Marshal.load(Marshal.dump(''))")
assert space.str_w(w_res) == ""
w_res = space.execute("return Marshal.load('\x04\bI\"\babc\x06:\x06ET')")
assert space.str_w(w_res) == "abc"
w_res = space.execute("return Marshal.load('\x04\bI\"\x19i am a longer string\x06:\x06ET')")
assert space.str_w(w_res) == "i am a longer string"
def test_array(self, space):
w_res = space.execute("return Marshal.load(Marshal.dump([1, 2, 3]))")
assert self.unwrap(space, w_res) == [1, 2, 3]
w_res = space.execute("return Marshal.load(Marshal.dump([1, [2, 3], 4]))")
assert self.unwrap(space, w_res) == [1, [2, 3], 4]
w_res = space.execute("return Marshal.load(Marshal.dump([130, [2, 3], 4]))")
assert self.unwrap(space, w_res) == [130, [2, 3], 4]
w_res = space.execute("return Marshal.load(Marshal.dump([-10000, [2, 123456], -9000]))")
assert self.unwrap(space, w_res) == [-10000, [2, 123456], -9000]
w_res = space.execute("return Marshal.load(Marshal.dump([:foo, :bar]))")
assert self.unwrap(space, w_res) == ["foo", "bar"]
w_res = space.execute("return Marshal.load(Marshal.dump(['foo', 'bar']))")
assert self.unwrap(space, w_res) == ["foo", "bar"]
def test_incompatible_format(self, space):
with self.raises(
space,
"TypeError",
"incompatible marshal file format (can't be read)\n"
"format version 4.8 required; 97.115 given"
):
space.execute("Marshal.load('asd')")
def test_short_data(self, space):
with self.raises(space, "ArgumentError", "marshal data too short"):
space.execute("Marshal.load('')")
def test_parameters(self, space):
with self.raises(space, "TypeError", "instance of IO needed"):
space.execute("Marshal.load(4)")
def test_io(self, space, tmpdir):
f = tmpdir.join("testfile")
w_res = space.execute("""
Marshal.dump('hallo', File.new('%s', 'wb'))
file = File.open('%s', 'rb')
return Marshal.load(file.read)
""" % (f, f))
assert space.str_w(w_res) == "hallo"
w_res = space.execute("""
Marshal.dump('hallo', File.new('%s', 'wb'))
file = File.open('%s', 'rb')
return Marshal.load(file)
""" % (f, f))
assert space.str_w(w_res) == "hallo"
| babelsberg/babelsberg-r | tests/modules/test_marshal.py | Python | bsd-3-clause | 16,593 |
/*
* Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Business Objects nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* IntellicutList.java
* Creation date: Dec 10th 2002
* By: Ken Wong
*/
package org.openquark.gems.client;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.JList;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import org.openquark.gems.client.IntellicutListModel.FilterLevel;
import org.openquark.gems.client.IntellicutListModelAdapter.IntellicutListEntry;
import org.openquark.gems.client.IntellicutManager.IntellicutMode;
/**
* A list that encapsulates all the details associated with populating
* a list with the unqualified names of gems.
* @author Ken Wong
* @author Frank Worsley
*/
public class IntellicutList extends JList {
private static final long serialVersionUID = -8515575227984050475L;
/** The last list index that was visible when the state was saved. */
private int savedVisibleIndex = -1;
/** The last list entry that was visible when the state was saved. */
private IntellicutListEntry savedVisibleEntry = null;
/** The list entry that was selected when the state was saved. */
private IntellicutListEntry savedSelectedEntry = null;
/** Whether or not this list should be drawn transparently. */
private boolean transparent = false;
/**
* Constructor for IntellicutList.
*/
public IntellicutList(IntellicutMode mode) {
setName("MatchingGemsList");
setCellRenderer(new IntellicutListRenderer(mode));
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
/**
* Enables the list to be transparent. If the list is transparent non selected list items
* will let the components below them show through. Selected list items will draw a blue
* semi-transparent tint as their background.
* @param value whether or not the list should be transparent
*/
void setTransparent(boolean value) {
this.transparent = value;
updateUI();
}
/**
* @return whether or not the intellicut list is transparent
*/
public boolean isTransparent() {
return transparent;
}
/**
* Saves the currently selected list item and the scroll position of the
* list so that the list state can be restored later.
*/
private void saveListState() {
IntellicutListModel listModel = (IntellicutListModel) getModel();
savedVisibleEntry = null;
savedSelectedEntry = null;
savedVisibleIndex = getLastVisibleIndex();
int selectedIndex = getSelectedIndex();
try {
savedVisibleEntry = listModel.get(savedVisibleIndex);
savedSelectedEntry = listModel.get(selectedIndex);
// We only want to make the selected entry visible again after refreshing
// the list if it was visible before.
if (selectedIndex > getLastVisibleIndex() || selectedIndex < getFirstVisibleIndex()) {
savedSelectedEntry = null;
}
} catch (Exception ex) {
// This might throw a NullPointerException or ArrayIndexOutOfBoundsException
// if the model is not initialized. In that case there is no index we can restore.
}
}
/**
* Restores the previously saved list state as closely as possible.
*/
private void restoreListState() {
IntellicutListModel listModel = (IntellicutListModel) getModel();
int newSelectedIndex = listModel.indexOf(savedSelectedEntry);
int newVisibleIndex = listModel.indexOf(savedVisibleEntry);
if (newVisibleIndex == -1) {
newVisibleIndex = savedVisibleIndex;
}
// We have to add one cell height, otherwise the cell will be just
// outside of the visible range of the list. ensureIndexIsVisible doesn't
// work here since we want the index to appear at the very bottom.
Point newLocation = indexToLocation(newVisibleIndex);
if (newLocation != null) {
newLocation.y += getCellBounds(0, 0).height;
scrollRectToVisible(new Rectangle(newLocation));
}
if (newSelectedIndex != -1) {
setSelectedIndex(newSelectedIndex);
ensureIndexIsVisible(newSelectedIndex);
} else {
setSelectedIndex(0);
}
}
/**
* Refreshes the list while remembering the selected item and scroll position
* as closely as possible. Simply refreshing the list model will not remember
* the list state.
* @param prefix the new prefix for values in the list
*/
public void refreshList(String prefix) {
IntellicutListModel listModel = (IntellicutListModel) getModel();
saveListState();
listModel.refreshList(prefix);
restoreListState();
}
/**
* Finds the JViewport this list is embedded in.
* @return the viewport or null if there is no viewport
*/
private JViewport getViewport() {
Container parent = getParent();
while (parent != null && !(parent instanceof JViewport)) {
parent = parent.getParent ();
}
return (JViewport) parent;
}
/**
* Scrolls the given index as close as possible to the top of the list's viewport.
* @param index index of the item to scroll to the top
*/
void scrollToTop(int index) {
Point location = indexToLocation(index);
if (location == null) {
return;
}
JViewport viewport = getViewport();
// Scroll this element as close to the top as possible.
if (viewport.getViewSize().height - location.y < viewport.getSize().height) {
location.y -= viewport.getSize().height - viewport.getViewSize().height + location.y;
}
viewport.setViewPosition(location);
}
/**
* Sets the current gem filtering level.
*
* The list is automatically refreshed after doing this. This method also saves
* the list's displayed state as opposed to just setting the filter level which
* will not remember the list state.
* @param filterLevel the new level to filter at
*/
void setFilterLevel(FilterLevel filterLevel) {
if (filterLevel == null) {
throw new NullPointerException("filterLevel must not be null in IntellicutList.setFilterLevel");
}
IntellicutListModel listModel = (IntellicutListModel) getModel();
saveListState();
listModel.setFilterLevel(filterLevel);
restoreListState();
}
/**
* Returns the user selected IntellicutListEntry
* @return IntellicutListEntry
*/
IntellicutListEntry getSelected(){
return getModel().getSize() > 0 ? (IntellicutListEntry) getSelectedValue() : null;
}
/**
* We want tooltips to be displayed to the right of an item.
* If there is no item at the coordinates it returns null.
* @param e the mouse event for which to determine the location
* @return the tooltip location for the list item at the coordinates of the mouse event
*/
@Override
public Point getToolTipLocation(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (index == -1) {
return null;
}
Rectangle cellBounds = getCellBounds(index, index);
// take off 50 and add 5 for good looks
return new Point (cellBounds.x + cellBounds.width - 50, cellBounds.y + 5);
}
/**
* @param e the MouseEvent for which to get the tooltip text
* @return the tooltip text for the list item at the coordinates or null if there is no
* item at the coordinates
*/
@Override
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (index == -1) {
return null;
}
IntellicutListEntry listEntry = (IntellicutListEntry) getModel().getElementAt(index);
if (listEntry == null) {
return null;
}
IntellicutListModel listModel = (IntellicutListModel) getModel();
return listModel.getAdapter().getToolTipTextForEntry(listEntry, this);
}
}
| levans/Open-Quark | src/Quark_Gems/src/org/openquark/gems/client/IntellicutList.java | Java | bsd-3-clause | 10,380 |
##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
unittest.main()
| chippey/gaffer | python/GafferImageTest/ObjectToImageTest.py | Python | bsd-3-clause | 3,067 |
import React from 'react';
import 'isomorphic-fetch';
import {RouteHandler} from 'react-router';
import Transmit from 'react-transmit';
import {createStore, combineReducers} from 'redux';
import {Provider} from 'react-redux';
import * as reducers from '../reducers/index';
class AppContainer extends React.Component {
static propTypes = {
initialState: React.PropTypes.object.isRequired
}
render() {
const reducer = combineReducers(reducers);
const store = createStore(reducer, this.props.initialState);
return (
<Provider store={store}>
{() =>
<RouteHandler />
}
</Provider>
);
}
}
export default Transmit.createContainer(AppContainer, {
queries: {}
});
| nivanson/hapi-universal-redux | src/containers/AppContainer.js | JavaScript | bsd-3-clause | 725 |
require("../pc.v0");
require("util").puts(JSON.stringify({
"name": "pc",
"version": pc.version,
"description": "property creation for reusable d3.js code.",
"keywords": ["d3", "visualization"],
"homepage": "http://milroc.github.com/pc/",
"author": {"name": "Miles McCrocklin", "url": "http://www.milesmccrocklin.com" },
"repository": {"type": "git", "url": "http://github.com/milroc/pc.git"},
"devDependencies": {
"uglify-js": "1.2.6",
"vows": "0.6.0"
}
}, null, 2)); | milroc/pc.js | src/package.js | JavaScript | bsd-3-clause | 485 |
.title {
margin-top: 30px;
vertical-align: top;
}
.title button {
margin-top: 20px;
}
.contents {
margin-top: 100px;
}
.contetns span {
margin-top: 20px;
}
| kokiBit/zend | public/css/type.css | CSS | bsd-3-clause | 182 |
package immortal
import (
"os/exec"
"syscall"
"testing"
"time"
)
func TestWatchPidGetpid(t *testing.T) {
ch := make(chan error, 1)
d := &Daemon{}
cmd := exec.Command("go", "version")
cmd.Start()
pid := cmd.Process.Pid
go func() {
d.WatchPid(pid, ch)
ch <- cmd.Wait()
}()
select {
case <-time.After(time.Millisecond):
syscall.Kill(pid, syscall.SIGTERM)
case err := <-ch:
if err != nil {
if err.Error() != "EXIT" {
t.Error(err)
}
}
}
}
func TestWatchPidGetpidKill(t *testing.T) {
d := &Daemon{}
ch := make(chan error, 1)
cmd := exec.Command("sleep", "100")
cmd.Start()
pid := cmd.Process.Pid
go func() {
d.WatchPid(pid, ch)
ch <- cmd.Wait()
}()
select {
case err := <-ch:
if err != nil {
if err.Error() != "EXIT" {
t.Error(err)
}
}
case <-time.After(1 * time.Millisecond):
if err := cmd.Process.Kill(); err != nil {
t.Errorf("failed to kill: %s", err)
}
}
}
| immortal/immortal | watchpid_test.go | GO | bsd-3-clause | 931 |
/*
* Author: Kiveisha Yevgeniy
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Utilities.h"
#include <string.h>
char
Utilities::toHEX (char code) {
return m_hex[code & 15];
}
long
Utilities::Escaping (char * src, char * dest) {
char *pstr = src;
char *pbuf = dest;
long count = 0;
while (*pstr) {
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') {
*pbuf++ = *pstr;
count++;
} else if (*pstr == ' ') {
*pbuf++ = '+';
count++;
} else if (*pstr == '=') {
*pbuf++ = *pstr;
count++;
} else {
*pbuf++ = '%', *pbuf++ = toHEX(*pstr >> 4), *pbuf++ = toHEX(*pstr & 15);
count += 3;
}
pstr++;
}
*pbuf = '\0';
return count;
}
std::string
Utilities::EncodeBase64 (unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++) {
ret += m_base64_chars[char_array_4[i]];
}
i = 0;
}
}
if (i) {
for(j = i; j < 3; j++) {
char_array_3[j] = '\0';
}
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++) {
ret += m_base64_chars[char_array_4[j]];
}
while((i++ < 3))
ret += '=';
}
return ret;
} | ykiveish/cortica-sdk | src/Utilities.cpp | C++ | bsd-3-clause | 2,892 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Tue May 19 11:04:42 CEST 2015 -->
<title>Uses of Interface com.mxgraph.util.svg.ShapeProducer (JGraph X 3.3.0.1 API Specification)</title>
<meta name="date" content="2015-05-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface com.mxgraph.util.svg.ShapeProducer (JGraph X 3.3.0.1 API Specification)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><p><b>JGraph X 3.3.0.1</b></p></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/mxgraph/util/svg/class-use/ShapeProducer.html" target="_top">Frames</a></li>
<li><a href="ShapeProducer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface com.mxgraph.util.svg.ShapeProducer" class="title">Uses of Interface<br>com.mxgraph.util.svg.ShapeProducer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.mxgraph.util.svg">com.mxgraph.util.svg</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.mxgraph.util.svg">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a> in <a href="../../../../../com/mxgraph/util/svg/package-summary.html">com.mxgraph.util.svg</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../com/mxgraph/util/svg/package-summary.html">com.mxgraph.util.svg</a> that implement <a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">ShapeProducer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPathProducer.html" title="class in com.mxgraph.util.svg">AWTPathProducer</a></strong></code>
<div class="block">This class provides an implementation of the PathHandler that initializes
a Shape from the value of a path's 'd' attribute.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPolygonProducer.html" title="class in com.mxgraph.util.svg">AWTPolygonProducer</a></strong></code>
<div class="block">This class produces a polygon shape from a reader.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../com/mxgraph/util/svg/AWTPolylineProducer.html" title="class in com.mxgraph.util.svg">AWTPolylineProducer</a></strong></code>
<div class="block">This class produces a polyline shape from a reader.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/mxgraph/util/svg/ShapeProducer.html" title="interface in com.mxgraph.util.svg">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><p><b>JGraph X 3.3.0.1</b></p></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/mxgraph/util/svg/class-use/ShapeProducer.html" target="_top">Frames</a></li>
<li><a href="ShapeProducer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size=1>Copyright (c) 2010 <a href="http://www.mxgraph.com/"
target="_blank">Gaudenz Alder</a>. All rights reserved.</font></small></p>
</body>
</html>
| pygospa/jgraphx | docs/api/com/mxgraph/util/svg/class-use/ShapeProducer.html | HTML | bsd-3-clause | 7,160 |
SEEK::Application.configure do
#This holds a secret phrase, used for encrypting private information in the database
#GLOBAL_PASSPHRASE=""
Seek::Config.default :solr_enabled, true
end
| stuzart/seek | docker/seek_local.rb | Ruby | bsd-3-clause | 191 |
#pragma once
#include "boxFilter.hpp"
class boxFilter_Separable_VHI_nonVec : public cp::BoxFilterBase
{
protected:
int ksize;
void filter_naive_impl() override;
void filter_omp_impl() override;
void operator()(const cv::Range& range) const override;
public:
boxFilter_Separable_VHI_nonVec(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType);
virtual void init();
};
class boxFilter_Separable_VHI_SSE : public boxFilter_Separable_VHI_nonVec
{
private:
__m128 mDiv;
void filter_naive_impl() override;
void filter_omp_impl() override;
void operator()(const cv::Range& range) const override;
public:
boxFilter_Separable_VHI_SSE(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType);
void init() override;
};
class boxFilter_Separable_VHI_AVX : public boxFilter_Separable_VHI_nonVec
{
private:
__m256 mDiv;
void filter_naive_impl() override;
void filter_omp_impl() override;
void operator()(const cv::Range& range) const override;
public:
boxFilter_Separable_VHI_AVX(cv::Mat& _src, cv::Mat& _dest, int _r, int _parallelType);
void init() override;
};
| norishigefukushima/OpenCP | OpenCP/box/boxFilter_Separable_Interleave.h | C | bsd-3-clause | 1,086 |
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia at 2014-11-25
| Rendered using Apache Maven Fluido Skin 1.3.0
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20141125" />
<meta http-equiv="Content-Language" content="en" />
<title>TrAP Transport WebSocket by Netty - Continuous Integration</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.3.0.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.3.0.min.js"></script>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left">
<div id="bannerLeft">
<h2>TrAP Transport WebSocket by Netty</h2>
</div>
</div>
<div class="pull-right"> </div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2014-11-25</li>
<li class="divider">|</li> <li id="projectVersion">Version: 1.3</li>
<li class="divider">|</li> <li class="">
<a href="../../../index.html" title="Trap">
Trap</a>
</li>
<li class="divider ">/</li>
<li class="">
<a href="../../" title="TrAP Transports">
TrAP Transports</a>
</li>
<li class="divider ">/</li>
<li class="">
<a href="../" title="WebSocket Transport Parent">
WebSocket Transport Parent</a>
</li>
<li class="divider ">/</li>
<li class="">
<a href="./" title="TrAP Transport WebSocket by Netty">
TrAP Transport WebSocket by Netty</a>
</li>
<li class="divider ">/</li>
<li class="">Continuous Integration</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Trap 1.3</li>
<li>
<a href="../../../index.html" title="Introduction">
<i class="none"></i>
Introduction</a>
</li>
<li>
<a href="../../../trap-api/quickstart.html" title="Java Quickstart">
<i class="none"></i>
Java Quickstart</a>
</li>
<li>
<a href="../../../trap-js/index.html" title="JavaScript Quickstart">
<i class="none"></i>
JavaScript Quickstart</a>
</li>
<li>
<a href="../../../channels.html" title="Channels">
<i class="none"></i>
Channels</a>
</li>
<li>
<a href="../../../configuration.html" title="Configuration">
<i class="none"></i>
Configuration</a>
</li>
<li class="nav-header">Language Specific Documentation</li>
<li>
<a href="../../../trap-api/index.html" title="Java">
<i class="none"></i>
Java</a>
</li>
<li>
<a href="../../../trap-js/index.html" title="JavaScript">
<i class="none"></i>
JavaScript</a>
</li>
<li class="nav-header">Project Documentation</li>
<li>
<a href="project-info.html" title="Project Information">
<i class="icon-chevron-down"></i>
Project Information</a>
<ul class="nav nav-list">
<li>
<a href="index.html" title="About">
<i class="none"></i>
About</a>
</li>
<li>
<a href="plugin-management.html" title="Plugin Management">
<i class="none"></i>
Plugin Management</a>
</li>
<li>
<a href="distribution-management.html" title="Distribution Management">
<i class="none"></i>
Distribution Management</a>
</li>
<li>
<a href="dependency-info.html" title="Dependency Information">
<i class="none"></i>
Dependency Information</a>
</li>
<li>
<a href="dependency-convergence.html" title="Dependency Convergence">
<i class="none"></i>
Dependency Convergence</a>
</li>
<li>
<a href="source-repository.html" title="Source Repository">
<i class="none"></i>
Source Repository</a>
</li>
<li>
<a href="mail-lists.html" title="Mailing Lists">
<i class="none"></i>
Mailing Lists</a>
</li>
<li>
<a href="issue-tracking.html" title="Issue Tracking">
<i class="none"></i>
Issue Tracking</a>
</li>
<li class="active">
<a href="#"><i class="none"></i>Continuous Integration</a>
</li>
<li>
<a href="plugins.html" title="Project Plugins">
<i class="none"></i>
Project Plugins</a>
</li>
<li>
<a href="license.html" title="Project License">
<i class="none"></i>
Project License</a>
</li>
<li>
<a href="dependency-management.html" title="Dependency Management">
<i class="none"></i>
Dependency Management</a>
</li>
<li>
<a href="team-list.html" title="Project Team">
<i class="none"></i>
Project Team</a>
</li>
<li>
<a href="project-summary.html" title="Project Summary">
<i class="none"></i>
Project Summary</a>
</li>
<li>
<a href="dependencies.html" title="Dependencies">
<i class="none"></i>
Dependencies</a>
</li>
</ul>
</li>
<li>
<a href="project-reports.html" title="Project Reports">
<i class="icon-chevron-right"></i>
Project Reports</a>
</li>
</ul>
<form id="search-form" action="http://www.google.com/search" method="get" >
<input value="ericssonresearch.github.io/trap/transports/websocket/websocket-netty/" name="sitesearch" type="hidden"/>
<input class="search-query" name="q" id="query" type="text" />
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=search-form"></script>
<hr class="divider" />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" />
</a>
</div>
</div>
</div>
<div id="bodyColumn" class="span9" >
<div class="section">
<h2>Continuous Integration<a name="Continuous_Integration"></a></h2><a name="Continuous_Integration"></a>
<p>No continuous integration management system is defined. Please check back at a later date.</p></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row span12">Copyright © 2014
<a href="https://www.ericsson.com">Ericsson AB</a>.
All Rights Reserved.
</div>
</div>
</footer>
</body>
</html> | princeofdarkness76/trap | transports/websocket/websocket-netty/integration.html | HTML | bsd-3-clause | 9,839 |
/**
* Created on: Mar 13, 2013
*/
package com.tubros.constraints.core.spi.solver
package runtime
import org.junit.runner.RunWith
import org.scalamock.scalatest.MockFactory
import org.scalatest._
import org.scalatest.junit.JUnitRunner
import com.tubros.constraints.api._
/**
* The '''SymbolTableSpec''' type defines the unit tests responsible for
* certifying the [[com.tubros.constraints.core.spi.solver.runtime.SymbolTable]]
* abstraction for use in CSP implementations.
*
* @author svickers
*
*/
@RunWith (classOf[JUnitRunner])
class SymbolTableSpec
extends ProjectSpec
{
"A SymbolTable" should "be able to be constructed with nothing in it" in
{
val table = SymbolTable.empty;
table shouldNot be (null);
table ('unknown) should be ('empty);
table.contains ('anyName) shouldBe (false);
}
it should "support symbol name addition" in
{
val entry = VariableName ('aName);
val oneEntry = SymbolTable.empty addSymbol (entry);
oneEntry.contains (entry) shouldBe (true);
oneEntry (entry) shouldBe (Set (entry));
}
it should "support dependant definitions" in
{
val dependant = (
SymbolTable.empty
addSymbol ('a)
addSymbol ('b)
addDerivedSymbol ('c, Set ('a, 'b))
);
dependant ('c) should not be ('empty);
dependant.contains ('c) shouldBe (true);
dependant ('c) shouldBe (
Set (VariableName ('a), VariableName ('b))
);
}
it should "support nested dependant definitions" in
{
val nested = (
SymbolTable.empty
addDerivedSymbol ('d, Set ('c))
addDerivedSymbol ('c, Set ('a, 'b))
addSymbol ('b)
addSymbol ('a)
);
nested.contains ('d) shouldBe (true);
nested ('d) should not be ('empty);
nested ('d) shouldBe (
Set (VariableName ('a), VariableName ('b))
);
}
it should "be able to determine what symbols are dependants" in
{
val dependant = (
SymbolTable.empty
addSymbol ('a)
addSymbol ('b)
addDerivedSymbol ('c, Set ('a, 'b))
);
dependant.isDerived ('a) shouldBe (false);
dependant.isDerived ('c) shouldBe (true);
}
it should "be able to resolve dependants available when expected" in
{
val dependant = (
SymbolTable.empty
addSymbol ('a)
addSymbol ('b)
addDerivedSymbol ('c, Set ('a, 'b))
);
dependant.derivedFrom (Set[VariableName] ('a, 'b)) shouldBe (
Set (VariableName ('c))
);
}
it should "not resolve a dependant unless all roots are available" in
{
val dependant = (
SymbolTable.empty
addSymbol ('a)
addSymbol ('b)
addDerivedSymbol ('c, Set ('a, 'b))
);
dependant.derivedFrom (Set[VariableName] ('a)) should be ('empty);
}
it should "not resolve a dependant unless all participants are available" in
{
val dependant = (
SymbolTable.empty
addSymbol ('a)
addSymbol ('b)
addSymbol ('d)
addDerivedSymbol ('c, Set ('a, 'e))
addDerivedSymbol ('e, Set ('d))
);
dependant.derivedFrom (Set[VariableName] ('a, 'b)) should be ('empty);
}
}
| osxhacker/smocs | smocs-core/src/test/scala/com/tubros/constraints/core/spi/solver/runtime/SymbolTableSpec.scala | Scala | bsd-3-clause | 2,993 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.genmod.cov_struct.Exchangeable.update — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.genmod.cov_struct.GlobalOddsRatio" href="statsmodels.genmod.cov_struct.GlobalOddsRatio.html" />
<link rel="prev" title="statsmodels.genmod.cov_struct.Exchangeable.summary" href="statsmodels.genmod.cov_struct.Exchangeable.summary.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.genmod.cov_struct.Exchangeable.update" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.13.0</span>
<span class="md-header-nav__topic"> statsmodels.genmod.cov_struct.Exchangeable.update </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../gee.html" class="md-tabs__link">Generalized Estimating Equations</a></li>
<li class="md-tabs__item"><a href="statsmodels.genmod.cov_struct.Exchangeable.html" class="md-tabs__link">statsmodels.genmod.cov_struct.Exchangeable</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.13.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../regression.html" class="md-nav__link">Linear Regression</a>
</li>
<li class="md-nav__item">
<a href="../glm.html" class="md-nav__link">Generalized Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a>
</li>
<li class="md-nav__item">
<a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a>
</li>
<li class="md-nav__item">
<a href="../rlm.html" class="md-nav__link">Robust Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a>
</li>
<li class="md-nav__item">
<a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../anova.html" class="md-nav__link">ANOVA</a>
</li>
<li class="md-nav__item">
<a href="../other_models.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">othermod</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.genmod.cov_struct.Exchangeable.update.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-genmod-cov-struct-exchangeable-update--page-root">statsmodels.genmod.cov_struct.Exchangeable.update<a class="headerlink" href="#generated-statsmodels-genmod-cov-struct-exchangeable-update--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt class="sig sig-object py" id="statsmodels.genmod.cov_struct.Exchangeable.update">
<span class="sig-prename descclassname"><span class="pre">Exchangeable.</span></span><span class="sig-name descname"><span class="pre">update</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">params</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/genmod/cov_struct.html#Exchangeable.update"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.genmod.cov_struct.Exchangeable.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the association parameter values based on the current
regression coefficients.</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>params</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array_like" title="(in NumPy v1.21)"><span>array_like</span></a></span></dt><dd><p>Working values for the regression parameters.</p>
</dd>
</dl>
</dd>
</dl>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.genmod.cov_struct.Exchangeable.summary.html" title="statsmodels.genmod.cov_struct.Exchangeable.summary"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.genmod.cov_struct.Exchangeable.summary </span>
</div>
</a>
<a href="statsmodels.genmod.cov_struct.GlobalOddsRatio.html" title="statsmodels.genmod.cov_struct.GlobalOddsRatio"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.genmod.cov_struct.GlobalOddsRatio </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 06, 2021.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 4.0.3.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | statsmodels/statsmodels.github.io | v0.13.0/generated/statsmodels.genmod.cov_struct.Exchangeable.update.html | HTML | bsd-3-clause | 18,859 |
#include "synchronization/Communicator.hpp"
namespace Synchronization
{
Communicator::Communicator()
: _numManagedCons(0),
_numManagedFmus(0)
{
}
size_type Synchronization::Communicator::addFmu(FMI::AbstractFmu* in, vector<FMI::InputMapping> & valuePacking)
{
vector<ConnectionSPtr>& connList = in->getConnections();
size_type numNewCons = 0;
for (auto & con : connList)
{
con->initialize(in->getFmuName());
size_type conId;
auto it = _knownConIds.find(con->getStartTag());
if (it == _knownConIds.end())
{
valuePacking.push_back(con->getPacking());
conId = _numManagedCons++;
_knownConIds[con->getStartTag()] = conId;
++numNewCons;
}
else
{
conId = it->second;
if (con->isShared())
{
++numNewCons;
valuePacking.push_back(con->getPacking());
}
}
con->setLocalId(conId);
}
in->setSharedId(_numManagedFmus++);
for (auto & con : connList)
{
if (con->getLocalId() + 1 > _connections.size())
{
_connections.resize(con->getLocalId() + 1);
_connections[con->getLocalId()] = con;
}
}
if (_outConnectionIds.size() < in->getSharedId() + 1)
{
_outConnectionIds.resize(in->getSharedId() + 1);
}
if (_inConnectionIds.size() < in->getSharedId() + 1)
{
_inConnectionIds.resize(in->getSharedId() + 1);
}
for (auto & i : connList)
{
if (i->isOutgoing(in->getFmuName()))
{
_outConnectionIds[in->getSharedId()].push_back(i->getLocalId());
}
else
{
_inConnectionIds[in->getSharedId()].push_back(i->getLocalId());
}
}
return numNewCons;
}
bool_type Communicator::send(HistoryEntry const & in, size_type communicationId)
{
return static_cast<bool_type>(_connections[communicationId]->send(in));
}
HistoryEntry Communicator::recv(size_type communicationId)
{
return _connections[communicationId]->recv();
}
int_type Communicator::connectionIsFree(size_type communicationId)
{
return _connections[communicationId]->hasFreeBuffer();
}
const vector<size_type> & Communicator::getInConnectionIds(const FMI::AbstractFmu * in) const
{
return _inConnectionIds[in->getSharedId()];
}
const vector<size_type> & Communicator::getOutConnectionIds(const FMI::AbstractFmu * in) const
{
return _outConnectionIds[in->getSharedId()];
}
size_type Communicator::getNumInConnections() const
{
size_type sum = 0;
for (const auto & _inConnectionId : _inConnectionIds)
{
sum += _inConnectionId.size();
}
return sum;
}
size_type Communicator::getNumOutConnections() const
{
size_type sum = 0;
for (const auto & _outConnectionId : _outConnectionIds)
{
sum += _outConnectionId.size();
}
return sum;
}
} /* namespace Synchronization */
| marchartung/ParallelFMU | src/synchronization/Communicator.cpp | C++ | bsd-3-clause | 3,412 |
{% load url from future %}
<div class="well">
<h3 class="title">Violence</h3>
<table class="table tabulated-data">
<thead>
<tr>
<th>Group</th>
<th>Monthly Numbers</th>
</tr>
</thead>
<tbody>
<tr>
<td>Girls Cases</td>
<td>{{ violence_numbers_girls|floatformat:0 }}</td>
</tr>
<tr>
<td>Boys Cases</td>
<td>{{ violence_numbers_boys|floatformat:0 }}</td>
</tr>
<tr>
<td>Cases Referred to Police</td>
<td>{{ violence_numbers_reported|floatformat:0 }}</td>
</tr>
</tbody>
</table>
<div class="actions">
<a href="{% url 'violence-admin-details' %}" class="btn btn-secondary"><i class="icon-th-list"></i> View Details</a>
</div>
</div>
| unicefuganda/edtrac | edtrac_project/rapidsms_edtrac/education/templates/education/admin/dashboard/violence.html | HTML | bsd-3-clause | 710 |
#!/usr/bin/env python2
from __future__ import print_function
import sys
import os
import urllib
import argparse
import xml.etree.ElementTree as ET
def warn(*msgs):
for x in msgs: print('[WARNING]:', x, file=sys.stderr)
class PDBTM:
def __init__(self, filename):
#self.tree = ET.parse(filename)
#self.root = self.tree.getroot()
def strsum(l):
s = ''
for x in l: s += x.rstrip() + '\n'
return s
f = open(filename)
s = []
for l in f: s.append(l)
#s = strsum(s[1:-1]).strip()
s = strsum(s).strip()
self.root = ET.fromstring(s)
print(root)
def get_database(prefix='.'):
if not prefix.endswith('/'): prefix += '/'
print('Fetching database...', file=sys.stderr)
db = urllib.urlopen('http://pdbtm.enzim.hu/data/pdbtmall')
print('Saving database...', file=sys.stderr)
f = open('%s/pdbtmall' % prefix, 'w')
for l in db: f.write(l)
#f.write(db.read())
db.close()
f.close()
def build_database(fn, prefix):
print('Unpacking database...', file=sys.stderr)
f = open(fn)
db = f.read()
f.close()
firstline = 1
header = ''
entries = []
pdbids = []
for l in db.split('\n'):
if firstline:
header += l
firstline -= 1
continue
if 'PDBTM>' in l: continue
if l.startswith('<?'): continue
if l.startswith('<pdbtm'):
a = l.find('ID=') + 4
b = a + 4
pdbids.append(l[a:b])
entries.append(header)
entries[-1] += '\n' + l
if not prefix.endswith('/'): prefix += '/'
if not os.path.isdir(prefix): os.mkdir(prefix)
for entry in zip(pdbids, entries):
f = open(prefix + entry[0] + '.xml', 'w')
f.write(entry[1])
f.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Manages PDBTM databases. Automatically fetches the PDBTM database if no options are specified. Run without any arguments, dbtool will retrieve the PDBTM database, store it in pdbtm, and unpack it.')
parser.add_argument('-d', '--db', default='pdbtmall', help='name of concatenated database file {default:pdbtmall}')
parser.add_argument('-b', '--build-db', action='store_true', help='(re)build database from an existing pdbtmsall file (available at http://pdbtm.enzim.hu/data/pdbtmall)')
parser.add_argument('directory', nargs='?', default='pdbtm', help='directory to store database in')
parser.add_argument('-f', '--force-refresh', action='store_true', help='force overwrite of existing database. Functionally equivalent to removing the old database and rerunning.')
#parser.add_argument('-n', metavar='bundle_size', type=int, help='size to cut bundles into')
args = parser.parse_args()
if args.build_db: build_database(args.db, args.directory)
else: #db = PDBTM(args.db)
if not os.path.isdir(args.directory): os.mkdir(args.directory)
if args.force_refresh or not os.path.isfile('%s/%s' % (args.directory, args.db)): get_database(args.directory)
build_database('%s/%s' % (args.directory, args.db), args.directory)
#http://pdbtm.enzim.hu/data/pdbtmall
| khendarg/pdbtmtop | dbtool.py | Python | bsd-3-clause | 2,933 |
{-# LANGUAGE TemplateHaskell #-}
module Data.Comp.Trans.DeriveUntrans (
deriveUntrans
) where
import Control.Lens ( view ,(^.))
import Control.Monad ( liftM )
import Control.Monad.Trans ( lift )
import Data.Comp.Multi ( Alg, cata, (:&:)(..) )
import Language.Haskell.TH
import Data.Comp.Trans.Util
--------------------------------------------------------------------------------
-- |
-- Creates an @untranslate@ function inverting the @translate@ function
-- created by @deriveTrans@.
--
-- @
-- import qualified Foo as F
-- type ArithTerm = Term (Arith :+: Atom :+: Lit)
-- deriveUntrans [''F.Arith, ''F.Atom, ''F.Lit] (TH.ConT ''ArithTerm)
-- @
--
-- will create
--
-- @
-- type family Targ l
-- newtype T l = T {t :: Targ l}
--
-- class Untrans f where
-- untrans :: Alg f t
--
-- untranslate :: ArithTerm l -> Targ l
-- untranslate = t . cata untrans
--
-- type instance Targ ArithL = F.Arith
-- instance Untrans Arith where
-- untrans (Add x y) = T $ F.Add (t x) (t y)
--
-- type instance Targ AtomL = F.Atom
-- instance Untrans Atom where
-- untrans (Var s) = T $ F.Var s
-- untrans (Const x) = T $ F.Const (t x)
--
-- type instance Targ LitL = F.Lit
-- instance Untrans Lit where
-- untrans (Lit n) = T $ F.Lit n
-- @
--
-- Note that you will need to manually provide an instance @(Untrans f, Untrans g) => Untrans (f :+: g)@
-- due to phase issues. (Or @(Untrans (f :&: p), Untrans (g :&: p)) => Untrans ((f :+: g) :&: p)@, if you
-- are propagating annotations.)
--
-- With annotation propagation on, it will instead produce
-- `untranslate :: Term (Arith :&: Ann) l -> Targ l Ann`
deriveUntrans :: [Name] -> Type -> CompTrans [Dec]
deriveUntrans names term = do targDec <- mkTarg targNm
wrapperDec <- mkWrapper wrapNm unwrapNm targNm
fnDec <- mkFn untranslateNm term targNm unwrapNm fnNm
classDec <- mkClass classNm fnNm wrapNm
instances <- liftM concat $ mapM (mkInstance classNm fnNm wrapNm unwrapNm targNm) names
return $ concat [ targDec
, wrapperDec
, fnDec
, classDec
, instances
]
where
targNm = mkName "Targ"
wrapNm = mkName "T"
unwrapNm = mkName "t"
untranslateNm = mkName "untranslate"
classNm = mkName "Untrans"
fnNm = mkName "untrans"
{- type family Targ l -}
mkTarg :: Name -> CompTrans [Dec]
mkTarg targNm = do i <- lift $ newName "i"
return [FamilyD TypeFam targNm [PlainTV i] Nothing]
{- newtype T l = T { t :: Targ l } -}
mkWrapper :: Name -> Name -> Name -> CompTrans [Dec]
mkWrapper tpNm fNm targNm = do i <- lift $ newName "i"
let con = RecC tpNm [(fNm, NotStrict, AppT (ConT targNm) (VarT i))]
return [NewtypeD [] tpNm [PlainTV i] con []]
{-
untranslate :: JavaTerm l -> Targ l
untranslate = t . cata untrans
-}
mkFn :: Name -> Type -> Name -> Name -> Name -> CompTrans [Dec]
mkFn fnNm term targNm fldNm untransNm = sequence [sig, def]
where
sig = do i <- lift $ newName "i"
lift $ sigD fnNm (forallT [PlainTV i] (return []) (typ $ varT i))
typ :: Q Type -> Q Type
typ i = [t| $term' $i -> $targ $i |]
term' = return term
targ = conT targNm
def = lift $ valD (varP fnNm) (normalB body) []
body = [| $fld . cata $untrans |]
fld = varE fldNm
untrans = varE untransNm
{-
class Untrans f where
untrans :: Alg f T
-}
mkClass :: Name -> Name -> Name -> CompTrans [Dec]
mkClass classNm funNm newtpNm = do f <- lift $ newName "f"
let funDec = SigD funNm (AppT (AppT (ConT ''Alg) (VarT f)) (ConT newtpNm))
return [ClassD [] classNm [PlainTV f] [] [funDec]]
{-
type instance Targ CompilationUnitL = J.CompilationUnit
instance Untrans CompilationUnit where
untrans (CompilationUnit x y z) = T $ J.CompilationUnit (t x) (t y) (t z)
-}
mkInstance :: Name -> Name -> Name -> Name -> Name -> Name -> CompTrans [Dec]
mkInstance classNm funNm wrap unwrap targNm typNm = do inf <- lift $ reify typNm
targTyp <- getFullyAppliedType typNm
let nmTyps = simplifyDataInf inf
clauses <- mapM (uncurry $ mkClause wrap unwrap) nmTyps
let conTyp = ConT (transName typNm)
annPropInf <- view annotationProp
let instTyp = case annPropInf of
Nothing -> conTyp
Just api -> foldl AppT (ConT ''(:&:)) [conTyp, api ^. annTyp]
return [ famInst targTyp
, inst clauses instTyp
]
where
famInst targTyp = TySynInstD targNm (TySynEqn [ConT $ nameLab typNm] targTyp)
inst clauses instTyp = InstanceD []
(AppT (ConT classNm) instTyp)
[FunD funNm clauses]
mapConditionallyReplacing :: [a] -> (a -> b) -> (a -> Bool) -> [b] -> [b]
mapConditionallyReplacing src f p reps = go src reps
where
go [] _ = []
go (x:xs) (y:ys) | p x = y : go xs ys
go (x:xs) l | not (p x) = f x : go xs l
go (_:_ ) [] = error "mapConditionallyReplacing: Insufficiently many replacements"
mkClause :: Name -> Name -> Name -> [Type] -> CompTrans Clause
mkClause wrap unwrap con tps = do isAnn <- getIsAnn
nms <- mapM (const $ lift $ newName "x") tps
nmAnn <- lift $ newName "a"
tps' <- applyCurSubstitutions tps
let nmTps = zip nms tps'
Clause <$> (sequence [pat isAnn nmTps nmAnn]) <*> (body nmTps nmAnn) <*> pure []
where
pat :: (Type -> Bool) -> [(Name, Type)] -> Name -> CompTrans Pat
pat isAnn nmTps nmAnn = do isProp <- isPropagatingAnns
if isProp then
return $ ConP '(:&:) [nodeP, VarP nmAnn]
else
return nodeP
where
nonAnnNms = map fst $ filter (not.isAnn.snd) nmTps
nodeP = ConP (transName con) (map VarP nonAnnNms)
body :: [(Name, Type)] -> Name -> CompTrans Body
body nmTps nmAnn = do annPropInf <- view annotationProp
args <- case annPropInf of
Nothing -> return $ map atom nmTps
Just api -> do isAnn <- getIsAnn
let unProp = api ^. unpropAnn
let annVars = filter (isAnn.snd) nmTps
let annExps = unProp (VarE nmAnn) (length annVars)
return $ mapConditionallyReplacing nmTps atom (isAnn.snd) annExps
return $ makeRhs args
where
makeRhs :: [Exp] -> Body
makeRhs args = NormalB $ AppE (ConE wrap) $ foldl AppE (ConE con) args
atom :: (Name, Type) -> Exp
atom (x, t) | elem t baseTypes = VarE x
atom (x, _) = AppE (VarE unwrap) (VarE x)
| jkoppel/comptrans | Data/Comp/Trans/DeriveUntrans.hs | Haskell | bsd-3-clause | 8,030 |
from django.template import Library, Node, resolve_variable, TemplateSyntaxError
from django.core.urlresolvers import reverse
register = Library()
@register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.get_full_path()):
return 'active'
return '' | Kami/munin_exchange | munin_exchange/apps/core/templatetags/navclass.py | Python | bsd-3-clause | 307 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <utility>
#include <vector>
#include "base/feature_list.h"
#include "base/macros.h"
#include "base/optional.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/metrics/user_action_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/test/test_mock_time_task_runner.h"
#include "build/build_config.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/password_manager/core/browser/form_fetcher_impl.h"
#include "components/password_manager/core/browser/http_auth_manager_impl.h"
#include "components/password_manager/core/browser/mock_password_store.h"
#include "components/password_manager/core/browser/password_form_manager.h"
#include "components/password_manager/core/browser/password_form_manager_for_ui.h"
#include "components/password_manager/core/browser/password_manager_driver.h"
#include "components/password_manager/core/browser/password_store.h"
#include "components/password_manager/core/browser/password_store_consumer.h"
#include "components/password_manager/core/browser/stub_password_manager_client.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using autofill::PasswordForm;
using base::ASCIIToUTF16;
using base::TestMockTimeTaskRunner;
using testing::_;
using testing::AnyNumber;
using testing::Invoke;
using testing::Mock;
using testing::Return;
using testing::ReturnRef;
using testing::SaveArg;
using testing::WithArg;
namespace password_manager {
namespace {
class MockPasswordManagerClient : public StubPasswordManagerClient {
public:
MockPasswordManagerClient() {}
MOCK_CONST_METHOD1(IsSavingAndFillingEnabled, bool(const GURL&));
MOCK_CONST_METHOD1(IsFillingEnabled, bool(const GURL&));
MOCK_METHOD2(AutofillHttpAuth,
void(const autofill::PasswordForm&,
const PasswordFormManagerForUI*));
MOCK_CONST_METHOD0(GetProfilePasswordStore, PasswordStore*());
MOCK_METHOD0(PromptUserToSaveOrUpdatePasswordPtr, void());
// Workaround for std::unique_ptr<> lacking a copy constructor.
bool PromptUserToSaveOrUpdatePassword(
std::unique_ptr<PasswordFormManagerForUI> manager,
bool update_password) override {
PromptUserToSaveOrUpdatePasswordPtr();
return true;
}
};
class MockHttpAuthObserver : public HttpAuthObserver {
public:
MockHttpAuthObserver() = default;
~MockHttpAuthObserver() override = default;
MOCK_METHOD0(OnLoginModelDestroying, void());
MOCK_METHOD2(OnAutofillDataAvailable,
void(const base::string16&, const base::string16&));
DISALLOW_COPY_AND_ASSIGN(MockHttpAuthObserver);
};
// Invokes the password store consumer with a single copy of |form|.
ACTION_P(InvokeConsumer, form) {
std::vector<std::unique_ptr<PasswordForm>> result;
result.push_back(std::make_unique<PasswordForm>(form));
arg0->OnGetPasswordStoreResults(std::move(result));
}
ACTION(InvokeEmptyConsumerWithForms) {
arg0->OnGetPasswordStoreResults(std::vector<std::unique_ptr<PasswordForm>>());
}
} // namespace
class HttpAuthManagerTest : public testing::Test {
public:
HttpAuthManagerTest() = default;
~HttpAuthManagerTest() override = default;
protected:
void SetUp() override {
store_ = new testing::StrictMock<MockPasswordStore>;
ASSERT_TRUE(store_->Init(nullptr));
ON_CALL(client_, GetProfilePasswordStore())
.WillByDefault(Return(store_.get()));
EXPECT_CALL(*store_, GetSiteStatsImpl(_)).Times(AnyNumber());
httpauth_manager_.reset(new HttpAuthManagerImpl(&client_));
EXPECT_CALL(*store_, IsAbleToSavePasswords()).WillRepeatedly(Return(true));
ON_CALL(client_, AutofillHttpAuth(_, _))
.WillByDefault(
Invoke(httpauth_manager_.get(), &HttpAuthManagerImpl::Autofill));
}
void TearDown() override {
store_->ShutdownOnUIThread();
store_ = nullptr;
}
HttpAuthManagerImpl* httpauth_manager() { return httpauth_manager_.get(); }
base::test::TaskEnvironment task_environment_;
scoped_refptr<MockPasswordStore> store_;
testing::NiceMock<MockPasswordManagerClient> client_;
std::unique_ptr<HttpAuthManagerImpl> httpauth_manager_;
};
TEST_F(HttpAuthManagerTest, HttpAuthFilling) {
for (bool filling_enabled : {false, true}) {
SCOPED_TRACE(testing::Message("filling_enabled=") << filling_enabled);
EXPECT_CALL(client_, IsFillingEnabled(_))
.WillRepeatedly(Return(filling_enabled));
PasswordForm observed_form;
observed_form.scheme = PasswordForm::Scheme::kBasic;
observed_form.origin = GURL("http://proxy.com/");
observed_form.signon_realm = "proxy.com/realm";
PasswordForm stored_form = observed_form;
stored_form.username_value = ASCIIToUTF16("user");
stored_form.password_value = ASCIIToUTF16("1234");
MockHttpAuthObserver observer;
PasswordStoreConsumer* consumer = nullptr;
EXPECT_CALL(*store_, GetLogins(_, _)).WillOnce(SaveArg<1>(&consumer));
httpauth_manager()->SetObserverAndDeliverCredentials(&observer,
observed_form);
EXPECT_CALL(observer, OnAutofillDataAvailable(ASCIIToUTF16("user"),
ASCIIToUTF16("1234")))
.Times(filling_enabled);
ASSERT_TRUE(consumer);
std::vector<std::unique_ptr<PasswordForm>> result;
result.push_back(std::make_unique<PasswordForm>(stored_form));
consumer->OnGetPasswordStoreResults(std::move(result));
testing::Mock::VerifyAndClearExpectations(&store_);
httpauth_manager()->DetachObserver(&observer);
}
}
TEST_F(HttpAuthManagerTest, HttpAuthSaving) {
for (bool filling_and_saving_enabled : {true, false}) {
SCOPED_TRACE(testing::Message("filling_and_saving_enabled=")
<< filling_and_saving_enabled);
EXPECT_CALL(client_, IsSavingAndFillingEnabled(_))
.WillRepeatedly(Return(filling_and_saving_enabled));
PasswordForm observed_form;
observed_form.scheme = PasswordForm::Scheme::kBasic;
observed_form.origin = GURL("http://proxy.com/");
observed_form.signon_realm = "proxy.com/realm";
MockHttpAuthObserver observer;
EXPECT_CALL(*store_, GetLogins(_, _))
.WillRepeatedly(WithArg<1>(InvokeEmptyConsumerWithForms()));
// Initiate creating a form manager.
httpauth_manager()->SetObserverAndDeliverCredentials(&observer,
observed_form);
// Emulate that http auth credentials submitted.
PasswordForm submitted_form = observed_form;
submitted_form.username_value = ASCIIToUTF16("user");
submitted_form.password_value = ASCIIToUTF16("1234");
httpauth_manager()->OnPasswordFormSubmitted(submitted_form);
httpauth_manager()->OnPasswordFormDismissed();
// Expect save prompt on successful submission.
std::unique_ptr<PasswordFormManagerForUI> form_manager_to_save;
EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr())
.Times(filling_and_saving_enabled ? 1 : 0);
httpauth_manager()->OnDidFinishMainFrameNavigation();
testing::Mock::VerifyAndClearExpectations(&client_);
httpauth_manager()->DetachObserver(&observer);
}
}
TEST_F(HttpAuthManagerTest, NavigationWithoutSubmission) {
EXPECT_CALL(client_, IsSavingAndFillingEnabled(_))
.WillRepeatedly(Return(true));
PasswordForm observed_form;
observed_form.scheme = PasswordForm::Scheme::kBasic;
observed_form.origin = GURL("http://proxy.com/");
observed_form.signon_realm = "proxy.com/realm";
MockHttpAuthObserver observer;
EXPECT_CALL(*store_, GetLogins(_, _))
.WillRepeatedly(WithArg<1>(InvokeEmptyConsumerWithForms()));
// Initiate creating a form manager.
httpauth_manager()->SetObserverAndDeliverCredentials(&observer,
observed_form);
// Expect no prompt, since no submission was happened.
EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr()).Times(0);
httpauth_manager()->OnDidFinishMainFrameNavigation();
httpauth_manager()->DetachObserver(&observer);
}
TEST_F(HttpAuthManagerTest, NavigationWhenMatchingNotReady) {
EXPECT_CALL(client_, IsSavingAndFillingEnabled).WillRepeatedly(Return(true));
PasswordForm observed_form;
observed_form.scheme = PasswordForm::Scheme::kBasic;
observed_form.origin = GURL("http://proxy.com/");
observed_form.signon_realm = "proxy.com/realm";
MockHttpAuthObserver observer;
// The password store is queried but it's slow and won't respond.
EXPECT_CALL(*store_, GetLogins);
// Initiate creating a form manager.
httpauth_manager()->SetObserverAndDeliverCredentials(&observer,
observed_form);
PasswordForm submitted_form = observed_form;
submitted_form.username_value = ASCIIToUTF16("user");
submitted_form.password_value = ASCIIToUTF16("1234");
httpauth_manager()->OnPasswordFormSubmitted(submitted_form);
httpauth_manager()->OnPasswordFormDismissed();
// Expect no prompt as the password store didn't reply.
EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr()).Times(0);
httpauth_manager()->OnDidFinishMainFrameNavigation();
httpauth_manager()->DetachObserver(&observer);
}
} // namespace password_manager
| endlessm/chromium-browser | components/password_manager/core/browser/http_auth_manager_unittest.cc | C++ | bsd-3-clause | 9,586 |
# VIVO: Connect, Share, Discover
[](https://github.com/vivo-project/VIVO/actions?query=workflow%3ABuild) [](https://github.com/vivo-project/VIVO/actions?query=workflow%3ADeploy) [](https://doi.org/10.5281/zenodo.2639713)
VIVO is an open source semantic web tool for research discovery -- finding people and the research they do.
VIVO supports editing, searching, browsing and visualizing research activity in order to discover people, programs,
facilities, funding, scholarly works and events. VIVO's search returns results faceted by type for rapid retrieval of
desired information across disciplines.
## Resources
### VIVO Project web site
http://vivoweb.org/
### VIVO Project Wiki
https://wiki.lyrasis.org/display/VIVO/
### Installation Instructions
Installation instructions for the latest release can be found at this location on the wiki:
https://wiki.lyrasis.org/display/VIVODOC112x/Installing+VIVO
### Docker
VIVO docker container is available at [vivoweb/vivo](https://hub.docker.com/repository/docker/vivoweb/vivo) with accompanying [vivoweb/vivo-solr](https://hub.docker.com/repository/docker/vivoweb/vivo-solr). These can be used independently or with docker-compose.
### Docker Compose
Docker Compose environment variables:
.env defaults
```
LOCAL_VIVO_HOME=./vivo-home
RESET_HOME=false
RESET_CORE=false
```
- `LOCAL_VIVO_HOME`: VIVO home directory on your host machine which will mount to volume in docker container. Set this environment variable to persist your VIVO data on your host machine.
- `RESET_HOME`: Convenience to reset VIVO home when starting container. **Caution**, will delete local configuration, content, and configuration model.
- `RESET_CORE`: Convenience to reset VIVO Solr core when starting container. **Caution**, will require complete reindex.
Before building VIVO, you will also need to clone (and switch to the same branch, if other than main) of [Vitro](https://github.com/vivo-project/Vitro). The Vitro project must be cloned to a sibling directory next to VIVO so that it can be found during the build. You will also need to clone (and switch to the appropriate branch) of [Vitro-languages](https://github.com/vivo-project/Vitro-languages) and [VIVO-languages](https://github.com/vivo-project/VIVO-languages).
Build and start VIVO.
1. In Vitro-languages, run:
```
mvn install
```
2. In VIVO-languages, run:
```
mvn install
```
3. In VIVO (with Vitro cloned alongside it), run:
```
mvn clean package -s installer/example-settings.xml
docker-compose up
```
### Docker Image
To build and run local Docker image.
```
docker build -t vivoweb/vivo:development .
docker run -p 8080:8080 vivoweb/vivo:development
```
## Contact us
There are several ways to contact the VIVO community.
Whatever your interest, we would be pleased to hear from you.
### Contact form
http://vivoweb.org/support/user-feedback
### Mailing lists
#### [vivo-all](https://groups.google.com/forum/#!forum/vivo-all)
This updates list provides news to the VIVO community of interest to all.
#### [vivo-community](https://groups.google.com/forum/#!forum/vivo-community)
Join the VIVO community! Here you'll find non-technical discussion regarding participation, the VIVO
conference, policy, project management, outreach, and engagement.
#### [vivo-tech](https://groups.google.com/forum/#!forum/vivo-tech)
The best place to get your hands dirty in the VIVO Project.
Developers and implementers frequent this list to get the latest on feature design,
development, implementation, and testing.
## Contributing Code
If you would like to contribute code to the VIVO project, please open a ticket
in our [JIRA](https://jira.lyrasis.org/projects/VIVO), and prepare a
pull request that references your ticket. Contributors welcome!
## Citing VIVO
If you are using VIVO in your publications or projects, please cite the software paper in the Journal of Open Source Software:
* Conlon et al., (2019). VIVO: a system for research discovery. Journal of Open Source Software, 4(39), 1182, https://doi.org/10.21105/joss.01182
### BibTeX
```tex
@article{Conlon2019,
doi = {10.21105/joss.01182},
url = {https://doi.org/10.21105/joss.01182},
year = {2019},
publisher = {The Open Journal},
volume = {4},
number = {39},
pages = {1182},
author = {Michael Conlon and Andrew Woods and Graham Triggs and Ralph O'Flinn and Muhammad Javed and Jim Blake and Benjamin Gross and Qazi Asim Ijaz Ahmad and Sabih Ali and Martin Barber and Don Elsborg and Kitio Fofack and Christian Hauschke and Violeta Ilik and Huda Khan and Ted Lawless and Jacob Levernier and Brian Lowe and Jose Martin and Steve McKay and Simon Porter and Tatiana Walther and Marijane White and Stefan Wolff and Rebecca Younes},
title = {{VIVO}: a system for research discovery},
journal = {Journal of Open Source Software}
}
| vivo-project/VIVO | README.md | Markdown | bsd-3-clause | 5,051 |
#!/bin/bash
# define helpers
source_dir=~/.osx-bootstrap
if [[ ! -f ~/.ssh/id_rsa ]]; then
echo ''
echo '##### Please enter your github username: '
read github_user
echo '##### Please enter your github email address: '
read github_email
# setup github
if [[ $github_user && $github_email ]]; then
# setup config
git config --global user.name $github_user
git config --global user.email $github_email
git config --global github.user $github_user
git config --global github.token your_token_here
git config --global color.ui true
git config --global push.default current
# sublime support
# git config --global core.editor "subl -w"
# set rsa key
curl -s -O http://github-media-downloads.s3.amazonaws.com/osx/git-credential-osxkeychain
chmod u+x git-credential-osxkeychain
sudo mv git-credential-osxkeychain "$(dirname $(which git))/git-credential-osxkeychain"
git config --global credential.helper osxkeychain
# generate ssh key
cd ~/.ssh
ssh-keygen -t rsa -C $github_email
pbcopy < ~/.ssh/id_rsa.pub
echo ''
echo '##### The following rsa key has been copied to your clipboard: '
cat ~/.ssh/id_rsa.pub
echo '##### Follow step 4 to complete: https://help.github.com/articles/generating-ssh-keys'
ssh -T [email protected]
fi
fi
| divio/osx-bootstrap | core/github.sh | Shell | bsd-3-clause | 1,443 |
#if !(NET35 || NET20 || WINDOWS_PHONE)
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Newtonsoft.Json.Utilities
{
internal sealed class DynamicProxyMetaObject<T> : DynamicMetaObject
{
private readonly DynamicProxy<T> _proxy;
private readonly bool _dontFallbackFirst;
internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy<T> proxy, bool dontFallbackFirst)
: base(expression, BindingRestrictions.Empty, value)
{
_proxy = proxy;
_dontFallbackFirst = dontFallbackFirst;
}
private new T Value { get { return (T)base.Value; } }
private bool IsOverridden(string method)
{
return _proxy.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance).Cast<MethodInfo>()
.Any(info =>
// check that the method overrides the original on DynamicObjectProxy
info.DeclaringType != typeof(DynamicProxy<T>) &&
info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy<T>));
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
return IsOverridden("TryGetMember")
? CallMethodWithResult("TryGetMember", binder, NoArgs, e => binder.FallbackGetMember(this, e))
: base.BindGetMember(binder);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
return IsOverridden("TrySetMember")
? CallMethodReturnLast("TrySetMember", binder, GetArgs(value), e => binder.FallbackSetMember(this, value, e))
: base.BindSetMember(binder, value);
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder)
{
return IsOverridden("TryDeleteMember")
? CallMethodNoResult("TryDeleteMember", binder, NoArgs, e => binder.FallbackDeleteMember(this, e))
: base.BindDeleteMember(binder);
}
public override DynamicMetaObject BindConvert(ConvertBinder binder)
{
return IsOverridden("TryConvert")
? CallMethodWithResult("TryConvert", binder, NoArgs, e => binder.FallbackConvert(this, e))
: base.BindConvert(binder);
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
if (!IsOverridden("TryInvokeMember"))
return base.BindInvokeMember(binder, args);
//
// Generate a tree like:
//
// {
// object result;
// TryInvokeMember(payload, out result)
// ? result
// : TryGetMember(payload, out result)
// ? FallbackInvoke(result)
// : fallbackResult
// }
//
// Then it calls FallbackInvokeMember with this tree as the
// "error", giving the language the option of using this
// tree or doing .NET binding.
//
Fallback fallback = e => binder.FallbackInvokeMember(this, args, e);
DynamicMetaObject call = BuildCallMethodWithResult(
"TryInvokeMember",
binder,
GetArgArray(args),
BuildCallMethodWithResult(
"TryGetMember",
new GetBinderAdapter(binder),
NoArgs,
fallback(null),
e => binder.FallbackInvoke(e, args, null)
),
null
);
return _dontFallbackFirst ? call : fallback(call);
}
public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args)
{
return IsOverridden("TryCreateInstance")
? CallMethodWithResult("TryCreateInstance", binder, GetArgArray(args), e => binder.FallbackCreateInstance(this, args, e))
: base.BindCreateInstance(binder, args);
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args)
{
return IsOverridden("TryInvoke")
? CallMethodWithResult("TryInvoke", binder, GetArgArray(args), e => binder.FallbackInvoke(this, args, e))
: base.BindInvoke(binder, args);
}
public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg)
{
return IsOverridden("TryBinaryOperation")
? CallMethodWithResult("TryBinaryOperation", binder, GetArgs(arg), e => binder.FallbackBinaryOperation(this, arg, e))
: base.BindBinaryOperation(binder, arg);
}
public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder)
{
return IsOverridden("TryUnaryOperation")
? CallMethodWithResult("TryUnaryOperation", binder, NoArgs, e => binder.FallbackUnaryOperation(this, e))
: base.BindUnaryOperation(binder);
}
public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
return IsOverridden("TryGetIndex")
? CallMethodWithResult("TryGetIndex", binder, GetArgArray(indexes), e => binder.FallbackGetIndex(this, indexes, e))
: base.BindGetIndex(binder, indexes);
}
public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
return IsOverridden("TrySetIndex")
? CallMethodReturnLast("TrySetIndex", binder, GetArgArray(indexes, value), e => binder.FallbackSetIndex(this, indexes, value, e))
: base.BindSetIndex(binder, indexes, value);
}
public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes)
{
return IsOverridden("TryDeleteIndex")
? CallMethodNoResult("TryDeleteIndex", binder, GetArgArray(indexes), e => binder.FallbackDeleteIndex(this, indexes, e))
: base.BindDeleteIndex(binder, indexes);
}
private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion);
private readonly static Expression[] NoArgs = new Expression[0];
private static Expression[] GetArgs(params DynamicMetaObject[] args)
{
return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray();
}
private static Expression[] GetArgArray(DynamicMetaObject[] args)
{
return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)) };
}
private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value)
{
return new Expression[]
{
Expression.NewArrayInit(typeof(object), GetArgs(args)),
Expression.Convert(value.Expression, typeof(object))
};
}
private static ConstantExpression Constant(DynamicMetaObjectBinder binder)
{
Type t = binder.GetType();
while (!t.IsVisible)
t = t.BaseType;
return Expression.Constant(binder, t);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic that returns a result
/// </summary>
private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke = null)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
DynamicMetaObject callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke)
{
//
// Build a new expression like:
// {
// object result;
// TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs.Add(result);
DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty);
// Need to add a conversion if calling TryConvert
if (binder.ReturnType != typeof (object))
{
UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType);
// will always be a cast or unbox
resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions);
}
if (fallbackInvoke != null)
resultMetaObject = fallbackInvoke(resultMetaObject);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] {result},
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
resultMetaObject.Expression,
fallbackResult.Expression,
binder.ReturnType
)
),
GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions)
);
return callDynamic;
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
/// </summary>
private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof (T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs[args.Length + 1] = Expression.Assign(result, callArgs[args.Length + 1]);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result },
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
result,
fallbackResult.Expression,
typeof(object)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
/// </summary>
private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
//
// Build a new expression like:
// if (TryDeleteMember(payload)) { } else { fallbackResult }
//
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
Expression.Empty(),
fallbackResult.Expression,
typeof (void)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
/// <summary>
/// Returns a Restrictions object which includes our current restrictions merged
/// with a restriction limiting our type
/// </summary>
private BindingRestrictions GetRestrictions()
{
return (Value == null && HasValue)
? BindingRestrictions.GetInstanceRestriction(Expression, null)
: BindingRestrictions.GetTypeRestriction(Expression, LimitType);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _proxy.GetDynamicMemberNames(Value);
}
// It is okay to throw NotSupported from this binder. This object
// is only used by DynamicObject.GetMember--it is not expected to
// (and cannot) implement binding semantics. It is just so the DO
// can use the Name and IgnoreCase properties.
private sealed class GetBinderAdapter : GetMemberBinder
{
internal GetBinderAdapter(InvokeMemberBinder binder) :
base(binder.Name, binder.IgnoreCase)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotSupportedException();
}
}
}
}
#endif | hawkstalion/Tog-Mobile | Tog/json.net/Source/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs | C# | bsd-3-clause | 14,749 |
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.in by autoheader. */
/* Whether to build xhprof as dynamic module */
#define COMPILE_DL_XHPROF 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if your C compiler doesn't accept -c and -o together. */
/* #undef NO_MINUS_C_MINUS_O */
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT ""
/* Define to the full name of this package. */
#define PACKAGE_NAME ""
/* Define to the full name and version of this package. */
#define PACKAGE_STRING ""
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME ""
/* Define to the version of this package. */
#define PACKAGE_VERSION ""
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
| erictj/protean | modules/thirdparty/xhprof/extension/config.h | C | bsd-3-clause | 1,655 |
'''
Given a number, find the next higher number using only the digits in the given number.
For example if the given number is 1234, next higher number with same digits is 1243
'''
def FindNext(num):
number = str(num)
length = len(number)
for i in range(length-2,-1,-1):
current = number[i]
right = number[i+1]
if current < right:
temp = sorted(number[i:])
Next = temp[temp.index(current)+1]
temp.remove(Next)
temp = ''.join(temp)
return int(number[:i]+Next+temp)
return num
| jenniferwx/Programming_Practice | FindNextHigherNumberWithSameDigits.py | Python | bsd-3-clause | 578 |
package manifest
import (
"encoding/json"
"fmt"
"log"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/fatih/color"
"github.com/servehub/serve/manifest/processor"
"github.com/servehub/utils"
"github.com/servehub/utils/gabs"
)
type Manifest struct {
tree *gabs.Container
}
func (m Manifest) String() string {
return m.tree.StringIndent("", " ")
}
func (m Manifest) Unwrap() interface{} {
return m.tree.Data()
}
func (m Manifest) Has(path string) bool {
v := m.tree.Path(path).Data()
return v != nil && v != ""
}
func (m Manifest) GetString(path string) string {
return fmt.Sprintf("%v", m.tree.Path(path).Data())
}
func (m Manifest) GetStringOr(path string, defaultVal string) string {
if m.tree.ExistsP(path) {
return m.GetString(path)
}
return defaultVal
}
func (m Manifest) GetFloat(path string) float64 {
f, err := strconv.ParseFloat(m.GetString(path), 64)
if err != nil {
log.Fatalf("Error on parse float64 '%v' from: %v", path, m.GetString(path))
}
return f
}
func (m Manifest) GetInt(path string) int {
i, err := strconv.Atoi(m.GetString(path))
if err != nil {
log.Fatalf("Error on parse integer '%v' from: %v", path, m.GetString(path))
}
return i
}
func (m Manifest) GetIntOr(path string, defaultVal int) int {
if m.tree.ExistsP(path) {
return m.GetInt(path)
}
return defaultVal
}
func (m Manifest) GetBool(path string) bool {
return strings.ToLower(m.GetString(path)) == "true"
}
func (m Manifest) GetMap(path string) map[string]Manifest {
out := make(map[string]Manifest)
tree := m.tree
if len(path) > 0 && path != "." && path != "/" {
tree = m.tree.Path(path)
}
mmap, err := tree.ChildrenMap()
if err != nil {
log.Fatalf("Error get map '%v' from: %v. Error: %s", path, m.tree.Path(path).Data(), err)
}
for k, v := range mmap {
out[k] = Manifest{v}
}
return out
}
func (m Manifest) GetArray(path string) []Manifest {
out := make([]Manifest, 0)
arr, err := m.tree.Path(path).Children()
if err != nil {
log.Fatalf("Error get array `%v` from: %v", path, m.tree.Path(path).Data())
}
for _, v := range arr {
out = append(out, Manifest{v})
}
return out
}
func (m Manifest) GetArrayForce(path string) []interface{} {
out := make([]interface{}, 0)
arr, err := m.tree.Path(path).Children()
if err != nil && m.tree.ExistsP(path) {
arr = append(arr, m.tree.Path(path))
}
for _, v := range arr {
out = append(out, v.Data())
}
return out
}
func (m Manifest) GetTree(path string) Manifest {
return Manifest{m.tree.Path(path)}
}
func (m Manifest) Set(path string, value interface{}) {
m.tree.SetP(value, path)
}
func (m Manifest) ArrayAppend(path string, value interface{}) {
m.tree.ArrayAppendP(value, path)
}
func (m Manifest) FindPlugins(plugin string) ([]PluginData, error) {
tree := m.tree.Path(plugin)
result := make([]PluginData, 0)
if tree.Data() == nil {
return nil, fmt.Errorf("Plugin `%s` not found in manifest!", plugin)
}
if _, ok := tree.Data().([]interface{}); ok {
arr, _ := tree.Children()
for _, item := range arr {
if _, ok := item.Data().(string); ok {
result = append(result, makePluginPair(plugin, item))
} else if res, err := item.ChildrenMap(); err == nil {
if len(res) == 1 {
for subplugin, data := range res {
result = append(result, makePluginPair(plugin+"."+subplugin, data))
break
}
} else if len(res) == 0 && !PluginRegestry.Has(plugin) {
// skip subplugin with empty data
} else {
result = append(result, makePluginPair(plugin, item))
}
}
}
} else if PluginRegestry.Has(plugin) {
result = append(result, makePluginPair(plugin, tree))
} else {
log.Println(color.YellowString("Plugins for `%s` section not specified, skip...", plugin))
}
return result, nil
}
func (m Manifest) DelTree(path string) error {
return m.tree.DeleteP(path)
}
func (m Manifest) GetPluginWithData(plugin string) PluginData {
return makePluginPair(plugin, m.tree)
}
var envNameRegex = regexp.MustCompile("\\W")
func (m Manifest) ToEnvMap(prefix string) map[string]string {
result := make(map[string]string)
if children, err := m.tree.ChildrenMap(); err == nil {
for k, child := range children {
result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strings.ToUpper(envNameRegex.ReplaceAllString(k, "_"))+"_"))
}
} else if children, err := m.tree.Children(); err == nil {
for i, child := range children {
result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strconv.Itoa(i)+"_"))
}
} else if m.tree.Data() != nil {
result[prefix[:len(prefix)-1]] = fmt.Sprintf("%v", m.tree.Data())
}
return result
}
func Load(path string, vars map[string]string) *Manifest {
tree, err := gabs.LoadYamlFile(path)
if err != nil {
log.Fatalln("Error on load file:", err)
}
for k, v := range vars {
tree.Set(v, "vars", k)
}
for _, proc := range processor.GetAll() {
if err := proc.Process(tree); err != nil {
log.Fatalf("Error in processor '%v': %v. \n\nManifest: %s", reflect.ValueOf(proc).Type().Name(), err, tree.StringIndent("", " "))
}
}
return &Manifest{tree}
}
func LoadJSON(path string) *Manifest {
tree, err := gabs.ParseJSONFile(path)
if err != nil {
log.Fatalf("Error on load json file '%s': %v\n", path, err)
}
return &Manifest{tree}
}
func ParseJSON(json string) *Manifest {
tree, err := gabs.ParseJSON([]byte(json))
if err != nil {
log.Fatalf("Error on parse json '%s': %v\n", json, err)
}
return &Manifest{tree}
}
func makePluginPair(plugin string, data *gabs.Container) PluginData {
if s, ok := data.Data().(string); ok {
obj := gabs.New()
ns := strings.Split(plugin, ".")
obj.Set(s, ns[len(ns)-1])
data = obj
} else {
var cpy interface{}
bs, _ := json.Marshal(data.Data())
json.Unmarshal(bs, &cpy)
data.Set(cpy)
}
return PluginData{plugin, PluginRegestry.Get(plugin), Manifest{data}}
}
| servehub/serve | manifest/manifest.go | GO | bsd-3-clause | 5,887 |
<?php
return array (
'This user account is not approved yet!' => 'Tento účet ještě není aktivován!',
'User not found!' => 'Uživatel nebyl nalezen!',
'You need to login to view this user profile!' => 'Abyste mohli prohlížet tento profil, je potřeba se nejdříve přihlásit.',
);
| LeonidLyalin/vova | common/humhub/protected/humhub/modules/user/messages/cs/behaviors_ProfileControllerBehavior.php | PHP | bsd-3-clause | 296 |
#region copyright
// Copyright (c) 2012, TIGWI
// All rights reserved.
// Distributed under BSD 2-Clause license
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Tigwi.UI.Models.Storage
{
using Tigwi.Storage.Library;
public class DuplicateUserException : Exception
{
public DuplicateUserException(string login, UserAlreadyExists innerException)
: base("This username is already taken.", innerException)
{
}
}
public class UserNotFoundException : Exception
{
public UserNotFoundException(string login, UserNotFound innerException)
: base("There is no user with the given login `" + login + "'.", innerException)
{
}
public UserNotFoundException(Guid id, UserNotFound innerException)
: base("There is no user with the given ID `" + id + "'.", innerException)
{
}
}
public class DuplicateAccountException : Exception
{
public DuplicateAccountException(string name, AccountAlreadyExists innerException)
: base("There is already an account with the given name `" + name + "'.", innerException)
{
}
}
public class AccountNotFoundException : Exception
{
public AccountNotFoundException(string name, AccountNotFound innerException)
: base("There is no account with the given name `" + name + "'.", innerException)
{
}
}
} | ismaelbelghiti/Tigwi | Core/Tigwi.UI/Models/Storage/StorageException.cs | C# | bsd-3-clause | 1,512 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="pandoc" />
<meta name="author" content="Copyright 2015 Intel Corporation All Rights Reserved." />
<title>IoT Services Orchestration Layer</title>
<style type="text/css">code{white-space: pre;}</style>
<link rel="stylesheet" href="styles/style.css" type="text/css" />
</head>
<body>
<div id="header">
<h1 class="title">IoT Services Orchestration Layer</h1>
<h2 class="author">Copyright 2015 Intel Corporation All Rights Reserved.</h2>
</div>
<div id="TOC">
<ul>
<li><a href="#email">email</a><ul>
<li><a href="#sendmail">sendmail</a><ul>
<li><a href="#description">Description</a></li>
<li><a href="#config">Config</a></li>
<li><a href="#inport">Inport</a></li>
<li><a href="#outport">Outport</a></li>
<li><a href="#example">Example</a></li>
</ul></li>
</ul></li>
</ul>
</div>
<h1 id="email">email</h1>
<h2 id="sendmail">sendmail</h2>
<h3 id="description">Description</h3>
<p>Send a message to the recipient via an email service provider.</p>
<p>This service is implemented by <a href="https://github.com/nodemailer/nodemailer">nodemailer</a></p>
<p>At this stage, only supports plain-text body, and don't support the network proxy.</p>
<h3 id="config">Config</h3>
<p><code>service</code>: String. your email service provider, such as Gmail,QQ,126,163,Hotmail,iCloud, see <a href="https://github.com/nodemailer/nodemailer-wellknown/blob/master/services.json">nodemailer-wellknown</a> for details.</p>
<p><code>account</code>: String. the registered username of your email, probably it is your email address.</p>
<p><code>passwd</code>: String. the password for the username (password for mail client, might be different from login's)</p>
<p><code>receiver</code>: String. the email address of recipient.</p>
<h3 id="inport">Inport</h3>
<p><code>text</code>: String. the content of email.</p>
<p><code>subject</code>: String. the subject of email.</p>
<h3 id="outport">Outport</h3>
<p><code>status</code>: Boolean. output <em>true</em> if send email successfully, otherwise output <em>false</em>.</p>
<h3 id="example">Example</h3>
<div class="figure">
<img src="./pic/email.jpg" />
</div>
<p>In this case, user([email protected]) may send an email to [email protected], which subject as “this is a title” and text as “this is a text”.</p>
</body>
</html>
| 01org/intel-iot-services-orchestration-layer | doc/html/builtin/email.html | HTML | bsd-3-clause | 2,603 |
import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created']
def summary(self):
"""Generates summary data of today's state"""
self.get_data()
highlight = self.highlight
last_item = self.data[-1]
output = {}
output['app'] = self.app or 'ALL'
data = last_item['locales']
if self.app:
get_item = lambda x: x['apps'][self.app]
else:
get_item = lambda x: x
apps = data.items()[0][1]['apps'].keys()
apps.sort()
output['apps'] = apps
items = [item for item in data.items() if item[0] not in highlight]
hitems = [item for item in data.items() if item[0] in highlight]
highlighted = []
if hitems:
for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
highlighted.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['highlighted'] = highlighted
locales = []
for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
locales.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['locales'] = locales
output['created'] = self.created
return output
def _mark_movement(self, data):
"""For each item, converts to a tuple of (movement, item)"""
ret = []
prev_day = None
for i, day in enumerate(data):
if i == 0:
ret.append(('', day))
prev_day = day
continue
if prev_day > day:
item = ('down', day)
elif prev_day < day:
item = ('up', day)
else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
app = self.app
# Get a list of the locales we'll iterate through
locales = sorted(data[-1]['locales'].keys())
num_days = 14
# Truncate the data to what we want to look at
data = data[-num_days:]
if app:
get_data = lambda x: x['apps'][app]['percent']
else:
get_data = lambda x: x['percent']
hlocales = [loc for loc in locales if loc in highlight]
locales = [loc for loc in locales if loc not in highlight]
output = {}
output['app'] = self.app or 'All'
output['headers'] = [item['created'] for item in data]
output['highlighted'] = sorted(
(loc, self._mark_movement(get_data(day['locales'][loc]) for day in data))
for loc in hlocales
)
output['locales'] = sorted(
(loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data))
for loc in locales
)
output['created'] = self.created
return output
| willkg/postatus | postatus/status.py | Python | bsd-3-clause | 4,559 |
<?php
/**
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cloud_StorageService
* @subpackage Adapter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* namespace
*/
namespace Zend\Cloud\StorageService\Adapter;
use Traversable,
Zend\Cloud\StorageService\Adapter,
Zend\Cloud\StorageService\Exception,
Zend\Service\Rackspace\Exception as RackspaceException,
Zend\Service\Rackspace\Files as RackspaceFile,
Zend\Stdlib\ArrayUtils;
/**
* Adapter for Rackspace cloud storage
*
* @category Zend
* @package Zend_Cloud_StorageService
* @subpackage Adapter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Rackspace implements Adapter
{
const USER = 'user';
const API_KEY = 'key';
const REMOTE_CONTAINER = 'container';
const DELETE_METADATA_KEY = 'ZF_metadata_deleted';
/**
* The Rackspace adapter
* @var RackspaceFile
*/
protected $rackspace;
/**
* Container in which files are stored
* @var string
*/
protected $container = 'default';
/**
* Constructor
*
* @param array|Traversable $options
* @return void
*/
function __construct($options = array())
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (!is_array($options) || empty($options)) {
throw new Exception\InvalidArgumentException('Invalid options provided');
}
try {
$this->rackspace = new RackspaceFile($options[self::USER], $options[self::API_KEY]);
} catch (RackspaceException $e) {
throw new Exception\RuntimeException('Error on create: '.$e->getMessage(), $e->getCode(), $e);
}
if (isset($options[self::HTTP_ADAPTER])) {
$this->rackspace->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]);
}
if (!empty($options[self::REMOTE_CONTAINER])) {
$this->container = $options[self::REMOTE_CONTAINER];
}
}
/**
* Get an item from the storage service.
*
* @param string $path
* @param array $options
* @return mixed
*/
public function fetchItem($path, $options = null)
{
$item = $this->rackspace->getObject($this->container,$path, $options);
if (!$this->rackspace->isSuccessful() && ($this->rackspace->getErrorCode()!='404')) {
throw new Exception\RuntimeException('Error on fetch: '.$this->rackspace->getErrorMsg());
}
if (!empty($item)) {
return $item->getContent();
} else {
return false;
}
}
/**
* Store an item in the storage service.
*
* @param string $destinationPath
* @param mixed $data
* @param array $options
* @return void
*/
public function storeItem($destinationPath, $data, $options = null)
{
$this->rackspace->storeObject($this->container,$destinationPath,$data,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on store: '.$this->rackspace->getErrorMsg());
}
}
/**
* Delete an item in the storage service.
*
* @param string $path
* @param array $options
* @return void
*/
public function deleteItem($path, $options = null)
{
$this->rackspace->deleteObject($this->container,$path);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on delete: '.$this->rackspace->getErrorMsg());
}
}
/**
* Copy an item in the storage service to a given path.
*
* @param string $sourcePath
* @param string $destination path
* @param array $options
* @return void
*/
public function copyItem($sourcePath, $destinationPath, $options = null)
{
$this->rackspace->copyObject($this->container,$sourcePath,$this->container,$destinationPath,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on copy: '.$this->rackspace->getErrorMsg());
}
}
/**
* Move an item in the storage service to a given path.
* WARNING: This operation is *very* expensive for services that do not
* support moving an item natively.
*
* @param string $sourcePath
* @param string $destination path
* @param array $options
* @return void
*/
public function moveItem($sourcePath, $destinationPath, $options = null)
{
try {
$this->copyItem($sourcePath, $destinationPath, $options);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on move: '.$e->getMessage());
}
try {
$this->deleteItem($sourcePath);
} catch (Exception\RuntimeException $e) {
$this->deleteItem($destinationPath);
throw new Exception\RuntimeException('Error on move: '.$e->getMessage());
}
}
/**
* Rename an item in the storage service to a given name.
*
* @param string $path
* @param string $name
* @param array $options
* @return void
*/
public function renameItem($path, $name, $options = null)
{
throw new Exception\OperationNotAvailableException('Renaming not implemented');
}
/**
* Get a key/value array of metadata for the given path.
*
* @param string $path
* @param array $options
* @return array An associative array of key/value pairs specifying the metadata for this object.
* If no metadata exists, an empty array is returned.
*/
public function fetchMetadata($path, $options = null)
{
$result = $this->rackspace->getMetadataObject($this->container,$path);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on fetch metadata: '.$this->rackspace->getErrorMsg());
}
$metadata = array();
if (isset($result['metadata'])) {
$metadata = $result['metadata'];
}
// delete the self::DELETE_METADATA_KEY - this is a trick to remove all
// the metadata information of an object (see deleteMetadata).
// Rackspace doesn't have an API to remove the metadata of an object
unset($metadata[self::DELETE_METADATA_KEY]);
return $metadata;
}
/**
* Store a key/value array of metadata at the given path.
* WARNING: This operation overwrites any metadata that is located at
* $destinationPath.
*
* @param string $destinationPath
* @param array $metadata associative array specifying the key/value pairs for the metadata.
* @param array $options
* @return void
*/
public function storeMetadata($destinationPath, $metadata, $options = null)
{
$this->rackspace->setMetadataObject($this->container, $destinationPath, $metadata);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on store metadata: '.$this->rackspace->getErrorMsg());
}
}
/**
* Delete a key/value array of metadata at the given path.
*
* @param string $path
* @param array $metadata - An associative array specifying the key/value pairs for the metadata
* to be deleted. If null, all metadata associated with the object will
* be deleted.
* @param array $options
* @return void
*/
public function deleteMetadata($path, $metadata = null, $options = null)
{
if (empty($metadata)) {
$newMetadata = array(self::DELETE_METADATA_KEY => true);
try {
$this->storeMetadata($path, $newMetadata);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on delete metadata: '.$e->getMessage());
}
} else {
try {
$oldMetadata = $this->fetchMetadata($path);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on delete metadata: '.$e->getMessage());
}
$newMetadata = array_diff_assoc($oldMetadata, $metadata);
try {
$this->storeMetadata($path, $newMetadata);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on delete metadata: '.$e->getMessage());
}
}
}
/*
* Recursively traverse all the folders and build an array that contains
* the path names for each folder.
*
* @param string $path folder path to get the list of folders from.
* @param array& $resultArray reference to the array that contains the path names
* for each folder.
* @return void
*/
private function getAllFolders($path, &$resultArray)
{
if (!empty($path)) {
$options = array (
'prefix' => $path
);
}
$files = $this->rackspace->getObjects($this->container,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on get all folders: '.$this->rackspace->getErrorMsg());
}
$resultArray = array();
foreach ($files as $file) {
$resultArray[dirname($file->getName())] = true;
}
$resultArray = array_keys($resultArray);
}
/**
* Return an array of the items contained in the given path. The items
* returned are the files or objects that in the specified path.
*
* @param string $path
* @param array $options
* @return array
*/
public function listItems($path, $options = null)
{
if (!empty($path)) {
$options = array (
'prefix' => $path
);
}
$files = $this->rackspace->getObjects($this->container,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on list items: '.$this->rackspace->getErrorMsg());
}
$resultArray = array();
if (!empty($files)) {
foreach ($files as $file) {
$resultArray[] = $file->getName();
}
}
return $resultArray;
}
/**
* Get the concrete client.
*
* @return RackspaceFile
*/
public function getClient()
{
return $this->rackspace;
}
}
| dineshkummarc/zf2 | library/Zend/Cloud/StorageService/Adapter/Rackspace.php | PHP | bsd-3-clause | 11,465 |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package contenant la commande 'débarquer'."""
from math import sqrt
from primaires.interpreteur.commande.commande import Commande
from secondaires.navigation.constantes import *
class CmdDebarquer(Commande):
"""Commande 'debarquer'"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "debarquer", "debark")
self.nom_categorie = "navire"
self.aide_courte = "débarque du navire"
self.aide_longue = \
"Cette commande permet de débarquer du navire sur lequel " \
"on se trouve. On doit se trouver assez prêt d'une côte " \
"pour débarquer dessus."
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
salle = personnage.salle
if not hasattr(salle, "navire") or salle.navire is None:
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
navire = salle.navire
if navire.etendue is None:
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
personnage.agir("bouger")
# On va chercher la salle la plus proche
etendue = navire.etendue
# On cherche la salle de nagvire la plus proche
d_salle = None # la salle de destination
distance = 2
x, y, z = salle.coords.tuple()
for t_salle in etendue.cotes.values():
if t_salle.coords.z == z:
t_x, t_y, t_z = t_salle.coords.tuple()
t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2)
if t_distance < distance and t_salle.nom_terrain in \
TERRAINS_ACCOSTABLES:
d_salle = t_salle
distance = t_distance
if d_salle is None:
personnage << "|err|Aucun quai n'a pu être trouvé à " \
"proximité.|ff|"
return
personnage.salle = d_salle
personnage << "Vous sautez sur {}.".format(
d_salle.titre.lower())
personnage << d_salle.regarder(personnage)
d_salle.envoyer("{{}} arrive en sautant depuis {}.".format(
navire.nom), personnage)
salle.envoyer("{{}} saute sur {}.".format(
d_salle.titre.lower()), personnage)
importeur.hook["personnage:deplacer"].executer(
personnage, d_salle, None, 0)
if not hasattr(d_salle, "navire") or d_salle.navire is None:
personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \
"avec %amarre% %amarre:attacher%.")
| vlegoff/tsunami | src/secondaires/navigation/commandes/debarquer/__init__.py | Python | bsd-3-clause | 4,221 |
#include<iostream>
using namespace std;
int a[]={1,255,8,6,25,47,14,35,58,75,96,158,657};
const int len = sizeof(a)/sizeof(int);
int b[10][len+1] = { 0 }; //将b全部置0
void bucketSort(int a[]);//桶排序函数
void distributeElments(int a[],int b[10][len+1],int digits);
void collectElments(int a[],int b[10][len+1]);
int numOfDigits(int a[]);
void zeroBucket(int b[10][len+1]);//将b数组中的全部元素置0
int main()
{
cout<<"原始数组:";
for(int i=0;i<len;i++)
cout<<a[i]<<",";
cout<<endl;
bucketSort(a);
cout<<"排序后数组:";
for(int i=0;i<len;i++)
cout<<a[i]<<",";
cout<<endl;
return 0;
}
void bucketSort(int a[])
{
int digits=numOfDigits(a);
for(int i=1;i<=digits;i++)
{
distributeElments(a,b,i);
collectElments(a,b);
if(i!=digits)
zeroBucket(b);
}
}
int numOfDigits(int a[])
{
int largest=0;
for(int i=0;i<len;i++)//获取最大值
if(a[i]>largest)
largest=a[i];
int digits=0;//digits为最大值的位数
while(largest)
{
digits++;
largest/=10;
}
return digits;
}
void distributeElments(int a[],int b[10][len+1],int digits)
{
int divisor=10;//除数
for(int i=1;i<digits;i++)
divisor*=10;
for(int j=0;j<len;j++)
{
int numOfDigist=(a[j]%divisor-a[j]%(divisor/10))/(divisor/10);
//numOfDigits为相应的(divisor/10)位的值,如当divisor=10时,求的是个位数
int num=++b[numOfDigist][0];//用b中第一列的元素来储存每行中元素的个数
b[numOfDigist][num]=a[j];
}
}
void collectElments(int a[],int b[10][len+1])
{
int k=0;
for(int i=0;i<10;i++)
for(int j=1;j<=b[i][0];j++)
a[k++]=b[i][j];
}
void zeroBucket(int b[][len+1])
{
for(int i=0;i<10;i++)
for(int j=0;j<len+1;j++)
b[i][j]=0;
}
| 1106944911/leetcode | C++/bucketSort.cpp | C++ | bsd-3-clause | 1,907 |
/*
* ColorBasedROIExtractorRGB.h
*
* Created on: Dec 2, 2011
* Author: Pinaki Sunil Banerjee
*/
#ifndef BRICS_3D_COLORBASEDROIEXTRACTORRGB_H_
#define BRICS_3D_COLORBASEDROIEXTRACTORRGB_H_
#include "IFiltering.h"
#include <stdlib.h>
#include <cmath>
#include <iostream>
#include <stdio.h>
#include <stdint.h>
namespace brics_3d {
/**
* @brief Extracts subset of input point cloud based on color-properties in RGB color space
* @ingroup filtering
*/
class ColorBasedROIExtractorRGB : public IFiltering {
int red;
int green;
int blue;
double distanceThresholdMinimum;
double distanceThresholdMaximum;
public:
ColorBasedROIExtractorRGB();
virtual ~ColorBasedROIExtractorRGB();
void filter(PointCloud3D* originalPointCloud, PointCloud3D* resultPointCloud);
// void extractColorBasedROI(brics_3d::ColoredPointCloud3D *in_cloud, brics_3d::ColoredPointCloud3D *out_cloud);
// void extractColorBasedROI(brics_3d::ColoredPointCloud3D *in_cloud, brics_3d::PointCloud3D *out_cloud);
int getBlue() const
{
return blue;
}
double getDistanceThresholdMinimum() const
{
return distanceThresholdMinimum;
}
void setDistanceThresholdMinimum(double distanceThreshold)
{
this->distanceThresholdMinimum = distanceThreshold;
}
double getDistanceThresholdMaximum() const
{
return distanceThresholdMaximum;
}
void setDistanceThresholdMaximum(double distanceThreshold)
{
this->distanceThresholdMaximum = distanceThreshold;
}
int getGreen() const
{
return green;
}
int getRed() const
{
return red;
}
void setBlue(int blue)
{
this->blue = blue;
}
void setGreen(int green)
{
this->green = green;
}
void setRed(int red)
{
this->red = red;
}
};
}
#endif /* BRICS_3D_COLORBASEDROIEXTRACTORRGB_H_ */
| brics/brics_3d | src/brics_3d/algorithm/filtering/ColorBasedROIExtractorRGB.h | C | bsd-3-clause | 1,916 |
<!DOCTYPE html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>Phing API Documentation » \DataTypeHandler</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script><script src="../js/jquery.mousewheel.min.js" type="text/javascript"></script><script src="../js/bootstrap.js" type="text/javascript"></script><script src="../js/template.js" type="text/javascript"></script><script src="../js/prettify/prettify.min.js" type="text/javascript"></script><link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner"><div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></a><a class="brand" href="../index.html">Phing API Documentation</a><div class="nav-collapse"><ul class="nav">
<li class="dropdown">
<a href="#api" class="dropdown-toggle" data-toggle="dropdown">
API Documentation <b class="caret"></b></a><ul class="dropdown-menu">
<li><a>Packages</a></li>
<li><a href="../packages/Default.html"><i class="icon-folder-open"></i> Default</a></li>
<li><a href="../packages/JSMin.html"><i class="icon-folder-open"></i> JSMin</a></li>
<li><a href="../packages/Parallel.html"><i class="icon-folder-open"></i> Parallel</a></li>
<li><a href="../packages/Phing.html"><i class="icon-folder-open"></i> Phing</a></li>
<li><a href="../packages/phing.html"><i class="icon-folder-open"></i> phing</a></li>
</ul>
</li>
<li class="dropdown" id="charts-menu">
<a href="#charts" class="dropdown-toggle" data-toggle="dropdown">
Charts <b class="caret"></b></a><ul class="dropdown-menu"><li><a href="../graph_class.html"><i class="icon-list-alt"></i> Class hierarchy diagram</a></li></ul>
</li>
<li class="dropdown" id="reports-menu">
<a href="#reports" class="dropdown-toggle" data-toggle="dropdown">
Reports <b class="caret"></b></a><ul class="dropdown-menu">
<li><a href="../errors.html"><i class="icon-remove-sign"></i> Errors
<span class="label label-info">2573</span></a></li>
<li><a href="../markers.html"><i class="icon-map-marker"></i> Markers
<ul>
<li>todo
<span class="label label-info">15</span>
</li>
<li>fixme
<span class="label label-info">8</span>
</li>
</ul></a></li>
<li><a href="../deprecated.html"><i class="icon-stop"></i> Deprecated elements
<span class="label label-info">11</span></a></li>
</ul>
</li>
</ul></div>
</div></div>
<div class="go_to_top"><a href="#___" style="color: inherit">Back to top <i class="icon-upload icon-white"></i></a></div>
</div>
<div id="___" class="container">
<noscript><div class="alert alert-warning">
Javascript is disabled; several features are only available
if Javascript is enabled.
</div></noscript>
<div class="row">
<div class="span4">
<span class="btn-group visibility" data-toggle="buttons-checkbox"><button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button></span><div class="btn-group view pull-right" data-toggle="buttons-radio">
<button class="btn details" title="Show descriptions and method names"><i class="icon-list"></i></button><button class="btn simple" title="Show only method names"><i class="icon-align-justify"></i></button>
</div>
<ul class="side-nav nav nav-list">
<li class="nav-header">
<i class="icon-custom icon-method"></i> Methods
<ul>
<li class="method public "><a href="#method___construct" title="__construct :: Constructs a new DataTypeHandler and sets up everything."><span class="description">Constructs a new DataTypeHandler and sets up everything.</span><pre>__construct()</pre></a></li>
<li class="method public "><a href="#method_characters" title="characters :: Handles character data."><span class="description">Handles character data.</span><pre>characters()</pre></a></li>
<li class="method public "><a href="#method_endElement" title="endElement :: Overrides endElement for data types."><span class="description">Overrides endElement for data types.</span><pre>endElement()</pre></a></li>
<li class="method public "><a href="#method_init" title="init :: Executes initialization actions required to setup the data structures
related to the tag."><span class="description">Executes initialization actions required to setup the data structures
related to the tag.</span><pre>init()</pre></a></li>
<li class="method public "><a href="#method_startElement" title="startElement :: Checks for nested tags within the current one."><span class="description">Checks for nested tags within the current one.</span><pre>startElement()</pre></a></li>
</ul>
</li>
<li class="nav-header protected">» Protected
<ul><li class="method protected inherited"><a href="#method_finished" title="finished :: Gets invoked when element closes method."><span class="description">Gets invoked when element closes method.</span><pre>finished()</pre></a></li></ul>
</li>
<li class="nav-header">
<i class="icon-custom icon-property"></i> Properties
<ul>
<li class="property public inherited"><a href="#property_parentHandler" title="$parentHandler :: "><span class="description"></span><pre>$parentHandler</pre></a></li>
<li class="property public inherited"><a href="#property_parser" title="$parser :: "><span class="description"></span><pre>$parser</pre></a></li>
</ul>
</li>
<li class="nav-header private">» Private
<ul>
<li class="property private "><a href="#property_element" title="$element :: "><span class="description"></span><pre>$element</pre></a></li>
<li class="property private "><a href="#property_target" title="$target :: "><span class="description"></span><pre>$target</pre></a></li>
<li class="property private "><a href="#property_wrapper" title="$wrapper :: "><span class="description"></span><pre>$wrapper</pre></a></li>
</ul>
</li>
</ul>
</div>
<div class="span8">
<a id="\DataTypeHandler"></a><ul class="breadcrumb">
<li>
<a href="../index.html"><i class="icon-custom icon-class"></i></a><span class="divider">\</span>
</li>
<li><a href="../namespaces/global.html">global</a></li>
<li class="active">
<span class="divider">\</span><a href="../classes/DataTypeHandler.html">DataTypeHandler</a>
</li>
</ul>
<div class="element class">
<p class="short_description">Configures a Project (complete with Targets and Tasks) based on
a XML build file.</p>
<div class="details">
<div class="long_description"><p><</p>
<p>p>
Design/ZE2 migration note:
If PHP would support nested classes. All the phing/parser/*Filter
classes would be nested within this class</p></div>
<table class="table table-bordered">
<tr>
<th>author</th>
<td><a href="mailto:[email protected]">Andreas Aderhold</a></td>
</tr>
<tr>
<th>copyright</th>
<td>2001,2002 THYRELL. All rights reserved</td>
</tr>
<tr>
<th>version</th>
<td>$Id$</td>
</tr>
<tr>
<th>access</th>
<td>public</td>
</tr>
<tr>
<th>package</th>
<td><a href="../packages/phing.parser.html">phing.parser</a></td>
</tr>
</table>
<h3>
<i class="icon-custom icon-method"></i> Methods</h3>
<a id="method___construct"></a><div class="element clickable method public method___construct" data-toggle="collapse" data-target=".method___construct .collapse">
<h2>Constructs a new DataTypeHandler and sets up everything.</h2>
<pre>__construct(\AbstractSAXParser $parser, \AbstractHandler $parentHandler, \ProjectConfigurator $configurator, <a href="../classes/Target.html">\Target</a> $target) </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"><p>The constructor must be called by all derived classes.</p></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$parser</h4>
<code><a href="../classes/AbstractSAXParser.html">\AbstractSAXParser</a></code><p>The XML parser (default: ExpatParser)</p>
</div>
<div class="subelement argument">
<h4>$parentHandler</h4>
<code><a href="../classes/AbstractHandler.html">\AbstractHandler</a></code><p>The parent handler that invoked this handler.</p></div>
<div class="subelement argument">
<h4>$configurator</h4>
<code><a href="../classes/ProjectConfigurator.html">\ProjectConfigurator</a></code><p>The ProjectConfigurator object</p></div>
<div class="subelement argument">
<h4>$target</h4>
<code><a href="../classes/Target.html">\Target</a></code><p>The target object this datatype is contained in (null for top-level datatypes).</p>
</div>
</div></div>
</div>
<a id="method_characters"></a><div class="element clickable method public method_characters" data-toggle="collapse" data-target=".method_characters .collapse">
<h2>Handles character data.</h2>
<pre>characters(string $data) </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<table class="table table-bordered"><tr>
<th>access</th>
<td>public</td>
</tr></table>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$data</h4>
<code>string</code><p>the CDATA that comes in</p></div>
</div></div>
</div>
<a id="method_endElement"></a><div class="element clickable method public method_endElement" data-toggle="collapse" data-target=".method_endElement .collapse">
<h2>Overrides endElement for data types.</h2>
<pre>endElement(string $name) : void</pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"><p>Tells the type
handler that processing the element had been finished so
handlers know they can perform actions that need to be
based on the data contained within the element.</p></div>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$name</h4>
<code>string</code><p>the name of the XML element</p></div>
</div></div>
</div>
<a id="method_init"></a><div class="element clickable method public method_init" data-toggle="collapse" data-target=".method_init .collapse">
<h2>Executes initialization actions required to setup the data structures
related to the tag.</h2>
<pre>init(string $propType, array $attrs) </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"><p><</p>
<p>p>
This includes:</p>
<ul>
<li>creation of the datatype object</li>
<li>calling the setters for attributes</li>
<li>adding the type to the target object if any</li>
<li>adding a reference to the task (if id attribute is given)</li>
</ul></div>
<table class="table table-bordered"><tr>
<th>access</th>
<td>public</td>
</tr></table>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$propType</h4>
<code>string</code><p>the tag that comes in</p></div>
<div class="subelement argument">
<h4>$attrs</h4>
<code>array</code><p>attributes the tag carries</p></div>
<h3>Exceptions</h3>
<table class="table table-bordered"><tr>
<th><code><a href="../classes/ExpatParseException.html">\ExpatParseException</a></code></th>
<td>if attributes are incomplete or invalid</td>
</tr></table>
</div></div>
</div>
<a id="method_startElement"></a><div class="element clickable method public method_startElement" data-toggle="collapse" data-target=".method_startElement .collapse">
<h2>Checks for nested tags within the current one.</h2>
<pre>startElement(string $name, array $attrs) </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"><p>Creates and calls
handlers respectively.</p></div>
<table class="table table-bordered"><tr>
<th>access</th>
<td>public</td>
</tr></table>
<h3>Parameters</h3>
<div class="subelement argument">
<h4>$name</h4>
<code>string</code><p>the tag that comes in</p></div>
<div class="subelement argument">
<h4>$attrs</h4>
<code>array</code><p>attributes the tag carries</p></div>
</div></div>
</div>
<a id="method_finished"></a><div class="element clickable method protected method_finished" data-toggle="collapse" data-target=".method_finished .collapse">
<h2>Gets invoked when element closes method.</h2>
<pre>finished() </pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<table class="table table-bordered"><tr>
<th>inherited_from</th>
<td>\AbstractHandler::finished()</td>
</tr></table>
</div></div>
</div>
<h3>
<i class="icon-custom icon-property"></i> Properties</h3>
<a id="property_parentHandler"> </a><div class="element clickable property public property_parentHandler" data-toggle="collapse" data-target=".property_parentHandler .collapse">
<h2></h2>
<pre>$parentHandler </pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<table class="table table-bordered"><tr>
<th>inherited_from</th>
<td>\AbstractHandler::$$parentHandler</td>
</tr></table>
</div></div>
</div>
<a id="property_parser"> </a><div class="element clickable property public property_parser" data-toggle="collapse" data-target=".property_parser .collapse">
<h2></h2>
<pre>$parser </pre>
<div class="labels"><span class="label">Inherited</span></div>
<div class="row collapse"><div class="detail-description">
<div class="long_description"></div>
<table class="table table-bordered"><tr>
<th>inherited_from</th>
<td>\AbstractHandler::$$parser</td>
</tr></table>
</div></div>
</div>
<a id="property_element"> </a><div class="element clickable property private property_element" data-toggle="collapse" data-target=".property_element .collapse">
<h2></h2>
<pre>$element </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property_target"> </a><div class="element clickable property private property_target" data-toggle="collapse" data-target=".property_target .collapse">
<h2></h2>
<pre>$target </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
<a id="property_wrapper"> </a><div class="element clickable property private property_wrapper" data-toggle="collapse" data-target=".property_wrapper .collapse">
<h2></h2>
<pre>$wrapper </pre>
<div class="labels"></div>
<div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div>
</div>
</div>
</div>
</div>
</div>
<div class="row"><footer class="span12">
Template is built using <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap 2</a> and icons provided by <a href="http://glyphicons.com/">Glyphicons</a>.<br>
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor 2.0.0a11</a> and<br>
generated on 2012-11-20T07:50:45+01:00.<br></footer></div>
</div>
</body>
</html>
| theghostbel/pimcore | pimcore/lib/Deployment/Phing/docs/api/docs/classes/DataTypeHandler.html | HTML | bsd-3-clause | 15,955 |
#
# GtkMain.py -- pygtk threading help routines.
#
# Eric Jeschke ([email protected])
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
"""
GUI threading help routines.
Usage:
import GtkMain
# See constructor for GtkMain for options
self.mygtk = GtkMain.GtkMain()
# NOT THIS
#gtk.main()
# INSTEAD, main thread calls this:
self.mygtk.mainloop()
# (asynchronous call)
self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN)
# OR
# (synchronous call)
res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN)
# To cause the GUI thread to terminate the mainloop
self.mygtk.qui_quit()
"""
import sys, traceback
import thread, threading
import logging
import Queue as que
import gtk
from ginga.misc import Task, Future
class GtkMain(object):
def __init__(self, queue=None, logger=None, ev_quit=None):
# You can pass in a queue if you prefer to do so
if not queue:
queue = que.Queue()
self.gui_queue = queue
# You can pass in a logger if you prefer to do so
if logger == None:
logger = logging.getLogger('GtkHelper')
self.logger = logger
if not ev_quit:
ev_quit = threading.Event()
self.ev_quit = ev_quit
self.gui_thread_id = None
def update_pending(self, timeout=0.0):
"""Process all pending GTK events and return. _timeout_ is a tuning
parameter for performance.
"""
# Process "out-of-band" GTK events
try:
while gtk.events_pending():
#gtk.main_iteration(False)
gtk.main_iteration()
finally:
pass
done = False
while not done:
# Process "in-band" GTK events
try:
future = self.gui_queue.get(block=True,
timeout=timeout)
# Execute the GUI method
try:
try:
res = future.thaw(suppress_exception=False)
except Exception, e:
future.resolve(e)
self.logger.error("gui error: %s" % str(e))
try:
(type, value, tb) = sys.exc_info()
tb_str = "".join(traceback.format_tb(tb))
self.logger.error("Traceback:\n%s" % (tb_str))
except Exception, e:
self.logger.error("Traceback information unavailable.")
finally:
pass
except que.Empty:
done = True
except Exception, e:
self.logger.error("Main GUI loop error: %s" % str(e))
# Process "out-of-band" GTK events again
try:
while gtk.events_pending():
#gtk.main_iteration(False)
gtk.main_iteration()
finally:
pass
def gui_do(self, method, *args, **kwdargs):
"""General method for asynchronously calling into the GUI.
It makes a future to call the given (method) with the given (args)
and (kwdargs) inside the gui thread. If the calling thread is a
non-gui thread the future is returned.
"""
future = Future.Future()
future.freeze(method, *args, **kwdargs)
self.gui_queue.put(future)
my_id = thread.get_ident()
if my_id != self.gui_thread_id:
return future
def gui_call(self, method, *args, **kwdargs):
"""General method for synchronously calling into the GUI.
This waits until the method has completed before returning.
"""
my_id = thread.get_ident()
if my_id == self.gui_thread_id:
return method(*args, **kwdargs)
else:
future = self.gui_do(method, *args, **kwdargs)
return future.wait()
def gui_do_future(self, future):
self.gui_queue.put(future)
return future
def nongui_do(self, method, *args, **kwdargs):
task = Task.FuncTask(method, args, kwdargs, logger=self.logger)
return self.nongui_do_task(task)
def nongui_do_cb(self, tup, method, *args, **kwdargs):
task = Task.FuncTask(method, args, kwdargs, logger=self.logger)
task.register_callback(tup[0], args=tup[1:])
return self.nongui_do_task(task)
def nongui_do_future(self, future):
task = Task.FuncTask(future.thaw, (), {}, logger=self.logger)
return self.nongui_do_task(task)
def nongui_do_task(self, task):
try:
task.init_and_start(self)
return task
except Exception, e:
self.logger.error("Error starting task: %s" % (str(e)))
raise(e)
def assert_gui_thread(self):
my_id = thread.get_ident()
assert my_id == self.gui_thread_id, \
Exception("Non-GUI thread (%d) is executing GUI code!" % (
my_id))
def assert_nongui_thread(self):
my_id = thread.get_ident()
assert my_id != self.gui_thread_id, \
Exception("GUI thread (%d) is executing non-GUI code!" % (
my_id))
def mainloop(self, timeout=0.001):
# Mark our thread id
self.gui_thread_id = thread.get_ident()
while not self.ev_quit.isSet():
self.update_pending(timeout=timeout)
def gui_quit(self):
"Call this to cause the GUI thread to quit the mainloop."""
self.ev_quit.set()
# END
| Rbeaty88/ginga | ginga/gtkw/GtkMain.py | Python | bsd-3-clause | 5,866 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\modules\inspection\models\InspectionHospitalMapSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="inspection-hospital-map-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'insp_id') ?>
<?= $form->field($model, 'hosp_id') ?>
<?= $form->field($model, 'contact') ?>
<?php // echo $form->field($model, 'isleaf') ?>
<?php // echo $form->field($model, 'status') ?>
<?php // echo $form->field($model, 'utime') ?>
<?php // echo $form->field($model, 'uid') ?>
<?php // echo $form->field($model, 'ctime') ?>
<?php // echo $form->field($model, 'cid') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| Gcaufy/shengzaizai | backend/modules/inspection/views/hospital/_search.php | PHP | bsd-3-clause | 1,079 |
/*!
\ingroup PkgAABB_treeConcepts
\cgalConcept
The concept `AABBTraits` provides the geometric primitive types and methods for the class `CGAL::AABB_tree<AABBTraits>`.
\cgalHasModel `CGAL::AABB_traits<AABBGeomTraits,AABBPrimitive>`
\sa `CGAL::AABB_traits<AABBGeomTraits,AABBPrimitive>`
\sa `CGAL::AABB_tree<AABBTraits>`
\sa `AABBPrimitive`
*/
class AABBTraits {
public:
/// \name Types
/// @{
/*!
Value type of the `Squared_distance` functor.
*/
typedef unspecified_type FT;
/*!
Type of a 3D point.
*/
typedef unspecified_type Point_3;
/*!
Type of primitive.
Must be a model of the concepts `AABBPrimitive` or `AABBPrimitiveWithSharedData`.
*/
typedef unspecified_type Primitive;
/*!
Bounding box type.
*/
typedef unspecified_type Bounding_box;
/*!
*/
enum Axis {
X_AXIS,
Y_AXIS,
Z_AXIS
};
/*!
*/
typedef std::pair<Point_3, Primitive::Id> Point_and_primitive_id;
/*!
\deprecated
This requirement is deprecated and is no longer needed.
*/
typedef std::pair<Object, Primitive::Id> Object_and_primitive_id;
/*!
A nested class template providing as a pair the intersection result of a `Query` object
and a `Primitive::Datum`, together with the `Primitive::Id` of the primitive intersected.
The type of the pair is `%Intersection_and_primitive_id<Query>::%Type`.
*/
template <typename Query>
using Intersection_and_primitive_id = unspecified_type;
/// @}
/// \name Splitting
/// During the construction of the AABB tree, the primitives are
/// sorted according to some comparison functions related to the \f$x\f$,
/// \f$ y\f$ or \f$ z\f$ coordinate axis:
/// @{
/*!
A functor object to split a range of primitives into two sub-ranges along the X-axis. Provides the operator:
`void operator()(InputIterator first, InputIterator beyond);` %Iterator type `InputIterator` must be a model of RandomAccessIterator and have `Primitive` as value type. The operator is used for determining the primitives assigned to the two children nodes of a given node, assuming that the goal is to split the X-dimension of the bounding box of the node. The primitives assigned to this node are passed as argument to the operator. It should modify the iterator range in such a way that its first half and its second half correspond to the two children nodes.
*/
typedef unspecified_type Split_primitives_along_x_axis;
/*!
A functor object to split a range of primitives into two sub-ranges along the Y-axis. See `Split_primitives_along_x_axis` for the detailed description.
*/
typedef unspecified_type Split_primitives_along_y_axis;
/*!
A functor object to split a range of primitives into two sub-ranges along the Z-axis. See `Split_primitives_along_x_axis` for the detailed description.
*/
typedef unspecified_type Split_primitives_along_z_axis;
/*!
A functor object to compute the bounding box of a set of primitives. Provides the operator:
`Bounding_box operator()(Input_iterator begin, Input_iterator beyond);` %Iterator type `InputIterator` must have `Primitive` as value type.
*/
typedef unspecified_type Compute_bbox;
// remove as not used any where in the code:
// A functor object to specify the direction along which the bounding box should be split:
// `Axis operator()(const Bounding_box& bbox);` which returns the
// direction used for splitting `bbox`. It is usually the axis aligned
// with the longest edge of `bbox`.
// typedef unspecified_type Splitting_direction;
/// @}
/// \name Intersections
/// The following predicates are required for each type `Query` for
/// which the class `CGAL::AABB_tree<AABBTraits>` may receive an intersection
/// detection or computation query.
/// @{
/*!
A functor object to compute intersection predicates between the query and the nodes of the tree. Provides the operators:
- `bool operator()(const Query & q, const Bounding_box & box);` which returns `true` iff the query intersects the bounding box
- `bool operator()(const Query & q, const Primitive & primitive);` which returns `true` iff the query intersects the primitive
*/
typedef unspecified_type Do_intersect;
/*!
A functor object to compute the intersection of a query and a primitive. Provides the operator:
`boost::optional<Intersection_and_primitive_id<Query>::%Type > operator()(const Query & q, const Primitive& primitive);` which returns the intersection as a pair composed of an object and a primitive id, iff the query intersects the primitive.
\cgalHeading{Note on Backward Compatibility}
Before the release 4.3 of \cgal, the return type of this function used to be `boost::optional<Object_and_primitive_id>`.
*/
typedef unspecified_type Intersect;
/// \name Distance Queries
/// The following predicates are required for each
/// type `Query` for which the class `CGAL::AABB_tree<AABBTraits>` may receive a
/// distance query.
/// @{
/*!
A functor object to compute distance comparisons between the query and the nodes of the tree. Provides the operators:
- `bool operator()(const Query & query, const Bounding_box& box, const Point & closest);` which returns `true` iff the bounding box is closer to `query` than `closest` is
- `bool operator()(const Query & query, const Primitive & primitive, const Point & closest);` which returns `true` iff `primitive` is closer to the `query` than `closest` is
*/
typedef unspecified_type Compare_distance;
/*!
A functor object to compute closest point from the query on a primitive. Provides the operator:
`Point_3 operator()(const Query& query, const Primitive& primitive, const Point_3 & closest);` which returns the closest point to `query`, among `closest` and all points of the primitive.
*/
typedef unspecified_type Closest_point;
/*!
A functor object to compute the squared distance between two points. Provides the operator:
`FT operator()(const Point& query, const Point_3 & p);` which returns the squared distance between `p` and `q`.
*/
typedef unspecified_type Squared_distance;
/// @}
/// \name Operations
/// @{
/*!
Returns the primitive splitting functor for the X axis.
*/
Split_primitives_along_x_axis split_primitives_along_x_axis_object();
/*!
Returns the primitive splitting functor for the Y axis.
*/
Split_primitives_along_y_axis split_primitives_along_y_axis_object();
/*!
Returns the primitive splitting functor for the Z axis.
*/
Split_primitives_along_z_axis split_primitives_along_z_axis_object();
/*!
Returns the bounding box constructor.
*/
Compute_bbox compute_bbox_object();
/*!
Returns the intersection detection functor.
*/
Do_intersect do_intersect_object();
/*!
Returns the intersection constructor.
*/
Intersect intersect_object();
/*!
Returns the distance comparison functor.
*/
Compare_distance compare_distance_object();
/*!
Returns the closest point constructor.
*/
Closest_point closest_point_object();
/*!
Returns the squared distance functor.
*/
Squared_distance squared_distance_object();
/// @}
/// \name Primitive with Shared Data
/// In addition, if `Primitive` is a model of the concept `AABBPrimitiveWithSharedData`,
/// the following functions are part of the concept:
/// @{
/*!
the signature of that function must be the same as the static function `Primitive::construct_shared_data`.
The type `Primitive` expects that the data constructed by a call to `Primitive::construct_shared_data(t...)`
is the one given back when accessing the reference point and the datum of a primitive.
*/
template <class ... T>
void set_shared_data(T ... t);
{}
/*!
Returns the shared data of the primitive constructed after a call to `set_shared_data`.
If no call to `set_shared_data` has been done, `Primitive::Shared_data()` is returned.
*/
const Primitive::Shared_data& shared_data() const;
/// @}
}; /* end AABBTraits */
| hlzz/dotfiles | graphics/cgal/AABB_tree/doc/AABB_tree/Concepts/AABBTraits.h | C | bsd-3-clause | 7,754 |
/*! jQuery UI - v1.11.4 - 2015-12-06
* http://jqueryui.com
* Includes: core.js, datepicker.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
/*!
* jQuery UI Core 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.11.4",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
scrollParent: function( includeHidden ) {
var position = this.css( "position" ),
excludeStaticParent = position === "absolute",
overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
scrollParent = this.parents().filter( function() {
var parent = $( this );
if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
return false;
}
return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
}).eq( 0 );
return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
},
uniqueId: (function() {
var uuid = 0;
return function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + ( ++uuid );
}
});
};
})(),
removeUniqueId: function() {
return this.each(function() {
if ( /^ui-id-\d+$/.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" )[ 0 ];
return !!img && visible( img );
}
return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
disableSelection: (function() {
var eventType = "onselectstart" in document.createElement( "div" ) ?
"selectstart" :
"mousedown";
return function() {
return this.bind( eventType + ".ui-disableSelection", function( event ) {
event.preventDefault();
});
};
})(),
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
}
});
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
$.ui.plugin = {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args, allowDisconnected ) {
var i,
set = instance.plugins[ name ];
if ( !set ) {
return;
}
if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
};
/*!
* jQuery UI Datepicker 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/datepicker/
*/
$.extend($.ui, { datepicker: { version: "1.11.4" } });
var datepicker_instActive;
function datepicker_getZindex( elem ) {
var position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
return 0;
}
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[""] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: ["January","February","March","April","May","June",
"July","August","September","October","November","December"], // Names of months for drop-down and formatting
monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional[""]);
this.regional.en = $.extend( true, {}, this.regional[ "" ]);
this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: "hasDatepicker",
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
datepicker_extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
* @param target element - the target input field or division or span
* @param settings object - the new settings to use for this date picker instance (anonymous)
*/
_attachDatepicker: function(target, settings) {
var nodeName, inline, inst;
nodeName = target.nodeName.toLowerCase();
inline = (nodeName === "div" || nodeName === "span");
if (!target.id) {
this.uuid += 1;
target.id = "dp" + this.uuid;
}
inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {});
if (nodeName === "input") {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName)) {
return;
}
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp);
this._autoSize(inst);
$.data(target, "datepicker", inst);
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var showOn, buttonText, buttonImage,
appendText = this._get(inst, "appendText"),
isRTL = this._get(inst, "isRTL");
if (inst.append) {
inst.append.remove();
}
if (appendText) {
inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
input[isRTL ? "before" : "after"](inst.append);
}
input.unbind("focus", this._showDatepicker);
if (inst.trigger) {
inst.trigger.remove();
}
showOn = this._get(inst, "showOn");
if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
}
if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
buttonText = this._get(inst, "buttonText");
buttonImage = this._get(inst, "buttonImage");
inst.trigger = $(this._get(inst, "buttonImageOnly") ?
$("<img/>").addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$("<button type='button'></button>").addClass(this._triggerClass).
html(!buttonImage ? buttonText : $("<img/>").attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? "before" : "after"](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
$.datepicker._hideDatepicker();
} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker(input[0]);
} else {
$.datepicker._showDatepicker(input[0]);
}
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, "autoSize") && !inst.inline) {
var findMax, max, maxI, i,
date = new Date(2009, 12 - 1, 20), // Ensure double digits
dateFormat = this._get(inst, "dateFormat");
if (dateFormat.match(/[DM]/)) {
findMax = function(names) {
max = 0;
maxI = 0;
for (i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
"monthNames" : "monthNamesShort"))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
}
inst.input.attr("size", this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName)) {
return;
}
divSpan.addClass(this.markerClassName).append(inst.dpDiv);
$.data(target, "datepicker", inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css( "display", "block" );
},
/* Pop-up the date picker in a "dialog" box.
* @param input element - ignored
* @param date string or Date - the initial date to display
* @param onSelect function - the function to call when a date is selected
* @param settings object - update the dialog date picker instance's settings (anonymous object)
* @param pos int[2] - coordinates for the dialog's position within the screen or
* event - with x/y coordinates or
* leave empty for default (screen centre)
* @return the manager object
*/
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var id, browserWidth, browserHeight, scrollX, scrollY,
inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
id = "dp" + this.uuid;
this._dialogInput = $("<input type='text' id='" + id +
"' style='position: absolute; top: -100px; width: 0px;'/>");
this._dialogInput.keydown(this._doKeyDown);
$("body").append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], "datepicker", inst);
}
datepicker_extendRemove(inst.settings, settings || {});
date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI) {
$.blockUI(this.dpDiv);
}
$.data(this._dialogInput[0], "datepicker", inst);
return this;
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyDatepicker: function(target) {
var nodeName,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData(target, "datepicker");
if (nodeName === "input") {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind("focus", this._showDatepicker).
unbind("keydown", this._doKeyDown).
unbind("keypress", this._doKeyPress).
unbind("keyup", this._doKeyUp);
} else if (nodeName === "div" || nodeName === "span") {
$target.removeClass(this.markerClassName).empty();
}
if ( datepicker_instActive === inst ) {
datepicker_instActive = null;
}
},
/* Enable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_enableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = false;
inst.trigger.filter("button").
each(function() { this.disabled = false; }).end().
filter("img").css({opacity: "1.0", cursor: ""});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().removeClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", false);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_disableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = true;
inst.trigger.filter("button").
each(function() { this.disabled = true; }).end().
filter("img").css({opacity: "0.5", cursor: "default"});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().addClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", true);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
* @param target element - the target input field or division or span
* @return boolean - true if disabled, false if enabled
*/
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] === target) {
return true;
}
}
return false;
},
/* Retrieve the instance data for the target control.
* @param target element - the target input field or division or span
* @return object - the associated instance data
* @throws error if a jQuery problem getting data
*/
_getInst: function(target) {
try {
return $.data(target, "datepicker");
}
catch (err) {
throw "Missing instance data for this datepicker";
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
* @param target element - the target input field or division or span
* @param name object - the new settings to update or
* string - the name of the setting to change or retrieve,
* when retrieving also "all" for all instance settings or
* "defaults" for all global defaults
* @param value any - the new value for the setting
* (omit if above is an object or to retrieve a value)
*/
_optionDatepicker: function(target, name, value) {
var settings, date, minDate, maxDate,
inst = this._getInst(target);
if (arguments.length === 2 && typeof name === "string") {
return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
(inst ? (name === "all" ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
settings = name || {};
if (typeof name === "string") {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst === inst) {
this._hideDatepicker();
}
date = this._getDateDatepicker(target, true);
minDate = this._getMinMaxDate(inst, "min");
maxDate = this._getMinMaxDate(inst, "max");
datepicker_extendRemove(inst.settings, settings);
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
inst.settings.minDate = this._formatDate(inst, minDate);
}
if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
inst.settings.maxDate = this._formatDate(inst, maxDate);
}
if ( "disabled" in settings ) {
if ( settings.disabled ) {
this._disableDatepicker(target);
} else {
this._enableDatepicker(target);
}
}
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
* @param target element - the target input field or division or span
*/
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
* @param target element - the target input field or division or span
* @param date Date - the new date
*/
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
* @param target element - the target input field or division or span
* @param noDefault boolean - true if no default date is to be used
* @return Date - the current date
*/
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline) {
this._setDateFromField(inst, noDefault);
}
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var onSelect, dateStr, sel,
inst = $.datepicker._getInst(event.target),
handled = true,
isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
inst._keyEvent = true;
if ($.datepicker._datepickerShowing) {
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
$.datepicker._currentClass + ")", inst.dpDiv);
if (sel[0]) {
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
}
onSelect = $.datepicker._get(inst, "onSelect");
if (onSelect) {
dateStr = $.datepicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
} else {
$.datepicker._hideDatepicker();
}
return false; // don't submit the form
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) {
$.datepicker._clearDate(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) {
$.datepicker._gotoToday(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
}
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, -7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
}
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, +7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var chars, chr,
inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, "constrainInput")) {
chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var date,
inst = $.datepicker._getInst(event.target);
if (inst.input.val() !== inst.lastVal) {
try {
date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (err) {
}
}
return true;
},
/* Pop-up the date picker for a given input field.
* If false returned from beforeShow event handler do not show.
* @param input element - the input field attached to the date picker or
* event - if triggered by focus
*/
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
input = $("input", input.parentNode)[0];
}
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
return;
}
var inst, beforeShow, beforeShowSettings, isFixed,
offset, showAnim, duration;
inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
if ( inst && $.datepicker._datepickerShowing ) {
$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
}
}
beforeShow = $.datepicker._get(inst, "beforeShow");
beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if(beforeShowSettings === false){
return;
}
datepicker_extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) { // hide cursor
input.value = "";
}
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css("position") === "fixed";
return !isFixed;
});
offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
"static" : (isFixed ? "fixed" : "absolute")), display: "none",
left: offset.left + "px", top: offset.top + "px"});
if (!inst.inline) {
showAnim = $.datepicker._get(inst, "showAnim");
duration = $.datepicker._get(inst, "duration");
inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
$.datepicker._datepickerShowing = true;
if ( $.effects && $.effects.effect[ showAnim ] ) {
inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
} else {
inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
}
if ( $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
datepicker_instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
var origyearshtml,
numMonths = this._getNumberOfMonths(inst),
cols = numMonths[1],
width = 17,
activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );
if ( activeCell.length > 0 ) {
datepicker_handleMouseover.apply( activeCell.get( 0 ) );
}
inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
if (cols > 1) {
inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
}
inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
"Class"]("ui-datepicker-multi");
inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
"Class"]("ui-datepicker-rtl");
if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
// deffered render of the years select (to avoid flashes on Firefox)
if( inst.yearshtml ){
origyearshtml = inst.yearshtml;
setTimeout(function(){
//assure that inst.yearshtml didn't change.
if( origyearshtml === inst.yearshtml && inst.yearshtml ){
inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
// Support: IE and jQuery <1.9
_shouldFocusInput: function( inst ) {
return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
* @param input element - the input field attached to the date picker
*/
_hideDatepicker: function(input) {
var showAnim, duration, postProcess, onClose,
inst = this._curInst;
if (!inst || (input && inst !== $.data(input, "datepicker"))) {
return;
}
if (this._datepickerShowing) {
showAnim = this._get(inst, "showAnim");
duration = this._get(inst, "duration");
postProcess = function() {
$.datepicker._tidyDialog(inst);
};
// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
} else {
inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
}
if (!showAnim) {
postProcess();
}
this._datepickerShowing = false;
onClose = this._get(inst, "onClose");
if (onClose) {
onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
}
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
if ($.blockUI) {
$.unblockUI();
$("body").append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst) {
return;
}
var $target = $(event.target),
inst = $.datepicker._getInst($target[0]);
if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.closest("." + $.datepicker._triggerClass).length &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
$.datepicker._hideDatepicker();
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id),
inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date,
target = $(id),
inst = this._getInst(target[0]);
if (this._get(inst, "gotoCurrent") && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id),
inst = this._getInst(target[0]);
inst["selected" + (period === "M" ? "Month" : "Year")] =
inst["draw" + (period === "M" ? "Month" : "Year")] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var inst,
target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $("a", td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
this._selectDate(target, "");
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var onSelect,
target = $(id),
inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input) {
inst.input.val(dateStr);
}
this._updateAlternate(inst);
onSelect = this._get(inst, "onSelect");
if (onSelect) {
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
} else if (inst.input) {
inst.input.trigger("change"); // fire the change event
}
if (inst.inline){
this._updateDatepicker(inst);
} else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) !== "object") {
inst.input.focus(); // restore focus
}
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altFormat, date, dateStr,
altField = this._get(inst, "altField");
if (altField) { // update alternate field too
altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
date = this._getDate(inst);
dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
* @param date Date - the date to customise
* @return [boolean, string] - is this date selectable?, what is its CSS class?
*/
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ""];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
iso8601Week: function(date) {
var time,
checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
* See formatDate below for the possible formats.
*
* @param format string - the expected format of the date
* @param value string - the date in the above format
* @param settings Object - attributes include:
* shortYearCutoff number - the cutoff year for determining the century (optional)
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return Date - the extracted date value or null if value is blank
*/
parseDate: function (format, value, settings) {
if (format == null || value == null) {
throw "Invalid arguments";
}
value = (typeof value === "object" ? value.toString() : value + "");
if (value === "") {
return null;
}
var iFormat, dim, extra,
iValue = 0,
shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
year = -1,
month = -1,
day = -1,
doy = -1,
literal = false,
date,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Extract a number from the string value
getNumber = function(match) {
var isDoubled = lookAhead(match),
size = (match === "@" ? 14 : (match === "!" ? 20 :
(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
minSize = (match === "y" ? size : 1),
digits = new RegExp("^\\d{" + minSize + "," + size + "}"),
num = value.substring(iValue).match(digits);
if (!num) {
throw "Missing number at position " + iValue;
}
iValue += num[0].length;
return parseInt(num[0], 10);
},
// Extract a name from the string value and convert to an index
getName = function(match, shortNames, longNames) {
var index = -1,
names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
return [ [k, v] ];
}).sort(function (a, b) {
return -(a[1].length - b[1].length);
});
$.each(names, function (i, pair) {
var name = pair[1];
if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
index = pair[0];
iValue += name.length;
return false;
}
});
if (index !== -1) {
return index + 1;
} else {
throw "Unknown name at position " + iValue;
}
},
// Confirm that a literal character matches the string value
checkLiteral = function() {
if (value.charAt(iValue) !== format.charAt(iFormat)) {
throw "Unexpected literal at position " + iValue;
}
iValue++;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
checkLiteral();
}
} else {
switch (format.charAt(iFormat)) {
case "d":
day = getNumber("d");
break;
case "D":
getName("D", dayNamesShort, dayNames);
break;
case "o":
doy = getNumber("o");
break;
case "m":
month = getNumber("m");
break;
case "M":
month = getName("M", monthNamesShort, monthNames);
break;
case "y":
year = getNumber("y");
break;
case "@":
date = new Date(getNumber("@"));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "!":
date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'")){
checkLiteral();
} else {
literal = true;
}
break;
default:
checkLiteral();
}
}
}
if (iValue < value.length){
extra = value.substr(iValue);
if (!/^\s+/.test(extra)) {
throw "Extra/unparsed characters found in date: " + extra;
}
}
if (year === -1) {
year = new Date().getFullYear();
} else if (year < 100) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
}
if (doy > -1) {
month = 1;
day = doy;
do {
dim = this._getDaysInMonth(year, month - 1);
if (day <= dim) {
break;
}
month++;
day -= dim;
} while (true);
}
date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
throw "Invalid date"; // E.g. 31/02/00
}
return date;
},
/* Standard date formats. */
ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
COOKIE: "D, dd M yy",
ISO_8601: "yy-mm-dd",
RFC_822: "D, d M y",
RFC_850: "DD, dd-M-y",
RFC_1036: "D, d M y",
RFC_1123: "D, d M yy",
RFC_2822: "D, d M yy",
RSS: "D, d M y", // RFC 822
TICKS: "!",
TIMESTAMP: "@",
W3C: "yy-mm-dd", // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
* The format can be combinations of the following:
* d - day of month (no leading zero)
* dd - day of month (two digit)
* o - day of year (no leading zeros)
* oo - day of year (three digit)
* D - day name short
* DD - day name long
* m - month of year (no leading zero)
* mm - month of year (two digit)
* M - month name short
* MM - month name long
* y - year (two digit)
* yy - year (four digit)
* @ - Unix timestamp (ms since 01/01/1970)
* ! - Windows ticks (100ns since 01/01/0001)
* "..." - literal text
* '' - single quote
*
* @param format string - the desired format of the date
* @param date Date - the date value to format
* @param settings Object - attributes include:
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return string - the date in the above format
*/
formatDate: function (format, date, settings) {
if (!date) {
return "";
}
var iFormat,
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Format a number, with leading zero if necessary
formatNumber = function(match, value, len) {
var num = "" + value;
if (lookAhead(match)) {
while (num.length < len) {
num = "0" + num;
}
}
return num;
},
// Format a name, short or long as requested
formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
},
output = "",
literal = false;
if (date) {
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
output += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d":
output += formatNumber("d", date.getDate(), 2);
break;
case "D":
output += formatName("D", date.getDay(), dayNamesShort, dayNames);
break;
case "o":
output += formatNumber("o",
Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case "m":
output += formatNumber("m", date.getMonth() + 1, 2);
break;
case "M":
output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
break;
case "y":
output += (lookAhead("y") ? date.getFullYear() :
(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
break;
case "@":
output += date.getTime();
break;
case "!":
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'")) {
output += "'";
} else {
literal = true;
}
break;
default:
output += format.charAt(iFormat);
}
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var iFormat,
chars = "",
literal = false,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
chars += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d": case "m": case "y": case "@":
chars += "0123456789";
break;
case "D": case "M":
return null; // Accept anything
case "'":
if (lookAhead("'")) {
chars += "'";
} else {
literal = true;
}
break;
default:
chars += format.charAt(iFormat);
}
}
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() === inst.lastVal) {
return;
}
var dateFormat = this._get(inst, "dateFormat"),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate(inst),
date = defaultDate,
settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
dates = (noDefault ? "" : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d" : case "D" :
day += parseInt(matches[1],10); break;
case "w" : case "W" :
day += parseInt(matches[1],10) * 7; break;
case "m" : case "M" :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case "y": case "Y" :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
/* Handle switch to/from daylight saving.
* Hours may be non-zero on daylight saving cut-over:
* > 12 when midnight changeover, but then cannot generate
* midnight datetime, so jump to 1AM, otherwise reset.
* @param date (Date) the date to check
* @return (Date) the corrected date
*/
_daylightSavingAdjust: function(date) {
if (!date) {
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !date,
origMonth = inst.selectedMonth,
origYear = inst.selectedYear,
newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
this._notifyChange(inst);
}
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? "" : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Attach the onxxx handlers. These are declared statically so
* they work with static code transformers like Caja.
*/
_attachHandlers: function(inst) {
var stepMonths = this._get(inst, "stepMonths"),
id = "#" + inst.id.replace( /\\\\/g, "\\" );
inst.dpDiv.find("[data-handler]").map(function () {
var handler = {
prev: function () {
$.datepicker._adjustDate(id, -stepMonths, "M");
},
next: function () {
$.datepicker._adjustDate(id, +stepMonths, "M");
},
hide: function () {
$.datepicker._hideDatepicker();
},
today: function () {
$.datepicker._gotoToday(id);
},
selectDay: function () {
$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
return false;
},
selectMonth: function () {
$.datepicker._selectMonthYear(id, this, "M");
return false;
},
selectYear: function () {
$.datepicker._selectMonthYear(id, this, "Y");
return false;
}
};
$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
});
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
printDate, dRow, tbody, daySettings, otherMonth, unselectable,
tempDate = new Date(),
today = this._daylightSavingAdjust(
new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
isRTL = this._get(inst, "isRTL"),
showButtonPanel = this._get(inst, "showButtonPanel"),
hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
numMonths = this._getNumberOfMonths(inst),
showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
stepMonths = this._get(inst, "stepMonths"),
isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
drawMonth = inst.drawMonth - showCurrentAtPos,
drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
prevText = this._get(inst, "prevText");
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
nextText = this._get(inst, "nextText");
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
currentText = this._get(inst, "currentText");
gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get(inst, "closeText") + "</button>" : "");
buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
firstDay = parseInt(this._get(inst, "firstDay"),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
showWeek = this._get(inst, "showWeek");
dayNames = this._get(inst, "dayNames");
dayNamesMin = this._get(inst, "dayNamesMin");
monthNames = this._get(inst, "monthNames");
monthNamesShort = this._get(inst, "monthNamesShort");
beforeShowDay = this._get(inst, "beforeShowDay");
showOtherMonths = this._get(inst, "showOtherMonths");
selectOtherMonths = this._get(inst, "selectOtherMonths");
defaultDate = this._getDefaultDate(inst);
html = "";
dow;
for (row = 0; row < numMonths[0]; row++) {
group = "";
this.maxRows = 4;
for (col = 0; col < numMonths[1]; col++) {
selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
cornerClass = " ui-corner-all";
calender = "";
if (isMultiMonth) {
calender += "<div class='ui-datepicker-group";
if (numMonths[1] > 1) {
switch (col) {
case 0: calender += " ui-datepicker-group-first";
cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
case numMonths[1]-1: calender += " ui-datepicker-group-last";
cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
}
}
calender += "'>";
}
calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
"</div><table class='ui-datepicker-calendar'><thead>" +
"<tr>";
thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
for (dow = 0; dow < 7; dow++) { // days of the week
day = (dow + firstDay) % 7;
thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
}
calender += thead + "</tr></thead><tbody>";
daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
}
leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += "<tr>";
tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
this._get(inst, "calculateWeek")(printDate) + "</td>");
for (dow = 0; dow < 7; dow++) { // create date picker days
daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
otherMonth = (printDate.getMonth() !== drawMonth);
unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += "<td class='" +
((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "") + // highlight selected day
(unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
(otherMonth && !showOtherMonths ? " " : // display for other months
(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + "</tr>";
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
group += calender;
}
html += group;
}
html += buttonPanel;
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// month selection
if (secondary || !changeMonth) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
} else {
inMinYear = (minDate && minDate.getFullYear() === drawYear);
inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for ( month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
monthHtml += "<option value='" + month + "'" +
(month === drawMonth ? " selected='selected'" : "") +
">" + monthNamesShort[month] + "</option>";
}
}
monthHtml += "</select>";
}
if (!showMonthAfterYear) {
html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
}
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, "yearSuffix");
if (showMonthAfterYear) {
html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
}
html += "</div>"; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period === "Y" ? offset : 0),
month = inst.drawMonth + (period === "M" ? offset : 0),
day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period === "M" || period === "Y") {
this._notifyChange(inst);
}
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
newDate = (minDate && date < minDate ? minDate : date);
return (maxDate && newDate > maxDate ? maxDate : newDate);
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, "onChangeMonthYear");
if (onChange) {
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
}
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, "numberOfMonths");
return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst),
date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0) {
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
minYear = null,
maxYear = null,
years = this._get(inst, "yearRange");
if (years){
yearSplit = years.split(":");
currentYear = new Date().getFullYear();
minYear = parseInt(yearSplit[0], 10);
maxYear = parseInt(yearSplit[1], 10);
if ( yearSplit[0].match(/[+\-].*/) ) {
minYear += currentYear;
}
if ( yearSplit[1].match(/[+\-].*/) ) {
maxYear += currentYear;
}
}
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) &&
(!minYear || date.getFullYear() >= minYear) &&
(!maxYear || date.getFullYear() <= maxYear));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, "shortYearCutoff");
shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day === "object" ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
}
});
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function datepicker_bindHover(dpDiv) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.delegate(selector, "mouseout", function() {
$(this).removeClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).removeClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).removeClass("ui-datepicker-next-hover");
}
})
.delegate( selector, "mouseover", datepicker_handleMouseover );
}
function datepicker_handleMouseover() {
if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) {
$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).addClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).addClass("ui-datepicker-next-hover");
}
}
}
/* jQuery extend now ignores nulls! */
function datepicker_extendRemove(target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] == null) {
target[name] = props[name];
}
}
return target;
}
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Verify an empty collection wasn't passed - Fixes #6976 */
if ( !this.length ) {
return this;
}
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick);
$.datepicker.initialized = true;
}
/* Append datepicker main container to body if not exist. */
if ($("#"+$.datepicker._mainDivId).length === 0) {
$("body").append($.datepicker.dpDiv);
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
return this.each(function() {
typeof options === "string" ?
$.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.11.4";
var datepicker = $.datepicker;
})); | davidred/spree_delivery_time | app/assets/javascripts/spree/frontend/store/datepicker.js | JavaScript | bsd-3-clause | 91,677 |
#!/bin/bash
#This program calculates the core count for each result row and updates the
#results. This is a work around due to a current limitation of
#HdpHBencher/HsBencher.
#Author: Blair Archibald
function usage {
echo "Usage: processResults.sh <resultsFile>"
exit -1
}
test -z $1 && usage
resultsFile="$1"
#Find the results column
flags=$(awk -F, '
NR == 1 {
for (i = 1; i <= NF; i++) {
if ($i == "RUNTIME_FLAGS") {
cid = i;
}
}
}
NR > 1 {
if (cid > 0) {
print $cid
}
}
' $resultsFile)
#Get the thread count and the processor count.
j=0
declare -a Lines
while read i; do
procs=$(echo $i | egrep -o "numProcs: [0-9]+" | egrep -o "[0-9]+")
threads=$(echo $i | egrep -o "numThreads: [0-9]+" | egrep -o "[0-9]+")
cores=$(($procs * $threads))
Lines[j]=$cores
let "j += 1"
done <<< "$flags"
#Could also use sed or awk here.
line=-1
tmp=$(mktemp)
while read l; do
#First line we add a new header
if [[ $line == -1 ]]; then
echo "$l,NUM_CORES" > $tmp
else
echo "$l,${Lines[$line]}" >> $tmp
fi
let "line += 1"
done < "$resultsFile"
cp $resultsFile ${resultsFile}.bak
cp $tmp $resultsFile
| BlairArchibald/HdpHBencher | processResults.sh | Shell | bsd-3-clause | 1,154 |
var sbModule = angular.module('sbServices', ['ngResource']);
sbModule.factory('App', function($resource) {
return $resource('/api/v1/app/:name', { q: '' }, {
get: { method: 'GET' }, //isArray: false },
query: { method: 'GET'} //, params: { q: '' }//, isArray: false }
});
});
| beni55/shipbuilder | webroot/js/services.js | JavaScript | bsd-3-clause | 302 |
// Copyright 2015 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef COBALT_BINDINGS_TESTING_GLOBAL_INTERFACE_PARENT_H_
#define COBALT_BINDINGS_TESTING_GLOBAL_INTERFACE_PARENT_H_
#include "cobalt/script/wrappable.h"
namespace cobalt {
namespace bindings {
namespace testing {
class GlobalInterfaceParent : public script::Wrappable {
public:
virtual void ParentOperation() {}
DEFINE_WRAPPABLE_TYPE(GlobalInterfaceParent);
};
} // namespace testing
} // namespace bindings
} // namespace cobalt
#endif // COBALT_BINDINGS_TESTING_GLOBAL_INTERFACE_PARENT_H_
| youtube/cobalt | cobalt/bindings/testing/global_interface_parent.h | C | bsd-3-clause | 1,126 |
# coding: utf-8
# This file is part of Thomas Aquinas.
#
# Thomas Aquinas is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Thomas Aquinas is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Thomas Aquinas. If not, see <http://www.gnu.org/licenses/>.
#
# veni, Sancte Spiritus.
import ctypes
import logging
| shackra/thomas-aquinas | summa/audio/system.py | Python | bsd-3-clause | 776 |
/*-
* Copyright (c) 2006 The FreeBSD Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/dev/tdfx/tdfx_linux.c 224778 2011-08-11 12:30:23Z rwatson $");
#include <sys/param.h>
#include <sys/capability.h>
#include <sys/file.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/proc.h>
#include <sys/systm.h>
#include <dev/tdfx/tdfx_linux.h>
LINUX_IOCTL_SET(tdfx, LINUX_IOCTL_TDFX_MIN, LINUX_IOCTL_TDFX_MAX);
/*
* Linux emulation IOCTL for /dev/tdfx
*/
static int
linux_ioctl_tdfx(struct thread *td, struct linux_ioctl_args* args)
{
int error = 0;
u_long cmd = args->cmd & 0xffff;
/* The structure passed to ioctl has two shorts, one int
and one void*. */
char d_pio[2*sizeof(short) + sizeof(int) + sizeof(void*)];
struct file *fp;
if ((error = fget(td, args->fd, CAP_IOCTL, &fp)) != 0)
return (error);
/* We simply copy the data and send it right to ioctl */
copyin((caddr_t)args->arg, &d_pio, sizeof(d_pio));
error = fo_ioctl(fp, cmd, (caddr_t)&d_pio, td->td_ucred, td);
fdrop(fp, td);
return error;
}
static int
tdfx_linux_modevent(struct module *mod __unused, int what, void *arg __unused)
{
switch (what) {
case MOD_LOAD:
case MOD_UNLOAD:
return (0);
}
return (EOPNOTSUPP);
}
static moduledata_t tdfx_linux_mod = {
"tdfx_linux",
tdfx_linux_modevent,
0
};
/* As in SYSCALL_MODULE */
DECLARE_MODULE(tdfx_linux, tdfx_linux_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
MODULE_VERSION(tdfx_linux, 1);
MODULE_DEPEND(tdfx_linux, tdfx, 1, 1, 1);
MODULE_DEPEND(tdfx_linux, linux, 1, 1, 1);
| dcui/FreeBSD-9.3_kernel | sys/dev/tdfx/tdfx_linux.c | C | bsd-3-clause | 2,886 |
module Mistral.Schedule.Value (
Env
, groupEnv
, lookupEnv
, bindType
, bindValue
, bindParam
, NodeTags
, bindNode
, lookupTag, lookupTags
, Value(..)
, SNetwork(..), mapWhen, modifyNode
, SNode(..), addTask
, STask(..), hasConstraints
, SConstraint(..), target
) where
import Mistral.TypeCheck.AST
import Mistral.Utils.PP
import Mistral.Utils.Panic ( panic )
import Mistral.Utils.SCC ( Group )
import qualified Data.Foldable as Fold
import qualified Data.Map as Map
import Data.Monoid ( Monoid(..) )
import qualified Data.Set as Set
sPanic :: [String] -> a
sPanic = panic "Mistral.Schedule.Value"
-- Environments ----------------------------------------------------------------
data Env = Env { envValues :: Map.Map Name Value
, envTypes :: Map.Map TParam Type
}
instance Monoid Env where
mempty = Env { envValues = mempty, envTypes = mempty }
mappend l r = mconcat [l,r]
-- merge the two environments, preferring things from the left
mconcat envs = Env { envValues = Map.unions (map envValues envs)
, envTypes = Map.unions (map envTypes envs) }
lookupEnv :: Name -> Env -> Value
lookupEnv n env =
case Map.lookup n (envValues env) of
Just v -> v
Nothing -> sPanic [ "no value for: " ++ pretty n ]
bindType :: TParam -> Type -> Env -> Env
bindType p ty env = env { envTypes = Map.insert p ty (envTypes env) }
bindValue :: Name -> Value -> Env -> Env
bindValue n v env = env { envValues = Map.insert n v (envValues env) }
bindParam :: Param -> Value -> Env -> Env
bindParam p v env = bindValue (pName p) v env
groupEnv :: (a -> Env) -> (Group a -> Env)
groupEnv = Fold.foldMap
-- Node Tags -------------------------------------------------------------------
newtype NodeTags = NodeTags { getNodeTags :: Map.Map Atom (Set.Set Name) }
instance Monoid NodeTags where
mempty = NodeTags mempty
mappend l r = mconcat [l,r]
mconcat nts = NodeTags (Map.unionsWith Set.union (map getNodeTags nts))
bindNode :: SNode -> NodeTags
bindNode sn = mempty { getNodeTags = foldl add mempty allTags }
where
name = snName sn
allTags = [ (tag, Set.singleton name) | tag <- snTags sn ]
add nodes (tag, s) = Map.insertWith Set.union tag s nodes
-- | Try to resolve a single tag to set of Node names.
lookupTag :: Atom -> NodeTags -> Set.Set Name
lookupTag tag env = case Map.lookup tag (getNodeTags env) of
Just nodes -> nodes
Nothing -> Set.empty
-- | Lookup the nodes that have all of the tags given.
lookupTags :: [Atom] -> NodeTags -> [Name]
lookupTags tags env
| null tags = [] -- XXX maybe all nodes?
| otherwise = Set.toList (foldl1 Set.intersection (map (`lookupTag` env) tags))
-- Values ----------------------------------------------------------------------
data Value = VTFun (Type -> Value)
-- ^ Type abstractions
| VFun (Value -> Value)
-- ^ Value abstractions
| VCon Name [Value]
-- ^ Constructor use
| VLit Literal
-- ^ Literals
| VSched [SNetwork]
-- ^ Evaluted schedules
| VTopo SNetwork
-- ^ Nodes and links
| VNode SNode
-- ^ Nodes
| VLink Link
-- ^ Links
| VTasks (NodeTags -> [STask])
| VTask STask
instance Show Value where
show val = case val of
VTFun _ -> "<function>"
VFun _ -> "<type-function>"
VCon n vs -> "(" ++ unwords (pretty n : map show vs) ++ ")"
VLit lit -> "(VLit " ++ show lit ++ ")"
VSched nets -> show nets
VTopo net -> show net
VNode n -> show n
VLink l -> show l
VTasks _ -> "<tasks>"
VTask t -> show t
-- | Scheduling network.
data SNetwork = SNetwork { snNodes :: [SNode]
, snLinks :: [Link]
} deriving (Show)
instance Monoid SNetwork where
mempty = SNetwork { snNodes = []
, snLinks = [] }
mappend l r = SNetwork { snNodes = Fold.foldMap snNodes [l,r]
, snLinks = Fold.foldMap snLinks [l,r] }
mapWhen :: (a -> Bool) -> (a -> a) -> [a] -> [a]
mapWhen p f = go
where
go as = case as of
a:rest | p a -> f a : rest
| otherwise -> a : go rest
[] -> []
-- | Modify the first occurrence of node n.
--
-- INVARIANT: This relies on the assumption that the renamer has given fresh
-- names to all nodes.
modifyNode :: Name -> (SNode -> SNode) -> (SNetwork -> SNetwork)
modifyNode n f net = net { snNodes = mapWhen nameMatches f (snNodes net) }
where
nameMatches sn = snName sn == n
data SNode = SNode { snName :: Name
, snSpec :: Expr
, snType :: Type
, snTags :: [Atom]
, snTasks :: [STask]
} deriving (Show)
addTask :: STask -> (SNode -> SNode)
addTask task sn = sn { snTasks = task : snTasks sn }
data STask = STask { stName :: Name
, stTask :: Task
, stTags :: [Atom]
, stConstraints :: [SConstraint]
} deriving (Show)
hasConstraints :: STask -> Bool
hasConstraints t = not (null (stConstraints t))
data SConstraint = SCOn Name -- ^ On this node
deriving (Show)
-- XXX This won't work for constraints that specify relative information like:
-- "I need to be able to communicate with X"
target :: SConstraint -> Name
target (SCOn n) = n
| GaloisInc/mistral | src/Mistral/Schedule/Value.hs | Haskell | bsd-3-clause | 5,624 |
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Jordan K. Hubbard
* 29 August 1998
*
* $FreeBSD: src/sys/boot/common/interp_backslash.c,v 1.4 1999/08/28 00:39:47 peter Exp $
*
* Routine for doing backslash elimination.
*/
#include <stand.h>
#include <string.h>
#define DIGIT(x) (isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A')
/*
* backslash: Return malloc'd copy of str with all standard "backslash
* processing" done on it. Original can be free'd if desired.
*/
char *
backslash(char *str)
{
/*
* Remove backslashes from the strings. Turn \040 etc. into a single
* character (we allow eight bit values). Currently NUL is not
* allowed.
*
* Turn "\n" and "\t" into '\n' and '\t' characters. Etc.
*
*/
char *new_str;
int seenbs = 0;
int i = 0;
if ((new_str = strdup(str)) == NULL)
return NULL;
while (*str) {
if (seenbs) {
seenbs = 0;
switch (*str) {
case '\\':
new_str[i++] = '\\';
str++;
break;
/* preserve backslashed quotes, dollar signs */
case '\'':
case '"':
case '$':
new_str[i++] = '\\';
new_str[i++] = *str++;
break;
case 'b':
new_str[i++] = '\b';
str++;
break;
case 'f':
new_str[i++] = '\f';
str++;
break;
case 'r':
new_str[i++] = '\r';
str++;
break;
case 'n':
new_str[i++] = '\n';
str++;
break;
case 's':
new_str[i++] = ' ';
str++;
break;
case 't':
new_str[i++] = '\t';
str++;
break;
case 'v':
new_str[i++] = '\13';
str++;
break;
case 'z':
str++;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
char val;
/* Three digit octal constant? */
if (*str >= '0' && *str <= '3' &&
*(str + 1) >= '0' && *(str + 1) <= '7' &&
*(str + 2) >= '0' && *(str + 2) <= '7') {
val = (DIGIT(*str) << 6) + (DIGIT(*(str + 1)) << 3) +
DIGIT(*(str + 2));
/* Allow null value if user really wants to shoot
at feet, but beware! */
new_str[i++] = val;
str += 3;
break;
}
/* One or two digit hex constant?
* If two are there they will both be taken.
* Use \z to split them up if this is not wanted.
*/
if (*str == '0' &&
(*(str + 1) == 'x' || *(str + 1) == 'X') &&
isxdigit(*(str + 2))) {
val = DIGIT(*(str + 2));
if (isxdigit(*(str + 3))) {
val = (val << 4) + DIGIT(*(str + 3));
str += 4;
}
else
str += 3;
/* Yep, allow null value here too */
new_str[i++] = val;
break;
}
}
break;
default:
new_str[i++] = *str++;
break;
}
}
else {
if (*str == '\\') {
seenbs = 1;
str++;
}
else
new_str[i++] = *str++;
}
}
if (seenbs) {
/*
* The final character was a '\'. Put it in as a single backslash.
*/
new_str[i++] = '\\';
}
new_str[i] = '\0';
return new_str;
}
| MarginC/kame | freebsd4/sys/boot/common/interp_backslash.c | C | bsd-3-clause | 3,531 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: AllTests.php 24594 2012-01-05 21:27:01Z matthew $
*/
if (!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Zend_Validate_Sitemap_AllTests::main');
}
require_once 'Zend/Validate/Sitemap/ChangefreqTest.php';
require_once 'Zend/Validate/Sitemap/LastmodTest.php';
require_once 'Zend/Validate/Sitemap/LocTest.php';
require_once 'Zend/Validate/Sitemap/PriorityTest.php';
/**
* @category Zend
* @package Zend_Validate
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Validate
* @group Zend_Validate_Sitemap
*/
class Zend_Validate_Sitemap_AllTests
{
public static function main()
{
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('Zend Framework - Zend_Validate_Sitemap');
$suite->addTestSuite('Zend_Validate_Sitemap_ChangefreqTest');
$suite->addTestSuite('Zend_Validate_Sitemap_LastmodTest');
$suite->addTestSuite('Zend_Validate_Sitemap_LocTest');
$suite->addTestSuite('Zend_Validate_Sitemap_PriorityTest');
return $suite;
}
}
if (PHPUnit_MAIN_METHOD == 'Zend_Validate_Sitemap_AllTests::main') {
Zend_Validate_Sitemap_AllTests::main();
}
| karthiksekarnz/educulas | tests/Zend/Validate/Sitemap/AllTests.php | PHP | bsd-3-clause | 2,115 |
#include "ADTFPinMessageEncoder.h"
using namespace A2O;
ADTFPinMessageEncoder::ADTFPinMessageEncoder(IAction::Ptr action,
ICarMetaModel::ConstPtr carMetaModel)
: _action(action)
{
// Create output pins
const std::vector<IServoDriveConfig::ConstPtr>& servoDriveConfigs = carMetaModel->getServoDriveConfigs();
for (unsigned int i = 0; i < servoDriveConfigs.size(); i++) {
_pins.push_back(OutputPin(servoDriveConfigs[i]->getEffectorName(), "tSignalValue"));
}
std::vector<IActuatorConfig::ConstPtr> actuatorConfigs = carMetaModel->getMotorConfigs();
for (unsigned int i = 0; i < actuatorConfigs.size(); i++) {
_pins.push_back(OutputPin(actuatorConfigs[i]->getEffectorName(), "tSignalValue"));
}
actuatorConfigs = carMetaModel->getLightConfigs();
for (unsigned int i = 0; i < actuatorConfigs.size(); i++) {
_pins.push_back(OutputPin(actuatorConfigs[i]->getEffectorName(), "tBoolSignalValue"));
}
actuatorConfigs = carMetaModel->getManeuverStatusConfigs();
for (unsigned int i = 0; i < actuatorConfigs.size(); i++) {
_pins.push_back(OutputPin(actuatorConfigs[i]->getEffectorName(), "tDriverStruct"));
}
}
ADTFPinMessageEncoder::~ADTFPinMessageEncoder()
{
}
int ADTFPinMessageEncoder::indexOfPin(OutputPin pin) const
{
for (unsigned int i = 0; i < _pins.size(); i++) {
if (_pins[i] == pin) {
return i;
}
}
return -1;
}
const std::vector<OutputPin>& ADTFPinMessageEncoder::getOutputPins()
{
return _pins;
}
bool ADTFPinMessageEncoder::encode(const OutputPin& pin,
adtf::IMediaTypeDescription* mediaTypeDescription,
adtf::IMediaSample* mediaSample)
{
int pinIndex = indexOfPin(pin);
bool toTransmit = false;
if (pinIndex >= 0) {
cObjectPtr<adtf::IMediaSerializer> serializer;
mediaTypeDescription->GetMediaSampleSerializer(&serializer);
tInt size = serializer->GetDeserializedSize();
mediaSample->AllocBuffer(size);
cObjectPtr<adtf::IMediaCoder> mediaCoder;
tUInt32 timestamp = 0;
if (pin.signalType == "tBoolSignalValue") {
IBoolValueEffector::Ptr boolEffector = _action->getLightEffector(pin.name);
if (boolEffector) {
__adtf_sample_write_lock_mediadescription(mediaTypeDescription, mediaSample, mediaCoder);
if(!mediaCoder)
{
return false;
}
tBool value = boolEffector->getValue();
mediaCoder->Set("bValue", (tVoid*)&value);
mediaCoder->Set("ui32ArduinoTimestamp", (tVoid*)×tamp);
toTransmit = true;
}
} else if (pin.signalType == "tSignalValue") {
IDoubleValueEffector::Ptr valueEffector = boost::dynamic_pointer_cast<IDoubleValueEffector>(_action->getEffector(pin.name));
if (valueEffector) {
__adtf_sample_write_lock_mediadescription(mediaTypeDescription, mediaSample, mediaCoder);
if(!mediaCoder)
{
return false;
}
tFloat32 value = valueEffector->getValue();
mediaCoder->Set("f32Value", (tVoid*)&value);
mediaCoder->Set("ui32ArduinoTimestamp", (tVoid*)×tamp);
toTransmit = true;
}
} else if (pin.signalType == "tDriverStruct") {
IManeuverStatusEffector::Ptr valueEffector = boost::dynamic_pointer_cast<IManeuverStatusEffector>(_action->getEffector(pin.name));
if (valueEffector)
{
__adtf_sample_write_lock_mediadescription(mediaTypeDescription, mediaSample, mediaCoder);
if(!mediaCoder)
{
return false;
}
int state = valueEffector->getStatus();
int maneuverId = valueEffector->getManeuverId();
mediaCoder->Set("i8StateID", (tVoid*)&state);
mediaCoder->Set("i16ManeuverEntry", (tVoid*)&maneuverId);
toTransmit = true;
}
}
}
return toTransmit;
}
| AppliedAutonomyOffenburg/AADC_2015_A2O | src/aadcUser/src/HSOG_Runtime/adtf/encoder/ADTFPinMessageEncoder.cpp | C++ | bsd-3-clause | 3,690 |
<?php namespace Exchange\EWSType; use Exchange\EWSType;
/**
* Contains EWSType_TentativelyAcceptItemType.
*/
/**
* Represents a Tentative reply to a meeting request.
*
* @package php-ews\Types
*
* @todo Extend EWSType_WellKnownResponseObjectType.
*/
class EWSType_TentativelyAcceptItemType extends EWSType
{
/**
* Contains the item or file that is attached to an item in the Exchange
* store.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfAttachmentsType
*/
public $Attachments;
/**
* Represents a collection of recipients to receive a blind carbon copy
* (Bcc) of an e-mail.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfRecipientsType
*/
public $BccRecipients;
/**
* Represents the actual body content of a message.
*
* @since Exchange 2007
*
* @var EWSType_BodyType
*/
public $Body;
/**
* Represents a collection of recipients that will receive a copy of the
* message.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfRecipientsType
*/
public $CcRecipients;
/**
* Represents the Internet message header name for a given header within the
* headers collection.
*
* @since Exchange 2007
*
* @var EWSType_NonEmptyArrayOfInternetHeadersType
*/
public $InternetMessageHeaders;
/**
* Indicates whether the sender of an item requests a delivery receipt.
*
* @since Exchange 2007
*
* @var boolean
*/
public $IsDeliveryReceiptRequested;
/**
* Indicates whether the sender of an item requests a read receipt.
*
* @since Exchange 2007
*
* @var boolean
*/
public $IsReadReceiptRequested;
/**
* Represents the message class of an item.
*
* @since Exchange 2007
*
* @var EWSType_ItemClassType
*/
public $ItemClass;
/**
* Identifies the delegate in a delegate access scenario.
*
* @since Exchange 2007 SP1
*
* @var EWSType_SingleRecipientType
*/
public $ReceivedBy;
/**
* Identifies the principal in a delegate access scenario.
*
* @since Exchange 2007 SP1
*
* @var EWSType_SingleRecipientType
*/
public $ReceivedRepresenting;
/**
* Identifies the item to which the response object refers.
*
* @since Exchange 2007
*
* @var EWSType_ItemIdType
*/
public $ReferenceItemId;
/**
* Identifies the sender of an item.
*
* @since Exchange 2007
*
* @var EWSType_SingleRecipientType
*/
public $Sender;
/**
* Identifies the sensitivity of an item.
*
* @since Exchange 2007
*
* @var EWSType_SensitivityChoicesType
*/
public $Sensitivity;
/**
* Contains a set of recipients of an item.
*
* These are the primary recipients of an item.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfRecipientsType
*/
public $ToRecipients;
}
| segpacto/yii2-exchange | EWSType/EWSType_TentativelyAcceptItemType.php | PHP | bsd-3-clause | 3,092 |
# Running JupyterHub itself in docker
This is a simple example of running jupyterhub in a docker container.
This example will:
- create a docker network
- run jupyterhub in a container
- enable 'dummy authenticator' for testing
- run users in their own containers
It does not:
- enable persistent storage for users or the hub
- run the proxy in its own container
## Initial setup
The first thing we are going to do is create a network for jupyterhub to use.
```bash
docker network create jupyterhub
```
Second, we are going to build our hub image:
```bash
docker build -t hub .
```
We also want to pull the image that will be used:
```bash
docker pull jupyter/base-notebook
```
## Start the hub
To start the hub, we want to:
- run it on the docker network
- expose port 8000
- mount the host docker socket
```bash
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock --net jupyterhub --name jupyterhub -p8000:8000 hub
```
Now we should have jupyterhub running on port 8000 on our docker host.
## Further goals
This shows the *very basics* of running the Hub in a docker container (mainly setting up the network). To run for real, you will want to:
- mount a volume (or a database) for the hub state
- mount volumes for user storage so they don't lose data on each shutdown
- pick a real authenticator
- run the proxy in a separate container so that reloading hub configuration doesn't disrupt users
[jupyterhub-deploy-docker](https://github.com/jupyterhub/jupyterhub-deploy-docker) does all of these things.
| minrk/dockerspawner | examples/simple/README.md | Markdown | bsd-3-clause | 1,541 |
{-# LANGUAGE ParallelListComp #-}
module OldHMM
(Prob, HMM(..), train, bestSequence, sequenceProb)
where
import qualified Data.Map as M
import Data.List (sort, groupBy, maximumBy, foldl')
import Data.Maybe (fromMaybe, fromJust)
import Data.Ord (comparing)
import Data.Function (on)
import Control.Monad
import Data.Number.LogFloat
type Prob = LogFloat
-- | The type of Hidden Markov Models.
data HMM state observation = HMM [state] [Prob] [[Prob]] (observation -> [Prob])
instance (Show state, Show observation) => Show (HMM state observation) where
show (HMM states probs tpm _) = "HMM " ++ show states ++ " "
++ show probs ++ " " ++ show tpm ++ " <func>"
-- | Perform a single step in the Viterbi algorithm.
--
-- Takes a list of path probabilities, and an observation, and returns the updated
-- list of (surviving) paths with probabilities.
viterbi :: HMM state observation
-> [(Prob, [state])]
-> observation
-> [(Prob, [state])]
viterbi (HMM states _ state_transitions observations) prev x =
deepSeq prev `seq`
[maximumBy (comparing fst)
[(transition_prob * prev_prob * observation_prob,
new_state:path)
| transition_prob <- transition_probs
| (prev_prob, path) <- prev
| observation_prob <- observation_probs]
| transition_probs <- state_transitions
| new_state <- states]
where
observation_probs = observations x
deepSeq ((x, y:ys):xs) = x `seq` y `seq` (deepSeq xs)
deepSeq ((x, _):xs) = x `seq` (deepSeq xs)
deepSeq [] = []
-- | The initial value for the Viterbi algorithm
viterbi_init :: HMM state observation -> [(Prob, [state])]
viterbi_init (HMM states state_probs _ _) = zip state_probs (map (:[]) states)
-- | Perform a single step of the forward algorithm
--
-- Each item in the input and output list is the probability that the system
-- ended in the respective state.
forward :: HMM state observation
-> [Prob]
-> observation
-> [Prob]
forward (HMM _ _ state_transitions observations) prev x =
last prev `seq`
[sum [transition_prob * prev_prob * observation_prob
| transition_prob <- transition_probs
| prev_prob <- prev
| observation_prob <- observation_probs]
| transition_probs <- state_transitions]
where
observation_probs = observations x
-- | The initial value for the forward algorithm
forward_init :: HMM state observation -> [Prob]
forward_init (HMM _ state_probs _ _) = state_probs
learn_states :: (Ord state, Fractional prob) => [(observation, state)] -> M.Map state prob
learn_states xs = histogram $ map snd xs
learn_transitions :: (Ord state, Fractional prob) => [(observation, state)] -> M.Map (state, state) prob
learn_transitions xs = let xs' = map snd xs in
histogram $ zip xs' (tail xs')
learn_observations :: (Ord state, Ord observation, Fractional prob) =>
M.Map state prob
-> [(observation, state)]
-> M.Map (observation, state) prob
learn_observations state_prob = M.mapWithKey (\ (observation, state) prob -> prob / (fromJust $ M.lookup state state_prob))
. histogram
histogram :: (Ord a, Fractional prob) => [a] -> M.Map a prob
histogram xs = let hist = foldl' (flip $ flip (M.insertWith (+)) 1) M.empty xs in
M.map (/ M.fold (+) 0 hist) hist
-- | Calculate the parameters of an HMM from a list of observations
-- and the corresponding states.
train :: (Ord observation, Ord state) =>
[(observation, state)]
-> HMM state observation
train sample = model
where
states = learn_states sample
state_list = M.keys states
transitions = learn_transitions sample
trans_prob_mtx = [[fromMaybe 1e-10 $ M.lookup (old_state, new_state) transitions
| old_state <- state_list]
| new_state <- state_list]
observations = learn_observations states sample
observation_probs = fromMaybe (fill state_list []) . (flip M.lookup $
M.fromList $ map (\ (e, xs) -> (e, fill state_list xs)) $
map (\ xs -> (fst $ head xs, map snd xs)) $
groupBy ((==) `on` fst)
[(observation, (state, prob))
| ((observation, state), prob) <- M.toAscList observations])
initial = map (\ state -> (fromJust $ M.lookup state states, [state])) state_list
model = HMM state_list (fill state_list $ M.toAscList states) trans_prob_mtx observation_probs
fill :: Eq state => [state] -> [(state, Prob)] -> [Prob]
fill states [] = map (const 1e-10) states
fill (s:states) xs@((s', p):xs') = if s /= s' then
1e-10 : fill states xs
else
p : fill states xs'
-- | Calculate the most likely sequence of states for a given sequence of observations
-- using Viterbi's algorithm
bestSequence :: (Ord observation) => HMM state observation -> [observation] -> [state]
bestSequence hmm = (reverse . tail . snd . (maximumBy (comparing fst))) . (foldl' (viterbi hmm) (viterbi_init hmm))
-- | Calculate the probability of a given sequence of observations
-- using the forward algorithm.
sequenceProb :: (Ord observation) => HMM state observation -> [observation] -> Prob
sequenceProb hmm = sum . (foldl' (forward hmm) (forward_init hmm)) | mikeizbicki/hmm | OldHMM.hs | Haskell | bsd-3-clause | 5,845 |
<?php
namespace app\modules\admin\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Trigger;
/**
* TriggerSearch represents the model behind the search form about `app\models\Trigger`.
*/
class TriggerSearch extends Trigger
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'type', 'item_id', 'active'], 'integer'],
[['date', 'time', 'weekdays', 'item_value', 'name'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Trigger::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'type' => $this->type,
'item_id' => $this->item_id,
'active' => $this->active,
]);
$query->andFilterWhere(['like', 'date', $this->date])
->andFilterWhere(['like', 'time', $this->time])
->andFilterWhere(['like', 'weekdays', $this->weekdays])
->andFilterWhere(['like', 'item_value', $this->item_value])
->andFilterWhere(['like', 'name', $this->name]);
return $dataProvider;
}
}
| CyanoFresh/SmartHome | modules/admin/models/TriggerSearch.php | PHP | bsd-3-clause | 1,914 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdlib.h>
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/net/url_fixer_upper.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/url_parse.h"
namespace {
class URLFixerUpperTest : public testing::Test {
};
};
namespace url_parse {
std::ostream& operator<<(std::ostream& os, const Component& part) {
return os << "(begin=" << part.begin << ", len=" << part.len << ")";
}
} // namespace url_parse
struct SegmentCase {
const std::string input;
const std::string result;
const url_parse::Component scheme;
const url_parse::Component username;
const url_parse::Component password;
const url_parse::Component host;
const url_parse::Component port;
const url_parse::Component path;
const url_parse::Component query;
const url_parse::Component ref;
};
static const SegmentCase segment_cases[] = {
{ "http://www.google.com/", "http",
url_parse::Component(0, 4), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(7, 14), // host
url_parse::Component(), // port
url_parse::Component(21, 1), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "aBoUt:vErSiOn", "about",
url_parse::Component(0, 5), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(6, 7), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "about:host/path?query#ref", "about",
url_parse::Component(0, 5), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(6, 4), // host
url_parse::Component(), // port
url_parse::Component(10, 5), // path
url_parse::Component(16, 5), // query
url_parse::Component(22, 3), // ref
},
{ "about://host/path?query#ref", "about",
url_parse::Component(0, 5), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(8, 4), // host
url_parse::Component(), // port
url_parse::Component(12, 5), // path
url_parse::Component(18, 5), // query
url_parse::Component(24, 3), // ref
},
{ "chrome:host/path?query#ref", "chrome",
url_parse::Component(0, 6), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(7, 4), // host
url_parse::Component(), // port
url_parse::Component(11, 5), // path
url_parse::Component(17, 5), // query
url_parse::Component(23, 3), // ref
},
{ "chrome://host/path?query#ref", "chrome",
url_parse::Component(0, 6), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(9, 4), // host
url_parse::Component(), // port
url_parse::Component(13, 5), // path
url_parse::Component(19, 5), // query
url_parse::Component(25, 3), // ref
},
{ " www.google.com:124?foo#", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(4, 14), // host
url_parse::Component(19, 3), // port
url_parse::Component(), // path
url_parse::Component(23, 3), // query
url_parse::Component(27, 0), // ref
},
{ "[email protected]", "http",
url_parse::Component(), // scheme
url_parse::Component(0, 4), // username
url_parse::Component(), // password
url_parse::Component(5, 14), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "ftp:/user:P:[email protected]...::23///pub?foo#bar", "ftp",
url_parse::Component(0, 3), // scheme
url_parse::Component(5, 4), // username
url_parse::Component(10, 7), // password
url_parse::Component(18, 20), // host
url_parse::Component(39, 2), // port
url_parse::Component(41, 6), // path
url_parse::Component(48, 3), // query
url_parse::Component(52, 3), // ref
},
{ "[2001:db8::1]/path", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 13), // host
url_parse::Component(), // port
url_parse::Component(13, 5), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "[::1]", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 5), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
// Incomplete IPv6 addresses (will not canonicalize).
{ "[2001:4860:", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 11), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "[2001:4860:/foo", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 11), // host
url_parse::Component(), // port
url_parse::Component(11, 4), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "http://:b005::68]", "http",
url_parse::Component(0, 4), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(7, 10), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
// Can't do anything useful with this.
{ ":b005::68]", "",
url_parse::Component(0, 0), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
};
TEST(URLFixerUpperTest, SegmentURL) {
std::string result;
url_parse::Parsed parts;
for (size_t i = 0; i < arraysize(segment_cases); ++i) {
SegmentCase value = segment_cases[i];
result = URLFixerUpper::SegmentURL(value.input, &parts);
EXPECT_EQ(value.result, result);
EXPECT_EQ(value.scheme, parts.scheme);
EXPECT_EQ(value.username, parts.username);
EXPECT_EQ(value.password, parts.password);
EXPECT_EQ(value.host, parts.host);
EXPECT_EQ(value.port, parts.port);
EXPECT_EQ(value.path, parts.path);
EXPECT_EQ(value.query, parts.query);
EXPECT_EQ(value.ref, parts.ref);
}
}
// Creates a file and returns its full name as well as the decomposed
// version. Example:
// full_path = "c:\foo\bar.txt"
// dir = "c:\foo"
// file_name = "bar.txt"
static bool MakeTempFile(const base::FilePath& dir,
const base::FilePath& file_name,
base::FilePath* full_path) {
*full_path = dir.Append(file_name);
return file_util::WriteFile(*full_path, "", 0) == 0;
}
// Returns true if the given URL is a file: URL that matches the given file
static bool IsMatchingFileURL(const std::string& url,
const base::FilePath& full_file_path) {
if (url.length() <= 8)
return false;
if (std::string("file:///") != url.substr(0, 8))
return false; // no file:/// prefix
if (url.find('\\') != std::string::npos)
return false; // contains backslashes
base::FilePath derived_path;
net::FileURLToFilePath(GURL(url), &derived_path);
return base::FilePath::CompareEqualIgnoreCase(derived_path.value(),
full_file_path.value());
}
struct FixupCase {
const std::string input;
const std::string desired_tld;
const std::string output;
} fixup_cases[] = {
{"www.google.com", "", "http://www.google.com/"},
{" www.google.com ", "", "http://www.google.com/"},
{" foo.com/asdf bar", "", "http://foo.com/asdf%20%20bar"},
{"..www.google.com..", "", "http://www.google.com./"},
{"http://......", "", "http://....../"},
{"http://host.com:ninety-two/", "", "http://host.com:ninety-two/"},
{"http://host.com:ninety-two?foo", "", "http://host.com:ninety-two/?foo"},
{"google.com:123", "", "http://google.com:123/"},
{"about:", "", "chrome://version/"},
{"about:foo", "", "chrome://foo/"},
{"about:version", "", "chrome://version/"},
{"about:usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"about://usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"chrome:usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"chrome://usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"www:123", "", "http://www:123/"},
{" www:123", "", "http://www:123/"},
{"www.google.com?foo", "", "http://www.google.com/?foo"},
{"www.google.com#foo", "", "http://www.google.com/#foo"},
{"www.google.com?", "", "http://www.google.com/?"},
{"www.google.com#", "", "http://www.google.com/#"},
{"www.google.com:123?foo#bar", "", "http://www.google.com:123/?foo#bar"},
{"[email protected]", "", "http://[email protected]/"},
{"\xE6\xB0\xB4.com" , "", "http://xn--1rw.com/"},
// It would be better if this next case got treated as http, but I don't see
// a clean way to guess this isn't the new-and-exciting "user" scheme.
{"user:[email protected]:8080/", "", "user:[email protected]:8080/"},
// {"file:///c:/foo/bar%20baz.txt", "", "file:///C:/foo/bar%20baz.txt"},
{"ftp.google.com", "", "ftp://ftp.google.com/"},
{" ftp.google.com", "", "ftp://ftp.google.com/"},
{"FTP.GooGle.com", "", "ftp://ftp.google.com/"},
{"ftpblah.google.com", "", "http://ftpblah.google.com/"},
{"ftp", "", "http://ftp/"},
{"google.ftp.com", "", "http://google.ftp.com/"},
// URLs which end with 0x85 (NEL in ISO-8859).
{ "http://google.com/search?q=\xd0\x85", "",
"http://google.com/search?q=%D0%85"
},
{ "http://google.com/search?q=\xec\x97\x85", "",
"http://google.com/search?q=%EC%97%85"
},
{ "http://google.com/search?q=\xf0\x90\x80\x85", "",
"http://google.com/search?q=%F0%90%80%85"
},
// URLs which end with 0xA0 (non-break space in ISO-8859).
{ "http://google.com/search?q=\xd0\xa0", "",
"http://google.com/search?q=%D0%A0"
},
{ "http://google.com/search?q=\xec\x97\xa0", "",
"http://google.com/search?q=%EC%97%A0"
},
{ "http://google.com/search?q=\xf0\x90\x80\xa0", "",
"http://google.com/search?q=%F0%90%80%A0"
},
// URLs containing IPv6 literals.
{"[2001:db8::2]", "", "http://[2001:db8::2]/"},
{"[::]:80", "", "http://[::]/"},
{"[::]:80/path", "", "http://[::]/path"},
{"[::]:180/path", "", "http://[::]:180/path"},
// TODO(pmarks): Maybe we should parse bare IPv6 literals someday.
{"::1", "", "::1"},
// Semicolon as scheme separator for standard schemes.
{"http;//www.google.com/", "", "http://www.google.com/"},
{"about;chrome", "", "chrome://chrome/"},
// Semicolon left as-is for non-standard schemes.
{"whatsup;//fool", "", "whatsup://fool"},
// Semicolon left as-is in URL itself.
{"http://host/port?query;moar", "", "http://host/port?query;moar"},
// Fewer slashes than expected.
{"http;www.google.com/", "", "http://www.google.com/"},
{"http;/www.google.com/", "", "http://www.google.com/"},
// Semicolon at start.
{";http://www.google.com/", "", "http://%3Bhttp//www.google.com/"},
};
TEST(URLFixerUpperTest, FixupURL) {
for (size_t i = 0; i < arraysize(fixup_cases); ++i) {
FixupCase value = fixup_cases[i];
EXPECT_EQ(value.output, URLFixerUpper::FixupURL(value.input,
value.desired_tld).possibly_invalid_spec())
<< "input: " << value.input;
}
// Check the TLD-appending functionality
FixupCase tld_cases[] = {
{"google", "com", "http://www.google.com/"},
{"google.", "com", "http://www.google.com/"},
{"google..", "com", "http://www.google.com/"},
{".google", "com", "http://www.google.com/"},
{"www.google", "com", "http://www.google.com/"},
{"google.com", "com", "http://google.com/"},
{"http://google", "com", "http://www.google.com/"},
{"..google..", "com", "http://www.google.com/"},
{"http://www.google", "com", "http://www.google.com/"},
{"9999999999999999", "com", "http://www.9999999999999999.com/"},
{"google/foo", "com", "http://www.google.com/foo"},
{"google.com/foo", "com", "http://google.com/foo"},
{"google/?foo=.com", "com", "http://www.google.com/?foo=.com"},
{"www.google/?foo=www.", "com", "http://www.google.com/?foo=www."},
{"google.com/?foo=.com", "com", "http://google.com/?foo=.com"},
{"http://www.google.com", "com", "http://www.google.com/"},
{"google:123", "com", "http://www.google.com:123/"},
{"http://google:123", "com", "http://www.google.com:123/"},
};
for (size_t i = 0; i < arraysize(tld_cases); ++i) {
FixupCase value = tld_cases[i];
EXPECT_EQ(value.output, URLFixerUpper::FixupURL(value.input,
value.desired_tld).possibly_invalid_spec());
}
}
// Test different types of file inputs to URIFixerUpper::FixupURL. This
// doesn't go into the nice array of fixups above since the file input
// has to exist.
TEST(URLFixerUpperTest, FixupFile) {
// this "original" filename is the one we tweak to get all the variations
base::FilePath dir;
base::FilePath original;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir));
ASSERT_TRUE(MakeTempFile(
dir,
base::FilePath(FILE_PATH_LITERAL("url fixer upper existing file.txt")),
&original));
// reference path
GURL golden(net::FilePathToFileURL(original));
// c:\foo\bar.txt -> file:///c:/foo/bar.txt (basic)
#if defined(OS_WIN)
GURL fixedup(URLFixerUpper::FixupURL(base::WideToUTF8(original.value()),
std::string()));
#elif defined(OS_POSIX)
GURL fixedup(URLFixerUpper::FixupURL(original.value(), std::string()));
#endif
EXPECT_EQ(golden, fixedup);
// TODO(port): Make some equivalent tests for posix.
#if defined(OS_WIN)
// c|/foo\bar.txt -> file:///c:/foo/bar.txt (pipe allowed instead of colon)
std::string cur(base::WideToUTF8(original.value()));
EXPECT_EQ(':', cur[1]);
cur[1] = '|';
EXPECT_EQ(golden, URLFixerUpper::FixupURL(cur, std::string()));
FixupCase file_cases[] = {
{"c:\\This%20is a non-existent file.txt", "",
"file:///C:/This%2520is%20a%20non-existent%20file.txt"},
// \\foo\bar.txt -> file://foo/bar.txt
// UNC paths, this file won't exist, but since there are no escapes, it
// should be returned just converted to a file: URL.
{"\\\\SomeNonexistentHost\\foo\\bar.txt", "",
"file://somenonexistenthost/foo/bar.txt"},
// We do this strictly, like IE8, which only accepts this form using
// backslashes and not forward ones. Turning "//foo" into "http" matches
// Firefox and IE, silly though it may seem (it falls out of adding "http"
// as the default protocol if you haven't entered one).
{"//SomeNonexistentHost\\foo/bar.txt", "",
"http://somenonexistenthost/foo/bar.txt"},
{"file:///C:/foo/bar", "", "file:///C:/foo/bar"},
// Much of the work here comes from GURL's canonicalization stage.
{"file://C:/foo/bar", "", "file:///C:/foo/bar"},
{"file:c:", "", "file:///C:/"},
{"file:c:WINDOWS", "", "file:///C:/WINDOWS"},
{"file:c|Program Files", "", "file:///C:/Program%20Files"},
{"file:/file", "", "file://file/"},
{"file:////////c:\\foo", "", "file:///C:/foo"},
{"file://server/folder/file", "", "file://server/folder/file"},
// These are fixups we don't do, but could consider:
//
// {"file:///foo:/bar", "", "file://foo/bar"},
// {"file:/\\/server\\folder/file", "", "file://server/folder/file"},
};
#elif defined(OS_POSIX)
#if defined(OS_MACOSX)
#define HOME "/Users/"
#else
#define HOME "/home/"
#endif
URLFixerUpper::home_directory_override = "/foo";
FixupCase file_cases[] = {
// File URLs go through GURL, which tries to escape intelligently.
{"/This%20is a non-existent file.txt", "",
"file:///This%2520is%20a%20non-existent%20file.txt"},
// A plain "/" refers to the root.
{"/", "",
"file:///"},
// These rely on the above home_directory_override.
{"~", "",
"file:///foo"},
{"~/bar", "",
"file:///foo/bar"},
// References to other users' homedirs.
{"~foo", "",
"file://" HOME "foo"},
{"~x/blah", "",
"file://" HOME "x/blah"},
};
#endif
for (size_t i = 0; i < arraysize(file_cases); i++) {
EXPECT_EQ(file_cases[i].output, URLFixerUpper::FixupURL(file_cases[i].input,
file_cases[i].desired_tld).possibly_invalid_spec());
}
EXPECT_TRUE(base::DeleteFile(original, false));
}
TEST(URLFixerUpperTest, FixupRelativeFile) {
base::FilePath full_path, dir;
base::FilePath file_part(
FILE_PATH_LITERAL("url_fixer_upper_existing_file.txt"));
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir));
ASSERT_TRUE(MakeTempFile(dir, file_part, &full_path));
full_path = base::MakeAbsoluteFilePath(full_path);
ASSERT_FALSE(full_path.empty());
// make sure we pass through good URLs
for (size_t i = 0; i < arraysize(fixup_cases); ++i) {
FixupCase value = fixup_cases[i];
base::FilePath input = base::FilePath::FromUTF8Unsafe(value.input);
EXPECT_EQ(value.output,
URLFixerUpper::FixupRelativeFile(dir, input).possibly_invalid_spec());
}
// make sure the existing file got fixed-up to a file URL, and that there
// are no backslashes
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
file_part).possibly_invalid_spec(), full_path));
EXPECT_TRUE(base::DeleteFile(full_path, false));
// create a filename we know doesn't exist and make sure it doesn't get
// fixed up to a file URL
base::FilePath nonexistent_file(
FILE_PATH_LITERAL("url_fixer_upper_nonexistent_file.txt"));
std::string fixedup(URLFixerUpper::FixupRelativeFile(dir,
nonexistent_file).possibly_invalid_spec());
EXPECT_NE(std::string("file:///"), fixedup.substr(0, 8));
EXPECT_FALSE(IsMatchingFileURL(fixedup, nonexistent_file));
// make a subdir to make sure relative paths with directories work, also
// test spaces:
// "app_dir\url fixer-upper dir\url fixer-upper existing file.txt"
base::FilePath sub_dir(FILE_PATH_LITERAL("url fixer-upper dir"));
base::FilePath sub_file(
FILE_PATH_LITERAL("url fixer-upper existing file.txt"));
base::FilePath new_dir = dir.Append(sub_dir);
base::CreateDirectory(new_dir);
ASSERT_TRUE(MakeTempFile(new_dir, sub_file, &full_path));
full_path = base::MakeAbsoluteFilePath(full_path);
ASSERT_FALSE(full_path.empty());
// test file in the subdir
base::FilePath relative_file = sub_dir.Append(sub_file);
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
relative_file).possibly_invalid_spec(), full_path));
// test file in the subdir with different slashes and escaping.
base::FilePath::StringType relative_file_str = sub_dir.value() +
FILE_PATH_LITERAL("/") + sub_file.value();
ReplaceSubstringsAfterOffset(&relative_file_str, 0,
FILE_PATH_LITERAL(" "), FILE_PATH_LITERAL("%20"));
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
base::FilePath(relative_file_str)).possibly_invalid_spec(), full_path));
// test relative directories and duplicate slashes
// (should resolve to the same file as above)
relative_file_str = sub_dir.value() + FILE_PATH_LITERAL("/../") +
sub_dir.value() + FILE_PATH_LITERAL("///./") + sub_file.value();
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
base::FilePath(relative_file_str)).possibly_invalid_spec(), full_path));
// done with the subdir
EXPECT_TRUE(base::DeleteFile(full_path, false));
EXPECT_TRUE(base::DeleteFile(new_dir, true));
// Test that an obvious HTTP URL isn't accidentally treated as an absolute
// file path (on account of system-specific craziness).
base::FilePath empty_path;
base::FilePath http_url_path(FILE_PATH_LITERAL("http://../"));
EXPECT_TRUE(URLFixerUpper::FixupRelativeFile(
empty_path, http_url_path).SchemeIs("http"));
}
| ChromiumWebApps/chromium | chrome/common/net/url_fixer_upper_unittest.cc | C++ | bsd-3-clause | 20,955 |
#<pycode(py_choose)>
class Choose:
"""
Choose - class for choose() with callbacks
"""
def __init__(self, list, title, flags=0, deflt=1, icon=37):
self.list = list
self.title = title
self.flags = flags
self.x0 = -1
self.x1 = -1
self.y0 = -1
self.y1 = -1
self.width = -1
self.deflt = deflt
self.icon = icon
# HACK: Add a circular reference for non-modal choosers. This prevents the GC
# from collecting the class object the callbacks need. Unfortunately this means
# that the class will never be collected, unless refhack is set to None explicitly.
if (flags & Choose2.CH_MODAL) == 0:
self.refhack = self
def sizer(self):
"""
Callback: sizer - returns the length of the list
"""
return len(self.list)
def getl(self, n):
"""
Callback: getl - get one item from the list
"""
if n == 0:
return self.title
if n <= self.sizer():
return str(self.list[n-1])
else:
return "<Empty>"
def ins(self):
pass
def update(self, n):
pass
def edit(self, n):
pass
def enter(self, n):
print "enter(%d) called" % n
def destroy(self):
pass
def get_icon(self, n):
pass
def choose(self):
"""
choose - Display the choose dialogue
"""
old = set_script_timeout(0)
n = _idaapi.choose_choose(
self,
self.flags,
self.x0,
self.y0,
self.x1,
self.y1,
self.width,
self.deflt,
self.icon)
set_script_timeout(old)
return n
#</pycode(py_choose)>
| nihilus/src | pywraps/py_choose.py | Python | bsd-3-clause | 1,595 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Console;
/**
* A static, utility class for interacting with Console environment.
* Declared abstract to prevent from instantiating.
*/
abstract class Console
{
/**
* @var Adapter\AdapterInterface
*/
protected static $instance;
/**
* Allow overriding whether or not we're in a console env. If set, and
* boolean, returns that value from isConsole().
* @var bool
*/
protected static $isConsole;
/**
* Create and return Adapter\AdapterInterface instance.
*
* @param null|string $forceAdapter Optional adapter class name. Can be absolute namespace or class name
* relative to Zend\Console\Adapter\. If not provided, a best matching
* adapter will be automatically selected.
* @param null|string $forceCharset optional charset name can be absolute namespace or class name relative to
* Zend\Console\Charset\. If not provided, charset will be detected
* automatically.
* @throws Exception\InvalidArgumentException
* @throws Exception\RuntimeException
* @return Adapter\AdapterInterface
*/
public static function getInstance($forceAdapter = null, $forceCharset = null)
{
if (static::$instance instanceof Adapter\AdapterInterface) {
return static::$instance;
}
// Create instance
if ($forceAdapter !== null) {
// Use the supplied adapter class
if (substr($forceAdapter, 0, 1) == '\\') {
$className = $forceAdapter;
} elseif (stristr($forceAdapter, '\\')) {
$className = __NAMESPACE__ . '\\' . ltrim($forceAdapter, '\\');
} else {
$className = __NAMESPACE__ . '\\Adapter\\' . $forceAdapter;
}
if (!class_exists($className)) {
throw new Exception\InvalidArgumentException(sprintf(
'Cannot find Console adapter class "%s"',
$className
));
}
} else {
// Try to detect best instance for console
$className = static::detectBestAdapter();
// Check if we were able to detect console adapter
if (!$className) {
throw new Exception\RuntimeException('Cannot create Console adapter - am I running in a console?');
}
}
// Create adapter instance
static::$instance = new $className();
// Try to use the supplied charset class
if ($forceCharset !== null) {
if (substr($forceCharset, 0, 1) == '\\') {
$className = $forceCharset;
} elseif (stristr($forceAdapter, '\\')) {
$className = __NAMESPACE__ . '\\' . ltrim($forceCharset, '\\');
} else {
$className = __NAMESPACE__ . '\\Charset\\' . $forceCharset;
}
if (!class_exists($className)) {
throw new Exception\InvalidArgumentException(sprintf(
'Cannot find Charset class "%s"',
$className
));
}
// Set adapter charset
static::$instance->setCharset(new $className());
}
return static::$instance;
}
/**
* Reset the console instance
*/
public static function resetInstance()
{
static::$instance = null;
}
/**
* Check if currently running under MS Windows
*
* @see http://stackoverflow.com/questions/738823/possible-values-for-php-os
* @return bool
*/
public static function isWindows()
{
return
(defined('PHP_OS') && (substr_compare(PHP_OS, 'win', 0, 3, true) === 0)) ||
(getenv('OS') != false && substr_compare(getenv('OS'), 'windows', 0, 7, true))
;
}
/**
* Check if running under MS Windows Ansicon
*
* @return bool
*/
public static function isAnsicon()
{
return getenv('ANSICON') !== false;
}
/**
* Check if running in a console environment (CLI)
*
* By default, returns value of PHP_SAPI global constant. If $isConsole is
* set, and a boolean value, that value will be returned.
*
* @return bool
*/
public static function isConsole()
{
if (null === static::$isConsole) {
static::$isConsole = (PHP_SAPI == 'cli');
}
return static::$isConsole;
}
/**
* Override the "is console environment" flag
*
* @param null|bool $flag
*/
public static function overrideIsConsole($flag)
{
if (null != $flag) {
$flag = (bool) $flag;
}
static::$isConsole = $flag;
}
/**
* Try to detect best matching adapter
* @return string|null
*/
public static function detectBestAdapter()
{
// Check if we are in a console environment
if (!static::isConsole()) {
return null;
}
// Check if we're on windows
if (static::isWindows()) {
if (static::isAnsicon()) {
$className = __NAMESPACE__ . '\Adapter\WindowsAnsicon';
} else {
$className = __NAMESPACE__ . '\Adapter\Windows';
}
return $className;
}
// Default is a Posix console
$className = __NAMESPACE__ . '\Adapter\Posix';
return $className;
}
/**
* Pass-thru static call to current AdapterInterface instance.
*
* @param $funcName
* @param $arguments
* @return mixed
*/
public static function __callStatic($funcName, $arguments)
{
$instance = static::getInstance();
return call_user_func_array(array($instance, $funcName), $arguments);
}
}
| ishvaram/email-app | vendor/ZF2/library/Zend/Console/Console.php | PHP | bsd-3-clause | 6,488 |
<dom-module id="my-scientists-list">
<template>
<firebase-collection data="{{scientists}}"
location="https://radiant-fire-9062.firebaseio.com/users">
</firebase-collection>
<template is="dom-repeat" items="[[scientists]]" as="scientist">
<p>Element: <span>[[index]]</span></p>
<p class="">Name: <a href="[[_itemUrl(scientist)]]"><span>[[scientist.firstName]]</span> <span>[[scientist.lastName]]</span></a></p>
<my-group-essentials group-id="[[scientist.groupId]]" keywords-ids="[[scientist.keywordsIds]]"></my-group-essentials>
<!-- profile should be in the menu bar -->
<a href="/profile/georg">profile of georg</a>
<p>//////////////////////////////</p>
</template>
</template>
<script>
(function () {
Polymer({
is: 'my-scientists-list',
_itemUrl: function(obj) {
return '/scientist/' + obj.firstName.replace(/ /g, '') + obj.lastName.replace(/ /g, '') + '/' + obj.__firebaseKey__;
},
});
})();
</script>
</dom-module> | salah-saleh/forsker | app/elements/scientists/my-scientists-list.html | HTML | bsd-3-clause | 1,063 |
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using ServiceStack.Common.Web;
namespace ServiceStack.WebHost.Endpoints.Support.Metadata.Controls
{
internal class Soap12OperationControl : OperationControl
{
public Soap12OperationControl()
{
EndpointType = EndpointType.Soap12;
}
public override string RequestUri
{
get
{
var endpointConfig = MetadataConfig.GetEndpointConfig(EndpointType);
var endpontPath = ResponseMessage != null ? endpointConfig.SyncReplyUri : endpointConfig.AsyncOneWayUri;
return string.Format("/{0}", endpontPath);
}
}
public override string HttpRequestTemplate
{
get
{
return string.Format(
@"POST {0} HTTP/1.1
Host: {1}
Content-Type: text/xml; charset=utf-8
Content-Length: <span class=""value"">length</span>
{2}", RequestUri, HostName, HttpUtility.HtmlEncode(RequestMessage));
}
}
}
} | firstsee/ServiceStack | src/ServiceStack.WebHost.Endpoints/Support/Metadata/Controls/Soap12OperationControl.cs | C# | bsd-3-clause | 908 |
<?php
/**
* inerface INewsDB
* содержит основные методы для работы с новостной лентой
*/
interface INewsDB{
/**
* Добавление новой записи в новостную ленту
*
* @param string $title - заголовок новости
* @param string $category - категория новости
* @param string $description - текст новости
* @param string $source - источник новости
*
* @return boolean - результат успех/ошибка
*/
function saveNews($t, $c, $d, $s);
/**
* Выборка всех записей из новостной ленты
*
* @return array - результат выборки в виде массива
*/
function getNews();
/**
* Удаление записи из новостной ленты
*
* @param integer $id - идентификатор удаляемой записи
*
* @return boolean - результат успех/ошибка
*/
function deleteNews($id);
}
?> | sowanderr/phonebook | web/phone/INewsDB.class.php | PHP | bsd-3-clause | 1,140 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_CROSTINI_CROSTINI_ENGAGEMENT_METRICS_SERVICE_H_
#define CHROME_BROWSER_ASH_CROSTINI_CROSTINI_ENGAGEMENT_METRICS_SERVICE_H_
#include "base/macros.h"
#include "base/no_destructor.h"
#include "components/guest_os/guest_os_engagement_metrics.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
#include "components/keyed_service/core/keyed_service.h"
class Profile;
namespace crostini {
// A KeyedService for tracking engagement with Crostini, reporting values as
// per GuestOsEngagementMetrics.
class CrostiniEngagementMetricsService : public KeyedService {
public:
class Factory : public BrowserContextKeyedServiceFactory {
public:
static CrostiniEngagementMetricsService* GetForProfile(Profile* profile);
static Factory* GetInstance();
private:
friend class base::NoDestructor<Factory>;
Factory();
~Factory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
bool ServiceIsCreatedWithBrowserContext() const override;
bool ServiceIsNULLWhileTesting() const override;
};
explicit CrostiniEngagementMetricsService(Profile* profile);
CrostiniEngagementMetricsService(const CrostiniEngagementMetricsService&) =
delete;
CrostiniEngagementMetricsService& operator=(
const CrostiniEngagementMetricsService&) = delete;
~CrostiniEngagementMetricsService() override;
// This needs to be called when Crostini starts and stops being active so we
// can correctly track background active time.
void SetBackgroundActive(bool background_active);
private:
std::unique_ptr<guest_os::GuestOsEngagementMetrics>
guest_os_engagement_metrics_;
};
} // namespace crostini
#endif // CHROME_BROWSER_ASH_CROSTINI_CROSTINI_ENGAGEMENT_METRICS_SERVICE_H_
| nwjs/chromium.src | chrome/browser/ash/crostini/crostini_engagement_metrics_service.h | C | bsd-3-clause | 2,046 |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>second_derivative — MetPy 0.8</title>
<link rel="shortcut icon" href="../../_static/metpy_32x32.ico"/>
<link rel="canonical" href="https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.second_derivative.html"/>
<link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />
<link rel="stylesheet" href="../../_static/theme_override.css" type="text/css" />
<link rel="index" title="Index"
href="../../genindex.html"/>
<link rel="search" title="Search" href="../../search.html"/>
<link rel="top" title="MetPy 0.8" href="../../index.html"/>
<link rel="up" title="calc" href="metpy.calc.html"/>
<link rel="next" title="shearing_deformation" href="metpy.calc.shearing_deformation.html"/>
<link rel="prev" title="saturation_vapor_pressure" href="metpy.calc.saturation_vapor_pressure.html"/>
<script src="../../_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="../../index.html" class="icon icon-home"> MetPy
<img src="../../_static/metpy_150x150.png" class="logo" />
</a>
<div class="version">
<div class="version-dropdown">
<select class="version-list" id="version-list">
<option value=''>0.8</option>
<option value="../latest">latest</option>
<option value="../dev">dev</option>
</select>
</div>
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../../installguide.html">Installation Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../units.html">Unit Support</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../examples/index.html">MetPy Examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../tutorials/index.html">MetPy Tutorials</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../index.html">The MetPy API</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="metpy.constants.html">constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.units.html">units</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.io.html">io</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.io.cdm.html">cdm</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="metpy.calc.html">calc</a><ul class="current">
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.absolute_vorticity.html">absolute_vorticity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.add_height_to_pressure.html">add_height_to_pressure</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.add_pressure_to_height.html">add_pressure_to_height</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.advection.html">advection</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.ageostrophic_wind.html">ageostrophic_wind</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.apparent_temperature.html">apparent_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.brunt_vaisala_frequency.html">brunt_vaisala_frequency</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.brunt_vaisala_frequency_squared.html">brunt_vaisala_frequency_squared</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.brunt_vaisala_period.html">brunt_vaisala_period</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.bulk_shear.html">bulk_shear</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.bunkers_storm_motion.html">bunkers_storm_motion</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.cape_cin.html">cape_cin</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.convergence_vorticity.html">convergence_vorticity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.coriolis_parameter.html">coriolis_parameter</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.critical_angle.html">critical_angle</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.density.html">density</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dewpoint.html">dewpoint</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dewpoint_from_specific_humidity.html">dewpoint_from_specific_humidity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dewpoint_rh.html">dewpoint_rh</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.divergence.html">divergence</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dry_lapse.html">dry_lapse</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.dry_static_energy.html">dry_static_energy</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.el.html">el</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.equivalent_potential_temperature.html">equivalent_potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.exner_function.html">exner_function</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.find_bounding_indices.html">find_bounding_indices</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.find_intersections.html">find_intersections</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.first_derivative.html">first_derivative</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.friction_velocity.html">friction_velocity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.frontogenesis.html">frontogenesis</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.geopotential_to_height.html">geopotential_to_height</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.geostrophic_wind.html">geostrophic_wind</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_layer.html">get_layer</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_layer_heights.html">get_layer_heights</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_perturbation.html">get_perturbation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_components.html">get_wind_components</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_dir.html">get_wind_dir</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.get_wind_speed.html">get_wind_speed</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.gradient.html">gradient</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.h_convergence.html">h_convergence</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.heat_index.html">heat_index</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.height_to_geopotential.html">height_to_geopotential</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.height_to_pressure_std.html">height_to_pressure_std</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.inertial_advective_wind.html">inertial_advective_wind</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.interp.html">interp</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.interpolate_nans.html">interpolate_nans</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.isentropic_interpolation.html">isentropic_interpolation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.kinematic_flux.html">kinematic_flux</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.laplacian.html">laplacian</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.lat_lon_grid_deltas.html">lat_lon_grid_deltas</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.lat_lon_grid_spacing.html">lat_lon_grid_spacing</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.lcl.html">lcl</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.lfc.html">lfc</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.log_interp.html">log_interp</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mean_pressure_weighted.html">mean_pressure_weighted</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixed_layer.html">mixed_layer</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixed_parcel.html">mixed_parcel</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixing_ratio.html">mixing_ratio</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixing_ratio_from_relative_humidity.html">mixing_ratio_from_relative_humidity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.mixing_ratio_from_specific_humidity.html">mixing_ratio_from_specific_humidity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.moist_lapse.html">moist_lapse</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.moist_static_energy.html">moist_static_energy</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.montgomery_streamfunction.html">montgomery_streamfunction</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.most_unstable_cape_cin.html">most_unstable_cape_cin</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.most_unstable_parcel.html">most_unstable_parcel</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.nearest_intersection_idx.html">nearest_intersection_idx</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.parcel_profile.html">parcel_profile</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.parse_angle.html">parse_angle</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.potential_temperature.html">potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.potential_vorticity_baroclinic.html">potential_vorticity_baroclinic</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.potential_vorticity_barotropic.html">potential_vorticity_barotropic</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.precipitable_water.html">precipitable_water</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.pressure_to_height_std.html">pressure_to_height_std</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.psychrometric_vapor_pressure_wet.html">psychrometric_vapor_pressure_wet</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.q_vector.html">q_vector</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.reduce_point_density.html">reduce_point_density</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_from_dewpoint.html">relative_humidity_from_dewpoint</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_from_mixing_ratio.html">relative_humidity_from_mixing_ratio</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_from_specific_humidity.html">relative_humidity_from_specific_humidity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.relative_humidity_wet_psychrometric.html">relative_humidity_wet_psychrometric</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.resample_nn_1d.html">resample_nn_1d</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.saturation_equivalent_potential_temperature.html">saturation_equivalent_potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.saturation_mixing_ratio.html">saturation_mixing_ratio</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.saturation_vapor_pressure.html">saturation_vapor_pressure</a></li>
<li class="toctree-l3 current"><a class="current reference internal" href="#">second_derivative</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.shearing_deformation.html">shearing_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.shearing_stretching_deformation.html">shearing_stretching_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.sigma_to_pressure.html">sigma_to_pressure</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.significant_tornado.html">significant_tornado</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.specific_humidity_from_mixing_ratio.html">specific_humidity_from_mixing_ratio</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.static_stability.html">static_stability</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.storm_relative_helicity.html">storm_relative_helicity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.stretching_deformation.html">stretching_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.supercell_composite.html">supercell_composite</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.surface_based_cape_cin.html">surface_based_cape_cin</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.temperature_from_potential_temperature.html">temperature_from_potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.thickness_hydrostatic.html">thickness_hydrostatic</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.thickness_hydrostatic_from_relative_humidity.html">thickness_hydrostatic_from_relative_humidity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.tke.html">tke</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.total_deformation.html">total_deformation</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.v_vorticity.html">v_vorticity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.vapor_pressure.html">vapor_pressure</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.virtual_potential_temperature.html">virtual_potential_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.virtual_temperature.html">virtual_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.vorticity.html">vorticity</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.wet_bulb_temperature.html">wet_bulb_temperature</a></li>
<li class="toctree-l3"><a class="reference internal" href="metpy.calc.windchill.html">windchill</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="metpy.plots.html">plots</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.plots.ctables.html">ctables</a></li>
<li class="toctree-l2"><a class="reference internal" href="metpy.gridding.html">gridding</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../gempak.html">GEMPAK Conversion Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../CONTRIBUTING.html">Contributors Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../infrastructureguide.html">Infrastructure Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../citing.html">Citing MetPy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../references.html">References</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="../../index.html">MetPy</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="../../index.html">Docs</a> »</li>
<li><a href="../index.html">The MetPy API</a> »</li>
<li><a href="metpy.calc.html">calc</a> »</li>
<li>second_derivative</li>
<li class="source-link">
<a href="https://github.com/Unidata/MetPy/issues/new?title=Suggested%20improvement%20for%20api/generated/metpy.calc.second_derivative&body=Please%20describe%20what%20could%20be%20improved%20about%20this%20page%20or%20the%20typo/mistake%20that%20you%20found%3A"
class="fa fa-github"> Improve this page</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="second-derivative">
<h1>second_derivative<a class="headerlink" href="#second-derivative" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="metpy.calc.second_derivative">
<code class="descclassname">metpy.calc.</code><code class="descname">second_derivative</code><span class="sig-paren">(</span><em>f</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="reference internal" href="../../_modules/metpy/calc/tools.html#second_derivative"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#metpy.calc.second_derivative" title="Permalink to this definition">¶</a></dt>
<dd><p>Calculate the second derivative of a grid of values.</p>
<p>Works for both regularly-spaced data and grids with varying spacing.</p>
<p>Either <em class="xref py py-obj">x</em> or <em class="xref py py-obj">delta</em> must be specified.</p>
<p>Either <em class="xref py py-obj">x</em> or <em class="xref py py-obj">delta</em> must be specified. This uses 3 points to calculate the
derivative, using forward or backward at the edges of the grid as appropriate, and
centered elsewhere. The irregular spacing is handled explicitly, using the formulation
as specified by <a class="reference internal" href="../../references.html#bowen2005" id="id1">[Bowen2005]</a>.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple">
<li><strong>f</strong> (<em>array-like</em>) – Array of values of which to calculate the derivative</li>
<li><strong>axis</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.6)"><em>int</em></a><em>, </em><em>optional</em>) – The array axis along which to take the derivative. Defaults to 0.</li>
<li><strong>x</strong> (<em>array-like</em><em>, </em><em>optional</em>) – The coordinate values corresponding to the grid points in <em class="xref py py-obj">f</em>.</li>
<li><strong>delta</strong> (<em>array-like</em><em>, </em><em>optional</em>) – Spacing between the grid points in <em class="xref py py-obj">f</em>. There should be one item less than the size
of <em class="xref py py-obj">f</em> along <em class="xref py py-obj">axis</em>.</li>
</ul>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first last"><em>array-like</em> – The second derivative calculated along the selected axis.</p>
</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="metpy.calc.first_derivative.html#metpy.calc.first_derivative" title="metpy.calc.first_derivative"><code class="xref py py-func docutils literal notranslate"><span class="pre">first_derivative()</span></code></a></p>
</div>
</dd></dl>
<div style='clear:both'></div></div>
</div>
<div class="articleComments">
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="metpy.calc.shearing_deformation.html" class="btn btn-neutral float-right" title="shearing_deformation" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
<a href="metpy.calc.saturation_vapor_pressure.html" class="btn btn-neutral" title="saturation_vapor_pressure" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<p>
© Copyright 2017, MetPy Developers.
Last updated on May 17, 2018 at 20:56:37.
</p>
</div>
Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-92978945-1', 'auto');
ga('send', 'pageview');
</script>
<script>var version_json_loc = "../../../versions.json";</script>
<p>Do you enjoy using MetPy?
<a href="https://saythanks.io/to/unidata" class="btn btn-neutral" title="Say Thanks!" accesskey="n">Say Thanks!</a>
</p>
</footer>
</div>
</div>
</section>
</div>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT:'../../',
VERSION:'0.8.0',
LANGUAGE:'None',
COLLAPSE_INDEX:false,
FILE_SUFFIX:'.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/underscore.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="../../_static/pop_ver.js"></script>
<script type="text/javascript" src="../../_static/js/theme.js"></script>
<script type="text/javascript">
jQuery(function () {
SphinxRtdTheme.StickyNav.enable();
});
</script>
</body>
</html> | metpy/MetPy | v0.8/api/generated/metpy.calc.second_derivative.html | HTML | bsd-3-clause | 25,592 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ABI41_0_0AndroidDialogPickerProps.h"
#include <ABI41_0_0React/components/image/conversions.h>
#include <ABI41_0_0React/core/propsConversions.h>
namespace ABI41_0_0facebook {
namespace ABI41_0_0React {
AndroidDialogPickerProps::AndroidDialogPickerProps(
const AndroidDialogPickerProps &sourceProps,
const RawProps &rawProps)
: ViewProps(sourceProps, rawProps),
color(convertRawProp(rawProps, "color", sourceProps.color, {})),
enabled(convertRawProp(rawProps, "enabled", sourceProps.enabled, {true})),
items(convertRawProp(rawProps, "items", sourceProps.items, {})),
prompt(convertRawProp(rawProps, "prompt", sourceProps.prompt, {""})),
selected(
convertRawProp(rawProps, "selected", sourceProps.selected, {0})) {}
} // namespace ABI41_0_0React
} // namespace ABI41_0_0facebook
| exponent/exponent | ios/versioned-react-native/ABI41_0_0/ReactNative/ReactCommon/fabric/components/picker/androidpicker/ABI41_0_0AndroidDialogPickerProps.cpp | C++ | bsd-3-clause | 1,031 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/drive/drive_api_util.h"
#include <string>
#include "base/files/file.h"
#include "base/logging.h"
#include "base/md5.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/drive/drive_api_parser.h"
#include "google_apis/drive/gdata_wapi_parser.h"
#include "net/base/escape.h"
#include "third_party/re2/re2/re2.h"
#include "url/gurl.h"
namespace drive {
namespace util {
namespace {
// Google Apps MIME types:
const char kGoogleDocumentMimeType[] = "application/vnd.google-apps.document";
const char kGoogleDrawingMimeType[] = "application/vnd.google-apps.drawing";
const char kGooglePresentationMimeType[] =
"application/vnd.google-apps.presentation";
const char kGoogleSpreadsheetMimeType[] =
"application/vnd.google-apps.spreadsheet";
const char kGoogleTableMimeType[] = "application/vnd.google-apps.table";
const char kGoogleFormMimeType[] = "application/vnd.google-apps.form";
const char kDriveFolderMimeType[] = "application/vnd.google-apps.folder";
std::string GetMimeTypeFromEntryKind(google_apis::DriveEntryKind kind) {
switch (kind) {
case google_apis::ENTRY_KIND_DOCUMENT:
return kGoogleDocumentMimeType;
case google_apis::ENTRY_KIND_SPREADSHEET:
return kGoogleSpreadsheetMimeType;
case google_apis::ENTRY_KIND_PRESENTATION:
return kGooglePresentationMimeType;
case google_apis::ENTRY_KIND_DRAWING:
return kGoogleDrawingMimeType;
case google_apis::ENTRY_KIND_TABLE:
return kGoogleTableMimeType;
case google_apis::ENTRY_KIND_FORM:
return kGoogleFormMimeType;
default:
return std::string();
}
}
ScopedVector<std::string> CopyScopedVectorString(
const ScopedVector<std::string>& source) {
ScopedVector<std::string> result;
result.reserve(source.size());
for (size_t i = 0; i < source.size(); ++i)
result.push_back(new std::string(*source[i]));
return result.Pass();
}
// Converts AppIcon (of GData WAPI) to DriveAppIcon.
scoped_ptr<google_apis::DriveAppIcon>
ConvertAppIconToDriveAppIcon(const google_apis::AppIcon& app_icon) {
scoped_ptr<google_apis::DriveAppIcon> resource(
new google_apis::DriveAppIcon);
switch (app_icon.category()) {
case google_apis::AppIcon::ICON_UNKNOWN:
resource->set_category(google_apis::DriveAppIcon::UNKNOWN);
break;
case google_apis::AppIcon::ICON_DOCUMENT:
resource->set_category(google_apis::DriveAppIcon::DOCUMENT);
break;
case google_apis::AppIcon::ICON_APPLICATION:
resource->set_category(google_apis::DriveAppIcon::APPLICATION);
break;
case google_apis::AppIcon::ICON_SHARED_DOCUMENT:
resource->set_category(google_apis::DriveAppIcon::SHARED_DOCUMENT);
break;
default:
NOTREACHED();
}
resource->set_icon_side_length(app_icon.icon_side_length());
resource->set_icon_url(app_icon.GetIconURL());
return resource.Pass();
}
// Converts InstalledApp to AppResource.
scoped_ptr<google_apis::AppResource>
ConvertInstalledAppToAppResource(
const google_apis::InstalledApp& installed_app) {
scoped_ptr<google_apis::AppResource> resource(new google_apis::AppResource);
resource->set_application_id(installed_app.app_id());
resource->set_name(installed_app.app_name());
resource->set_object_type(installed_app.object_type());
resource->set_supports_create(installed_app.supports_create());
{
ScopedVector<std::string> primary_mimetypes(
CopyScopedVectorString(installed_app.primary_mimetypes()));
resource->set_primary_mimetypes(primary_mimetypes.Pass());
}
{
ScopedVector<std::string> secondary_mimetypes(
CopyScopedVectorString(installed_app.secondary_mimetypes()));
resource->set_secondary_mimetypes(secondary_mimetypes.Pass());
}
{
ScopedVector<std::string> primary_file_extensions(
CopyScopedVectorString(installed_app.primary_extensions()));
resource->set_primary_file_extensions(primary_file_extensions.Pass());
}
{
ScopedVector<std::string> secondary_file_extensions(
CopyScopedVectorString(installed_app.secondary_extensions()));
resource->set_secondary_file_extensions(secondary_file_extensions.Pass());
}
{
const ScopedVector<google_apis::AppIcon>& app_icons =
installed_app.app_icons();
ScopedVector<google_apis::DriveAppIcon> icons;
icons.reserve(app_icons.size());
for (size_t i = 0; i < app_icons.size(); ++i) {
icons.push_back(ConvertAppIconToDriveAppIcon(*app_icons[i]).release());
}
resource->set_icons(icons.Pass());
}
// supports_import, installed and authorized are not supported in
// InstalledApp.
return resource.Pass();
}
// Returns the argument string.
std::string Identity(const std::string& resource_id) { return resource_id; }
} // namespace
std::string EscapeQueryStringValue(const std::string& str) {
std::string result;
result.reserve(str.size());
for (size_t i = 0; i < str.size(); ++i) {
if (str[i] == '\\' || str[i] == '\'') {
result.push_back('\\');
}
result.push_back(str[i]);
}
return result;
}
std::string TranslateQuery(const std::string& original_query) {
// In order to handle non-ascii white spaces correctly, convert to UTF16.
base::string16 query = base::UTF8ToUTF16(original_query);
const base::string16 kDelimiter(
base::kWhitespaceUTF16 +
base::string16(1, static_cast<base::char16>('"')));
std::string result;
for (size_t index = query.find_first_not_of(base::kWhitespaceUTF16);
index != base::string16::npos;
index = query.find_first_not_of(base::kWhitespaceUTF16, index)) {
bool is_exclusion = (query[index] == '-');
if (is_exclusion)
++index;
if (index == query.length()) {
// Here, the token is '-' and it should be ignored.
continue;
}
size_t begin_token = index;
base::string16 token;
if (query[begin_token] == '"') {
// Quoted query.
++begin_token;
size_t end_token = query.find('"', begin_token);
if (end_token == base::string16::npos) {
// This is kind of syntax error, since quoted string isn't finished.
// However, the query is built by user manually, so here we treat
// whole remaining string as a token as a fallback, by appending
// a missing double-quote character.
end_token = query.length();
query.push_back('"');
}
token = query.substr(begin_token, end_token - begin_token);
index = end_token + 1; // Consume last '"', too.
} else {
size_t end_token = query.find_first_of(kDelimiter, begin_token);
if (end_token == base::string16::npos) {
end_token = query.length();
}
token = query.substr(begin_token, end_token - begin_token);
index = end_token;
}
if (token.empty()) {
// Just ignore an empty token.
continue;
}
if (!result.empty()) {
// If there are two or more tokens, need to connect with "and".
result.append(" and ");
}
// The meaning of "fullText" should include title, description and content.
base::StringAppendF(
&result,
"%sfullText contains \'%s\'",
is_exclusion ? "not " : "",
EscapeQueryStringValue(base::UTF16ToUTF8(token)).c_str());
}
return result;
}
std::string ExtractResourceIdFromUrl(const GURL& url) {
return net::UnescapeURLComponent(url.ExtractFileName(),
net::UnescapeRule::URL_SPECIAL_CHARS);
}
std::string CanonicalizeResourceId(const std::string& resource_id) {
// If resource ID is in the old WAPI format starting with a prefix like
// "document:", strip it and return the remaining part.
std::string stripped_resource_id;
if (RE2::FullMatch(resource_id, "^[a-z-]+(?::|%3A)([\\w-]+)$",
&stripped_resource_id))
return stripped_resource_id;
return resource_id;
}
ResourceIdCanonicalizer GetIdentityResourceIdCanonicalizer() {
return base::Bind(&Identity);
}
const char kDocsListScope[] = "https://docs.google.com/feeds/";
const char kDriveAppsScope[] = "https://www.googleapis.com/auth/drive.apps";
void ParseShareUrlAndRun(const google_apis::GetShareUrlCallback& callback,
google_apis::GDataErrorCode error,
scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!value) {
callback.Run(error, GURL());
return;
}
// Parsing ResourceEntry is cheap enough to do on UI thread.
scoped_ptr<google_apis::ResourceEntry> entry =
google_apis::ResourceEntry::ExtractAndParse(*value);
if (!entry) {
callback.Run(google_apis::GDATA_PARSE_ERROR, GURL());
return;
}
const google_apis::Link* share_link =
entry->GetLinkByType(google_apis::Link::LINK_SHARE);
callback.Run(error, share_link ? share_link->href() : GURL());
}
scoped_ptr<google_apis::AboutResource>
ConvertAccountMetadataToAboutResource(
const google_apis::AccountMetadata& account_metadata,
const std::string& root_resource_id) {
scoped_ptr<google_apis::AboutResource> resource(
new google_apis::AboutResource);
resource->set_largest_change_id(account_metadata.largest_changestamp());
resource->set_quota_bytes_total(account_metadata.quota_bytes_total());
resource->set_quota_bytes_used(account_metadata.quota_bytes_used());
resource->set_root_folder_id(root_resource_id);
return resource.Pass();
}
scoped_ptr<google_apis::AppList>
ConvertAccountMetadataToAppList(
const google_apis::AccountMetadata& account_metadata) {
scoped_ptr<google_apis::AppList> resource(new google_apis::AppList);
const ScopedVector<google_apis::InstalledApp>& installed_apps =
account_metadata.installed_apps();
ScopedVector<google_apis::AppResource> app_resources;
app_resources.reserve(installed_apps.size());
for (size_t i = 0; i < installed_apps.size(); ++i) {
app_resources.push_back(
ConvertInstalledAppToAppResource(*installed_apps[i]).release());
}
resource->set_items(app_resources.Pass());
// etag is not supported in AccountMetadata.
return resource.Pass();
}
scoped_ptr<google_apis::FileResource> ConvertResourceEntryToFileResource(
const google_apis::ResourceEntry& entry) {
scoped_ptr<google_apis::FileResource> file(new google_apis::FileResource);
file->set_file_id(entry.resource_id());
file->set_title(entry.title());
file->set_created_date(entry.published_time());
if (std::find(entry.labels().begin(), entry.labels().end(),
"shared-with-me") != entry.labels().end()) {
// Set current time to mark the file is shared_with_me, since ResourceEntry
// doesn't have |shared_with_me_date| equivalent.
file->set_shared_with_me_date(base::Time::Now());
}
file->set_shared(std::find(entry.labels().begin(), entry.labels().end(),
"shared") != entry.labels().end());
if (entry.is_folder()) {
file->set_mime_type(kDriveFolderMimeType);
} else {
std::string mime_type = GetMimeTypeFromEntryKind(entry.kind());
if (mime_type.empty())
mime_type = entry.content_mime_type();
file->set_mime_type(mime_type);
}
file->set_md5_checksum(entry.file_md5());
file->set_file_size(entry.file_size());
file->mutable_labels()->set_trashed(entry.deleted());
file->set_etag(entry.etag());
google_apis::ImageMediaMetadata* image_media_metadata =
file->mutable_image_media_metadata();
image_media_metadata->set_width(entry.image_width());
image_media_metadata->set_height(entry.image_height());
image_media_metadata->set_rotation(entry.image_rotation());
std::vector<google_apis::ParentReference>* parents = file->mutable_parents();
for (size_t i = 0; i < entry.links().size(); ++i) {
using google_apis::Link;
const Link& link = *entry.links()[i];
switch (link.type()) {
case Link::LINK_PARENT: {
google_apis::ParentReference parent;
parent.set_parent_link(link.href());
std::string file_id =
drive::util::ExtractResourceIdFromUrl(link.href());
parent.set_file_id(file_id);
parent.set_is_root(file_id == kWapiRootDirectoryResourceId);
parents->push_back(parent);
break;
}
case Link::LINK_ALTERNATE:
file->set_alternate_link(link.href());
break;
default:
break;
}
}
file->set_modified_date(entry.updated_time());
file->set_last_viewed_by_me_date(entry.last_viewed_time());
return file.Pass();
}
google_apis::DriveEntryKind GetKind(
const google_apis::FileResource& file_resource) {
if (file_resource.IsDirectory())
return google_apis::ENTRY_KIND_FOLDER;
const std::string& mime_type = file_resource.mime_type();
if (mime_type == kGoogleDocumentMimeType)
return google_apis::ENTRY_KIND_DOCUMENT;
if (mime_type == kGoogleSpreadsheetMimeType)
return google_apis::ENTRY_KIND_SPREADSHEET;
if (mime_type == kGooglePresentationMimeType)
return google_apis::ENTRY_KIND_PRESENTATION;
if (mime_type == kGoogleDrawingMimeType)
return google_apis::ENTRY_KIND_DRAWING;
if (mime_type == kGoogleTableMimeType)
return google_apis::ENTRY_KIND_TABLE;
if (mime_type == kGoogleFormMimeType)
return google_apis::ENTRY_KIND_FORM;
if (mime_type == "application/pdf")
return google_apis::ENTRY_KIND_PDF;
return google_apis::ENTRY_KIND_FILE;
}
scoped_ptr<google_apis::ResourceEntry>
ConvertFileResourceToResourceEntry(
const google_apis::FileResource& file_resource) {
scoped_ptr<google_apis::ResourceEntry> entry(new google_apis::ResourceEntry);
// ResourceEntry
entry->set_resource_id(file_resource.file_id());
entry->set_id(file_resource.file_id());
entry->set_kind(GetKind(file_resource));
entry->set_title(file_resource.title());
entry->set_published_time(file_resource.created_date());
std::vector<std::string> labels;
if (!file_resource.shared_with_me_date().is_null())
labels.push_back("shared-with-me");
if (file_resource.shared())
labels.push_back("shared");
entry->set_labels(labels);
// This should be the url to download the file_resource.
{
google_apis::Content content;
content.set_mime_type(file_resource.mime_type());
entry->set_content(content);
}
// TODO(kochi): entry->resource_links_
// For file entries
entry->set_filename(file_resource.title());
entry->set_suggested_filename(file_resource.title());
entry->set_file_md5(file_resource.md5_checksum());
entry->set_file_size(file_resource.file_size());
// If file is removed completely, that information is only available in
// ChangeResource, and is reflected in |removed_|. If file is trashed, the
// file entry still exists but with its "trashed" label true.
entry->set_deleted(file_resource.labels().is_trashed());
// ImageMediaMetadata
entry->set_image_width(file_resource.image_media_metadata().width());
entry->set_image_height(file_resource.image_media_metadata().height());
entry->set_image_rotation(file_resource.image_media_metadata().rotation());
// CommonMetadata
entry->set_etag(file_resource.etag());
// entry->authors_
// entry->links_.
ScopedVector<google_apis::Link> links;
for (size_t i = 0; i < file_resource.parents().size(); ++i) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_PARENT);
link->set_href(file_resource.parents()[i].parent_link());
links.push_back(link);
}
if (!file_resource.alternate_link().is_empty()) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_ALTERNATE);
link->set_href(file_resource.alternate_link());
links.push_back(link);
}
entry->set_links(links.Pass());
// entry->categories_
entry->set_updated_time(file_resource.modified_date());
entry->set_last_viewed_time(file_resource.last_viewed_by_me_date());
entry->FillRemainingFields();
return entry.Pass();
}
scoped_ptr<google_apis::ResourceEntry>
ConvertChangeResourceToResourceEntry(
const google_apis::ChangeResource& change_resource) {
scoped_ptr<google_apis::ResourceEntry> entry;
if (change_resource.file())
entry = ConvertFileResourceToResourceEntry(*change_resource.file()).Pass();
else
entry.reset(new google_apis::ResourceEntry);
entry->set_resource_id(change_resource.file_id());
// If |is_deleted()| returns true, the file is removed from Drive.
entry->set_removed(change_resource.is_deleted());
entry->set_changestamp(change_resource.change_id());
entry->set_modification_date(change_resource.modification_date());
return entry.Pass();
}
scoped_ptr<google_apis::ResourceList>
ConvertFileListToResourceList(const google_apis::FileList& file_list) {
scoped_ptr<google_apis::ResourceList> feed(new google_apis::ResourceList);
const ScopedVector<google_apis::FileResource>& items = file_list.items();
ScopedVector<google_apis::ResourceEntry> entries;
for (size_t i = 0; i < items.size(); ++i)
entries.push_back(ConvertFileResourceToResourceEntry(*items[i]).release());
feed->set_entries(entries.Pass());
ScopedVector<google_apis::Link> links;
if (!file_list.next_link().is_empty()) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_NEXT);
link->set_href(file_list.next_link());
links.push_back(link);
}
feed->set_links(links.Pass());
return feed.Pass();
}
scoped_ptr<google_apis::ResourceList>
ConvertChangeListToResourceList(const google_apis::ChangeList& change_list) {
scoped_ptr<google_apis::ResourceList> feed(new google_apis::ResourceList);
const ScopedVector<google_apis::ChangeResource>& items = change_list.items();
ScopedVector<google_apis::ResourceEntry> entries;
for (size_t i = 0; i < items.size(); ++i) {
entries.push_back(
ConvertChangeResourceToResourceEntry(*items[i]).release());
}
feed->set_entries(entries.Pass());
feed->set_largest_changestamp(change_list.largest_change_id());
ScopedVector<google_apis::Link> links;
if (!change_list.next_link().is_empty()) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_NEXT);
link->set_href(change_list.next_link());
links.push_back(link);
}
feed->set_links(links.Pass());
return feed.Pass();
}
std::string GetMd5Digest(const base::FilePath& file_path) {
const int kBufferSize = 512 * 1024; // 512kB.
base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!file.IsValid())
return std::string();
base::MD5Context context;
base::MD5Init(&context);
int64 offset = 0;
scoped_ptr<char[]> buffer(new char[kBufferSize]);
while (true) {
int result = file.Read(offset, buffer.get(), kBufferSize);
if (result < 0) {
// Found an error.
return std::string();
}
if (result == 0) {
// End of file.
break;
}
offset += result;
base::MD5Update(&context, base::StringPiece(buffer.get(), result));
}
base::MD5Digest digest;
base::MD5Final(&digest, &context);
return MD5DigestToBase16(digest);
}
const char kWapiRootDirectoryResourceId[] = "folder:root";
} // namespace util
} // namespace drive
| patrickm/chromium.src | chrome/browser/drive/drive_api_util.cc | C++ | bsd-3-clause | 19,627 |
class Vehicletype < ActiveRecord::Base
has_many :vehicles
attr_accessible :capacity, :fuel, :maintcycle, :name
validates :name, :uniqueness => true
end
| alliciga/MWM | app/models/vehicletype.rb | Ruby | bsd-3-clause | 158 |
The jStar Eclipse Plug-in
=============================
There is a tutorial for the plugin:
doc/jstar eclipse tutorial/jstar eclipse tutorial.pdf
For more information, see [http://www.jstarverifier.org](https://web.archive.org/web/20141217130023/http://jstarverifier.org/)
___
This repository contains information related to the tool jStar-Eclipse presented in Foundations of Software Engineering, 2011. The tool was originally presented in this [paper](http://www.cl.cam.ac.uk/~mb741/papers/fse11.pdf).
This repository <b><i>IS NOT</i></b> the original repository for this tool. Here are some links to the original project:
* [A Video of the Tool](https://www.youtube.com/watch?v=2QRbdlppgrk)
* [jStar-Eclipse plugin](https://github.com/seplogic/jstar-eclipse/tree/master/com.jstar.eclipse.update.site)
* [jStar repository](https://github.com/seplogic/jstar)
* [Corestar repository](https://github.com/seplogic/corestar)
In this repository, for jStar-Eclipse you will find:
* :white_check_mark: Source code (available [here](https://github.com/SoftwareEngineeringToolDemos/FSE-2011-jstar-eclipse/tree/master/com.jstar.eclipse/src/com/jstar/eclipse)
* :white_check_mark: The original tool (available [here](https://github.com/SoftwareEngineeringToolDemos/FSE-2011-jstar-eclipse/tree/master/com.jstar.eclipse.update.site))<br>
* :white_check_mark: Binaries (available [here](https://github.com/SoftwareEngineeringToolDemos/FSE-2011-jstar-eclipse/tree/master/bin))
* :white_check_mark: [Virtual machine containing tool](http://go.ncsu.edu/SE-tool-VMs)
This repository was constructed by [Sumeet Agarwal](https://github.com/sumeet29) under the supervision of [Dr. Emerson Murphy-Hill](https://github.com/CaptainEmerson).<br>
Thanks to Daiva Naudziuniene, Matko Botincan, Dino Distefano, Mike Dodds, Radu Grigore and Matthew Parkinson for their help in establishing this repository.
| SoftwareEngineeringToolDemos/FSE-2011-jstar-eclipse | README.md | Markdown | bsd-3-clause | 1,915 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<title>DIRECTION-TOWARDS-OTHERS</title>
</head>
<body>
<h3><i>I update my desired direction to head toward those in my local
interaction zone if not in my personal space.</i> </h3>
<font size="2" color="gray">Begin micro-behaviour</font>
<p><b>DIRECTION-TOWARDS-OTHERS</b></p>
<font size="2" color="gray">Begin NetLogo code:</font>
<pre>substitute-text-area-for cycle-duration 1
do-every cycle-duration
[ask all-individuals with [distance-between the-personal-space the-local-interaction]
[set my-next-desired-direction
add my-next-desired-direction
unit-vector subtract location myself my-location]]
</pre>
<font size="2" color="gray">End NetLogo code</font>
<h2>Variants</h2>
<p>The variable <i>the-personal-space</i> in the above is the value of α in [1].
It can be defined and changed by a slider defined in
<a title="CREATE-SLIDER-FOR-PERSONAL-SPACE" href="CREATE-SLIDER-FOR-PERSONAL-SPACE.html">
CREATE-SLIDER-FOR-PERSONAL-SPACE</a>. The variable <i>the-local-interaction</i>
is the zone of local interaction or the value of ρ in [1]. It is defined by
the slider in
<a title="CREATE-SLIDER-FOR-LOCAL-INTERACTION" href="CREATE-SLIDER-FOR-LOCAL-INTERACTION.html">
CREATE-SLIDER-FOR-LOCAL-INTERACTION</a>.</p>
<p>If you add <i>and abs angle-from-me <= cone-of-vision</i> to <i>
distance-between the-personal-space the-local-interaction</i> then only those who
are within my cone of vision will be considered. <i>cone-of-vision</i> can
be defined by a slider as a variable that ranges from 0 to 180 degrees.</p>
<p>You can change the frequency that this runs by changing the <i>1</i>.</p>
<h2>Related Micro-behaviours</h2>
<p>
<a title="DIRECTION-TO-AVOID-OTHERS" href="DIRECTION-TO-AVOID-OTHERS.html">
DIRECTION-TO-AVOID-OTHERS</a> sets my desired direction away from those too
close to me.
<a title="DIRECTION-TO-ALIGN-WITH-OTHERS" href="DIRECTION-TO-ALIGN-WITH-OTHERS.html">
DIRECTION-TO-ALIGN-WITH-OTHERS</a> aligns with those within my local
interaction range and
<a title="INFORMED-DIRECTION" href="INFORMED-DIRECTION.html">
INFORMED-DIRECTION</a> implements a preferred direction.</p>
<p>Note that the desired-direction is used by
<a title="TURN-IN-DIRECTION-AT-MAXIMUM-SPEED" href="TURN-IN-DIRECTION-AT-MAXIMUM-SPEED.html">
TURN-IN-DIRECTION-AT-MAXIMUM-SPEED</a> to turn me.</p>
<p>
<a title="DIRECTION-TOWARDS-OTHERS-DELAYED" href="DIRECTION-TOWARDS-OTHERS-DELAYED.html">
DIRECTION-TOWARDS-OTHERS-DELAYED</a> runs this with a delay.</p>
<h2>How this works</h2>
<p>This adds a vector to me from each of the others whose distance is
between the <i>the-personal-space</i> and <i>the-local-interaction</i>. It
implements part of equation 2 in [1].</p>
<p>
<img alt="Image:couzin_formula2.png" src="images/Couzin_formula2.png" border="0" width="431" height="56">
</p>
<h2>History</h2>
<p>This was implemented by Ken Kahn.</p>
<h2>References</h2>
<p>[1] Couzin, I.D., Krause, J., Franks, N.R. & Levin, S.A.(2005)
<a class="external text" title="http://www.princeton.edu/~icouzin/Couzinetal2005.pdf" rel="nofollow" href="http://www.princeton.edu/~icouzin/Couzinetal2005.pdf">
Effective leadership and decision making in animal groups on the move</a>
Nature 433, 513-516.</p>
</body>
</html>
| ToonTalk/behaviour-composer | BC/Static Web Pages/Resources/Composer/en/MB.3/DIRECTION-TOWARDS-OTHERS.html | HTML | bsd-3-clause | 3,523 |
'use strict';
describe('Directive: searchFilters', function () {
// load the directive's module
beforeEach(module('searchApp'));
var element,
scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<search-filters></search-filters>');
element = $compile(element)(scope);
expect(element.text()).toBe('this is the searchFilters directive');
}));
});
| MLR-au/esrc-search | test/spec/directives/search-filters.js | JavaScript | bsd-3-clause | 509 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Fahrtenbuch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="fahrtenbuch-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'fahrer')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'fahrzeug')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'start')->textInput() ?>
<?= $form->field($model, 'ende')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| smoos/fb_dispo | views/fahrtenbuch/_form.php | PHP | bsd-3-clause | 745 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <UIKit/UIKit.h>
#import <ABI42_0_0React/ABI42_0_0RCTView.h>
@interface ABI42_0_0RCTMaskedView : ABI42_0_0RCTView
@end
| exponentjs/exponent | ios/versioned-react-native/ABI42_0_0/ReactNative/React/Views/ABI42_0_0RCTMaskedView.h | C | bsd-3-clause | 318 |
# This code is free software; you can redistribute it and/or modify it under
# the terms of the new BSD License.
#
# Copyright (c) 2011, Sebastian Staudt
require 'fixtures'
require 'helper'
class TestGitHub < Test::Unit::TestCase
context 'The GitHub implementation' do
should 'not support file stats' do
assert_not Metior::GitHub.supports? :file_stats
end
should 'not support line stats' do
assert_not Metior::GitHub.supports? :line_stats
end
end
context 'A GitHub repository' do
setup do
@repo = Metior::GitHub::Repository.new 'mojombo', 'grit'
api_response = Fixtures.commits_as_rashies(''..'master')
@commits_stub = Octokit.stubs :commits
14.times { @commits_stub.returns api_response.shift(35) }
@commits_stub.then.raises Octokit::NotFound.new(nil)
end
should 'be able to load all commits from the repository\'s default branch' do
commits = @repo.commits
assert_equal 460, commits.size
assert commits.all? { |commit| commit.is_a? Metior::GitHub::Commit }
head = commits.first
assert_equal '1b2fe77', head.id
end
should 'be able to load a range of commits from the repository' do
@commits_stub = Octokit.stubs :commits
api_response = Fixtures.commits_as_rashies(''..'4c592b4')
14.times { @commits_stub.returns api_response.shift(35) }
@commits_stub.raises Octokit::NotFound.new(nil)
api_response = Fixtures.commits_as_rashies(''..'ef2870b')
13.times { @commits_stub.returns api_response.shift(35) }
@commits_stub.then.raises Octokit::NotFound.new(nil)
commits = @repo.commits 'ef2870b'..'4c592b4'
assert_equal 6, commits.size
assert commits.all? { |commit| commit.is_a? Metior::GitHub::Commit }
assert_equal '4c592b4', commits.first.id
assert_equal 'f0cc7f7', commits.last.id
end
should 'know the authors of the repository' do
authors = @repo.authors
assert_equal 37, authors.size
assert authors.values.all? { |author| author.is_a? Metior::GitHub::Actor }
assert_equal %w{
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] tom@taco.(none) [email protected] [email protected]
}, authors.keys.sort
end
should 'know the committers of the repository' do
committers = @repo.committers
assert_equal 29, committers.size
assert committers.values.all? { |committer| committer.is_a? Metior::GitHub::Actor }
assert_equal %w{
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected]
[email protected] [email protected] [email protected] tom@taco.(none)
[email protected]
}, committers.keys.sort
end
should 'know the top authors of the repository' do
authors = @repo.top_authors
assert_equal 3, authors.size
assert authors.all? { |author| author.is_a? Metior::GitHub::Actor }
assert_equal [
"[email protected]", "[email protected]", "[email protected]"
], authors.collect { |author| author.id }
end
should 'not be able to get file stats of a repository' do
assert_raises UnsupportedError do
@repo.file_stats
end
end
should 'not be able to get the most significant authors of a repository' do
assert_raises UnsupportedError do
@repo.significant_authors
end
end
should 'not be able to get the most significant commits of a repository' do
assert_raises UnsupportedError do
@repo.significant_commits
end
end
should 'provide easy access to simple repository statistics' do
stats = Metior.simple_stats :github, 'mojombo', 'grit'
assert_equal 157, stats[:active_days].size
assert_equal 460, stats[:commit_count]
assert_in_delta 2.92993630573248, stats[:commits_per_active_day], 0.0001
assert_equal Time.at(1191997100), stats[:first_commit_date]
assert_equal Time.at(1306794294), stats[:last_commit_date]
assert_equal 5, stats[:top_contributors].size
end
end
end
| travis-repos/metior | test/test_github.rb | Ruby | bsd-3-clause | 5,231 |
---
id: 5900f4331000cf542c50ff45
challengeType: 5
title: 'Problem 198: Ambiguous Numbers'
forumTopicId: 301836
---
## Description
<section id='description'>
A best approximation to a real number x for the denominator bound d is a rational number r/s (in reduced form) with s ≤ d, so that any rational number p/q which is closer to x than r/s has q > d.
Usually the best approximation to a real number is uniquely determined for all denominator bounds. However, there are some exceptions, e.g. 9/40 has the two best approximations 1/4 and 1/5 for the denominator bound 6.
We shall call a real number x ambiguous, if there is at least one denominator bound for which x possesses two best approximations. Clearly, an ambiguous number is necessarily rational.
How many ambiguous numbers x = p/q,
0 < x < 1/100, are there whose denominator q does not exceed 108?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler198()</code> should return 52374425.
testString: assert.strictEqual(euler198(), 52374425);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler198() {
// Good luck!
return true;
}
euler198();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>
| BhaveshSGupta/FreeCodeCamp | curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-198-ambiguous-numbers.english.md | Markdown | bsd-3-clause | 1,360 |
/*
* HE_Mesh Frederik Vanhoutte - www.wblut.com
*
* https://github.com/wblut/HE_Mesh
* A Processing/Java library for for creating and manipulating polygonal meshes.
*
* Public Domain: http://creativecommons.org/publicdomain/zero/1.0/
* I , Frederik Vanhoutte, have waived all copyright and related or neighboring
* rights.
*
* This work is published from Belgium. (http://creativecommons.org/publicdomain/zero/1.0/)
*
*/
package wblut.geom;
/**
* Interface for implementing mutable mathematical operations on 3D coordinates.
*
* All of the operators defined in the interface change the calling object. All
* operators use the label "Self", such as "addSelf" to indicate this.
*
* @author Frederik Vanhoutte
*
*/
public interface WB_MutableCoordinateMath3D extends WB_CoordinateMath3D {
/**
* Add coordinate values.
*
* @param x
* @return this
*/
public WB_Coord addSelf(final double... x);
/**
* Add coordinate values.
*
* @param p
* @return this
*/
public WB_Coord addSelf(final WB_Coord p);
/**
* Subtract coordinate values.
*
* @param x
* @return this
*/
public WB_Coord subSelf(final double... x);
/**
* Subtract coordinate values.
*
* @param p
* @return this
*/
public WB_Coord subSelf(final WB_Coord p);
/**
* Multiply by factor.
*
* @param f
* @return this
*/
public WB_Coord mulSelf(final double f);
/**
* Divide by factor.
*
* @param f
* @return this
*/
public WB_Coord divSelf(final double f);
/**
* Add multiple of coordinate values.
*
* @param f
* multiplier
* @param x
* @return this
*/
public WB_Coord addMulSelf(final double f, final double... x);
/**
* Add multiple of coordinate values.
*
* @param f
* @param p
* @return this
*/
public WB_Coord addMulSelf(final double f, final WB_Coord p);
/**
* Multiply this coordinate by factor f and add other coordinate values
* multiplied by g.
*
* @param f
* @param g
* @param x
* @return this
*/
public WB_Coord mulAddMulSelf(final double f, final double g, final double... x);
/**
* Multiply this coordinate by factor f and add other coordinate values
* multiplied by g.
*
* @param f
* @param g
* @param p
* @return this
*/
public WB_Coord mulAddMulSelf(final double f, final double g, final WB_Coord p);
/**
*
*
* @param p
* @return this
*/
public WB_Coord crossSelf(final WB_Coord p);
/**
* Normalize this vector. Return the length before normalization. If this
* vector is degenerate 0 is returned and the vector remains the zero
* vector.
*
* @return this
*/
public double normalizeSelf();
/**
* If vector is larger than given value, trim vector.
*
* @param d
* @return this
*/
public WB_Coord trimSelf(final double d);
}
| DweebsUnited/CodeMonkey | java/CodeMonkey/HEMesh/wblut/geom/WB_MutableCoordinateMath3D.java | Java | bsd-3-clause | 2,810 |
The *Control Freak* IDE provides already a sophisticated Editor which comes with auto completion and snippets by the default.
Since most developers prefer their own editors and key bindings, the IDE allows also to write driver code outside of the
IDE. All you you need to do is open the driver Javascript file and start coding. The IDE server will recognize file
those changes and updates the running driver instance with your changes.
Be aware that you will loose the auto-completion of the IDE which shows common methods by default.
### Recommended Editors
- Best fit: WebStorm or PHPStorm with the "More Dojo" plugin enabled.
- Sublime
| xblox/control-freak | documentation/docFiles/08_Driver/04_Editors.md | Markdown | bsd-3-clause | 644 |
# -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use sendgrid to send emails
- Use MEMCACHIER on Heroku
'''
from configurations import values
# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings
try:
from S3 import CallingFormat
AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN
except ImportError:
# TODO: Fix this where even if in Dev this class is called.
pass
from .common import Common
class Production(Common):
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# SECRET KEY
SECRET_KEY = values.SecretValue()
# END SECRET KEY
# django-secure
INSTALLED_APPS += ("djangosecure", )
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = values.BooleanValue(True)
SECURE_FRAME_DENY = values.BooleanValue(True)
SECURE_CONTENT_TYPE_NOSNIFF = values.BooleanValue(True)
SECURE_BROWSER_XSS_FILTER = values.BooleanValue(True)
SESSION_COOKIE_SECURE = values.BooleanValue(False)
SESSION_COOKIE_HTTPONLY = values.BooleanValue(True)
SECURE_SSL_REDIRECT = values.BooleanValue(True)
# end django-secure
# SITE CONFIGURATION
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]
# END SITE CONFIGURATION
INSTALLED_APPS += ("gunicorn", )
# STORAGE CONFIGURATION
# See: http://django-storages.readthedocs.org/en/latest/index.html
INSTALLED_APPS += (
'storages',
)
# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings
STATICFILES_STORAGE = DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings
AWS_ACCESS_KEY_ID = values.SecretValue()
AWS_SECRET_ACCESS_KEY = values.SecretValue()
AWS_STORAGE_BUCKET_NAME = values.SecretValue()
AWS_AUTO_CREATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False
# see: https://github.com/antonagestam/collectfast
AWS_PRELOAD_METADATA = True
INSTALLED_APPS += ('collectfast', )
# AWS cache settings, don't change unless you know what you're doing:
AWS_EXPIRY = 60 * 60 * 24 * 7
AWS_HEADERS = {
'Cache-Control': 'max-age=%d, s-maxage=%d, must-revalidate' % (
AWS_EXPIRY, AWS_EXPIRY)
}
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
# END STORAGE CONFIGURATION
# EMAIL
DEFAULT_FROM_EMAIL = values.Value('tco2 <[email protected]>')
EMAIL_HOST = values.Value('smtp.sendgrid.com')
EMAIL_HOST_PASSWORD = values.SecretValue(environ_prefix="", environ_name="SENDGRID_PASSWORD")
EMAIL_HOST_USER = values.SecretValue(environ_prefix="", environ_name="SENDGRID_USERNAME")
EMAIL_PORT = values.IntegerValue(587, environ_prefix="", environ_name="EMAIL_PORT")
EMAIL_SUBJECT_PREFIX = values.Value('[tco2] ', environ_name="EMAIL_SUBJECT_PREFIX")
EMAIL_USE_TLS = True
SERVER_EMAIL = EMAIL_HOST_USER
# END EMAIL
# TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
# END TEMPLATE CONFIGURATION
# CACHING
# Only do this here because thanks to django-pylibmc-sasl and pylibmc
# memcacheify is painful to install on windows.
try:
# See: https://github.com/rdegges/django-heroku-memcacheify
from memcacheify import memcacheify
CACHES = memcacheify()
except ImportError:
CACHES = values.CacheURLValue(default="memcached://127.0.0.1:11211")
# END CACHING
# Your production stuff: Below this line define 3rd party library settings
| tpugsley/tco2 | tco2/config/production.py | Python | bsd-3-clause | 4,340 |
<?php
/**
* Locale data for 'tn'.
*
* This file is automatically generated by yiic cldr command.
*
* Copyright © 1991-2007 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
*
* Copyright © 2008-2010 Yii Software LLC (http://www.yiiframework.com/license/)
*/
return array (
'version' => '4123',
'numberSymbols' =>
array (
'decimal' => ',',
'group' => ' ',
'list' => ';',
'percentSign' => '%',
'nativeZeroDigit' => '0',
'patternDigit' => '#',
'plusSign' => '+',
'minusSign' => '-',
'exponential' => 'E',
'perMille' => '‰',
'infinity' => '∞',
'nan' => 'NaN',
),
'decimalFormat' => '#,##0.###',
'scientificFormat' => '#E0',
'percentFormat' => '#,##0%',
'currencyFormat' => '¤#,##0.00',
'currencySymbols' =>
array (
'AFN' => 'Af',
'ANG' => 'NAf.',
'AOA' => 'Kz',
'ARA' => '₳',
'ARL' => '$L',
'ARM' => 'm$n',
'ARS' => 'AR$',
'AUD' => 'AU$',
'AWG' => 'Afl.',
'AZN' => 'man.',
'BAM' => 'KM',
'BBD' => 'Bds$',
'BDT' => 'Tk',
'BEF' => 'BF',
'BHD' => 'BD',
'BIF' => 'FBu',
'BMD' => 'BD$',
'BND' => 'BN$',
'BOB' => 'Bs',
'BOP' => '$b.',
'BRL' => 'R$',
'BSD' => 'BS$',
'BTN' => 'Nu.',
'BWP' => 'BWP',
'BZD' => 'BZ$',
'CAD' => 'CA$',
'CDF' => 'CDF',
'CHF' => 'Fr.',
'CLE' => 'Eº',
'CLP' => 'CL$',
'CNY' => 'CN¥',
'COP' => 'CO$',
'CRC' => '₡',
'CUC' => 'CUC$',
'CUP' => 'CU$',
'CVE' => 'CV$',
'CYP' => 'CY£',
'CZK' => 'Kč',
'DEM' => 'DM',
'DJF' => 'Fdj',
'DKK' => 'Dkr',
'DOP' => 'RD$',
'DZD' => 'DA',
'EEK' => 'Ekr',
'EGP' => 'EG£',
'ERN' => 'Nfk',
'ESP' => 'Pts',
'ETB' => 'Br',
'EUR' => '€',
'FIM' => 'mk',
'FJD' => 'FJ$',
'FKP' => 'FK£',
'FRF' => '₣',
'GBP' => '£',
'GHC' => '₵',
'GHS' => 'GH₵',
'GIP' => 'GI£',
'GMD' => 'GMD',
'GNF' => 'FG',
'GRD' => '₯',
'GTQ' => 'GTQ',
'GYD' => 'GY$',
'HKD' => 'HK$',
'HNL' => 'HNL',
'HRK' => 'kn',
'HTG' => 'HTG',
'HUF' => 'Ft',
'IDR' => 'Rp',
'IEP' => 'IR£',
'ILP' => 'I£',
'ILS' => '₪',
'INR' => 'Rs',
'ISK' => 'Ikr',
'ITL' => 'IT₤',
'JMD' => 'J$',
'JOD' => 'JD',
'JPY' => 'JP¥',
'KES' => 'Ksh',
'KMF' => 'CF',
'KRW' => '₩',
'KWD' => 'KD',
'KYD' => 'KY$',
'LAK' => '₭',
'LBP' => 'LB£',
'LKR' => 'SLRs',
'LRD' => 'L$',
'LSL' => 'LSL',
'LTL' => 'Lt',
'LVL' => 'Ls',
'LYD' => 'LD',
'MMK' => 'MMK',
'MNT' => '₮',
'MOP' => 'MOP$',
'MRO' => 'UM',
'MTL' => 'Lm',
'MTP' => 'MT£',
'MUR' => 'MURs',
'MXP' => 'MX$',
'MYR' => 'RM',
'MZM' => 'Mt',
'MZN' => 'MTn',
'NAD' => 'N$',
'NGN' => '₦',
'NIO' => 'C$',
'NLG' => 'fl',
'NOK' => 'Nkr',
'NPR' => 'NPRs',
'NZD' => 'NZ$',
'PAB' => 'B/.',
'PEI' => 'I/.',
'PEN' => 'S/.',
'PGK' => 'PGK',
'PHP' => '₱',
'PKR' => 'PKRs',
'PLN' => 'zł',
'PTE' => 'Esc',
'PYG' => '₲',
'QAR' => 'QR',
'RHD' => 'RH$',
'RON' => 'RON',
'RSD' => 'din.',
'SAR' => 'SR',
'SBD' => 'SI$',
'SCR' => 'SRe',
'SDD' => 'LSd',
'SEK' => 'Skr',
'SGD' => 'S$',
'SHP' => 'SH£',
'SKK' => 'Sk',
'SLL' => 'Le',
'SOS' => 'Ssh',
'SRD' => 'SR$',
'SRG' => 'Sf',
'STD' => 'Db',
'SVC' => 'SV₡',
'SYP' => 'SY£',
'SZL' => 'SZL',
'THB' => '฿',
'TMM' => 'TMM',
'TND' => 'DT',
'TOP' => 'T$',
'TRL' => 'TRL',
'TRY' => 'TL',
'TTD' => 'TT$',
'TWD' => 'NT$',
'TZS' => 'TSh',
'UAH' => '₴',
'UGX' => 'USh',
'USD' => 'US$',
'UYU' => '$U',
'VEF' => 'Bs.F.',
'VND' => '₫',
'VUV' => 'VT',
'WST' => 'WS$',
'XAF' => 'FCFA',
'XCD' => 'EC$',
'XOF' => 'CFA',
'XPF' => 'CFPF',
'YER' => 'YR',
'ZAR' => 'R',
'ZMK' => 'ZK',
'ZRN' => 'NZ',
'ZRZ' => 'ZRZ',
'ZWD' => 'Z$',
),
'monthNames' =>
array (
'wide' =>
array (
1 => 'Ferikgong',
2 => 'Tlhakole',
3 => 'Mopitlo',
4 => 'Moranang',
5 => 'Motsheganang',
6 => 'Seetebosigo',
7 => 'Phukwi',
8 => 'Phatwe',
9 => 'Lwetse',
10 => 'Diphalane',
11 => 'Ngwanatsele',
12 => 'Sedimonthole',
),
'abbreviated' =>
array (
1 => 'Fer',
2 => 'Tlh',
3 => 'Mop',
4 => 'Mor',
5 => 'Mot',
6 => 'See',
7 => 'Phu',
8 => 'Pha',
9 => 'Lwe',
10 => 'Dip',
11 => 'Ngw',
12 => 'Sed',
),
),
'monthNamesSA' =>
array (
'narrow' =>
array (
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
10 => '10',
11 => '11',
12 => '12',
),
),
'weekDayNames' =>
array (
'wide' =>
array (
0 => 'Tshipi',
1 => 'Mosopulogo',
2 => 'Labobedi',
3 => 'Laboraro',
4 => 'Labone',
5 => 'Labotlhano',
6 => 'Matlhatso',
),
'abbreviated' =>
array (
0 => 'Tsh',
1 => 'Mos',
2 => 'Bed',
3 => 'Rar',
4 => 'Ne',
5 => 'Tla',
6 => 'Mat',
),
),
'weekDayNamesSA' =>
array (
'narrow' =>
array (
0 => '1',
1 => '2',
2 => '3',
3 => '4',
4 => '5',
5 => '6',
6 => '7',
),
),
'eraNames' =>
array (
'abbreviated' =>
array (
0 => 'BC',
1 => 'AD',
),
'wide' =>
array (
0 => 'BC',
1 => 'AD',
),
'narrow' =>
array (
0 => 'BC',
1 => 'AD',
),
),
'dateFormats' =>
array (
'full' => 'EEEE, y MMMM dd',
'long' => 'y MMMM d',
'medium' => 'y MMM d',
'short' => 'yy/MM/dd',
),
'timeFormats' =>
array (
'full' => 'HH:mm:ss zzzz',
'long' => 'HH:mm:ss z',
'medium' => 'HH:mm:ss',
'short' => 'HH:mm',
),
'dateTimeFormat' => '{1} {0}',
'amName' => 'AM',
'pmName' => 'PM',
);
| hukumonline/yii | framework/i18n/data/tn.php | PHP | bsd-3-clause | 6,212 |
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Zend\\View\\' => array($vendorDir . '/zendframework/zend-view/src'),
'Zend\\Validator\\' => array($vendorDir . '/zendframework/zend-validator/src'),
'Zend\\Uri\\' => array($vendorDir . '/zendframework/zend-uri/src'),
'Zend\\Stdlib\\' => array($vendorDir . '/zendframework/zend-stdlib/src'),
'Zend\\Session\\' => array($vendorDir . '/zendframework/zend-session/src'),
'Zend\\ServiceManager\\' => array($vendorDir . '/zendframework/zend-servicemanager/src'),
'Zend\\Router\\' => array($vendorDir . '/zendframework/zend-router/src'),
'Zend\\Mvc\\Plugin\\Prg\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-prg/src'),
'Zend\\Mvc\\Plugin\\Identity\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-identity/src'),
'Zend\\Mvc\\Plugin\\FlashMessenger\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-flashmessenger/src'),
'Zend\\Mvc\\Plugin\\FilePrg\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-fileprg/src'),
'Zend\\Mvc\\I18n\\' => array($vendorDir . '/zendframework/zend-mvc-i18n/src'),
'Zend\\Mvc\\' => array($vendorDir . '/zendframework/zend-mvc/src'),
'Zend\\ModuleManager\\' => array($vendorDir . '/zendframework/zend-modulemanager/src'),
'Zend\\Loader\\' => array($vendorDir . '/zendframework/zend-loader/src'),
'Zend\\Json\\' => array($vendorDir . '/zendframework/zend-json/src'),
'Zend\\InputFilter\\' => array($vendorDir . '/zendframework/zend-inputfilter/src'),
'Zend\\I18n\\' => array($vendorDir . '/zendframework/zend-i18n/src'),
'Zend\\Hydrator\\' => array($vendorDir . '/zendframework/zend-hydrator/src'),
'Zend\\Http\\' => array($vendorDir . '/zendframework/zend-http/src'),
'Zend\\Form\\' => array($vendorDir . '/zendframework/zend-form/src'),
'Zend\\Filter\\' => array($vendorDir . '/zendframework/zend-filter/src'),
'Zend\\EventManager\\' => array($vendorDir . '/zendframework/zend-eventmanager/src'),
'Zend\\Escaper\\' => array($vendorDir . '/zendframework/zend-escaper/src'),
'Zend\\Debug\\' => array($vendorDir . '/zendframework/zend-debug/src'),
'Zend\\Db\\' => array($vendorDir . '/zendframework/zend-db/src'),
'Zend\\Config\\' => array($vendorDir . '/zendframework/zend-config/src'),
'Zend\\ComponentInstaller\\' => array($vendorDir . '/zendframework/zend-component-installer/src'),
'Zend\\Code\\' => array($vendorDir . '/zendframework/zend-code/src'),
'Zend\\Authentication\\' => array($vendorDir . '/zendframework/zend-authentication/src'),
'ZendDeveloperTools\\' => array($vendorDir . '/zendframework/zend-developer-tools/src'),
'ZF\\DevelopmentMode\\' => array($vendorDir . '/zfcampus/zf-development-mode/src'),
'Pajakdaerah\\' => array($baseDir . '/module/Pajakdaerah/src'),
'Interop\\Container\\' => array($vendorDir . '/container-interop/container-interop/src/Interop/Container'),
'Application\\' => array($baseDir . '/module/Application/src'),
'ApplicationTest\\' => array($baseDir . '/module/Application/test'),
);
| fabi4n/pajakdaerah | vendor/composer/autoload_psr4.php | PHP | bsd-3-clause | 3,163 |
/*
* Software License Agreement (New BSD License)
*
* Copyright (c) 2013, Keith Leung, Felipe Inostroza
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Advanced Mining Technology Center (AMTC), the
* Universidad de Chile, nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AMTC, UNIVERSIDAD DE CHILE, OR THE COPYRIGHT
* HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <boost/filesystem.hpp>
#include "GaussianMixture.hpp"
#include "Landmark.hpp"
#include "COLA.hpp"
#include "Particle.hpp"
#include "Pose.hpp"
#include <stdio.h>
#include <string>
#include <vector>
typedef unsigned int uint;
using namespace rfs;
class MM : public Landmark2d{
public:
MM(double x, double y, rfs::TimeStamp t = TimeStamp() ){
x_(0) = x;
x_(1) = y;
this->setTime(t);
}
~MM(){}
double operator-(const MM& other){
rfs::Landmark2d::Vec dx = x_ - other.x_;
return dx.norm();
//return sqrt(mahalanobisDist2( other )); For Mahalanobis distance
}
};
struct COLA_Error{
double error; // combined average error
double loc; // localization error
double card; // cardinality error
TimeStamp t;
};
/**
* \class LogFileReader2dSim
* \brief A class for reading 2d sim log files and for calculating errors
*/
class LogFileReader2dSim
{
public:
typedef Particle<Pose2d, GaussianMixture<Landmark2d> > TParticle;
typedef std::vector< TParticle > TParticleSet;
/** Constructor */
LogFileReader2dSim(const char* logDir){
std::string filename_gtpose( logDir );
std::string filename_gtlmk( logDir );
std::string filename_pose( logDir );
std::string filename_lmk( logDir );
std::string filename_dr( logDir );
filename_gtpose += "gtPose.dat";
filename_gtlmk += "gtLandmark.dat";
filename_pose += "particlePose.dat";
filename_lmk += "landmarkEst.dat";
filename_dr += "deadReckoning.dat";
pGTPoseFile = fopen(filename_gtpose.data(), "r");
pGTLandmarkFile = fopen(filename_gtlmk.data(), "r");
pParticlePoseFile = fopen(filename_pose.data(), "r");
pLandmarkEstFile = fopen(filename_lmk.data(), "r");
pDRFile = fopen(filename_dr.data(), "r");
readLandmarkGroundtruth();
int nread = fscanf(pParticlePoseFile, "%lf %d %lf %lf %lf %lf", &p_t_, &p_id_, &p_x_, &p_y_, &p_z_, &p_w_);
//printf("n = %d\n", nread);
//printf("t = %f [%d] %f %f %f\n", p_t_, p_id_, p_x_, p_y_, p_w_);
nread = fscanf(pLandmarkEstFile, "%lf %d %lf %lf %lf %lf %lf %lf\n",
&lmk_t_, &lmk_pid_, &lmk_x_, &lmk_y_, &lmk_sxx_, &lmk_sxy_, &lmk_syy_, &lmk_w_);
//printf("n = %d\n", nread);
//printf("t = %f [%d] %f %f %f\n", lmk_t_, lmk_pid_, lmk_x_, lmk_y_, lmk_w_);
}
/** Destructor */
~LogFileReader2dSim(){
fclose(pGTPoseFile);
fclose(pGTLandmarkFile);
fclose(pParticlePoseFile);
fclose(pLandmarkEstFile);
fclose(pDRFile);
}
/** Read landmark groundtruth data
* \return number of landmarks
*/
void readLandmarkGroundtruth(){
double x, y, t;
while( fscanf(pGTLandmarkFile, "%lf %lf %lf", &x, &y, &t) == 3){
map_e_M_.push_back( MM( x, y, TimeStamp(t) ) );
}
}
/** Read data for the next timestep
* \return time for which data was read
*/
double readNextStepData(){
if( fscanf(pGTPoseFile, "%lf %lf %lf %lf\n", &t_currentStep_, &rx_, &ry_, &rz_ ) == 4){
// Dead reckoning
int rval = fscanf(pDRFile, "%lf %lf %lf %lf\n", &dr_t_, &dr_x_, &dr_y_, &dr_z_);
// Particles
particles_.clear();
particles_.reserve(200);
w_sum_ = 0;
double w_hi = 0;
while(fabs(p_t_ - t_currentStep_) < 1e-12 ){
// printf("t = %f [%d] %f %f %f\n", p_t_, p_id_, p_x_, p_y_, p_w_);
w_sum_ += p_w_;
if( p_w_ > w_hi ){
i_hi_ = p_id_;
w_hi = p_w_;
}
Pose2d p;
p[0] = p_x_;
p[1] = p_y_;
p[2] = p_z_;
TParticle particle(p_id_, p, p_w_);
particles_.push_back( particle );
particles_[p_id_].setData( TParticle::PtrData( new GaussianMixture<Landmark2d> ));
if( fscanf(pParticlePoseFile, "%lf %d %lf %lf %lf %lf", &p_t_, &p_id_, &p_x_, &p_y_, &p_z_, &p_w_) != 6)
break;
}
// Landmark estimate from highest weighted particle
double const W_THRESHOLD = 0.75;
emap_e_M_.clear();
cardEst_ = 0;
while(fabs(lmk_t_ - t_currentStep_) < 1e-12){
if( lmk_pid_ == i_hi_ ){
if( lmk_w_ >= W_THRESHOLD ){
MM m_e_M(lmk_x_, lmk_y_, lmk_t_);
rfs::Landmark2d::Cov mCov;
mCov << lmk_sxx_, lmk_sxy_, lmk_sxy_, lmk_syy_;
m_e_M.setCov(mCov);
emap_e_M_.push_back(m_e_M);
}
cardEst_ += lmk_w_;
}
if(fscanf(pLandmarkEstFile, "%lf %d %lf %lf %lf %lf %lf %lf\n",
&lmk_t_, &lmk_pid_, &lmk_x_, &lmk_y_, &lmk_sxx_, &lmk_sxy_, &lmk_syy_, &lmk_w_) != 8)
break;
}
return t_currentStep_;
}
return -1;
}
/** Calculate the cardinality error for landmark estimates
* \param[out] nLandmarksObservable the actual number of observed landnmarks up to the current time
* \return cardinality estimate
*/
double getCardinalityEst( int &nLandmarksObservable ){
std::vector<MM> map_e_k_M; // observed groundtruth map storage (for Mahananobis distance calculations)
map_e_k_M.clear();
for(uint i = 0; i < map_e_M_.size(); i++){
if( map_e_M_[i].getTime().getTimeAsDouble() <= t_currentStep_ ){
map_e_k_M.push_back(map_e_M_[i]);
}
}
nLandmarksObservable = map_e_k_M.size();
return cardEst_;
}
/** Caclculate the error for landmark estimates
* \return COLA errors
*/
COLA_Error calcLandmarkError(){
double const cutoff = 0.20; // cola cutoff
double const order = 1.0; // cola order
std::vector<MM> map_e_k_M; // observed groundtruth map storage (for Mahananobis distance calculations)
map_e_k_M.clear();
for(uint i = 0; i < map_e_M_.size(); i++){
if( map_e_M_[i].getTime().getTimeAsDouble() <= t_currentStep_ ){
map_e_k_M.push_back(map_e_M_[i]);
}
}
COLA_Error e_cola;
e_cola.t = t_currentStep_;
COLA<MM> cola(emap_e_M_, map_e_k_M, cutoff, order);
e_cola.error = cola.calcError(&(e_cola.loc), &(e_cola.card));
return e_cola;
}
/** Calculate the dead reckoning error */
void calcDRError(double &err_x, double &err_y, double &err_rot, double &err_dist){
err_x = dr_x_ - rx_;
err_y = dr_y_ - ry_;
err_rot = dr_z_ - rz_;
if(err_rot > PI)
err_rot -= 2*PI;
else if(err_rot < -PI)
err_rot += 2*PI;
err_dist = sqrt(err_x * err_x + err_y * err_y);
}
/** Calculate the error for vehicle pose estimate */
void calcPoseError(double &err_x, double &err_y, double &err_rot, double &err_dist, bool getAverageError = true){
err_x = 0;
err_y = 0;
err_rot = 0;
err_dist = 0;
Pose2d poseEst;
double w = 1;
double ex;
double ey;
double er;
for(int i = 0; i < particles_.size(); i++){
if( !getAverageError && i != i_hi_){
continue;
}
if( getAverageError ){
w = particles_[i].getWeight();
}
poseEst = particles_[i];
ex = poseEst[0] - rx_;
ey = poseEst[1] - ry_;
er = poseEst[2] - rz_;
if(er > PI)
er -= 2 * PI;
else if(er < -PI)
er += 2 * PI;
err_x += ex * w;
err_y += ey * w;
err_rot += er * w;
err_dist += sqrt(ex * ex + ey * ey) * w;
if( !getAverageError && i == i_hi_){
break;
}
}
if( getAverageError ){
err_x /= w_sum_;
err_y /= w_sum_;
err_rot /= w_sum_;
err_dist /= w_sum_;
}
}
private:
FILE* pGTPoseFile; /**< robot pose groundtruth file pointer */
FILE* pGTLandmarkFile; /**< landmark groundtruth file pointer */
FILE* pParticlePoseFile; /**< pose estimate file pointer */
FILE* pLandmarkEstFile; /**< landmark estimate file pointer */
FILE* pMapEstErrorFile; /**< landmark estimate error file pointer */
FILE* pDRFile; /**< Dead-reckoning file */
double mx_; /**< landmark x pos */
double my_; /**< landmark y pos */
double t_currentStep_;
double rx_;
double ry_;
double rz_;
double dr_x_;
double dr_y_;
double dr_z_;
double dr_t_;
double i_hi_; /** highest particle weight index */
double w_sum_; /** particle weight sum */
TParticleSet particles_;
std::vector< Pose2d > pose_gt_;
std::vector<MM> map_e_M_; // groundtruth map storage (for Mahananobis distance calculations)
std::vector<MM> emap_e_M_; // estimated map storage (for Mahananobis distance calculations)
double cardEst_; // cardinality estimate
double p_t_;
int p_id_;
double p_x_;
double p_y_;
double p_z_;
double p_w_;
double lmk_t_;
int lmk_pid_;
double lmk_x_;
double lmk_y_;
double lmk_sxx_;
double lmk_sxy_;
double lmk_syy_;
double lmk_w_;
};
int main(int argc, char* argv[]){
if( argc != 2 ){
printf("Usage: analysis2dSim DATA_DIR/\n");
return 0;
}
const char* logDir = argv[1];
printf("Log directory: %s\n", logDir);
boost::filesystem::path dir(logDir);
if(!exists(dir)){
printf("Log directory %s does not exist\n", logDir);
return 0;
}
std::string filenameLandmarkEstError( logDir );
std::string filenamePoseEstError( logDir );
std::string filenameDREstError( logDir );
filenameLandmarkEstError += "landmarkEstError.dat";
filenamePoseEstError += "poseEstError.dat";
filenameDREstError += "deadReckoningError.dat";
FILE* pMapEstErrorFile = fopen(filenameLandmarkEstError.data(), "w");
FILE* pPoseEstErrorFile = fopen(filenamePoseEstError.data(), "w");
FILE* pDREstErrorFile = fopen(filenameDREstError.data(), "w");
LogFileReader2dSim reader(logDir);
double k = reader.readNextStepData();
while( k != -1){
//printf("Time: %f\n", k);
double ex, ey, er, ed;
reader.calcDRError( ex, ey, er, ed);
fprintf(pDREstErrorFile, "%f %f %f %f %f\n", k, ex, ey, er, ed);
reader.calcPoseError( ex, ey, er, ed, false );
fprintf(pPoseEstErrorFile, "%f %f %f %f %f\n", k, ex, ey, er, ed);
//printf(" error x: %f error y: %f error rot: %f error dist: %f\n", ex, ey, er, ed);
int nLandmarksObserved;
double cardEst = reader.getCardinalityEst( nLandmarksObserved );
COLA_Error colaError = reader.calcLandmarkError();
fprintf(pMapEstErrorFile, "%f %d %f %f\n", k, nLandmarksObserved, cardEst, colaError.error);
//printf(" nLandmarks: %d nLandmarks estimated: %f COLA error: %f\n", nLandmarksObserved, cardEst, colaError.loc + colaError.card);
//printf("--------------------\n");
k = reader.readNextStepData();
}
fclose(pPoseEstErrorFile);
fclose(pMapEstErrorFile);
fclose(pDREstErrorFile);
return 0;
}
| RangerKD/RFS-SLAM | src/analysis2dSim.cpp | C++ | bsd-3-clause | 12,152 |
/*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#include "TextEvent.h"
#include "DocumentFragment.h"
#include "EventNames.h"
namespace WebCore {
PassRefPtr<TextEvent> TextEvent::create()
{
return adoptRef(new TextEvent);
}
PassRefPtr<TextEvent> TextEvent::create(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
{
return adoptRef(new TextEvent(view, data, inputType));
}
PassRefPtr<TextEvent> TextEvent::createForPlainTextPaste(PassRefPtr<AbstractView> view, const String& data, bool shouldSmartReplace)
{
return adoptRef(new TextEvent(view, data, 0, shouldSmartReplace, false));
}
PassRefPtr<TextEvent> TextEvent::createForFragmentPaste(PassRefPtr<AbstractView> view, PassRefPtr<DocumentFragment> data, bool shouldSmartReplace, bool shouldMatchStyle)
{
return adoptRef(new TextEvent(view, "", data, shouldSmartReplace, shouldMatchStyle));
}
PassRefPtr<TextEvent> TextEvent::createForDrop(PassRefPtr<AbstractView> view, const String& data)
{
return adoptRef(new TextEvent(view, data, TextEventInputDrop));
}
PassRefPtr<TextEvent> TextEvent::createForDictation(PassRefPtr<AbstractView> view, const String& data, const Vector<DictationAlternative>& dictationAlternatives)
{
return adoptRef(new TextEvent(view, data, dictationAlternatives));
}
TextEvent::TextEvent()
: m_inputType(TextEventInputKeyboard)
, m_shouldSmartReplace(false)
, m_shouldMatchStyle(false)
{
}
TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
: UIEvent(eventNames().textInputEvent, true, true, view, 0)
, m_inputType(inputType)
, m_data(data)
, m_pastingFragment(0)
, m_shouldSmartReplace(false)
, m_shouldMatchStyle(false)
{
}
TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, PassRefPtr<DocumentFragment> pastingFragment,
bool shouldSmartReplace, bool shouldMatchStyle)
: UIEvent(eventNames().textInputEvent, true, true, view, 0)
, m_inputType(TextEventInputPaste)
, m_data(data)
, m_pastingFragment(pastingFragment)
, m_shouldSmartReplace(shouldSmartReplace)
, m_shouldMatchStyle(shouldMatchStyle)
{
}
TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, const Vector<DictationAlternative>& dictationAlternatives)
: UIEvent(eventNames().textInputEvent, true, true, view, 0)
, m_inputType(TextEventInputDictation)
, m_data(data)
, m_shouldSmartReplace(false)
, m_shouldMatchStyle(false)
, m_dictationAlternatives(dictationAlternatives)
{
}
TextEvent::~TextEvent()
{
}
void TextEvent::initTextEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, const String& data)
{
if (dispatched())
return;
initUIEvent(type, canBubble, cancelable, view, 0);
m_data = data;
}
EventInterface TextEvent::eventInterface() const
{
return TextEventInterfaceType;
}
} // namespace WebCore
| klim-iv/phantomjs-qt5 | src/webkit/Source/WebCore/dom/TextEvent.cpp | C++ | bsd-3-clause | 4,309 |
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
export default {"viewBox":"0 0 52 52","xmlns":"http://www.w3.org/2000/svg","path":[{"d":"M43.3 6h-1.73a.74.74 0 00-.67.8V10a6.37 6.37 0 01-6.3 6.4H17.4a6.37 6.37 0 01-6.3-6.4V6.67a.74.74 0 00-.8-.67H8.7A4.77 4.77 0 004 10.8v34.4A4.77 4.77 0 008.7 50h34.6a4.77 4.77 0 004.7-4.8V10.8A4.77 4.77 0 0043.3 6zM25.92 45a12 12 0 01.16-24 12 12 0 01-.16 24z"},{"d":"M16.91 11.6h17.86a1.59 1.59 0 001.63-1.55V6.8A4.81 4.81 0 0031.6 2H20.4a4.82 4.82 0 00-4.8 4.8V10a1.47 1.47 0 001.31 1.6zM32.23 27.2A9.09 9.09 0 0026 24.4v8.8h8.77a7.32 7.32 0 00-2.54-6z"}]};
| salesforce/design-system-react | icons/utility/capacity_plan.js | JavaScript | bsd-3-clause | 701 |
// 1000-page badge
// Awarded when total read page count exceeds 1000.
var sys = require('sys');
var _ = require('underscore');
var users = require('../../users');
var badge_template = require('./badge');
// badge key, must be unique.
var name = "1000page";
exports.badge_info =
{
id: name,
name: "1,000 Pages",
achievement: "Reading over 1,000 pages."
}
// the in-work state of a badge for a user
function Badge (userid) {
badge_template.Badge.apply(this,arguments);
this.id = name;
this.page_goal = 1000;
};
// inherit from the badge template
sys.inherits(Badge, badge_template.Badge);
// Steps to perform when a book is added or modified in the read list
Badge.prototype.add_reading_transform = function(reading,callback) {
var pages = parseInt(reading.book.pages);
if (_.isNumber(pages)) {
this.state[reading.book_id] = pages
}
callback();
};
// Steps to perform when a book is removed from the read list.
Badge.prototype.remove_book_transform = function(book,callback) {
delete(this.state[book.id]);
callback();
};
// determine if the badge should be awarded, and if yes, do so
Badge.prototype.should_award = function(callback) {
// sum all page counts in state
var pagecount = 0;
for (bookid in this.state) {
pagecount += this.state[bookid]
}
return (pagecount >= this.page_goal);
}
exports.Badge = Badge; | scsibug/read52 | badger/badges/1000page.js | JavaScript | bsd-3-clause | 1,422 |
/*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class StaticRouteProfile extends ApplyProfile {
public String key;
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key=key;
}
} | xebialabs/vijava | src/com/vmware/vim25/StaticRouteProfile.java | Java | bsd-3-clause | 1,954 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.