prompt large_stringlengths 70 991k | completion large_stringlengths 0 1.02k |
|---|---|
<|file_name|>DelimitedParseSpecTest.java<|end_file_name|><|fim▁begin|>/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you 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.
*/
package io.druid.data.input.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import io.druid.TestObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import javax.validation.constraints.Null;
import java.io.IOException;
import java.util.Arrays;
public class DelimitedParseSpecTest
{
private final ObjectMapper jsonMapper = new TestObjectMapper();
@Test
public void testSerde() throws IOException
{
DelimitedParseSpec spec = new DelimitedParseSpec(
new TimestampSpec("abc", "iso", null,null),
new DimensionsSpec(DimensionsSpec.getDefaultSchemas(Arrays.asList("abc")), null, null),
"\u0001",
"\u0002",
Arrays.asList("abc")
);
final DelimitedParseSpec serde = jsonMapper.readValue(
jsonMapper.writeValueAsString(spec),
DelimitedParseSpec.class
);
Assert.assertEquals("abc", serde.getTimestampSpec().getTimestampColumn());
Assert.assertEquals("iso", serde.getTimestampSpec().getTimestampFormat());
Assert.assertEquals(Arrays.asList("abc"), serde.getColumns());
Assert.assertEquals("\u0001", serde.getDelimiter());
Assert.assertEquals("\u0002", serde.getListDelimiter());
Assert.assertEquals(Arrays.asList("abc"), serde.getDimensionsSpec().getDimensionNames());
}
@Test(expected = IllegalArgumentException.class)<|fim▁hole|> {
final ParseSpec spec = new DelimitedParseSpec(
new TimestampSpec(
"timestamp",
"auto",
null,
null
),
new DimensionsSpec(
DimensionsSpec.getDefaultSchemas(Arrays.asList("a", "b")),
Lists.<String>newArrayList(),
Lists.<SpatialDimensionSchema>newArrayList()
),
",",
" ",
Arrays.asList("a")
);
}
@Test(expected = IllegalArgumentException.class)
public void testComma() throws Exception
{
final ParseSpec spec = new DelimitedParseSpec(
new TimestampSpec(
"timestamp",
"auto",
null,
null
),
new DimensionsSpec(
DimensionsSpec.getDefaultSchemas(Arrays.asList("a,", "b")),
Lists.<String>newArrayList(),
Lists.<SpatialDimensionSchema>newArrayList()
),
",",
null,
Arrays.asList("a")
);
}
@Test(expected = NullPointerException.class)
public void testDefaultColumnList(){
final DelimitedParseSpec spec = new DelimitedParseSpec(
new TimestampSpec(
"timestamp",
"auto",
null,
null
),
new DimensionsSpec(
DimensionsSpec.getDefaultSchemas(Arrays.asList("a", "b")),
Lists.<String>newArrayList(),
Lists.<SpatialDimensionSchema>newArrayList()
),
",",
null,
// pass null columns not allowed
null
);
}
}<|fim▁end|> | public void testColumnMissing() throws Exception |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>import django.db.models as models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
class Profile(models.Model):
"""
parameters we can get from gigya:
birthMonth,isLoggedIn,city,UID,zip,birthYear,state,provider,email,
UIDSig,photoURL,timestamp,loginProviderUID,signature,isSiteUID,proxiedEmail
,thumbnailURL,nickname,firstName,loginProvider,gender,lastName,profileURL
birthDay,country,isSiteUser
One unique user can have several UID's
"""
user = models.ForeignKey(User, unique=True, null=True)
uid = models.CharField(max_length=255)
login_provider = models.CharField(max_length=150)
timestamp = models.DateTimeField(null=True,blank=True)
isLoggedIn = models.BooleanField(default=False)
birthday = models.DateField(null=True,blank=True)
city = models.CharField(max_length=150, null=True,blank=True)
state = models.CharField(max_length=150, null=True,blank=True)<|fim▁hole|> country = models.CharField(max_length=30, null=True,blank=True)
photourl = models.CharField(max_length=255, null=True,blank=True)
first_name = models.CharField(max_length=80, null=True,blank=True)
last_name = models.CharField(max_length=80, null=True,blank=True)
gender = models.CharField(max_length=2, null=True,blank=True)
profileUrl = models.CharField(max_length=2, null=True, blank=True)
def create_profile(sender, instance=None, **kwargs):
if instance is None:
return
profile, created = Profile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)<|fim▁end|> | zip = models.CharField(max_length=30, null=True,blank=True) |
<|file_name|>gdaldrivermanager.cpp<|end_file_name|><|fim▁begin|>/******************************************************************************
* $Id: gdaldrivermanager.cpp 27121 2014-04-03 22:08:55Z rouault $
*
* Project: GDAL Core
* Purpose: Implementation of GDALDriverManager class.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1998, Frank Warmerdam
* Copyright (c) 2009-2013, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "gdal_priv.h"
#include "cpl_string.h"
#include "cpl_multiproc.h"
#include "ogr_srs_api.h"
#include "cpl_multiproc.h"
#include "gdal_pam.h"
#include "gdal_alg_priv.h"
#ifdef _MSC_VER
# ifdef MSVC_USE_VLD
# include <wchar.h>
# include <vld.h>
# endif
#endif
CPL_CVSID("$Id: gdaldrivermanager.cpp 27121 2014-04-03 22:08:55Z rouault $");
static const char *pszUpdatableINST_DATA =
"__INST_DATA_TARGET: ";
/************************************************************************/
/* ==================================================================== */
/* GDALDriverManager */
/* ==================================================================== */
/************************************************************************/
static volatile GDALDriverManager *poDM = NULL;
static void *hDMMutex = NULL;
void** GDALGetphDMMutex() { return &hDMMutex; }
/************************************************************************/
/* GetGDALDriverManager() */
/* */
/* A freestanding function to get the only instance of the */
/* GDALDriverManager. */
/************************************************************************/
/**
* \brief Fetch the global GDAL driver manager.
*
* This function fetches the pointer to the singleton global driver manager.
* If the driver manager doesn't exist it is automatically created.
*
* @return pointer to the global driver manager. This should not be able
* to fail.
*/
GDALDriverManager * GetGDALDriverManager()
{
if( poDM == NULL )
{
CPLMutexHolderD( &hDMMutex );
if( poDM == NULL )
poDM = new GDALDriverManager();
}
CPLAssert( NULL != poDM );
return const_cast<GDALDriverManager *>( poDM );
}
/************************************************************************/
/* GDALDriverManager() */
/************************************************************************/
GDALDriverManager::GDALDriverManager()
{
nDrivers = 0;
papoDrivers = NULL;
pszHome = CPLStrdup("");
CPLAssert( poDM == NULL );
/* -------------------------------------------------------------------- */
/* We want to push a location to search for data files */
/* supporting GDAL/OGR such as EPSG csv files, S-57 definition */
/* files, and so forth. The static pszUpdateableINST_DATA */
/* string can be updated within the shared library or */
/* executable during an install to point installed data */
/* directory. If it isn't burned in here then we use the */
/* INST_DATA macro (setup at configure time) if */
/* available. Otherwise we don't push anything and we hope */
/* other mechanisms such as environment variables will have */
/* been employed. */
/* -------------------------------------------------------------------- */
if( CPLGetConfigOption( "GDAL_DATA", NULL ) != NULL )
{
// this one is picked up automatically by finder initialization.
}
else if( pszUpdatableINST_DATA[19] != ' ' )
{
CPLPushFinderLocation( pszUpdatableINST_DATA + 19 );
}
else
{
#ifdef INST_DATA
CPLPushFinderLocation( INST_DATA );
#endif
}
}
/************************************************************************/
/* ~GDALDriverManager() */
/************************************************************************/
void GDALDatasetPoolPreventDestroy(); /* keep that in sync with gdalproxypool.cpp */
void GDALDatasetPoolForceDestroy(); /* keep that in sync with gdalproxypool.cpp */
GDALDriverManager::~GDALDriverManager()
{
/* -------------------------------------------------------------------- */
/* Cleanup any open datasets. */
/* -------------------------------------------------------------------- */
int i, nDSCount;
GDALDataset **papoDSList;
/* First begin by requesting each reamining dataset to drop any reference */
/* to other datasets */
int bHasDroppedRef;
/* We have to prevent the destroying of the dataset pool during this first */
/* phase, otherwise it cause crashes with a VRT B referencing a VRT A, and if */
/* CloseDependentDatasets() is called first on VRT A. */
/* If we didn't do this nasty trick, due to the refCountOfDisableRefCount */
/* mechanism that cheats the real refcount of the dataset pool, we might */
/* destroy the dataset pool too early, leading the VRT A to */
/* destroy itself indirectly ... Ok, I am aware this explanation does */
/* not make any sense unless you try it under a debugger ... */
/* When people just manipulate "top-level" dataset handles, we luckily */
/* don't need this horrible hack, but GetOpenDatasets() expose "low-level" */
/* datasets, which defeat some "design" of the proxy pool */
GDALDatasetPoolPreventDestroy();
do
{
papoDSList = GDALDataset::GetOpenDatasets(&nDSCount);
/* If a dataset has dropped a reference, the list might have become */
/* invalid, so go out of the loop and try again with the new valid */
/* list */
bHasDroppedRef = FALSE;
for(i=0;i<nDSCount && !bHasDroppedRef;i++)
{
//CPLDebug("GDAL", "Call CloseDependentDatasets() on %s",
// papoDSList[i]->GetDescription() );
bHasDroppedRef = papoDSList[i]->CloseDependentDatasets();
}
} while(bHasDroppedRef);
/* Now let's destroy the dataset pool. Nobody shoud use it afterwards */
/* if people have well released their dependent datasets above */
GDALDatasetPoolForceDestroy();
/* Now close the stand-alone datasets */
papoDSList = GDALDataset::GetOpenDatasets(&nDSCount);
for(i=0;i<nDSCount;i++)
{
CPLDebug( "GDAL", "force close of %s (%p) in GDALDriverManager cleanup.",
papoDSList[i]->GetDescription(), papoDSList[i] );
/* Destroy with delete operator rather than GDALClose() to force deletion of */
/* datasets with multiple reference count */
/* We could also iterate while GetOpenDatasets() returns a non NULL list */
delete papoDSList[i];
}
/* -------------------------------------------------------------------- */
/* Destroy the existing drivers. */
/* -------------------------------------------------------------------- */
while( GetDriverCount() > 0 )
{
GDALDriver *poDriver = GetDriver(0);
DeregisterDriver(poDriver);
delete poDriver;
}
delete GDALGetAPIPROXYDriver();
/* -------------------------------------------------------------------- */
/* Cleanup local memory. */
/* -------------------------------------------------------------------- */
VSIFree( papoDrivers );
VSIFree( pszHome );
/* -------------------------------------------------------------------- */
/* Cleanup any Proxy related memory. */
/* -------------------------------------------------------------------- */
PamCleanProxyDB();
/* -------------------------------------------------------------------- */
/* Blow away all the finder hints paths. We really shouldn't */
/* be doing all of them, but it is currently hard to keep track */
/* of those that actually belong to us. */
/* -------------------------------------------------------------------- */
CPLFinderClean();
CPLFreeConfig();
CPLCleanupSharedFileMutex();
/* -------------------------------------------------------------------- */
/* Cleanup any memory allocated by the OGRSpatialReference */
/* related subsystem. */
/* -------------------------------------------------------------------- */
OSRCleanup();
/* -------------------------------------------------------------------- */
/* Cleanup VSIFileManager. */
/* -------------------------------------------------------------------- */
VSICleanupFileManager();
/* -------------------------------------------------------------------- */
/* Cleanup thread local storage ... I hope the program is all */
/* done with GDAL/OGR! */
/* -------------------------------------------------------------------- */
CPLCleanupTLS();
/* -------------------------------------------------------------------- */
/* Cleanup our mutex. */
/* -------------------------------------------------------------------- */
if( hDMMutex )
{
CPLDestroyMutex( hDMMutex );
hDMMutex = NULL;
}
/* -------------------------------------------------------------------- */
/* Cleanup dataset list mutex */
/* -------------------------------------------------------------------- */
if ( *GDALGetphDLMutex() != NULL )
{
CPLDestroyMutex( *GDALGetphDLMutex() );
*GDALGetphDLMutex() = NULL;
}
/* -------------------------------------------------------------------- */
/* Cleanup raster block mutex */
/* -------------------------------------------------------------------- */
GDALRasterBlock::DestroyRBMutex();
/* -------------------------------------------------------------------- */
/* Cleanup gdaltransformer.cpp mutex */
/* -------------------------------------------------------------------- */
GDALCleanupTransformDeserializerMutex();
/* -------------------------------------------------------------------- */
/* Cleanup cpl_error.cpp mutex */
/* -------------------------------------------------------------------- */
CPLCleanupErrorMutex();
/* -------------------------------------------------------------------- */
/* Cleanup CPLsetlocale mutex */
/* -------------------------------------------------------------------- */
CPLCleanupSetlocaleMutex();
/* -------------------------------------------------------------------- */
/* Cleanup the master CPL mutex, which governs the creation */
/* of all other mutexes. */
/* -------------------------------------------------------------------- */
CPLCleanupMasterMutex();
/* -------------------------------------------------------------------- */
/* Ensure the global driver manager pointer is NULLed out. */
/* -------------------------------------------------------------------- */
if( poDM == this )
poDM = NULL;
}
/************************************************************************/
/* GetDriverCount() */
/************************************************************************/
/**
* \brief Fetch the number of registered drivers.
*
* This C analog to this is GDALGetDriverCount().
*
* @return the number of registered drivers.
*/
int GDALDriverManager::GetDriverCount()
{
return( nDrivers );
}
/************************************************************************/
/* GDALGetDriverCount() */
/************************************************************************/
/**
* \brief Fetch the number of registered drivers.
*
* @see GDALDriverManager::GetDriverCount()
*/
int CPL_STDCALL GDALGetDriverCount()
{
return GetGDALDriverManager()->GetDriverCount();
}
/************************************************************************/
/* GetDriver() */
/************************************************************************/
/**
* \brief Fetch driver by index.
*
* This C analog to this is GDALGetDriver().
*
* @param iDriver the driver index from 0 to GetDriverCount()-1.
*
* @return the driver identified by the index or NULL if the index is invalid
*/
GDALDriver * GDALDriverManager::GetDriver( int iDriver )
{
CPLMutexHolderD( &hDMMutex );
if( iDriver < 0 || iDriver >= nDrivers )
return NULL;
else
return papoDrivers[iDriver];
}
/************************************************************************/
/* GDALGetDriver() */
/************************************************************************/
/**
* \brief Fetch driver by index.
*
* @see GDALDriverManager::GetDriver()
*/
GDALDriverH CPL_STDCALL GDALGetDriver( int iDriver )
{
return (GDALDriverH) GetGDALDriverManager()->GetDriver(iDriver);
}
/************************************************************************/
/* RegisterDriver() */
/************************************************************************/
/**
* \brief Register a driver for use.
*
* The C analog is GDALRegisterDriver().
*
* Normally this method is used by format specific C callable registration
* entry points such as GDALRegister_GTiff() rather than being called
* directly by application level code.
*
* If this driver (based on the object pointer, not short name) is already
* registered, then no change is made, and the index of the existing driver
* is returned. Otherwise the driver list is extended, and the new driver
* is added at the end.
*
* @param poDriver the driver to register.
*
* @return the index of the new installed driver.
*/
int GDALDriverManager::RegisterDriver( GDALDriver * poDriver )
{
CPLMutexHolderD( &hDMMutex );
/* -------------------------------------------------------------------- */
/* If it is already registered, just return the existing */
/* index. */
/* -------------------------------------------------------------------- */
if( GetDriverByName( poDriver->GetDescription() ) != NULL )
{
int i;
for( i = 0; i < nDrivers; i++ )
{
if( papoDrivers[i] == poDriver )
{
return i;
}
}
CPLAssert( FALSE );
}
/* -------------------------------------------------------------------- */
/* Otherwise grow the list to hold the new entry. */
/* -------------------------------------------------------------------- */
papoDrivers = (GDALDriver **)
VSIRealloc(papoDrivers, sizeof(GDALDriver *) * (nDrivers+1));
papoDrivers[nDrivers] = poDriver;
nDrivers++;
if( poDriver->pfnCreate != NULL )
poDriver->SetMetadataItem( GDAL_DCAP_CREATE, "YES" );
if( poDriver->pfnCreateCopy != NULL )
poDriver->SetMetadataItem( GDAL_DCAP_CREATECOPY, "YES" );
int iResult = nDrivers - 1;
return iResult;
}
/************************************************************************/
/* GDALRegisterDriver() */
/************************************************************************/
/**
* \brief Register a driver for use.
*
* @see GDALDriverManager::GetRegisterDriver()
*/
int CPL_STDCALL GDALRegisterDriver( GDALDriverH hDriver )
{
VALIDATE_POINTER1( hDriver, "GDALRegisterDriver", 0 );
return GetGDALDriverManager()->RegisterDriver( (GDALDriver *) hDriver );
}
/************************************************************************/
/* DeregisterDriver() */
/************************************************************************/
/**
* \brief Deregister the passed driver.
*
* If the driver isn't found no change is made.
*
* The C analog is GDALDeregisterDriver().
*
* @param poDriver the driver to deregister.
*/<|fim▁hole|>void GDALDriverManager::DeregisterDriver( GDALDriver * poDriver )
{
int i;
CPLMutexHolderD( &hDMMutex );
for( i = 0; i < nDrivers; i++ )
{
if( papoDrivers[i] == poDriver )
break;
}
if( i == nDrivers )
return;
while( i < nDrivers-1 )
{
papoDrivers[i] = papoDrivers[i+1];
i++;
}
nDrivers--;
}
/************************************************************************/
/* GDALDeregisterDriver() */
/************************************************************************/
/**
* \brief Deregister the passed driver.
*
* @see GDALDriverManager::GetDeregisterDriver()
*/
void CPL_STDCALL GDALDeregisterDriver( GDALDriverH hDriver )
{
VALIDATE_POINTER0( hDriver, "GDALDeregisterDriver" );
GetGDALDriverManager()->DeregisterDriver( (GDALDriver *) hDriver );
}
/************************************************************************/
/* GetDriverByName() */
/************************************************************************/
/**
* \brief Fetch a driver based on the short name.
*
* The C analog is the GDALGetDriverByName() function.
*
* @param pszName the short name, such as GTiff, being searched for.
*
* @return the identified driver, or NULL if no match is found.
*/
GDALDriver * GDALDriverManager::GetDriverByName( const char * pszName )
{
int i;
CPLMutexHolderD( &hDMMutex );
for( i = 0; i < nDrivers; i++ )
{
if( EQUAL(papoDrivers[i]->GetDescription(), pszName) )
return papoDrivers[i];
}
return NULL;
}
/************************************************************************/
/* GDALGetDriverByName() */
/************************************************************************/
/**
* \brief Fetch a driver based on the short name.
*
* @see GDALDriverManager::GetDriverByName()
*/
GDALDriverH CPL_STDCALL GDALGetDriverByName( const char * pszName )
{
VALIDATE_POINTER1( pszName, "GDALGetDriverByName", NULL );
return( GetGDALDriverManager()->GetDriverByName( pszName ) );
}
/************************************************************************/
/* GetHome() */
/************************************************************************/
const char *GDALDriverManager::GetHome()
{
return pszHome;
}
/************************************************************************/
/* SetHome() */
/************************************************************************/
void GDALDriverManager::SetHome( const char * pszNewHome )
{
CPLMutexHolderD( &hDMMutex );
CPLFree( pszHome );
pszHome = CPLStrdup(pszNewHome);
}
/************************************************************************/
/* AutoSkipDrivers() */
/************************************************************************/
/**
* \brief This method unload undesirable drivers.
*
* All drivers specified in the space delimited list in the GDAL_SKIP
* environment variable) will be deregistered and destroyed. This method
* should normally be called after registration of standard drivers to allow
* the user a way of unloading undesired drivers. The GDALAllRegister()
* function already invokes AutoSkipDrivers() at the end, so if that functions
* is called, it should not be necessary to call this method from application
* code.
*/
void GDALDriverManager::AutoSkipDrivers()
{
if( CPLGetConfigOption( "GDAL_SKIP", NULL ) == NULL )
return;
char **papszList = CSLTokenizeString( CPLGetConfigOption("GDAL_SKIP","") );
for( int i = 0; i < CSLCount(papszList); i++ )
{
GDALDriver *poDriver = GetDriverByName( papszList[i] );
if( poDriver == NULL )
CPLError( CE_Warning, CPLE_AppDefined,
"Unable to find driver %s to unload from GDAL_SKIP environment variable.",
papszList[i] );
else
{
CPLDebug( "GDAL", "AutoSkipDriver(%s)", papszList[i] );
DeregisterDriver( poDriver );
delete poDriver;
}
}
CSLDestroy( papszList );
}
/************************************************************************/
/* AutoLoadDrivers() */
/************************************************************************/
/**
* \brief Auto-load GDAL drivers from shared libraries.
*
* This function will automatically load drivers from shared libraries. It
* searches the "driver path" for .so (or .dll) files that start with the
* prefix "gdal_X.so". It then tries to load them and then tries to call a
* function within them called GDALRegister_X() where the 'X' is the same as
* the remainder of the shared library basename ('X' is case sensitive), or
* failing that to call GDALRegisterMe().
*
* There are a few rules for the driver path. If the GDAL_DRIVER_PATH
* environment variable it set, it is taken to be a list of directories to
* search separated by colons on UNIX, or semi-colons on Windows. Otherwise
* the /usr/local/lib/gdalplugins directory, and (if known) the
* lib/gdalplugins subdirectory of the gdal home directory are searched on
* UNIX and $(BINDIR)\gdalplugins on Windows.
*
* Auto loading can be completely disabled by setting the GDAL_DRIVER_PATH
* config option to "disable".
*/
void GDALDriverManager::AutoLoadDrivers()
{
char **papszSearchPath = NULL;
const char *pszGDAL_DRIVER_PATH =
CPLGetConfigOption( "GDAL_DRIVER_PATH", NULL );
/* -------------------------------------------------------------------- */
/* Allow applications to completely disable this search by */
/* setting the driver path to the special string "disable". */
/* -------------------------------------------------------------------- */
if( pszGDAL_DRIVER_PATH != NULL && EQUAL(pszGDAL_DRIVER_PATH,"disable"))
{
CPLDebug( "GDAL", "GDALDriverManager::AutoLoadDrivers() disabled." );
return;
}
/* -------------------------------------------------------------------- */
/* Where should we look for stuff? */
/* -------------------------------------------------------------------- */
if( pszGDAL_DRIVER_PATH != NULL )
{
#ifdef WIN32
papszSearchPath =
CSLTokenizeStringComplex( pszGDAL_DRIVER_PATH, ";", TRUE, FALSE );
#else
papszSearchPath =
CSLTokenizeStringComplex( pszGDAL_DRIVER_PATH, ":", TRUE, FALSE );
#endif
}
else
{
#ifdef GDAL_PREFIX
papszSearchPath = CSLAddString( papszSearchPath,
#ifdef MACOSX_FRAMEWORK
GDAL_PREFIX "/PlugIns");
#else
GDAL_PREFIX "/lib/gdalplugins" );
#endif
#else
char szExecPath[1024];
if( CPLGetExecPath( szExecPath, sizeof(szExecPath) ) )
{
char szPluginDir[sizeof(szExecPath)+50];
strcpy( szPluginDir, CPLGetDirname( szExecPath ) );
strcat( szPluginDir, "\\gdalplugins" );
papszSearchPath = CSLAddString( papszSearchPath, szPluginDir );
}
else
{
papszSearchPath = CSLAddString( papszSearchPath,
"/usr/local/lib/gdalplugins" );
}
#endif
#ifdef MACOSX_FRAMEWORK
#define num2str(x) str(x)
#define str(x) #x
papszSearchPath = CSLAddString( papszSearchPath,
"/Library/Application Support/GDAL/"
num2str(GDAL_VERSION_MAJOR) "."
num2str(GDAL_VERSION_MINOR) "/PlugIns" );
#endif
if( strlen(GetHome()) > 0 )
{
papszSearchPath = CSLAddString( papszSearchPath,
CPLFormFilename( GetHome(),
#ifdef MACOSX_FRAMEWORK
"/Library/Application Support/GDAL/"
num2str(GDAL_VERSION_MAJOR) "."
num2str(GDAL_VERSION_MINOR) "/PlugIns", NULL ) );
#else
"lib/gdalplugins", NULL ) );
#endif
}
}
/* -------------------------------------------------------------------- */
/* Format the ABI version specific subdirectory to look in. */
/* -------------------------------------------------------------------- */
CPLString osABIVersion;
osABIVersion.Printf( "%d.%d", GDAL_VERSION_MAJOR, GDAL_VERSION_MINOR );
/* -------------------------------------------------------------------- */
/* Scan each directory looking for files starting with gdal_ */
/* -------------------------------------------------------------------- */
for( int iDir = 0; iDir < CSLCount(papszSearchPath); iDir++ )
{
char **papszFiles = NULL;
VSIStatBufL sStatBuf;
CPLString osABISpecificDir =
CPLFormFilename( papszSearchPath[iDir], osABIVersion, NULL );
if( VSIStatL( osABISpecificDir, &sStatBuf ) != 0 )
osABISpecificDir = papszSearchPath[iDir];
papszFiles = CPLReadDir( osABISpecificDir );
for( int iFile = 0; iFile < CSLCount(papszFiles); iFile++ )
{
char *pszFuncName;
const char *pszFilename;
const char *pszExtension = CPLGetExtension( papszFiles[iFile] );
void *pRegister;
if( !EQUALN(papszFiles[iFile],"gdal_",5) )
continue;
if( !EQUAL(pszExtension,"dll")
&& !EQUAL(pszExtension,"so")
&& !EQUAL(pszExtension,"dylib") )
continue;
pszFuncName = (char *) CPLCalloc(strlen(papszFiles[iFile])+20,1);
sprintf( pszFuncName, "GDALRegister_%s",
CPLGetBasename(papszFiles[iFile]) + 5 );
pszFilename =
CPLFormFilename( osABISpecificDir,
papszFiles[iFile], NULL );
CPLErrorReset();
CPLPushErrorHandler(CPLQuietErrorHandler);
pRegister = CPLGetSymbol( pszFilename, pszFuncName );
CPLPopErrorHandler();
if( pRegister == NULL )
{
CPLString osLastErrorMsg(CPLGetLastErrorMsg());
strcpy( pszFuncName, "GDALRegisterMe" );
pRegister = CPLGetSymbol( pszFilename, pszFuncName );
if( pRegister == NULL )
{
CPLError( CE_Failure, CPLE_AppDefined,
"%s", osLastErrorMsg.c_str() );
}
}
if( pRegister != NULL )
{
CPLDebug( "GDAL", "Auto register %s using %s.",
pszFilename, pszFuncName );
((void (*)()) pRegister)();
}
CPLFree( pszFuncName );
}
CSLDestroy( papszFiles );
}
CSLDestroy( papszSearchPath );
}
/************************************************************************/
/* GDALDestroyDriverManager() */
/************************************************************************/
/**
* \brief Destroy the driver manager.
*
* Incidently unloads all managed drivers.
*
* NOTE: This function is not thread safe. It should not be called while
* other threads are actively using GDAL.
*/
void CPL_STDCALL GDALDestroyDriverManager( void )
{
// THREADSAFETY: We would like to lock the mutex here, but it
// needs to be reacquired within the destructor during driver
// deregistration.
if( poDM != NULL )
delete poDM;
}<|fim▁end|> | |
<|file_name|>test_complex.py<|end_file_name|><|fim▁begin|># Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import unittest
from iptest.type_util import *
from iptest import run_test
class ComplexTest(unittest.TestCase):
def test_from_string(self):
# complex from string: negative
# - space related
l = ['1.2', '.3', '4e3', '.3e-4', "0.031"]
for x in l:
for y in l:
self.assertRaises(ValueError, complex, "%s +%sj" % (x, y))
self.assertRaises(ValueError, complex, "%s+ %sj" % (x, y))
self.assertRaises(ValueError, complex, "%s - %sj" % (x, y))
self.assertRaises(ValueError, complex, "%s- %sj" % (x, y))
self.assertRaises(ValueError, complex, "%s-\t%sj" % (x, y))
self.assertRaises(ValueError, complex, "%sj+%sj" % (x, y))
self.assertEqual(complex(" %s+%sj" % (x, y)), complex(" %s+%sj " % (x, y)))
def test_misc(self):
self.assertEqual(mycomplex(), complex())
a = mycomplex(1)
b = mycomplex(1,0)
c = complex(1)
d = complex(1,0)
for x in [a,b,c,d]:
for y in [a,b,c,d]:
self.assertEqual(x,y)
self.assertEqual(a ** 2, a)
self.assertEqual(a-complex(), a)
self.assertEqual(a+complex(), a)
self.assertEqual(complex()/a, complex())
self.assertEqual(complex()*a, complex())
self.assertEqual(complex()%a, complex())
self.assertEqual(complex() // a, complex())
self.assertEqual(complex(2), complex(2, 0))
def test_inherit(self):
class mycomplex(complex): pass
a = mycomplex(2+1j)
self.assertEqual(a.real, 2)<|fim▁hole|> self.assertEqual(a.imag, 1)
def test_repr(self):
self.assertEqual(repr(1-6j), '(1-6j)')
def test_infinite(self):
self.assertEqual(repr(1.0e340j), 'infj')
self.assertEqual(repr(-1.0e340j),'-infj')
run_test(__name__)<|fim▁end|> | |
<|file_name|>classes-simple-cross-crate.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|>use cci_class::kitties::cat;
pub fn main() {
let nyan : cat = cat(52u, 99);
let kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
}<|fim▁end|> | // xfail-fast
// aux-build:cci_class.rs
extern mod cci_class; |
<|file_name|>beerspider.py<|end_file_name|><|fim▁begin|>from scrapy.spiders import Spider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from scrapy.conf import settings
from beerindex.items import BeerindexItem
import logging
import lxml.html
from urlparse import urlparse
import re
class BeerSpider(Spider):
name = "beerspider"
beer_sites = {
'www.wbeer.com.br':
{
"start_url" : 'https://www.wbeer.com.br/browse.ep?cID=103354',
"next_link" : '.paginacao li.prox a::attr(href)',
"product_link" : '.catalogo-lista .lista .informacoes a::attr("href")',
"xpath_title" : "//span[@itemprop='name']//text()",
"xpath_price" : "//div[@class='preco-por']//text()",
"xpath_style" : "//div[@class='resumo']//span[@class='nome-tipo']//text()"
},
'www.emporioveredas.com.br' : {
"start_url" : 'http://www.emporioveredas.com.br/cervejas-importadas.html',
"next_link" : '.pager a.next::attr(href)',
"product_link" : '.products-grid a.product-image ::attr("href")',
"xpath_title" : "//h1[@itemprop='name']//text()",
"xpath_price" : "//div[@class='product-shop']//span[@itemprop='price']//text()",
"xpath_style" : "//table[@id='product-attribute-specs-table']//tr[contains(.,'Estilo')]//td[last()]//text()"
},
'www.mundodascervejas.com' : {
"start_url" : 'http://www.mundodascervejas.com/buscar?q=cerveja',
"next_link" : '.topo .pagination a[rel="next"]::attr("href")',
"product_link" : '#listagemProdutos a.produto-sobrepor::attr("href")',
"xpath_title" : "//h1[@itemprop='name']//text()",
"xpath_price" : "//div[@class='principal']//div[contains(@class,'preco-produto')]//strong[contains(@class,'preco-promocional')]//text()",
"xpath_style" : "//div[@id='descricao']//table//tr[contains(.,'Estilo')]//td[last()]//text()"
},
'www.clubeer.com.br': {
"start_url" : 'http://www.clubeer.com.br/loja',
"next_link" : '#pagination li.current + li a::attr("href")',
"product_link" : '.minhascervejas li .areaborder > a:first-child::attr("href")',
"xpath_title" : "//h1[@itemprop='name']//text()",
"xpath_price" : "//div[@id='principal']//div[contains(@class,'areaprecos')]//span[@itemprop='price']//text()",
"xpath_style" : "//div[contains(@class,'areaprodutoinfoscontent')]//ul[contains(.,'ESTILO')]//li[position()=2]//text()"
},
'www.clubedomalte.com.br': {
"start_url" : 'http://www.clubedomalte.com.br/pais',
"next_link" : '.paginacao li.pg:last-child a::attr("href")',
"product_link" : '.mainBar .spotContent > a:first-child::attr("href")',
"xpath_title" : "//h1[@itemprop='name']//text()",
"xpath_price" : "//div[contains(@class,'interna')]//div[contains(@class,'preco')]//*[@itemprop='price']//text()",
"xpath_style" : "//div[contains(@class,'areaprodutoinfoscontent')]//ul[contains(.,'ESTILO')]//li[position()=2]//text()"
}
}
def domain_from_url(self,url):
parsed = urlparse(url)
return parsed.netloc
#allowed_domains = ["www.cervejastore.com.br"]
# start_urls = ['http://www.mundodascervejas.com/buscar?q=cerveja']<|fim▁hole|>
def parse(self,response):
domain = self.domain_from_url(response.url)
for url in response.css(self.beer_sites[domain]["next_link"]).extract():
request = Request(response.urljoin(url.strip()), self.parse)
yield request
titles = response.css(self.beer_sites[domain]["product_link"]).extract()
for title in titles:
yield Request(response.urljoin(title), self.parse_product)
def parse_product(self,response):
domain = self.domain_from_url(response.url)
item = BeerindexItem()
item["name"] = response.xpath(self.beer_sites[domain]["xpath_title"]).extract_first()
item["style"] = response.xpath(self.beer_sites[domain]["xpath_style"]).extract_first()
item["link"] = response.url
item["price"] = "".join(response.xpath(self.beer_sites[domain]["xpath_price"]).extract())
item["price"] = re.sub(r"\s+", "", item["price"], flags=re.UNICODE)
item["price"] = re.sub(r"[^\d,\.+]", "", item["price"], flags=re.UNICODE)
item["price"] = re.sub(r",", ".", item["price"], flags=re.UNICODE)
yield item<|fim▁end|> | # start_urls = ["http://www.emporioveredas.com.br/cervejas-importadas.html"]
start_urls = [beer_sites[store]["start_url"] for store in beer_sites] |
<|file_name|>test_security_groups.py<|end_file_name|><|fim▁begin|><|fim▁hole|># 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.
import random
from openstack_dashboard.test.integration_tests import helpers
from openstack_dashboard.test.integration_tests.regions import messages
class TestSecuritygroup(helpers.TestCase):
SEC_GROUP_NAME = helpers.gen_random_resource_name("securitygroup")
RULE_PORT = str(random.randint(9000, 9999))
@property
def securitygroup_page(self):
return self.home_pg.\
go_to_compute_accessandsecurity_securitygroupspage()
def _create_securitygroup(self):
page = self.securitygroup_page
page.create_securitygroup(self.SEC_GROUP_NAME)
self.assertTrue(page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(page.find_message_and_dismiss(messages.ERROR))
self.assertTrue(page.is_securitygroup_present(self.SEC_GROUP_NAME))
def _delete_securitygroup(self):
page = self.securitygroup_page
page.delete_securitygroup(self.SEC_GROUP_NAME)
self.assertTrue(page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(page.find_message_and_dismiss(messages.ERROR))
self.assertFalse(page.is_securitygroup_present(self.SEC_GROUP_NAME))
def _add_rule(self):
page = self.securitygroup_page
page = page.go_to_manage_rules(self.SEC_GROUP_NAME)
page.create_rule(self.RULE_PORT)
self.assertTrue(page.find_message_and_dismiss(messages.SUCCESS))
self.assertTrue(page.is_port_present(self.RULE_PORT))
def _delete_rule_by_table_action(self):
page = self.securitygroup_page
page = page.go_to_manage_rules(self.SEC_GROUP_NAME)
page.delete_rules(self.RULE_PORT)
self.assertTrue(page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(page.find_message_and_dismiss(messages.ERROR))
self.assertFalse(page.is_port_present(self.RULE_PORT))
def _delete_rule_by_row_action(self):
page = self.securitygroup_page
page = page.go_to_manage_rules(self.SEC_GROUP_NAME)
page.delete_rule(self.RULE_PORT)
self.assertTrue(page.find_message_and_dismiss(messages.SUCCESS))
self.assertFalse(page.find_message_and_dismiss(messages.ERROR))
self.assertFalse(page.is_port_present(self.RULE_PORT))
def test_securitygroup_create_delete(self):
"""tests the security group creation and deletion functionalities:
* creates a new security group
* verifies the security group appears in the security groups table
* deletes the newly created security group
* verifies the security group does not appear in the table after
deletion
"""
self._create_securitygroup()
self._delete_securitygroup()
def test_managerules_create_delete_by_row(self):
"""tests the manage rules creation and deletion functionalities:
* create a new security group
* verifies the security group appears in the security groups table
* creates a new rule
* verifies the rule appears in the rules table
* delete the newly created rule
* verifies the rule does not appear in the table after deletion
* deletes the newly created security group
* verifies the security group does not appear in the table after
deletion
"""
self._create_securitygroup()
self._add_rule()
self._delete_rule_by_row_action()
self._delete_securitygroup()
def test_managerules_create_delete_by_table(self):
"""tests the manage rules creation and deletion functionalities:
* create a new security group
* verifies the security group appears in the security groups table
* creates a new rule
* verifies the rule appears in the rules table
* delete the newly created rule
* verifies the rule does not appear in the table after deletion
* deletes the newly created security group
* verifies the security group does not appear in the table after
deletion
"""
self._create_securitygroup()
self._add_rule()
self._delete_rule_by_table_action()
self._delete_securitygroup()<|fim▁end|> | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
<|file_name|>types.go<|end_file_name|><|fim▁begin|>package drivers
//DriverType id of type of driver
type DriverType int
const (
//FTP id of ftp driver type
FTP DriverType = iota
//SSH id of ssh driver type<|fim▁hole|> //SMB id of smb driver type
SMB
//DAV id of dav driver type
DAV
//NFS id of nfs driver type
NFS
)
var driverTypes = []string{
"ftp",
"ssh",
"smb",
"dav",
"nfs",
}
func (dt DriverType) String() string {
return driverTypes[dt]
}<|fim▁end|> | SSH |
<|file_name|>HW1_4a.cpp<|end_file_name|><|fim▁begin|>//
// HW1_4a.cpp
// Homework 1
//
// Raymond Dam
//
//
#include <iostream>
#include <fstream> //file io stuff
#include <cstring> //using strings
#include <sstream>
#include <stdlib.h> //atoi to convert string to int
#include <ctime> //for timing
using namespace std;
//***function prototypes & global variables***//
int recursion (int n, int &sum);
void fileio (string inputfile, int n);
int *a;
//********************************************//<|fim▁hole|> int n; // number of elements in the array a
int sum = 0; // we’ll use this for adding numbers
string inputfile; // holds name of the input file
//ask user how many elements there are in the array
cout << endl;
cout << "How many numbers are in your dataset?" << endl;
cout << "User Entry: ";
cin >> n;
//ask user to enter name of input file
cout << endl;
cout << "Please the name of your input file." << endl;
cout << "User Entry: ";
cin >> inputfile;
//dynamically allocate an array based on user entry to pointer, a
a = new int [n];
//call fileio function
fileio(inputfile, n);
//subtract by one so we stay within the array when we do recursion
n -= 1;
//***start the clock!!***//
clock_t start, finish;
double dur;
start = clock();
//***********************//
/*
//for loop method
sum = 0;
for (int i = 0; i < n; i ++)
{
sum += a[i];
}
*/
//call recursion function to sum up array
recursion(n, sum);
//***stop the clock!!***//
finish = clock();
dur = (double)(finish - start);
dur /= CLOCKS_PER_SEC;
cout << "Elapsed seconds: " << scientific << dur << endl;
//**********************//
cout << endl;
cout << sum << endl;
//release dynamically allocated memory
delete [] a;
return 0;
}
//recursive algorithm that sums the array
int recursion (int n, int &sum)
{
if (n == 0)
{
sum += a[n]; //a[0] is still storing a value
return sum;
}
else
{
sum += a[n];
return recursion (n-1, sum);
}
}
//reads in a file with a list of numbers and stores the dataset in the array
void fileio (string inputfile, int n)
{
ifstream filein(inputfile.c_str());
//if and else statements for input validation of the user file
if (!filein)
{
cout << endl;
cout << "Invalid file. Please check the name and location of your file and try again." << endl;
cout << endl;
cout << "----------------------------------------------------------------------------" << endl;
}
else
{
for (int i = 0; i < n; i++)
{
int temp;
//parses file for data
filein >> temp;
//store data in array
a[i] = temp;
}
}
filein.close();
}<|fim▁end|> |
int main ()
{ |
<|file_name|>log.rs<|end_file_name|><|fim▁begin|>macro_rules! log {
($tag:expr) => (println!($tag));
($tag:expr, $fmt:expr) => (println!(concat!($tag, ": ", $fmt)));
($tag:expr, $fmt:expr, $($arg:tt)*) => (println!(concat!($tag, ": ", $fmt), $($arg)*));<|fim▁hole|>
macro_rules! error {
() => (log!("[Error]: "));
($fmt:expr) => (log!("[Error]", $fmt));
($fmt:expr, $($arg:tt)*) => (log!("[Error]", $fmt, $($arg)*));
}
macro_rules! debug {
() => (log!("[Debug]: "));
($fmt:expr) => (log!("[Debug]", $fmt));
($fmt:expr, $($arg:tt)*) => (log!("[Debug]", $fmt, $($arg)*));
}<|fim▁end|> | } |
<|file_name|>secp256k1-tests.ts<|end_file_name|><|fim▁begin|>import { SignOptions, ecdsaSign, ecdsaRecover } from "secp256k1";
const opts: SignOptions = {<|fim▁hole|>};
const message = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
const prvKey = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
const ret = ecdsaSign(message, prvKey, opts);
const recovered = ecdsaRecover(ret.signature, ret.recid, message);<|fim▁end|> | data: Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]) |
<|file_name|>geepeeex.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
import gpxpy
import datetime
import time
import os
import gpxpy.gpx
import sqlite3
import pl
import re
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
filebase = os.environ["XDG_DATA_HOME"]+"/"+os.environ["APP_ID"].split('_')[0]
def create_gpx():
# Creating a new file:
# --------------------
gpx = gpxpy.gpx.GPX()
# Create first track in our GPX:
gpx_track = gpxpy.gpx.GPXTrack()
gpx.tracks.append(gpx_track)
# Create first segment in our GPX track:
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)
# Create points:
return gpx
def write_gpx(gpx,name,act_type):
# You can add routes and waypoints, too...
tzname=None
npoints=None
# polyline encoder default values
numLevels = 18;
zoomFactor = 2;
epsilon = 0.0;
forceEndpoints = True;
##print('Created GPX:', gpx.to_xml())
ts = int(time.time())
filename = "%s/%i.gpx" % (filebase,ts)
a = open(filename, 'w')
a.write(gpx.to_xml())
a.close()
gpx.simplify()
#gpx.reduce_points(1000)
trk = pl.read_gpx_trk(gpx.to_xml(),tzname,npoints,2,None)
try:
polyline=pl.print_gpx_google_polyline(trk,numLevels,zoomFactor,epsilon,forceEndpoints)
except UnboundLocalError as er:
print(er)
print("Not enough points to create a polyline")
polyline=""
#polyline="polyline"
add_run(gpx,name,act_type,filename,polyline)
def add_point(gpx,lat,lng,elev):
gpx.tracks[0].segments[0].points.append(gpxpy.gpx.GPXTrackPoint(lat, lng, elevation=elev,time=datetime.datetime.now()))
def add_run(gpx, name,act_type,filename,polyline):
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists activities
(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text,
speed text, act_type text,filename text,polyline text)""")
sql = "INSERT INTO activities VALUES (?,?,?,?,?,?,?,?)"
start_time, end_time = gpx.get_time_bounds()
l2d='{:.3f}'.format(gpx.length_2d() / 1000.)
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
print(max_speed)
#print('%sStopped distance: %sm' % stopped_distance)
maxspeed = 'Max speed: {:.2f}km/h'.format(max_speed * 60. ** 2 / 1000. if max_speed else 0)
duration = 'Duration: {:.2f}min'.format(gpx.get_duration() / 60)
print("-------------------------")
print(name)
print(start_time)
print(l2d)
print(maxspeed)
print("-------------------------")
try:
cursor.execute(sql, [None, name,start_time,l2d,duration,act_type,filename,polyline])
conn.commit()
except sqlite3.Error as er:
print(er)
conn.close()
def get_runs():
#add_run("1", "2", "3", "4")
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists activities
(id INTEGER PRIMARY KEY AUTOINCREMENT,name text, act_date text, distance text,
speed text, act_type text,filename text,polyline text)""")
ret_data=[]
sql = "SELECT * FROM activities LIMIT 30"
for i in cursor.execute(sql):
ret_data.append(dict(i))
conn.close()
return ret_data
def get_units():
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("""CREATE TABLE if not exists settings
(units text)""")
ret_data=[]
sql = "SELECT units FROM settings"
cursor.execute(sql)
data=cursor.fetchone()
if data is None:
print("NONESIES")
cursor.execute("INSERT INTO settings VALUES ('kilometers')")
conn.commit()
conn.close()
return "kilometers"
return data
def set_units(label):
os.makedirs(filebase, exist_ok=True)
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
cursor.execute("UPDATE settings SET units=? WHERE 1", (label,))
conn.commit()
conn.close()
def onetime_db_fix():
os.makedirs(filebase, exist_ok=True)
filename = "%s/%s" % (filebase,".dbfixed")
if not os.path.exists(filename):
print("Fixing db")
conn = sqlite3.connect('%s/activities.db' % filebase)
numonly = re.compile("(\d*\.\d*)")
cursor = conn.cursor()
a=get_runs()
sql="UPDATE activities SET distance=? WHERE id=?"
for i in a:
print(i["distance"])
b=numonly.search(i["distance"])
print(b.group(0))
print(b)
cursor.execute(sql, (b.group(0), i["id"]))
conn.commit()
conn.close()<|fim▁hole|> dotfile.close
else:
print("db already fixed")
def rm_run(run):
conn = sqlite3.connect('%s/activities.db' % filebase)
cursor = conn.cursor()
sql = "DELETE from activities WHERE id=?"
try:
cursor.execute(sql, [run])
conn.commit()
except sqlite3.Error as er:
print("-------------______---_____---___----____--____---___-----")
print(er)
conn.close()
def km_to_mi(km):
return km * 0.62137
def get_data():
moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
return moving_distance, moving_time<|fim▁end|> | dotfile=open(filename, "w")
dotfile.write("db fixed") |
<|file_name|>aria-allowed-attr-test.js<|end_file_name|><|fim▁begin|>/**
* @license
* Copyright 2016 Google Inc. 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.
*/
'use strict';
const Audit = require('../../../audits/accessibility/aria-allowed-attr.js');
const assert = require('assert');
/* eslint-env mocha */
describe('Accessibility: aria-allowed-attr audit', () => {
it('generates an audit output', () => {
const artifacts = {
Accessibility: {
violations: [{
id: 'aria-allowed-attr',
nodes: [],
help: 'http://example.com/'
}]
}
};
const output = Audit.audit(artifacts);
assert.equal(output.rawValue, false);
assert.equal(output.displayValue, '');
});
it('generates an audit output (single node)', () => {
const artifacts = {
Accessibility: {
violations: [{
id: 'aria-allowed-attr',
nodes: [{}],
help: 'http://example.com/'
}]
}
};
const output = Audit.audit(artifacts);
assert.equal(output.rawValue, false);
assert.equal(output.displayValue, '');
});<|fim▁hole|><|fim▁end|> | }); |
<|file_name|>search.py<|end_file_name|><|fim▁begin|>import os, re, traceback
from dirtree_node import get_file_info
from util import is_text_file
class SearchAborted(Exception):
pass
def null_filter(info):
return True
class Search(object):
def __init__(self, path, match, output, file_filter=null_filter, dir_filter=null_filter):
self.path = path
self.match = match
self.output = output
self.file_filter = file_filter
self.dir_filter = dir_filter
self.encoding = "utf-8"
self.quit = False
def _search_file(self, filepath):
if self.quit:
raise SearchAborted()
self.output.begin_file(self, filepath)
if not is_text_file(filepath):
return
with open(filepath, "r") as f:
matched_file = False
for line_num, line in enumerate(f, 1):
line = line.rstrip("\r\n")
try:
line = line.decode(self.encoding)
except UnicodeDecodeError:
line = line.decode("latin-1")
if self.match(line):
if not matched_file:
self.output.add_file(self, filepath)
matched_file = True
self.output.add_line(self, line_num, line)
if self.quit:
raise SearchAborted()
if matched_file:
self.output.end_file(self)
def _search_dir(self, dirpath):
if self.quit:
raise SearchAborted()
try:
dirlist = os.listdir(dirpath)
except OSError:
pass
else:
dirlist.sort()
for name in dirlist:
self._search(dirpath, name)
def _search(self, dirpath, name):
if self.quit:
raise SearchAborted()
try:
info = get_file_info(dirpath, name)
if info.is_file and self.file_filter(info):
self._search_file(info.path)
elif info.is_dir and self.dir_filter(info):
self._search_dir(info.path)
except OSError:
pass
def search(self):
self.quit = False
try:
self._search(*os.path.split(self.path))
except SearchAborted:
self.output.abort_find(self)
except Exception as e:
self.output.end_find(self)
if not isinstance(e, (OSError, IOError)):
print traceback.format_exc()
else:
self.output.end_find(self)
def stop(self):
self.quit = True
class SearchFileOutput(object):
def __init__(self, file):
self.file = file
self.max_line_length = 100
def add_file(self, finder, filepath):
self.file.write(filepath + "\n")
def add_line(self, finder, line_num, line):
if len(line) > self.max_line_length:
line = line[:self.max_line_length] + "..."
self.file.write(" %d: %s\n" % (line_num, line))
def begin_file(self, finder, filepath):<|fim▁hole|> def end_file(self, finder):
self.file.write("\n")
def end_find(self, finder):
pass
def make_matcher(pattern, case_sensitive=True, is_regexp=False):
if not is_regexp:
pattern = "^.*" + re.escape(pattern)
flags = re.UNICODE
if not case_sensitive:
flags |= re.IGNORECASE
return re.compile(pattern, flags).search
if __name__ == "__main__":
import sys
Search(".", make_matcher("class"), SearchFileOutput(sys.stdout)).search()<|fim▁end|> | pass
|
<|file_name|>rule.py<|end_file_name|><|fim▁begin|>import cPickle
def dump_rules(filename, rules):
with open(filename, 'w') as f:
cPickle.dump(rules, f, cPickle.HIGHEST_PROTOCOL)
def load_rules(filename):
with open(filename, 'r') as f:
rules = cPickle.load(f)
return rules
class Rule():
APPLY_ACTION = 0
CLEAR_ACTION = 1
WRITE_ACTION = 2
GOTO_TABLE = 3
INSTRUCTION = [APPLY_ACTION, CLEAR_ACTION, WRITE_ACTION, GOTO_TABLE]
SET_FIELD = 0
GROUP = 1
OUTPUT = 2
ACTION = [SET_FIELD, GROUP, OUTPUT]
EDGE_PORT = 1000
MAX_PRIORITY = 30000
def __init__(self, id, switch_id, prefix, in_port, out_port, priority=MAX_PRIORITY):
self.id = id;
self.switch_id = switch_id;
self.priority = priority
self.prefix = prefix
self.header_space, self.ip, self.match_length = self.to_header_space(prefix)
self.out_port = out_port
self.in_port = in_port
self.is_path_start = False
self.is_path_end = False
self.timeout = 0
self.path_index = None
self.inst_actions = {}
self.table_id = 0
self.group_id = None
self.modify_field = None
self.all_pair_path_index = None
self.is_incremental = False
self.is_sendback = False
self.is_deleted = False
self.is_modified_input = False
self.is_modified_output = False
def to_header_space(self, prefix):
ip = prefix.split('/')[0]
match_length = 32 if len(prefix.split('/')) < 2 else int(prefix.split('/')[1] )
hs = ''.join([bin(int(x)+256)[3:] for x in ip.split('.')])
hs = hs[:match_length]
hs += 'x'*(32-len(hs))
return hs, ip, match_length
def is_match(self, last_rule):
return self.header_space[:self.header_space.index('x')] == last_rule.get_header_sapce()[:self.header_space.index('x')]
def serialize(self):
return cPickle.dumps(self)
def get_id(self):
return self.id
def get_switch_id(self):
return self.switch_id
def set_in_port(self, in_port):
self.in_port = in_port
def get_in_port(self):
return self.in_port
def set_out_port(self, out_port):
self.out_port = out_port
def get_out_port(self):
return self.out_port
def set_inst_actions(self, inst, actions):
self.inst_actions[inst] = actions
def set_table_id(self, table_id):
self.table_id = table_id
def get_table_id(self):
return self.table_id
def set_path_index(self, index):
self.path_index = index
def get_path_index(self):
return self.path_index
def set_all_pair_path_index(self, index):
self.all_pair_path_index = index;
def set_priority(self, priority):
self.priority = priority
def get_priority(self):
return self.priority
def set_prefix(self, prefix):
self.prefix = prefix
self.header_space, self.ip, self.match_length = self.to_header_space(prefix)
def get_prefix(self):<|fim▁hole|>
def get_header_space(self):
return self.header_space
def get_all_pair_path_index(self):
return self.all_pair_path_index;
def __str__(self):
string = 'Rule ID: ' + str(self.id) + ', ' + "Switch ID: " + str(self.switch_id) + ', ' + \
'Priority: ' + str(self.priority) + ', ' + 'Prefix: ' + self.prefix + ', ' + 'HeaderSpace: ' + self.header_space + ', ' + \
'Inport: ' + str(self.in_port) + ', ' + 'Outport: ' + str(self.out_port) + ', ' + 'Inst_actions: ' + str(self.inst_actions)
return string
if __name__ == '__main__':
pass<|fim▁end|> | return self.prefix |
<|file_name|>spotify.js<|end_file_name|><|fim▁begin|>var Plugin = require('./baseplugin'),
request = require('request-promise');
class Spotify extends Plugin {
init() {
this.httpRegex = /(?:https?:\/\/)?open\.spotify\.com\/(album|track|user\/[^\/]+\/playlist)\/([a-zA-Z0-9]+)/;
this.uriRegex = /^spotify:(album|track|user:[^:]+:playlist):([a-zA-Z0-9]+)$/;
}
canHandle(url) {
return this.httpRegex.test(url) || this.uriRegex.test(url);
}
run(url) {<|fim▁hole|> var options = {
url: `https://embed.spotify.com/oembed/?url=${url}`,
headers: {'User-Agent': 'request'}
};
return request.get(options)
.then(body => JSON.parse(body).html)
.then(html => ({ type: 'spotify', html: html }));
}
}
module.exports = Spotify;<|fim▁end|> | |
<|file_name|>doGrid.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from osgeo import ogr
from ui_widgetGrid import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
import GdalTools_utils as Utils
class GdalToolsDialog(QWidget, Ui_Widget, BasePluginWidget):
def __init__(self, iface):
QWidget.__init__(self)
self.iface = iface
self.algorithm = ('invdist', 'average', 'nearest', 'datametrics')
self.datametrics = ('minimum', 'maximum', 'range')
self.setupUi(self)
BasePluginWidget.__init__(self, self.iface, "gdal_grid")
# set the default QSpinBoxes value
self.invdistPowerSpin.setValue(2.0)
self.outputFormat = Utils.fillRasterOutputFormat()
self.lastEncoding = Utils.getLastUsedEncoding()
self.setParamsStatus(
[
(self.inputLayerCombo, [SIGNAL("currentIndexChanged(int)"), SIGNAL("editTextChanged(const QString &)")] ),
(self.outputFileEdit, SIGNAL("textChanged(const QString &)")),
(self.zfieldCombo, SIGNAL("currentIndexChanged(int)"), self.zfieldCheck),
(self.algorithmCombo, SIGNAL("currentIndexChanged(int)"), self.algorithmCheck),
(self.stackedWidget, SIGNAL("currentChanged(int)"), self.algorithmCheck),
([self.invdistPowerSpin, self.invdistSmothingSpin, self.invdistRadius1Spin, self.invdistRadius2Spin, self.invdistAngleSpin, self.invdistNoDataSpin], SIGNAL("valueChanged(double)")),
([self.invdistMaxPointsSpin, self.invdistMinPointsSpin], SIGNAL("valueChanged(int)")),
([self.averageRadius1Spin, self.averageRadius2Spin, self.averageAngleSpin, self.averageNoDataSpin], SIGNAL("valueChanged(double)")),
(self.averageMinPointsSpin, SIGNAL("valueChanged(int)")),
([self.nearestRadius1Spin, self.nearestRadius2Spin, self.nearestAngleSpin, self.nearestNoDataSpin], SIGNAL("valueChanged(double)")),
(self.datametricsCombo, SIGNAL("currentIndexChanged(int)")),
([self.datametricsRadius1Spin, self.datametricsRadius2Spin, self.datametricsAngleSpin, self.datametricsNoDataSpin], SIGNAL("valueChanged(double)")),
(self.datametricsMinPointsSpin, SIGNAL("valueChanged(int)"))
]
)
self.connect(self.selectInputFileButton, SIGNAL("clicked()"), self.fillInputFileEdit)
self.connect(self.selectOutputFileButton, SIGNAL("clicked()"), self.fillOutputFileEdit)
self.connect(self.inputLayerCombo, SIGNAL("currentIndexChanged(int)"), self.fillFieldsCombo)
# fill layers combo
self.fillInputLayerCombo()
def fillInputLayerCombo(self):
self.inputLayerCombo.clear()
( self.layers, names ) = Utils.getVectorLayers()
self.inputLayerCombo.addItems( names )
<|fim▁hole|> if index < 0:
return
self.lastEncoding = self.layers[index].dataProvider().encoding()
self.loadFields( self.getInputFileName() )
def fillInputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedVectorFilter()
inputFile, encoding = Utils.FileDialog.getOpenFileName(self, self.tr( "Select the input file for Grid" ), Utils.FileFilter.allVectorsFilter(), lastUsedFilter, True)
if inputFile.isEmpty():
return
Utils.FileFilter.setLastUsedVectorFilter(lastUsedFilter)
self.inputLayerCombo.setCurrentIndex(-1)
self.inputLayerCombo.setEditText(inputFile)
self.lastEncoding = encoding
self.loadFields( inputFile )
def fillOutputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
outputFile = Utils.FileDialog.getSaveFileName(self, self.tr( "Select the raster file to save the results to" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter )
if outputFile.isEmpty():
return
Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter)
self.outputFormat = Utils.fillRasterOutputFormat( lastUsedFilter, outputFile )
self.outputFileEdit.setText(outputFile)
def getArguments(self):
arguments = QStringList()
if self.zfieldCheck.isChecked() and self.zfieldCombo.currentIndex() >= 0:
arguments << "-zfield"
arguments << self.zfieldCombo.currentText()
if self.inputLayerCombo.currentIndex() >= 0:
arguments << "-l"
arguments << QFileInfo(self.layers[ self.inputLayerCombo.currentIndex() ].source()).baseName()
elif not self.inputLayerCombo.currentText().isEmpty():
arguments << "-l"
arguments << QFileInfo(self.inputLayerCombo.currentText()).baseName()
if self.algorithmCheck.isChecked() and self.algorithmCombo.currentIndex() >= 0:
arguments << "-a"
arguments << self.algorithmArguments(self.algorithmCombo.currentIndex())
if not self.outputFileEdit.text().isEmpty():
arguments << "-of"
arguments << self.outputFormat
arguments << self.getInputFileName()
arguments << self.outputFileEdit.text()
return arguments
def getInputFileName(self):
if self.inputLayerCombo.currentIndex() >= 0:
return self.layers[self.inputLayerCombo.currentIndex()].source()
return self.inputLayerCombo.currentText()
def getOutputFileName(self):
return self.outputFileEdit.text()
def addLayerIntoCanvas(self, fileInfo):
self.iface.addRasterLayer(fileInfo.filePath())
def algorithmArguments(self, index):
algorithm = self.algorithm[index]
arguments = QStringList()
if algorithm == "invdist":
arguments.append(algorithm)
arguments.append("power=" + str(self.invdistPowerSpin.value()))
arguments.append("smothing=" + str(self.invdistSmothingSpin.value()))
arguments.append("radius1=" + str(self.invdistRadius1Spin.value()))
arguments.append("radius2=" + str(self.invdistRadius2Spin.value()))
arguments.append("angle=" + str(self.invdistAngleSpin.value()))
arguments.append("max_points=" + str(self.invdistMaxPointsSpin.value()))
arguments.append("min_points=" + str(self.invdistMinPointsSpin.value()))
arguments.append("nodata=" + str(self.invdistNoDataSpin.value()))
elif algorithm == "average":
arguments.append(algorithm)
arguments.append("radius1=" + str(self.averageRadius1Spin.value()))
arguments.append("radius2=" + str(self.averageRadius2Spin.value()))
arguments.append("angle=" + str(self.averageAngleSpin.value()))
arguments.append("min_points=" + str(self.averageMinPointsSpin.value()))
arguments.append("nodata=" + str(self.averageNoDataSpin.value()))
elif algorithm == "nearest":
arguments.append(algorithm)
arguments.append("radius1=" + str(self.nearestRadius1Spin.value()))
arguments.append("radius2=" + str(self.nearestRadius2Spin.value()))
arguments.append("angle=" + str(self.nearestAngleSpin.value()))
arguments.append("nodata=" + str(self.nearestNoDataSpin.value()))
else:
arguments.append(self.datametrics[self.datametricsCombo.currentIndex()])
arguments.append("radius1=" + str(self.datametricsRadius1Spin.value()))
arguments.append("radius2=" + str(self.datametricsRadius2Spin.value()))
arguments.append("angle=" + str(self.datametricsAngleSpin.value()))
arguments.append("min_points=" + str(self.datametricsMinPointsSpin.value()))
arguments.append("nodata=" + str(self.datametricsNoDataSpin.value()))
return arguments.join(":")
def loadFields(self, vectorFile = QString()):
self.zfieldCombo.clear()
if vectorFile.isEmpty():
return
try:
(fields, names) = Utils.getVectorFields(vectorFile)
except Exception, e:
QErrorMessage(self).showMessage( str(e) )
self.inputLayerCombo.clearEditText()
self.inputLayerCombo.setCurrentIndex(-1)
return
ncodec = QTextCodec.codecForName(self.lastEncoding)
for name in names:
self.zfieldCombo.addItem( ncodec.toUnicode(name) )<|fim▁end|> | def fillFieldsCombo(self):
index = self.inputLayerCombo.currentIndex() |
<|file_name|>pst05.cpp<|end_file_name|><|fim▁begin|><|fim▁hole|>PST05::PST05(QSettings *settings)
{
this->settings = settings;
qDebug() << "Reading up the device's serial id...";
QFile procInfo("/proc/cpuinfo");
if (!procInfo.open(QFile::ReadOnly))
{
qDebug() << "Failed to read \"/proc/cpuinfo\"";
exit(2);
}
mDeviceId = DEFAULT_DEVICE_ID;
foreach (QByteArray line, procInfo.readAll().split('\n')) {
QList<QByteArray> pair = line.split(':');
if (pair[0].trimmed() == "Serial")
{
mDeviceId = pair[1].trimmed();
}
}
mDeviceId = "raspberry";
qDebug() << "Device ID is: " << mDeviceId;
procInfo.close();
QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
foreach (const QSerialPortInfo &info, ports) {
qDebug() << info.portName();
qDebug() << info.isBusy();
serial = new QSerialPort(info);
break;
}
//serial = new QSerialPort(settings->value("portName", "ttyS0").toString());
if (serial->open(QSerialPort::ReadWrite))
{
serial->setBaudRate((QSerialPort::BaudRate) settings->value("baudRate", QSerialPort::Baud9600).toInt());
serial->setDataBits((QSerialPort::DataBits) settings->value("dataBits", QSerialPort::Data8).toInt());
serial->setFlowControl((QSerialPort::FlowControl) settings->value("flowControl", QSerialPort::NoFlowControl).toInt());
serial->setParity((QSerialPort::Parity) settings->value("parity", QSerialPort::NoParity).toInt());
serial->setStopBits((QSerialPort::StopBits) settings->value("stopBits", QSerialPort::OneStop).toInt());
qDebug() << serial->baudRate();
qDebug() << serial->dataBits();
qDebug() << serial->flowControl();
qDebug() << serial->parity();
qDebug() << serial->stopBits();
}
}
PST05::~PST05()
{
if (serial)
{
if (serial->isOpen()) serial->close();
serial->deleteLater();
}
}
void PST05::writeTestDataToSerial(uint cbytes)
{
QByteArray data;
qsrand(QTime::currentTime().msec());
for (uint i = 0; i < cbytes; i++)
{
data.append((char) (qrand() % 256));
}
data[2] = 49; // data bytes count...
serial->write(data);
serial->flush();
}
// Possibly make it asynchronously some day
PST05Data PST05::queryDevice()
{
char res;
char queryAddress[] = {(char) 0xFA};
char queryCommand[] = {(char) 0x82};
if (!serial->isOpen()) return PST05Data(true);
// address
serial->write(queryAddress, 1);
serial->flush();
if (!serial->waitForReadyRead(30000))
{
// writeTestDataToSerial(54);
goto rs232read;
}
serial->read(&res, 1);
if (res != queryAddress[0])
{
// writeTestDataToSerial(54);
goto rs232read;
}
// command
serial->write(queryCommand, 1);
serial->flush();
if (!serial->waitForReadyRead(30000))
{
// writeTestDataToSerial(54);
goto rs232read;
}
serial->read(&res, 1);
if (res != queryCommand[0])
{
// writeTestDataToSerial(54);
goto rs232read;
}
rs232read:
QByteArray data;
uint bytesRemaining = 5, i = 0;
// Wait 2 seconds for data at MOST
while (serial->waitForReadyRead(60000))
{
QByteArray read = serial->read(bytesRemaining);
data += read;
bytesRemaining -= read.size();
if (i++ == 0 && data.size() > 3)
{
// The address or the command returned is wrong (first 2 bits are 0)
if (data[0] != (queryAddress[0] & (char) 63)) break;
if (data[1] != (queryCommand[0] & (char) 63)) break;
// The third byte contains the number of bytes that will be available after the first 4
bytesRemaining += data[2];
}
qDebug() << QString::number(bytesRemaining);
if (!bytesRemaining) break;
}
// The data wasn't received OR incorrect checksum (not added)
if (bytesRemaining > 0 || !checkCRC(data))
{
return PST05Data(true);
}
// We got it all
data = data.right(data.size() - 5);
PST05Data pstdata(false);
pstdata.U1 = (((float)data[0] * 128 + (float)data[1]) / 10 ) * 220 / 57.7;
pstdata.U2 = (((float)data[2] * 128 + (float)data[3]) / 10 ) * 220 / 57.7 ;
pstdata.U3 = (((float)data[4] * 128 + (float)data[5]) / 10 ) * 220 / 57.7;
pstdata.I1 = ((float)data[6] * 128 + (float)data[7]) / 1000;
pstdata.I2 = ((float)data[8] * 128 + (float)data[9]) / 1000;
pstdata.I3 = ((float)data[10] * 128 + (float)data[11]) / 1000;
pstdata.P = ((float)data[12] * 128 + (float)data[13]) / 10;
if (pstdata.P > 64*128) pstdata.P -= 128*128;
pstdata.Q = ((float)data[14] * 128 + (float)data[15]) / 10;
if (pstdata.Q > 64*128) pstdata.Q -= 128*128;
pstdata.F = ((float)data[16] * 128 + (float)data[17]) / 100;
return pstdata;
}
QByteArray PST05::deviceId()
{
return mDeviceId;
}
bool PST05::checkCRC(const QByteArray &data) {
unsigned short calcCRC = 0;
for (int i = 5; i < data.length(); i++)
{
calcCRC += data[i];
}
QByteArray crc((const char *) calcCRC, 2);
return data.mid(3, 2) == crc;
}<|fim▁end|> | #include "pst05.h"
|
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|>#
# Copyright 2018 Analytics Zoo Authors.
#
# 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.
#
import pytest
import numpy as np
from test.zoo.pipeline.utils.test_utils import ZooTestCase
from zoo.chronos.detector.anomaly.ae_detector import AEDetector
class TestAEDetector(ZooTestCase):
def setup_method(self, method):
pass
def teardown_method(self, method):
pass
def create_data(self):
cycles = 10
time = np.arange(0, cycles * np.pi, 0.01)
data = np.sin(time)
data[600:800] = 10
return data
def test_ae_fit_score_rolled_keras(self):
y = self.create_data()
ad = AEDetector(roll_len=314)
ad.fit(y)
anomaly_scores = ad.score()
assert len(anomaly_scores) == len(y)
anomaly_indexes = ad.anomaly_indexes()
assert len(anomaly_indexes) == int(ad.ratio * len(y))
def test_ae_fit_score_rolled_pytorch(self):
y = self.create_data()
ad = AEDetector(roll_len=314, backend="torch")
ad.fit(y)
anomaly_scores = ad.score()
assert len(anomaly_scores) == len(y)
anomaly_indexes = ad.anomaly_indexes()
assert len(anomaly_indexes) == int(ad.ratio * len(y))
def test_ae_fit_score_unrolled(self):
y = self.create_data()
ad = AEDetector(roll_len=0)
ad.fit(y)
anomaly_scores = ad.score()
assert len(anomaly_scores) == len(y)
anomaly_indexes = ad.anomaly_indexes()
assert len(anomaly_indexes) == int(ad.ratio * len(y))
def test_corner_cases(self):
y = self.create_data()
ad = AEDetector(roll_len=314, backend="dummy")<|fim▁hole|> with pytest.raises(RuntimeError):
ad.score()
y = np.array([1])
with pytest.raises(ValueError):
ad.fit(y)
y = self.create_data()
y = y.reshape(2, -1)
with pytest.raises(ValueError):
ad.fit(y)<|fim▁end|> | with pytest.raises(ValueError):
ad.fit(y)
ad = AEDetector(roll_len=314) |
<|file_name|>netplay.cpp<|end_file_name|><|fim▁begin|>/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2002 Xodnizel
*
* This program 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 2 of the License, or
* (at your option) any later version.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "types.h"
#include "file.h"
#include "utils/endian.h"
#include "netplay.h"
#include "fceu.h"
#include "state.h"
#include "cheat.h"
#include "input.h"
#include "driver.h"
#include "utils/memory.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
//#include <unistd.h> //mbg merge 7/17/06 removed
#include <zlib.h>
int FCEUnetplay=0;
static uint8 netjoy[4]; // Controller cache.
static int numlocal;
static int netdivisor;
static int netdcount;
//NetError should only be called after a FCEUD_*Data function returned 0, in the function
//that called FCEUD_*Data, to prevent it from being called twice.
static void NetError(void)
{
FCEU_DispMessage("Network error/connection lost!",0);
FCEUD_NetworkClose();
}
void FCEUI_NetplayStop(void)
{
if(FCEUnetplay)
{
FCEUnetplay = 0;
FCEU_FlushGameCheats(0,1); //Don't save netplay cheats.
FCEU_LoadGameCheats(0); //Reload our original cheats.
}
else puts("Check your code!");
}
int FCEUI_NetplayStart(int nlocal, int divisor)
{
FCEU_FlushGameCheats(0, 0); //Save our pre-netplay cheats.
FCEU_LoadGameCheats(0); // Load them again, for pre-multiplayer action.
FCEUnetplay = 1;
memset(netjoy,0,sizeof(netjoy));
numlocal = nlocal;
netdivisor = divisor;
netdcount = 0;
return(1);
}
int FCEUNET_SendCommand(uint8 cmd, uint32 len)
{
//mbg merge 7/17/06 changed to alloca
//uint8 buf[numlocal + 1 + 4];
uint8 *buf = (uint8*)alloca(numlocal+1+4);
buf[0] = 0xFF;
FCEU_en32lsb(&buf[numlocal], len);
buf[numlocal + 4] = cmd;
if(!FCEUD_SendData(buf,numlocal + 1 + 4))
{
NetError();
return(0);
}
return(1);
}
void FCEUI_NetplayText(uint8 *text)
{
uint32 len;
len = strlen((char*)text); //mbg merge 7/17/06 added cast
if(!FCEUNET_SendCommand(FCEUNPCMD_TEXT,len)) return;
if(!FCEUD_SendData(text,len))
NetError();
}
int FCEUNET_SendFile(uint8 cmd, char *fn)
{
uint32 len;
uLongf clen;
char *buf, *cbuf;
FILE *fp;
struct stat sb;
if(!(fp=FCEUD_UTF8fopen(fn,"rb"))) return(0);
fstat(fileno(fp),&sb);
len = sb.st_size;
buf = (char*)FCEU_dmalloc(len); //mbg merge 7/17/06 added cast
fread(buf, 1, len, fp);
fclose(fp);
cbuf = (char*)FCEU_dmalloc(4 + len + len / 1000 + 12); //mbg merge 7/17/06 added cast
FCEU_en32lsb((uint8*)cbuf, len); //mbg merge 7/17/06 added cast
compress2((uint8*)cbuf + 4, &clen, (uint8*)buf, len, 7); //mbg merge 7/17/06 added casts
free(buf);
//printf("Sending file: %s, %d, %d\n",fn,len,clen);
len = clen + 4;
if(!FCEUNET_SendCommand(cmd,len))
{
free(cbuf);
return(0);
}
if(!FCEUD_SendData(cbuf, len))
{
NetError();
free(cbuf);
return(0);
}
free(cbuf);
return(1);
<|fim▁hole|>
static FILE *FetchFile(uint32 remlen)
{
uint32 clen = remlen;
char *cbuf;
uLongf len;
char *buf;
FILE *fp;
if(clen > 500000) // Sanity check
{
NetError();
return(0);
}
//printf("Receiving file: %d...\n",clen);
if((fp = tmpfile()))
{
cbuf = (char *)FCEU_dmalloc(clen); //mbg merge 7/17/06 added cast
if(!FCEUD_RecvData(cbuf, clen))
{
NetError();
fclose(fp);
free(cbuf);
return(0);
}
len = FCEU_de32lsb((uint8*)cbuf); //mbg merge 7/17/06 added cast
if(len > 500000) // Another sanity check
{
NetError();
fclose(fp);
free(cbuf);
return(0);
}
buf = (char *)FCEU_dmalloc(len); //mbg merge 7/17/06 added cast
uncompress((uint8*)buf, &len, (uint8*)cbuf + 4, clen - 4); //mbg merge 7/17/06 added casts
fwrite(buf, 1, len, fp);
free(buf);
fseek(fp, 0, SEEK_SET);
return(fp);
}
return(0);
}
void NetplayUpdate(uint8 *joyp)
{
static uint8 buf[5]; /* 4 play states, + command/extra byte */
static uint8 joypb[4];
memcpy(joypb,joyp,4);
/* This shouldn't happen, but just in case. 0xFF is used as a command escape elsewhere. */
if(joypb[0] == 0xFF)
joypb[0] = 0xF;
if(!netdcount)
if(!FCEUD_SendData(joypb,numlocal))
{
NetError();
return;
}
if(!netdcount)
{
do
{
if(!FCEUD_RecvData(buf,5))
{
NetError();
return;
}
switch(buf[4])
{
default: FCEU_DoSimpleCommand(buf[4]);break;
case FCEUNPCMD_TEXT:
{
uint8 *tbuf;
uint32 len = FCEU_de32lsb(buf);
if(len > 100000) // Insanity check!
{
NetError();
return;
}
tbuf = (uint8*)malloc(len + 1); //mbg merge 7/17/06 added cast
tbuf[len] = 0;
if(!FCEUD_RecvData(tbuf, len))
{
NetError();
free(tbuf);
return;
}
FCEUD_NetplayText(tbuf);
free(tbuf);
}
break;
case FCEUNPCMD_SAVESTATE:
{
//mbg todo netplay
//char *fn;
//FILE *fp;
////Send the cheats first, then the save state, since
////there might be a frame or two in between the two sendfile
////commands on the server side.
//fn = strdup(FCEU_MakeFName(FCEUMKF_CHEAT,0,0).c_str());
////why??????
////if(!
// FCEUNET_SendFile(FCEUNPCMD_LOADCHEATS,fn);
//// {
//// free(fn);
//// return;
//// }
//free(fn);
//if(!FCEUnetplay) return;
//fn = strdup(FCEU_MakeFName(FCEUMKF_NPTEMP,0,0).c_str());
//fp = fopen(fn, "wb");
//if(FCEUSS_SaveFP(fp,Z_BEST_COMPRESSION))
//{
// fclose(fp);
// if(!FCEUNET_SendFile(FCEUNPCMD_LOADSTATE, fn))
// {
// unlink(fn);
// free(fn);
// return;
// }
// unlink(fn);
// free(fn);
//}
//else
//{
// fclose(fp);
// FCEUD_PrintError("File error. (K)ill, (M)aim, (D)estroy? Now!");
// unlink(fn);
// free(fn);
// return;
//}
}
break;
case FCEUNPCMD_LOADCHEATS:
{
FILE *fp = FetchFile(FCEU_de32lsb(buf));
if(!fp) return;
FCEU_FlushGameCheats(0,1);
FCEU_LoadGameCheats(fp);
}
break;
//mbg 6/16/08 - netplay doesnt work right now anyway
/*case FCEUNPCMD_LOADSTATE:
{
FILE *fp = FetchFile(FCEU_de32lsb(buf));
if(!fp) return;
if(FCEUSS_LoadFP(fp,SSLOADPARAM_BACKUP))
{
fclose(fp);
FCEU_DispMessage("Remote state loaded.",0);
} else FCEUD_PrintError("File error. (K)ill, (M)aim, (D)estroy?");
}
break;*/
}
} while(buf[4]);
netdcount=(netdcount+1)%netdivisor;
memcpy(netjoy,buf,4);
*(uint32 *)joyp=*(uint32 *)netjoy;
}
}<|fim▁end|> | }
|
<|file_name|>CustomJakanHelper.java<|end_file_name|><|fim▁begin|>/*
** 2013 October 27
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
package common.zeroquest.entity.helper;
import java.util.Random;
import common.zeroquest.entity.EntityJakanPrime;
import net.minecraft.entity.DataWatcher;
import net.minecraft.nbt.NBTTagCompound;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class CustomJakanHelper {
protected final EntityJakanPrime dragon;
protected final DataWatcher dataWatcher;
protected final Random rand;
public CustomJakanHelper(EntityJakanPrime dragon) {
this.dragon = dragon;
this.dataWatcher = dragon.getDataWatcher();
this.rand = dragon.getRNG();
}
public void writeToNBT(NBTTagCompound nbt) {}
public void readFromNBT(NBTTagCompound nbt) {}
public void applyEntityAttributes() {}
<|fim▁hole|>}<|fim▁end|> | public void onLivingUpdate() {}
public void onDeathUpdate() {}
public void onDeath() {}
|
<|file_name|>453.minimum-moves-to-equal-array-elements.go<|end_file_name|><|fim▁begin|>// https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
package leetcode
func minMoves(nums []int) int {
sum, min := 0, (1<<31 - 1)
for _, num := range nums {
if min > num {
min = num
}<|fim▁hole|>}<|fim▁end|> | sum += num
}
return sum - len(nums)*min |
<|file_name|>tree.rs<|end_file_name|><|fim▁begin|>#![cfg_attr(feature = "unstable", feature(test))]
extern crate rand;
extern crate rdxsort;
#[cfg(feature = "unstable")]
mod unstable {
extern crate test;
use self::test::Bencher;
use rand::{Rng, XorShiftRng};
use rdxsort::*;
use std::collections::BTreeSet;
use std::collections::HashSet;
static N_MEDIUM: usize = 10_000;
fn bench_generic<F>(b: &mut Bencher, f: F) where F: Fn(Vec<u32>) {
let mut set = HashSet::new();
let mut rng = XorShiftRng::new_unseeded();
while set.len() < N_MEDIUM {
set.insert(rng.gen::<u32>());
}
let mut vec: Vec<u32> = set.into_iter().collect();
rng.shuffle(&mut vec[..]);
let _ = b.iter(|| {
let vec = vec.clone();
f(vec);
});
}
#[bench]
fn bench_set_rdx(b: &mut Bencher) {
bench_generic(b, |vec| {
let mut set = RdxTree::new();
for x in vec {
set.insert(x);
}
});
}
<|fim▁hole|> for x in vec {
set.insert(x);
}
});
}
}<|fim▁end|> | #[bench]
fn bench_set_std(b: &mut Bencher) {
bench_generic(b, |vec| {
let mut set = BTreeSet::new(); |
<|file_name|>buffer.rs<|end_file_name|><|fim▁begin|>use std::ptr;
use std::io::Read;
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buffer. Any
/// method that modifies the buffer directory or provides the caller with bytes that can be modifies
/// results in those bytes being marked as used by the buffer.
pub trait FixedBuffer {
/// Input a vector of bytes. If the buffer becomes full, process it with the provided
/// function and then clear the buffer.
fn input<F: FnMut(&[u8])>(&mut self, input: &[u8], func: F);
/// Reset the buffer.
fn reset(&mut self);
/// Zero the buffer up until the specified index. The buffer position currently must not be
/// greater than that index.
fn zero_until(&mut self, idx: usize);
/// Get a slice of the buffer of the specified size. There must be at least that many bytes
/// remaining in the buffer.
fn next(&mut self, len: usize) -> &mut [u8];
/// Get the current buffer. The buffer must already be full. This clears the buffer as well.
fn full_buffer(&mut self) -> &[u8];
/// Get the current buffer.
fn current_buffer(&self) -> &[u8];
/// Get the current position of the buffer.
fn position(&self) -> usize;
/// Get the number of bytes remaining in the buffer until it is full.
fn remaining(&self) -> usize;
/// Get the size of the buffer
fn size() -> usize;
}<|fim▁hole|>
macro_rules! impl_fixed_buffer( ($name:ident, $size:expr) => (
pub struct $name {
buffer: [u8; $size],
position: usize,
}
impl $name {
/// Create a new buffer
pub fn new() -> Self {
$name {
buffer: [0u8; $size],
position: 0
}
}
}
impl FixedBuffer for $name {
fn input<F: FnMut(&[u8])>(&mut self, mut input: &[u8], mut func: F) {
while let Ok(size) = input.read(&mut self.buffer[self.position..$size]) {
if (size + self.position) < $size {
self.position += size;
break
}
func(&self.buffer);
self.position = 0;
}
}
fn reset(&mut self) {
self.position = 0;
}
fn zero_until(&mut self, idx: usize) {
assert!(idx >= self.position);
zero(&mut self.buffer[self.position..idx]);
self.position = idx;
}
fn next(&mut self, len: usize) -> &mut [u8] {
self.position += len;
&mut self.buffer[self.position - len..self.position]
}
fn full_buffer(&mut self) -> &[u8] {
assert!(self.position == $size);
self.position = 0;
&self.buffer[..$size]
}
fn current_buffer(&self) -> &[u8] {
&self.buffer[..self.position]
}
fn position(&self) -> usize { self.position }
fn remaining(&self) -> usize { $size - self.position }
fn size() -> usize { $size }
}
));
/// A fixed size buffer of 64 bytes useful for cryptographic operations.
impl_fixed_buffer!(FixedBuffer64, 64);
/// A fixed size buffer of 64 bytes useful for cryptographic operations.
impl_fixed_buffer!(FixedBuffer128, 128);
/// The StandardPadding trait adds a method useful for various hash algorithms to a FixedBuffer
/// struct.
pub trait StandardPadding {
/// Add standard padding to the buffer. The buffer must not be full when this method is called
/// and is guaranteed to have exactly rem remaining bytes when it returns. If there are not at
/// least rem bytes available, the buffer will be zero padded, processed, cleared, and then
/// filled with zeros again until only rem bytes are remaining.
fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, func: F);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F: FnMut(&[u8])>(&mut self, rem: usize, mut func: F) {
let size = Self::size();
self.next(1)[0] = 0b10000000;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// Zero all bytes in dst
#[inline]
pub fn zero(dst: &mut [u8]) {
unsafe {
ptr::write_bytes(dst.as_mut_ptr(), 0, dst.len());
}
}<|fim▁end|> | |
<|file_name|>AbstractAddress.java<|end_file_name|><|fim▁begin|>/**
* Copyright 2010 CosmoCode GmbH
*
* 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.
*/
package de.cosmocode.palava.model.business;
import java.util.Locale;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.apache.commons.validator.UrlValidator;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import de.cosmocode.commons.Locales;
import de.cosmocode.commons.Patterns;
import de.cosmocode.commons.TrimMode;
/**
* Abstract base implementation of the {@link AddressBase} interface.
*
* @author Willi Schoenborn
*/
@Embeddable
@MappedSuperclass
public abstract class AbstractAddress implements AddressBase {
private static final EmailValidator EMAIL_VALIDATOR = EmailValidator.getInstance();
private static final UrlValidator URL_VALIDATOR = new UrlValidator();
private static final Set<String> INVERSE_ADDRESS_COUNTRIES = ImmutableSet.of(
Locale.US.getCountry(),
Locale.UK.getCountry(),
Locale.CANADA.getCountry(),
Locales.AUSTRALIA.getCountry(),
Locale.FRANCE.getCountry(),
Locales.NEW_ZEALAND.getCountry()
);
private String street;
@Column(name = "street_number")
private String streetNumber;
private String additional;
@Column(name = "postal_code")
private String postalCode;
private String district;
@Column(name = "city_name")
private String cityName;
private String state;
@Column(name = "country_code")
private String countryCode;
private Double latitude;
private Double longitude;
private String phone;
@Column(name = "mobile_phone")
private String mobilePhone;
private String fax;
@Column(unique = true)
private String email;
private String website;
@Transient
private final transient Location location = new InternalLocation();
@Override
public String getStreet() {
return street;
}
@Override
public void setStreet(String street) {
this.street = TrimMode.NULL.apply(street);
}
@Override
public String getStreetNumber() {
return streetNumber;
}
@Override
public void setStreetNumber(String streetNumber) {
this.streetNumber = TrimMode.NULL.apply(streetNumber);
}
@Override<|fim▁hole|> public String getLocalizedAddress() {
if (INVERSE_ADDRESS_COUNTRIES.contains(countryCode)) {
return getAddressInverse();
} else {
return getAddress();
}
}
private String getAddress() {
return String.format("%s %s", street, streetNumber).trim();
}
private String getAddressInverse() {
return String.format("%s %s", streetNumber, street).trim();
}
@Override
public String getAdditional() {
return additional;
}
@Override
public void setAdditional(String additional) {
this.additional = TrimMode.NULL.apply(additional);
}
@Override
public String getPostalCode() {
return postalCode;
}
@Override
public void setPostalCode(String postalCode) {
this.postalCode = TrimMode.NULL.apply(postalCode);
}
@Override
public String getDistrict() {
return district;
}
@Override
public void setDistrict(String district) {
this.district = TrimMode.NULL.apply(district);
}
@Override
public String getCityName() {
return cityName;
}
@Override
public void setCityName(String cityName) {
this.cityName = TrimMode.NULL.apply(cityName);
}
@Override
public String getState() {
return state;
}
@Override
public void setState(String state) {
this.state = TrimMode.NULL.apply(state);
}
@Override
public String getCountryCode() {
return countryCode == null ? null : countryCode.toUpperCase();
}
@Override
public void setCountryCode(String code) {
this.countryCode = StringUtils.upperCase(TrimMode.NULL.apply(code));
if (countryCode == null) return;
Preconditions.checkArgument(Patterns.ISO_3166_1_ALPHA_2.matcher(countryCode).matches(),
"%s does not match %s", countryCode, Patterns.ISO_3166_1_ALPHA_2.pattern()
);
}
@Override
public Location getLocation() {
return location;
}
/**
* Internal implementation of the {@link Location} interface which
* owns a reference to the enclosing class and is able to directly manipulate the
* corresponding values.
*
* @author Willi Schoenborn
*/
private final class InternalLocation extends AbstractLocation {
@Override
public Double getLatitude() {
return latitude;
}
@Override
public void setLatitude(Double latitude) {
AbstractAddress.this.latitude = latitude;
}
@Override
public Double getLongitude() {
return longitude;
}
@Override
public void setLongitude(Double longitude) {
AbstractAddress.this.longitude = longitude;
}
}
@Override
public void setLocation(Location location) {
Preconditions.checkNotNull(location, "Location");
this.latitude = location.getLatitude();
this.longitude = location.getLongitude();
}
@Override
public boolean hasLocation() {
return latitude != null && longitude != null;
}
@Override
public String getPhone() {
return phone;
}
@Override
public void setPhone(String phone) {
this.phone = TrimMode.NULL.apply(phone);
}
@Override
public String getMobilePhone() {
return mobilePhone;
}
@Override
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = TrimMode.NULL.apply(mobilePhone);
}
@Override
public String getFax() {
return fax;
}
@Override
public void setFax(String fax) {
this.fax = TrimMode.NULL.apply(fax);
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String e) {
this.email = TrimMode.NULL.apply(e);
if (email == null) return;
Preconditions.checkArgument(EMAIL_VALIDATOR.isValid(email), "%s is not a valid email", email);
}
@Override
public String getWebsite() {
return website;
}
@Override
public void setWebsite(String w) {
this.website = TrimMode.NULL.apply(w);
if (website == null) return;
Preconditions.checkArgument(URL_VALIDATOR.isValid(website), "%s is not a valid website", website);
}
}<|fim▁end|> | |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use dox::{mem, Option};
pub type c_char = i8;
pub type wchar_t = i32;
pub type off_t = i64;
pub type useconds_t = u32;
pub type blkcnt_t = i64;
pub type socklen_t = u32;
pub type sa_family_t = u8;
pub type pthread_t = ::uintptr_t;
pub type nfds_t = ::c_uint;
s! {
pub struct sockaddr {
pub sa_len: u8,
pub sa_family: sa_family_t,
pub sa_data: [::c_char; 14],
}
pub struct sockaddr_in6 {
pub sin6_len: u8,
pub sin6_family: sa_family_t,
pub sin6_port: ::in_port_t,
pub sin6_flowinfo: u32,
pub sin6_addr: ::in6_addr,
pub sin6_scope_id: u32,
}
pub struct sockaddr_un {
pub sun_len: u8,
pub sun_family: sa_family_t,
pub sun_path: [c_char; 104]
}
pub struct passwd {
pub pw_name: *mut ::c_char,
pub pw_passwd: *mut ::c_char,
pub pw_uid: ::uid_t,
pub pw_gid: ::gid_t,
pub pw_change: ::time_t,
pub pw_class: *mut ::c_char,
pub pw_gecos: *mut ::c_char,
pub pw_dir: *mut ::c_char,
pub pw_shell: *mut ::c_char,
pub pw_expire: ::time_t,
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "netbsd",
target_os = "openbsd")))]
pub pw_fields: ::c_int,
}
pub struct ifaddrs {
pub ifa_next: *mut ifaddrs,
pub ifa_name: *mut ::c_char,
pub ifa_flags: ::c_uint,
pub ifa_addr: *mut ::sockaddr,
pub ifa_netmask: *mut ::sockaddr,
pub ifa_dstaddr: *mut ::sockaddr,
pub ifa_data: *mut ::c_void
}
pub struct fd_set {
#[cfg(all(target_pointer_width = "64",
any(target_os = "freebsd", target_os = "dragonfly")))]
fds_bits: [i64; FD_SETSIZE / 64],
#[cfg(not(all(target_pointer_width = "64",
any(target_os = "freebsd", target_os = "dragonfly"))))]
fds_bits: [i32; FD_SETSIZE / 32],
}
pub struct tm {
pub tm_sec: ::c_int,
pub tm_min: ::c_int,
pub tm_hour: ::c_int,
pub tm_mday: ::c_int,
pub tm_mon: ::c_int,
pub tm_year: ::c_int,
pub tm_wday: ::c_int,
pub tm_yday: ::c_int,
pub tm_isdst: ::c_int,
pub tm_gmtoff: ::c_long,
pub tm_zone: *mut ::c_char,
}
pub struct utsname {
#[cfg(not(target_os = "dragonfly"))]
pub sysname: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub sysname: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub nodename: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub nodename: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub release: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub release: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub version: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub version: [::c_char; 32],
#[cfg(not(target_os = "dragonfly"))]
pub machine: [::c_char; 256],
#[cfg(target_os = "dragonfly")]
pub machine: [::c_char; 32],
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg_iov: *mut ::iovec,
pub msg_iovlen: ::c_int,
pub msg_control: *mut ::c_void,
pub msg_controllen: ::socklen_t,
pub msg_flags: ::c_int,
}
pub struct cmsghdr {
pub cmsg_len: ::socklen_t,
pub cmsg_level: ::c_int,
pub cmsg_type: ::c_int,
}
pub struct fsid_t {
__fsid_val: [::int32_t; 2],
}
pub struct if_nameindex {
pub if_index: ::c_uint,
pub if_name: *mut ::c_char,
}
}
pub const LC_ALL: ::c_int = 0;
pub const LC_COLLATE: ::c_int = 1;
pub const LC_CTYPE: ::c_int = 2;
pub const LC_MONETARY: ::c_int = 3;
pub const LC_NUMERIC: ::c_int = 4;
pub const LC_TIME: ::c_int = 5;
pub const LC_MESSAGES: ::c_int = 6;
pub const FIOCLEX: ::c_ulong = 0x20006601;
pub const FIONBIO: ::c_ulong = 0x8004667e;
pub const PATH_MAX: ::c_int = 1024;
pub const SA_ONSTACK: ::c_int = 0x0001;
pub const SA_SIGINFO: ::c_int = 0x0040;
pub const SA_RESTART: ::c_int = 0x0002;
pub const SA_RESETHAND: ::c_int = 0x0004;
pub const SA_NOCLDSTOP: ::c_int = 0x0008;
pub const SA_NODEFER: ::c_int = 0x0010;
pub const SA_NOCLDWAIT: ::c_int = 0x0020;
pub const SS_ONSTACK: ::c_int = 1;
pub const SS_DISABLE: ::c_int = 4;
pub const SIGCHLD: ::c_int = 20;
pub const SIGBUS: ::c_int = 10;
pub const SIGUSR1: ::c_int = 30;
pub const SIGUSR2: ::c_int = 31;
pub const SIGCONT: ::c_int = 19;
pub const SIGSTOP: ::c_int = 17;
pub const SIGTSTP: ::c_int = 18;
pub const SIGURG: ::c_int = 16;
pub const SIGIO: ::c_int = 23;
pub const SIGSYS: ::c_int = 12;
pub const SIGTTIN: ::c_int = 21;
pub const SIGTTOU: ::c_int = 22;
pub const SIGXCPU: ::c_int = 24;
pub const SIGXFSZ: ::c_int = 25;
pub const SIGVTALRM: ::c_int = 26;
pub const SIGPROF: ::c_int = 27;
pub const SIGWINCH: ::c_int = 28;
pub const SIGINFO: ::c_int = 29;
pub const SIG_SETMASK: ::c_int = 3;
pub const SIG_BLOCK: ::c_int = 0x1;
pub const SIG_UNBLOCK: ::c_int = 0x2;
pub const IP_MULTICAST_IF: ::c_int = 9;
pub const IP_MULTICAST_TTL: ::c_int = 10;
pub const IP_MULTICAST_LOOP: ::c_int = 11;
pub const IPV6_MULTICAST_LOOP: ::c_int = 11;
pub const IPV6_V6ONLY: ::c_int = 27;
pub const ST_RDONLY: ::c_ulong = 1;
pub const SCM_RIGHTS: ::c_int = 0x01;
pub const NCCS: usize = 20;
pub const O_ACCMODE: ::c_int = 0x3;
pub const O_RDONLY: ::c_int = 0;
pub const O_WRONLY: ::c_int = 1;
pub const O_RDWR: ::c_int = 2;
pub const O_APPEND: ::c_int = 8;
pub const O_CREAT: ::c_int = 512;
pub const O_TRUNC: ::c_int = 1024;
pub const O_EXCL: ::c_int = 2048;
pub const O_ASYNC: ::c_int = 0x40;
pub const O_SYNC: ::c_int = 0x80;
pub const O_NONBLOCK: ::c_int = 0x4;
pub const O_NOFOLLOW: ::c_int = 0x100;
pub const O_SHLOCK: ::c_int = 0x10;
pub const O_EXLOCK: ::c_int = 0x20;
pub const O_FSYNC: ::c_int = O_SYNC;
pub const O_NDELAY: ::c_int = O_NONBLOCK;
pub const F_GETOWN: ::c_int = 5;
pub const F_SETOWN: ::c_int = 6;
pub const MNT_FORCE: ::c_int = 0x80000;
pub const Q_SYNC: ::c_int = 0x600;
pub const Q_QUOTAON: ::c_int = 0x100;
pub const Q_QUOTAOFF: ::c_int = 0x200;
pub const TCIOFF: ::c_int = 3;
pub const TCION: ::c_int = 4;
pub const TCOOFF: ::c_int = 1;
pub const TCOON: ::c_int = 2;
pub const TCIFLUSH: ::c_int = 1;
pub const TCOFLUSH: ::c_int = 2;
pub const TCIOFLUSH: ::c_int = 3;
pub const TCSANOW: ::c_int = 0;
pub const TCSADRAIN: ::c_int = 1;
pub const TCSAFLUSH: ::c_int = 2;
pub const VEOF: usize = 0;
pub const VEOL: usize = 1;
pub const VEOL2: usize = 2;
pub const VERASE: usize = 3;
pub const VWERASE: usize = 4;
pub const VKILL: usize = 5;
pub const VREPRINT: usize = 6;
pub const VINTR: usize = 8;
pub const VQUIT: usize = 9;
pub const VSUSP: usize = 10;
pub const VDSUSP: usize = 11;
pub const VSTART: usize = 12;
pub const VSTOP: usize = 13;
pub const VLNEXT: usize = 14;
pub const VDISCARD: usize = 15;
pub const VMIN: usize = 16;
pub const VTIME: usize = 17;
pub const VSTATUS: usize = 18;
pub const _POSIX_VDISABLE: ::cc_t = 0xff;
pub const IGNBRK: ::tcflag_t = 0x00000001;
pub const BRKINT: ::tcflag_t = 0x00000002;
pub const IGNPAR: ::tcflag_t = 0x00000004;
pub const PARMRK: ::tcflag_t = 0x00000008;
pub const INPCK: ::tcflag_t = 0x00000010;
pub const ISTRIP: ::tcflag_t = 0x00000020;
pub const INLCR: ::tcflag_t = 0x00000040;
pub const IGNCR: ::tcflag_t = 0x00000080;
pub const ICRNL: ::tcflag_t = 0x00000100;
pub const IXON: ::tcflag_t = 0x00000200;
pub const IXOFF: ::tcflag_t = 0x00000400;
pub const IXANY: ::tcflag_t = 0x00000800;
pub const IMAXBEL: ::tcflag_t = 0x00002000;
pub const OPOST: ::tcflag_t = 0x1;
pub const ONLCR: ::tcflag_t = 0x2;
pub const OXTABS: ::tcflag_t = 0x4;
pub const ONOEOT: ::tcflag_t = 0x8;
pub const CIGNORE: ::tcflag_t = 0x00000001;
pub const CSIZE: ::tcflag_t = 0x00000300;
pub const CS5: ::tcflag_t = 0x00000000;
pub const CS6: ::tcflag_t = 0x00000100;
pub const CS7: ::tcflag_t = 0x00000200;
pub const CS8: ::tcflag_t = 0x00000300;
pub const CSTOPB: ::tcflag_t = 0x00000400;
pub const CREAD: ::tcflag_t = 0x00000800;
pub const PARENB: ::tcflag_t = 0x00001000;
pub const PARODD: ::tcflag_t = 0x00002000;
pub const HUPCL: ::tcflag_t = 0x00004000;
pub const CLOCAL: ::tcflag_t = 0x00008000;
pub const ECHOKE: ::tcflag_t = 0x00000001;
pub const ECHOE: ::tcflag_t = 0x00000002;
pub const ECHOK: ::tcflag_t = 0x00000004;
pub const ECHO: ::tcflag_t = 0x00000008;
pub const ECHONL: ::tcflag_t = 0x00000010;
pub const ECHOPRT: ::tcflag_t = 0x00000020;
pub const ECHOCTL: ::tcflag_t = 0x00000040;
pub const ISIG: ::tcflag_t = 0x00000080;
pub const ICANON: ::tcflag_t = 0x00000100;
pub const ALTWERASE: ::tcflag_t = 0x00000200;
pub const IEXTEN: ::tcflag_t = 0x00000400;
pub const EXTPROC: ::tcflag_t = 0x00000800;
pub const TOSTOP: ::tcflag_t = 0x00400000;
pub const FLUSHO: ::tcflag_t = 0x00800000;
pub const NOKERNINFO: ::tcflag_t = 0x02000000;
pub const PENDIN: ::tcflag_t = 0x20000000;
pub const NOFLSH: ::tcflag_t = 0x80000000;
pub const MDMBUF: ::tcflag_t = 0x00100000;
pub const WNOHANG: ::c_int = 0x00000001;
pub const WUNTRACED: ::c_int = 0x00000002;
pub const RTLD_NOW: ::c_int = 0x2;
pub const RTLD_NEXT: *mut ::c_void = -1isize as *mut ::c_void;
pub const RTLD_DEFAULT: *mut ::c_void = -2isize as *mut ::c_void;
pub const RTLD_SELF: *mut ::c_void = -3isize as *mut ::c_void;
pub const LOG_CRON: ::c_int = 9 << 3;
pub const LOG_AUTHPRIV: ::c_int = 10 << 3;
pub const LOG_FTP: ::c_int = 11 << 3;
pub const LOG_PERROR: ::c_int = 0x20;
pub const TCP_MAXSEG: ::c_int = 2;
pub const PIPE_BUF: usize = 512;
pub const POLLRDNORM: ::c_short = 0x040;
pub const POLLWRNORM: ::c_short = 0x004;
pub const POLLRDBAND: ::c_short = 0x080;
pub const POLLWRBAND: ::c_short = 0x100;
f! {
pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () {
let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
(*set).fds_bits[fd / bits] &= !(1 << (fd % bits));
return
}
pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool {
let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0
}
pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () {
let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8;
let fd = fd as usize;
(*set).fds_bits[fd / bits] |= 1 << (fd % bits);
return
}
pub fn FD_ZERO(set: *mut fd_set) -> () {
for slot in (*set).fds_bits.iter_mut() {
*slot = 0;
}
}
pub fn WTERMSIG(status: ::c_int) -> ::c_int {
status & 0o177
}
pub fn WIFEXITED(status: ::c_int) -> bool {
(status & 0o177) == 0
}
pub fn WEXITSTATUS(status: ::c_int) -> ::c_int {
status >> 8
}
pub fn WCOREDUMP(status: ::c_int) -> bool {
(status & 0o200) != 0
}
}
extern {
pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int;
pub fn freeifaddrs(ifa: *mut ::ifaddrs);
pub fn setgroups(ngroups: ::c_int,
ptr: *const ::gid_t) -> ::c_int;
pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int;
pub fn kqueue() -> ::c_int;
pub fn unmount(target: *const ::c_char, arg: ::c_int) -> ::c_int;
pub fn syscall(num: ::c_int, ...) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")]
pub fn getpwnam_r(name: *const ::c_char,
pwd: *mut passwd,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut passwd) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")]
pub fn getpwuid_r(uid: ::uid_t,
pwd: *mut passwd,
buf: *mut ::c_char,
buflen: ::size_t,
result: *mut *mut passwd) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__getpwent50")]
pub fn getpwent() -> *mut passwd;
pub fn setpwent();
pub fn getprogname() -> *const ::c_char;
pub fn setprogname(name: *const ::c_char);
pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int;
pub fn if_nameindex() -> *mut if_nameindex;
pub fn if_freenameindex(ptr: *mut if_nameindex);
pub fn getpeereid(socket: ::c_int,
euid: *mut ::uid_t,
egid: *mut ::gid_t) -> ::c_int;
#[cfg_attr(target_os = "macos", link_name = "glob$INODE64")]
#[cfg_attr(target_os = "netbsd", link_name = "__glob30")]
pub fn glob(pattern: *const ::c_char,
flags: ::c_int,
errfunc: Option<extern fn(epath: *const ::c_char,
errno: ::c_int) -> ::c_int>,
pglob: *mut ::glob_t) -> ::c_int;
#[cfg_attr(target_os = "netbsd", link_name = "__globfree30")]
pub fn globfree(pglob: *mut ::glob_t);
pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int)
-> ::c_int;
pub fn shm_unlink(name: *const ::c_char) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86_64"),
link_name = "seekdir$INODE64")]
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "seekdir$INODE64$UNIX2003")]
pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long);
#[cfg_attr(all(target_os = "macos", target_arch = "x86_64"),
link_name = "telldir$INODE64")]
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "telldir$INODE64$UNIX2003")]
pub fn telldir(dirp: *mut ::DIR) -> ::c_long;
pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int)
-> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "msync$UNIX2003")]
#[cfg_attr(target_os = "netbsd", link_name = "__msync13")]
pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "recvfrom$UNIX2003")]
pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t,
flags: ::c_int, addr: *mut ::sockaddr,
addrlen: *mut ::socklen_t) -> ::ssize_t;
pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int;
pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int;
pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "bind$UNIX2003")]
pub fn bind(socket: ::c_int, address: *const ::sockaddr,
address_len: ::socklen_t) -> ::c_int;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "writev$UNIX2003")]
pub fn writev(fd: ::c_int,
iov: *const ::iovec,
iovcnt: ::c_int) -> ::ssize_t;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "readv$UNIX2003")]<|fim▁hole|> #[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "sendmsg$UNIX2003")]
pub fn sendmsg(fd: ::c_int,
msg: *const ::msghdr,
flags: ::c_int) -> ::ssize_t;
#[cfg_attr(all(target_os = "macos", target_arch = "x86"),
link_name = "recvmsg$UNIX2003")]
pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int)
-> ::ssize_t;
pub fn sync();
}
cfg_if! {
if #[cfg(any(target_os = "macos", target_os = "ios"))] {
mod apple;
pub use self::apple::*;
} else if #[cfg(any(target_os = "openbsd", target_os = "netbsd",
target_os = "bitrig"))] {
mod netbsdlike;
pub use self::netbsdlike::*;
} else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] {
mod freebsdlike;
pub use self::freebsdlike::*;
} else {
// Unknown target_os
}
}<|fim▁end|> | pub fn readv(fd: ::c_int,
iov: *const ::iovec,
iovcnt: ::c_int) -> ::ssize_t;
|
<|file_name|>JvmRenderEngineFactory.java<|end_file_name|><|fim▁begin|>package cn.dlb.bim.ifc.engine.jvm;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.dlb.bim.component.PlatformServer;
import cn.dlb.bim.component.PlatformServerConfig;
import cn.dlb.bim.ifc.emf.PackageMetaData;
import cn.dlb.bim.ifc.engine.IRenderEngine;
import cn.dlb.bim.ifc.engine.IRenderEngineFactory;
import cn.dlb.bim.ifc.engine.RenderEngineException;
import cn.dlb.bim.utils.PathUtils;
public class JvmRenderEngineFactory implements IRenderEngineFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(JvmRenderEngineFactory.class);
private Path nativeFolder;
private Path schemaFile;
private PlatformServer server;
public JvmRenderEngineFactory(PlatformServer server) {
this.server = server;
initialize();
}
public void initialize() {
try {
String os = System.getProperty("os.name").toLowerCase();
String libraryName = "";
if (os.contains("windows")) {
libraryName = "ifcengine.dll";
} else if (os.contains("osx") || os.contains("os x") || os.contains("darwin")) {
libraryName = "libIFCEngine.dylib";
} else if (os.contains("linux")) {
libraryName = "libifcengine.so";
}
InputStream inputStream = Files.newInputStream(server.getPlatformServerConfig().getCompileClassRoute().resolve("lib/" + System.getProperty("sun.arch.data.model") + "/" + libraryName));<|fim▁hole|> nativeFolder = tmpFolder.resolve("ifcenginedll");
Path file = nativeFolder.resolve(libraryName);
if (Files.exists(nativeFolder)) {
try {
PathUtils.removeDirectoryWithContent(nativeFolder);
} catch (IOException e) {
// Ignore
}
}
Files.createDirectories(nativeFolder);
OutputStream outputStream = Files.newOutputStream(file);
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public IRenderEngine createRenderEngine(String schema) throws RenderEngineException {
try {
PackageMetaData packageMetaData = server.getMetaDataManager().getPackageMetaData(schema);
schemaFile = packageMetaData.getSchemaPath();
if (schemaFile == null) {
throw new RenderEngineException("No schema file");
}
List<String> classPathEntries = new ArrayList<>();
// for (Dependency dependency : pluginContext.getDependencies()) {
// Path path = dependency.getPath();
// classPathEntries.add(path.toAbsolutePath().toString());
// }
return new JvmIfcEngine(schemaFile, nativeFolder, server.getPlatformServerConfig().getTempDir(), server.getPlatformServerConfig().getClassPath()
, classPathEntries);
} catch (RenderEngineException e) {
throw e;
}
}
}<|fim▁end|> | if (inputStream != null) {
try {
Path tmpFolder = server.getPlatformServerConfig().getTempDir(); |
<|file_name|>serde_types.rs<|end_file_name|><|fim▁begin|>use hybrid_clocks::{Timestamp, WallT};
use potboiler_common::{enum_str, types::CRDT};
use serde_derive::{Deserialize, Serialize};
use std::{collections::HashMap, fmt};
enum_str!(Operation {
Set("set"),
Add("add"),
Remove("remove"),
Create("create"),
});
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Change {
pub table: String,
pub key: String,
pub op: Operation,
pub change: serde_json::Value,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct LWWConfigOp {
pub crdt: CRDT,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct LWW {
pub when: Timestamp<WallT>,
pub data: serde_json::Value,<|fim▁hole|>
#[derive(Serialize, Deserialize, Debug)]
pub struct ORSetOp {
pub item: String,
pub key: String,
pub metadata: serde_json::Value,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ORSet {
pub adds: HashMap<String, String>,
pub removes: HashMap<String, String>,
}<|fim▁end|> | }
#[derive(Serialize, Deserialize, Debug)]
pub struct ORCreateOp {} |
<|file_name|>Location.java<|end_file_name|><|fim▁begin|>package app.location;
import app.core.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Column;<|fim▁hole|>
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "app_location")
public class Location extends BaseEntity {
@Column(name = "name")
private String name;
}<|fim▁end|> | import javax.persistence.Entity;
import javax.persistence.Table; |
<|file_name|>Ninja.py<|end_file_name|><|fim▁begin|>from robot import Robot
class TheRobot(Robot):
def initialize(self):
# Try to get in to a corner
self.forseconds(5, self.force, 50)
self.forseconds(0.9, self.force, -10)
self.forseconds(0.7, self.torque, 100)
self.forseconds(6, self.force, 50)
# Then look around and shoot stuff
self.forever(self.scanfire)
self._turretdirection = 1
self.turret(180)
self._pingfoundrobot = None
def scanfire(self):
self.ping()
sensors = self.sensors
kind, angle, dist = sensors['PING']
tur = sensors['TUR']
if self._pingfoundrobot is not None:
# has pinged a robot previously
if angle == self._pingfoundrobot:
# This is where we saw the robot previously
if kind in 'rb':<|fim▁hole|> # Something is still there, so shoot it
self.fire()
else:
# No robot there now
self._pingfoundrobot = None
elif kind == 'r':
# This is not where we saw something before,
# but there is a robot at this location also
self.fire()
self._pingfoundrobot = angle
self.turret(angle)
else:
# No robot where we just pinged. So go back to
# where we saw a robot before.
self.turret(self._pingfoundrobot)
elif kind == 'r':
# pinged a robot
# shoot it
self.fire()
# keep the turret here, and see if we can get it again
self._pingfoundrobot = angle
self.turret(angle)
else:
# No robot pinged, and have not seen a robot yet
# so move the turret and keep looking
if self._turretdirection == 1:
if tur < 180:
self.turret(180)
else:
self._turretdirection = 0
elif self._turretdirection == 0:
if tur > 90:
self.turret(90)
else:
self._turretdirection = 1<|fim▁end|> | |
<|file_name|>util.py<|end_file_name|><|fim▁begin|>"""Contains utility methods used by and with the pyebnf package."""
import math
def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False):
"""Escape-aware text splitting:
Split text on on a delimiter, recognizing escaped delimiters."""
is_escaped = False
split_count = 0
yval = []
for char in text:
if is_escaped:
is_escaped = False
yval.append(char)
else:
if char == escape:
is_escaped = True
elif char in delimiter and split_count != maxsplit:
if yval or not ignore_empty:
yield "".join(yval)
split_count += 1
yval = []
else:
yval.append(char)
yield "".join(yval)
def esc_join(iterable, delimiter=" ", escape="\\"):
"""Join an iterable by a delimiter, replacing instances of delimiter in items
with escape + delimiter.
"""
rep = escape + delimiter
return delimiter.join(i.replace(delimiter, rep) for i in iterable)
def get_newline_positions(text):
"""Returns a list of the positions in the text where all new lines occur. This is used by
get_line_and_char to efficiently find coordinates represented by offset positions.
"""
pos = []
for i, c in enumerate(text):
if c == "\n":
pos.append(i)
return pos
def get_line_and_char(newline_positions, position):
"""Given a list of newline positions, and an offset from the start of the source code
that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates.
"""
if newline_positions:
for line_no, nl_pos in enumerate(newline_positions):
if nl_pos >= position:
if line_no == 0:
return (line_no, position)
else:
return (line_no, position - newline_positions[line_no - 1] - 1)
return (line_no + 1, position - newline_positions[-1] - 1)
else:
return (0, position)
def point_to_source(source, position, fmt=(2, True, "~~~~~", "^")):
"""Point to a position in source code.
source is the text we're pointing in.
position is a 2-tuple of (line_number, character_number) to point to.
fmt is a 4-tuple of formatting parameters, they are:
name default description
---- ------- -----------
surrounding_lines 2 the number of lines above and below the target line to print
show_line_numbers True if true line numbers will be generated for the output_lines
tail_body "~~~~~" the body of the tail
pointer_char "^" the character that will point to the position
"""
surrounding_lines, show_line_numbers, tail_body, pointer_char = fmt
line_no, char_no = position
lines = source.split("\n")
line = lines[line_no]
if char_no >= len(tail_body):
tail = " " * (char_no - len(tail_body)) + tail_body + pointer_char
else:
tail = " " * char_no + pointer_char + tail_body
if show_line_numbers:
line_no_width = int(math.ceil(math.log10(max(1, line_no + surrounding_lines))) + 1)
line_fmt = "{0:" + str(line_no_width) + "}: {1}"
else:
line_fmt = "{1}"
pivot = line_no + 1
output_lines = [(pivot, line), ("", tail)]
for i in range(surrounding_lines):
upper_ofst = i + 1
upper_idx = line_no + upper_ofst
lower_ofst = -upper_ofst
lower_idx = line_no + lower_ofst
if lower_idx >= 0:
output_lines.insert(0, (pivot + lower_ofst, lines[lower_idx]))<|fim▁hole|> return "\n".join(line_fmt.format(n, c) for n, c in output_lines)<|fim▁end|> | if upper_idx < len(lines):
output_lines.append((pivot + upper_ofst, lines[upper_idx]))
|
<|file_name|>Simplif.java<|end_file_name|><|fim▁begin|>/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
This program 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.
This program 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 this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
package keel.Algorithms.RE_SL_Methods.LEL_TSK;
import java.io.*;
import org.core.*;
import java.util.*;
import java.lang.Math;
class Simplif {
public double semilla;
public long cont_soluciones;
public long Gen, n_genes, n_reglas, n_generaciones;
public int n_soluciones;
public String fich_datos_chequeo, fich_datos_tst, fich_datos_val;
public String fichero_conf, ruta_salida;
public String fichero_br, fichero_reglas, fich_tra_obli, fich_tst_obli;
public String datos_inter = "";
public String cadenaReglas = "";
public MiDataset tabla, tabla_tst, tabla_val;
public BaseR_TSK base_reglas;
public BaseR_TSK base_total;
public Adap_Sel fun_adap;
public AG alg_gen;
public Simplif(String f_e) {
fichero_conf = f_e;
}
private String Quita_blancos(String cadena) {
StringTokenizer sT = new StringTokenizer(cadena, "\t ", false);
return (sT.nextToken());
}
/** Reads the data of the configuration file */
public void leer_conf() {
int i, j;
String cadenaEntrada, valor;
double cruce, mutacion, porc_radio_reglas, porc_min_reglas, alfa, tau;
int tipo_fitness, long_poblacion;
// we read the file in a String
cadenaEntrada = Fichero.leeFichero(fichero_conf);
StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false);
// we read the algorithm's name
sT.nextToken();
sT.nextToken();
// we read the name of the training and test files
sT.nextToken();
valor = sT.nextToken();
StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false);
fich_datos_chequeo = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_datos_val = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_datos_tst = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
// we read the name of the output files
sT.nextToken();
valor = sT.nextToken();
ficheros = new StringTokenizer(valor, "\t ", false);
fich_tra_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_tst_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
String aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //Br inicial
aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BD
fichero_br = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de MAN2TSK
fichero_reglas = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Select
aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Tuning
ruta_salida = fich_tst_obli.substring(0, fich_tst_obli.lastIndexOf('/') + 1);
// we read the seed of the random generator
sT.nextToken();
valor = sT.nextToken();
semilla = Double.parseDouble(valor.trim());
Randomize.setSeed( (long) semilla); ;
for (i = 0; i < 19; i++) {
sT.nextToken(); //variable
sT.nextToken(); //valor
}
// we read the Number of Iterations
sT.nextToken();
valor = sT.nextToken();
n_generaciones = Long.parseLong(valor.trim());
// we read the Population Size
sT.nextToken();
valor = sT.nextToken();
long_poblacion = Integer.parseInt(valor.trim());
// we read the Tau parameter for the minimun maching degree required to the KB
sT.nextToken();
valor = sT.nextToken();
tau = Double.parseDouble(valor.trim());
// we read the Rate of Rules that don't are eliminated
sT.nextToken();
valor = sT.nextToken();
porc_min_reglas = Double.parseDouble(valor.trim());
// we read the Rate of rules to estimate the niche radio
sT.nextToken();
valor = sT.nextToken();
porc_radio_reglas = Double.parseDouble(valor.trim());
// we read the Alfa parameter for the Power Law
sT.nextToken();
valor = sT.nextToken();
alfa = Double.parseDouble(valor.trim());
// we read the Type of Fitness Function
sT.nextToken();
valor = sT.nextToken();
tipo_fitness = Integer.parseInt(valor.trim());
// we select the numero de soluciones
n_soluciones = 1;
// we read the Cross Probability
sT.nextToken();
valor = sT.nextToken();
cruce = Double.parseDouble(valor.trim());
// we read the Mutation Probability
sT.nextToken();
valor = sT.nextToken();
mutacion = Double.parseDouble(valor.trim());
// we create all the objects
tabla = new MiDataset(fich_datos_chequeo, false);
if (tabla.salir == false) {
tabla_val = new MiDataset(fich_datos_val, false);
tabla_tst = new MiDataset(fich_datos_tst, false);
base_total = new BaseR_TSK(fichero_br, tabla, true);
base_reglas = new BaseR_TSK(base_total.n_reglas, tabla);
fun_adap = new Adap_Sel(tabla, tabla_tst, base_reglas, base_total,
base_total.n_reglas, porc_radio_reglas,
porc_min_reglas, n_soluciones, tau, alfa,
tipo_fitness);
alg_gen = new AG(long_poblacion, base_total.n_reglas, cruce, mutacion,
fun_adap);
}
}
public void run() {
int i, j;
double ec, el, min_CR, ectst, eltst;
/* We read the configutate file and we initialize the structures and variables */
leer_conf();
if (tabla.salir == false) {
/* Inicializacion del contador de soluciones ya generadas */
cont_soluciones = 0;
System.out.println("Simplif-TSK");
do {
/* Generation of the initial population */
alg_gen.Initialize();
Gen = 0;
/* Evaluation of the initial population */
alg_gen.Evaluate();
Gen++;
/* Main of the genetic algorithm */
do {
/* Interchange of the new and old population */
alg_gen.Intercambio();
/* Selection by means of Baker */
alg_gen.Select();
/* Crossover */
alg_gen.Cruce_Multipunto();
/* Mutation */
alg_gen.Mutacion_Uniforme();
/* Elitist selection */
alg_gen.Elitist();
/* Evaluation of the current population */
alg_gen.Evaluate();
/* we increment the counter */
Gen++;
}
while (Gen <= n_generaciones);
/* we store the RB in the Tabu list */
if (Aceptar(alg_gen.solucion()) == 1) {
fun_adap.guardar_solucion(alg_gen.solucion());
/* we increment the number of solutions */
cont_soluciones++;
fun_adap.Decodifica(alg_gen.solucion());
fun_adap.Cubrimientos_Base();
/* we calcule the MSEs */
fun_adap.Error_tra();
ec = fun_adap.EC;
el = fun_adap.EL;
fun_adap.tabla_tst = tabla_tst;
fun_adap.Error_tst();
ectst = fun_adap.EC;
eltst = fun_adap.EL;
/* we calculate the minimum and maximum matching */
min_CR = 1.0;
for (i = 0; i < tabla.long_tabla; i++) {
min_CR = Adap.Minimo(min_CR, tabla.datos[i].maximo_cubrimiento);
}
/* we write the RB */
cadenaReglas = base_reglas.BRtoString();
cadenaReglas += "\n\nMinimum of C_R: " + min_CR +
" Minimum covering degree: " + fun_adap.mincb +
"\nAverage covering degree: " + fun_adap.medcb + " MLE: " + el +
"\nMSEtra: " + ec + " , MSEtst: " + ectst + "\n";
Fichero.escribeFichero(fichero_reglas, cadenaReglas);
/* we write the obligatory output files*/
String salida_tra = tabla.getCabecera();
salida_tra += fun_adap.getSalidaObli(tabla_val);
Fichero.escribeFichero(fich_tra_obli, salida_tra);
String salida_tst = tabla_tst.getCabecera();
salida_tst += fun_adap.getSalidaObli(tabla_tst);
Fichero.escribeFichero(fich_tst_obli, salida_tst);
/* we write the MSEs in specific files */
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunR.txt", "" + base_reglas.n_reglas + "\n");
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTRA.txt", "" + ec + "\n");
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTST.txt", "" + ectst + "\n");
}
/* the multimodal GA finish when the condition is true */
}
while (Parada() == 0);
}
}
/** Criterion of stop */
public int Parada() {
if (cont_soluciones == n_soluciones) {
return (1);
<|fim▁hole|> }
/** Criterion to accept the solutions */
int Aceptar(char[] cromosoma) {
return (1);
}
}<|fim▁end|> | }
else {
return (0);
}
|
<|file_name|>ConversionParser.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
ConversionParser.py $Id: ConversionParser.py,v 1.5 2004/10/20 01:44:53 chrish Exp $
Copyright 2003 Bill Nalen <bill.nalen@towers.com>
Distributable under the GNU General Public License Version 2 or newer.
Provides methods to wrap external convertors to return PluckerTextDocuments
"""
import os, sys, string, tempfile
from PyPlucker import TextParser
<|fim▁hole|>def WordParser (url, data, headers, config, attributes):
"""Convert a Word document to HTML and returns a PluckerTextDocument"""
# retrieve config information
worddoc_converter = config.get_string('worddoc_converter')
if worddoc_converter is None:
message(0, "Could not find Word conversion command")
return None
check = os.path.basename (worddoc_converter)
(check, ext) = os.path.splitext (check)
check = string.lower (check)
if check == 'wvware':
# need to save data to a local file
tempbase = tempfile.mktemp()
tempdoc = os.path.join(tempfile.tempdir, tempbase + ".doc")
try:
file = open (tempdoc, "wb")
file.write (data)
file.close ()
except IOError, text:
message(0, "Error saving temporary file %s" % tempdoc)
os.unlink(tempdoc)
return None
# then convert it > local.html
temphtml = os.path.join(tempfile.tempdir, tempbase + ".html")
command = worddoc_converter
command = command + " -d " + tempfile.tempdir + " -b " + os.path.join(tempfile.tempdir, tempbase)
command = command + " " + tempdoc + " > " + temphtml
try:
if os.system (command):
message(0, "Error running Word converter %s" % command)
try:
os.unlink(tempdoc)
os.unlink(temphtml)
except:
pass
return None
except:
message(0, "Exception running word converter %s" % command)
try:
os.unlink(tempdoc)
os.unlink(temphtml)
except:
pass
return None
# then load the local.html file to data2
try:
try:
file = open (temphtml, "rb")
data2 = file.read ()
file.close ()
finally:
os.unlink(tempdoc)
os.unlink(temphtml)
except IOError, text:
message(0, "Error reading temporary file %s" % temphtml)
return None
# then create a structuredhtmlparser from data2
parser = TextParser.StructuredHTMLParser (url, data2, headers, config, attributes)
return parser.get_plucker_doc ()
else:
return None<|fim▁end|> | from UtilFns import message, error
|
<|file_name|>hough_transform.rs<|end_file_name|><|fim▁begin|>// Implements http://rosettacode.org/wiki/Hough_transform
//
// Contributed by Gavin Baker <gavinb@antonym.org>
// Adapted from the Go version
use std::io::{BufReader, BufRead, BufWriter, Write, Read};
use std::fs::File;
use std::iter::repeat;
// Simple 8-bit grayscale image
struct ImageGray8 {
width: usize,
height: usize,
data: Vec<u8>,
}
fn load_pgm(filename: &str) -> ImageGray8 {
// Open file
let mut file = BufReader::new(File::open(filename).unwrap());
// Read header
let mut magic_in = String::new();
let _ = file.read_line(&mut magic_in).unwrap();
let mut width_in = String::new();
let _ = file.read_line(&mut width_in).unwrap();
let mut height_in = String::new();
let _ = file.read_line(&mut height_in).unwrap();
let mut maxval_in = String::new();
let _ = file.read_line(&mut maxval_in).unwrap();
assert_eq!(magic_in, "P5\n");
assert_eq!(maxval_in, "255\n");
// Parse header
let width = width_in.trim().parse::<usize>().unwrap();
let height: usize = height_in.trim().parse::<usize>().unwrap();
println!("Reading pgm file {}: {} x {}", filename, width, height);
// Create image and allocate buffer
let mut img = ImageGray8 {
width: width,
height: height,
data: repeat(0u8).take(width*height).collect(),
};
// Read image data
let len = img.data.len();
match file.read(&mut img.data) {
Ok(bytes_read) if bytes_read == len => println!("Read {} bytes", bytes_read),
Ok(bytes_read) =>
println!("Error: read {} bytes, expected {}", bytes_read, len),
Err(e) => println!("error reading: {}", e)
}
img
}
fn save_pgm(img: &ImageGray8, filename: &str) {
// Open file
let mut file = BufWriter::new(File::create(filename).unwrap());
// Write header
match writeln!(&mut file, "P5\n{}\n{}\n255", img.width, img.height) {
Err(e) => println!("Failed to write header: {}", e),
_ => {},
}
println!("Writing pgm file {}: {} x {}", filename, img.width, img.height);
// Write binary image data
match file.write_all(&(img.data[..])) {
Err(e) => println!("Failed to image data: {}", e),
_ => {},
}
}
fn hough(image: &ImageGray8, out_width: usize, out_height: usize) -> ImageGray8 {
let in_width = image.width;
let in_height = image.height;
// Allocate accumulation buffer
let out_height = ((out_height/2) * 2) as usize;
let mut accum = ImageGray8 {
width: out_width,
height: out_height,
data: repeat(255).take(out_width*out_height).collect(),
};
// Transform extents
let rmax = (in_width as f64).hypot(in_height as f64);
let dr = rmax / (out_height/2) as f64;
let dth = std::f64::consts::PI / out_width as f64;
// Process input image in raster order
for y in (0..in_height) {
for x in (0..in_width) {
let in_idx = y*in_width+x;
let col = image.data[in_idx];
if col == 255 {
continue;
}
// Project into rho,theta space
for jtx in (0..out_width) {
let th = dth * (jtx as f64);
let r = (x as f64)*(th.cos()) + (y as f64)*(th.sin());
let iry = out_height/2 - (r/(dr as f64)+0.5).floor() as usize;
let out_idx = jtx + iry * out_width;
let col = accum.data[out_idx];
if col > 0 {
accum.data[out_idx] = col - 1;
}
}
}
}<|fim▁hole|>
#[cfg(not(test))]
fn main() {
let image = load_pgm("../src/resources/Pentagon.pgm");
let accum = hough(&image, 460, 360);
save_pgm(&accum, "hough.pgm");
}<|fim▁end|> | accum
} |
<|file_name|>sgicc.py<|end_file_name|><|fim▁begin|>"""SCons.Tool.sgicc
Tool-specific initialization for MIPSPro cc on SGI.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# __COPYRIGHT__
#
# 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.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
from . import cc
def generate(env):
"""Add Builders and construction variables for gcc to an Environment."""
cc.generate(env)
env['CXX'] = 'CC'
env['SHOBJSUFFIX'] = '.o'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
def exists(env):
return env.Detect('cc')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:<|fim▁hole|><|fim▁end|> | # vim: set expandtab tabstop=4 shiftwidth=4: |
<|file_name|>15.2.3.6-2-8.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.6-2-8
description: >
Object.defineProperty - argument 'P' is a number that converts to
a string (value is -0)<|fim▁hole|>
assert(obj.hasOwnProperty("0"), 'obj.hasOwnProperty("0") !== true');<|fim▁end|> | ---*/
var obj = {};
Object.defineProperty(obj, -0, {}); |
<|file_name|>21.05.2015.14.36.java<|end_file_name|><|fim▁begin|>// dvt
/* 1. Да се напише if-конструкция,
* която изчислява стойността на две целочислени променливи и
* разменя техните стойности,
* ако стойността на първата променлива е по-голяма от втората.
*/<|fim▁hole|>
package myJava;
import java.util.Scanner;
public class dvt {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int a, b, temp;
System.out.print("a = "); a = read.nextInt();
System.out.print("b = "); b = read.nextInt();
if (a > b){
temp = a;
a = b;
b = temp;
System.out.println(
"a > b! The values have been switched!\n"
+ "a = " + a + " b = " + b);
}
}
}<|fim▁end|> | |
<|file_name|>resources.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Resource object code
#
# Created: Thu Jul 25 00:08:39 2013
# by: The Resource Compiler for PyQt (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x05\x3e\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x01\x04\x7d\x4a\x62\
\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x00\x7e\x00\x00\x00\x7e\
\x01\x6a\xf1\x2e\x6d\x00\x00\x00\x19\x74\x45\x58\x74\x53\x6f\x66\
\x74\x77\x61\x72\x65\x00\x41\x64\x6f\x62\x65\x20\x49\x6d\x61\x67\
\x65\x52\x65\x61\x64\x79\x71\xc9\x65\x3c\x00\x00\x04\xcb\x49\x44\
\x41\x54\x78\xda\x62\x60\xc0\x06\xd2\x0f\x3a\xff\xff\x5f\xc1\xff\
\x5f\xa7\xfa\xe2\x7f\x26\xac\x2a\xfe\x7f\x90\xff\x0f\xc2\x1d\xeb\
\x9a\xff\x03\x04\x10\x0e\xfd\x40\x45\x30\x55\x18\x66\x30\x82\x44\
\x19\x04\x1e\x32\xe4\xcd\x9f\xc9\x60\x2a\x7b\x99\x01\x20\x80\x18\
\x61\xda\x40\xf4\x0c\xfb\xbd\x0c\xba\xd5\x17\xc1\x2a\xcb\x1c\x67\
\x33\xc4\x9a\x6c\x66\x60\x41\x37\xe2\xf2\x5f\x3b\x06\x86\x0a\x01\
\x06\xdd\xee\x4d\x0c\x9f\x7f\xf2\x60\x2a\xd0\x65\x3e\xc4\xc0\xd0\
\xcd\xc0\x10\x63\xbc\x89\x21\xcb\x7a\x39\xaa\xbb\xc1\x18\xea\x42\
\x90\x2f\x41\x34\x40\x00\x31\x10\x02\x60\x57\x9b\x1d\x32\x60\x38\
\x65\x77\x01\x6c\x2f\xdc\x2d\xa5\x7e\x20\x6a\x02\xd8\x78\xd3\x4d\
\xfe\x28\xc6\xaf\x3f\x92\x08\xb3\x62\x3f\xd6\xc0\x0c\xd0\xd9\x07\
\x67\x63\x55\x70\xfa\x91\x0e\x9c\x8d\xe2\xcd\xbc\x90\x7e\x86\xfd\
\xdd\x4e\xc8\x6e\x80\x98\x60\xc4\xff\x05\xcc\x99\xb4\xbb\x08\x2e\
\x01\x73\x30\x48\xc1\x87\x54\xf9\x17\xd0\x50\x62\x03\x6a\xfd\x05\
\x57\x04\x04\x09\x00\x01\xc4\x08\x0d\xa8\x78\x20\xb5\x80\x81\x34\
\xf0\x81\x51\xe0\xa1\x20\xcc\x80\xff\x19\x17\x55\x18\xce\x7d\xe4\
\x01\x3b\x67\x86\xfe\x1d\x06\x50\x8c\x83\x40\x67\x72\x25\xc3\x0d\
\x53\x6d\x86\x33\x8f\x75\xe1\x3a\xd5\x45\xef\x31\xac\x49\x28\x00\
\x31\x0f\xb0\x10\xb2\xa6\x5c\x74\x1a\x03\x43\x84\x00\x22\xae\x81\
\x7e\xbb\xf9\x5a\x89\x61\xda\xd1\x48\x70\x5c\x33\x31\x90\x09\x78\
\xd9\xbf\x60\x06\x33\x36\xf0\xf4\xa3\x18\xc3\xb3\x47\x6a\x0c\xd3\
\x8e\x45\xc2\xbd\x61\x02\x4c\xc8\xa0\xb4\x0a\x4e\x2b\xb0\x30\x20\
\x14\xa1\xa6\x72\x57\xc0\x7c\x75\xb1\xfb\x0c\xd6\x93\x97\x33\xac\
\x8e\xcf\x67\xd0\x10\xbb\x8f\x08\x83\xd9\x0f\x25\xc0\xb8\x50\xe9\
\x29\x43\xa4\xcc\x6b\x70\x20\x9a\xda\x40\xa3\x6f\x8b\x04\x98\x5a\
\x7c\xd6\x8f\xe1\xe6\x2b\x45\x70\x5a\x07\x6a\x46\xb8\x00\xea\x8a\
\x7e\x20\x65\x80\xe1\x8c\x23\x3f\x18\x18\x6c\x38\xb0\x39\x30\x01\
\x18\x8d\x0f\x01\x02\x88\x81\x52\x00\x0b\x83\xf7\x40\x4a\x80\x44\
\xbd\x20\x17\x2c\x64\x84\x3a\xbd\x00\x94\xe9\x40\x00\x94\xf1\x40\
\x60\x9a\xaf\x27\xc3\x74\xbb\x4c\x14\x1d\x52\x7c\x2f\x19\x76\xa6\
\xa7\x22\x6c\x17\x78\xc8\xc8\x84\xd5\xdf\x40\x90\x75\x78\x06\xc3\
\xd1\x1e\x1b\x70\x94\x81\x30\x08\x3c\xfb\x24\x8e\x92\xab\x09\xa6\
\x03\xbe\x9f\x9f\x19\xe6\x47\x54\xa3\xa4\x42\x10\xb0\x9a\xb4\x8c\
\xe1\x58\x5e\x14\xee\x0c\x8d\x0b\x34\x7b\x4e\x00\xd3\xa0\xf2\x0c\
\x6f\x89\x80\x0b\x98\xca\x5e\xc1\x10\x23\xc9\x80\xd3\x8f\x75\x28\
\x33\xa0\x76\x7b\x01\x3c\x36\x88\x0a\x44\x58\x7e\xb8\x01\x4c\xbe\
\x5d\xfb\x11\xd1\x87\x1c\x95\x38\x0d\xf8\xc4\xce\xcb\x60\x5d\x72\
\x84\x81\x61\x25\xaa\xf8\xd1\xdc\x48\x8c\x92\x7b\x3f\x90\x76\xc0\
\x9a\x8d\x81\x18\x5c\x02\x01\x33\xce\xe7\x9f\xdc\xc0\x32\xe0\x2b\
\x43\xe8\xc2\x09\x60\x36\x28\x1a\x41\x09\x09\x25\x37\x4a\xb2\xff\
\x62\xf0\x91\x78\xc7\xc0\x60\xfb\x8c\x41\xfa\xf2\x43\x06\xe9\x0f\
\xf2\x70\x03\x41\x59\x18\x1b\x60\x42\x36\xa0\xe9\x96\x1c\x84\x13\
\x05\x8d\xe7\xe8\x57\x0c\x0c\xcb\x20\x25\x4f\xa6\xd5\x72\x30\x46\
\x2e\xd3\x61\x5e\x00\x59\xf3\xe0\xd9\x0f\x36\x06\x5e\x96\xbf\x60\
\x0c\x07\xd0\x82\x95\x01\xea\x92\xc4\x15\xad\xe0\x52\x09\x5a\x98\
\xa0\x94\xca\xf2\x58\x8b\xf5\x37\x40\xc3\x44\x98\xb1\xb9\xfc\x02\
\x50\x73\x21\x88\x01\x10\x60\x8c\x68\x0d\x00\x90\x41\x05\xb8\x32\
\x18\x15\x00\x28\xab\x4f\x40\x2e\x88\x90\x7d\x00\x92\x14\xe8\xbb\
\x2b\xcd\x70\xeb\x0b\x27\x5c\x87\x1a\xcf\x77\x86\x22\xe5\xa7\x88\
\x74\xb5\x4c\x85\x61\x9f\x84\x03\x38\x6d\x61\x03\xd2\x7c\xaf\x18\
\xa4\xf8\x5f\x81\x5b\x20\xa0\x72\x18\x57\xa5\x06\xf2\x24\xc8\x21\
\x30\x07\xc0\x93\x12\xac\x82\x83\x01\x78\x45\x87\x16\x2f\x37\xc4\
\xd5\x19\xf2\x81\x95\xf5\x33\x01\x69\x82\xde\x06\x15\x47\x13\x03\
\xda\x18\xf8\x38\xbe\x22\x0b\x1f\x00\x3a\xc0\x91\x85\xdc\xb0\xd4\
\x78\x79\x93\x61\xe7\x54\x2f\x60\x8b\x89\x1f\xdc\x6a\x82\x67\xa0\
\x1f\xdc\x0c\x4b\x80\x95\xc7\xf4\x63\x88\x0c\x03\x4a\x38\xa0\x64\
\x0c\x4a\x85\xf0\x86\x13\x39\x65\x01\x31\x00\xe4\x4b\x90\x25\xa0\
\xa4\x0e\x2b\x88\x61\x00\xe4\x28\xe4\xaa\x92\x26\x0e\x40\xa9\x15\
\xac\x96\x63\x29\x11\x75\xe9\xe7\x00\x62\x00\x4d\x1d\x30\xed\x58\
\x24\x86\x98\x93\xea\x09\xe2\xeb\x44\x72\x01\x28\x9e\xf3\x37\x54\
\xa1\x54\x7d\xb0\x2a\x11\xd6\xa2\xa1\x8a\x03\x16\x9b\x46\x33\x4c\
\xff\x9d\xc1\xf0\xb9\x9b\x0f\xaf\x3a\x50\x7b\x74\x1e\xb0\x72\x47\
\xcb\x86\xe4\x39\x80\x98\xfc\x0f\x4a\xfd\x4e\x2a\x27\x80\xc1\x7d\
\x92\x41\x1a\x58\x28\xc1\x42\x05\x54\x2d\xa1\x3b\x02\xa3\x20\xc2\
\x0b\x80\xed\x7b\x86\x0e\x60\x21\xf6\xf1\x1f\xb0\x7a\x01\xfa\xda\
\x9b\x0b\x43\xc9\xbe\xdb\xe6\xc0\xe0\xaf\x86\xb7\x81\x63\x8c\x37\
\xa3\x94\x09\x48\x65\x01\xf6\x82\x68\xf9\x13\x51\x86\xfe\x7b\x08\
\xdf\x4d\xd7\xbb\xc3\x60\x2c\x00\xa9\xd2\x18\x7c\x80\xad\xd5\x8f\
\xd0\x96\xf0\x91\xd7\xf0\x5a\x0a\xbd\x22\x86\x01\x50\x1a\x80\x25\
\x3a\x50\x83\x04\x54\x4c\x83\x5a\xb6\xd8\xa2\xe0\x02\x2c\x04\x40\
\x65\x3f\x0c\xf0\x30\xff\x65\x90\xe4\xf8\x85\x50\xfd\x10\x58\xdf\
\x3e\xfa\x03\x09\x01\x50\x48\x08\x3c\x44\xc8\x5d\x02\x3a\x5a\x8e\
\x05\xdc\x70\x87\x35\xde\xf3\xd6\x57\x01\x5b\x00\x13\x11\xdd\x0d\
\x60\x35\x8a\x14\x05\x17\xd0\x9b\xd7\xf1\xe0\xce\x1f\xb1\x8d\xdc\
\xad\xdf\x80\x15\xfe\x6b\x08\xdb\x1b\x58\x79\x2d\x15\xc3\x4c\x2f\
\xc0\x0a\x2b\x1f\xe8\x08\x50\x93\x14\xe4\xf3\x72\xa7\x39\xb0\x8a\<|fim▁hole|>\x08\xd4\x30\xde\xc8\x30\x18\x00\x00\x74\x67\xf6\x10\x90\x35\x83\
\x2d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\
"
qt_resource_name = "\
\x00\x07\
\x07\x3b\xe0\xb3\
\x00\x70\
\x00\x6c\x00\x75\x00\x67\x00\x69\x00\x6e\x00\x73\
\x00\x17\
\x03\xff\x46\x7e\
\x00\x62\
\x00\x6f\x00\x75\x00\x6e\x00\x64\x00\x61\x00\x72\x00\x79\x00\x5f\x00\x69\x00\x64\x00\x65\x00\x6e\x00\x74\x00\x69\x00\x66\x00\x69\
\x00\x63\x00\x61\x00\x74\x00\x69\x00\x6f\x00\x6e\
\x00\x08\
\x0a\x61\x5a\xa7\
\x00\x69\
\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\
"
qt_resource_struct = "\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\
\x00\x00\x00\x14\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\
\x00\x00\x00\x48\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()<|fim▁end|> | |
<|file_name|>server.js<|end_file_name|><|fim▁begin|>var socketio = require('socket.io');
exports.listen = function( server, Manager ) {
var io = socketio.listen(server);
Manager.findAllUsers(function ( err, data ) {
if(!err){
if(data.length === 0){
Manager.addUser({'login': 'madzia26', 'password': 'qwertyuiop', 'id': new Date().getTime() }, function ( err, data ) {
if(!err){
console.log('first user added');
}
});
}
}
});
io.sockets.on('connection', function ( client ) {
'use strict';
// console.log('socket.io connected');
// console.log(client.id);
//init
client.on('init', function () {
Manager.findAllUsers(function ( err, data ) {
if(!err){
var res = {
'users': [],
'categories': []
};
for(var i = 0; i < data.length; i++){
res.users.push({'login': data[i].login, "id": data[i].id});
}
Manager.findAllCategories( function ( err, data) {
if(!err){
res.categories = data;
Manager.findAllCds( function ( err, data) {
if(!err){
res.cds = data;
client.emit('init', res);
// console.log('init');
}
});
}
});
}
});<|fim▁hole|>
//users
client.on('addUser', function ( user ) {
Manager.addUser(user, function ( err, data ) {
if(!err){
// var token = new Date().getTime();
// User.signin(data.login, data.id, token);
client.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.broadcast.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.emit('auth', {'login': data.login, 'id': data.id });
}
});
});
//categories
client.on('addCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = { 'name': data.data.name, 'owner': data.data.owner };
Manager.addCategory(category, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'categories', 'data': category });
client.broadcast.emit('add', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('editCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.editCategory(category, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'categories', 'data': category });
client.broadcast.emit('update', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('rmCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.rmCategory(category, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'categories', 'data': category });
client.broadcast.emit('remove', {'coll': 'categories', 'data': category });
}
});
}
});
//cds
client.on('addCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = { 'name': data.data.name, 'owner': data.data.owner,
'category': data.data.category, 'url': data.data.url };
Manager.addCd(cd, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'cds', 'data': cd });
client.broadcast.emit('add', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('editCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.editCd(cd, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'cds', 'data': cd });
client.broadcast.emit('update', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('rmCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.rmCd(cd, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'cds', 'data': cd });
client.broadcast.emit('remove', {'coll': 'cds', 'data': cd });
}
});
}
});
});
};<|fim▁end|> | }); |
<|file_name|>comb.py<|end_file_name|><|fim▁begin|>def comb(xs):
if len(xs) == 0:
return [""]
else:
return comb2(xs) + [""]
def comb2(xs):
if len(xs) == 1:<|fim▁hole|> else:
subwo = comb2( xs[1:] )
head = xs[0]
subwith = [ head + zs for zs in subwo ]
return subwo + subwith + [ head ]
result = comb( "abcde" )
result.sort()
print result
print len( result )<|fim▁end|> | return [ xs ] |
<|file_name|>94-sample.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# vi: ts=4 sw=4
################################################################################
# Code for defining a 'Sample' object, which keeps track of its state, and
# simplifies the task of aligning, measuring, etc.
################################################################################
# Known Bugs:
# N/A
################################################################################
# TODO:
# - Search for "TODO" below.
# - Ability to have a collection of simultaneous motions? (E.g. build up a set
# of deferred motions?)
# - Use internal naming scheme to control whether 'saxs'/'waxs' is put in the
# filename
################################################################################
import time
import re
import os
import shutil
class CoordinateSystem(object):
"""
A generic class defining a coordinate system. Several coordinate systems
can be layered on top of one another (with a reference to the underlying
coordinate system given by the 'base_stage' pointer). When motion of a given
CoordinateSystem is requested, the motion is passed (with coordinate
conversion) to the underlying stage.
"""
hint_replacements = { 'positive': 'negative',
'up': 'down',
'left': 'right',
'towards': 'away from',
'downstream': 'upstream',
'inboard': 'outboard',
'clockwise': 'counterclockwise',
'CW': 'CCW',
}
# Core methods
########################################
def __init__(self, name='<unnamed>', base=None, **kwargs):
'''Create a new CoordinateSystem (e.g. a stage or a sample).
Parameters
----------
name : str
Name for this stage/sample.
base : Stage
The stage on which this stage/sample sits.
'''
self.name = name
self.base_stage = base
self.enabled = True
self.md = {}
self._marks = {}
self._set_axes_definitions()
self._init_axes(self._axes_definitions)
def _set_axes_definitions(self):
'''Internal function which defines the axes for this stage. This is kept
as a separate function so that it can be over-ridden easily.'''
# The _axes_definitions array holds a list of dicts, each defining an axis
self._axes_definitions = []
def _init_axes(self, axes):
'''Internal method that generates method names to control the various axes.'''
# Note: Instead of defining CoordinateSystem() having methods '.x', '.xr',
# '.y', '.yr', etc., we programmatically generate these methods when the
# class (and subclasses) are instantiated.
# Thus, the Axis() class has generic versions of these methods, which are
# appropriated renamed (bound, actually) when a class is instantiated.
self._axes = {}
for axis in axes:
axis_object = Axis(axis['name'], axis['motor'], axis['enabled'], axis['scaling'], axis['units'], axis['hint'], self.base_stage, stage=self)
self._axes[axis['name']] = axis_object
# Bind the methods of axis_object to appropriately-named methods of
# the CoordinateSystem() class.
setattr(self, axis['name'], axis_object.get_position )
setattr(self, axis['name']+'abs', axis_object.move_absolute )
setattr(self, axis['name']+'r', axis_object.move_relative )
setattr(self, axis['name']+'pos', axis_object.get_position )
setattr(self, axis['name']+'posMotor', axis_object.get_motor_position )
setattr(self, axis['name']+'units', axis_object.get_units )
setattr(self, axis['name']+'hint', axis_object.get_hint )
setattr(self, axis['name']+'info', axis_object.get_info )
setattr(self, axis['name']+'set', axis_object.set_current_position )
setattr(self, axis['name']+'o', axis_object.goto_origin )
setattr(self, axis['name']+'setOrigin', axis_object.set_origin )
setattr(self, axis['name']+'mark', axis_object.mark )
setattr(self, axis['name']+'search', axis_object.search )
setattr(self, axis['name']+'scan', axis_object.scan )
setattr(self, axis['name']+'c', axis_object.center )
def comment(self, text, logbooks=None, tags=None, append_md=True, **md):
'''Add a comment related to this CoordinateSystem.'''
text += '\n\n[comment for CoordinateSystem: {} ({})].'.format(self.name, self.__class__.__name__)
if append_md:
md_current = { k : v for k, v in RE.md.items() } # Global md
md_current.update(get_beamline().get_md()) # Beamline md
# Self md
#md_current.update(self.get_md())
# Specified md
md_current.update(md)
text += '\n\n\nMetadata\n----------------------------------------'
for key, value in sorted(md_current.items()):
text += '\n{}: {}'.format(key, value)
logbook.log(text, logbooks=logbooks, tags=tags)
def set_base_stage(self, base):
self.base_stage = base
self._init_axes(self._axes_definitions)
# Convenience/helper methods
########################################
def multiple_string_replacements(self, text, replacements, word_boundaries=False):
'''Peform multiple string replacements simultaneously. Matching is case-insensitive.
Parameters
----------
text : str
Text to return modified
replacements : dictionary
Replacement pairs
word_boundaries : bool, optional
Decides whether replacements only occur for words.
'''
# Code inspired from:
# http://stackoverflow.com/questions/6116978/python-replace-multiple-strings
# Note inclusion of r'\b' sequences forces the regex-match to occur at word-boundaries.
if word_boundaries:
replacements = dict((r'\b'+re.escape(k.lower())+r'\b', v) for k, v in replacements.items())
pattern = re.compile("|".join(replacements.keys()), re.IGNORECASE)
text = pattern.sub(lambda m: replacements[r'\b'+re.escape(m.group(0).lower())+r'\b'], text)
else:
replacements = dict((re.escape(k.lower()), v) for k, v in replacements.items())
pattern = re.compile("|".join(replacements.keys()), re.IGNORECASE)
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
return text
def _hint_replacements(self, text):
'''Convert a motor-hint into its logical inverse.'''
# Generates all the inverse replacements
replacements = dict((v, k) for k, v in self.hint_replacements.items())
replacements.update(self.hint_replacements)
return self.multiple_string_replacements(text, replacements, word_boundaries=True)
# Control methods
########################################
def setTemperature(self, temperature, verbosity=3):
if verbosity>=1:
print('Temperature functions not implemented in {}'.format(self.__class__.__name__))
def temperature(self, verbosity=3):
if verbosity>=1:
print('Temperature functions not implemented in {}'.format(self.__class__.__name__))
return 0.0
# Motion methods
########################################
def enable(self):
self.enabled = True
def disable(self):
self.enabled = False
def is_enabled(self):
return self.enabled
def pos(self, verbosity=3):
'''Return (and print) the positions of all axes associated with this
stage/sample.'''
out = {}
for axis_name, axis_object in sorted(self._axes.items()):
out[axis_name] = axis_object.get_position(verbosity=verbosity)
#if verbosity>=2: print('') # \n
return out
def hints(self, verbosity=3):
'''Return (and print) the hints of all axes associated with this
stage/sample.'''
out = {}
for axis_name, axis_object in sorted(self._axes.items()):
if verbosity>=2: print('{:s}'.format(axis_name))
out[axis_name] = axis_object.get_hint(verbosity=verbosity)
if verbosity>=2: print('') # \n
return out
def origin(self, verbosity=3):
'''Returns the origin for axes.'''
out = {}
for axis_name, axis_object in sorted(self._axes.items()):
origin = axis_object.get_origin()
if verbosity>=2: print('{:s} origin = {:.3f} {:s}'.format(axis_name, origin, axis_object.get_units()))
out[axis_name] = origin
return out
def gotoOrigin(self, axes=None):
'''Go to the origin (zero-point) for this stage. All axes are zeroed,
unless one specifies the axes to move.'''
# TODO: Guard against possibly buggy behavior if 'axes' is a string instead of a list.
# (Python will happily iterate over the characters in a string.)
if axes is None:
axes_to_move = self._axes.values()
else:
axes_to_move = [self._axes[axis_name] for axis_name in axes]
for axis in axes_to_move:
axis.goto_origin()
def setOrigin(self, axes, positions=None):
'''Define the current position as the zero-point (origin) for this stage/
sample. The axes to be considered in this redefinition must be supplied
as a list.
If the optional positions parameter is passed, then those positions are
used to define the origins for the axes.'''
if positions is None:
for axis in axes:
getattr(self, axis+'setOrigin')()
else:
for axis, pos in zip(axes, positions):
getattr(self, axis+'setOrigin')(pos)
def gotoAlignedPosition(self):
'''Goes to the currently-defined 'aligned' position for this stage. If
no specific aligned position is defined, then the zero-point for the stage
is used instead.'''
# TODO: Optional offsets? (Like goto mark?)
if 'aligned_position' in self.md and self.md['aligned_position'] is not None:
for axis_name, position in self.md['aligned_position'].items():
self._axes[axis_name].move_absolute(position)
else:
self.gotoOrigin()
# Motion logging
########################################
def setAlignedPosition(self, axes):
'''Saves the current position as the 'aligned' position for this stage/
sample. This allows one to return to this position later. One must
specify the axes to be considered.
WARNING: Currently this position data is not saved persistently. E.g. it will
be lost if you close and reopen the console.
'''
positions = {}
for axis_name in axes:
positions[axis_name] = self._axes[axis_name].get_position(verbosity=0)
self.attributes['aligned_position'] = positions
def mark(self, label, *axes, **axes_positions):
'''Set a mark for the stage/sample/etc.
'Marks' are locations that have been labelled, which is useful for
later going to a labelled position (using goto), or just to keep track
of sample information (metadata).
By default, the mark is set at the current position. If no 'axes' are
specified, all motors are logged. Alternately, axes (as strings) can
be specified. If axes_positions are given as keyword arguments, then
positions other than the current position can be specified.
'''
positions = {}
if len(axes)==0 and len(axes_positions)==0:
for axis_name in self._axes:
positions[axis_name] = self._axes[axis_name].get_position(verbosity=0)
else:
for axis_name in axes:
positions[axis_name] = self._axes[axis_name].get_position(verbosity=0)
for axis_name, position in axes_positions.items():
positions[axis_name] = position
self._marks[label] = positions
def marks(self, verbosity=3):
'''Get a list of the current marks on the stage/sample/etc. 'Marks'
are locations that have been labelled, which is useful for later
going to a labelled position (using goto), or just to keep track
of sample information (metadata).'''
if verbosity>=3:
print('Marks for {:s} (class {:s}):'.format(self.name, self.__class__.__name__))
if verbosity>=2:
for label, positions in self._marks.items():
print(label)
for axis_name, position in sorted(positions.items()):
print(' {:s} = {:.4f} {:s}'.format(axis_name, position, self._axes[axis_name].get_units()))
return self._marks
def goto(self, label, verbosity=3, **additional):
'''Move the stage/sample to the location given by the label. For this
to work, the specified label must have been 'marked' at some point.
Additional keyword arguments can be provided. For instance, to move
3 mm from the left edge:
sam.goto('left edge', xr=+3.0)
'''
if label not in self._marks:
if verbosity>=1:
print("Label '{:s}' not recognized. Use '.marks()' for the list of marked positions.".format(label))
return
for axis_name, position in sorted(self._marks[label].items()):
if axis_name+'abs' in additional:
# Override the marked value for this position
position = additional[axis_name+'abs']
del(additional[axis_name+'abs'])
#relative = 0.0 if axis_name+'r' not in additional else additional[axis_name+'r']
if axis_name+'r' in additional:
relative = additional[axis_name+'r']
del(additional[axis_name+'r'])
else:
relative = 0.0
self._axes[axis_name].move_absolute(position+relative, verbosity=verbosity)
# Handle any optional motions not already covered
for command, amount in additional.items():
if command[-1]=='r':
getattr(self, command)(amount, verbosity=verbosity)
elif command[-3:]=='abs':
getattr(self, command)(amount, verbosity=verbosity)
else:
print("Keyword argument '{}' not understood (should be 'r' or 'abs').".format(command))
# State methods
########################################
def save_state(self):
'''Outputs a string you can use to re-initialize this object back
to its current state.'''
#TODO: Save to databroker?
state = { 'origin': {} }
for axis_name, axis in self._axes.items():
state['origin'][axis_name] = axis.origin
return state
def restore_state(self, state):
'''Outputs a string you can use to re-initialize this object back
to its current state.'''
for axis_name, axis in self._axes.items():
axis.origin = state['origin'][axis_name]
# End class CoordinateSystem(object)
########################################
class Axis(object):
'''Generic motor axis.
Meant to be used within a CoordinateSystem() or Stage() object.
'''
def __init__(self, name, motor, enabled, scaling, units, hint, base, stage=None, origin=0.0):
self.name = name
self.motor = motor
self.enabled = enabled
self.scaling = scaling
self.units = units
self.hint = hint
self.base_stage = base
self.stage = stage
self.origin = 0.0
self._move_settle_max_time = 10.0
self._move_settle_period = 0.05
self._move_settle_tolerance = 0.01
# Coordinate transformations
########################################
def cur_to_base(self, position):
'''Convert from this coordinate system to the coordinate in the (immediate) base.'''
base_position = self.get_origin() + self.scaling*position
return base_position
def base_to_cur(self, base_position):
'''Convert from this base position to the coordinate in the current system.'''
position = (base_position - self.get_origin())/self.scaling
return position
def cur_to_motor(self, position):
'''Convert from this coordinate system to the underlying motor.'''
if self.motor is not None:
return self.cur_to_base(position)
else:
base_position = self.cur_to_base(position)
return self.base_stage._axes[self.name].cur_to_motor(base_position)
def motor_to_cur(self, motor_position):
'''Convert a motor position into the current coordinate system.'''
if self.motor is not None:
return self.base_to_cur(motor_position)
else:
base_position = self.base_stage._axes[self.name].motor_to_cur(motor_position)
return self.base_to_cur(base_position)
# Programmatically-defined methods
########################################
# Note: Instead of defining CoordinateSystem() having methods '.x', '.xr',
# '.xp', etc., we programmatically generate these methods when the class
# (and subclasses) are instantiated.
# Thus, the Axis() class has generic versions of these methods, which are
# appropriated renamed (bound, actually) when a class is instantiated.
def get_position(self, verbosity=3):
'''Return the current position of this axis (in its coordinate system).
By default, this also prints out the current position.'''
if self.motor is not None:
base_position = self.motor.position
else:
verbosity_c = verbosity if verbosity>=4 else 0
base_position = getattr(self.base_stage, self.name+'pos')(verbosity=verbosity_c)
position = self.base_to_cur(base_position)
if verbosity>=2:
if self.stage:
stg = self.stage.name
else:
stg = '?'
if verbosity>=5 and self.motor is not None:
print( '{:s} = {:.3f} {:s}'.format(self.motor.name, base_position, self.get_units()) )
print( '{:s}.{:s} = {:.3f} {:s} (origin = {:.3f})'.format(stg, self.name, position, self.get_units(), self.get_origin()) )
return position
def get_motor_position(self, verbosity=3):
'''Returns the position of this axis, traced back to the underlying
motor.'''
if self.motor is not None:
return self.motor.position
else:
return getattr(self.base_stage, self.name+'posMotor')(verbosity=verbosity)
#return self.base_stage._axes[self.name].get_motor_position(verbosity=verbosity)
def move_absolute(self, position=None, wait=True, verbosity=3):
'''Move axis to the specified absolute position. The position is given
in terms of this axis' current coordinate system. The "defer" argument
can be used to defer motions until "move" is called.'''
if position is None:
# If called without any argument, just print the current position
return self.get_position(verbosity=verbosity)
# Account for coordinate transformation
base_position = self.cur_to_base(position)
if self.is_enabled():
if self.motor:
#mov( self.motor, base_position )
self.motor.user_setpoint.value = base_position
else:
# Call self.base_stage.xabs(base_position)
getattr(self.base_stage, self.name+'abs')(base_position, verbosity=0)
if self.stage:
stg = self.stage.name
else:
stg = '?'
if verbosity>=2:
# Show a realtime output of position
start_time = time.time()
current_position = self.get_position(verbosity=0)
while abs(current_position-position)>self._move_settle_tolerance and (time.time()-start_time)<self._move_settle_max_time:
current_position = self.get_position(verbosity=0)
print( '{:s}.{:s} = {:5.3f} {:s} \r'.format(stg, self.name, current_position, self.get_units()), end='')
time.sleep(self._move_settle_period)
#if verbosity>=1:
#current_position = self.get_position(verbosity=0)
#print( '{:s}.{:s} = {:5.3f} {:s} '.format(stg, self.name, current_position, self.get_units()))
elif verbosity>=1:
print( 'Axis %s disabled (stage %s).' % (self.name, self.stage.name) )
def move_relative(self, move_amount=None, verbosity=3):
'''Move axis relative to the current position.'''
if move_amount is None:
# If called without any argument, just print the current position
return self.get_position(verbosity=verbosity)
target_position = self.get_position(verbosity=0) + move_amount
return self.move_absolute(target_position, verbosity=verbosity)
def goto_origin(self):
'''Move axis to the currently-defined origin (zero-point).'''
self.move_absolute(0)
def set_origin(self, origin=None):
'''Sets the origin (zero-point) for this axis. If no origin is supplied,
the current position is redefined as zero. Alternatively, you can supply
a position (in the current coordinate system of the axis) that should
henceforth be considered zero.'''
if origin is None:
# Use current position
if self.motor is not None:
self.origin = self.motor.position
else:
if self.base_stage is None:
print("Error: %s %s has 'base_stage' and 'motor' set to 'None'." % (self.__class__.__name__, self.name))
else:
self.origin = getattr(self.base_stage, self.name+'pos')(verbosity=0)
else:
# Use supplied value (in the current coordinate system)
base_position = self.cur_to_base(origin)
self.origin = base_position
def set_current_position(self, new_position):
'''Redefines the position value of the current position.'''
current_position = self.get_position(verbosity=0)
self.origin = self.get_origin() + (current_position - new_position)*self.scaling
def search(self, step_size=1.0, min_step=0.05, intensity=None, target=0.5, detector=None, detector_suffix=None, polarity=+1, verbosity=3):
'''Moves this axis, searching for a target value.
Parameters
----------
step_size : float
The initial step size when moving the axis
min_step : float
The final (minimum) step size to try
intensity : float
The expected full-beam intensity readout
target : 0.0 to 1.0
The target ratio of full-beam intensity; 0.5 searches for half-max.
The target can also be 'max' to find a local maximum.
detector, detector_suffix
The beamline detector (and suffix, such as '_stats4_total') to trigger to measure intensity
polarity : +1 or -1
Positive motion assumes, e.g. a step-height 'up' (as the axis goes more positive)
'''
if not get_beamline().beam.is_on():
print('WARNING: Experimental shutter is not open.')
if intensity is None:
intensity = RE.md['beam_intensity_expected']
if detector is None:
#detector = gs.DETS[0]
detector = get_beamline().detector[0]
if detector_suffix is None:
#value_name = gs.TABLE_COLS[0]
value_name = get_beamline().TABLE_COLS[0]
else:
value_name = detector.name + detector_suffix
bec.disable_table()
# Check current value
RE(count([detector]))
value = detector.read()[value_name]['value']
if target is 'max':
if verbosity>=5:
print("Performing search on axis '{}' target is 'max'".format(self.name))
max_value = value
max_position = self.get_position(verbosity=0)
direction = +1*polarity
while step_size>=min_step:
if verbosity>=4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
self.move_relative(move_amount=direction*step_size, verbosity=verbosity-2)
prev_value = value
RE(count([detector]))
value = detector.read()[value_name]['value']
if verbosity>=3:
print(" {} = {:.3f} {}; value : {}".format(self.name, self.get_position(verbosity=0), self.units, value))
if value>max_value:
max_value = value
max_position = self.get_position(verbosity=0)
if value>prev_value:
# Keep going in this direction...
pass
else:
# Switch directions!
direction *= -1
step_size *= 0.5
elif target is 'min':
if verbosity>=5:
print("Performing search on axis '{}' target is 'min'".format(self.name))
direction = +1*polarity
while step_size>=min_step:
if verbosity>=4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
self.move_relative(move_amount=direction*step_size, verbosity=verbosity-2)
prev_value = value
RE(count([detector]))
value = detector.read()[value_name]['value']
if verbosity>=3:
print(" {} = {:.3f} {}; value : {}".format(self.name, self.get_position(verbosity=0), self.units, value))
if value<prev_value:
# Keep going in this direction...
pass
else:
# Switch directions!
direction *= -1
step_size *= 0.5
else:
target_rel = target
target = target_rel*intensity
if verbosity>=5:
print("Performing search on axis '{}' target {} × {} = {}".format(self.name, target_rel, intensity, target))
if verbosity>=4:
print(" value : {} ({:.1f}%)".format(value, 100.0*value/intensity))
# Determine initial motion direction
if value>target:
direction = -1*polarity
else:
direction = +1*polarity
while step_size>=min_step:
if verbosity>=4:
print(" move {} by {} × {}".format(self.name, direction, step_size))
self.move_relative(move_amount=direction*step_size, verbosity=verbosity-2)
RE(count([detector]))
value = detector.read()[value_name]['value']
if verbosity>=3:
print(" {} = {:.3f} {}; value : {} ({:.1f}%)".format(self.name, self.get_position(verbosity=0), self.units, value, 100.0*value/intensity))
# Determine direction
if value>target:
new_direction = -1.0*polarity
else:
new_direction = +1.0*polarity
if abs(direction-new_direction)<1e-4:
# Same direction as we've been going...
# ...keep moving this way
pass
else:
# Switch directions!
direction *= -1
step_size *= 0.5
bec.enable_table()
def scan(self):
print('todo')
def center(self):
print('todo')
def mark(self, label, position=None, verbosity=3):
'''Set a mark for this axis. (By default, the current position is
used.)'''
if position is None:
position = self.get_position(verbosity=0)
axes_positions = { self.name : position }
self.stage.mark(label, **axes_positions)
# Book-keeping
########################################
def enable(self):
self.enabled = True
def disable(self):
self.enabled = False
def is_enabled(self):
return self.enabled and self.stage.is_enabled()
def get_origin(self):
return self.origin
def get_units(self):
if self.units is not None:
return self.units
else:
return getattr(self.base_stage, self.name+'units')()
def get_hint(self, verbosity=3):
'''Return (and print) the "motion hint" associated with this axis. This
hint gives information about the expected directionality of the motion.'''
if self.hint is not None:
s = '%s\n%s' % (self.hint, self.stage._hint_replacements(self.hint))
if verbosity>=2:
print(s)
return s
else:
return getattr(self.base_stage, self.name+'hint')(verbosity=verbosity)
def get_info(self, verbosity=3):
'''Returns information about this axis.'''
self.get_position(verbosity=verbosity)
self.get_hint(verbosity=verbosity)
def check_base(self):
if self.base_stage is None:
print("Error: %s %s has 'base_stage' set to 'None'." % (self.__class__.__name__, self.name))
class Sample_Generic(CoordinateSystem):
"""
The Sample() classes are used to define a single, individual sample. Each
sample is created with a particular name, which is recorded during measurements.
Logging of comments also includes the sample name. Different Sample() classes
can define different defaults for alignment, measurement, etc.
"""
# Core methods
########################################
def __init__(self, name, base=None, **md):
'''Create a new Sample object.
Parameters
----------
name : str
Name for this sample.
base : Stage
The stage/holder on which this sample sits.
'''
if base is None:
base = get_default_stage()
#print("Note: No base/stage/holder specified for sample '{:s}'. Assuming '{:s}' (class {:s})".format(name, base.name, base.__class__.__name__))
super().__init__(name=name, base=base)
self.name = name
self.md = {
'exposure_time' : 1.0 ,
'measurement_ID' : 1 ,
}
self.md.update(md)
self.naming_scheme = ['name', 'extra', 'exposure_time','id']
self.naming_delimeter = '_'
# TODO
#if base is not None:
#base.addSample(self)
self.reset_clock()
def _set_axes_definitions(self):
'''Internal function which defines the axes for this stage. This is kept
as a separate function so that it can be over-ridden easily.'''
# The _axes_definitions array holds a list of dicts, each defining an axis
self._axes_definitions = [ {'name': 'x',
'motor': None,
'enabled': True,
'scaling': +1.0,
'units': None,
'hint': None,
},
{'name': 'y',
'motor': None,
'enabled': True,
'scaling': +1.0,
'units': 'mm',
'hint': None,
},
#{'name': 'z',
#'motor': None,
#'enabled': False,
#'scaling': +1.0,
#'units': 'mm',
#'hint': None,
#},
{'name': 'th',
'motor': None,
'enabled': True,
'scaling': +1.0,
'units': 'deg',
'hint': None,
},
#{'name': 'chi',
#'motor': None,
#'enabled': True,
#'scaling': +1.0,
#'units': 'deg',
#'hint': None,
#},
#{'name': 'phi',
#'motor': None,
#'enabled': True,
#'scaling': +1.0,
#'units': 'deg',
#'hint': None,
#},
]
# Metadata methods
########################################
# These involve setting or getting values associated with this sample.
def clock(self):
'''Return the current value of the "clock" variable. This provides a
way to set a clock/timer for a sample. For instance, you can call
"reset_clock" when you initiate some change to the sample. Thereafter,
the "clock" method lets you check how long it has been since that
event.'''
clock_delta = time.time() - self.clock_zero
return clock_delta
def reset_clock(self):
'''Resets the sample's internal clock/timer to zero.'''
self.clock_zero = time.time()
return self.clock()
def get_attribute(self, attribute):
'''Return the value of the requested md.'''
if attribute in self._axes:
return self._axes[attribute].get_position(verbosity=0)
if attribute=='name':
return self.name
if attribute=='clock':
return self.clock()
if attribute=='temperature':
return self.temperature(verbosity=0)
if attribute in self.md:
return self.md[attribute]
replacements = {
'id' : 'measurement_ID' ,
'ID' : 'measurement_ID' ,
'extra' : 'savename_extra' ,
}
if attribute in replacements:
return self.md[replacements[attribute]]
return None
def set_attribute(self, attribute, value):
'''Arbitrary attributes can be set and retrieved. You can use this to
store additional meta-data about the sample.
WARNING: Currently this meta-data is not saved anywhere. You can opt
to store the information in the sample filename (using "naming").
'''
self.md[attribute] = value
def set_md(self, **md):
self.md.update(md)
def get_md(self, prefix='sample_', include_marks=True, **md):
'''Returns a dictionary of the current metadata.
The 'prefix' argument is prepended to all the md keys, which allows the
metadata to be grouped with other metadata in a clear way. (Especially,
to make it explicit that this metadata came from the sample.)'''
# Update internal md
#self.md['key'] = value
md_return = self.md.copy()
md_return['name'] = self.name
if include_marks:
for label, positions in self._marks.items():
md_return['mark_'+label] = positions
# Add md that varies over time
md_return['clock'] = self.clock()
md_return['temperature'] = self.temperature(verbosity=0)
for axis_name, axis in self._axes.items():
md_return[axis_name] = axis.get_position(verbosity=0)
md_return['motor_'+axis_name] = axis.get_motor_position(verbosity=0)
md_return['savename'] = self.get_savename() # This should be over-ridden by 'measure'
# Include the user-specified metadata
md_return.update(md)
# Add an optional prefix
if prefix is not None:
md_return = { '{:s}{:s}'.format(prefix, key) : value for key, value in md_return.items() }
return md_return
# Naming scheme methods
########################################
# These allow the user to control how data is named.
def naming(self, scheme=['name', 'extra', 'exposure_time','id'], delimeter='_'):
'''This method allows one to define the naming convention that will be
used when storing data for this sample. The "scheme" variable is an array
that lists the various elements one wants to store in the filename.
Each entry in "scheme" is a string referring to a particular element/
value. For instance, motor names can be stored ("x", "y", etc.), the
measurement time can be stored, etc.'''
self.naming_scheme = scheme
self.naming_delimeter = delimeter
def get_naming_string(self, attribute):
# Handle special cases of formatting the text
if attribute in self._axes:
return '{:s}{:.3f}'.format(attribute, self._axes[attribute].get_position(verbosity=0))
if attribute=='clock':
return '{:.1f}s'.format(self.get_attribute(attribute))
if attribute=='exposure_time':
return '{:.2f}s'.format(self.get_attribute(attribute))
if attribute=='temperature':
return 'T{:.3f}C'.format(self.get_attribute(attribute))
if attribute=='extra':
# Note: Don't eliminate this check; it will not be properly handled
# by the generic call below. When 'extra' is None, we should
# return None, so that it gets skipped entirely.
return self.get_attribute('savename_extra')
if attribute=='spot_number':
return 'spot{:d}'.format(self.get_attribute(attribute))
# Generically: lookup the attribute and convert to string
att = self.get_attribute(attribute)
if att is None:
# If the attribute is not found, simply return the text.
# This allows the user to insert arbitrary text info into the
# naming scheme.
return attribute
else:
return str(att)
def get_savename(self, savename_extra=None):
'''Return the filename that will be used to store data for the upcoming
measurement. The method "naming" lets one control what gets stored in
the filename.'''
if savename_extra is not None:
self.set_attribute('savename_extra', savename_extra)
attribute_strings = []
for attribute in self.naming_scheme:
s = self.get_naming_string(attribute)
if s is not None:
attribute_strings.append(s)
self.set_attribute('savename_extra', None)
savename = self.naming_delimeter.join(attribute_strings)
# Avoid 'dangerous' characters
savename = savename.replace(' ', '_')
#savename = savename.replace('.', 'p')
savename = savename.replace('/', '-slash-')
return savename
# Logging methods
########################################
def comment(self, text, logbooks=None, tags=None, append_md=True, **md):
'''Add a comment related to this sample.'''
text += '\n\n[comment for sample: {} ({})].'.format(self.name, self.__class__.__name__)
if append_md:
md_current = { k : v for k, v in RE.md.items() } # Global md
md_current.update(get_beamline().get_md()) # Beamline md
# Sample md
md_current.update(self.get_md())
# Specified md
md_current.update(md)
text += '\n\n\nMetadata\n----------------------------------------'
for key, value in sorted(md_current.items()):
text += '\n{}: {}'.format(key, value)
logbook.log(text, logbooks=logbooks, tags=tags)
def log(self, text, logbooks=None, tags=None, append_md=True, **md):
if append_md:
text += '\n\n\nMetadata\n----------------------------------------'
for key, value in sorted(md.items()):
text += '\n{}: {}'.format(key, value)
logbook.log(text, logbooks=logbooks, tags=tags)
# Control methods
########################################
def setTemperature(self, temperature, verbosity=3):
return self.base_stage.setTemperature(temperature, verbosity=verbosity)
def temperature(self, verbosity=3):
return self.base_stage.temperature(verbosity=verbosity)
# Measurement methods
########################################
def get_measurement_md(self, prefix=None, **md):
#md_current = {}
md_current = { k : v for k, v in RE.md.items() } # Global md
#md_current['detector_sequence_ID'] = caget('XF:11BMB-ES{Det:SAXS}:cam1:FileNumber_RBV')
#md_current['detector_sequence_ID'] = caget('XF:11BMB-ES{}:cam1:FileNumber_RBV'.format(pilatus_Epicsname))
if get_beamline().detector[0].name is 'pilatus300':
md_current['detector_sequence_ID'] = caget('XF:11BMB-ES{Det:SAXS}:cam1:FileNumber_RBV')
elif get_beamline().detector[0].name is 'pilatus2M':
md_current['detector_sequence_ID'] = caget('XF:11BMB-ES{Det:PIL2M}:cam1:FileNumber_RBV')
md_current.update(get_beamline().get_md())
md_current.update(md)
# Add an optional prefix
if prefix is not None:
md_return = { '{:s}{:s}'.format(prefix, key) : value for key, value in md_return.items() }
return md_current
def _expose_manual(self, exposure_time=None, verbosity=3, poling_period=0.1, **md):
'''Internal function that is called to actually trigger a measurement.'''
# TODO: Improve this (switch to Bluesky methods)
# TODO: Store metadata
if 'measure_type' not in md:
md['measure_type'] = 'expose'
self.log('{} for {}.'.format(md['measure_type'], self.name), **md)
if exposure_time is not None:
# Prep detector
#caput('XF:11BMB-ES{Det:SAXS}:cam1:AcquireTime', exposure_time)
#caput('XF:11BMB-ES{Det:SAXS}:cam1:AcquirePeriod', exposure_time+0.1)
#caput('XF:11BMB-ES{}:cam1:AcquireTime'.format(pilatus_Epicsname), exposure_time)
#caput('XF:11BMB-ES{}:cam1:AcquirePeriod'.format(pilatus_Epicsname), exposure_time+0.1)
if get_beamline().detector[0].name is 'pilatus300':
caput('XF:11BMB-ES{Det:SAXS}:cam1:AcquireTime', exposure_time)
caput('XF:11BMB-ES{Det:SAXS}:cam1:AcquirePeriod', exposure_time+0.1)
elif get_beamline().detector[0].name is 'pilatus2M':
caput('XF:11BMB-ES{Det:PIL2M}:cam1:AcquireTime', exposure_time)
caput('XF:11BMB-ES{Det:PIL2M}:cam1:AcquirePeriod', exposure_time+0.1)
get_beamline().beam.on()
# Trigger acquisition manually
caput('XF:11BMB-ES{}:cam1:Acquire'.format(pilatus_Epicsname), 1)
if verbosity>=2:
start_time = time.time()
while caget('XF:11BMB-ES{}:cam1:Acquire'.format(pilatus_Epicsname))==1 and (time.time()-start_time)<(exposure_time+20):
percentage = 100*(time.time()-start_time)/exposure_time
print( 'Exposing {:6.2f} s ({:3.0f}%) \r'.format((time.time()-start_time), percentage), end='')
time.sleep(poling_period)
else:
time.sleep(exposure_time)
if verbosity>=3 and caget('XF:11BMB-ES{}:cam1:Acquire'.format(pilatus_Epicsname))==1:
print('Warning: Detector still not done acquiring.')
get_beamline().beam.off()
def expose(self, exposure_time=None, extra=None, verbosity=3, poling_period=0.1, **md):
'''Internal function that is called to actually trigger a measurement.'''
'''TODO: **md doesnot work in RE(count). '''
if 'measure_type' not in md:
md['measure_type'] = 'expose'
#self.log('{} for {}.'.format(md['measure_type'], self.name), **md)
# Set exposure time
if exposure_time is not None:
#for detector in gs.DETS:
for detector in get_beamline().detector:
if exposure_time != caget('XF:11BMB-ES{Det:PIL2M}:cam1:AcquireTime'):<|fim▁hole|>
#extra wait time for adjusting pilatus2M
#time.sleep(2)
# Do acquisition
get_beamline().beam.on()
md['plan_header_override'] = md['measure_type']
start_time = time.time()
#md_current = self.get_md()
md['beam_int_bim3'] = beam.bim3.flux(verbosity=0)
md['beam_int_bim4'] = beam.bim4.flux(verbosity=0)
md['beam_int_bim5'] = beam.bim5.flux(verbosity=0)
#md.update(md_current)
#uids = RE(count(get_beamline().detector, 1), **md)
uids = RE(count(get_beamline().detector), **md)
#get_beamline().beam.off()
#print('shutter is off')
# Wait for detectors to be ready
max_exposure_time = 0
for detector in get_beamline().detector:
if detector.name is 'pilatus300':
current_exposure_time = caget('XF:11BMB-ES{Det:SAXS}:cam1:AcquireTime')
max_exposure_time = max(max_exposure_time, current_exposure_time)
elif detector.name is 'pilatus2M':
current_exposure_time = caget('XF:11BMB-ES{Det:PIL2M}:cam1:AcquireTime')
max_exposure_time = max(max_exposure_time, current_exposure_time)
elif detector.name is 'PhotonicSciences_CMS':
current_exposure_time = detector.exposure_time
max_exposure_time = max(max_exposure_time, current_exposure_time)
else:
if verbosity>=1:
print("WARNING: Didn't recognize detector '{}'.".format(detector.name))
if verbosity>=2:
status = 0
while (status==0) and (time.time()-start_time)<(max_exposure_time+20):
percentage = 100*(time.time()-start_time)/max_exposure_time
print( 'Exposing {:6.2f} s ({:3.0f}%) \r'.format((time.time()-start_time), percentage), end='')
time.sleep(poling_period)
status = 1
for detector in get_beamline().detector:
if detector.name is 'pilatus300':
if caget('XF:11BMB-ES{Det:SAXS}:cam1:Acquire')==1:
status *= 0
elif detector.name is 'pilatus2M':
if caget('XF:11BMB-ES{Det:PIL2M}:cam1:Acquire')==1:
status *= 0
elif detector.name is 'PhotonicSciences_CMS':
if not detector.detector_is_ready(verbosity=0):
status *= 0
print('')
else:
time.sleep(max_exposure_time)
if verbosity>=3 and caget('XF:11BMB-ES{Det:SAXS}:cam1:Acquire')==1:
print('Warning: Detector pilatus300 still not done acquiring.')
if verbosity>=3 and caget('XF:11BMB-ES{Det:PIL2M}:cam1:Acquire')==1:
print('Warning: Detector pilatus2M still not done acquiring.')
get_beamline().beam.off()
for detector in get_beamline().detector:
#self.handle_file(detector, extra=extra, verbosity=verbosity, **md)
self.handle_file(detector, extra=extra, verbosity=verbosity)
def handle_file(self, detector, extra=None, verbosity=3, subdirs=True, **md):
subdir = ''
if detector.name is 'pilatus300':
chars = caget('XF:11BMB-ES{Det:SAXS}:TIFF1:FullFileName_RBV')
filename = ''.join(chr(char) for char in chars)[:-1]
# Alternate method to get the last filename
#filename = '{:s}/{:s}.tiff'.format( detector.tiff.file_path.get(), detector.tiff.file_name.get() )
if verbosity>=3:
print(' Data saved to: {}'.format(filename))
if subdirs:
subdir = '/saxs/'
#if md['measure_type'] is not 'snap':
if True:
self.set_attribute('exposure_time', caget('XF:11BMB-ES{Det:SAXS}:cam1:AcquireTime'))
# Create symlink
#link_name = '{}/{}{}'.format(RE.md['experiment_alias_directory'], subdir, md['filename'])
#savename = md['filename'][:-5]
savename = self.get_savename(savename_extra=extra)
link_name = '{}/{}{}_{:04d}_saxs.tiff'.format(RE.md['experiment_alias_directory'], subdir, savename, RE.md['scan_id'])
if os.path.isfile(link_name):
i = 1
while os.path.isfile('{}.{:d}'.format(link_name,i)):
i += 1
os.rename(link_name, '{}.{:d}'.format(link_name,i))
os.symlink(filename, link_name)
if verbosity>=3:
print(' Data linked as: {}'.format(link_name))
elif detector.name is 'pilatus2M':
chars = caget('XF:11BMB-ES{Det:PIL2M}:TIFF1:FullFileName_RBV')
filename = ''.join(chr(char) for char in chars)[:-1]
# Alternate method to get the last filename
#filename = '{:s}/{:s}.tiff'.format( detector.tiff.file_path.get(), detector.tiff.file_name.get() )
if verbosity>=3:
print(' Data saved to: {}'.format(filename))
if subdirs:
subdir = '/saxs/'
#if md['measure_type'] is not 'snap':
if True:
self.set_attribute('exposure_time', caget('XF:11BMB-ES{Det:PIL2M}:cam1:AcquireTime'))
# Create symlink
#link_name = '{}/{}{}'.format(RE.md['experiment_alias_directory'], subdir, md['filename'])
#savename = md['filename'][:-5]
savename = self.get_savename(savename_extra=extra)
link_name = '{}/{}{}_{:04d}_saxs.tiff'.format(RE.md['experiment_alias_directory'], subdir, savename, RE.md['scan_id'])
#link_name = '{}/{}{}_{:04d}_saxs.cbf'.format(RE.md['experiment_alias_directory'], subdir, savename, RE.md['scan_id']-1)
if os.path.isfile(link_name):
i = 1
while os.path.isfile('{}.{:d}'.format(link_name,i)):
i += 1
os.rename(link_name, '{}.{:d}'.format(link_name,i))
os.symlink(filename, link_name)
if verbosity>=3:
print(' Data linked as: {}'.format(link_name))
elif detector.name is 'PhotonicSciences_CMS':
self.set_attribute('exposure_time', detector.exposure_time)
filename = '{:s}/{:s}.tif'.format( detector.file_path, detector.file_name )
if subdirs:
subdir = '/waxs/'
#savename = md['filename'][:-5]
savename = self.get_savename(savename_extra=extra)
savename = '{}/{}{}_{:04d}_waxs.tiff'.format(RE.md['experiment_alias_directory'], subdir, savename, RE.md['scan_id'])
shutil.copy(filename, savename)
if verbosity>=3:
print(' Data saved to: {}'.format(savename))
else:
if verbosity>=1:
print("WARNING: Can't do file handling for detector '{}'.".format(detector.name))
return
def snap(self, exposure_time=None, extra=None, measure_type='snap', verbosity=3, **md):
'''Take a quick exposure (without saving data).'''
self.measure(exposure_time=exposure_time, extra=extra, measure_type=measure_type, verbosity=verbosity, **md)
def measure(self, exposure_time=None, extra=None, measure_type='measure', verbosity=3, tiling=False, **md):
'''Measure data by triggering the area detectors.
Parameters
----------
exposure_time : float
How long to collect data
extra : string, optional
Extra information about this particular measurement (which is typically
included in the savename/filename).
tiling : string
Controls the detector tiling mode.
None : regular measurement (single detector position)
'ygaps' : try to cover the vertical gaps in the Pilatus300k
'''
if tiling is 'ygaps':
extra_current = 'pos1' if extra is None else '{}_pos1'.format(extra)
md['detector_position'] = 'lower'
self.measure_single(exposure_time=exposure_time, extra=extra_current, measure_type=measure_type, verbosity=verbosity, **md)
#movr(SAXSy, 5.16) # move detector up by 30 pixels; 30*0.172 = 5.16
SAXSy.move(SAXSy.user_readback.value + 5.16)
extra_current = 'pos2' if extra is None else '{}_pos2'.format(extra)
md['detector_position'] = 'upper'
self.measure_single(exposure_time=exposure_time, extra=extra_current, measure_type=measure_type, verbosity=verbosity, **md)
#movr(SAXSy, -5.16)
SAXSy.move(SAXSy.user_readback.value + -5.16)
#if tiling is 'big':
# TODO: Use multiple images to fill the entire detector motion range
else:
# Just do a normal measurement
self.measure_single(exposure_time=exposure_time, extra=extra, measure_type=measure_type, verbosity=verbosity, **md)
def measure_single(self, exposure_time=None, extra=None, measure_type='measure', verbosity=3, **md):
'''Measure data by triggering the area detectors.
Parameters
----------
exposure_time : float
How long to collect data
extra : string, optional
Extra information about this particular measurement (which is typically
included in the savename/filename).
'''
if exposure_time is not None:
self.set_attribute('exposure_time', exposure_time)
#else:
#exposure_time = self.get_attribute('exposure_time')
savename = self.get_savename(savename_extra=extra)
#caput('XF:11BMB-ES{Det:SAXS}:cam1:FileName', savename)
if verbosity>=2 and (get_beamline().current_mode != 'measurement'):
print("WARNING: Beamline is not in measurement mode (mode is '{}')".format(get_beamline().current_mode))
if verbosity>=1 and len(get_beamline().detector)<1:
print("ERROR: No detectors defined in cms.detector")
return
md_current = self.get_md()
md_current.update(self.get_measurement_md())
md_current['sample_savename'] = savename
md_current['measure_type'] = measure_type
#md_current['filename'] = '{:s}_{:04d}.tiff'.format(savename, md_current['detector_sequence_ID'])
md_current['filename'] = '{:s}_{:04d}.tiff'.format(savename, RE.md['scan_id'])
#md_current.update(md)
self.expose(exposure_time, extra=extra, verbosity=verbosity, **md_current)
#self.expose(exposure_time, extra=extra, verbosity=verbosity, **md)
self.md['measurement_ID'] += 1
def _test_time(self):
print(time.time())
time.time()
def _test_measure_single(self, exposure_time=None, extra=None, shutteronoff=True, measure_type='measure', verbosity=3, **md):
'''Measure data by triggering the area detectors.
Parameters
----------
exposure_time : float
How long to collect data
extra : string, optional
Extra information about this particular measurement (which is typically
included in the savename/filename).
'''
#print('1') #0s
#print(time.time())
if exposure_time is not None:
self.set_attribute('exposure_time', exposure_time)
#else:
#exposure_time = self.get_attribute('exposure_time')
savename = self.get_savename(savename_extra=extra)
#caput('XF:11BMB-ES{Det:SAXS}:cam1:FileName', savename)
if verbosity>=2 and (get_beamline().current_mode != 'measurement'):
print("WARNING: Beamline is not in measurement mode (mode is '{}')".format(get_beamline().current_mode))
if verbosity>=1 and len(get_beamline().detector)<1:
print("ERROR: No detectors defined in cms.detector")
return
#print('2') #0.0004s
#print(time.time())
md_current = self.get_md()
md_current['sample_savename'] = savename
md_current['measure_type'] = measure_type
md_current.update(self.get_measurement_md())
#md_current['filename'] = '{:s}_{:04d}.tiff'.format(savename, md_current['detector_sequence_ID'])
md_current['filename'] = '{:s}_{:04d}.tiff'.format(savename, RE.md['scan_id'])
md_current.update(md)
#print('3') #0.032s
#print(time.time())
self._test_expose(exposure_time, shutteronoff=shutteronoff, extra=extra, verbosity=verbosity, **md_current)
#print('4') #5.04s
#print(time.time())
self.md['measurement_ID'] += 1
#print('5') #5.0401
#print(time.time())
def _test_expose(self, exposure_time=None, extra=None, verbosity=3, poling_period=0.1, shutteronoff=True, **md):
'''Internal function that is called to actually trigger a measurement.'''
if 'measure_type' not in md:
md['measure_type'] = 'expose'
#self.log('{} for {}.'.format(md['measure_type'], self.name), **md)
# Set exposure time
if exposure_time is not None:
for detector in get_beamline().detector:
detector.setExposureTime(exposure_time, verbosity=verbosity)
#print('1') #5e-5
#print(self.clock())
# Do acquisition
# check shutteronoff, if
if shutteronoff == True:
get_beamline().beam.on()
else:
print('shutter is disabled')
#print('2') #3.0
#print(self.clock())
md['plan_header_override'] = md['measure_type']
start_time = time.time()
print('2') #3.0
print(self.clock())
#uids = RE(count(get_beamline().detector, 1), **md)
#uids = RE(count(get_beamline().detector), **md)
yield from (count(get_beamline().detector))
print('3') #4.3172
print(self.clock())
#get_beamline().beam.off()
#print('shutter is off')
# Wait for detectors to be ready
max_exposure_time = 0
for detector in get_beamline().detector:
if detector.name is 'pilatus300' or 'pilatus2M':
current_exposure_time = caget('XF:11BMB-ES{}:cam1:AcquireTime'.format(pilatus_Epicsname))
max_exposure_time = max(max_exposure_time, current_exposure_time)
elif detector.name is 'PhotonicSciences_CMS':
current_exposure_time = detector.exposure_time
max_exposure_time = max(max_exposure_time, current_exposure_time)
else:
if verbosity>=1:
print("WARNING: Didn't recognize detector '{}'.".format(detector.name))
print('4') #4.3193
print(self.clock())
if verbosity>=2:
status = 0
print('status1 = ', status)
while (status==0) and (time.time()-start_time)<(max_exposure_time+20):
percentage = 100*(time.time()-start_time)/max_exposure_time
print( 'Exposing {:6.2f} s ({:3.0f}%) \r'.format((time.time()-start_time), percentage), end='')
print('status2 = ', status)
time.sleep(poling_period)
status = 1
for detector in get_beamline().detector:
if detector.name is 'pilatus300' or 'pilatus2M':
print('status2.5 = ', status)
if caget('XF:11BMB-ES{}:cam1:Acquire'.format(pilatus_Epicsname))==1:
status = 0
print('status3 = ', status)
print('status3.5 = ', status)
elif detector.name is 'PhotonicSciences_CMS':
if not detector.detector_is_ready(verbosity=0):
status = 0
print('5') #3.0
print(self.clock())
print('6') #3.0
print(self.clock())
else:
time.sleep(max_exposure_time)
#print('5') #4.4193
#print(self.clock())
if verbosity>=3 and caget('XF:11BMB-ES{}:cam1:Acquire'.format(pilatus_Epicsname))==1:
print('Warning: Detector still not done acquiring.')
if shutteronoff == True:
get_beamline().beam.off()
else:
print('shutter is disabled')
#print('6') #4.9564
#print(self.clock())
for detector in get_beamline().detector:
self.handle_file(detector, extra=extra, verbosity=verbosity, **md)
#print('7') #4.9589
#print(self.clock())
def _test_measureSpots(self, num_spots=4, translation_amount=0.2, axis='y', exposure_time=None, extra=None, shutteronoff=True, measure_type='measureSpots', tiling=False, **md):
'''Measure multiple spots on the sample.'''
if 'spot_number' not in self.md:
self.md['spot_number'] = 1
start_time = time.time()
for spot_num in range(num_spots):
self._test_measure_single(exposure_time=exposure_time, extra=extra, measure_type=measure_type, shutteronoff=shutteronoff, tiling=tiling, **md)
print(spot_num+1)
print(time.time()-start_time)
getattr(self, axis+'r')(translation_amount)
self.md['spot_number'] += 1
print('{:d} of {:d} is done'.format(spot_num+1,num_spots))
print(time.time()-start_time)
def measureSpots(self, num_spots=4, translation_amount=0.2, axis='y', exposure_time=None, extra=None, measure_type='measureSpots', tiling=False, **md):
'''Measure multiple spots on the sample.'''
if 'spot_number' not in self.md:
self.md['spot_number'] = 1
for spot_num in range(num_spots):
self.measure(exposure_time=exposure_time, extra=extra, measure_type=measure_type, tiling=tiling, **md)
getattr(self, axis+'r')(translation_amount)
self.md['spot_number'] += 1
print('{:d} of {:d} is done'.format(spot_num+1,num_spots))
def measureTimeSeries(self, exposure_time=None, num_frames=10, wait_time=None, extra=None, measure_type='measureTimeSeries', verbosity=3, tiling=False, fix_name=True, **md):
if fix_name and ('clock' not in self.naming_scheme):
self.naming_scheme_hold = self.naming_scheme
self.naming_scheme = self.naming_scheme_hold.copy()
self.naming_scheme.insert(-1, 'clock')
md['measure_series_num_frames'] = num_frames
for i in range(num_frames):
if verbosity>=3:
print('Measuring frame {:d}/{:d} ({:.1f}% complete).'.format(i+1, num_frames, 100.0*i/num_frames))
md['measure_series_current_frame'] = i+1
self.measure(exposure_time=exposure_time, extra=extra, measure_type=measure_type, verbosity=verbosity, tiling=tiling, **md)
if wait_time is not None:
time.sleep(wait_time)
def measureTimeSeriesAngles(self, exposure_time=None, num_frames=10, wait_time=None, extra=None, measure_type='measureTimeSeries', verbosity=3, tiling=False, fix_name=True, **md):
if fix_name and ('clock' not in self.naming_scheme):
self.naming_scheme_hold = self.naming_scheme
self.naming_scheme = self.naming_scheme_hold.copy()
self.naming_scheme.insert(-1, 'clock')
md['measure_series_num_frames'] = num_frames
for i in range(num_frames):
if verbosity>=3:
print('Measuring frame {:d}/{:d} ({:.1f}% complete).'.format(i+1, num_frames, 100.0*i/num_frames))
md['measure_series_current_frame'] = i+1
print('Angles in measure include: {}'.format(sam.incident_angles_default))
self.measureIncidentAngles(exposure_time=exposure_time, extra=extra, **md)
if wait_time is not None:
time.sleep(wait_time)
#if (i % 2 ==0):
# self.xr(-1)
#else:
# self.xr(1)
#self.pos()
def measureTemperature(self, temperature, exposure_time=None, wait_time=None, temperature_tolerance=0.4, extra=None, measure_type='measureTemperature', verbosity=3, tiling=False, poling_period=1.0, fix_name=True, **md):
# Set new temperature
self.setTemperature(temperature, verbosity=verbosity)
# Wait until we reach the temperature
while abs(self.temperature(verbosity=0) - temperature)>temperature_tolerance:
if verbosity>=3:
print(' setpoint = {:.3f}°C, Temperature = {:.3f}°C \r'.format(caget('XF:11BM-ES{Env:01-Out:1}T-SP')-273.15, self.temperature(verbosity=0)), end='')
time.sleep(poling_period)
# Allow for additional equilibration at this temperature
if wait_time is not None:
time.sleep(wait_time)
# Measure
#if fix_name and ('temperature' not in self.naming_scheme):
# self.naming_scheme_hold = self.naming_scheme
# self.naming_scheme = self.naming_scheme_hold.copy()
# self.naming_scheme.insert(-1, 'temperature')
self.measure(exposure_time=exposure_time, extra=extra, measure_type=measure_type, verbosity=verbosity, tiling=tiling, **md)
#self.naming_scheme = self.naming_scheme_hold
def measureTemperatures(self, temperatures, exposure_time=None, wait_time=None, temperature_tolerance=0.4, extra=None, measure_type='measureTemperature', verbosity=3, tiling=False, poling_period=1.0, fix_name=True, **md):
for temperature in temperatures:
self.measureTemperature(temperature, exposure_time=exposure_time, wait_time=wait_time, temperature_tolerance=temperature_tolerance, measure_type=measure_type, verbosity=verbosity, tiling=tiling, poling_period=poling_period, fix_name=fix_name, **md)
def do(self, step=0, verbosity=3, **md):
'''Performs the "default action" for this sample. This usually means
aligning the sample, and taking data.
The 'step' argument can optionally be given to jump to a particular
step in the sequence.'''
if verbosity>=4:
print(' doing sample {}'.format(self.name))
if step<=1:
if verbosity>=5:
print(' step 1: goto origin')
self.xo() # goto origin
self.yo()
#self.gotoAlignedPosition()
#if step<=5:
#self.align()
if step<=10:
if verbosity>=5:
print(' step 10: measuring')
self.measure(**md)
# Control methods
########################################
def setTemperature(self, temperature, verbosity=3):
#if verbosity>=1:
#print('Temperature functions not implemented in {}'.format(self.__class__.__name__))
if verbosity>=2:
print(' Changing temperature setpoint from {:.3f}°C to {:.3f}°C'.format(caget('XF:11BM-ES{Env:01-Out:1}T-SP')-273.15, temperature))
caput('XF:11BM-ES{Env:01-Out:1}T-SP', temperature+273.15)
def temperature(self, verbosity=3):
#if verbosity>=1:
#print('Temperature functions not implemented in {}'.format(self.__class__.__name__))
current_temperature = caget('XF:11BM-ES{Env:01-Chan:A}T:C-I')
if verbosity>=3:
print(' Temperature = {:.3f}°C (setpoint = {:.3f}°C)'.format( current_temperature, caget('XF:11BM-ES{Env:01-Out:1}T-SP')-273.15 ) )
return current_temperature
class SampleTSAXS_Generic(Sample_Generic):
pass
class SampleGISAXS_Generic(Sample_Generic):
def __init__(self, name, base=None, **md):
super().__init__(name=name, base=base, **md)
self.naming_scheme = ['name', 'extra', 'th', 'exposure_time']
self.incident_angles_default = [0.08, 0.10, 0.12, 0.15, 0.20]
def measureSpots(self, num_spots=2, translation_amount=0.1, axis='x', exposure_time=None, extra=None, measure_type='measureSpots', **md):
super().measureSpots(num_spots=num_spots, translation_amount=translation_amount, axis=axis, exposure_time=exposure_time, extra=extra, measure_type=measure_type, **md)
def measureIncidentAngle(self, angle, exposure_time=None, extra=None, **md):
self.thabs(angle)
self.measure(exposure_time=exposure_time, extra=extra, **md)
def measureIncidentAngles(self, angles=None, exposure_time=None, extra=None, **md):
if angles is None:
angles = self.incident_angles_default
for angle in angles:
self.measureIncidentAngle(angle, exposure_time=exposure_time, extra=extra, **md)
def _alignOld(self, step=0):
'''Align the sample with respect to the beam. GISAXS alignment involves
vertical translation to the beam center, and rocking theta to get the
sample plane parralel to the beam.
The 'step' argument can optionally be given to jump to a particular
step in the sequence.'''
# TODO: Deprecate and delete
if step<=0:
# TODO: Check what mode we are in, change if necessary...
# get_beamline().modeAlignment()
beam.on()
# TODO: Improve implementation
if step<=2:
#fit_scan(smy, 2.6, 35, fit='HM')
fit_scan(smy, 2.6, 35, fit='sigmoid_r')
if step<=4:
#fit_scan(smy, 0.6, 17, fit='HM')
fit_scan(smy, 0.6, 17, fit='sigmoid_r')
fit_scan(sth, 1.2, 21, fit='max')
#if step<=6:
# fit_scan(smy, 0.3, 17, fit='sigmoid_r')
# fit_scan(sth, 1.2, 21, fit='COM')
if step<=8:
fit_scan(smy, 0.2, 17, fit='sigmoid_r')
fit_scan(sth, 0.8, 21, fit='gauss')
if step<=9:
#self._testing_refl_pos()
#movr(sth,.1)
#fit_scan(sth, 0.2, 41, fit='gauss')
#fit_scan(smy, 0.2, 21, fit='gauss')
#movr(sth,-.1)
beam.off()
def align(self, step=0, reflection_angle=0.08, verbosity=3):
'''Align the sample with respect to the beam. GISAXS alignment involves
vertical translation to the beam center, and rocking theta to get the
sample plane parralel to the beam. Finally, the angle is re-optimized
in reflection mode.
The 'step' argument can optionally be given to jump to a particular
step in the sequence.'''
if verbosity>=4:
print(' Aligning {}'.format(self.name))
if step<=0:
# Prepare for alignment
if RE.state!='idle':
RE.abort()
if get_beamline().current_mode!='alignment':
if verbosity>=2:
print("WARNING: Beamline is not in alignment mode (mode is '{}')".format(get_beamline().current_mode))
#get_beamline().modeAlignment()
get_beamline().setDirectBeamROI()
beam.on()
if step<=2:
if verbosity>=4:
print(' align: searching')
# Estimate full-beam intensity
value = None
if True:
# You can eliminate this, in which case RE.md['beam_intensity_expected'] is used by default
self.yr(-2)
#detector = gs.DETS[0]
detector = get_beamline().detector[0]
value_name = get_beamline().TABLE_COLS[0]
RE(count([detector]))
value = detector.read()[value_name]['value']
self.yr(+2)
if 'beam_intensity_expected' in RE.md and value<RE.md['beam_intensity_expected']*0.75:
print('WARNING: Direct beam intensity ({}) lower than it should be ({})'.format(value, RE.md['beam_intensity_expected']))
# Find the step-edge
self.ysearch(step_size=0.5, min_step=0.005, intensity=value, target=0.5, verbosity=verbosity, polarity=-1)
# Find the peak
self.thsearch(step_size=0.4, min_step=0.01, target='max', verbosity=verbosity)
if step<=4:
if verbosity>=4:
print(' align: fitting')
fit_scan(smy, 1.2, 21, fit='HMi')
#time.sleep(2)
fit_scan(sth, 1.5, 21, fit='max')
#time.sleep(2)
#if step<=5:
# #fit_scan(smy, 0.6, 17, fit='sigmoid_r')
# fit_edge(smy, 0.6, 17)
# fit_scan(sth, 1.2, 21, fit='max')
if step<=8:
#fit_scan(smy, 0.3, 21, fit='sigmoid_r')
fit_edge(smy, 0.6, 21)
#time.sleep(2)
#fit_edge(smy, 0.4, 21)
fit_scan(sth, 0.8, 21, fit='COM')
#time.sleep(2)
self.setOrigin(['y', 'th'])
if step<=9 and reflection_angle is not None:
# Final alignment using reflected beam
if verbosity>=4:
print(' align: reflected beam')
get_beamline().setReflectedBeamROI(total_angle=reflection_angle*2.0)
#get_beamline().setReflectedBeamROI(total_angle=reflection_angle*2.0, size=[12,2])
self.thabs(reflection_angle)
result = fit_scan(sth, 0.2, 41, fit='max')
#result = fit_scan(sth, 0.2, 81, fit='max') #it's useful for alignment of SmarAct stage
sth_target = result.values['x_max']-reflection_angle
if result.values['y_max']>10:
th_target = self._axes['th'].motor_to_cur(sth_target)
self.thsetOrigin(th_target)
#fit_scan(smy, 0.2, 21, fit='max')
self.setOrigin(['y'])
if step<=10:
self.thabs(0.0)
beam.off()
def alignQuick(self, align_step=8, reflection_angle=0.08, verbosity=3):
get_beamline().modeAlignment()
#self.yo()
self.tho()
beam.on()
self.align(step=align_step, reflection_angle=reflection_angle, verbosity=verbosity)
def _testing_level(self, step=0,pos_x_left=-5, pos_x_right=5):
#TODO: Move this code. (This should be a property of the GIBar object.)
#level GIBar by checking bar height at pos_left and pos_right
print('checking the level of GIBar')
#if step<=1:
# cms.modeAlignment()
#sam.xabs(pos_x_left)
#fit_scan(smy, .6, 17, fit='sigmooid_r') #it's better not to move smy after scan but only the center position
#pos_y_left=smy.user_readback.value
#
#sam.xabs(pos_x_right)
#fit_scan(smy, .6, 17, fit='sigmooid_r')
#pos_y_right=smy.user_readback.value
#offset_schi=(pos_y_right-pos_y_left)/(pos_x_right-pos_x_left)
#movr(sch, offset_schi)
#double-check the chi offset
#sam.xabs(pos_x_left)
#fit_scan(smy, .6, 17, fit='sigmooid_r') #it's better not to move smy after scan but only the center position
#pos_y_left=smy.user_readback.value
#sam.xabs(pos_x_right)
#fit_scan(smy, .6, 17, fit='sigmooid_r')
#pos_y_right=smy.user_readback.value
#offset_schi=(pos_y_right-pos_y_left)/(pos_x_right-pos_x_left)
#if offset_schi<=0.1:
#print('schi offset is aligned successfully!')
#else:
#print('schi offset is WRONG. Please redo the level command')
pass
def do(self, step=0, align_step=0, **md):
if step<=1:
get_beamline().modeAlignment()
if step<=2:
self.xo() # goto origin
if step<=4:
self.yo()
self.tho()
if step<=5:
self.align(step=align_step)
#self.setOrigin(['y','th']) # This is done within align
#if step<=7:
#self.xr(0.2)
if step<=8:
get_beamline().modeMeasurement()
if step<=10:
#detselect([pilatus300, psccd])
#detselect(psccd)
#detselect(pilatus300)
detselect(pilatus2M)
for detector in get_beamline().detector:
detector.setExposureTime(self.md['exposure_time'])
self.measureIncidentAngles(self.incident_angles_default, **md)
self.thabs(0.0)
class SampleCDSAXS_Generic(Sample_Generic):
def __init__(self, name, base=None, **md):
super().__init__(name=name, base=base, **md)
self.naming_scheme = ['name', 'extra', 'phi', 'exposure_time']
self.rot_angles_default = np.arange(-45, +45+1, +1)
#self.rot_angles_default = np.linspace(-45, +45, num=90, endpoint=True)
def _set_axes_definitions(self):
'''Internal function which defines the axes for this stage. This is kept
as a separate function so that it can be over-ridden easily.'''
super()._set_axes_definitions()
self._axes_definitions.append( {'name': 'phi',
'motor': srot,
'enabled': True,
'scaling': +1.0,
'units': 'deg',
'hint': None,
} )
def measureAngle(self, angle, exposure_time=None, extra=None, measure_type='measure', **md):
self.phiabs(angle)
self.measure(exposure_time=exposure_time, extra=extra, measure_type=measure_type, **md)
def measureAngles(self, angles=None, exposure_time=None, extra=None, measure_type='measureAngles', **md):
if angles is None:
angles = self.rot_angles_default
for angle in angles:
self.measureAngle(angle, exposure_time=exposure_time, extra=extra, measure_type=measure_type, **md)
class Stage(CoordinateSystem):
pass
class SampleStage(Stage):
def __init__(self, name='SampleStage', base=None, **kwargs):
super().__init__(name=name, base=base, **kwargs)
def _set_axes_definitions(self):
'''Internal function which defines the axes for this stage. This is kept
as a separate function so that it can be over-ridden easily.'''
# The _axes_definitions array holds a list of dicts, each defining an axis
self._axes_definitions = [ {'name': 'x',
'motor': smx,
'enabled': True,
'scaling': +1.0,
'units': 'mm',
'hint': 'positive moves stage left/outboard (beam moves right on sample)',
},
{'name': 'y',
'motor': smy,
'enabled': True,
'scaling': +1.0,
'units': 'mm',
'hint': 'positive moves stage up (beam moves down on sample)',
},
{'name': 'th',
'motor': sth,
'enabled': True,
'scaling': +1.0,
'units': 'deg',
'hint': 'positive tilts clockwise (positive incident angle)',
},
]
class Holder(Stage):
'''The Holder() classes are used to define bars/stages that hold one or more
samples. This class can thus help to keep track of coordinate conversions,
to store the positions of multiple samples, and to automate the measurement
of multiple samples.'''
# Core methods
########################################
def __init__(self, name='Holder', base=None, **kwargs):
if base is None:
base = get_default_stage()
super().__init__(name=name, base=base, **kwargs)
self._samples = {}
def _set_axes_definitions(self):
'''Internal function which defines the axes for this stage. This is kept
as a separate function so that it can be over-ridden easily.'''
# The _axes_definitions array holds a list of dicts, each defining an axis
self._axes_definitions = [ {'name': 'x',
'motor': None,
'enabled': True,
'scaling': +1.0,
'units': 'mm',
'hint': 'positive moves stage left/outboard (beam moves right on sample)',
},
{'name': 'y',
'motor': None,
'enabled': True,
'scaling': +1.0,
'units': 'mm',
'hint': 'positive moves stage up (beam moves down on sample)',
},
{'name': 'th',
'motor': None,
'enabled': True,
'scaling': +1.0,
'units': 'deg',
'hint': 'positive tilts clockwise (positive incident angle)',
},
]
# Sample management
########################################
def addSample(self, sample, sample_number=None):
'''Add a sample to this holder/bar.'''
if sample_number is None:
if len(self._samples)==0:
sample_number = 1
else:
ki = [ int(key) for key in self._samples.keys() ]
sample_number = np.max(ki) + 1
if sample_number in self._samples.keys():
print('Warning: Sample number {} is already defined on holder "{:s}". Use "replaceSample" if you are sure you want to eliminate the existing sample from the holder.'.format(sample_number, self.name) )
else:
self._samples[sample_number] = sample
self._samples[sample_number] = sample
sample.set_base_stage(self)
sample.md['holder_sample_number'] = sample_number
def removeSample(self, sample_number):
'''Remove a particular sample from this holder/bar.'''
del self._samples[sample_number]
def removeSamplesAll(self):
self._samples = {}
def replaceSample(self, sample, sample_number):
'''Replace a given sample on this holder/bar with a different sample.'''
self.removeSample(sample_number)
self.addSample(sample, sample_number)
def getSample(self, sample_number, verbosity=3):
'''Return the requested sample object from this holder/bar.
One can provide an integer, in which case the corresponding sample
(from the holder's inventory) is returned. If a string is provided,
the closest-matching sample (by name) is returned.'''
if type(sample_number) is int:
if sample_number not in self._samples:
if verbosity>=1:
print('Error: Sample {} not defined.'.format(sample_number))
return None
sample_match = self._samples[sample_number]
if verbosity>=3:
print('{}: {:s}'.format(sample_number, sample_match.name))
return sample_match
elif type(sample_number) is str:
# First search for an exact name match
matches = 0
sample_match = None
sample_i_match = None
for sample_i, sample in sorted(self._samples.items()):
if sample.name==sample_number:
matches += 1
if sample_match is None:
sample_match = sample
sample_i_match = sample_i
if matches==1:
if verbosity>=3:
print('{}: {:s}'.format(sample_i_match, sample_match.name))
return sample_match
elif matches>1:
if verbosity>=2:
print('{:d} exact matches for "{:s}", returning sample {}: {:s}'.format(matches, sample_number, sample_i_match, sample_match.name))
return sample_match
# Try to find a 'start of name' match
for sample_i, sample in sorted(self._samples.items()):
if sample.name.startswith(sample_number):
matches += 1
if sample_match is None:
sample_match = sample
sample_i_match = sample_i
if matches==1:
if verbosity>=3:
print('Beginning-name match: {}: {:s}'.format(sample_i_match, sample_match.name))
return sample_match
elif matches>1:
if verbosity>=2:
print('{:d} beginning-name matches for "{:s}", returning sample {}: {:s}'.format(matches, sample_number, sample_i_match, sample_match.name))
return sample_match
# Try to find a substring match
for sample_i, sample in sorted(self._samples.items()):
if sample_number in sample.name:
matches += 1
if sample_match is None:
sample_match = sample
sample_i_match = sample_i
if matches==1:
if verbosity>=3:
print('Substring match: {}: {:s}'.format(sample_i_match, sample_match.name))
return sample_match
elif matches>1:
if verbosity>=2:
print('{:d} substring matches for "{:s}", returning sample {}: {:s}'.format(matches, sample_number, sample_i_match, sample_match.name))
return sample_match
if verbosity>=1:
print('No sample has a name matching "{:s}"'.format(sample_number))
return None
else:
print('Error: Sample designation "{}" not understood.'.format(sample_number))
return None
def getSamples(self, range=None, verbosity=3):
'''Get the list of samples associated with this holder.
If the optional range argument is provided (2-tuple), then only sample
numbers within that range (inclusive) are run. If range is instead a
string, then all samples with names that match are returned.'''
samples = []
if range is None:
for sample_number in sorted(self._samples):
samples.append(self._samples[sample_number])
elif type(range) is list:
start, stop = range
for sample_number in sorted(self._samples):
if sample_number>=start and sample_number<=stop:
samples.append(self._samples[sample_number])
elif type(range) is str:
for sample_number, sample in sorted(self._samples.items()):
if range in sample.name:
samples.append(sample)
elif type(range) is int:
samples.append(self._samples[range])
else:
if verbosity>=1:
print('Range argument "{}" not understood.'.format(range))
return samples
def listSamples(self):
'''Print a list of the current samples associated with this holder/
bar.'''
for sample_number, sample in sorted(self._samples.items()):
print( '{}: {:s}'.format(sample_number, sample.name) )
def gotoSample(self, sample_number):
sample = self.getSample(sample_number, verbosity=0)
sample.gotoAlignedPosition()
return sample
# Control methods
########################################
def setTemperature(self, temperature, verbosity=3):
#if verbosity>=1:
#print('Temperature functions not implemented in {}'.format(self.__class__.__name__))
if verbosity>=2:
print(' Changing temperature setpoint from {:.3f}°C to {:.3f}°C'.format(caget('XF:11BM-ES{Env:01-Out:1}T-SP')-273.15, temperature))
caput('XF:11BM-ES{Env:01-Out:1}T-SP', temperature+273.15)
def temperature(self, verbosity=3):
#if verbosity>=1:
#print('Temperature functions not implemented in {}'.format(self.__class__.__name__))
current_temperature = caget('XF:11BM-ES{Env:01-Chan:A}T:C-I')
if verbosity>=3:
print(' Temperature = {:.3f}°C (setpoint = {:.3f}°C)'.format( current_temperature, caget('XF:11BM-ES{Env:01-Out:1}T-SP')-273.15 ) )
return current_temperature
# Action (measurement) methods
########################################
def doSamples(self, range=None, verbosity=3, **md):
'''Activate the default action (typically measurement) for all the samples.
If the optional range argument is provided (2-tuple), then only sample
numbers within that range (inclusive) are run. If range is instead a
string, then all samples with names that match are returned.'''
for sample in self.getSamples(range=range):
if verbosity>=3:
print('Doing sample {}...'.format(sample.name))
sample.do(verbosity=verbosity, **md)
def doTemperature(self, temperature, wait_time=None, temperature_tolerance=0.4, range=None, verbosity=3, poling_period=2.0, **md):
# Set new temperature
self.setTemperature(temperature, verbosity=verbosity)
# Wait until we reach the temperature
while abs(self.temperature(verbosity=0) - temperature)>temperature_tolerance:
if verbosity>=3:
print(' setpoint = {:.3f}°C, Temperature = {:.3f}°C \r'.format(caget('XF:11BM-ES{Env:01-Out:1}T-SP')-273.15, self.temperature(verbosity=0)), end='')
time.sleep(poling_period)
# Allow for additional equilibration at this temperature
if wait_time is not None:
time.sleep(wait_time)
self.doSamples(range=range, verbosity=verbosity, **md)
def doTemperatures(self, temperatures, wait_time=None, temperature_tolerance=0.4, range=None, verbosity=3, **md):
for temperature in temperatures:
self.doTemperature(temperature, wait_time=wait_time, temperature_tolerance=temperature_tolerance, range=range, verbosity=verbosity, **md)
class PositionalHolder(Holder):
'''This class is a sample holder that is one-dimensional. E.g. a bar with a
set of samples lined up, or a holder with a set number of slots for holding
samples. This class thus helps to associate each sample with its position
on the bar.'''
# Core methods
########################################
def __init__(self, name='PositionalHolder', base=None, **kwargs):
super().__init__(name=name, base=base, **kwargs)
self._positional_axis = 'x'
self.GaragePosition=[]
# Sample management
########################################
def slot(self, sample_number):
'''Moves to the selected slot in the holder.'''
getattr(self, self._positional_axis+'abs')( self.get_slot_position(sample_number) )
def get_slot_position(self, slot):
'''Return the motor position for the requested slot number.'''
# This method should be over-ridden in sub-classes, so as to properly
# implement the positioning appropriate for that holder.
position = 0.0 + slot*1.0
return position
def addSampleSlot(self, sample, slot, detector_opt='SAXS'):
'''Adds a sample to the specified "slot" (defined/numbered sample
holding spot on this holder).'''
self.addSample(sample, sample_number=slot)
sample.setOrigin( [self._positional_axis], [self.get_slot_position(slot)] )
sample.detector=detector_opt
def addSampleSlotPosition(self, sample, slot, position, detector_opt='SAXS'):
'''Adds a sample to the specified "slot" (defined/numbered sample
holding spot on this holder).'''
self.addSample(sample, sample_number=slot)
sample.setOrigin( [self._positional_axis], [position] )
sample.detector=detector_opt
def listSamplesPositions(self):
'''Print a list of the current samples associated with this holder/
bar.'''
for sample_number, sample in self._samples.items():
#pos = getattr(sample, self._positional_axis+'pos')(verbosity=0)
pos = sample.origin(verbosity=0)[self._positional_axis]
print( '%s: %s (%s = %.3f)' % (str(sample_number), sample.name, self._positional_axis, pos) )
def listSamplesDetails(self):
'''Print a list of the current samples associated with this holder/
bar.'''
for sample_number, sample in self._samples.items():
#pos = getattr(sample, self._positional_axis+'pos')(verbosity=0)
pos = sample.origin(verbosity=0)[self._positional_axis]
print( '%s: %s (%s = %.3f) %s' % (str(sample_number), sample.name, self._positional_axis, pos, sample.detector) )
def addGaragePosition(self, shelf_num, spot_num):
'''the position in garage'''
if shelf_num not in range(1, 5) or spot_num not in range(1, 4):
print('Out of the range in Garage (4 x 3)')
self.GaragePosition=[shelf_num, spot_num]
class GIBar(PositionalHolder):
'''This class is a sample bar for grazing-incidence (GI) experiments.'''
# Core methods
########################################
def __init__(self, name='GIBar', base=None, **kwargs):
super().__init__(name=name, base=base, **kwargs)
self._positional_axis = 'x'
# Set the x and y origin to be the center of slot 8
self.xsetOrigin(-71.89405)
self.ysetOrigin(10.37925)
self.mark('right edge', x=+108.2)
self.mark('left edge', x=0)
self.mark('center', x=54.1, y=0)
def addSampleSlotPosition(self, sample, slot, position, detector_opt='SAXS', account_substrate=True):
'''Adds a sample to the specified "slot" (defined/numbered sample
holding spot on this holder).'''
super().addSampleSlotPosition(sample, slot, position)
# Adjust y-origin to account for substrate thickness
if account_substrate and 'substrate_thickness' in sample.md:
sample.ysetOrigin( -1.0*sample.md['substrate_thickness'] )
sample.detector=detector_opt
class CapillaryHolder(PositionalHolder):
'''This class is a sample holder that has 15 slots for capillaries.'''
# Core methods
########################################
def __init__(self, name='CapillaryHolder', base=None, **kwargs):
super().__init__(name=name, base=base, **kwargs)
self._positional_axis = 'x'
self.x_spacing = 6.342 # 3.5 inches / 14 spaces
# slot 1; smx = +26.60
# slot 8; smx = -17.80
# slot 15; smx = -61.94
# Set the x and y origin to be the center of slot 8
self.xsetOrigin(-17.49410+0.35)
self.ysetOrigin(-2.36985)
self.mark('right edge', x=+54.4)
self.mark('left edge', x=-54.4)
self.mark('bottom edge', y=-12.71)
self.mark('center', x=0, y=0)
def get_slot_position(self, slot):
'''Return the motor position for the requested slot number.'''
return +1*self.x_spacing*(slot-8)
class CapillaryHolderHeated(CapillaryHolder):
def update_sample_names(self):
for sample in self.getSamples():
if 'temperature' not in sample.naming_scheme:
sample.naming_scheme.insert(-1, 'temperature')
def doHeatCool(self, heat_temps, cool_temps, exposure_time=None, stabilization_time=120, temp_tolerance=0.5, step=1):
if step<=1:
for temperature in heat_temps:
try:
self.setTemperature(temperature)
while self.temperature(verbosity=0) < temperature-temp_tolerance:
time.sleep(5)
time.sleep(stabilization_time)
for sample in self.getSamples():
sample.gotoOrigin()
sample.xr(-0.05)
sample.measure(exposure_time)
except HTTPError:
pass
if step<=5:
for temperature in heat_temps:
try:
self.setTemperature(temperature)
self.setTemperature(temperature)
while self.temperature(verbosity=0) > temperature+temp_tolerance:
time.sleep(5)
time.sleep(stabilization_time)
for sample in self.getSamples():
sample.gotoOrigin()
sample.xr(0.1)
sample.measure(exposure_time)
except HTTPError:
pass
stg = SampleStage()
def get_default_stage():
return stg
if False:
# For testing:
# %run -i /opt/ipython_profiles/profile_collection/startup/94-sample.py
sam = SampleGISAXS_Generic('testing_of_code')
sam.mark('here')
#sam.mark('XY_field', 'x', 'y')
#sam.mark('specified', x=1, th=0.1)
#sam.naming(['name', 'extra', 'clock', 'th', 'exposure_time', 'id'])
#sam.thsetOrigin(0.5)
#sam.marks()
hol = CapillaryHolder(base=stg)
hol.addSampleSlot( SampleGISAXS_Generic('test_sample_01'), 1.0 )
hol.addSampleSlot( SampleGISAXS_Generic('test_sample_02'), 3.0 )
hol.addSampleSlot( SampleGISAXS_Generic('test_sample_03'), 5.0 )
sam = hol.getSample(1)<|fim▁end|> | detector.setExposureTime(exposure_time, verbosity=verbosity)
#extra wait time when changing the exposure time.
time.sleep(2) |
<|file_name|>12_strings_test.go<|end_file_name|><|fim▁begin|><|fim▁hole|>func stringGet(s string, index int) byte {
return s[index]
}
func stringLen(s string) int {
return len(s)
}
func substring(s string, low, high int) string {
switch {
case low >= 0 && high >= 0:
return s[low:high]
case low >= 0:
return s[low:]
case high >= 0:
return s[:high]
default:
return s
}
}<|fim▁end|> | package conformance
|
<|file_name|>issue-23311.rs<|end_file_name|><|fim▁begin|>// run-pass<|fim▁hole|>fn main() {
match "foo".as_bytes() {
b"food" => (),
&[b'f', ..] => (),
_ => ()
}
}<|fim▁end|> |
// Test that we do not ICE when pattern matching an array against a slice.
|
<|file_name|>OCommandExecutorFunction.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* 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.
*/
package com.orientechnologies.orient.core.command.script;
import java.util.Map;
import java.util.Map.Entry;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandExecutorAbstract;
import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx;
import com.orientechnologies.orient.core.metadata.function.OFunction;
/**
* Executes Script Commands.
*
* @see OCommandScript
* @author Luca Garulli
*
*/
public class OCommandExecutorFunction extends OCommandExecutorAbstract {
protected OCommandFunction request;
<|fim▁hole|>
@SuppressWarnings("unchecked")
public OCommandExecutorFunction parse(final OCommandRequest iRequest) {
request = (OCommandFunction) iRequest;
return this;
}
public Object execute(final Map<Object, Object> iArgs) {
return executeInContext(null, iArgs);
}
public Object executeInContext(final Map<String, Object> iContext, final Map<Object, Object> iArgs) {
parserText = request.getText();
final ODatabaseRecordTx db = (ODatabaseRecordTx) getDatabase();
final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(parserText);
final OScriptManager scriptManager = Orient.instance().getScriptManager();
final ScriptEngine scriptEngine = scriptManager.getEngine(f.getLanguage());
final Bindings binding = scriptManager.bind(scriptEngine, db, iContext, iArgs);
try {
scriptEngine.setBindings(binding, ScriptContext.ENGINE_SCOPE);
// COMPILE FUNCTION LIBRARY
scriptEngine.eval(scriptManager.getLibrary(db, f.getLanguage()));
if (scriptEngine instanceof Invocable) {
// INVOKE AS FUNCTION. PARAMS ARE PASSED BY POSITION
final Invocable invocableEngine = (Invocable) scriptEngine;
Object[] args = null;
if (iArgs != null) {
args = new Object[iArgs.size()];
int i = 0;
for (Entry<Object, Object> arg : iArgs.entrySet())
args[i++] = arg.getValue();
}
return invocableEngine.invokeFunction(parserText, args);
} else {
// INVOKE THE CODE SNIPPET
return scriptEngine.eval(invokeFunction(f, iArgs.values().toArray()), binding);
}
} catch (ScriptException e) {
throw new OCommandScriptException("Error on execution of the script", request.getText(), e.getColumnNumber(), e);
} catch (NoSuchMethodException e) {
throw new OCommandScriptException("Error on execution of the script", request.getText(), 0, e);
} finally {
scriptManager.unbind(binding);
}
}
public boolean isIdempotent() {
return false;
}
@Override
protected void throwSyntaxErrorException(String iText) {
throw new OCommandScriptException("Error on execution of the script: " + iText, request.getText(), 0);
}
protected String invokeFunction(final OFunction f, Object[] iArgs) {
final StringBuilder code = new StringBuilder();
code.append(f.getName());
code.append('(');
int i = 0;
for (Object a : iArgs) {
if (i++ > 0)
code.append(',');
code.append(a);
}
code.append(");");
return code.toString();
}
}<|fim▁end|> |
public OCommandExecutorFunction() {
}
|
<|file_name|>NonNCEPModel.py<|end_file_name|><|fim▁begin|>import time
from bs4 import BeautifulSoup
import sys
if (sys.version_info > (3, 0)):
# Python 3 code in this block
import urllib.request as urllib2
else:
# Python 2 code in this block<|fim▁hole|> import urllib2
import datetime, re, os
class NonNCEPModel:
'''''
Base Class for all Non-NCEP models.
'''''
def __init__(self):
self.modelUrls = ''
self.isNCEPSource = False
return
'''''
Gets the previous forecast hour for a given model, and forecast hour.
'''''
def getPreviousTime(self, model, currentHour):
if currentHour == '000':
return '000'
defaultHours = self.getDefaultHours()
defaultHours.sort() #assert ascending order
for (idx,hour) in enumerate(defaultHours):
if currentHour == hour:
return defaultHours[idx-1]
return '000'
'''''
Intialze all of our models hour stamp data to defaults.
'''''
def setDefaultHours(self):
# Default times.
self.modelTimes = self.defaultTimes
return
'''''
Intialze all of our models hour stamp data to defaults.
'''''
def getDefaultHours(self):
# Default times.
return self.defaultTimes
'''''
Intialze all of our models hour stamp data to defaults.
'''''
def getDefaultHours(self):
# Default times.
modelTimes = self.defaultTimes
return modelTimes
def getName(self):
return self.name
def getAlias(self):
if self.modelAliases != "":
return self.modelAlias
else:
return self.name
def getForecastHourInt(self, filename, noPrefix = False):
fhour = self.getForecastHour(filename, noPrefix)
return int(fhour[1:])
def getForecastHour(self, fileName, noPrefix = False):
return ""
def getLastForecastHour(self):
return "000"
def getRun(self):
return
def getName(self):
return self.name<|fim▁end|> | |
<|file_name|>bitcoin_ne.ts<|end_file_name|><|fim▁begin|><TS language="ne" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>ठेगाना वा लेबल सम्पादन गर्न दायाँ-क्लिक गर्नुहोस्</translation>
</message>
<message>
<source>Create a new address</source>
<translation>नयाँ ठेगाना सिर्जना गर्नुहोस्</translation>
</message>
<message>
<source>&New</source>
<translation>&amp;नयाँ</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>भर्खरै चयन गरेको ठेगाना प्रणाली क्लिपबोर्डमा कपी गर्नुहोस्</translation>
</message>
<message>
<source>&Copy</source>
<translation>&amp;कपी गर्नुहोस्</translation>
</message>
<message>
<source>C&lose</source>
<translation>बन्द गर्नुहोस्</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>भर्खरै चयन गरेको ठेगाना सूचीबाट मेटाउनुहोस्</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>वर्तमान ट्याबको डाटालाई फाइलमा निर्यात गर्नुहोस्</translation>
</message>
<message>
<source>&Export</source>
<translation>&amp;निर्यात गर्नुहोस्</translation>
</message>
<message>
<source>&Delete</source>
<translation>&amp;मेटाउनुहोस्</translation>
</message>
<message>
<source>C&hoose</source>
<translation>छनौट गर्नुहोस्...</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>पठाउने ठेगानाहरू...</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>प्राप्त गर्ने ठेगानाहरू...</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>ठेगाना कपी गर्नुहोस्</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>पासफ्रेज संवाद</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>पासफ्रेज प्रवेश गर्नुहोस्</translation>
</message>
<message>
<source>New passphrase</source>
<translation>नयाँ पासफ्रेज</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>नयाँ पासफ्रेज दोहोर्याउनुहोस्</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>IP/Netmask</source>
<translation>IP/नेटमास्क</translation>
</message>
<message>
<source>Banned Until</source>
<translation>प्रतिबन्धित समय</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>सन्देशमा &amp;हस्ताक्षर गर्नुहोस्...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>नेटवर्कमा समिकरण हुँदै...</translation>
</message>
<message><|fim▁hole|> <source>Show general overview of wallet</source>
<translation>वालेटको साधारण शारांश देखाउनुहोस्</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&amp;कारोबार</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>कारोबारको इतिहास हेर्नुहोस्</translation>
</message>
<message>
<source>E&xit</source>
<translation>बाहिर निस्कनुहोस्</translation>
</message>
<message>
<source>Quit application</source>
<translation>एप्लिकेसन बन्द गर्नुहोस्</translation>
</message>
<message>
<source>&About %1</source>
<translation>&amp;बारेमा %1</translation>
</message>
<message>
<source>Show information about %1</source>
<translation>%1 को बारेमा सूचना देखाउनुहोस्</translation>
</message>
<message>
<source>About &Qt</source>
<translation>&amp;Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Qt को बारेमा सूचना देखाउनुहोस्</translation>
</message>
<message>
<source>&Options...</source>
<translation>&amp;विकल्प...</translation>
</message>
<message>
<source>Modify configuration options for %1</source>
<translation>%1 का लागि कन्फिगुरेसनको विकल्प परिमार्जन गर्नुहोस</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&amp;वालेटलाई इन्क्रिप्ट गर्नुहोस्...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&amp;वालेटलाई ब्याकअप गर्नुहोस्...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&amp;पासफ्रेज परिवर्तन गर्नुहोस्...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>URI &amp;खोल्नुहोस्...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>डिस्कमा ब्लकलाई पुनः सूचीकरण गरिँदै...</translation>
</message>
<message>
<source>Send coins to a Bitcoin address</source>
<translation>बिटकोइन ठेगानामा सिक्का पठाउनुहोस्</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>वालेटलाई अर्को ठेगानामा ब्याकअप गर्नुहोस्</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>वालेट इन्क्रिप्सनमा प्रयोग हुने इन्क्रिप्सन पासफ्रेज परिवर्तन गर्नुहोस्</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount</source>
<translation>रकम</translation>
</message>
<message>
<source>Copy address</source>
<translation>ठेगाना कपी गर्नुहोस्</translation>
</message>
</context>
<context>
<name>CreateWalletActivity</name>
</context>
<context>
<name>CreateWalletDialog</name>
</context>
<context>
<name>EditAddressDialog</name>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
</context>
<context>
<name>Intro</name>
</context>
<context>
<name>ModalOverlay</name>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OpenWalletActivity</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>इन्टरफेसमा र सिक्का पठाउँदा देखिने डिफल्ट उपविभाजन एकाइ चयन गर्नुहोस् ।</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source>
<translation>देखाइएको सूचना पूरानो हुन सक्छ । कनेक्सन स्थापित भएपछि, तपाईंको वालेट बिटकोइन नेटवर्कमा स्वचालित रूपमा समिकरण हुन्छ , तर यो प्रक्रिया अहिले सम्म पूरा भएको छैन ।</translation>
</message>
<message>
<source>Watch-only:</source>
<translation>हेर्ने-मात्र:</translation>
</message>
<message>
<source>Available:</source>
<translation>उपलब्ध:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>तपाईंको खर्च गर्न मिल्ने ब्यालेन्स</translation>
</message>
<message>
<source>Pending:</source>
<translation>विचाराधिन:</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>अझै पुष्टि हुन बाँकी र खर्च गर्न मिल्ने ब्यालेन्समा गणना गर्न नमिल्ने जम्मा कारोबार</translation>
</message>
<message>
<source>Immature:</source>
<translation>अपरिपक्व:</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>अझै परिपक्व नभएको खनन गरिएको ब्यालेन्स</translation>
</message>
<message>
<source>Balances</source>
<translation>ब्यालेन्स</translation>
</message>
<message>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation>अहिलेसम्म परिपक्व नभएको खनन गरिएको, हेर्ने-मात्र ठेगानामा रहेको ब्यालेन्स</translation>
</message>
<message>
<source>Current total balance in watch-only addresses</source>
<translation>हेर्ने-मात्र ठेगानामा रहेको हालको जम्मा ब्यालेन्स</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>प्रयोगकर्ता एजेन्ट</translation>
</message>
<message>
<source>Node/Service</source>
<translation>नोड/सेव</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>रकम</translation>
</message>
<message>
<source>Enter a Bitcoin address (e.g. %1)</source>
<translation>कृपया बिटकोइन ठेगाना प्रवेश गर्नुहोस् (उदाहरण %1)</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>User Agent</source>
<translation>प्रयोगकर्ता एजेन्ट</translation>
</message>
<message>
<source>Ping Time</source>
<translation>पिङ समय</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Amount</source>
<translation>रकम</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Choose...</source>
<translation>छनौट गर्नुहोस्...</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>Choose previously used address</source>
<translation>पहिला प्रयोग गरिएको ठेगाना प्रयोग गर्नुहोस्</translation>
</message>
<message>
<source>The fee will be deducted from the amount being sent. The recipient will receive less bitcoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source>
<translation>पठाइँदै गरेको रकमबाट शुल्क कटौती गरिनेछ । प्राप्तकर्ताले तपाईंले रकम क्षेत्रमा प्रवेष गरेको भन्दा थोरै बिटकोइन प्राप्त गर्ने छन् । धेरै प्राप्तकर्ता चयन गरिएको छ भने समान रूपमा शुल्क विभाजित गरिनेछ ।</translation>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>यो ठेगानालाई प्रयोग गरिएको ठेगानाको सूचीमा थप्न एउटा लेबल प्रविष्ट गर्नुहोस्</translation>
</message>
<message>
<source>A message that was attached to the bitcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Bitcoin network.</source>
<translation>बिटकोइनमा संलग्न गरिएको सन्देश: तपाईंको मध्यस्थको लागि कारोबारको साथमा भण्डारण गरिने URI । नोट: यो सन्देश बिटकोइन नेटवर्क मार्फत पठाइने छैन ।</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>You can sign messages/agreements with your addresses to prove you can receive bitcoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>आफ्नो ठेगानामा पठाइएको बिटकोइन प्राप्त गर्न सकिन्छ भनेर प्रमाणित गर्न तपाईंले ती ठेगानाले सन्देश/सम्झौताहरूमा हस्ताक्षर गर्न सक्नुहुन्छ । फिसिङ आक्रमणले तपाईंलाई छक्याएर अरूका लागि तपाईंको परिचयमा हस्ताक्षर गराउने प्रयास गर्न सक्ने भएकाले अस्पष्ट वा जथाभावीमा हस्ताक्षर गर्दा ध्यान दिनुहोस् । आफू सहमत भएको पूर्ण विस्तृत-कथनमा मात्र हस्ताक्षर गर्नुहोस् ।</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>पहिला प्रयोग गरिएको ठेगाना प्रयोग गर्नुहोस्</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>वर्तमान हस्ताक्षरलाई प्रणाली क्लिपबोर्डमा कपी गर्नुहोस्</translation>
</message>
<message>
<source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source>
<translation>सन्देश प्रमाणित गर्न, तल दिइएको स्थानमा प्राप्तकर्ता ठेगाना, सन्देश (लाइन ब्रेक, स्पेस, ट्याब, आदि उस्तै गरी कपी गर्ने कुरा सुनिश्चित गर्नुहोस्) र हस्ताक्षर &apos;s प्रविष्ट गर्नुहोस् । बीचमा-मानिसको-आक्रमणबाट बच्न हस्ताक्षर पढ्दा हस्ताक्षर गरिएको सन्देशमा जे छ त्यो भन्दा धेरै कुरामा ध्यान नदिनुहोस् । यो कार्यले हस्ताक्षर गर्ने पक्षले मात्र यो ठेगानाले प्राप्त गर्छ भन्ने कुरा प्रमाणित गर्छ, यसले कुनै पनि कारोबारको प्रेषककर्तालाई प्रमाणित गर्न सक्दैन भन्ने कुरा याद गर्नुहोस्!</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Amount</source>
<translation>रकम</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Copy address</source>
<translation>ठेगाना कपी गर्नुहोस्</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletController</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&amp;निर्यात गर्नुहोस्</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>वर्तमान ट्याबको डाटालाई फाइलमा निर्यात गर्नुहोस्</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source>
<translation>ब्लक डाटाबेसमा भविष्यबाट आए जस्तो देखिने एउटा ब्लक हुन्छ । तपाईंको कम्प्युटरको मिति र समय गलत तरिकाले सेट गरिएकाले यस्तो हुन सक्छ । तपाईं आफ्नो कम्प्युटरको मिति र समय सही छ भनेर पक्का हुनुहुन्छ भने मात्र ब्लक डाटाबेस पुनर्निर्माण गर्नुहोस् ।</translation>
</message>
<message>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>यो जारी गर्नु पूर्वको परीक्षण संस्करण हो - आफ्नै जोखिममा प्रयोग गर्नुहोस् - खनन वा व्यापारीक प्रयोगको लागि प्रयोग नगर्नुहोस</translation>
</message>
<message>
<source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source>
<translation>प्रि-फर्क अवस्थामा डाटाबेस रिवाइन्ड गर्न सकिएन । तपाईंले फेरि ब्लकचेन डाउनलोड गर्नु पर्ने हुन्छ</translation>
</message>
<message>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation>चेतावनी: नेटवर्क पूरै तरिकाले सहमत छैन जस्तो देखिन्छ! केही खननकर्ताहरूले समस्या भोगिरहेका छन् जस्तो देखिन्छ ।</translation>
</message>
<message>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>चेतावनी: हामी हाम्रा सहकर्मीहरूसँग पूर्णतया सहमत छैनौं जस्तो देखिन्छ! तपाईंले अपग्रेड गर्नु पर्ने हुनसक्छ वा अरू नोडहरूले अपग्रेड गर्नु पर्ने हुनसक्छ ।</translation>
</message>
<message>
<source>%s corrupt, salvage failed</source>
<translation>%s मा क्षति, बचाव विफल भयो</translation>
</message>
<message>
<source>-maxmempool must be at least %d MB</source>
<translation>-maxmempool कम्तिमा %d MB को हुनुपर्छ ।</translation>
</message>
<message>
<source>Cannot resolve -%s address: '%s'</source>
<translation>-%s ठेगाना: &apos;%s&apos; निश्चय गर्न सकिँदैन</translation>
</message>
<message>
<source>Change index out of range</source>
<translation>सूचकांक परिवर्तन सीमा भन्दा बाहर</translation>
</message>
<message>
<source>Copyright (C) %i-%i</source>
<translation>सर्वाधिकार (C) %i-%i</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>क्षति पुगेको ब्लक डाटाबेस फेला पर</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>तपाईं अहिले ब्लक डेटाबेस पुनर्निर्माण गर्न चाहनुहुन्छ ?</translation>
</message>
<message>
<source>Unable to bind to %s on this computer. %s is probably already running.</source>
<translation>यो कम्प्युटरको %s मा बाँध्न सकिएन । %s सम्भवित रूपमा पहिलैबाट चलिरहेको छ ।</translation>
</message>
<message>
<source>User Agent comment (%s) contains unsafe characters.</source>
<translation>प्रयोगकर्ता एजेन्टको टिप्पणी (%s) मा असुरक्षित अक्षरहरू छन् ।</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>ब्लक प्रमाणित गरिँदै...</translation>
</message>
<message>
<source>Wallet needed to be rewritten: restart %s to complete</source>
<translation>वालेट फेरि लेख्नु आवश्यक छ: पूरा गर्न %s लाई पुन: सुरु गर्नुहोस्</translation>
</message>
<message>
<source>Error: Listening for incoming connections failed (listen returned error %s)</source>
<translation>त्रुटि: आगमन कनेक्सनमा सुन्ने कार्य असफल भयो (सुन्ने कार्यले त्रुटि %s फर्कायो)</translation>
</message>
<message>
<source>Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source>
<translation>maxtxfee=&lt;रकम&gt;: का लागि अमान्य रकम &apos;%s&apos; (कारोबारलाई अड्कन नदिन अनिवार्य रूपमा कम्तिमा %s को न्यूनतम रिले शुल्क हुनु पर्छ)</translation>
</message>
<message>
<source>The transaction amount is too small to send after the fee has been deducted</source>
<translation>कारोबार रकम शुल्क कटौती गरेपछि पठाउँदा धेरै नै सानो हुन्छ</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source>
<translation>तपाईंले काटछाँट नगरेको मोडमा जान पुनः सूचकांक प्रयोग गरेर डाटाबेस पुनर्निर्माण गर्नु पर्ने हुन्छ । यसले सम्पूर्ण ब्लकचेनलाई फेरि डाउनलोड गर्नेछ</translation>
</message>
</context>
</TS><|fim▁end|> | <source>&Overview</source>
<translation>शारांश</translation>
</message>
<message> |
<|file_name|>search_yt.py<|end_file_name|><|fim▁begin|>import urllib
import urllib2
from bs4 import BeautifulSoup
textToSearch = 'gorillaz'
query = urllib.quote(textToSearch)<|fim▁hole|>url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
print 'https://www.youtube.com' + vid['href']<|fim▁end|> | |
<|file_name|>utility.py<|end_file_name|><|fim▁begin|>"""<|fim▁hole|>
def extract_traceback(exception):
"""
Utility function for extracting the traceback from an exception.
:param exception: The exception to extract the traceback from.
:return: The extracted traceback.
"""
return ''.join(traceback.format_tb(exception.__traceback__))<|fim▁end|> | The utility module.
"""
import traceback |
<|file_name|>base_extension_test.py<|end_file_name|><|fim▁begin|>"""Tests for base extension."""
import unittest<|fim▁hole|>
class BaseExtensionTestCase(unittest.TestCase):
"""Test the base extension."""
def test_config_disabled(self):
"""Uses the disabled config."""
ext = base_extension.BaseExtension(None, {
'disabled': [
'a',
],
'enabled': [
'a',
],
})
self.assertFalse(ext.hooks.is_enabled('a'))
self.assertFalse(ext.hooks.is_enabled('b'))
def test_config_enabled(self):
"""Uses the enabled config."""
ext = base_extension.BaseExtension(None, {
'enabled': [
'a',
],
})
self.assertTrue(ext.hooks.is_enabled('a'))
self.assertFalse(ext.hooks.is_enabled('b'))<|fim▁end|> | from grow.extensions import base_extension
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
datadir = os.path.dirname(__file__)
with open(os.path.join(datadir, 'README.rst')) as f:
readme = f.read()
with open(os.path.join(datadir, 'HISTORY.rst')) as f:
history = f.read().replace('.. :changelog:', '')
class PyTestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py', '-v'])
raise SystemExit(errno)
#data_files = [(path, [os.path.join(path, f) for f in files])
# for dir, dirs, files in os.walk(datadir)]
#print(data_files)
setup(
name='provis',
version='0.1.1',
description=(
'Infrastructure Provisioning Scripts, Configuration, and Tests'),
long_description=readme + '\n\n' + history,
author='Wes Turner',
author_email='wes@wrd.nu',
url='https://github.com/westurner/provis',
packages=[
'provis',
],
package_dir={'provis': 'provis'},
include_package_data=True,
#data_files = data_files,
install_requires=[
],
license="BSD",
zip_safe=False,
keywords='provis',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
test_suite='tests',
tests_require=['pytest', 'pytest-capturelog'],
cmdclass = {
'test': PyTestCommand,
},
)<|fim▁end|> | # -*- coding: utf-8 -*-
import os
import sys |
<|file_name|>indexer.py<|end_file_name|><|fim▁begin|>import pyes
import os
from models import *
from sqlalchemy import select
from downloader import download
import utils
import re
import time
class Search(object):
def __init__(self,host,index,map_name,mapping=None,id_key=None):
self.es = pyes.ES(host)
self.index = index
self.map_name = map_name
self.mapping = mapping
self.id_key = id_key
def create_index(self):
self.es.create_index_if_missing(self.index)
if self.mapping:
if self.id_key:
self.es.put_mapping(self.map_name,{
self.map_name:{
'_id':{
'path':self.id_key
},
'properties':self.mapping}
},[self.index])
else:
self.es.put_mapping(self.map_name,{
self.map_name:{
'properties':self.mapping
}
},[self.index])
self.es.refresh(self.index)
def index_item(self,item):
self.es.index(item,self.index,self.map_name)
self.es.refresh(self.index)
def convert_to_document(revision):
temp = {}
rev_key = [ i for i in dir(revision) if not re.match('^_',i) ]
bill_key = [ i for i in dir(revision.bill) if not re.match('^_',i) ]
for key in rev_key:
if key != 'metadata' and key != 'bill':
temp[key] = getattr(revision,key)
for key in bill_key:
if key != 'metadata' and key!='id' and key!='bill_revs':
temp[key] = getattr(revision.bill,key)
full_path = download(temp['url'])
if full_path:
temp['document'] = pyes.file_to_attachment(full_path)
return temp
def initial_index():
host = '127.0.0.1:9200'
index = 'bill-index'
map_name = 'bill-type'
mapping = {
'document':{
'type':'attachment',
'fields':{
"title" : { "store" : "yes" },
"file" : {
"term_vector":"with_positions_offsets",
"store":"yes"
}
}
},
'name':{
'type':'string',
'store':'yes',
'boost':1.0,
'index':'analyzed'
},
'long_name':{
'type':'string',
'store':'yes',
'boost':1.0,
'index':'analyzed'
},
'status':{
'type':'string',
'store':'yes',
},
'year':{
'type':'integer',
'store':'yes'
},
'read_by':{
'type':'string',
'store':'yes',
'index':'analyzed'
},
'date_presented':{
'type':'date',
'store':'yes'
},
'bill_id':{
'type':'integer',
'store':'yes'
},
'id':{
'type':'integer',
'store':'yes'
}
}
search = Search(host,index,map_name,mapping)
search.create_index()
initdb()
session = DBSession()
revision = (session.query(BillRevision)
.join((BillRevision.bill,Bill)).all()
)
for rev in revision:
temp = convert_to_document(rev)
search.index_item(temp)
time.sleep(5)<|fim▁hole|>def index_single(rev_id):
host = '127.0.0.1:9200'
index = 'bill-index'
map_name = 'bill-type'
initdb()
session = DBSession()
revision = (session.query(BillRevision).get(rev_id)
)
temp = convert_to_document(revision)
search = Search(host,index,map_name)
search.index_item(temp)
if __name__ == '__main__':
initial_index()<|fim▁end|> | |
<|file_name|>UIAsset.js<|end_file_name|><|fim▁begin|>/**
* Symbol Art Editor
*
* @author malulleybovo (since 2021)
* @license GNU General Public License v3.0
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2021 Arthur Malulley B. de O.
*
*
* The JavaScript code in this page is free software: you can
* redistribute it and/or modify it under the terms of the GNU
* General Public License (GNU GPL) as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. The code is distributed WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
*
* As additional permission under GNU GPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* @licend The above is the entire license notice
* for the JavaScript code in this page.
*
*/
class UIAsset extends UIView {
get viewPath() { return 'res/templates/asset.html' }
_onTap = null;
get onTap() { return this._onTap }
set onTap(value) {
if (typeof value !== 'function' && value !== null) return;
this._onTap = value;
}
get assetFilePath() {
return this.view.attr('src');
}
_resourceLoaded = false;
get loaded() {
return this.view instanceof jQuery
&& this.view[0] instanceof HTMLElement
&& this._resourceLoaded;
}
constructor({ filePath = null } = {}) {
super();
let path = filePath;
this.didLoad(_ => {
this.view.on('load', _ => {
this._resourceLoaded = true;
});<|fim▁hole|> this.gestureRecognizer = new UITapGestureRecognizer({
targetHtmlElement: this.view[0], onTap: () => {
if (this._onTap) {
this._onTap(this);
}
}
});
});
}
}<|fim▁end|> | this.view.attr('src', path); |
<|file_name|>accounts.py<|end_file_name|><|fim▁begin|>"""
sentry.web.frontend.accounts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import itertools
from django.contrib import messages
from django.contrib.auth import login as login_user, authenticate
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.db import transaction
from django.http import HttpResponseRedirect
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.utils import timezone
from sudo.decorators import sudo_required
from sentry import features
from sentry.models import (
AuthProvider, LostPasswordHash, Organization, OrganizationMemberType,
Project, Team, UserOption
)
from sentry.plugins import plugins
from sentry.web.decorators import login_required
from sentry.web.forms.accounts import (
AccountSettingsForm, NotificationSettingsForm, AppearanceSettingsForm,
RegistrationForm, RecoverPasswordForm, ChangePasswordRecoverForm,
ProjectEmailOptionsForm)
from sentry.web.helpers import render_to_response
from sentry.utils.auth import get_auth_providers, get_login_redirect
from sentry.utils.safe import safe_execute
@csrf_protect
@never_cache
@transaction.atomic
def register(request):
from django.conf import settings
if not (features.has('auth:register') or request.session.get('can_register')):
return HttpResponseRedirect(reverse('sentry'))
form = RegistrationForm(request.POST or None,
captcha=bool(request.session.get('needs_captcha')))
if form.is_valid():
user = form.save()
# TODO(dcramer): ideally this would be handled by a special view
# specifically for organization registration
if settings.SENTRY_SINGLE_ORGANIZATION:
org = Organization.get_default()
defaults = {
'has_global_access': True,
'type': OrganizationMemberType.MEMBER,
}
try:
auth_provider = AuthProvider.objects.get(
organization=org.id,
)
except AuthProvider.DoesNotExist:
pass
else:
defaults.update({
'has_global_access': auth_provider.default_global_access,
'type': auth_provider.default_role,
})<|fim▁hole|> )
# can_register should only allow a single registration
request.session.pop('can_register', None)
# HACK: grab whatever the first backend is and assume it works
user.backend = settings.AUTHENTICATION_BACKENDS[0]
login_user(request, user)
request.session.pop('needs_captcha', None)
return login_redirect(request)
elif request.POST and not request.session.get('needs_captcha'):
request.session['needs_captcha'] = 1
form = RegistrationForm(request.POST or None, captcha=True)
form.errors.pop('captcha', None)
return render_to_response('sentry/register.html', {
'form': form,
}, request)
@login_required
def login_redirect(request):
login_url = get_login_redirect(request)
return HttpResponseRedirect(login_url)
def recover(request):
form = RecoverPasswordForm(request.POST or None,
captcha=bool(request.session.get('needs_captcha')))
if form.is_valid():
password_hash, created = LostPasswordHash.objects.get_or_create(
user=form.cleaned_data['user']
)
if not password_hash.is_valid():
password_hash.date_added = timezone.now()
password_hash.set_hash()
password_hash.save()
password_hash.send_recover_mail()
request.session.pop('needs_captcha', None)
return render_to_response('sentry/account/recover/sent.html', {
'email': password_hash.user.email,
}, request)
elif request.POST and not request.session.get('needs_captcha'):
request.session['needs_captcha'] = 1
form = RecoverPasswordForm(request.POST or None, captcha=True)
form.errors.pop('captcha', None)
context = {
'form': form,
}
return render_to_response('sentry/account/recover/index.html', context, request)
def recover_confirm(request, user_id, hash):
try:
password_hash = LostPasswordHash.objects.get(user=user_id, hash=hash)
if not password_hash.is_valid():
password_hash.delete()
raise LostPasswordHash.DoesNotExist
user = password_hash.user
except LostPasswordHash.DoesNotExist:
context = {}
tpl = 'sentry/account/recover/failure.html'
else:
tpl = 'sentry/account/recover/confirm.html'
if request.method == 'POST':
form = ChangePasswordRecoverForm(request.POST)
if form.is_valid():
user.set_password(form.cleaned_data['password'])
user.save()
# Ugly way of doing this, but Django requires the backend be set
user = authenticate(
username=user.username,
password=form.cleaned_data['password'],
)
login_user(request, user)
password_hash.delete()
return login_redirect(request)
else:
form = ChangePasswordRecoverForm()
context = {
'form': form,
}
return render_to_response(tpl, context, request)
@csrf_protect
@never_cache
@login_required
@sudo_required
@transaction.atomic
def settings(request):
form = AccountSettingsForm(request.user, request.POST or None, initial={
'email': request.user.email,
'username': request.user.username,
'first_name': request.user.first_name,
})
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS, 'Your settings were saved.')
return HttpResponseRedirect(request.path)
context = csrf(request)
context.update({
'form': form,
'page': 'settings',
'AUTH_PROVIDERS': get_auth_providers(),
})
return render_to_response('sentry/account/settings.html', context, request)
@csrf_protect
@never_cache
@login_required
@sudo_required
@transaction.atomic
def appearance_settings(request):
from django.conf import settings
options = UserOption.objects.get_all_values(user=request.user, project=None)
form = AppearanceSettingsForm(request.user, request.POST or None, initial={
'language': options.get('language') or request.LANGUAGE_CODE,
'stacktrace_order': int(options.get('stacktrace_order', -1) or -1),
'timezone': options.get('timezone') or settings.SENTRY_DEFAULT_TIME_ZONE,
})
if form.is_valid():
form.save()
messages.add_message(request, messages.SUCCESS, 'Your settings were saved.')
return HttpResponseRedirect(request.path)
context = csrf(request)
context.update({
'form': form,
'page': 'appearance',
'AUTH_PROVIDERS': get_auth_providers(),
})
return render_to_response('sentry/account/appearance.html', context, request)
@csrf_protect
@never_cache
@login_required
@sudo_required
@transaction.atomic
def notification_settings(request):
settings_form = NotificationSettingsForm(request.user, request.POST or None)
# TODO(dcramer): this is an extremely bad pattern and we need a more optimal
# solution for rendering this (that ideally plays well with the org data)
project_list = []
organization_list = Organization.objects.get_for_user(
user=request.user,
)
for organization in organization_list:
team_list = Team.objects.get_for_user(
user=request.user,
organization=organization,
)
for team in team_list:
project_list.extend(
Project.objects.get_for_user(
user=request.user,
team=team,
)
)
project_forms = [
(project, ProjectEmailOptionsForm(
project, request.user,
request.POST or None,
prefix='project-%s' % (project.id,)
))
for project in sorted(project_list, key=lambda x: (x.team.name, x.name))
]
ext_forms = []
for plugin in plugins.all():
for form in safe_execute(plugin.get_notification_forms) or ():
form = safe_execute(form, plugin, request.user, request.POST or None, prefix=plugin.slug)
if not form:
continue
ext_forms.append(form)
if request.POST:
all_forms = list(itertools.chain(
[settings_form], ext_forms, (f for _, f in project_forms)
))
if all(f.is_valid() for f in all_forms):
for form in all_forms:
form.save()
messages.add_message(request, messages.SUCCESS, 'Your settings were saved.')
return HttpResponseRedirect(request.path)
context = csrf(request)
context.update({
'settings_form': settings_form,
'project_forms': project_forms,
'ext_forms': ext_forms,
'page': 'notifications',
'AUTH_PROVIDERS': get_auth_providers(),
})
return render_to_response('sentry/account/notifications.html', context, request)
@csrf_protect
@never_cache
@login_required
def list_identities(request):
from social_auth.models import UserSocialAuth
identity_list = list(UserSocialAuth.objects.filter(user=request.user))
AUTH_PROVIDERS = get_auth_providers()
context = csrf(request)
context.update({
'identity_list': identity_list,
'page': 'identities',
'AUTH_PROVIDERS': AUTH_PROVIDERS,
})
return render_to_response('sentry/account/identities.html', context, request)<|fim▁end|> |
org.member_set.create(
user=user,
**defaults |
<|file_name|>default_module_exceptions.py<|end_file_name|><|fim▁begin|>"""
Copyright 2009 55 Minutes (http://www.55minutes.com)
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.
"""
import time
<|fim▁hole|><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Test coverage report: %(title)s</title>
<style type="text/css" media="screen">
body
{
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size: 13px;
}
#content-header
{
margin-left: 50px;
}
#content-header h1
{
font-size: 18px;
margin-bottom: 0;
}
#content-header p
{
font-size: 13px;
margin: 0;
color: #909090;
}
#result-list
{
margin: 0 50px;
}
#result-list ul
{
padding-left: 13px;
list-style-position: inside;
}
</style>
</head>
<body>
"""
CONTENT_HEADER = """\
<div id="content-header">
<h1>Test Coverage Report: %(title)s</h1>"""
CONTENT_HEADER += "<p>Generated: %(test_timestamp)s</p>" %vars()
CONTENT_HEADER += "</div>"
CONTENT_BODY = """\
<div id="result-list">
<p>%(long_desc)s</p>
<ul>
%(exception_list)s
</ul>
Back to <a href="index.html">index</a>.
</div>
"""
EXCEPTION_LINE = "<li>%(module_name)s</li>"
BOTTOM = """\
</body>
</html>
"""<|fim▁end|> | test_timestamp = time.strftime('%a %Y-%m-%d %H:%M %Z')
TOP = """\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
<|file_name|>ipfs-util.js<|end_file_name|><|fim▁begin|>module.exports = IpfsUtil;
var fs = require('fs');
var formstream = require('formstream');
var http = require('http');
var request = require('request');
function IpfsUtil() {
}
IpfsUtil.prototype.init = function (config) {
this.__host = config.ipfs.host;
this.__port = config.ipfs.port;
};
IpfsUtil.prototype.getTar = function (key, toFile, callback) {
var self = this;
var uri = 'http://' + self.__host + ':' + self.__port + '/api/v0/tar/cat?arg=' + key;
console.log(uri);
request
.get(uri)
.on('end', function () {
console.log('GET request ended....');
callback();
}).on('error', function (err) {
console.log('ERROR: ', err);
return callback(err);
})
.pipe(fs.createWriteStream(toFile));
};
IpfsUtil.prototype.uploadTar = function (filePath, callback) {
var self = this;
var form = formstream();
form.file('file', filePath);<|fim▁hole|> var options = {
method: 'POST',
host: self.__host,
port: self.__port,
path: '/api/v0/tar/add',
headers: form.headers()
};
console.log(options);
var req = http.request(options, function (res) {
res.on('data', function (data) {
console.log(data);
callback(null, (JSON.parse(data)).Hash);
});
//res.on('end', function () {
// console.log('Request ended...');
// callback();
//});
res.on('error', function (err) {
console.log(err);
return callback(err);
})
});
form.pipe(req);
};<|fim▁end|> | |
<|file_name|>GuiRobotState.java<|end_file_name|><|fim▁begin|>package jaci.openrio.toast.core.loader.simulation;
import jaci.openrio.toast.lib.state.RobotState;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Rectangle2D;
/**
* A GUI Element for switching the Robot State during Simulation
*
* @author Jaci
*/
public class GuiRobotState extends JComponent implements MouseListener {
RobotState state;
int x, y;
int width = 100;
int height = 30;
static final Color bgPassive = new Color(20, 20, 20);
static final Color bgClicked = new Color(11, 11, 11);
static final Color fgPassive = new Color(100, 100, 100);
public GuiRobotState(int x, int y, RobotState state, JPanel parent) {
this.x = x;
this.y = y;
this.state = state;
this.setBounds(x, y, width, height);
parent.add(this);
parent.addMouseListener(this);
this.setBackground(bgPassive);
this.setForeground(fgPassive);
}
/**
* Paints the component. This calls the super as well as calling the second 'paint()' method that will
* draw the button based on the state given in {@link SimulationData}
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
paint((Graphics2D) g);
}
/**
* Paints the object with the new Graphics2D object. This takes data from the {@link SimulationData} class in order
* to paint the correct button.
*/
public void paint(Graphics2D g) {
g.setColor(this.getBackground());
g.fillRect(0, 0, width, height);
g.setColor(SimulationData.currentState == state ? new Color(100, 170, 100) : this.getForeground());
FontMetrics metrics = g.getFontMetrics();
Rectangle2D textBounds = metrics.getStringBounds(state.state, g);
g.drawString(state.state, (float) ((width - textBounds.getWidth()) / 2), (float) ((height - textBounds.getHeight()) / 2 + metrics.getAscent()));
}
/**
* Does a check for whether or not the Mouse exists within the bounds of the button.
*/
public boolean inBounds(MouseEvent e) {
return e.getX() > x && e.getX() < x + width && e.getY() > y && e.getY() < y + height;
}
/**
* Apply this button
*/
public void apply() {
SimulationData.currentState = this.state;
repaint();
}
/**
* Stub Method - Not Used
*/
@Override
public void mouseClicked(MouseEvent e) {
}
/**
* Serves to change the colour of the button to indicate it being depressed.
*/
@Override
public void mousePressed(MouseEvent e) {
if (inBounds(e)) {
this.setBackground(bgClicked);
}
this.repaint();
}<|fim▁hole|> /**
* Invokes the new state change
*/
@Override
public void mouseReleased(MouseEvent e) {
if (inBounds(e))
apply();
this.setBackground(bgPassive);
this.repaint();
}
/**
* Stub Method - Not Used
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/**
* Stub Method - Not Used
*/
@Override
public void mouseExited(MouseEvent e) {
}
}<|fim▁end|> | |
<|file_name|>npm-api.js<|end_file_name|><|fim▁begin|>/*jslint node: true */
'use strict';
var npm = require('npm');
module.exports = Npm;
<|fim▁hole|> var conf = {
jobs: 1
};
npm.load(conf, callback);
}
Npm.prototype.search = function (searchTerms, callback) {
npm.commands.search(searchTerms, true, callback);
};
Npm.prototype.view = function (name, callback) {
npm.commands.view([name], callback);
};<|fim▁end|> | function Npm (callback) { |
<|file_name|>win_services.go<|end_file_name|><|fim▁begin|>//go:build windows
// +build windows
package win_services
import (
"fmt"
"os"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/plugins/inputs"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/mgr"
)
type ServiceErr struct {
Message string
Service string
Err error
}
func (e *ServiceErr) Error() string {
return fmt.Sprintf("%s: '%s': %v", e.Message, e.Service, e.Err)
}
func IsPermission(err error) bool {
if err, ok := err.(*ServiceErr); ok {
return os.IsPermission(err.Err)
}
return false
}
// WinService provides interface for svc.Service
type WinService interface {
Close() error
Config() (mgr.Config, error)
Query() (svc.Status, error)
}
// ManagerProvider sets interface for acquiring manager instance, like mgr.Mgr
type ManagerProvider interface {
Connect() (WinServiceManager, error)
}
// WinServiceManager provides interface for mgr.Mgr
type WinServiceManager interface {
Disconnect() error
OpenService(name string) (WinService, error)
ListServices() ([]string, error)
}
// WinSvcMgr is wrapper for mgr.Mgr implementing WinServiceManager interface
type WinSvcMgr struct {
realMgr *mgr.Mgr
}
func (m *WinSvcMgr) Disconnect() error {
return m.realMgr.Disconnect()
}
func (m *WinSvcMgr) OpenService(name string) (WinService, error) {
return m.realMgr.OpenService(name)
}
func (m *WinSvcMgr) ListServices() ([]string, error) {
return m.realMgr.ListServices()
}
// MgProvider is an implementation of WinServiceManagerProvider interface returning WinSvcMgr
type MgProvider struct {
}
func (rmr *MgProvider) Connect() (WinServiceManager, error) {
scmgr, err := mgr.Connect()
if err != nil {
return nil, err
} else {
return &WinSvcMgr{scmgr}, nil
}
}
var sampleConfig = `
## Names of the services to monitor. Leave empty to monitor all the available services on the host. Globs accepted.
service_names = [
"LanmanServer",
"TermService",
"Win*",
]
#excluded_service_names = [] # optional, list of service names to exclude
`
var description = "Input plugin to report Windows services info."
//WinServices is an implementation if telegraf.Input interface, providing info about Windows Services
type WinServices struct {
Log telegraf.Logger
ServiceNames []string `toml:"service_names"`
ServiceNamesExcluded []string `toml:"excluded_service_names"`
mgrProvider ManagerProvider
servicesFilter filter.Filter
}
type ServiceInfo struct {
ServiceName string
DisplayName string
State int
StartUpMode int
}
func (m *WinServices) Init() error {
var err error
m.servicesFilter, err = filter.NewIncludeExcludeFilter(m.ServiceNames, m.ServiceNamesExcluded)
if err != nil {
return err
}
return nil
}
func (m *WinServices) Description() string {
return description
}
func (m *WinServices) SampleConfig() string {
return sampleConfig
}
func (m *WinServices) Gather(acc telegraf.Accumulator) error {
scmgr, err := m.mgrProvider.Connect()
if err != nil {
return fmt.Errorf("Could not open service manager: %s", err)
}
defer scmgr.Disconnect()
serviceNames, err := m.listServices(scmgr)
if err != nil {
return err
}
for _, srvName := range serviceNames {
service, err := collectServiceInfo(scmgr, srvName)
if err != nil {
if IsPermission(err) {
m.Log.Debug(err.Error())
} else {
m.Log.Error(err.Error())
}
continue
}
tags := map[string]string{
"service_name": service.ServiceName,
}
//display name could be empty, but still valid service
if len(service.DisplayName) > 0 {
tags["display_name"] = service.DisplayName
}
fields := map[string]interface{}{
"state": service.State,
"startup_mode": service.StartUpMode,
}
acc.AddFields("win_services", fields, tags)
}
return nil
}
// listServices returns a list of services to gather.
func (m *WinServices) listServices(scmgr WinServiceManager) ([]string, error) {
names, err := scmgr.ListServices()
if err != nil {
return nil, fmt.Errorf("Could not list services: %s", err)
}
var services []string
for _, n := range names {
if m.servicesFilter.Match(n) {
services = append(services, n)
}
}
<|fim▁hole|>
// collectServiceInfo gathers info about a service.
func collectServiceInfo(scmgr WinServiceManager, serviceName string) (*ServiceInfo, error) {
srv, err := scmgr.OpenService(serviceName)
if err != nil {
return nil, &ServiceErr{
Message: "could not open service",
Service: serviceName,
Err: err,
}
}
defer srv.Close()
srvStatus, err := srv.Query()
if err != nil {
return nil, &ServiceErr{
Message: "could not query service",
Service: serviceName,
Err: err,
}
}
srvCfg, err := srv.Config()
if err != nil {
return nil, &ServiceErr{
Message: "could not get config of service",
Service: serviceName,
Err: err,
}
}
serviceInfo := &ServiceInfo{
ServiceName: serviceName,
DisplayName: srvCfg.DisplayName,
StartUpMode: int(srvCfg.StartType),
State: int(srvStatus.State),
}
return serviceInfo, nil
}
func init() {
inputs.Add("win_services", func() telegraf.Input {
return &WinServices{
mgrProvider: &MgProvider{},
}
})
}<|fim▁end|> | return services, nil
} |
<|file_name|>sms.js<|end_file_name|><|fim▁begin|>var twilio = require('twilio'),
Player = require('../models/Player'),
Question = require('../models/Question');
// Handle inbound SMS and process commands
module.exports = function(request, response) {
var twiml = new twilio.TwimlResponse();
var body = request.param('Body').trim(),
playerPhone = request.param('From'),
player = null,
question = null;
// Emit a response with the given message
function respond(str) {
twiml.message(str);
response.send(twiml);
}
// Process the "nick" command
function nick(input) {
if (was('help', input)) {
respond('Set your nickname, as you want it to appear on the leaderboard. Example: "nick Mrs. Awesomepants"');
} else {
if (input === '') {
respond('A nickname is required. Text "nick help" for command help.');
} else {
player.nick = input;
player.save(function(err) {
if (err) {
respond('There was a problem updating your nickname, or that nickname is already in use. Please try another nickname.');
} else {
respond('Your nickname has been changed!');
}
});
}
}
}
// Process the "stop" command
function stop(input) {
if (was('help', input)) {
respond('Unsubscribe from all messages. Example: "stop"');
} else {
player.remove(function(err, model) {
if (err) {
respond('There was a problem unsubscribing. Please try again later.');
} else {
respond('You have been unsubscribed.');
}
});
}
}
// Process the "question" command
function questionCommand(input) {
if (was('help', input)) {
respond('Print out the current question. Example: "question"');
} else {
Question.findOne({}, function(err, q) {
question = err ? {question:'Error, no question found.'} : q;
respond('Current question: '+question.question);
});
}
}
// Once the current question is found, determine if we have an eligible
// answer
function processAnswer(input) {
if (!question.answered) {
question.answered = [];<|fim▁hole|>
if (question.answered.indexOf(player.phone) > -1) {
respond('You have already answered this question!');
} else {
var answerLower = question.answer.toLowerCase(),
inputLower = input.toLowerCase().trim();
if (inputLower !== '' && answerLower.indexOf(inputLower) > -1) {
var points = 5 - question.answered.length;
if (points < 1) {
points = 1;
}
// DOUBLE POINTS
// points = points*2;
// Update the question, then the player score
question.answered.push(player.phone);
question.save(function(err) {
player.points = player.points+points;
player.save(function(err2) {
respond('Woop woop! You got it! Your score is now: '+player.points);
});
});
} else {
respond('Sorry! That answer was incorrect. Guess again...');
}
}
}
// Process the "answer" command
function answer(input) {
if (was('help', input)) {
respond('Answer the current question - spelling is important, capitalization is not. If you don\'t know the current question, text "question". Example: "answer frodo baggins"');
} else {
Question.findOne({}, function(err, q) {
question = err ? {question:'Error, no question found.'} : q;
processAnswer(input);
});
}
}
// Process the "score" command
function score(input) {
if (was('help', input)) {
respond('Print out your current score. Example: "score"');
} else {
respond('Your current score is: '+player.points);
}
}
// Helper to see if the command was a given string
function was(command, input) {
var lowered = input.toLowerCase();
return lowered ? lowered.indexOf(command) === 0 : false;
}
// Helper to chop off the command string for further processing
function chop(input) {
var idx = input.indexOf(' ');
return idx > 0 ? input.substring(idx).trim() : '';
}
// Parse their input command
function processInput() {
var input = body||'help';
var chopped = chop(input);
if (was('nick', input)) {
nick(chopped);
} else if (was('stop', input)) {
stop(chopped);
} else if (was('answer', input)) {
answer(chopped);
} else if (was('question', input)) {
questionCommand(chopped);
} else if (was('score', input)) {
score(chopped);
} else {
respond('Welcome to Twilio Trivia '+player.nick+'! Commands are "answer", "question", "nick", "score", help", and "stop". Text "<command name> help" for usage. View the current leaderboard and question at http://build-trivia.azurewebsites.net/');
}
}
// Create a new player
function createPlayer() {
Player.create({
phone:playerPhone,
nick:'Mysterious Stranger '+playerPhone.substring(7),
points:0
}, function(err, model) {
if (err) {
respond('There was an error signing you up, try again later.');
} else {
player = model;
respond('Welcome to Twilio Trivia! You are now signed up. Text "help" for instructions.');
}
});
}
// Deal with the found player, if it exists
function playerFound(err, model) {
if (err) {
respond('There was an error recording your answer.');
} else {
if (model) {
player = model;
processInput();
} else {
createPlayer();
}
}
}
// Kick off the db access by finding the player for this phone number
Player.findOne({
phone:playerPhone
}, playerFound);
};<|fim▁end|> | } |
<|file_name|>model_licenseinfo.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
# This code is automatically transpiled by Saklient Translator
import six
from ..client import Client
from .model import Model
from ..resources.resource import Resource
from ..resources.licenseinfo import LicenseInfo
from ...util import Util
import saklient
str = six.text_type
# module saklient.cloud.models.model_licenseinfo
class Model_LicenseInfo(Model):
## ライセンス種別情報を検索するための機能を備えたクラス。
## @private
# @return {str}
def _api_path(self):
return "/product/license"
## @private
# @return {str}
def _root_key(self):
return "LicenseInfo"
## @private
# @return {str}
def _root_key_m(self):
return "LicenseInfo"
## @private
# @return {str}
def _class_name(self):
return "LicenseInfo"
## @private
# @param {any} obj
# @param {bool} wrapped=False
# @return {saklient.cloud.resources.resource.Resource}
def _create_resource_impl(self, obj, wrapped=False):
Util.validate_type(wrapped, "bool")
return LicenseInfo(self._client, obj, wrapped)
## 次に取得するリストの開始オフセットを指定します。
#
# @param {int} offset オフセット
# @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this
def offset(self, offset):
Util.validate_type(offset, "int")
return self._offset(offset)
## 次に取得するリストの上限レコード数を指定します。
#
# @param {int} count 上限レコード数
# @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this
def limit(self, count):
Util.validate_type(count, "int")
return self._limit(count)
## Web APIのフィルタリング設定を直接指定します。
#
# @param {str} key キー
# @param {any} value 値
# @param {bool} multiple=False valueに配列を与え、OR条件で完全一致検索する場合にtrueを指定します。通常、valueはスカラ値であいまい検索されます。
# @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo}
def filter_by(self, key, value, multiple=False):
Util.validate_type(key, "str")
Util.validate_type(multiple, "bool")
return self._filter_by(key, value, multiple)
## 次のリクエストのために設定されているステートをすべて破棄します。
#
# @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this
def reset(self):
return self._reset()
## 指定したIDを持つ唯一のリソースを取得します。
# <|fim▁hole|> return self._get_by_id(id)
## リソースの検索リクエストを実行し、結果をリストで取得します。
#
# @return {saklient.cloud.resources.licenseinfo.LicenseInfo[]} リソースオブジェクトの配列
def find(self):
return self._find()
## 指定した文字列を名前に含むリソースに絞り込みます。
#
# 大文字・小文字は区別されません。
# 半角スペースで区切られた複数の文字列は、それらをすべて含むことが条件とみなされます。
#
# @todo Implement test case
# @param {str} name
# @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo}
def with_name_like(self, name):
Util.validate_type(name, "str")
return self._with_name_like(name)
## 名前でソートします。
#
# @todo Implement test case
# @param {bool} reverse=False
# @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo}
def sort_by_name(self, reverse=False):
Util.validate_type(reverse, "bool")
return self._sort_by_name(reverse)
## @ignore
# @param {saklient.cloud.client.Client} client
def __init__(self, client):
super(Model_LicenseInfo, self).__init__(client)
Util.validate_type(client, "saklient.cloud.client.Client")<|fim▁end|> | # @param {str} id
# @return {saklient.cloud.resources.licenseinfo.LicenseInfo} リソースオブジェクト
def get_by_id(self, id):
Util.validate_type(id, "str") |
<|file_name|>build_test.go<|end_file_name|><|fim▁begin|>package integration<|fim▁hole|>import (
"fmt"
"os/exec"
"strings"
"golang.org/x/net/context"
. "gopkg.in/check.v1"
)
func (s *CliSuite) TestBuild(c *C) {
p := s.RandomProject()
cmd := exec.Command(s.command, "-f", "./assets/build/docker-compose.yml", "-p", p, "build")
err := cmd.Run()
oneImageName := fmt.Sprintf("%s_one", p)
twoImageName := fmt.Sprintf("%s_two", p)
c.Assert(err, IsNil)
client := GetClient(c)
one, _, err := client.ImageInspectWithRaw(context.Background(), oneImageName, false)
c.Assert(err, IsNil)
c.Assert([]string(one.Config.Cmd), DeepEquals, []string{"echo", "one"})
two, _, err := client.ImageInspectWithRaw(context.Background(), twoImageName, false)
c.Assert(err, IsNil)
c.Assert([]string(two.Config.Cmd), DeepEquals, []string{"echo", "two"})
}
func (s *CliSuite) TestBuildWithNoCache1(c *C) {
p := s.RandomProject()
cmd := exec.Command(s.command, "-f", "./assets/build/docker-compose.yml", "-p", p, "build")
output, err := cmd.Output()
c.Assert(err, IsNil)
cmd = exec.Command(s.command, "-f", "./assets/build/docker-compose.yml", "-p", p, "build")
output, err = cmd.Output()
c.Assert(err, IsNil)
out := string(output[:])
c.Assert(strings.Contains(out,
"Using cache"),
Equals, true, Commentf("%s", out))
}
func (s *CliSuite) TestBuildWithNoCache2(c *C) {
p := s.RandomProject()
cmd := exec.Command(s.command, "-f", "./assets/build/docker-compose.yml", "-p", p, "build")
output, err := cmd.Output()
c.Assert(err, IsNil)
cmd = exec.Command(s.command, "-f", "./assets/build/docker-compose.yml", "-p", p, "build", "--no-cache")
output, err = cmd.Output()
c.Assert(err, IsNil)
out := string(output[:])
c.Assert(strings.Contains(out,
"Using cache"),
Equals, false, Commentf("%s", out))
}
func (s *CliSuite) TestBuildWithNoCache3(c *C) {
p := s.RandomProject()
cmd := exec.Command(s.command, "-f", "./assets/build/docker-compose.yml", "-p", p, "build", "--no-cache")
err := cmd.Run()
oneImageName := fmt.Sprintf("%s_one", p)
twoImageName := fmt.Sprintf("%s_two", p)
c.Assert(err, IsNil)
client := GetClient(c)
one, _, err := client.ImageInspectWithRaw(context.Background(), oneImageName, false)
c.Assert(err, IsNil)
c.Assert([]string(one.Config.Cmd), DeepEquals, []string{"echo", "one"})
two, _, err := client.ImageInspectWithRaw(context.Background(), twoImageName, false)
c.Assert(err, IsNil)
c.Assert([]string(two.Config.Cmd), DeepEquals, []string{"echo", "two"})
}<|fim▁end|> | |
<|file_name|>bitcoin_zh_CN.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="zh_CN">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About TurboStake</source>
<translation>关于TurboStake</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="75"/>
<source><html><head/><body><p><span style=" font-weight:600;">TurboStake</span></p></body></html></source>
<translation><html><head/><body><p><span style=" font-weight:600;">TurboStake</span></p></body></html></translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="113"/>
<source>Copyright © 2014 TurboStake Developers</source>
<translation>版权归TurboStake开发者所有 © 2014 TurboStake Developers</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="120"/>
<source>Copyright © 2011-2014 TurboStake Developers</source>
<translation>版权归TurboStake开发者所有 © 2011-2014 TurboStake Developers</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="133"/>
<source>Copyright © 2009-2014 Bitcoin Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished">版权归比特币开发者所有 © 2009-2013 TurboStake Developers
这是一个实验性软件。
Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard. {2009-2014 ?} {11 ?}</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>地址薄</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your TurboStake addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="33"/>
<source>Double-click to edit address or label</source>
<translation>双击以编辑地址或标签</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="57"/>
<source>Create a new address</source>
<translation>创建新地址</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="60"/>
<source>&New Address...</source>
<translation>&新地址...</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="71"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>复制当前选中地址到系统剪贴板</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="74"/>
<source>&Copy to Clipboard</source>
<translation>&复制到剪贴板</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="85"/>
<source>Show &QR Code</source>
<translation>显示二维码(&Q)</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="96"/>
<source>Sign a message to prove you own this address</source>
<translation>发送签名消息以证明您是该比特币地址的拥有者</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="99"/>
<source>&Sign Message</source>
<translation>&发送签名消息</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="110"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>从列表中删除当前选中地址。只有发送地址可以被删除。</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="113"/>
<source>&Delete</source>
<translation>&删除</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="65"/>
<source>Copy address</source>
<translation>复制地址</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="66"/>
<source>Copy label</source>
<translation>复制标签</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="67"/>
<source>Edit</source>
<translation>编辑</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="68"/>
<source>Delete</source>
<translation>删除</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="273"/>
<source>Export Address Book Data</source>
<translation>导出地址薄数据</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="274"/>
<source>Comma separated file (*.csv)</source>
<translation>逗号分隔文件 (*.csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="287"/>
<source>Error exporting</source>
<translation>导出错误</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="287"/>
<source>Could not write to file %1.</source>
<translation>无法写入文件 %1。</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="79"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="79"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="115"/>
<source>(no label)</source>
<translation>(没有标签)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Dialog</source>
<translation>会话</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="94"/>
<source>TextLabel</source>
<translation>文本标签</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="47"/>
<source>Enter passphrase</source>
<translation>输入口令</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="61"/>
<source>New passphrase</source>
<translation>新口令</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="75"/>
<source>Repeat new passphrase</source>
<translation>重复新口令</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="114"/>
<source>Toggle Keyboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="37"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>输入钱包的新口令。<br/>使用的口令请至少包含<b>10个以上随机字符</>,或者是<b>8个以上的单词</b>。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="38"/>
<source>Encrypt wallet</source>
<translation>加密钱包</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="41"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>该操作需要您首先使用口令解锁钱包。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="46"/>
<source>Unlock wallet</source>
<translation>解锁钱包</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="49"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>该操作需要您首先使用口令解密钱包。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Decrypt wallet</source>
<translation>解密钱包</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="57"/>
<source>Change passphrase</source>
<translation>修改口令</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="58"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>请输入钱包的旧口令与新口令。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="106"/>
<source>Confirm wallet encryption</source>
<translation>确认加密钱包</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="116"/>
<location filename="../askpassphrasedialog.cpp" line="165"/>
<source>Wallet encrypted</source>
<translation>钱包已加密</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="213"/>
<location filename="../askpassphrasedialog.cpp" line="237"/>
<source>Warning: The Caps Lock key is on.</source>
<translation>警告:大写锁定键CapsLock开启。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="122"/>
<location filename="../askpassphrasedialog.cpp" line="129"/>
<location filename="../askpassphrasedialog.cpp" line="171"/>
<location filename="../askpassphrasedialog.cpp" line="177"/>
<source>Wallet encryption failed</source>
<translation>钱包加密失败</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="107"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR PEERCOINS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<source>TurboStake will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your TurboStakes from being stolen by malware infecting your computer.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="123"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>由于一个本地错误,加密钱包操作已经失败。您的钱包没有被加密。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="130"/>
<location filename="../askpassphrasedialog.cpp" line="178"/>
<source>The supplied passphrases do not match.</source>
<translation>口令不匹配。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="141"/>
<source>Wallet unlock failed</source>
<translation>钱包解锁失败</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="142"/>
<location filename="../askpassphrasedialog.cpp" line="153"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>用于解密钱包的口令不正确。</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="152"/>
<source>Wallet decryption failed</source>
<translation>钱包解密失败</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>钱包口令修改成功。</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="191"/>
<source>&Overview</source>
<translation>概况(&O)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="192"/>
<source>Show general overview of wallet</source>
<translation>显示钱包概况</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="197"/>
<source>&Transactions</source>
<translation>交易(&T)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="198"/>
<source>Browse transaction history</source>
<translation>查看交易历史</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="203"/>
<source>&Minting</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="204"/>
<source>Show your minting capacity</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="209"/>
<source>&Address Book</source>
<translation>地址薄(&A)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="210"/>
<source>Edit the list of stored addresses and labels</source>
<translation>修改存储的地址和标签列表</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="215"/>
<source>&Receive coins</source>
<translation>接收货币(&R)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="216"/>
<source>Show the list of addresses for receiving payments</source>
<translation>显示接收支付的地址列表</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="221"/>
<source>&Send coins</source>
<translation>发送货币(&S)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="227"/>
<source>Sign/Verify &message</source>
<translation>签名/验证消息(&M)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="228"/>
<source>Prove you control an address</source>
<translation>证明您拥有某个地址</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>E&xit</source>
<translation>退出(&E)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="250"/>
<source>Quit application</source>
<translation>退出程序</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="254"/>
<source>Show information about TurboStake</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="256"/>
<source>About &Qt</source>
<translation>关于 &Qt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="257"/>
<source>Show information about Qt</source><|fim▁hole|> <translation>显示Qt相关信息</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="259"/>
<source>&Options...</source>
<translation>选项(&O)...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="264"/>
<source>&Export...</source>
<translation>导出(&E)...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="265"/>
<source>Export the data in the current tab to a file</source>
<translation>导出当前数据到文件</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="266"/>
<source>&Encrypt Wallet</source>
<translation>加密钱包(&E)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="267"/>
<source>Encrypt or decrypt wallet</source>
<translation>加密或解密钱包</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="269"/>
<source>&Unlock Wallet for Minting Only</source>
<translation>只为铸币而解锁钱包(&U)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="270"/>
<source>Unlock wallet only for minting. Sending coins will still require the passphrase.</source>
<translation>只为铸币而解锁钱包。发送币仍然需要密码。</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="272"/>
<source>&Backup Wallet</source>
<translation>备份钱包(&B)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="273"/>
<source>Backup wallet to another location</source>
<translation>备份钱包到其它文位置</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="274"/>
<source>&Change Passphrase</source>
<translation>修改口令(&C)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="275"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>修改钱包加密口令</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="276"/>
<source>&Debug window</source>
<translation>调试窗口(&D)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="277"/>
<source>Open debugging and diagnostic console</source>
<translation>打开调试和诊断控制台</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="301"/>
<source>&File</source>
<translation>文件(&F)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="310"/>
<source>&Settings</source>
<translation>设置(&S)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="317"/>
<source>&Help</source>
<translation>帮助(&H)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="326"/>
<source>Tabs toolbar</source>
<translation>分页工具栏</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="338"/>
<source>Actions toolbar</source>
<translation>动作工具栏</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="350"/>
<source>[testnet]</source>
<translation>[测试网络]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="658"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1. Do you want to pay the fee?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="76"/>
<source>TurboStake Wallet</source>
<translation>TurboStake钱包</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="222"/>
<source>Send coins to a TurboStake address</source>
<translation>向一个TurboStake地址发送币</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="253"/>
<source>&About TurboStake</source>
<translation>关于TurboStake(&A)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="260"/>
<source>Modify configuration options for TurboStake</source>
<translation>设置选项</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="262"/>
<source>Show/Hide &TurboStake</source>
<translation>显示/隐藏&TurboStake</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="263"/>
<source>Show or hide the TurboStake window</source>
<translation>显示或隐藏主窗口</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="415"/>
<source>TurboStake client</source>
<translation>TurboStake客户端</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="443"/>
<source>p-qt</source>
<translation>p-qt</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="507"/>
<source>%n active connection(s) to TurboStake network</source>
<translation>
<numerusform>%n条到TurboStake网络的活动连接</numerusform>
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="531"/>
<source>Synchronizing with network...</source>
<translation>正在与网络同步...</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="533"/>
<source>~%n block(s) remaining</source>
<translation>
<numerusform>剩余 ~%n 块</numerusform>
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="544"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>%2中%1个交易历史的区块已下载(已完成%3%)。</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="556"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>%1 个交易历史的区块已下载。</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="571"/>
<source>%n second(s) ago</source>
<translation>
<numerusform>%n 秒前</numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="575"/>
<source>%n minute(s) ago</source>
<translation>
<numerusform>%n 分种前</numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="579"/>
<source>%n hour(s) ago</source>
<translation>
<numerusform>%n 小时前</numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="583"/>
<source>%n day(s) ago</source>
<translation>
<numerusform>%n 天前</numerusform>
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="589"/>
<source>Up to date</source>
<translation>最新状态</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="594"/>
<source>Catching up...</source>
<translation>更新中...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="602"/>
<source>Last received block was generated %1.</source>
<translation>最新收到的区块产生于 %1。</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="661"/>
<source>Sending...</source>
<translation>发送中...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="688"/>
<source>Sent transaction</source>
<translation>已发送交易</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="689"/>
<source>Incoming transaction</source>
<translation>流入交易</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="690"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>日期: %1
金额: %2
类别: %3
地址: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="821"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked for block minting only</b></source>
<translation>钱包已被<b>加密</b>,当前为<b>只为铸币而解锁</b>的状态</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="821"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>钱包已被<b>加密</b>,当前为<b>解锁</b>状态</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="831"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>钱包已被<b>加密</b>,当前为<b>锁定</b>状态</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="888"/>
<source>Backup Wallet</source>
<translation>备份钱包</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="888"/>
<source>Wallet Data (*.dat)</source>
<translation>钱包数据(*.dat)</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="891"/>
<source>Backup Failed</source>
<translation>备份失败</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="891"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>备份钱包到其它位置失败。</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="128"/>
<source>A fatal error occured. TurboStake can no longer continue safely and will quit.</source>
<translation>发生致命错误。TurboStake无法继续安全运行,将要退出。</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="14"/>
<source>Coin Control</source>
<translation>交易源地址控制</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="45"/>
<source>Quantity:</source>
<translation>总量:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="64"/>
<location filename="../forms/coincontroldialog.ui" line="96"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="77"/>
<source>Bytes:</source>
<translation>字节:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="125"/>
<source>Amount:</source>
<translation>金额:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="144"/>
<location filename="../forms/coincontroldialog.ui" line="224"/>
<location filename="../forms/coincontroldialog.ui" line="310"/>
<location filename="../forms/coincontroldialog.ui" line="348"/>
<source>0.00 BTC</source>
<translation>0.00 trbo</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="157"/>
<source>Priority:</source>
<translation>优先级:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="205"/>
<source>Fee:</source>
<translation>费用:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="240"/>
<source>Low Output:</source>
<translation>低输出:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="262"/>
<location filename="../coincontroldialog.cpp" line="572"/>
<source>no</source>
<translation>否</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="291"/>
<source>After Fee:</source>
<translation>减交易费后:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="326"/>
<source>Change:</source>
<translation>找零:</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="395"/>
<source>(un)select all</source>
<translation>(不)全选</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="408"/>
<source>Tree mode</source>
<translation>树状模式</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="424"/>
<source>List mode</source>
<translation>列表模式</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="469"/>
<source>Amount</source>
<translation>金额</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="479"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="484"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="489"/>
<source>Confirmations</source>
<translation>确认</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="492"/>
<source>Confirmed</source>
<translation>已确认</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="497"/>
<source>Coin days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="502"/>
<source>Priority</source>
<translation>优先级</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="36"/>
<source>Copy address</source>
<translation>复制地址</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="37"/>
<source>Copy label</source>
<translation>复制标签</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="38"/>
<location filename="../coincontroldialog.cpp" line="64"/>
<source>Copy amount</source>
<translation>复制金额</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="39"/>
<source>Copy transaction ID</source>
<translation>复制交易编号</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="63"/>
<source>Copy quantity</source>
<translation>复制总量</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="65"/>
<source>Copy fee</source>
<translation>复制交易费</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="66"/>
<source>Copy after fee</source>
<translation>复制去除交易费后的金额</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="67"/>
<source>Copy bytes</source>
<translation>复制字节</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="68"/>
<source>Copy priority</source>
<translation>复制优先级</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="69"/>
<source>Copy low output</source>
<translation>复制低输出</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="70"/>
<source>Copy change</source>
<translation>复制金额</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="388"/>
<source>highest</source>
<translation>最高</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="389"/>
<source>high</source>
<translation>高</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="390"/>
<source>medium-high</source>
<translation>中高</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="391"/>
<source>medium</source>
<translation>中</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="395"/>
<source>low-medium</source>
<translation>中低</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="396"/>
<source>low</source>
<translation>低</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="397"/>
<source>lowest</source>
<translation>最低</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="572"/>
<source>DUST</source>
<translation>尘埃交易</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="572"/>
<source>yes</source>
<translation>是</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="582"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>如果这笔交易大于10000字节,标签会变成红色。
这意味着每千字节至少需要 %1的交易费。
每个输入可能带来+/- 1字节的变化。</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="583"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>交易的优先级越高,被矿工收入数据块的速度也越快。
如果优先级低于“中”,标签将变成红色。
这意味着每千字节至少需要 %1的交易费。</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="584"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>如果收款地址收到小于%1的比特币,标签将变成红色。
这意味着至少需要 %2的交易费。
低于最小费用的0.546倍的金额显示为尘埃交易。</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="585"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>如果零钱小于 %1,标签将变成红色。
这意味着至少需要 %2的交易费。</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="622"/>
<location filename="../coincontroldialog.cpp" line="688"/>
<source>(no label)</source>
<translation>(没有标签)</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="679"/>
<source>change from %1 (%2)</source>
<translation>来自%1的零钱 (%2)</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="680"/>
<source>(change)</source>
<translation>(零钱)</translation>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="275"/>
<source>&Unit to show amounts in: </source>
<translation>金额显示单位(&U):</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="279"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>选择显示及发送币时使用的最小单位</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="286"/>
<source>&Display addresses in transaction list</source>
<translation>在交易清单中显示地址(&D)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="287"/>
<source>Whether to show TurboStake addresses in the transaction list</source>
<translation>是否需要在交易清单中显示币地址</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="290"/>
<source>Display coin control features (experts only!)</source>
<translation>显示交易源地址控制功能(只适合行家!)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="291"/>
<source>Whether to show coin control features or not</source>
<translation>是否显示交易源地址控制功能</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="14"/>
<source>Edit Address</source>
<translation>编辑地址</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&标签</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>与此地址条目关联的标签</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>地址(&A)</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>该地址与地址簿中的条目已关联,无法作为发送地址编辑。</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>新接收地址</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>新发送地址</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>编辑接收地址</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>编辑发送地址</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>输入的地址 "%1" 已经存在于地址薄。</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid TurboStake address.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>无法解锁钱包。</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>密钥创建失败.</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="177"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&最小化到托盘</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="178"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>最小化窗口后只显示一个托盘标志</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="186"/>
<source>Map port using &UPnP</source>
<translation>使用 &UPnP 映射端口</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="181"/>
<source>M&inimize on close</source>
<translation>关闭时最小化(&i)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="182"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>当窗口关闭时程序最小化而不是退出。当使用该选项时,程序只能通过在菜单中选择退出来关闭。</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="187"/>
<source>Automatically open the TurboStake client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>自动在路由器中打开TurboStake端口。只有当您的路由器支持并开启了 UPnP 选项时此功能才有效。</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="190"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>通过SOCKS4代理连接(&C):</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="191"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>通过一个SOCKS4代理连接到比特币网络 (如使用Tor连接时)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="196"/>
<source>Proxy &IP: </source>
<translation>代理 &IP:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="202"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>代理服务器IP (如 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="205"/>
<source>&Port: </source>
<translation>端口(&P):</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="211"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>代理端口 (比如 1234)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="217"/>
<source>Mandatory network transaction fee per kB transferred. Most transactions are 1 kB and incur a 0.01 trbo fee. Note: transfer size may increase depending on the number of input transactions required to be added together to fund the payment.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Additional network &fee:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="234"/>
<source>Detach databases at shutdown</source>
<translation>关闭时断开数据库</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="235"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>关闭时断开块和地址数据库。这使它们能被移动到另外目录,但减慢关闭速度。钱包总是断开的。</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="172"/>
<source>&Start TurboStake on window system startup</source>
<translation>系统启动时运行TurboStake(&S)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="173"/>
<source>Automatically start TurboStake after the computer is turned on</source>
<translation>计算机启动后自动开启TurboStake客户端</translation>
</message>
</context>
<context>
<name>MintingTableModel</name>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Transaction</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Address</source>
<translation type="unfinished">地址</translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Age</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>Balance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>CoinDay</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="203"/>
<source>MintProbability</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="284"/>
<source>minutes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="291"/>
<source>hours</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="295"/>
<source>days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="298"/>
<source>You have %1 chance to find a POS block if you mint %2 %3 at current difficulty.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="418"/>
<source>Destination address of the output.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="420"/>
<source>Original transaction id.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="422"/>
<source>Age of the transaction in days.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="424"/>
<source>Balance of the output.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="426"/>
<source>Coin age in the output.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingtablemodel.cpp" line="428"/>
<source>Chance to mint a block within given time interval.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MintingView</name>
<message>
<location filename="../mintingview.cpp" line="33"/>
<source>transaction is too young</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="40"/>
<source>transaction is mature</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="47"/>
<source>transaction has reached maximum probability</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="60"/>
<source>Display minting probability within : </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="62"/>
<source>10 min</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="63"/>
<source>24 hours</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="64"/>
<source>30 days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="65"/>
<source>90 days</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="162"/>
<source>Export Minting Data</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="163"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="171"/>
<source>Address</source>
<translation type="unfinished">地址</translation>
</message>
<message>
<location filename="../mintingview.cpp" line="172"/>
<source>Transaction</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="173"/>
<source>Age</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="174"/>
<source>CoinDay</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="175"/>
<source>Balance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="176"/>
<source>MintingProbability</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mintingview.cpp" line="180"/>
<source>Error exporting</source>
<translation type="unfinished">导出错误</translation>
</message>
<message>
<location filename="../mintingview.cpp" line="180"/>
<source>Could not write to file %1.</source>
<translation type="unfinished">无法写入文件 %1。</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="81"/>
<source>Main</source>
<translation>主要</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="86"/>
<source>Display</source>
<translation>显示</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="106"/>
<source>Options</source>
<translation>选项</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>表单</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Balance:</source>
<translation>余额:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="54"/>
<source>Number of transactions:</source>
<translation>交易笔数:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="61"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="68"/>
<source>Unconfirmed:</source>
<translation>未确认:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="82"/>
<source>Stake:</source>
<translation>权益:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="102"/>
<source>Wallet</source>
<translation>钱包</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="138"/>
<source><b>Recent transactions</b></source>
<translation><b>最近交易记录</b></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="104"/>
<source>Your current balance</source>
<translation>您的当前余额</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="109"/>
<source>Your current stake</source>
<translation>您的当前权益</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="114"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>尚未确认的交易总额, 未计入当前余额</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="117"/>
<source>Total number of transactions in wallet</source>
<translation>钱包总交易数量</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>Dialog</source>
<translation>会话</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation>二维码</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="55"/>
<source>Request Payment</source>
<translation>请求付款</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="70"/>
<source>Amount:</source>
<translation>金额:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="105"/>
<source>trbo</source>
<translation>trbo</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="121"/>
<source>Label:</source>
<translation>标签:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="144"/>
<source>Message:</source>
<translation>消息:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="186"/>
<source>&Save As...</source>
<translation>另存为(&S)...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="46"/>
<source>Error encoding URI into QR Code.</source>
<translation>将URI编码入二维码时发生错误。</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="64"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>生成的URI太长。请尝试减少标签/消息的文字。</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="121"/>
<source>Save Image...</source>
<translation>保存图像...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="121"/>
<source>PNG Images (*.png)</source>
<translation>PNG图像文件(*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="14"/>
<source>TurboStake (TurboStake) debug window</source>
<translation>TurboStake (TurboStake)调试窗口</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="24"/>
<source>Information</source>
<translation>信息</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="33"/>
<source>Client name</source>
<translation>客户端名称</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="40"/>
<location filename="../forms/rpcconsole.ui" line="60"/>
<location filename="../forms/rpcconsole.ui" line="106"/>
<location filename="../forms/rpcconsole.ui" line="156"/>
<location filename="../forms/rpcconsole.ui" line="176"/>
<location filename="../forms/rpcconsole.ui" line="196"/>
<location filename="../forms/rpcconsole.ui" line="229"/>
<location filename="../rpcconsole.cpp" line="338"/>
<source>N/A</source>
<translation>不可用</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="53"/>
<source>Client version</source>
<translation>客户端版本</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="79"/>
<source>Version</source>
<translation>版本</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="92"/>
<source>Network</source>
<translation>网络</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="99"/>
<source>Number of connections</source>
<translation>连接数</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="119"/>
<source>On testnet</source>
<translation>使用测试网络</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="142"/>
<source>Block chain</source>
<translation>块链</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="149"/>
<source>Current number of blocks</source>
<translation>当前数据块数量</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="169"/>
<source>Estimated total blocks</source>
<translation>预计数据块数量</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="189"/>
<source>Last block time</source>
<translation>上一数据块时间</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="222"/>
<source>Build date</source>
<translation>创建日期</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="237"/>
<source>Console</source>
<translation>控制台</translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="270"/>
<source>></source>
<translation>></translation>
</message>
<message>
<location filename="../forms/rpcconsole.ui" line="286"/>
<source>Clear console</source>
<translation>清空控制台</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="306"/>
<source>Welcome to the TurboStake RPC console.<br>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.<br>Type <b>help</b> for an overview of available commands.</source>
<translation>欢迎来到TurboStake RPC 控制台。<br>使用上下方向键浏览历史, <b>Ctrl-L</b>清除屏幕。<br>使用 <b>help</b> 命令显示帮助信息。</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="176"/>
<location filename="../sendcoinsdialog.cpp" line="181"/>
<location filename="../sendcoinsdialog.cpp" line="186"/>
<location filename="../sendcoinsdialog.cpp" line="191"/>
<location filename="../sendcoinsdialog.cpp" line="197"/>
<location filename="../sendcoinsdialog.cpp" line="202"/>
<location filename="../sendcoinsdialog.cpp" line="207"/>
<source>Send Coins</source>
<translation>发送货币</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="90"/>
<source>Coin Control Features</source>
<translation>交易源地址控制功能</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="110"/>
<source>Inputs...</source>
<translation>输入...</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="117"/>
<source>automatically selected</source>
<translation>自动选择的</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="136"/>
<source>Insufficient funds!</source>
<translation>金额不足!</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="213"/>
<source>Quantity:</source>
<translation>总量:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="235"/>
<location filename="../forms/sendcoinsdialog.ui" line="270"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="251"/>
<source>Bytes:</source>
<translation>字节:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="302"/>
<source>Amount:</source>
<translation>金额:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="324"/>
<location filename="../forms/sendcoinsdialog.ui" line="410"/>
<location filename="../forms/sendcoinsdialog.ui" line="496"/>
<location filename="../forms/sendcoinsdialog.ui" line="528"/>
<source>0.00 BTC</source>
<translation>0.00 trbo</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="337"/>
<source>Priority:</source>
<translation>优先级:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="356"/>
<source>medium</source>
<translation>中</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="388"/>
<source>Fee:</source>
<translation>交易费:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="423"/>
<source>Low Output:</source>
<translation>低输出:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="442"/>
<source>no</source>
<translation>否</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="474"/>
<source>After Fee:</source>
<translation>减交易费后:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="509"/>
<source>Change</source>
<translation>找零:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="559"/>
<source>custom change address</source>
<translation>自定义零钱地址</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="665"/>
<source>Send to multiple recipients at once</source>
<translation>一次发送给多个接收者</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="668"/>
<source>&Add recipient...</source>
<translation>&添加接收者...</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="685"/>
<source>Remove all transaction fields</source>
<translation>移除所有交易项</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="688"/>
<source>Clear all</source>
<translation>清除全部</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="707"/>
<source>Balance:</source>
<translation>余额:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="714"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="745"/>
<source>Confirm the send action</source>
<translation>确认并发送货币</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="748"/>
<source>&Send</source>
<translation>&发送</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="51"/>
<source>Copy quantity</source>
<translation>复制总量</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="52"/>
<source>Copy amount</source>
<translation>复制金额</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="53"/>
<source>Copy fee</source>
<translation>复制交易费</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="54"/>
<source>Copy after fee</source>
<translation>复制去除交易费后的金额</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="55"/>
<source>Copy bytes</source>
<translation>复制字节</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="56"/>
<source>Copy priority</source>
<translation>复制优先级</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="57"/>
<source>Copy low output</source>
<translation>复制低输出</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="58"/>
<source>Copy change</source>
<translation>复制金额</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="144"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> 到 %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="149"/>
<source>Confirm send coins</source>
<translation>确认发送货币</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="150"/>
<source>Are you sure you want to send %1?</source>
<translation>确定您要发送 %1?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="150"/>
<source> and </source>
<translation> 和 </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="182"/>
<source>The amount to pay must be at least one cent (0.01).</source>
<translation>支付金额必须至少1分(0.01)。</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="457"/>
<source>Warning: Invalid Bitcoin address</source>
<translation>警告:无效的币地址</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="466"/>
<source>Warning: Unknown change address</source>
<translation>警告:未知的找零地址</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="477"/>
<source>(no label)</source>
<translation>(没有标签)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="187"/>
<source>Amount exceeds your balance</source>
<translation>余额不足</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="36"/>
<source>Enter a TurboStake address</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="177"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="192"/>
<source>Total exceeds your balance when the %1 transaction fee is included</source>
<translation>计入 %1 的交易费后,您的余额不足以支付总价</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="198"/>
<source>Duplicate address found, can only send to each address once in one send operation</source>
<translation>发现重复地址,一次操作中只可以给每个地址发送一次</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="203"/>
<source>Error: Transaction creation failed </source>
<translation>错误:交易创建失败 </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="208"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>错误:交易被拒绝。这种情况通常发生在您钱包中的一些货币已经被消费之后,比如您使用了一个wallet.dat的副本,而货币在那个副本中已经被消费,但在当前钱包中未被标记为已消费。</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>表单</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>金额(&M):</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>支付到(&T):</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>为这个地址输入一个标签,以便将它添加到您的地址簿</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>标签(&L):</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to</source>
<translation>付款给这个地址</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>从地址薄选择地址</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>从剪贴板粘贴地址</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>移除此接收者</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a TurboStake address</source>
<translation>输入TurboStake地址</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>签名 - 为消息签名/验证签名消息</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="24"/>
<source>&Sign Message</source>
<translation>签名消息(&S)</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="30"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>您可以用你的地址对消息进行签名,以证明您是该地址的所有人。注意不要对模棱两可的消息签名,以免遭受钓鱼式攻击。请确保消息真实明确的表达了您的意愿。</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="48"/>
<source>The address to sign the message with</source>
<translation>用于签名消息的地址</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="55"/>
<location filename="../forms/signverifymessagedialog.ui" line="265"/>
<source>Choose previously used address</source>
<translation>选择以前用过的地址</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="65"/>
<location filename="../forms/signverifymessagedialog.ui" line="275"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="75"/>
<source>Paste address from clipboard</source>
<translation>从剪贴板粘贴地址</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="85"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="97"/>
<source>Enter the message you want to sign here</source>
<translation>请输入您要签名的消息</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="104"/>
<source>Signature</source>
<translation>签名</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="131"/>
<source>Copy the current signature to the system clipboard</source>
<translation>复制当前签名至剪切板</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="152"/>
<source>Sign the message to prove you own this TurboStake address</source>
<translation>签名消息,证明这个地址属于您</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="155"/>
<source>Sign &Message</source>
<translation>消息签名(&M)</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="169"/>
<source>Reset all sign message fields</source>
<translation>清空所有签名消息栏</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="172"/>
<location filename="../forms/signverifymessagedialog.ui" line="315"/>
<source>Clear &All</source>
<translation>清除所有(&A)</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="231"/>
<source>&Verify Message</source>
<translation>验证消息(&V)</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="237"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>在下面输入签名地址、消息(请确保换行符、空格符、制表符等等一个不漏)和签名以验证消息。小心签名的保护有限,要理解所签消息本身信息,提防中间人攻击。</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="258"/>
<source>The address the message was signed with</source>
<translation>用于签名消息的地址</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="295"/>
<source>Verify the message to ensure it was signed with the specified TurboStake address</source>
<translation>验证消息,确保消息是由指定的TurboStake地址签名过的</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="298"/>
<source>Verify &Message</source>
<translation>验证消息签名(&M)</translation>
</message>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="312"/>
<source>Reset all verify message fields</source>
<translation>清空所有验证消息栏</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="29"/>
<source>Click "Sign Message" to generate signature</source>
<translation>单击“签名消息“产生签名</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="30"/>
<source>Enter the signature of the message</source>
<translation>输入消息的签名</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="31"/>
<location filename="../signverifymessagedialog.cpp" line="32"/>
<source>Enter a TurboStake address</source>
<translation>输入一个TurboStake地址</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="115"/>
<location filename="../signverifymessagedialog.cpp" line="195"/>
<source>The entered address is invalid.</source>
<translation>输入的地址非法。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="115"/>
<location filename="../signverifymessagedialog.cpp" line="123"/>
<location filename="../signverifymessagedialog.cpp" line="195"/>
<location filename="../signverifymessagedialog.cpp" line="203"/>
<source>Please check the address and try again.</source>
<translation>请检查地址后重试。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="123"/>
<location filename="../signverifymessagedialog.cpp" line="203"/>
<source>The entered address does not refer to a key.</source>
<translation>输入的地址没有关联的公私钥对。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="131"/>
<source>Wallet unlock was cancelled.</source>
<translation>钱包解锁动作取消。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="139"/>
<source>Private key for the entered address is not available.</source>
<translation>找不到输入地址关联的私钥。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="151"/>
<source>Message signing failed.</source>
<translation>消息签名失败。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="156"/>
<source>Message signed.</source>
<translation>消息已签名。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="214"/>
<source>The signature could not be decoded.</source>
<translation>签名无法解码。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="214"/>
<location filename="../signverifymessagedialog.cpp" line="227"/>
<source>Please check the signature and try again.</source>
<translation>请检查签名后重试。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="227"/>
<source>The signature did not match the message digest.</source>
<translation>签名与消息摘要不匹配。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="234"/>
<source>Message verification failed.</source>
<translation>消息验证失败。</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="239"/>
<source>Message verified.</source>
<translation>消息验证成功。</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="21"/>
<source>Open for %1 blocks</source>
<translation>开启 %1 个数据块</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="23"/>
<source>Open until %1</source>
<translation>至 %1 个数据块时开启</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="29"/>
<source>%1/offline?</source>
<translation>%1/离线?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="31"/>
<source>%1/unconfirmed</source>
<translation>%1/未确认</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="33"/>
<source>%1 confirmations</source>
<translation>%1 确认项</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="51"/>
<source><b>Status:</b> </source>
<translation><b>状态:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, has not been successfully broadcast yet</source>
<translation>, 未被成功广播</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="58"/>
<source>, broadcast through %1 node</source>
<translation>,同过 %1 节点广播</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source>, broadcast through %1 nodes</source>
<translation>,同过 %1 节点组广播</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="64"/>
<source><b>Date:</b> </source>
<translation><b>日期:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="71"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>来源:</b> 生成<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="77"/>
<location filename="../transactiondesc.cpp" line="94"/>
<source><b>From:</b> </source>
<translation><b>从:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source>unknown</source>
<translation>未知</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="95"/>
<location filename="../transactiondesc.cpp" line="118"/>
<location filename="../transactiondesc.cpp" line="178"/>
<source><b>To:</b> </source>
<translation><b>到:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="98"/>
<source> (yours, label: </source>
<translation>(您的, 标签:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="100"/>
<source> (yours)</source>
<translation>(您的)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="136"/>
<location filename="../transactiondesc.cpp" line="150"/>
<location filename="../transactiondesc.cpp" line="195"/>
<location filename="../transactiondesc.cpp" line="212"/>
<source><b>Credit:</b> </source>
<translation><b>到帐:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="138"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1 成熟于 %2 以上数据块)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="142"/>
<source>(not accepted)</source>
<translation>(未接受)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="186"/>
<location filename="../transactiondesc.cpp" line="194"/>
<location filename="../transactiondesc.cpp" line="209"/>
<source><b>Debit:</b> </source>
<translation>支出</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="200"/>
<source><b>Transaction fee:</b> </source>
<translation>交易费</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="218"/>
<source><b>Net amount:</b> </source>
<translation><b>网络金额:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="220"/>
<source><b>Retained amount:</b> %1 until %2 more blocks<br></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="227"/>
<source>Message:</source>
<translation>消息:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="229"/>
<source>Comment:</source>
<translation>备注</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="231"/>
<source>Transaction ID:</source>
<translation>交易ID:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="234"/>
<source>Generated coins must wait 520 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>新生产的币必须等待520个数据块之后才能被使用。 当您生产出此数据块,它被广播至比特币网络并添加至数据链。 如果添加到数据链失败, 它的状态将变成"不被接受",生产的币将不能使用. 在您生产新数据块的几秒钟内, 如果其它节点也生产出数据块,有可能会发生这种情况。</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="236"/>
<source>Staked coins must wait 520 blocks before they can return to balance and be spent. When you generated this proof-of-stake block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to "not accepted" and not be a valid stake. This may occasionally happen if another node generates a proof-of-stake block within a few seconds of yours.</source>
<translation>权益币必须等待520个数据块之后才能回到余额中被使用。 当您生产出此权益证明数据块,它被广播至比特币网络并添加至数据链。 如果添加到数据链失败, 它的状态将变成"不被接受",不能成为合法的权益,生产的币将不能使用. 在您生产新数据块的几秒钟内, 如果其它节点也生产出权益证明数据块,有可能会发生这种情况。</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>交易细节</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>当前面板显示了交易的详细描述</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Type</source>
<translation>类型</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="214"/>
<source>Amount</source>
<translation>数量</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="281"/>
<source>Open for %n block(s)</source>
<translation>
<numerusform>开启 %n 个数据块</numerusform>
</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="284"/>
<source>Open until %1</source>
<translation>至 %1 个数据块时开启</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="287"/>
<source>Offline (%1 confirmations)</source>
<translation>离线 (%1 个确认项)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="290"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>未确认 (%1 / %2 条确认信息)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="293"/>
<source>Confirmed (%1 confirmations)</source>
<translation>已确认 (%1 条确认信息)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>Mined balance will be available in %n more blocks</source>
<translation>
<numerusform>挖矿所得将在 %n 个数据块之后可用</numerusform>
</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="307"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>此区块未被其他节点接收,并可能不被接受!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="310"/>
<source>Generated but not accepted</source>
<translation>已生成但未被接受</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="353"/>
<source>Received with</source>
<translation>接收于</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="355"/>
<source>Received from</source>
<translation>收款来自</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="358"/>
<source>Sent to</source>
<translation>发送到</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="360"/>
<source>Payment to yourself</source>
<translation>付款给自己</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="362"/>
<source>Mined</source>
<translation>挖矿所得</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="364"/>
<source>Mint by stake</source>
<translation>权益铸造</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="403"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="603"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>交易状态。 鼠标移到此区域上可显示确认消息项的数目。</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="605"/>
<source>Date and time that the transaction was received.</source>
<translation>接收交易的时间</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="607"/>
<source>Type of transaction.</source>
<translation>交易类别。</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="609"/>
<source>Destination address of transaction.</source>
<translation>交易目的地址。</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="611"/>
<source>Amount removed from or added to balance.</source>
<translation>从余额添加或移除的金额</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>全部</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>今天</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>本周</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>本月</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>上月</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>今年</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>范围...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>接收于</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>发送到</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>到自己</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>挖矿所得</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Mint by stake</source>
<translation>权益铸造</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="79"/>
<source>Other</source>
<translation>其他</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="85"/>
<source>Enter address or label to search</source>
<translation>输入地址或标签进行搜索</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="91"/>
<source>Min amount</source>
<translation>最小金额</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="125"/>
<source>Copy address</source>
<translation>复制地址</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy label</source>
<translation>复制标签</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Copy amount</source>
<translation>复制金额</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Edit label</source>
<translation>编辑标签</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="129"/>
<source>Show details...</source>
<translation>显示细节...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="130"/>
<source>Clear orphans</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../transactionview.cpp" line="273"/>
<source>Export Transaction Data</source>
<translation>导出交易数据</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="274"/>
<source>Comma separated file (*.csv)</source>
<translation>逗号分隔文件(*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Confirmed</source>
<translation>已确认</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="284"/>
<source>Type</source>
<translation>类别</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="285"/>
<source>Label</source>
<translation>标签</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="286"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Amount</source>
<translation>金额</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="288"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="292"/>
<source>Error exporting</source>
<translation>导出错误</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="292"/>
<source>Could not write to file %1.</source>
<translation>无法写入文件 %1。</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="400"/>
<source>Range:</source>
<translation>范围:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="408"/>
<source>to</source>
<translation>到</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="164"/>
<source>Sending...</source>
<translation>发送中...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="11"/>
<source>Warning: Disk space is low </source>
<translation>警告:磁盘空间低</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="13"/>
<source>Usage:</source>
<translation>使用:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>Unable to bind to port %d on this computer. TurboStake is probably already running.</source>
<translation>无法绑定本机端口 %s Perunity可能已经在运行。</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="12"/>
<source>TurboStake version</source>
<translation>TurboStake版本</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="14"/>
<source>Send command to -server or TurboStaked</source>
<translation>向 -server或 TurboStaked发命令</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="15"/>
<source>List commands</source>
<translation>列出命令</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="16"/>
<source>Get help for a command</source>
<translation>获得某条命令的帮助</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="17"/>
<source>Options:</source>
<translation>选项:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Specify configuration file (default: TurboStake.conf)</source>
<translation>指定配置文件 (默认为 TurboStake.conf)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>Specify pid file (default: TurboStaked.pid)</source>
<translation>指定 pid 文件 (默认为 TurboStaked.pid)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>Generate coins</source>
<translation>生成币</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="21"/>
<source>Don't generate coins</source>
<translation>不要生成货币</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="22"/>
<source>Start minimized</source>
<translation>启动时最小化
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="23"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>启动时显示图片(缺省:1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="24"/>
<source>Specify data directory</source>
<translation>指定数据目录
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>设置数据库缓存大小,单位为兆比特(缺省:25)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="26"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>设置数据库磁盘日志大小,单位为兆比特(缺省:100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="27"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>指定连接超时时间 (微秒)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Connect through socks4 proxy</source>
<translation>通过 socks4 代理连接</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="29"/>
<source>Allow DNS lookups for addnode and connect</source>
<translation>使用 addnode和 connect 选项时点时允许DNS查找
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Listen for connections on <port> (default: 6901 or testnet: 9903)</source>
<translation>监听端口连接 <port> (缺省: 6901 或测试网络: 9903)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>最大连接数 <n> (缺省: 125)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>添加节点并与其保持连接</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="33"/>
<source>Connect only to the specified node</source>
<translation>只连接到指定节点</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="34"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>通过IRC查找节点(缺省:0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="35"/>
<source>Accept connections from outside (default: 1)</source>
<translation>接受来自外部的连接 (缺省: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>设置语言,例如"de_DE" (缺省:系统locale)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>通过DNS查找节点(缺省:1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="38"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>断开行为不端对端阀值(缺省: 100)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="39"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>重新连接异常节点的秒数(缺省: 86400)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation>每个连接的最大接收缓存,<n>*1000 字节 (缺省: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation>每个连接的最大发送缓存,<n>*1000 字节(缺省: 10000)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Use Universal Plug and Play to map the listening port (default: 1)</source>
<translation>使用UPnP映射监听端口 (缺省: 1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Use Universal Plug and Play to map the listening port (default: 0)</source>
<translation>使用UPnP映射监听端口 (缺省: 0)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<source>Fee per KB to add to transactions you send</source>
<translation>为付款交易支付费用(每kb)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>接受命令行和 JSON-RPC 命令
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="48"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>在后台运行并接受命令</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="49"/>
<source>Use the test network</source>
<translation>使用测试网络
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Output extra debugging information</source>
<translation>输出调试信息</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Prepend debug output with timestamp</source>
<translation>为调试输出信息时,前面添加时间戳</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>跟踪/调试信息输出到控制台,不输出到debug.log文件</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Send trace/debug info to debugger</source>
<translation>跟踪/调试信息输出到 调试器debugger</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="54"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC连接用户名
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="55"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC连接密码
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>Listen for JSON-RPC connections on <port> (default: 6902)</source>
<translation>JSON-RPC连接监听<端口> (默认为 6902)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>允许从指定IP接受到的JSON-RPC连接
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="58"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>向IP地址为 <ip> 的节点发送指令 (缺省: 127.0.0.1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="59"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>当最佳数据块变化时执行命令 (命令行中的 %s 被替换成数据块哈希值)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Upgrade wallet to latest format</source>
<translation>将钱包升级到最新的格式</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>设置密钥池大小为 <n> (缺省: 100)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>重新扫描数据链以查找钱包遗漏的交易</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>启动时检测多少个数据块(缺省:2500,0=所有)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>块验证的全面程度(0-6,缺省:1)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>
SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL选项:(参见Bitcoin Wiki关于SSL设置栏目)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>为 JSON-RPC 连接使用 OpenSSL (https)连接</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Server certificate file (default: server.cert)</source>
<translation>服务器证书 (默认为 server.cert)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Server private key (default: server.pem)</source>
<translation>服务器私钥 (默认为 server.pem)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>可接受的加密器 (默认为 TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>This help message</source>
<translation>本帮助信息
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="77"/>
<source>Usage</source>
<translation>使用</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="78"/>
<source>Cannot obtain a lock on data directory %s. TurboStake is probably already running.</source>
<translation>无法锁住数据目录%s。TurboStake可能已经在运行中。</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>TurboStake</source>
<translation>TurboStake</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="88"/>
<source>Error loading wallet.dat: Wallet requires newer version of TurboStake</source>
<translation>wallet.dat钱包文件加载错误:钱包需要更新版本的TurboStake</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="89"/>
<source>Wallet needed to be rewritten: restart TurboStake to complete</source>
<translation>钱包文件需要被重写:请重新启动TurboStake客户端</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="103"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=peercoinrpc
rpcpassword=%s
(you do not need to remember this password)
If the file does not exist, create it with owner-readable-only file permissions.
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="119"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong TurboStake will not work properly.</source>
<translation>警告:请检查电脑的日期时间设置是否正确。时间错误可能会导致TurboStake客户端运行异常。</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="82"/>
<source>Loading addresses...</source>
<translation>正在加载地址...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="83"/>
<source>Error loading addr.dat</source>
<translation>addr.dat文件加载错误</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="84"/>
<source>Loading block index...</source>
<translation>正在加载区块索引...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="85"/>
<source>Error loading blkindex.dat</source>
<translation>blkindex.dat文件加载错误</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="86"/>
<source>Loading wallet...</source>
<translation>正在加载钱包...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="87"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat钱包文件加载错误:钱包损坏</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="90"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat钱包文件加载错误</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="91"/>
<source>Cannot downgrade wallet</source>
<translation>无法降级钱包</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="92"/>
<source>Cannot initialize keypool</source>
<translation>无法初始化秘钥池</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="93"/>
<source>Cannot write default address</source>
<translation>无法写入默认地址</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="94"/>
<source>Rescanning...</source>
<translation>正在重新扫描...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="95"/>
<source>Done loading</source>
<translation>加载完成</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="96"/>
<source>Invalid -proxy address</source>
<translation>代理地址不合法</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="97"/>
<source>Invalid amount for -paytxfee=<amount></source>
<translation>非法金额 -paytxfee=<amount></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="98"/>
<source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source>
<translation>警告: -paytxfee 交易费设置很高。 每笔交易都将支付该数量的交易费.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="101"/>
<source>Error: CreateThread(StartNode) failed</source>
<translation>错误:线程创建(StartNode)失败</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="102"/>
<source>To use the %s option</source>
<translation>使用 %s 选项</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="112"/>
<source>Error</source>
<translation>错误</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="113"/>
<source>An error occured while setting up the RPC port %i for listening: %s</source>
<translation>当设置RPC监听端口%i时出现错误:%s</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="114"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translatorcomment>您必须在配置文件设置rpcpassword=<password>:
%s
如果配置文件不存在,请自行建立一个只有所有者拥有只读权限的文件。</translatorcomment>
<translation>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="122"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>错误:钱包被锁定,无法创建交易。</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="123"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>错误:需要支付不少于%s的交易费用,因为该交易的数量、复杂度或者动用了刚收到不久的资金。</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="126"/>
<source>Error: Transaction creation failed </source>
<translation>错误:交易创建失败</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="127"/>
<source>Sending...</source>
<translation>发送中...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="128"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>错误:交易被拒绝。这种情况通常发生在您钱包中的一些币已经被用之后,比如您使用了一个wallet.dat的副本,而货币在那个副本中已经被消费,但在当前钱包中未被标记为已用掉。</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="132"/>
<source>Invalid amount</source>
<translation>无效金额</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="133"/>
<source>Insufficient funds</source>
<translation>金额不足</translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>video_capture_device_linux.cc<|end_file_name|><|fim▁begin|>// 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 "media/video/capture/linux/video_capture_device_linux.h"
#if defined(OS_OPENBSD)
#include <sys/videoio.h>
#else
#include <linux/videodev2.h>
#endif
#include <list>
#include "base/bind.h"
#include "base/strings/stringprintf.h"
#include "media/video/capture/linux/v4l2_capture_delegate.h"
namespace media {
// USB VID and PID are both 4 bytes long.
static const size_t kVidPidSize = 4;
// /sys/class/video4linux/video{N}/device is a symlink to the corresponding
// USB device info directory.
static const char kVidPathTemplate[] =
"/sys/class/video4linux/%s/device/../idVendor";
static const char kPidPathTemplate[] =
"/sys/class/video4linux/%s/device/../idProduct";
static bool ReadIdFile(const std::string path, std::string* id) {
char id_buf[kVidPidSize];
FILE* file = fopen(path.c_str(), "rb");
if (!file)
return false;
const bool success = fread(id_buf, kVidPidSize, 1, file) == 1;
fclose(file);
if (!success)
return false;
id->append(id_buf, kVidPidSize);
return true;
}
// Translates Video4Linux pixel formats to Chromium pixel formats.
// static
VideoPixelFormat VideoCaptureDeviceLinux::V4l2FourCcToChromiumPixelFormat(
uint32 v4l2_fourcc) {
return V4L2CaptureDelegate::V4l2FourCcToChromiumPixelFormat(v4l2_fourcc);
}
// Gets a list of usable Four CC formats prioritised.
// static
std::list<uint32_t> VideoCaptureDeviceLinux::GetListOfUsableFourCCs(
bool favour_mjpeg) {
return V4L2CaptureDelegate::GetListOfUsableFourCcs(favour_mjpeg);
}
const std::string VideoCaptureDevice::Name::GetModel() const {
// |unique_id| is of the form "/dev/video2". |file_name| is "video2".
const std::string dev_dir = "/dev/";
DCHECK_EQ(0, unique_id_.compare(0, dev_dir.length(), dev_dir));
const std::string file_name =
unique_id_.substr(dev_dir.length(), unique_id_.length());
const std::string vidPath =
base::StringPrintf(kVidPathTemplate, file_name.c_str());
const std::string pidPath =
base::StringPrintf(kPidPathTemplate, file_name.c_str());
std::string usb_id;
if (!ReadIdFile(vidPath, &usb_id))
return "";
usb_id.append(":");
if (!ReadIdFile(pidPath, &usb_id))
return "";
return usb_id;
}
VideoCaptureDeviceLinux::VideoCaptureDeviceLinux(const Name& device_name)
: v4l2_thread_("V4L2CaptureThread"),
device_name_(device_name) {
}
VideoCaptureDeviceLinux::~VideoCaptureDeviceLinux() {
// Check if the thread is running.
// This means that the device has not been StopAndDeAllocate()d properly.
DCHECK(!v4l2_thread_.IsRunning());
v4l2_thread_.Stop();
}
void VideoCaptureDeviceLinux::AllocateAndStart(
const VideoCaptureParams& params,
scoped_ptr<VideoCaptureDevice::Client> client) {<|fim▁hole|> v4l2_thread_.Start();
const int line_frequency =
TranslatePowerLineFrequencyToV4L2(GetPowerLineFrequencyForLocation());
capture_impl_ = V4L2CaptureDelegate::CreateV4L2CaptureDelegate(
device_name_, v4l2_thread_.message_loop_proxy(), line_frequency);
if (!capture_impl_) {
client->OnError("Failed to create VideoCaptureDelegate");
return;
}
v4l2_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2CaptureDelegate::AllocateAndStart, capture_impl_,
params.requested_format.frame_size.width(),
params.requested_format.frame_size.height(),
params.requested_format.frame_rate, base::Passed(&client)));
}
void VideoCaptureDeviceLinux::StopAndDeAllocate() {
if (!v4l2_thread_.IsRunning())
return; // Wrong state.
v4l2_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2CaptureDelegate::StopAndDeAllocate, capture_impl_));
v4l2_thread_.Stop();
capture_impl_ = NULL;
}
void VideoCaptureDeviceLinux::SetRotation(int rotation) {
if (v4l2_thread_.IsRunning()) {
v4l2_thread_.message_loop()->PostTask(
FROM_HERE, base::Bind(&V4L2CaptureDelegate::SetRotation,
capture_impl_, rotation));
}
}
// static
int VideoCaptureDeviceLinux::TranslatePowerLineFrequencyToV4L2(int frequency) {
switch (frequency) {
case kPowerLine50Hz:
return V4L2_CID_POWER_LINE_FREQUENCY_50HZ;
case kPowerLine60Hz:
return V4L2_CID_POWER_LINE_FREQUENCY_60HZ;
default:
// If we have no idea of the frequency, at least try and set it to AUTO.
return V4L2_CID_POWER_LINE_FREQUENCY_AUTO;
}
}
} // namespace media<|fim▁end|> | DCHECK(!capture_impl_);
if (v4l2_thread_.IsRunning())
return; // Wrong state. |
<|file_name|>run_tutorial_a.py<|end_file_name|><|fim▁begin|>from __future__ import print_function
from pysb.simulator import ScipyOdeSimulator<|fim▁hole|>simresult = simulator.run()
print(simresult.species)<|fim▁end|> | from tutorial_a import model
t = [0, 10, 20, 30, 40, 50, 60]
simulator = ScipyOdeSimulator(model, tspan=t) |
<|file_name|>module.js<|end_file_name|><|fim▁begin|>M.tool_assignmentupgrade = {
init_upgrade_table: function(Y) {
Y.use('node', function(Y) {
checkboxes = Y.all('td.c0 input');
checkboxes.each(function(node) {
node.on('change', function(e) {
rowelement = e.currentTarget.get('parentNode').get('parentNode');
if (e.currentTarget.get('checked')) {
rowelement.setAttribute('class', 'selectedrow');
} else {
rowelement.setAttribute('class', 'unselectedrow');
}
});
rowelement = node.get('parentNode').get('parentNode');
if (node.get('checked')) {
rowelement.setAttribute('class', 'selectedrow');
} else {
rowelement.setAttribute('class', 'unselectedrow');
}
});
});
var selectall = Y.one('th.c0 input');
selectall.on('change', function(e) {
if (e.currentTarget.get('checked')) {
checkboxes = Y.all('td.c0 input');
checkboxes.each(function(node) {
rowelement = node.get('parentNode').get('parentNode');
node.set('checked', true);
rowelement.setAttribute('class', 'selectedrow');
});
} else {
checkboxes = Y.all('td.c0 input');<|fim▁hole|> node.set('checked', false);
rowelement.setAttribute('class', 'unselectedrow');
});
}
});
var batchform = Y.one('.tool_assignmentupgrade_batchform form');
batchform.on('submit', function(e) {
checkboxes = Y.all('td.c0 input');
var selectedassignments = [];
checkboxes.each(function(node) {
if (node.get('checked')) {
selectedassignments[selectedassignments.length] = node.get('value');
}
});
operation = Y.one('#id_operation');
assignmentsinput = Y.one('input.selectedassignments');
assignmentsinput.set('value', selectedassignments.join(','));
if (selectedassignments.length == 0) {
alert(M.str.assign.noassignmentsselected);
e.preventDefault();
}
});
var perpage = Y.one('#id_perpage');
perpage.on('change', function(e) {
window.onbeforeunload = null;
Y.one('.tool_assignmentupgrade_paginationform form').submit();
});
}
}<|fim▁end|> | checkboxes.each(function(node) {
rowelement = node.get('parentNode').get('parentNode'); |
<|file_name|>models.js<|end_file_name|><|fim▁begin|>/**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/<|fim▁hole|>
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
// connection: 'localDiskDb',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
migrate: 'safe',
schema: true,
/**
* This method adds records to the database
*
* To use add a variable 'seedData' in your model and call the
* method in the bootstrap.js file
*/
seed: function (callback) {
var self = this;
var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1);
if (!self.seedData) {
sails.log.debug('No data avaliable to seed ' + modelName);
callback();
return;
}
self.count().exec(function (err, count) {
if (!err && count === 0) {
sails.log.debug('Seeding ' + modelName + '...');
if (self.seedData instanceof Array) {
self.seedArray(callback);
}else{
self.seedObject(callback);
}
} else {
sails.log.debug(modelName + ' had models, so no seed needed');
callback();
}
});
},
seedArray: function (callback) {
var self = this;
var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1);
self.createEach(self.seedData).exec(function (err, results) {
if (err) {
sails.log.debug(err);
callback();
} else {
sails.log.debug(modelName + ' seed planted');
callback();
}
});
},
seedObject: function (callback) {
var self = this;
var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1);
self.create(self.seedData).exec(function (err, results) {
if (err) {
sails.log.debug(err);
callback();
} else {
sails.log.debug(modelName + ' seed planted');
callback();
}
});
}
};<|fim▁end|> |
module.exports.models = { |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict';
// https://github.com/jambit/eslint-plugin-typed-redux-saga
module.exports = {
rules: {
'use-typed-effects': require('./rules/use-typed-effects'),
'delegate-effects': require('./rules/delegate-effects'),<|fim▁hole|><|fim▁end|> | },
}; |
<|file_name|>gaussian_kde.go<|end_file_name|><|fim▁begin|>package bayes
import (
"fmt"
. "fp/mat"
"math"
)
type GaussianKDE struct {
d, n int
normFactor float64
dataset *Mat
covariance, invCov *Mat
}
func NewGaussianKDE(dataset *Mat, bw_method ...float64) *GaussianKDE {
if dataset.Cols() <= 1 {
panic("`dataset` input should have multiple elements")
}
d := dataset.Rows()
n := dataset.Cols()
var bandwidth float64
if len(bw_method) != 0 {
bandwidth = bw_method[0]
} else {
//scotts factor
bandwidth = math.Pow(float64(n), -1.0/float64(d+4))
}
factor := bandwidth
_data_covariance := CovOfRowvecs(dataset, 0)
_data_inv_cov := _data_covariance.Inv()
covariance := _data_covariance.MulScale(factor * factor)
invCov := _data_inv_cov.DivScale(factor * factor)
normFactor := math.Sqrt(covariance.MulScale(2*math.Pi).Det()) * float64(n)
return &GaussianKDE{
d: d,
n: n,
normFactor: normFactor,
dataset: dataset.Clone(),
covariance: covariance,
invCov: invCov,
}
}
<|fim▁hole|>//Parameters
//----------
//points : (# of dimensions, # of points)-array
// Alternatively, a (# of dimensions,) vector can be passed in and
// treated as a single point.
//Returns
//-------
//values : (# of points,)-array
// The values at each point.
//Raises
//------
//ValueError : if the dimensionality of the input points is different than
// the dimensionality of the KDE.
//"""
func (self *GaussianKDE) Evaluate(points *Mat) *Mat {
d, m := points.Rows(), points.Cols()
if d != self.d {
panic(fmt.Errorf("points have dimension %v, dataset has dimension %v", d, self.d))
}
result := MatZeros(1, m)
if m >= self.n {
//there are more points than data, so loop over data
for i := 0; i < self.n; i++ {
diff := points.MulScale(-1.0).Add(self.dataset.NthCol(i))
tdiff := self.invCov.Mul(diff)
energy := diff.MulBit(tdiff).SumOfColvecs().DivScale(2.0)
result.AddEqual(Exp(energy.MulScale(-1.0)))
}
return result.DivScale(self.normFactor)
} else {
for i := 0; i < m; i++ {
diff := self.dataset.Sub(points.NthCol(i))
tdiff := self.invCov.Mul(diff)
energy := diff.MulBit(tdiff).SumOfColvecs().DivScale(2.0)
result.Set(0, i, Exp(energy.MulScale(-1.0)).SumOfAll())
}
return result.DivScale(self.normFactor)
}
}
func (self *GaussianKDE) Pdf(points *Mat) *Mat {
return self.Evaluate(points)
}<|fim▁end|> | //"""Evaluate the estimated pdf on a set of points. |
<|file_name|>class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.js<|end_file_name|><|fim▁begin|>var class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee =
[
[ "AccountId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#aa5f13daf52f6212580695248d62ed83d", null ],
[ "AuditTs", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a95210c8ea60bb4107cb1a76b0617e58a", null ],
[ "AuditUserId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#ad3b75c8f461c7ebc2756c1fddca8991d", null ],<|fim▁hole|> [ "IsFlatAmount", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a7f09ea80a18909ebaeb1f2c561a63e77", null ],
[ "LateFeeCode", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#af38567944abc8be98c7ac91c30d4f1f5", null ],
[ "LateFeeId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a95fd529069d0e5705260329f8d895e5c", null ],
[ "LateFeeName", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a770c2823bf447fb41c54062fef2334ba", null ],
[ "Rate", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#ab6a4512cbe1dcde39c2ec00be539acbf", null ]
];<|fim▁end|> | |
<|file_name|>api.py<|end_file_name|><|fim▁begin|>from kolibri.auth.api import KolibriAuthPermissions, KolibriAuthPermissionsFilter
from kolibri.content.api import OptionalPageNumberPagination
from rest_framework import filters, viewsets
from .models import ContentRatingLog, ContentSessionLog, ContentSummaryLog, UserSessionLog
from .serializers import ContentRatingLogSerializer, ContentSessionLogSerializer, ContentSummaryLogSerializer, UserSessionLogSerializer
class ContentSessionLogFilter(filters.FilterSet):
class Meta:<|fim▁hole|> model = ContentSessionLog
fields = ['user_id', 'content_id']
class ContentSessionLogViewSet(viewsets.ModelViewSet):
permission_classes = (KolibriAuthPermissions,)
filter_backends = (KolibriAuthPermissionsFilter, filters.DjangoFilterBackend)
queryset = ContentSessionLog.objects.all()
serializer_class = ContentSessionLogSerializer
pagination_class = OptionalPageNumberPagination
filter_class = ContentSessionLogFilter
class ContentSummaryFilter(filters.FilterSet):
class Meta:
model = ContentSummaryLog
fields = ['user_id', 'content_id']
class ContentSummaryLogViewSet(viewsets.ModelViewSet):
permission_classes = (KolibriAuthPermissions,)
filter_backends = (KolibriAuthPermissionsFilter, filters.DjangoFilterBackend)
queryset = ContentSummaryLog.objects.all()
serializer_class = ContentSummaryLogSerializer
pagination_class = OptionalPageNumberPagination
filter_class = ContentSummaryFilter
class ContentRatingLogViewSet(viewsets.ModelViewSet):
permission_classes = (KolibriAuthPermissions,)
filter_backends = (KolibriAuthPermissionsFilter,)
queryset = ContentRatingLog.objects.all()
serializer_class = ContentRatingLogSerializer
pagination_class = OptionalPageNumberPagination
class UserSessionLogViewSet(viewsets.ModelViewSet):
permission_classes = (KolibriAuthPermissions,)
filter_backends = (KolibriAuthPermissionsFilter,)
queryset = UserSessionLog.objects.all()
serializer_class = UserSessionLogSerializer
pagination_class = OptionalPageNumberPagination<|fim▁end|> | |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 Guanhao Yin <sopium@mysterious.site>
// This file is part of TiTun.
// TiTun 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<|fim▁hole|>// 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 TiTun. If not, see <https://www.gnu.org/licenses/>.
pub mod commands;
// Export for fuzzing.
#[doc(hidden)]
pub mod parse;
mod server;
mod wait_delete;
pub use self::server::*;<|fim▁end|> | // (at your option) any later version.
// TiTun is distributed in the hope that it will be useful, |
<|file_name|>injectStyles.js<|end_file_name|><|fim▁begin|>// @flow
/* global document */
export default function injectStyles(styles: any) {
const stylesElement = document.createElement('style');<|fim▁hole|><|fim▁end|> | stylesElement.innerText = styles.toString();
return stylesElement;
} |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | from schema import * |
<|file_name|>FileDropZoneView.js<|end_file_name|><|fim▁begin|>//==============================================================================
//
// File drop zone view
//
//==============================================================================
(function(app, config, $)
{
app.FileDropZoneView = Marionette.ItemView.extend({
events : {
'drop' : 'handleDrop'
},
initialize : function()
{
_.bindAll(this, 'enableEffect', 'disableEffect');
},
delegateEvents : function()
{
// Check browser compatibility
if(!(window.File && window.FileList && window.FileReader))
{
return;
}
Marionette.ItemView.prototype.delegateEvents.apply(this, arguments);
this.el.addEventListener('dragover', this.enableEffect, false);
this.el.addEventListener('dragleave', this.disableEffect, false);
},
undelegateEvents : function()
{
// Check browser compatibility
if(!(window.File && window.FileList && window.FileReader))
{
return;
}
this.el.removeEventListener('dragover', this.enableEffect, false);
this.el.removeEventListener('dragleave', this.disableEffect, false);
Marionette.ItemView.prototype.undelegateEvents.apply(this, arguments);
},
enableEffect : function(e)
{
e.preventDefault();
e.stopPropagation();
if(!this._isFileTransfer(e)) return;
if(this.disableTimer) clearTimeout(this.disableTimer);
this.$el.addClass('active');
},
disableEffect : function(e)
{
if(this.disableTimer) clearTimeout(this.disableTimer);
var _this = this;
this.disableTimer = setTimeout(function()
{
_this.$el.removeClass('active');
}, 100);
},
handleDrop : function(e)
{
e.preventDefault();
e.stopPropagation();
this.disableEffect();
var files = e.originalEvent.dataTransfer.files || e.originalEvent.target.files;
if(files && files.length > 0)
{
this.trigger('drop', files);
}
},
_isFileTransfer : function(e)
{
if(e.dataTransfer.types)<|fim▁hole|> {
for(var i = 0; i < e.dataTransfer.types.length; i++)
{
if(e.dataTransfer.types[i] === 'Files') return true;
}
return false;
}
return true;
}
});
})(window.Application, window.chatConfig, jQuery);<|fim▁end|> | |
<|file_name|>jquery-ui-1.10.3.custom.js<|end_file_name|><|fim▁begin|>/*! jQuery UI - v1.10.3 - 2014-01-12
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.accordion.js, jquery.ui.progressbar.js, jquery.ui.slider.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function( $, undefined ) {
var uuid = 0,
runiqueId = /^ui-id-\d+$/;
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.10.3",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.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 ),
scrollParent: function() {
var scrollParent;
if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
}
return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
},
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;
},
uniqueId: function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + (++uuid);
}
});
},
removeUniqueId: function() {
return this.each(function() {
if ( runiqueId.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() );
$.support.selectstart = "onselectstart" in document.createElement( "div" );
$.fn.extend({
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
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 ) {
var i,
set = instance.plugins[ name ];
if ( !set || !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 );
}
}
}
},
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
}
});
})( jQuery );
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
(function( $, undefined ) {
var mouseHandled = false;
$( document ).mouseup( function() {
mouseHandled = false;
});
$.widget("ui.mouse", {
version: "1.10.3",
options: {
cancel: "input,textarea,button,select,option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var that = this;
this.element
.bind("mousedown."+this.widgetName, function(event) {
return that._mouseDown(event);
})
.bind("click."+this.widgetName, function(event) {
if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
$.removeData(event.target, that.widgetName + ".preventClickEvent");
event.stopImmediatePropagation();
return false;
}
});
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind("."+this.widgetName);
if ( this._mouseMoveDelegate ) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
}
},
_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
if( mouseHandled ) { return; }
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));
this._mouseDownEvent = event;
var that = this,
btnIsLeft = (event.which === 1),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
that.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
$.removeData(event.target, this.widgetName + ".preventClickEvent");
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return that._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return that._mouseUp(event);
};
$(document)
.bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.bind("mouseup."+this.widgetName, this._mouseUpDelegate);
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
return this._mouseUp(event);
}
if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}
return !this._mouseStarted;
},
_mouseUp: function(event) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
if (event.target === this._mouseDownEvent.target) {
$.data(event.target, this.widgetName + ".preventClickEvent", true);
}
this._mouseStop(event);
}
return false;
},
_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(/* event */) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(/* event */) {},
_mouseDrag: function(/* event */) {},
_mouseStop: function(/* event */) {},
_mouseCapture: function(/* event */) { return true; }
});
})(jQuery);
(function( $, undefined ) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] );
return {
element: withinElement,
isWindow: isWindow,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
}( jQuery ) );
(function( $, undefined ) {
var uid = 0,
hideProps = {},
showProps = {};
hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
showProps.borderTopWidth = showProps.borderBottomWidth = "show";
$.widget( "ui.accordion", {
version: "1.10.3",
options: {
active: 0,
animate: {},
collapsible: false,
event: "click",
header: "> li > :first-child,> :not(li):even",
heightStyle: "auto",
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
},
// callbacks
activate: null,
beforeActivate: null
},
_create: function() {
var options = this.options;
this.prevShow = this.prevHide = $();
this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
// ARIA
.attr( "role", "tablist" );
// don't allow collapsible: false and active: false / null
if ( !options.collapsible && (options.active === false || options.active == null) ) {
options.active = 0;
}
this._processPanels();
// handle negative values
if ( options.active < 0 ) {
options.active += this.headers.length;
}
this._refresh();
},
_getCreateEventData: function() {
return {
header: this.active,
panel: !this.active.length ? $() : this.active.next(),
content: !this.active.length ? $() : this.active.next()
};
},
_createIcons: function() {
var icons = this.options.icons;
if ( icons ) {
$( "<span>" )
.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
.prependTo( this.headers );
this.active.children( ".ui-accordion-header-icon" )
.removeClass( icons.header )
.addClass( icons.activeHeader );
this.headers.addClass( "ui-accordion-icons" );
}
},
_destroyIcons: function() {
this.headers
.removeClass( "ui-accordion-icons" )
.children( ".ui-accordion-header-icon" )
.remove();
},
_destroy: function() {
var contents;
// clean up main element
this.element
.removeClass( "ui-accordion ui-widget ui-helper-reset" )
.removeAttr( "role" );
// clean up headers
this.headers
.removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
.removeAttr( "role" )
.removeAttr( "aria-selected" )
.removeAttr( "aria-controls" )
.removeAttr( "tabIndex" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
this._destroyIcons();
// clean up content panels
contents = this.headers.next()
.css( "display", "" )
.removeAttr( "role" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-labelledby" )
.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
if ( this.options.heightStyle !== "content" ) {
contents.css( "height", "" );
}
},
_setOption: function( key, value ) {
if ( key === "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "event" ) {
if ( this.options.event ) {
this._off( this.headers, this.options.event );
}
this._setupEvents( value );
}
this._super( key, value );
// setting collapsible: false while collapsed; open first panel
if ( key === "collapsible" && !value && this.options.active === false ) {
this._activate( 0 );
}
if ( key === "icons" ) {
this._destroyIcons();
if ( value ) {
this._createIcons();
}
}
// #5332 - opacity doesn't cascade to positioned elements in IE
// so we need to add the disabled class to the headers and panels
if ( key === "disabled" ) {
this.headers.add( this.headers.next() )
.toggleClass( "ui-state-disabled", !!value );
}
},
_keydown: function( event ) {
/*jshint maxcomplexity:15*/
if ( event.altKey || event.ctrlKey ) {
return;
}
var keyCode = $.ui.keyCode,
length = this.headers.length,
currentIndex = this.headers.index( event.target ),
toFocus = false;
switch ( event.keyCode ) {
case keyCode.RIGHT:
case keyCode.DOWN:
toFocus = this.headers[ ( currentIndex + 1 ) % length ];
break;
case keyCode.LEFT:
case keyCode.UP:
toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
break;
case keyCode.SPACE:
case keyCode.ENTER:
this._eventHandler( event );
break;
case keyCode.HOME:
toFocus = this.headers[ 0 ];
break;
case keyCode.END:
toFocus = this.headers[ length - 1 ];
break;
}
if ( toFocus ) {
$( event.target ).attr( "tabIndex", -1 );
$( toFocus ).attr( "tabIndex", 0 );
toFocus.focus();
event.preventDefault();
}
},
_panelKeyDown : function( event ) {
if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
$( event.currentTarget ).prev().focus();
}
},
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} else if ( options.active === false ) {
this._activate( 0 );
// was active, but active panel is gone
} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
// all remaining panel are disabled
if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate( Math.max( 0, options.active - 1 ) );
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index( this.active );
}
this._destroyIcons();
this._refresh();
},
_processPanels: function() {
this.headers = this.element.find( this.options.header )
.addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );
this.headers.next()
.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
.filter(":not(.ui-accordion-content-active)")
.hide();
},
_refresh: function() {
var maxHeight,
options = this.options,
heightStyle = options.heightStyle,
parent = this.element.parent(),
accordionId = this.accordionId = "ui-accordion-" +
(this.element.attr( "id" ) || ++uid);
this.active = this._findActive( options.active )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
.removeClass( "ui-corner-all" );
this.active.next()
.addClass( "ui-accordion-content-active" )
.show();
this.headers
.attr( "role", "tab" )
.each(function( i ) {
var header = $( this ),
headerId = header.attr( "id" ),
panel = header.next(),
panelId = panel.attr( "id" );
if ( !headerId ) {
headerId = accordionId + "-header-" + i;
header.attr( "id", headerId );
}
if ( !panelId ) {
panelId = accordionId + "-panel-" + i;
panel.attr( "id", panelId );
}
header.attr( "aria-controls", panelId );
panel.attr( "aria-labelledby", headerId );
})
.next()
.attr( "role", "tabpanel" );
this.headers
.not( this.active )
.attr({
"aria-selected": "false",
tabIndex: -1
})
.next()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
})
.hide();
// make sure at least one header is in the tab order
if ( !this.active.length ) {
this.headers.eq( 0 ).attr( "tabIndex", 0 );
} else {
this.active.attr({
"aria-selected": "true",
tabIndex: 0
})
.next()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
this._createIcons();
this._setupEvents( options.event );
if ( heightStyle === "fill" ) {
maxHeight = parent.height();
this.element.siblings( ":visible" ).each(function() {
var elem = $( this ),
position = elem.css( "position" );
if ( position === "absolute" || position === "fixed" ) {
return;
}
maxHeight -= elem.outerHeight( true );
});
this.headers.each(function() {
maxHeight -= $( this ).outerHeight( true );
});
this.headers.next()
.each(function() {
$( this ).height( Math.max( 0, maxHeight -
$( this ).innerHeight() + $( this ).height() ) );
})
.css( "overflow", "auto" );
} else if ( heightStyle === "auto" ) {
maxHeight = 0;
this.headers.next()
.each(function() {
maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
})
.height( maxHeight );
}
},
_activate: function( index ) {
var active = this._findActive( index )[ 0 ];
// trying to activate the already active panel
if ( active === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the currently active header
active = active || this.active[ 0 ];
this._eventHandler({
target: active,
currentTarget: active,
preventDefault: $.noop
});
},
_findActive: function( selector ) {
return typeof selector === "number" ? this.headers.eq( selector ) : $();
},
_setupEvents: function( event ) {
var events = {
keydown: "_keydown"
};
if ( event ) {
$.each( event.split(" "), function( index, eventName ) {
events[ eventName ] = "_eventHandler";
});
}
this._off( this.headers.add( this.headers.next() ) );
this._on( this.headers, events );
this._on( this.headers.next(), { keydown: "_panelKeyDown" });
this._hoverable( this.headers );
this._focusable( this.headers );
},
_eventHandler: function( event ) {
var options = this.options,
active = this.active,
clicked = $( event.currentTarget ),
clickedIsActive = clicked[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : clicked.next(),
toHide = active.next(),
eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow
};
event.preventDefault();
if (
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
return;
}
options.active = collapsing ? false : this.headers.index( clicked );
// when the call to ._toggle() comes after the class changes
// it causes a very odd bug in IE 8 (see #6720)
this.active = clickedIsActive ? $() : clicked;
this._toggle( eventData );
// switch classes
// corner classes on the previously active header stay after the animation
active.removeClass( "ui-accordion-header-active ui-state-active" );
if ( options.icons ) {
active.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.activeHeader )
.addClass( options.icons.header );
}
if ( !clickedIsActive ) {
clicked
.removeClass( "ui-corner-all" )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
if ( options.icons ) {
clicked.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.header )
.addClass( options.icons.activeHeader );
}
clicked
.next()
.addClass( "ui-accordion-content-active" );
}
},
_toggle: function( data ) {
var toShow = data.newPanel,
toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
// handle activating a panel during the animation for another activation
this.prevShow.add( this.prevHide ).stop( true, true );
this.prevShow = toShow;
this.prevHide = toHide;
if ( this.options.animate ) {
this._animate( toShow, toHide, data );
} else {
toHide.hide();
toShow.show();
this._toggleComplete( data );
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
toHide.prev().attr( "aria-selected", "false" );
// if we're switching panels, remove the old header from the tab order
// if we're opening from collapsed state, remove the previous header from the tab order
// if we're collapsing, then keep the collapsing header in the tab order
if ( toShow.length && toHide.length ) {
toHide.prev().attr( "tabIndex", -1 );
} else if ( toShow.length ) {
this.headers.filter(function() {
return $( this ).attr( "tabIndex" ) === 0;
})
.attr( "tabIndex", -1 );
}
toShow
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
})
.prev()
.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_animate: function( toShow, toHide, data ) {
var total, easing, duration,
that = this,
adjust = 0,
down = toShow.length &&
( !toHide.length || ( toShow.index() < toHide.index() ) ),
animate = this.options.animate || {},
options = down && animate.down || animate,
complete = function() {
that._toggleComplete( data );
};
if ( typeof options === "number" ) {
duration = options;
}
if ( typeof options === "string" ) {
easing = options;
}
// fall back from options to animation in case of partial down settings
easing = easing || options.easing || animate.easing;
duration = duration || options.duration || animate.duration;
if ( !toHide.length ) {
return toShow.animate( showProps, duration, easing, complete );
}
if ( !toShow.length ) {
return toHide.animate( hideProps, duration, easing, complete );
}
total = toShow.show().outerHeight();
toHide.animate( hideProps, {
duration: duration,
easing: easing,
step: function( now, fx ) {
fx.now = Math.round( now );
}
});
toShow
.hide()
.animate( showProps, {
duration: duration,
easing: easing,
complete: complete,
step: function( now, fx ) {
fx.now = Math.round( now );
if ( fx.prop !== "height" ) {
adjust += fx.now;
} else if ( that.options.heightStyle !== "content" ) {
fx.now = Math.round( total - toHide.outerHeight() - adjust );
adjust = 0;
}
}
});
},
_toggleComplete: function( data ) {
var toHide = data.oldPanel;
toHide
.removeClass( "ui-accordion-content-active" )
.prev()
.removeClass( "ui-corner-top" )
.addClass( "ui-corner-all" );
// Work around for rendering bug in IE (#5421)
if ( toHide.length ) {
toHide.parent()[0].className = toHide.parent()[0].className;
}
this._trigger( "activate", null, data );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "ui.progressbar", {
version: "1.10.3",
options: {
max: 100,
value: 0,
change: null,
complete: null
},
min: 0,
_create: function() {
// Constrain initial value
this.oldValue = this.options.value = this._constrainedValue();
this.element
.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.attr({
// Only set static values, aria-valuenow and aria-valuemax are
// set inside _refreshValue()
role: "progressbar",
"aria-valuemin": this.min
});
this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
.appendTo( this.element );
this._refreshValue();
},
_destroy: function() {
this.element
.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.removeAttr( "role" )
.removeAttr( "aria-valuemin" )
.removeAttr( "aria-valuemax" )
.removeAttr( "aria-valuenow" );
this.valueDiv.remove();
},
value: function( newValue ) {
if ( newValue === undefined ) {
return this.options.value;
}
this.options.value = this._constrainedValue( newValue );
this._refreshValue();
},
_constrainedValue: function( newValue ) {
if ( newValue === undefined ) {
newValue = this.options.value;
}
this.indeterminate = newValue === false;
// sanitize value
if ( typeof newValue !== "number" ) {
newValue = 0;
}
return this.indeterminate ? false :
Math.min( this.options.max, Math.max( this.min, newValue ) );
},
_setOptions: function( options ) {
// Ensure "value" option is set after other values (like max)
var value = options.value;
delete options.value;
this._super( options );
this.options.value = this._constrainedValue( value );
this._refreshValue();
},
_setOption: function( key, value ) {
if ( key === "max" ) {
// Don't allow a max less than min
value = Math.max( this.min, value );
}
this._super( key, value );
},
_percentage: function() {
return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
},
_refreshValue: function() {
var value = this.options.value,
percentage = this._percentage();
this.valueDiv
.toggle( this.indeterminate || value > this.min )
.toggleClass( "ui-corner-right", value === this.options.max )
.width( percentage.toFixed(0) + "%" );
this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );
if ( this.indeterminate ) {
this.element.removeAttr( "aria-valuenow" );
if ( !this.overlayDiv ) {
this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
}
} else {
this.element.attr({
"aria-valuemax": this.options.max,
"aria-valuenow": value
});
if ( this.overlayDiv ) {
this.overlayDiv.remove();
this.overlayDiv = null;
}
}
if ( this.oldValue !== value ) {
this.oldValue = value;
this._trigger( "change" );
}
if ( value === this.options.max ) {
this._trigger( "complete" );
}
}
});
})( jQuery );
(function( $, undefined ) {
// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;
$.widget( "ui.slider", $.ui.mouse, {
version: "1.10.3",
widgetEventPrefix: "slide",
options: {
animate: false,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: false,
step: 1,
value: 0,
values: null,
// callbacks
change: null,
slide: null,
start: null,
stop: null
},
_create: function() {
this._keySliding = false;
this._mouseSliding = false;
this._animateOff = true;
this._handleIndex = null;
this._detectOrientation();
this._mouseInit();
this.element
.addClass( "ui-slider" +
" ui-slider-" + this.orientation +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all");
this._refresh();
this._setOption( "disabled", this.options.disabled );
this._animateOff = false;
},
_refresh: function() {
this._createRange();
this._createHandles();
this._setupEvents();
this._refreshValue();
},
_createHandles: function() {
var i, handleCount,
options = this.options,
existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
handles = [];
handleCount = ( options.values && options.values.length ) || 1;
if ( existingHandles.length > handleCount ) {
existingHandles.slice( handleCount ).remove();
existingHandles = existingHandles.slice( 0, handleCount );
}
for ( i = existingHandles.length; i < handleCount; i++ ) {
handles.push( handle );
}
this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );
this.handle = this.handles.eq( 0 );
this.handles.each(function( i ) {
$( this ).data( "ui-slider-handle-index", i );
});
},
_createRange: function() {<|fim▁hole|>
if ( options.range ) {
if ( options.range === true ) {
if ( !options.values ) {
options.values = [ this._valueMin(), this._valueMin() ];
} else if ( options.values.length && options.values.length !== 2 ) {
options.values = [ options.values[0], options.values[0] ];
} else if ( $.isArray( options.values ) ) {
options.values = options.values.slice(0);
}
}
if ( !this.range || !this.range.length ) {
this.range = $( "<div></div>" )
.appendTo( this.element );
classes = "ui-slider-range" +
// note: this isn't the most fittingly semantic framework class for this element,
// but worked best visually with a variety of themes
" ui-widget-header ui-corner-all";
} else {
this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
// Handle range switching from true to min/max
.css({
"left": "",
"bottom": ""
});
}
this.range.addClass( classes +
( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
} else {
this.range = $([]);
}
},
_setupEvents: function() {
var elements = this.handles.add( this.range ).filter( "a" );
this._off( elements );
this._on( elements, this._handleEvents );
this._hoverable( elements );
this._focusable( elements );
},
_destroy: function() {
this.handles.remove();
this.range.remove();
this.element
.removeClass( "ui-slider" +
" ui-slider-horizontal" +
" ui-slider-vertical" +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all" );
this._mouseDestroy();
},
_mouseCapture: function( event ) {
var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
that = this,
o = this.options;
if ( o.disabled ) {
return false;
}
this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
};
this.elementOffset = this.element.offset();
position = { x: event.pageX, y: event.pageY };
normValue = this._normValueFromMouse( position );
distance = this._valueMax() - this._valueMin() + 1;
this.handles.each(function( i ) {
var thisDistance = Math.abs( normValue - that.values(i) );
if (( distance > thisDistance ) ||
( distance === thisDistance &&
(i === that._lastChangedValue || that.values(i) === o.min ))) {
distance = thisDistance;
closestHandle = $( this );
index = i;
}
});
allowed = this._start( event, index );
if ( allowed === false ) {
return false;
}
this._mouseSliding = true;
this._handleIndex = index;
closestHandle
.addClass( "ui-state-active" )
.focus();
offset = closestHandle.offset();
mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
top: event.pageY - offset.top -
( closestHandle.height() / 2 ) -
( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
};
if ( !this.handles.hasClass( "ui-state-hover" ) ) {
this._slide( event, index, normValue );
}
this._animateOff = true;
return true;
},
_mouseStart: function() {
return true;
},
_mouseDrag: function( event ) {
var position = { x: event.pageX, y: event.pageY },
normValue = this._normValueFromMouse( position );
this._slide( event, this._handleIndex, normValue );
return false;
},
_mouseStop: function( event ) {
this.handles.removeClass( "ui-state-active" );
this._mouseSliding = false;
this._stop( event, this._handleIndex );
this._change( event, this._handleIndex );
this._handleIndex = null;
this._clickOffset = null;
this._animateOff = false;
return false;
},
_detectOrientation: function() {
this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
},
_normValueFromMouse: function( position ) {
var pixelTotal,
pixelMouse,
percentMouse,
valueTotal,
valueMouse;
if ( this.orientation === "horizontal" ) {
pixelTotal = this.elementSize.width;
pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
} else {
pixelTotal = this.elementSize.height;
pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
}
percentMouse = ( pixelMouse / pixelTotal );
if ( percentMouse > 1 ) {
percentMouse = 1;
}
if ( percentMouse < 0 ) {
percentMouse = 0;
}
if ( this.orientation === "vertical" ) {
percentMouse = 1 - percentMouse;
}
valueTotal = this._valueMax() - this._valueMin();
valueMouse = this._valueMin() + percentMouse * valueTotal;
return this._trimAlignValue( valueMouse );
},
_start: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
return this._trigger( "start", event, uiHash );
},
_slide: function( event, index, newVal ) {
var otherVal,
newValues,
allowed;
if ( this.options.values && this.options.values.length ) {
otherVal = this.values( index ? 0 : 1 );
if ( ( this.options.values.length === 2 && this.options.range === true ) &&
( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
) {
newVal = otherVal;
}
if ( newVal !== this.values( index ) ) {
newValues = this.values();
newValues[ index ] = newVal;
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal,
values: newValues
} );
otherVal = this.values( index ? 0 : 1 );
if ( allowed !== false ) {
this.values( index, newVal, true );
}
}
} else {
if ( newVal !== this.value() ) {
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal
} );
if ( allowed !== false ) {
this.value( newVal );
}
}
}
},
_stop: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
this._trigger( "stop", event, uiHash );
},
_change: function( event, index ) {
if ( !this._keySliding && !this._mouseSliding ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
//store the last changed value index for reference when handles overlap
this._lastChangedValue = index;
this._trigger( "change", event, uiHash );
}
},
value: function( newValue ) {
if ( arguments.length ) {
this.options.value = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, 0 );
return;
}
return this._value();
},
values: function( index, newValue ) {
var vals,
newValues,
i;
if ( arguments.length > 1 ) {
this.options.values[ index ] = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, index );
return;
}
if ( arguments.length ) {
if ( $.isArray( arguments[ 0 ] ) ) {
vals = this.options.values;
newValues = arguments[ 0 ];
for ( i = 0; i < vals.length; i += 1 ) {
vals[ i ] = this._trimAlignValue( newValues[ i ] );
this._change( null, i );
}
this._refreshValue();
} else {
if ( this.options.values && this.options.values.length ) {
return this._values( index );
} else {
return this.value();
}
}
} else {
return this._values();
}
},
_setOption: function( key, value ) {
var i,
valsLength = 0;
if ( key === "range" && this.options.range === true ) {
if ( value === "min" ) {
this.options.value = this._values( 0 );
this.options.values = null;
} else if ( value === "max" ) {
this.options.value = this._values( this.options.values.length-1 );
this.options.values = null;
}
}
if ( $.isArray( this.options.values ) ) {
valsLength = this.options.values.length;
}
$.Widget.prototype._setOption.apply( this, arguments );
switch ( key ) {
case "orientation":
this._detectOrientation();
this.element
.removeClass( "ui-slider-horizontal ui-slider-vertical" )
.addClass( "ui-slider-" + this.orientation );
this._refreshValue();
break;
case "value":
this._animateOff = true;
this._refreshValue();
this._change( null, 0 );
this._animateOff = false;
break;
case "values":
this._animateOff = true;
this._refreshValue();
for ( i = 0; i < valsLength; i += 1 ) {
this._change( null, i );
}
this._animateOff = false;
break;
case "min":
case "max":
this._animateOff = true;
this._refreshValue();
this._animateOff = false;
break;
case "range":
this._animateOff = true;
this._refresh();
this._animateOff = false;
break;
}
},
//internal value getter
// _value() returns value trimmed by min and max, aligned by step
_value: function() {
var val = this.options.value;
val = this._trimAlignValue( val );
return val;
},
//internal values getter
// _values() returns array of values trimmed by min and max, aligned by step
// _values( index ) returns single value trimmed by min and max, aligned by step
_values: function( index ) {
var val,
vals,
i;
if ( arguments.length ) {
val = this.options.values[ index ];
val = this._trimAlignValue( val );
return val;
} else if ( this.options.values && this.options.values.length ) {
// .slice() creates a copy of the array
// this copy gets trimmed by min and max and then returned
vals = this.options.values.slice();
for ( i = 0; i < vals.length; i+= 1) {
vals[ i ] = this._trimAlignValue( vals[ i ] );
}
return vals;
} else {
return [];
}
},
// returns the step-aligned value that val is closest to, between (inclusive) min and max
_trimAlignValue: function( val ) {
if ( val <= this._valueMin() ) {
return this._valueMin();
}
if ( val >= this._valueMax() ) {
return this._valueMax();
}
var step = ( this.options.step > 0 ) ? this.options.step : 1,
valModStep = (val - this._valueMin()) % step,
alignValue = val - valModStep;
if ( Math.abs(valModStep) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see #4124)
return parseFloat( alignValue.toFixed(5) );
},
_valueMin: function() {
return this.options.min;
},
_valueMax: function() {
return this.options.max;
},
_refreshValue: function() {
var lastValPercent, valPercent, value, valueMin, valueMax,
oRange = this.options.range,
o = this.options,
that = this,
animate = ( !this._animateOff ) ? o.animate : false,
_set = {};
if ( this.options.values && this.options.values.length ) {
this.handles.each(function( i ) {
valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( that.options.range === true ) {
if ( that.orientation === "horizontal" ) {
if ( i === 0 ) {
that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
}
if ( i === 1 ) {
that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
} else {
if ( i === 0 ) {
that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
}
if ( i === 1 ) {
that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
}
lastValPercent = valPercent;
});
} else {
value = this.value();
valueMin = this._valueMin();
valueMax = this._valueMax();
valPercent = ( valueMax !== valueMin ) ?
( value - valueMin ) / ( valueMax - valueMin ) * 100 :
0;
_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( oRange === "min" && this.orientation === "horizontal" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "horizontal" ) {
this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
if ( oRange === "min" && this.orientation === "vertical" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "vertical" ) {
this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
},
_handleEvents: {
keydown: function( event ) {
/*jshint maxcomplexity:25*/
var allowed, curVal, newVal, step,
index = $( event.target ).data( "ui-slider-handle-index" );
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
case $.ui.keyCode.END:
case $.ui.keyCode.PAGE_UP:
case $.ui.keyCode.PAGE_DOWN:
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
event.preventDefault();
if ( !this._keySliding ) {
this._keySliding = true;
$( event.target ).addClass( "ui-state-active" );
allowed = this._start( event, index );
if ( allowed === false ) {
return;
}
}
break;
}
step = this.options.step;
if ( this.options.values && this.options.values.length ) {
curVal = newVal = this.values( index );
} else {
curVal = newVal = this.value();
}
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
newVal = this._valueMin();
break;
case $.ui.keyCode.END:
newVal = this._valueMax();
break;
case $.ui.keyCode.PAGE_UP:
newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) );
break;
case $.ui.keyCode.PAGE_DOWN:
newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) );
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
if ( curVal === this._valueMax() ) {
return;
}
newVal = this._trimAlignValue( curVal + step );
break;
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
if ( curVal === this._valueMin() ) {
return;
}
newVal = this._trimAlignValue( curVal - step );
break;
}
this._slide( event, index, newVal );
},
click: function( event ) {
event.preventDefault();
},
keyup: function( event ) {
var index = $( event.target ).data( "ui-slider-handle-index" );
if ( this._keySliding ) {
this._keySliding = false;
this._stop( event, index );
this._change( event, index );
$( event.target ).removeClass( "ui-state-active" );
}
}
}
});
}(jQuery));<|fim▁end|> | var options = this.options,
classes = ""; |
<|file_name|>logistic.rs<|end_file_name|><|fim▁begin|>//! Provides the [logistic](http://en.wikipedia.org/wiki/Logistic_function) and
//! related functions
use crate::error::StatsError;
use crate::Result;
/// Computes the logistic function
pub fn logistic(p: f64) -> f64 {
1.0 / ((-p).exp() + 1.0)
}
/// Computes the logit function
///
/// # Panics
///
/// If `p < 0.0` or `p > 1.0`
pub fn logit(p: f64) -> f64 {
checked_logit(p).unwrap()
}
/// Computes the logit function
///
/// # Errors
///
/// If `p < 0.0` or `p > 1.0`
pub fn checked_logit(p: f64) -> Result<f64> {
if p < 0.0 || p > 1.0 {
Err(StatsError::ArgIntervalIncl("p", 0.0, 1.0))
} else {
Ok((p / (1.0 - p)).ln())
}
}
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use std::f64;
#[test]
fn test_logistic() {
assert_eq!(super::logistic(f64::NEG_INFINITY), 0.0);
assert_eq!(super::logistic(-11.512915464920228103874353849992239636376994324587), 0.00001);
assert_almost_eq!(super::logistic(-6.9067547786485535272274487616830597875179908939086), 0.001, 1e-18);
assert_almost_eq!(super::logistic(-2.1972245773362193134015514347727700402304323440139), 0.1, 1e-16);
assert_eq!(super::logistic(0.0), 0.5);
assert_almost_eq!(super::logistic(2.1972245773362195801634726294284168954491240598975), 0.9, 1e-15);
assert_almost_eq!(super::logistic(6.9067547786485526081487245019905638981131702804661), 0.999, 1e-15);
assert_eq!(super::logistic(11.512915464924779098232747799811946290419057060965), 0.99999);
assert_eq!(super::logistic(f64::INFINITY), 1.0);
}
#[test]
fn test_logit() {
assert_eq!(super::logit(0.0), f64::NEG_INFINITY);
assert_eq!(super::logit(0.00001), -11.512915464920228103874353849992239636376994324587);
assert_eq!(super::logit(0.001), -6.9067547786485535272274487616830597875179908939086);
assert_eq!(super::logit(0.1), -2.1972245773362193134015514347727700402304323440139);
assert_eq!(super::logit(0.5), 0.0);
assert_eq!(super::logit(0.9), 2.1972245773362195801634726294284168954491240598975);
assert_eq!(super::logit(0.999), 6.9067547786485526081487245019905638981131702804661);
assert_eq!(super::logit(0.99999), 11.512915464924779098232747799811946290419057060965);
assert_eq!(super::logit(1.0), f64::INFINITY);
}
#[test]
#[should_panic]
fn test_logit_p_lt_0() {
super::logit(-1.0);
}
#[test]
#[should_panic]
fn test_logit_p_gt_1() {
super::logit(2.0);
}
#[test]
fn test_checked_logit_p_lt_0() {
assert!(super::checked_logit(-1.0).is_err());<|fim▁hole|> assert!(super::checked_logit(2.0).is_err());
}
}<|fim▁end|> | }
#[test]
fn test_checked_logit_p_gt_1() { |
<|file_name|>20141116202453-troopcost.js<|end_file_name|><|fim▁begin|>var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.addColumn("troop_type", "production_cost", "int", callback);
};<|fim▁hole|>};<|fim▁end|> |
exports.down = function(db, callback) {
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># Copyright 2015 Mirantis, Inc.
# Copyright 2012-2013 IBM Corp.
# 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.<|fim▁hole|>
setuptools.setup(
setup_requires=['pbr'],
pbr=True)<|fim▁end|> |
import setuptools |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python<|fim▁hole|><|fim▁end|> | # encoding: UTF-8
'''give access permission for files in this folder''' |
<|file_name|>ASTCollExpr.java<|end_file_name|><|fim▁begin|>package cn.ac.iscas.cloudeploy.v2.puppet.transform.ast;
import java.util.List;
public class ASTCollExpr extends ASTBase{
private Object test1;
private Object test2;
private String oper;
private List<Object> children;
private String form;
private String type;
public Object getTest1() {
return test1;
}
public void setTest1(Object test1) {
this.test1 = test1;
}
public Object getTest2() {
return test2;
}
public void setTest2(Object test2) {
this.test2 = test2;
}
public String getOper() {
return oper;
}
public void setOper(String oper) {
this.oper = oper;
}
public List<Object> getChildren() {
return children;
}<|fim▁hole|> public void setChildren(List<Object> children) {
this.children = children;
}
public String getForm() {
return form;
}
public void setForm(String form) {
this.form = form;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
from collections import namedtuple
from django.conf import settings
from sentry.utils.dates import to_datetime
from sentry.utils.services import LazyServiceWrapper
from .backends.base import Backend # NOQA
from .backends.dummy import DummyBackend # NOQA
backend = LazyServiceWrapper(Backend, settings.SENTRY_DIGESTS,
settings.SENTRY_DIGESTS_OPTIONS,
(DummyBackend,))
backend.expose(locals())
class Record(namedtuple('Record', 'key value timestamp')):
@property
def datetime(self):
return to_datetime(self.timestamp)
ScheduleEntry = namedtuple('ScheduleEntry', 'key timestamp')
OPTIONS = frozenset((
'increment_delay',
'maximum_delay',
'minimum_delay',<|fim▁hole|>
def get_option_key(plugin, option):
assert option in OPTIONS
return 'digests:{}:{}'.format(plugin, option)<|fim▁end|> | )) |
<|file_name|>champpack.go<|end_file_name|><|fim▁begin|>package structs
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strconv"
)
// packedChampID : Only used in packed data structures related to champions.
type packedChampID int
// ChampPack : Low-level mapping struct used to convert between sparse RiotID's and dense packedChampID's. This
// struct keeps a direct mapping in memory and can convert between the two in a single array lookup, which provides
// roughly a 5.2x speedup in go1.7.1 (see packedarray_test.go benchmarks for experiment).
type ChampPack struct {
toPacked []packedChampID
toUnpacked []RiotID
toPackedAdded []bool // has a value been set for toPacked[i]?
MaxID RiotID
MaxSize int
}
// NewChampPack : Return a new ChampPack instance with a max (packed) size of `count` and a maximum
// ID value of `maxID`. For example, NewChampPack(5, 10) means there will be at most five mappings
// added, with the max RiotID being 10.
func NewChampPack(count int, maxID RiotID) *ChampPack {
return &ChampPack{
toPacked: make([]packedChampID, maxID+1), // +1 so the max ID can actually fit
toPackedAdded: make([]bool, maxID+1),
toUnpacked: make([]RiotID, 0, count),
MaxID: maxID,
MaxSize: count,
}
}
// NewRiotChampPack : Create a new champpack populated with summoner stats. This function makes a<|fim▁hole|>func NewRiotChampPack() *ChampPack {
resp, err := http.Get("http://ddragon.leagueoflegends.com/cdn/7.15.1/data/en_US/champion.json")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var rc struct {
Data map[string]struct {
Key string
Name string
}
}
json.Unmarshal(body, &rc)
count := len(rc.Data)
max := 0
// Find the max champion ID so we can create the champpack
for _, champ := range rc.Data {
id, _ := strconv.Atoi(champ.Key)
if id > max {
max = id
}
}
cp := NewChampPack(count, RiotID(max))
for _, champ := range rc.Data {
id, _ := strconv.Atoi(champ.Key)
cp.AddRiotID(RiotID(id))
}
return cp
}
// AddRiotID : Add a new Riot ID to the mapping. Returns the corresponding packedChampID.
func (cp *ChampPack) AddRiotID(id RiotID) packedChampID {
if id <= cp.MaxID && cp.PackedSize() < cp.MaxSize {
cp.toUnpacked = append(cp.toUnpacked, id)
packed := packedChampID(len(cp.toUnpacked) - 1)
cp.toPacked[id] = packed
cp.toPackedAdded[id] = true
return packed
}
return -1
}
// GetPacked : Get a packedChampID for a previously-added RiotID. The boolean return value indicates whether
// the specified RiotID is known, and if not then the first value should not be trusted.
func (cp *ChampPack) GetPacked(id RiotID) (packedChampID, bool) {
if int(id) < len(cp.toPacked) {
return cp.toPacked[id], cp.toPackedAdded[id]
}
return 0, false
}
// GetUnpacked : Get previously-added RiotID corresponding to a packedChampID. The boolean return value indicates
// whether the specified RiotID is known, and if not then the first value should not be trusted.
func (cp *ChampPack) GetUnpacked(id packedChampID) (RiotID, bool) {
if int(id) < len(cp.toUnpacked) {
return cp.toUnpacked[id], true
}
return 0, false
}
// PackedSize : Returns the current number of champions packed in.
func (cp *ChampPack) PackedSize() int {
return len(cp.toUnpacked)
}<|fim▁end|> | // request to Riot's API for the latest champion list. |
<|file_name|>reconnect_remoterepositories.py<|end_file_name|><|fim▁begin|>import json
from django.db.models import Q, Subquery
from django.core.management.base import BaseCommand
from readthedocs.oauth.models import RemoteRepository
from readthedocs.oauth.services import registry
from readthedocs.oauth.services.base import SyncServiceError
from readthedocs.projects.models import Project
from readthedocs.organizations.models import Organization
class Command(BaseCommand):
help = "Re-connect RemoteRepository to Project"
def add_arguments(self, parser):
parser.add_argument('organization', nargs='+', type=str)
parser.add_argument(
'--no-dry-run',
action='store_true',
default=False,
help='Update database with the changes proposed.',
)
# If owners does not have their RemoteRepository synced, it could
# happen we don't find a matching Project (see --force-owners-social-resync)
parser.add_argument(
'--only-owners',
action='store_true',
default=False,
help='Connect repositories only to organization owners.',
)
parser.add_argument(
'--force-owners-social-resync',
action='store_true',
default=False,
help='Force to re-sync RemoteRepository for organization owners.',
)
def _force_owners_social_resync(self, organization):
for owner in organization.owners.all():
for service_cls in registry:
for service in service_cls.for_user(owner):
try:
service.sync()
except SyncServiceError:
print(f'Service {service} failed while syncing. Skipping...')
def _connect_repositories(self, organization, no_dry_run, only_owners):
connected_projects = []
# TODO: consider using same login than RemoteRepository.matches method
# https://github.com/readthedocs/readthedocs.org/blob/49b03f298b6105d755554f7dc7e97a3398f7066f/readthedocs/oauth/models.py#L185-L194
remote_query = (
Q(ssh_url__in=Subquery(organization.projects.values('repo'))) |
Q(clone_url__in=Subquery(organization.projects.values('repo')))
)
for remote in RemoteRepository.objects.filter(remote_query).order_by('created'):
admin = json.loads(remote.json).get('permissions', {}).get('admin')
if only_owners and remote.users.first() not in organization.owners.all():
# Do not connect a RemoteRepository if the User is not owner of the organization
continue
if not admin:
# Do not connect a RemoteRepository where the User is not admin of the repository
continue
if not organization.users.filter(username=remote.users.first().username).exists():
# Do not connect a RemoteRepository if the use does not belong to the organization
continue
# Projects matching
# - RemoteRepository URL
# - are under the Organization
# - not connected to a RemoteRepository already
# - was not connected previously by this call to the script
projects = Project.objects.filter(
Q(repo=remote.ssh_url) | Q(repo=remote.clone_url),
organizations__in=[organization.pk],
remote_repository__isnull=True
).exclude(slug__in=connected_projects)
for project in projects:
connected_projects.append(project.slug)
if no_dry_run:
remote.project = project
remote.save()
print(f'{project.slug: <40} {remote.pk: <10} {remote.html_url: <60} {remote.users.first().username: <20} {admin: <5}') # noqa
print('Total:', len(connected_projects))
if not no_dry_run:
print(
'Changes WERE NOT applied to the database. '<|fim▁hole|> def handle(self, *args, **options):
no_dry_run = options.get('no_dry_run')
only_owners = options.get('only_owners')
force_owners_social_resync = options.get('force_owners_social_resync')
for organization in options.get('organization'):
try:
organization = Organization.objects.get(slug=organization)
if force_owners_social_resync:
self._force_owners_social_resync(organization)
self._connect_repositories(organization, no_dry_run, only_owners)
except Organization.DoesNotExist:
print(f'Organization does not exist. organization={organization}')<|fim▁end|> | 'Run it with --no-dry-run to save the changes.'
)
|
<|file_name|>select_model.py<|end_file_name|><|fim▁begin|>__version__="v2.5 beta10"
welcome_block="""
# Multi-Echo ICA, Version %s
#
# Kundu, P., Brenowitz, N.D., Voon, V., Worbe, Y., Vertes, P.E., Inati, S.J., Saad, Z.S.,
# Bandettini, P.A. & Bullmore, E.T. Integrated strategy for improving functional
# connectivity mapping using multiecho fMRI. PNAS (2013).
#
# Kundu, P., Inati, S.J., Evans, J.W., Luh, W.M. & Bandettini, P.A. Differentiating
# BOLD and non-BOLD signals in fMRI time series using multi-echo EPI. NeuroImage (2011).
# https://doi.org/10.1016/j.neuroimage.2011.12.028
#
# PROCEDURE 2a: Model fitting and component selection routines
"""
import numpy as np
def fitmodels_direct(catd,mmix,mask,t2s,tes,fout=None,reindex=False,mmixN=None,full_sel=True,debugout=False):
"""
Usage:
fitmodels_direct(fout)
Input:
fout is flag for output of per-component TE-dependence maps
t2s is a (nx,ny,nz) ndarray
tes is a 1d array
"""
#Compute opt. com. raw data
tsoc = np.array(optcom(catd,t2s,tes,mask),dtype=float)[mask]
tsoc_mean = tsoc.mean(axis=-1)
tsoc_dm = tsoc-tsoc_mean[:,np.newaxis]
#Compute un-normalized weight dataset (features)
if mmixN == None: mmixN=mmix
WTS = computefeats2(unmask(tsoc,mask),mmixN,mask,normalize=False)
#Compute PSC dataset - shouldn't have to refit data
tsoc_B = get_coeffs(unmask(tsoc_dm,mask),mask,mmix)[mask]
tsoc_Babs = np.abs(tsoc_B)
PSC = tsoc_B/tsoc.mean(axis=-1)[:,np.newaxis]*100
#Compute skews to determine signs based on unnormalized weights, correct mmix & WTS signs based on spatial distribution tails
from scipy.stats import skew
signs = skew(WTS,axis=0)
signs /= np.abs(signs)
mmix = mmix.copy()
mmix*=signs
WTS*=signs
PSC*=signs
totvar = (tsoc_B**2).sum()
totvar_norm = (WTS**2).sum()
#Compute Betas and means over TEs for TE-dependence analysis
Ne = tes.shape[0]
betas = cat2echos(get_coeffs(uncat2echos(catd,Ne),np.tile(mask,(1,1,Ne)),mmix),Ne)
nx,ny,nz,Ne,nc = betas.shape
Nm = mask.sum()
mu = catd.mean(axis=-1)
tes = np.reshape(tes,(Ne,1))
fmin,fmid,fmax = getfbounds(ne)
<|fim▁hole|> #Mask arrays
mumask = fmask(mu,mask)
t2smask = fmask(t2s,mask)
betamask = fmask(betas,mask)
if debugout: fout=aff
#Setup Xmats
#Model 1
X1 = mumask.transpose()
#Model 2
X2 = np.tile(tes,(1,Nm))*mumask.transpose()/t2smask.transpose()
#Tables for component selection
Kappas = np.zeros([nc])
Rhos = np.zeros([nc])
varex = np.zeros([nc])
varex_norm = np.zeros([nc])
Z_maps = np.zeros([Nm,nc])
F_R2_maps = np.zeros([Nm,nc])
F_S0_maps = np.zeros([Nm,nc])
Z_clmaps = np.zeros([Nm,nc])
F_R2_clmaps = np.zeros([Nm,nc])
F_S0_clmaps = np.zeros([Nm,nc])
Br_clmaps_R2 = np.zeros([Nm,nc])
Br_clmaps_S0 = np.zeros([Nm,nc])
for i in range(nc):
#size of B is (nc, nx*ny*nz)
B = np.atleast_3d(betamask)[:,:,i].transpose()
alpha = (np.abs(B)**2).sum(axis=0)
varex[i] = (tsoc_B[:,i]**2).sum()/totvar*100.
varex_norm[i] = (WTS[:,i]**2).sum()/totvar_norm*100.
#S0 Model
coeffs_S0 = (B*X1).sum(axis=0)/(X1**2).sum(axis=0)
SSE_S0 = (B - X1*np.tile(coeffs_S0,(Ne,1)))**2
SSE_S0 = SSE_S0.sum(axis=0)
F_S0 = (alpha - SSE_S0)*2/(SSE_S0)
F_S0_maps[:,i] = F_S0
#R2 Model
coeffs_R2 = (B*X2).sum(axis=0)/(X2**2).sum(axis=0)
SSE_R2 = (B - X2*np.tile(coeffs_R2,(Ne,1)))**2
SSE_R2 = SSE_R2.sum(axis=0)
F_R2 = (alpha - SSE_R2)*2/(SSE_R2)
F_R2_maps[:,i] = F_R2
#Compute weights as Z-values
wtsZ=(WTS[:,i]-WTS[:,i].mean())/WTS[:,i].std()
wtsZ[np.abs(wtsZ)>Z_MAX]=(Z_MAX*(np.abs(wtsZ)/wtsZ))[np.abs(wtsZ)>Z_MAX]
Z_maps[:,i] = wtsZ
#Compute Kappa and Rho
F_S0[F_S0>F_MAX] = F_MAX
F_R2[F_R2>F_MAX] = F_MAX
Kappas[i] = np.average(F_R2,weights=np.abs(wtsZ)**2.)
Rhos[i] = np.average(F_S0,weights=np.abs(wtsZ)**2.)
#Tabulate component values
comptab_pre = np.vstack([np.arange(nc),Kappas,Rhos,varex,varex_norm]).T
if reindex:
#Re-index all components in Kappa order
comptab = comptab_pre[comptab_pre[:,1].argsort()[::-1],:]
Kappas = comptab[:,1]; Rhos = comptab[:,2]; varex = comptab[:,3]; varex_norm = comptab[:,4]
nnc = np.array(comptab[:,0],dtype=np.int)
mmix_new = mmix[:,nnc]
F_S0_maps = F_S0_maps[:,nnc]; F_R2_maps = F_R2_maps[:,nnc]; Z_maps = Z_maps[:,nnc]
WTS = WTS[:,nnc]; PSC=PSC[:,nnc]; tsoc_B=tsoc_B[:,nnc]; tsoc_Babs=tsoc_Babs[:,nnc]
comptab[:,0] = np.arange(comptab.shape[0])
else:
comptab = comptab_pre
mmix_new = mmix
#Full selection including clustering criteria
seldict=None
if full_sel:
for i in range(nc):
#Save out files
out = np.zeros((nx,ny,nz,4))
if fout!=None:
ccname = "cc%.3d.nii" % i
else: ccname = ".cc_temp.nii.gz"
out[:,:,:,0] = np.squeeze(unmask(PSC[:,i],mask))
out[:,:,:,1] = np.squeeze(unmask(F_R2_maps[:,i],mask))
out[:,:,:,2] = np.squeeze(unmask(F_S0_maps[:,i],mask))
out[:,:,:,3] = np.squeeze(unmask(Z_maps[:,i],mask))
niwrite(out,fout,ccname)
os.system('3drefit -sublabel 0 PSC -sublabel 1 F_R2 -sublabel 2 F_SO -sublabel 3 Z_sn %s 2> /dev/null > /dev/null'%ccname)
csize = np.max([int(Nm*0.0005)+5,20])
#Do simple clustering on F
os.system("3dcalc -overwrite -a %s[1..2] -expr 'a*step(a-%i)' -prefix .fcl_in.nii.gz -overwrite" % (ccname,fmin))
os.system('3dmerge -overwrite -dxyz=1 -1clust 1 %i -doall -prefix .fcl_out.nii.gz .fcl_in.nii.gz' % (csize))
sel = fmask(nib.load('.fcl_out.nii.gz').get_data(),mask)!=0
sel = np.array(sel,dtype=np.int)
F_R2_clmaps[:,i] = sel[:,0]
F_S0_clmaps[:,i] = sel[:,1]
#Do simple clustering on Z at p<0.05
sel = spatclust(None,mask,csize,1.95,head,aff,infile=ccname,dindex=3,tindex=3)
Z_clmaps[:,i] = sel
#Do simple clustering on ranked signal-change map
countsigFR2 = F_R2_clmaps[:,i].sum()
countsigFS0 = F_S0_clmaps[:,i].sum()
Br_clmaps_R2[:,i] = spatclust(rankvec(tsoc_Babs[:,i]),mask,csize,max(tsoc_Babs.shape)-countsigFR2,head,aff)
Br_clmaps_S0[:,i] = spatclust(rankvec(tsoc_Babs[:,i]),mask,csize,max(tsoc_Babs.shape)-countsigFS0,head,aff)
seldict = {}
selvars = ['Kappas','Rhos','WTS','varex','Z_maps','F_R2_maps','F_S0_maps',\
'Z_clmaps','F_R2_clmaps','F_S0_clmaps','tsoc_B','Br_clmaps_R2','Br_clmaps_S0']
for vv in selvars:
seldict[vv] = eval(vv)
if debugout or ('DEBUGOUT' in args):
#Package for debug
import cPickle as cP
import zlib
try: os.system('mkdir compsel.debug')
except: pass
selvars = ['Kappas','Rhos','WTS','varex','Z_maps','Z_clmaps','F_R2_clmaps','F_S0_clmaps','Br_clmaps_R2','Br_clmaps_S0']
for vv in selvars:
with open('compsel.debug/%s.pkl.gz' % vv,'wb') as ofh:
print "Writing debug output: compsel.debug/%s.pkl.gz" % vv
ofh.write(zlib.compress(cP.dumps(eval(vv))))
ofh.close()
return seldict,comptab,betas,mmix_new
def selcomps(seldict,debug=False,olevel=2,oversion=99,knobargs=''):
#import ipdb
#Dump dictionary into variable names
for key in seldict.keys(): exec("%s=seldict['%s']" % (key,key))
#List of components
midk = []
ign = []
nc = np.arange(len(Kappas))
ncl = np.arange(len(Kappas))
#If user has specified
try:
if options.manacc:
acc = sorted([int(vv) for vv in options.manacc.split(',')])
midk = []
rej = sorted(np.setdiff1d(ncl,acc))
return acc,rej,midk #Add string for ign
except:
pass
"""
Set knobs
"""
LOW_PERC=25
HIGH_PERC=90
EXTEND_FACTOR=2
try:
if nt<100: EXTEND_FACTOR=3
except: pass
RESTRICT_FACTOR=2
if knobargs!='':
for knobarg in ''.join(knobargs).split(','): exec(knobarg)
"""
Do some tallies for no. of significant voxels
"""
countsigZ = Z_clmaps.sum(0)
countsigFS0 = F_S0_clmaps.sum(0)
countsigFR2 = F_R2_clmaps.sum(0)
countnoise = np.zeros(len(nc))
"""
Make table of dice values
"""
dice_table = np.zeros([nc.shape[0],2])
csize = np.max([int(mask.sum()*0.0005)+5,20])
for ii in ncl:
dice_FR2 = dice(Br_clmaps_R2[:,ii],F_R2_clmaps[:,ii])
dice_FS0 = dice(Br_clmaps_S0[:,ii],F_S0_clmaps[:,ii])
dice_table[ii,:] = [dice_FR2,dice_FS0] #step 3a here and above
dice_table[np.isnan(dice_table)]=0
"""
Make table of noise gain
"""
tt_table = np.zeros([len(nc),4])
counts_FR2_Z = np.zeros([len(nc),2])
for ii in nc:
comp_noise_sel = andb([np.abs(Z_maps[:,ii])>1.95,Z_clmaps[:,ii]==0])==2
countnoise[ii] = np.array(comp_noise_sel,dtype=np.int).sum()
noise_FR2_Z = np.log10(np.unique(F_R2_maps[comp_noise_sel,ii]))
signal_FR2_Z = np.log10(np.unique(F_R2_maps[Z_clmaps[:,ii]==1,ii]))
counts_FR2_Z[ii,:] = [len(signal_FR2_Z),len(noise_FR2_Z)]
tt_table[ii,:2] = stats.ttest_ind(signal_FR2_Z,noise_FR2_Z,equal_var=False)
tt_table[np.isnan(tt_table)]=0
"""
Assemble decision table
"""
d_table_rank = np.vstack([len(nc)-rankvec(Kappas), len(nc)-rankvec(dice_table[:,0]), \
len(nc)-rankvec(tt_table[:,0]), rankvec(countnoise), len(nc)-rankvec(countsigFR2) ]).T
d_table_score = d_table_rank.sum(1)
"""
Step 1: Reject anything that's obviously an artifact
a. Estimate a null variance
"""
rej = ncl[andb([Rhos>Kappas,countsigFS0>countsigFR2])>0]
rej = np.union1d(rej,ncl[andb([dice_table[:,1]>dice_table[:,0],varex>np.median(varex)])==2])
rej = np.union1d(rej,ncl[andb([tt_table[ncl,0]<0,varex[ncl]>np.median(varex)])==2])
ncl = np.setdiff1d(ncl,rej)
varex_ub_p = np.median(varex[Kappas>Kappas[getelbow(Kappas)]])
"""
Step 2: Make a guess for what the good components are, in order to estimate good component properties
a. Not outlier variance
b. Kappa>kappa_elbow
c. Rho<Rho_elbow
d. High R2* dice compared to S0 dice
e. Gain of F_R2 in clusters vs noise
f. Estimate a low and high variance
"""
ncls = ncl.copy()
for nn in range(3): ncls = ncls[1:][(varex[ncls][1:]-varex[ncls][:-1])<varex_ub_p] #Step 2a
Kappas_lim = Kappas[Kappas<getfbounds(ne)[-1]]
Rhos_lim = np.array(sorted(Rhos[ncls])[::-1])
Rhos_sorted = np.array(sorted(Rhos)[::-1])
Kappas_elbow = min(Kappas_lim[getelbow(Kappas_lim)],Kappas[getelbow(Kappas)])
Rhos_elbow = np.mean([Rhos_lim[getelbow(Rhos_lim)] , Rhos_sorted[getelbow(Rhos_sorted)], getfbounds(ne)[0]])
good_guess = ncls[andb([Kappas[ncls]>=Kappas_elbow, Rhos[ncls]<Rhos_elbow])==2]
if debug:
import ipdb
ipdb.set_trace()
if len(good_guess)==0:
return [],sorted(rej),[],sorted(np.setdiff1d(nc,rej))
Kappa_rate = (max(Kappas[good_guess])-min(Kappas[good_guess]))/(max(varex[good_guess])-min(varex[good_guess]))
Kappa_ratios = Kappa_rate*varex/Kappas
varex_lb = scoreatpercentile(varex[good_guess],LOW_PERC )
varex_ub = scoreatpercentile(varex[good_guess],HIGH_PERC)
if debug:
import ipdb
ipdb.set_trace()
"""
Step 3: Get rid of midk components - those with higher than max decision score and high variance
"""
max_good_d_score = EXTEND_FACTOR*len(good_guess)*d_table_rank.shape[1]
midkadd = ncl[andb([d_table_score[ncl] > max_good_d_score, varex[ncl] > EXTEND_FACTOR*varex_ub])==2]
midk = np.union1d(midkadd, midk)
ncl = np.setdiff1d(ncl,midk)
"""
Step 4: Find components to ignore
"""
good_guess = np.setdiff1d(good_guess,midk)
loaded = np.union1d(good_guess, ncl[varex[ncl]>varex_lb])
igncand = np.setdiff1d(ncl,loaded)
igncand = np.setdiff1d(igncand, igncand[d_table_score[igncand]<max_good_d_score])
igncand = np.setdiff1d(igncand,igncand[Kappas[igncand]>Kappas_elbow])
ign = np.array(np.union1d(ign,igncand),dtype=np.int)
ncl = np.setdiff1d(ncl,ign)
if debug:
import ipdb
ipdb.set_trace()
"""
Step 5: Scrub the set
"""
if len(ncl)>len(good_guess):
#Recompute the midk steps on the limited set to clean up the tail
d_table_rank = np.vstack([len(ncl)-rankvec(Kappas[ncl]), len(ncl)-rankvec(dice_table[ncl,0]),len(ncl)-rankvec(tt_table[ncl,0]), rankvec(countnoise[ncl]), len(ncl)-rankvec(countsigFR2[ncl])]).T
d_table_score = d_table_rank.sum(1)
num_acc_guess = np.mean([np.sum(andb([Kappas[ncl]>Kappas_elbow,Rhos[ncl]<Rhos_elbow])==2), np.sum(Kappas[ncl]>Kappas_elbow)])
candartA = np.intersect1d(ncl[d_table_score>num_acc_guess*d_table_rank.shape[1]/RESTRICT_FACTOR],ncl[Kappa_ratios[ncl]>EXTEND_FACTOR*2])
midkadd = np.union1d(midkadd,np.intersect1d(candartA,candartA[varex[candartA]>varex_ub*EXTEND_FACTOR]))
candartB = ncl[d_table_score>num_acc_guess*d_table_rank.shape[1]*HIGH_PERC/100.]
midkadd = np.union1d(midkadd,np.intersect1d(candartB,candartB[varex[candartB]>varex_lb*EXTEND_FACTOR]))
midk = np.union1d(midk,midkadd)
#Find comps to ignore
new_varex_lb = scoreatpercentile(varex[ncl[:num_acc_guess]],LOW_PERC)
candart = np.setdiff1d(ncl[d_table_score>num_acc_guess*d_table_rank.shape[1]],midk)
ignadd = np.intersect1d(candart,candart[varex[candart]>new_varex_lb])
ignadd = np.union1d(ignadd,np.intersect1d(ncl[Kappas[ncl]<=Kappas_elbow],ncl[varex[ncl]>new_varex_lb]))
ign = np.setdiff1d(np.union1d(ign,ignadd),midk)
ncl = np.setdiff1d(ncl,np.union1d(midk,ign))
if debug:
import ipdb
ipdb.set_trace()
return list(sorted(ncl)),list(sorted(rej)),list(sorted(midk)),list(sorted(ign))<|fim▁end|> | |
<|file_name|>display.rs<|end_file_name|><|fim▁begin|>//! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display for DisplayCausesAndBacktrace<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for cause in self.err.causes() {
if first {
first = false;<|fim▁hole|> } else {
writeln!(f, " caused by: {}", cause)?;
}
}
if self.include_backtrace {
write!(f, "{}", self.err.backtrace())?;
}
Ok(())
}
}
/// Extensions to standard `failure::Error` trait.
pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes, plus an optional
/// backtrace.
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace;
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes. However, the
/// backtrace will be omitted even if `RUST_BACKTRACE` is set. This is
/// intended to be used in situations where the backtrace needed to be
/// handled separately, as with APIs like Rollbar's.
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace;
}
impl DisplayCausesAndBacktraceExt for failure::Error {
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
}
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}<|fim▁end|> | writeln!(f, "Error: {}", cause)?; |
<|file_name|>Class_1435.java<|end_file_name|><|fim▁begin|>package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;<|fim▁hole|>public class Class_1435 {
}<|fim▁end|> |
@Annotation_001 |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use test::Bencher;
use digest::md5::Md5;<|fim▁hole|><|fim▁end|> |
bench_digest!(Md5); |
<|file_name|>spell_lists.py<|end_file_name|><|fim▁begin|>import os
import json
import re
from BeautifulSoup import BeautifulSoup
from psrd.rules import write_rules
from psrd.files import char_replace
from psrd.universal import parse_universal, print_struct
from psrd.sections import ability_pass, is_anonymous_section, has_subsections, entity_pass, quote_pass<|fim▁hole|> spell_lists = []
for s in section['sections']:
if s['name'].endswith('Spells'):
spell_lists.append(s)
elif s['name'].endswith('Formulae'):
spell_lists.append(s)
elif s['name'] != 'Spells by Class':
sections.append(s)
section['sections'] = sections
return section, spell_lists
def advanced_class_guide_structure_pass(section, filename):
spell_lists = section['sections'][6:]
del section['sections'][6:]
return section, spell_lists
def advanced_structure_pass(section, filename):
sections = []
spell_lists = []
top = section['sections'].pop(0)
top['name'] = "Spell Lists"
for s in section['sections']:
if s['name'].endswith('Spells'):
spell_lists.append(s)
return top, spell_lists
def ultimate_magic_structure_pass(section, filename):
section['sections'].pop(0)
return None, section['sections']
def spell_list_structure_pass(section, filename):
spell_lists = []
if filename == 'spellLists.html' and len(section['sections']) == 18:
section, spell_lists = mythic_structure_pass(section, filename)
elif section['source'] == "Advanced Class Guide":
section, spell_lists = advanced_class_guide_structure_pass(section, filename)
elif filename in ('spellLists.html'):
section, spell_lists = core_structure_pass(section, filename)
elif filename in ('advancedSpellLists.html', 'ultimateCombatSpellLists.html'):
section, spell_lists = advanced_structure_pass(section, filename)
elif filename in ('ultimateMagicSpellLists.html'):
section, spell_lists = ultimate_magic_structure_pass(section, filename)
else:
del section['sections']
print section
return section, spell_lists
def spell_list_name_pass(spell_lists):
retlists = []
for casting_class in spell_lists:
clname = casting_class['name']
clname = clname.replace('Spells', '').strip()
clname = clname.replace('Formulae', '').strip()
for sl in casting_class['sections']:
sl['type'] = 'spell_list'
if clname.find('Mythic') > -1:
clname = clname.replace('Mythic', '').strip()
sl['type'] = 'mythic_spell_list'
sl['class'] = clname
m = re.search('(\d)', sl['name'])
sl['level'] = int(m.group(0))
retlists.append(sl)
return retlists
def spell_pass(spell_list):
spells = []
school = None
descriptor = None
school_type = True
if spell_list['class'] in ['Elementalist Wizard']:
school_type = False
for s in spell_list['sections']:
if s.has_key('sections'):
if school_type:
school = s['name']
else:
descriptor = s['name']
for ss in s['sections']:
soup = BeautifulSoup(ss['text'])
spells.append(create_spell(ss['name'], soup, school, descriptor))
elif spell_list['source'] in ('Mythic Adventures', 'Advanced Race Guide'):# spell_list['type'] == 'mythic_spell_list':
soup = BeautifulSoup(s['text'])
spells.append(create_spell(s['name'], soup))
else:
soup = BeautifulSoup(s['text'])
if ''.join(soup.findAll(text=True)) == '':
if school_type:
school = s['name']
else:
descriptor = s['name']
else:
spells.append(create_spell(s['name'], soup, school, descriptor))
spell_list['spells'] = spells
del spell_list['sections']
return spell_list
def create_spell(name, soup, school=None, descriptor=None):
if name.endswith(":"):
name = name[:-1]
comps = ""
if soup.find('sup'):
sup = soup.find('sup')
comps = sup.renderContents()
sup.replaceWith('')
if comps.find(",") > -1:
comps = [c.strip() for c in comps.split(",")]
else:
comps = list(comps)
desc = ''.join(soup.findAll(text=True))
if desc.startswith(":"):
desc = desc[1:].strip()
spell = {'name': name}
if desc.strip() != '':
desc = desc.strip()
desc = desc.replace("“", '"')
desc = desc.replace("”", '"')
desc = desc.replace("–", '-')
spell['description'] = desc
if len(comps) > 0:
spell['material'] = comps
if school:
spell['school'] = school
if descriptor:
spell['descriptor'] = descriptor
return spell
def parse_spell_lists(filename, output, book):
struct = parse_universal(filename, output, book)
struct = quote_pass(struct)
struct = entity_pass(struct)
rules, spell_lists = spell_list_structure_pass(struct, os.path.basename(filename))
spell_lists = spell_list_name_pass(spell_lists)
for spell_list in spell_lists:
sl = spell_pass(spell_list)
print "%s: %s" %(sl['source'], sl['name'])
filename = create_spell_list_filename(output, book, sl)
fp = open(filename, 'w')
json.dump(sl, fp, indent=4)
fp.close()
if rules:
write_rules(output, rules, book, "spell_lists")
def create_spell_list_filename(output, book, spell_list):
title = char_replace(book) + "/spell_lists/" + char_replace(spell_list['class']) + "-" + unicode(spell_list['level'])
return os.path.abspath(output + "/" + title + ".json")<|fim▁end|> |
def core_structure_pass(section, filename):
section['name'] = 'Spell Lists'
sections = [] |
<|file_name|>indentation.ts<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, IActionOptions, registerEditorAction, registerEditorContribution, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { ShiftCommand } from 'vs/editor/common/commands/shiftCommand';
import { EditorAutoIndentStrategy, EditorOption } from 'vs/editor/common/config/editorOptions';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { IRange, Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { ICommand, ICursorStateComputerData, IEditOperationBuilder, IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { EndOfLineSequence, IIdentifiedSingleEditOperation, ITextModel } from 'vs/editor/common/model';
import { TextModel } from 'vs/editor/common/model/textModel';
import { StandardTokenType, TextEdit } from 'vs/editor/common/modes';
import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry';
import { IndentConsts } from 'vs/editor/common/modes/supports/indentRules';
import { IModelService } from 'vs/editor/common/services/modelService';
import * as indentUtils from 'vs/editor/contrib/indentation/indentUtils';
import * as nls from 'vs/nls';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
export function getReindentEditOperations(model: ITextModel, startLineNumber: number, endLineNumber: number, inheritedIndent?: string): IIdentifiedSingleEditOperation[] {
if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
// Model is empty
return [];
}
let indentationRules = LanguageConfigurationRegistry.getIndentationRules(model.getLanguageIdentifier().id);
if (!indentationRules) {
return [];
}
endLineNumber = Math.min(endLineNumber, model.getLineCount());
// Skip `unIndentedLinePattern` lines
while (startLineNumber <= endLineNumber) {
if (!indentationRules.unIndentedLinePattern) {
break;
}
let text = model.getLineContent(startLineNumber);
if (!indentationRules.unIndentedLinePattern.test(text)) {
break;
}
startLineNumber++;
}
if (startLineNumber > endLineNumber - 1) {
return [];
}
const { tabSize, indentSize, insertSpaces } = model.getOptions();
const shiftIndent = (indentation: string, count?: number) => {
count = count || 1;
return ShiftCommand.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
};
const unshiftIndent = (indentation: string, count?: number) => {
count = count || 1;
return ShiftCommand.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
};
let indentEdits: IIdentifiedSingleEditOperation[] = [];
// indentation being passed to lines below
let globalIndent: string;
// Calculate indentation for the first line
// If there is no passed-in indentation, we use the indentation of the first line as base.
let currentLineText = model.getLineContent(startLineNumber);
let adjustedLineContent = currentLineText;
if (inheritedIndent !== undefined && inheritedIndent !== null) {
globalIndent = inheritedIndent;
let oldIndentation = strings.getLeadingWhitespace(currentLineText);
adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
globalIndent = unshiftIndent(globalIndent);
adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
}
if (currentLineText !== adjustedLineContent) {
indentEdits.push(EditOperation.replaceMove(new Selection(startLineNumber, 1, startLineNumber, oldIndentation.length + 1), TextModel.normalizeIndentation(globalIndent, indentSize, insertSpaces)));
}
} else {
globalIndent = strings.getLeadingWhitespace(currentLineText);
}
// idealIndentForNextLine doesn't equal globalIndent when there is a line matching `indentNextLinePattern`.
let idealIndentForNextLine: string = globalIndent;
if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
globalIndent = shiftIndent(globalIndent);
}
else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
}
startLineNumber++;
// Calculate indentation adjustment for all following lines
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let text = model.getLineContent(lineNumber);
let oldIndentation = strings.getLeadingWhitespace(text);
let adjustedLineContent = idealIndentForNextLine + text.substring(oldIndentation.length);
if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
idealIndentForNextLine = unshiftIndent(idealIndentForNextLine);
globalIndent = unshiftIndent(globalIndent);
}
if (oldIndentation !== idealIndentForNextLine) {
indentEdits.push(EditOperation.replaceMove(new Selection(lineNumber, 1, lineNumber, oldIndentation.length + 1), TextModel.normalizeIndentation(idealIndentForNextLine, indentSize, insertSpaces)));
}
// calculate idealIndentForNextLine
if (indentationRules.unIndentedLinePattern && indentationRules.unIndentedLinePattern.test(text)) {
// In reindent phase, if the line matches `unIndentedLinePattern` we inherit indentation from above lines
// but don't change globalIndent and idealIndentForNextLine.
continue;
} else if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
globalIndent = shiftIndent(globalIndent);
idealIndentForNextLine = globalIndent;
} else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
} else {
idealIndentForNextLine = globalIndent;
}
}
return indentEdits;
}
export class IndentationToSpacesAction extends EditorAction {
public static readonly ID = 'editor.action.indentationToSpaces';
constructor() {
super({
id: IndentationToSpacesAction.ID,
label: nls.localize('indentationToSpaces', "Convert Indentation to Spaces"),
alias: 'Convert Indentation to Spaces',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
let model = editor.getModel();
if (!model) {
return;
}
let modelOpts = model.getOptions();
let selection = editor.getSelection();
if (!selection) {
return;
}
const command = new IndentationToSpacesCommand(selection, modelOpts.tabSize);
editor.pushUndoStop();
editor.executeCommands(this.id, [command]);
editor.pushUndoStop();
model.updateOptions({
insertSpaces: true
});
}
}
export class IndentationToTabsAction extends EditorAction {
public static readonly ID = 'editor.action.indentationToTabs';
constructor() {
super({
id: IndentationToTabsAction.ID,
label: nls.localize('indentationToTabs', "Convert Indentation to Tabs"),
alias: 'Convert Indentation to Tabs',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
let model = editor.getModel();
if (!model) {
return;
}
let modelOpts = model.getOptions();
let selection = editor.getSelection();
if (!selection) {
return;
}
const command = new IndentationToTabsCommand(selection, modelOpts.tabSize);
editor.pushUndoStop();
editor.executeCommands(this.id, [command]);
editor.pushUndoStop();
model.updateOptions({
insertSpaces: false
});
}
}
export class ChangeIndentationSizeAction extends EditorAction {
constructor(private readonly insertSpaces: boolean, opts: IActionOptions) {
super(opts);
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const quickInputService = accessor.get(IQuickInputService);
const modelService = accessor.get(IModelService);
let model = editor.getModel();
if (!model) {
return;
}
let creationOpts = modelService.getCreationOptions(model.getLanguageIdentifier().language, model.uri, model.isForSimpleWidget);
const picks = [1, 2, 3, 4, 5, 6, 7, 8].map(n => ({
id: n.toString(),
label: n.toString(),
// add description for tabSize value set in the configuration
description: n === creationOpts.tabSize ? nls.localize('configuredTabSize', "Configured Tab Size") : undefined
}));
// auto focus the tabSize set for the current editor
const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7);
setTimeout(() => {
quickInputService.pick(picks, { placeHolder: nls.localize({ key: 'selectTabWidth', comment: ['Tab corresponds to the tab key'] }, "Select Tab Size for Current File"), activeItem: picks[autoFocusIndex] }).then(pick => {
if (pick) {
if (model && !model.isDisposed()) {
model.updateOptions({
tabSize: parseInt(pick.label, 10),
insertSpaces: this.insertSpaces
});
}
}
});
}, 50/* quick input is sensitive to being opened so soon after another */);
}
}
export class IndentUsingTabs extends ChangeIndentationSizeAction {
public static readonly ID = 'editor.action.indentUsingTabs';
constructor() {
super(false, {
id: IndentUsingTabs.ID,
label: nls.localize('indentUsingTabs', "Indent Using Tabs"),
alias: 'Indent Using Tabs',
precondition: undefined
});
}
}
export class IndentUsingSpaces extends ChangeIndentationSizeAction {
public static readonly ID = 'editor.action.indentUsingSpaces';
constructor() {
super(true, {
id: IndentUsingSpaces.ID,
label: nls.localize('indentUsingSpaces', "Indent Using Spaces"),
alias: 'Indent Using Spaces',
precondition: undefined
});
}
}
export class DetectIndentation extends EditorAction {
public static readonly ID = 'editor.action.detectIndentation';
constructor() {
super({
id: DetectIndentation.ID,
label: nls.localize('detectIndentation', "Detect Indentation from Content"),
alias: 'Detect Indentation from Content',
precondition: undefined
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const modelService = accessor.get(IModelService);
let model = editor.getModel();
if (!model) {
return;
}
let creationOpts = modelService.getCreationOptions(model.getLanguageIdentifier().language, model.uri, model.isForSimpleWidget);
model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
}
}
export class ReindentLinesAction extends EditorAction {
constructor() {
super({
id: 'editor.action.reindentlines',
label: nls.localize('editor.reindentlines', "Reindent Lines"),
alias: 'Reindent Lines',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
let model = editor.getModel();
if (!model) {
return;
}
let edits = getReindentEditOperations(model, 1, model.getLineCount());
if (edits.length > 0) {
editor.pushUndoStop();
editor.executeEdits(this.id, edits);
editor.pushUndoStop();
}
}
}
export class ReindentSelectedLinesAction extends EditorAction {
constructor() {
super({
id: 'editor.action.reindentselectedlines',
label: nls.localize('editor.reindentselectedlines', "Reindent Selected Lines"),
alias: 'Reindent Selected Lines',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
let model = editor.getModel();
if (!model) {
return;
}
let selections = editor.getSelections();
if (selections === null) {
return;
}
let edits: IIdentifiedSingleEditOperation[] = [];
for (let selection of selections) {
let startLineNumber = selection.startLineNumber;
let endLineNumber = selection.endLineNumber;
if (startLineNumber !== endLineNumber && selection.endColumn === 1) {
endLineNumber--;
}
if (startLineNumber === 1) {
if (startLineNumber === endLineNumber) {
continue;
}
} else {
startLineNumber--;
}
let editOperations = getReindentEditOperations(model, startLineNumber, endLineNumber);
edits.push(...editOperations);
}
if (edits.length > 0) {
editor.pushUndoStop();
editor.executeEdits(this.id, edits);
editor.pushUndoStop();
}
}
}
export class AutoIndentOnPasteCommand implements ICommand {
private readonly _edits: { range: IRange; text: string; eol?: EndOfLineSequence; }[];
private readonly _initialSelection: Selection;
private _selectionId: string | null;
constructor(edits: TextEdit[], initialSelection: Selection) {
this._initialSelection = initialSelection;
this._edits = [];
this._selectionId = null;
for (let edit of edits) {
if (edit.range && typeof edit.text === 'string') {
this._edits.push(edit as { range: IRange; text: string; eol?: EndOfLineSequence; });
}
}
}
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
for (let edit of this._edits) {
builder.addEditOperation(Range.lift(edit.range), edit.text);
}
let selectionIsSet = false;
if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
if (this._edits[0].range.startColumn === this._initialSelection.endColumn &&
this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
selectionIsSet = true;
this._selectionId = builder.trackSelection(this._initialSelection, true);
} else if (this._edits[0].range.endColumn === this._initialSelection.startColumn &&<|fim▁hole|> this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
selectionIsSet = true;
this._selectionId = builder.trackSelection(this._initialSelection, false);
}
}
if (!selectionIsSet) {
this._selectionId = builder.trackSelection(this._initialSelection);
}
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
return helper.getTrackedSelection(this._selectionId!);
}
}
export class AutoIndentOnPaste implements IEditorContribution {
public static readonly ID = 'editor.contrib.autoIndentOnPaste';
private readonly editor: ICodeEditor;
private readonly callOnDispose = new DisposableStore();
private readonly callOnModel = new DisposableStore();
constructor(editor: ICodeEditor) {
this.editor = editor;
this.callOnDispose.add(editor.onDidChangeConfiguration(() => this.update()));
this.callOnDispose.add(editor.onDidChangeModel(() => this.update()));
this.callOnDispose.add(editor.onDidChangeModelLanguage(() => this.update()));
}
private update(): void {
// clean up
this.callOnModel.clear();
// we are disabled
if (this.editor.getOption(EditorOption.autoIndent) < EditorAutoIndentStrategy.Full || this.editor.getOption(EditorOption.formatOnPaste)) {
return;
}
// no model
if (!this.editor.hasModel()) {
return;
}
this.callOnModel.add(this.editor.onDidPaste(({ range }) => {
this.trigger(range);
}));
}
private trigger(range: Range): void {
let selections = this.editor.getSelections();
if (selections === null || selections.length > 1) {
return;
}
const model = this.editor.getModel();
if (!model) {
return;
}
if (!model.isCheapToTokenize(range.getStartPosition().lineNumber)) {
return;
}
const autoIndent = this.editor.getOption(EditorOption.autoIndent);
const { tabSize, indentSize, insertSpaces } = model.getOptions();
let textEdits: TextEdit[] = [];
let indentConverter = {
shiftIndent: (indentation: string) => {
return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
},
unshiftIndent: (indentation: string) => {
return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
}
};
let startLineNumber = range.startLineNumber;
while (startLineNumber <= range.endLineNumber) {
if (this.shouldIgnoreLine(model, startLineNumber)) {
startLineNumber++;
continue;
}
break;
}
if (startLineNumber > range.endLineNumber) {
return;
}
let firstLineText = model.getLineContent(startLineNumber);
if (!/\S/.test(firstLineText.substring(0, range.startColumn - 1))) {
let indentOfFirstLine = LanguageConfigurationRegistry.getGoodIndentForLine(autoIndent, model, model.getLanguageIdentifier().id, startLineNumber, indentConverter);
if (indentOfFirstLine !== null) {
let oldIndentation = strings.getLeadingWhitespace(firstLineText);
let newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize);
let oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
let newIndent = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
textEdits.push({
range: new Range(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
text: newIndent
});
firstLineText = newIndent + firstLineText.substr(oldIndentation.length);
} else {
let indentMetadata = LanguageConfigurationRegistry.getIndentMetadata(model, startLineNumber);
if (indentMetadata === 0 || indentMetadata === IndentConsts.UNINDENT_MASK) {
// we paste content into a line where only contains whitespaces
// after pasting, the indentation of the first line is already correct
// the first line doesn't match any indentation rule
// then no-op.
return;
}
}
}
}
const firstLineNumber = startLineNumber;
// ignore empty or ignored lines
while (startLineNumber < range.endLineNumber) {
if (!/\S/.test(model.getLineContent(startLineNumber + 1))) {
startLineNumber++;
continue;
}
break;
}
if (startLineNumber !== range.endLineNumber) {
let virtualModel = {
getLineTokens: (lineNumber: number) => {
return model.getLineTokens(lineNumber);
},
getLanguageIdentifier: () => {
return model.getLanguageIdentifier();
},
getLanguageIdAtPosition: (lineNumber: number, column: number) => {
return model.getLanguageIdAtPosition(lineNumber, column);
},
getLineContent: (lineNumber: number) => {
if (lineNumber === firstLineNumber) {
return firstLineText;
} else {
return model.getLineContent(lineNumber);
}
}
};
let indentOfSecondLine = LanguageConfigurationRegistry.getGoodIndentForLine(autoIndent, virtualModel, model.getLanguageIdentifier().id, startLineNumber + 1, indentConverter);
if (indentOfSecondLine !== null) {
let newSpaceCntOfSecondLine = indentUtils.getSpaceCnt(indentOfSecondLine, tabSize);
let oldSpaceCntOfSecondLine = indentUtils.getSpaceCnt(strings.getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize);
if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
let spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
for (let i = startLineNumber + 1; i <= range.endLineNumber; i++) {
let lineContent = model.getLineContent(i);
let originalIndent = strings.getLeadingWhitespace(lineContent);
let originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize);
let newSpacesCnt = originalSpacesCnt + spaceCntOffset;
let newIndent = indentUtils.generateIndent(newSpacesCnt, tabSize, insertSpaces);
if (newIndent !== originalIndent) {
textEdits.push({
range: new Range(i, 1, i, originalIndent.length + 1),
text: newIndent
});
}
}
}
}
}
if (textEdits.length > 0) {
this.editor.pushUndoStop();
let cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection()!);
this.editor.executeCommand('autoIndentOnPaste', cmd);
this.editor.pushUndoStop();
}
}
private shouldIgnoreLine(model: ITextModel, lineNumber: number): boolean {
model.forceTokenization(lineNumber);
let nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
if (nonWhitespaceColumn === 0) {
return true;
}
let tokens = model.getLineTokens(lineNumber);
if (tokens.getCount() > 0) {
let firstNonWhitespaceTokenIndex = tokens.findTokenIndexAtOffset(nonWhitespaceColumn);
if (firstNonWhitespaceTokenIndex >= 0 && tokens.getStandardTokenType(firstNonWhitespaceTokenIndex) === StandardTokenType.Comment) {
return true;
}
}
return false;
}
public dispose(): void {
this.callOnDispose.dispose();
this.callOnModel.dispose();
}
}
function getIndentationEditOperations(model: ITextModel, builder: IEditOperationBuilder, tabSize: number, tabsToSpaces: boolean): void {
if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
// Model is empty
return;
}
let spaces = '';
for (let i = 0; i < tabSize; i++) {
spaces += ' ';
}
let spacesRegExp = new RegExp(spaces, 'gi');
for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
if (lastIndentationColumn === 0) {
lastIndentationColumn = model.getLineMaxColumn(lineNumber);
}
if (lastIndentationColumn === 1) {
continue;
}
const originalIndentationRange = new Range(lineNumber, 1, lineNumber, lastIndentationColumn);
const originalIndentation = model.getValueInRange(originalIndentationRange);
const newIndentation = (
tabsToSpaces
? originalIndentation.replace(/\t/ig, spaces)
: originalIndentation.replace(spacesRegExp, '\t')
);
builder.addEditOperation(originalIndentationRange, newIndentation);
}
}
export class IndentationToSpacesCommand implements ICommand {
private selectionId: string | null = null;
constructor(private readonly selection: Selection, private tabSize: number) { }
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
this.selectionId = builder.trackSelection(this.selection);
getIndentationEditOperations(model, builder, this.tabSize, true);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
return helper.getTrackedSelection(this.selectionId!);
}
}
export class IndentationToTabsCommand implements ICommand {
private selectionId: string | null = null;
constructor(private readonly selection: Selection, private tabSize: number) { }
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
this.selectionId = builder.trackSelection(this.selection);
getIndentationEditOperations(model, builder, this.tabSize, false);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
return helper.getTrackedSelection(this.selectionId!);
}
}
registerEditorContribution(AutoIndentOnPaste.ID, AutoIndentOnPaste);
registerEditorAction(IndentationToSpacesAction);
registerEditorAction(IndentationToTabsAction);
registerEditorAction(IndentUsingTabs);
registerEditorAction(IndentUsingSpaces);
registerEditorAction(DetectIndentation);
registerEditorAction(ReindentLinesAction);
registerEditorAction(ReindentSelectedLinesAction);<|fim▁end|> | |
<|file_name|>01-add-snippets-table.js<|end_file_name|><|fim▁begin|>const {addTable} = require('../../utils');<|fim▁hole|>module.exports = addTable('snippets');<|fim▁end|> | |
<|file_name|>rename_unix.go<|end_file_name|><|fim▁begin|><|fim▁hole|>package atomicfile
import (
"os"
)
// AtomicRename atomically renames (moves) oldpath to newpath.
// It is guaranteed to either replace the target file entirely, or not
// change either file.
func AtomicRename(oldpath, newpath string) error {
return os.Rename(oldpath, newpath)
}<|fim▁end|> | // +build !windows
|
<|file_name|>orca_gui_prefs.py<|end_file_name|><|fim▁begin|># Orca
#
# Copyright 2005-2009 Sun Microsystems Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA 02110-1301 USA.
"""Displays a GUI for the user to set Orca preferences."""
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2005-2009 Sun Microsystems Inc."
__license__ = "LGPL"
import os
from gi.repository import Gdk
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import GObject
from gi.repository import Pango
import pyatspi
import time
from . import acss
from . import debug
from . import guilabels
from . import messages
from . import orca
from . import orca_gtkbuilder
from . import orca_gui_profile
from . import orca_state
from . import orca_platform
from . import settings
from . import settings_manager
from . import input_event
from . import keybindings
from . import pronunciation_dict
from . import braille
from . import speech
from . import speechserver
from . import text_attribute_names
_settingsManager = settings_manager.getManager()
try:
import louis
except ImportError:
louis = None
from .orca_platform import tablesdir
if louis and not tablesdir:
louis = None
(HANDLER, DESCRIP, MOD_MASK1, MOD_USED1, KEY1, CLICK_COUNT1, OLDTEXT1, \
TEXT1, MODIF, EDITABLE) = list(range(10))
(NAME, IS_SPOKEN, IS_BRAILLED, VALUE) = list(range(4))
(ACTUAL, REPLACEMENT) = list(range(2))
# Must match the order of voice types in the GtkBuilder file.
#
(DEFAULT, UPPERCASE, HYPERLINK, SYSTEM) = list(range(4))
# Must match the order that the timeFormatCombo is populated.
#
(TIME_FORMAT_LOCALE, TIME_FORMAT_12_HM, TIME_FORMAT_12_HMS, TIME_FORMAT_24_HMS,
TIME_FORMAT_24_HMS_WITH_WORDS, TIME_FORMAT_24_HM,
TIME_FORMAT_24_HM_WITH_WORDS) = list(range(7))
# Must match the order that the dateFormatCombo is populated.
#
(DATE_FORMAT_LOCALE, DATE_FORMAT_NUMBERS_DM, DATE_FORMAT_NUMBERS_MD,
DATE_FORMAT_NUMBERS_DMY, DATE_FORMAT_NUMBERS_MDY, DATE_FORMAT_NUMBERS_YMD,
DATE_FORMAT_FULL_DM, DATE_FORMAT_FULL_MD, DATE_FORMAT_FULL_DMY,
DATE_FORMAT_FULL_MDY, DATE_FORMAT_FULL_YMD, DATE_FORMAT_ABBREVIATED_DM,
DATE_FORMAT_ABBREVIATED_MD, DATE_FORMAT_ABBREVIATED_DMY,
DATE_FORMAT_ABBREVIATED_MDY, DATE_FORMAT_ABBREVIATED_YMD) = list(range(16))
class OrcaSetupGUI(orca_gtkbuilder.GtkBuilderWrapper):
def __init__(self, fileName, windowName, prefsDict):
"""Initialize the Orca configuration GUI.
Arguments:
- fileName: name of the GtkBuilder file.
- windowName: name of the component to get from the GtkBuilder file.
- prefsDict: dictionary of preferences to use during initialization
"""
orca_gtkbuilder.GtkBuilderWrapper.__init__(self, fileName, windowName)
self.prefsDict = prefsDict
self._defaultProfile = ['Default', 'default']
# Initialize variables to None to keep pylint happy.
#
self.bbindings = None
self.cellRendererText = None
self.defaultVoice = None
self.disableKeyGrabPref = None
self.getTextAttributesView = None
self.hyperlinkVoice = None
self.initializingSpeech = None
self.kbindings = None
self.keyBindingsModel = None
self.keyBindView = None
self.newBinding = None
self.pendingKeyBindings = None
self.planeCellRendererText = None
self.pronunciationModel = None
self.pronunciationView = None
self.screenHeight = None
self.screenWidth = None
self.speechFamiliesChoice = None
self.speechFamiliesChoices = None
self.speechFamiliesModel = None
self.speechLanguagesChoice = None
self.speechLanguagesChoices = None
self.speechLanguagesModel = None
self.speechFamilies = []
self.speechServersChoice = None
self.speechServersChoices = None
self.speechServersModel = None
self.speechSystemsChoice = None
self.speechSystemsChoices = None
self.speechSystemsModel = None
self.systemVoice = None
self.uppercaseVoice = None
self.window = None
self.workingFactories = None
self.savedGain = None
self.savedPitch = None
self.savedRate = None
self._isInitialSetup = False
self.selectedFamilyChoices = {}
self.selectedLanguageChoices = {}
self.profilesCombo = None
self.profilesComboModel = None
self.startingProfileCombo = None
self._capturedKey = []
self.script = None
def init(self, script):
"""Initialize the Orca configuration GUI. Read the users current
set of preferences and set the GUI state to match. Setup speech
support and populate the combo box lists on the Speech Tab pane
accordingly.
"""
self.script = script
# Restore the default rate/pitch/gain,
# in case the user played with the sliders.
#
try:
voices = _settingsManager.getSetting('voices')
defaultVoice = voices[settings.DEFAULT_VOICE]
except KeyError:
defaultVoice = {}
try:
self.savedGain = defaultVoice[acss.ACSS.GAIN]
except KeyError:
self.savedGain = 10.0
try:
self.savedPitch = defaultVoice[acss.ACSS.AVERAGE_PITCH]
except KeyError:
self.savedPitch = 5.0
try:
self.savedRate = defaultVoice[acss.ACSS.RATE]
except KeyError:
self.savedRate = 50.0
# ***** Key Bindings treeview initialization *****
self.keyBindView = self.get_widget("keyBindingsTreeview")
if self.keyBindView.get_columns():
for column in self.keyBindView.get_columns():
self.keyBindView.remove_column(column)
self.keyBindingsModel = Gtk.TreeStore(
GObject.TYPE_STRING, # Handler name
GObject.TYPE_STRING, # Human Readable Description
GObject.TYPE_STRING, # Modifier mask 1
GObject.TYPE_STRING, # Used Modifiers 1
GObject.TYPE_STRING, # Modifier key name 1
GObject.TYPE_STRING, # Click count 1
GObject.TYPE_STRING, # Original Text of the Key Binding Shown 1
GObject.TYPE_STRING, # Text of the Key Binding Shown 1
GObject.TYPE_BOOLEAN, # Key Modified by User
GObject.TYPE_BOOLEAN) # Row with fields editable or not
self.planeCellRendererText = Gtk.CellRendererText()
self.cellRendererText = Gtk.CellRendererText()
self.cellRendererText.set_property("ellipsize", Pango.EllipsizeMode.END)
# HANDLER - invisble column
#
column = Gtk.TreeViewColumn("Handler",
self.planeCellRendererText,
text=HANDLER)
column.set_resizable(True)
column.set_visible(False)
column.set_sort_column_id(HANDLER)
self.keyBindView.append_column(column)
# DESCRIP
#
column = Gtk.TreeViewColumn(guilabels.KB_HEADER_FUNCTION,
self.cellRendererText,
text=DESCRIP)
column.set_resizable(True)
column.set_min_width(380)
column.set_sort_column_id(DESCRIP)
self.keyBindView.append_column(column)
# MOD_MASK1 - invisble column
#
column = Gtk.TreeViewColumn("Mod.Mask 1",
self.planeCellRendererText,
text=MOD_MASK1)
column.set_visible(False)
column.set_resizable(True)
column.set_sort_column_id(MOD_MASK1)
self.keyBindView.append_column(column)
# MOD_USED1 - invisble column
#
column = Gtk.TreeViewColumn("Use Mod.1",
self.planeCellRendererText,
text=MOD_USED1)
column.set_visible(False)
column.set_resizable(True)
column.set_sort_column_id(MOD_USED1)
self.keyBindView.append_column(column)
# KEY1 - invisble column
#
column = Gtk.TreeViewColumn("Key1",
self.planeCellRendererText,
text=KEY1)
column.set_resizable(True)
column.set_visible(False)
column.set_sort_column_id(KEY1)
self.keyBindView.append_column(column)
# CLICK_COUNT1 - invisble column
#
column = Gtk.TreeViewColumn("ClickCount1",
self.planeCellRendererText,
text=CLICK_COUNT1)
column.set_resizable(True)
column.set_visible(False)
column.set_sort_column_id(CLICK_COUNT1)
self.keyBindView.append_column(column)
# OLDTEXT1 - invisble column which will store a copy of the
# original keybinding in TEXT1 prior to the Apply or OK
# buttons being pressed. This will prevent automatic
# resorting each time a cell is edited.
#
column = Gtk.TreeViewColumn("OldText1",
self.planeCellRendererText,
text=OLDTEXT1)
column.set_resizable(True)
column.set_visible(False)
column.set_sort_column_id(OLDTEXT1)
self.keyBindView.append_column(column)
# TEXT1
#
rendererText = Gtk.CellRendererText()
rendererText.connect("editing-started",
self.editingKey,
self.keyBindingsModel)
rendererText.connect("editing-canceled",
self.editingCanceledKey)
rendererText.connect('edited',
self.editedKey,
self.keyBindingsModel,
MOD_MASK1, MOD_USED1, KEY1, CLICK_COUNT1, TEXT1)
column = Gtk.TreeViewColumn(guilabels.KB_HEADER_KEY_BINDING,
rendererText,
text=TEXT1,
editable=EDITABLE)
column.set_resizable(True)
column.set_sort_column_id(OLDTEXT1)
self.keyBindView.append_column(column)
# MODIF
#
rendererToggle = Gtk.CellRendererToggle()
rendererToggle.connect('toggled',
self.keyModifiedToggle,
self.keyBindingsModel,
MODIF)
column = Gtk.TreeViewColumn(guilabels.KB_MODIFIED,
rendererToggle,
active=MODIF,
activatable=EDITABLE)
#column.set_visible(False)
column.set_resizable(True)
column.set_sort_column_id(MODIF)
self.keyBindView.append_column(column)
# EDITABLE - invisble column
#
rendererToggle = Gtk.CellRendererToggle()
rendererToggle.set_property('activatable', False)
column = Gtk.TreeViewColumn("Modified",
rendererToggle,
active=EDITABLE)
column.set_visible(False)
column.set_resizable(True)
column.set_sort_column_id(EDITABLE)
self.keyBindView.append_column(column)
# Populates the treeview with all the keybindings:
#
self._populateKeyBindings()
self.window = self.get_widget("orcaSetupWindow")
self._setKeyEchoItems()
self.speechSystemsModel = \
self._initComboBox(self.get_widget("speechSystems"))
self.speechServersModel = \
self._initComboBox(self.get_widget("speechServers"))
self.speechLanguagesModel = \
self._initComboBox(self.get_widget("speechLanguages"))
self.speechFamiliesModel = \
self._initComboBox(self.get_widget("speechFamilies"))
self._initSpeechState()
# TODO - JD: Will this ever be the case??
self._isInitialSetup = \
not os.path.exists(_settingsManager.getPrefsDir())
appPage = self.script.getAppPreferencesGUI()
if appPage:
label = Gtk.Label(label=self.script.app.name)
self.get_widget("notebook").append_page(appPage, label)
self._initGUIState()
def _getACSSForVoiceType(self, voiceType):
"""Return the ACSS value for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
Returns the voice dictionary for the given voice type.
"""
if voiceType == DEFAULT:
voiceACSS = self.defaultVoice
elif voiceType == UPPERCASE:
voiceACSS = self.uppercaseVoice
elif voiceType == HYPERLINK:
voiceACSS = self.hyperlinkVoice
elif voiceType == SYSTEM:
voiceACSS = self.systemVoice
else:
voiceACSS = self.defaultVoice
return voiceACSS
def writeUserPreferences(self):
"""Write out the user's generic Orca preferences.
"""
pronunciationDict = self.getModelDict(self.pronunciationModel)
keyBindingsDict = self.getKeyBindingsModelDict(self.keyBindingsModel)
self.prefsDict.update(self.script.getPreferencesFromGUI())
_settingsManager.saveSettings(self.script,
self.prefsDict,
pronunciationDict,
keyBindingsDict)
def _getKeyValueForVoiceType(self, voiceType, key, useDefault=True):
"""Look for the value of the given key in the voice dictionary
for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
- key: the key to look for in the voice dictionary.
- useDefault: if True, and the key isn't found for the given voice
type, the look for it in the default voice dictionary
as well.
Returns the value of the given key, or None if it's not set.
"""
if voiceType == DEFAULT:
voice = self.defaultVoice
elif voiceType == UPPERCASE:
voice = self.uppercaseVoice
if key not in voice:
if not useDefault:
return None
voice = self.defaultVoice
elif voiceType == HYPERLINK:
voice = self.hyperlinkVoice
if key not in voice:
if not useDefault:
return None
voice = self.defaultVoice
elif voiceType == SYSTEM:
voice = self.systemVoice
if key not in voice:
if not useDefault:
return None
voice = self.defaultVoice
else:
voice = self.defaultVoice
if key in voice:
return voice[key]
else:
return None
def _getFamilyNameForVoiceType(self, voiceType):
"""Gets the name of the voice family for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
Returns the name of the voice family for the given voice type,
or None if not set.
"""
familyName = None
family = self._getKeyValueForVoiceType(voiceType, acss.ACSS.FAMILY)
if family and speechserver.VoiceFamily.NAME in family:
familyName = family[speechserver.VoiceFamily.NAME]
return familyName
def _setFamilyNameForVoiceType(self, voiceType, name, language, dialect, variant):
"""Sets the name of the voice family for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
- name: the name of the voice family to set.
- language: the locale of the voice family to set.
- dialect: the dialect of the voice family to set.
"""
family = self._getKeyValueForVoiceType(voiceType,
acss.ACSS.FAMILY,
False)
voiceACSS = self._getACSSForVoiceType(voiceType)
if family:
family[speechserver.VoiceFamily.NAME] = name
family[speechserver.VoiceFamily.LANG] = language
family[speechserver.VoiceFamily.DIALECT] = dialect
family[speechserver.VoiceFamily.VARIANT] = variant
else:
voiceACSS[acss.ACSS.FAMILY] = {}
voiceACSS[acss.ACSS.FAMILY][speechserver.VoiceFamily.NAME] = name
voiceACSS[acss.ACSS.FAMILY][speechserver.VoiceFamily.LANG] = language
voiceACSS[acss.ACSS.FAMILY][speechserver.VoiceFamily.DIALECT] = dialect
voiceACSS[acss.ACSS.FAMILY][speechserver.VoiceFamily.VARIANT] = variant
voiceACSS['established'] = True
#settings.voices[voiceType] = voiceACSS
def _getRateForVoiceType(self, voiceType):
"""Gets the speaking rate value for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
Returns the rate value for the given voice type, or None if
not set.
"""
return self._getKeyValueForVoiceType(voiceType, acss.ACSS.RATE)
def _setRateForVoiceType(self, voiceType, value):
"""Sets the speaking rate value for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
- value: the rate value to set.
"""
voiceACSS = self._getACSSForVoiceType(voiceType)
voiceACSS[acss.ACSS.RATE] = value
voiceACSS['established'] = True
#settings.voices[voiceType] = voiceACSS
def _getPitchForVoiceType(self, voiceType):
"""Gets the pitch value for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
Returns the pitch value for the given voice type, or None if
not set.
"""
return self._getKeyValueForVoiceType(voiceType,
acss.ACSS.AVERAGE_PITCH)
def _setPitchForVoiceType(self, voiceType, value):
"""Sets the pitch value for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
- value: the pitch value to set.
"""
voiceACSS = self._getACSSForVoiceType(voiceType)
voiceACSS[acss.ACSS.AVERAGE_PITCH] = value
voiceACSS['established'] = True
#settings.voices[voiceType] = voiceACSS
def _getVolumeForVoiceType(self, voiceType):
"""Gets the volume (gain) value for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
Returns the volume (gain) value for the given voice type, or
None if not set.
"""
return self._getKeyValueForVoiceType(voiceType, acss.ACSS.GAIN)
def _setVolumeForVoiceType(self, voiceType, value):
"""Sets the volume (gain) value for the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
- value: the volume (gain) value to set.
"""
voiceACSS = self._getACSSForVoiceType(voiceType)
voiceACSS[acss.ACSS.GAIN] = value
voiceACSS['established'] = True
#settings.voices[voiceType] = voiceACSS
def _setVoiceSettingsForVoiceType(self, voiceType):
"""Sets the family, rate, pitch and volume GUI components based
on the given voice type.
Arguments:
- voiceType: one of DEFAULT, UPPERCASE, HYPERLINK, SYSTEM
"""
familyName = self._getFamilyNameForVoiceType(voiceType)
self._setSpeechFamiliesChoice(familyName)
rate = self._getRateForVoiceType(voiceType)
if rate is not None:
self.get_widget("rateScale").set_value(rate)
else:
self.get_widget("rateScale").set_value(50.0)
pitch = self._getPitchForVoiceType(voiceType)
if pitch is not None:
self.get_widget("pitchScale").set_value(pitch)
else:
self.get_widget("pitchScale").set_value(5.0)
volume = self._getVolumeForVoiceType(voiceType)
if volume is not None:
self.get_widget("volumeScale").set_value(volume)
else:
self.get_widget("volumeScale").set_value(10.0)
def _setSpeechFamiliesChoice(self, familyName):
"""Sets the active item in the families ("Person:") combo box
to the given family name.
Arguments:
- familyName: the family name to use to set the active combo box item.
"""
if len(self.speechFamilies) == 0:
return
languageSet = False
familySet = False
for family in self.speechFamilies:
name = family[speechserver.VoiceFamily.NAME]
if name == familyName:
lang = family[speechserver.VoiceFamily.LANG]
dialect = family[speechserver.VoiceFamily.DIALECT]
if dialect:
language = lang + '-' + dialect
else:
language = lang
i = 0
for languageChoice in self.speechLanguagesChoices:
if languageChoice == language:
self.get_widget("speechLanguages").set_active(i)
self.speechLanguagesChoice = self.speechLanguagesChoices[i]
languageSet = True
self._setupFamilies()
i = 0
for familyChoice in self.speechFamiliesChoices:
name = familyChoice[speechserver.VoiceFamily.NAME]
if name == familyName:
self.get_widget("speechFamilies").set_active(i)
self.speechFamiliesChoice = self.speechFamiliesChoices[i]
familySet = True
break
i += 1
break
i += 1
break
if not languageSet:
debug.println(debug.LEVEL_FINEST,
"Could not find speech language match for %s" \
% familyName)
self.get_widget("speechLanguages").set_active(0)
self.speechLanguagesChoice = self.speechLanguagesChoices[0]
if languageSet:
self.selectedLanguageChoices[self.speechServersChoice] = i
if not familySet:
debug.println(debug.LEVEL_FINEST,
"Could not find speech family match for %s" \
% familyName)
self.get_widget("speechFamilies").set_active(0)
self.speechFamiliesChoice = self.speechFamiliesChoices[0]
if familySet:
self.selectedFamilyChoices[self.speechServersChoice,
self.speechLanguagesChoice] = i
def _setupFamilies(self):
"""Gets the list of voice variants for the current speech server and
current language.
If there are variants, get the information associated with
each voice variant and add an entry for it to the variants
GtkComboBox list.
"""
self.speechFamiliesModel.clear()
currentLanguage = self.speechLanguagesChoice
i = 0
self.speechFamiliesChoices = []
for family in self.speechFamilies:
lang = family[speechserver.VoiceFamily.LANG]
dialect = family[speechserver.VoiceFamily.DIALECT]
if dialect:
language = lang + '-' + dialect
else:
language = lang
if language != currentLanguage:
continue
name = family[speechserver.VoiceFamily.NAME]
self.speechFamiliesChoices.append(family)
self.speechFamiliesModel.append((i, name))
i += 1
if i == 0:
debug.println(debug.LEVEL_SEVERE, "No speech family was available for %s." % str(currentLanguage))
debug.printStack(debug.LEVEL_FINEST)
self.speechFamiliesChoice = None
return
# If user manually selected a family for the current speech server
# this choice it's restored. In other case the first family
# (usually the default one) is selected
#
selectedIndex = 0
if (self.speechServersChoice, self.speechLanguagesChoice) \
in self.selectedFamilyChoices:
selectedIndex = self.selectedFamilyChoices[self.speechServersChoice,
self.speechLanguagesChoice]
self.get_widget("speechFamilies").set_active(selectedIndex)
def _setSpeechLanguagesChoice(self, languageName):
"""Sets the active item in the languages ("Language:") combo box
to the given language name.
Arguments:
- languageName: the language name to use to set the active combo box item.
"""
print("setSpeechLanguagesChoice")
if len(self.speechLanguagesChoices) == 0:
return
valueSet = False
i = 0
for language in self.speechLanguagesChoices:
if language == languageName:
self.get_widget("speechLanguages").set_active(i)
self.speechLanguagesChoice = self.speechLanguagesChoices[i]
valueSet = True
break
i += 1
if not valueSet:
debug.println(debug.LEVEL_FINEST,
"Could not find speech language match for %s" \
% languageName)
self.get_widget("speechLanguages").set_active(0)
self.speechLanguagesChoice = self.speechLanguagesChoices[0]
if valueSet:
self.selectedLanguageChoices[self.speechServersChoice] = i
self._setupFamilies()
def _setupVoices(self):
"""Gets the list of voices for the current speech server.
If there are families, get the information associated with
each voice family and add an entry for it to the families
GtkComboBox list.
"""
self.speechLanguagesModel.clear()
self.speechFamilies = self.speechServersChoice.getVoiceFamilies()
self.speechLanguagesChoices = []
if len(self.speechFamilies) == 0:
debug.println(debug.LEVEL_SEVERE, "No speech voice was available.")
debug.printStack(debug.LEVEL_FINEST)
self.speechLanguagesChoice = None
return
done = {}
i = 0
for family in self.speechFamilies:
lang = family[speechserver.VoiceFamily.LANG]
dialect = family[speechserver.VoiceFamily.DIALECT]
if (lang,dialect) in done:
continue
done[lang,dialect] = True
if dialect:
language = lang + '-' + dialect
else:
language = lang
# TODO: get translated language name from CLDR or such
msg = language
if msg == "":
# Unsupported locale
msg = "default language"
self.speechLanguagesChoices.append(language)
self.speechLanguagesModel.append((i, msg))
i += 1
# If user manually selected a language for the current speech server
# this choice it's restored. In other case the first language
# (usually the default one) is selected
#
selectedIndex = 0
if self.speechServersChoice in self.selectedLanguageChoices:
selectedIndex = self.selectedLanguageChoices[self.speechServersChoice]
self.get_widget("speechLanguages").set_active(selectedIndex)
if self.initializingSpeech:
self.speechLanguagesChoice = self.speechLanguagesChoices[selectedIndex]
self._setupFamilies()
# The family name will be selected as part of selecting the
# voice type. Whenever the families change, we'll reset the
# voice type selection to the first one ("Default").
#
comboBox = self.get_widget("voiceTypesCombo")
types = [guilabels.SPEECH_VOICE_TYPE_DEFAULT,
guilabels.SPEECH_VOICE_TYPE_UPPERCASE,
guilabels.SPEECH_VOICE_TYPE_HYPERLINK,
guilabels.SPEECH_VOICE_TYPE_SYSTEM]
self.populateComboBox(comboBox, types)
comboBox.set_active(DEFAULT)
voiceType = comboBox.get_active()
self._setVoiceSettingsForVoiceType(voiceType)
def _setSpeechServersChoice(self, serverInfo):
"""Sets the active item in the speech servers combo box to the
given server.
Arguments:
- serversChoices: the list of available speech servers.
- serverInfo: the speech server to use to set the active combo
box item.
"""
if len(self.speechServersChoices) == 0:
return
# We'll fallback to whatever we happen to be using in the event
# that this preference has never been set.
#
if not serverInfo:
serverInfo = speech.getInfo()
valueSet = False
i = 0
for server in self.speechServersChoices:
if serverInfo == server.getInfo():
self.get_widget("speechServers").set_active(i)
self.speechServersChoice = server
valueSet = True
break
i += 1
if not valueSet:
debug.println(debug.LEVEL_FINEST,
"Could not find speech server match for %s" \
% repr(serverInfo))
self.get_widget("speechServers").set_active(0)
self.speechServersChoice = self.speechServersChoices[0]
self._setupVoices()
def _setupSpeechServers(self):
"""Gets the list of speech servers for the current speech factory.
If there are servers, get the information associated with each
speech server and add an entry for it to the speechServers
GtkComboBox list. Set the current choice to be the first item.
"""
self.speechServersModel.clear()
self.speechServersChoices = \
self.speechSystemsChoice.SpeechServer.getSpeechServers()
if len(self.speechServersChoices) == 0:
debug.println(debug.LEVEL_SEVERE, "Speech not available.")
debug.printStack(debug.LEVEL_FINEST)
self.speechServersChoice = None
self.speechLanguagesChoices = []
self.speechLanguagesChoice = None
self.speechFamiliesChoices = []
self.speechFamiliesChoice = None
return
i = 0
for server in self.speechServersChoices:
name = server.getInfo()[0]
self.speechServersModel.append((i, name))
i += 1
self._setSpeechServersChoice(self.prefsDict["speechServerInfo"])
debug.println(
debug.LEVEL_FINEST,
"orca_gui_prefs._setupSpeechServers: speechServersChoice: %s" \
% self.speechServersChoice.getInfo())
def _setSpeechSystemsChoice(self, systemName):
"""Set the active item in the speech systems combo box to the
given system name.
Arguments:
- factoryChoices: the list of available speech factories (systems).
- systemName: the speech system name to use to set the active combo
box item.
"""
systemName = systemName.strip("'")
if len(self.speechSystemsChoices) == 0:
self.speechSystemsChoice = None
return
valueSet = False
i = 0
for speechSystem in self.speechSystemsChoices:
name = speechSystem.__name__
if name.endswith(systemName):
self.get_widget("speechSystems").set_active(i)
self.speechSystemsChoice = self.speechSystemsChoices[i]
valueSet = True
break
i += 1
if not valueSet:
debug.println(debug.LEVEL_FINEST,
"Could not find speech system match for %s" \
% systemName)
self.get_widget("speechSystems").set_active(0)
self.speechSystemsChoice = self.speechSystemsChoices[0]
self._setupSpeechServers()
def _setupSpeechSystems(self, factories):
"""Sets up the speech systems combo box and sets the selection
to the preferred speech system.
Arguments:
-factories: the list of known speech factories (working or not)
"""
self.speechSystemsModel.clear()
self.workingFactories = []
for factory in factories:
try:
servers = factory.SpeechServer.getSpeechServers()
if len(servers):
self.workingFactories.append(factory)
except:
debug.printException(debug.LEVEL_FINEST)
self.speechSystemsChoices = []
if len(self.workingFactories) == 0:
debug.println(debug.LEVEL_SEVERE, "Speech not available.")
debug.printStack(debug.LEVEL_FINEST)
self.speechSystemsChoice = None
self.speechServersChoices = []
self.speechServersChoice = None
self.speechLanguagesChoices = []
self.speechLanguagesChoice = None
self.speechFamiliesChoices = []
self.speechFamiliesChoice = None
return
i = 0
for workingFactory in self.workingFactories:
self.speechSystemsChoices.append(workingFactory)
name = workingFactory.SpeechServer.getFactoryName()
self.speechSystemsModel.append((i, name))
i += 1
if self.prefsDict["speechServerFactory"]:
self._setSpeechSystemsChoice(self.prefsDict["speechServerFactory"])
else:
self.speechSystemsChoice = None
debug.println(
debug.LEVEL_FINEST,
"orca_gui_prefs._setupSpeechSystems: speechSystemsChoice: %s" \
% self.speechSystemsChoice)
def _initSpeechState(self):
"""Initialize the various speech components.
"""
voices = self.prefsDict["voices"]
self.defaultVoice = acss.ACSS(voices.get(settings.DEFAULT_VOICE))
self.uppercaseVoice = acss.ACSS(voices.get(settings.UPPERCASE_VOICE))
self.hyperlinkVoice = acss.ACSS(voices.get(settings.HYPERLINK_VOICE))
self.systemVoice = acss.ACSS(voices.get(settings.SYSTEM_VOICE))
# Just a note on general naming pattern:
#
# * = The name of the combobox
# *Model = the name of the comobox model
# *Choices = the Orca/speech python objects
# *Choice = a value from *Choices
#
# Where * = speechSystems, speechServers, speechLanguages, speechFamilies
#
factories = _settingsManager.getSpeechServerFactories()
if len(factories) == 0 or not self.prefsDict.get('enableSpeech', True):
self.workingFactories = []
self.speechSystemsChoice = None
self.speechServersChoices = []
self.speechServersChoice = None
self.speechLanguagesChoices = []
self.speechLanguagesChoice = None
self.speechFamiliesChoices = []
self.speechFamiliesChoice = None
return
try:
speech.init()
except:
self.workingFactories = []
self.speechSystemsChoice = None
self.speechServersChoices = []
self.speechServersChoice = None
self.speechLanguagesChoices = []
self.speechLanguagesChoice = None
self.speechFamiliesChoices = []
self.speechFamiliesChoice = None
return
# This cascades into systems->servers->voice_type->families...
#
self.initializingSpeech = True
self._setupSpeechSystems(factories)
self.initializingSpeech = False
def _setSpokenTextAttributes(self, view, setAttributes,
state, moveToTop=False):
"""Given a set of spoken text attributes, update the model used by the
text attribute tree view.
Arguments:
- view: the text attribute tree view.
- setAttributes: the list of spoken text attributes to update.
- state: the state (True or False) that they all should be set to.
- moveToTop: if True, move these attributes to the top of the list.
"""
model = view.get_model()
view.set_model(None)
[attrList, attrDict] = \
self.script.utilities.stringToKeysAndDict(setAttributes)
[allAttrList, allAttrDict] = self.script.utilities.stringToKeysAndDict(
_settingsManager.getSetting('allTextAttributes'))
for i in range(0, len(attrList)):
for path in range(0, len(allAttrList)):
localizedKey = text_attribute_names.getTextAttributeName(
attrList[i], self.script)
localizedValue = text_attribute_names.getTextAttributeName(
attrDict[attrList[i]], self.script)
if localizedKey == model[path][NAME]:
thisIter = model.get_iter(path)
model.set_value(thisIter, NAME, localizedKey)
model.set_value(thisIter, IS_SPOKEN, state)
model.set_value(thisIter, VALUE, localizedValue)
if moveToTop:
thisIter = model.get_iter(path)
otherIter = model.get_iter(i)
model.move_before(thisIter, otherIter)
break
view.set_model(model)
def _setBrailledTextAttributes(self, view, setAttributes, state):
"""Given a set of brailled text attributes, update the model used
by the text attribute tree view.
Arguments:
- view: the text attribute tree view.
- setAttributes: the list of brailled text attributes to update.
- state: the state (True or False) that they all should be set to.
"""
model = view.get_model()
view.set_model(None)
[attrList, attrDict] = \
self.script.utilities.stringToKeysAndDict(setAttributes)
[allAttrList, allAttrDict] = self.script.utilities.stringToKeysAndDict(
_settingsManager.getSetting('allTextAttributes'))
for i in range(0, len(attrList)):
for path in range(0, len(allAttrList)):
localizedKey = text_attribute_names.getTextAttributeName(
attrList[i], self.script)
if localizedKey == model[path][NAME]:
thisIter = model.get_iter(path)
model.set_value(thisIter, IS_BRAILLED, state)
break
view.set_model(model)
def _getAppNameForAttribute(self, attributeName):
"""Converts the given Atk attribute name into the application's
equivalent. This is necessary because an application or toolkit
(e.g. Gecko) might invent entirely new names for the same text
attributes.
Arguments:
- attribName: The name of the text attribute
Returns the application's equivalent name if found or attribName
otherwise.
"""
return self.script.utilities.getAppNameForAttribute(attributeName)
def _updateTextDictEntry(self):
"""The user has updated the text attribute list in some way. Update
the "enabledSpokenTextAttributes" and "enabledBrailledTextAttributes"
preference strings to reflect the current state of the corresponding
text attribute lists.
"""
model = self.getTextAttributesView.get_model()
spokenAttrStr = ""
brailledAttrStr = ""
noRows = model.iter_n_children(None)
for path in range(0, noRows):
localizedKey = model[path][NAME]
key = text_attribute_names.getTextAttributeKey(localizedKey)
# Convert the normalized, Atk attribute name back into what
# the app/toolkit uses.
#
key = self._getAppNameForAttribute(key)
localizedValue = model[path][VALUE]
value = text_attribute_names.getTextAttributeKey(localizedValue)
if model[path][IS_SPOKEN]:
spokenAttrStr += key + ":" + value + "; "
if model[path][IS_BRAILLED]:
brailledAttrStr += key + ":" + value + "; "
self.prefsDict["enabledSpokenTextAttributes"] = spokenAttrStr
self.prefsDict["enabledBrailledTextAttributes"] = brailledAttrStr
def contractedBrailleToggled(self, checkbox):
grid = self.get_widget('contractionTableGrid')
grid.set_sensitive(checkbox.get_active())
self.prefsDict["enableContractedBraille"] = checkbox.get_active()
def contractionTableComboChanged(self, combobox):
model = combobox.get_model()
myIter = combobox.get_active_iter()
self.prefsDict["brailleContractionTable"] = model[myIter][1]
def flashPersistenceToggled(self, checkbox):
grid = self.get_widget('flashMessageDurationGrid')
grid.set_sensitive(not checkbox.get_active())
self.prefsDict["flashIsPersistent"] = checkbox.get_active()
def textAttributeSpokenToggled(self, cell, path, model):
"""The user has toggled the state of one of the text attribute
checkboxes to be spoken. Update our model to reflect this, then
update the "enabledSpokenTextAttributes" preference string.
Arguments:
- cell: the cell that changed.
- path: the path of that cell.
- model: the model that the cell is part of.
"""
thisIter = model.get_iter(path)
model.set(thisIter, IS_SPOKEN, not model[path][IS_SPOKEN])
self._updateTextDictEntry()
def textAttributeBrailledToggled(self, cell, path, model):
"""The user has toggled the state of one of the text attribute
checkboxes to be brailled. Update our model to reflect this,
then update the "enabledBrailledTextAttributes" preference string.
Arguments:
- cell: the cell that changed.
- path: the path of that cell.
- model: the model that the cell is part of.
"""
thisIter = model.get_iter(path)
model.set(thisIter, IS_BRAILLED, not model[path][IS_BRAILLED])
self._updateTextDictEntry()
def textAttrValueEdited(self, cell, path, new_text, model):
"""The user has edited the value of one of the text attributes.
Update our model to reflect this, then update the
"enabledSpokenTextAttributes" and "enabledBrailledTextAttributes"
preference strings.
Arguments:
- cell: the cell that changed.
- path: the path of that cell.
- new_text: the new text attribute value string.
- model: the model that the cell is part of.
"""
thisIter = model.get_iter(path)
model.set(thisIter, VALUE, new_text)
self._updateTextDictEntry()
def textAttrCursorChanged(self, widget):
"""Set the search column in the text attribute tree view
depending upon which column the user currently has the cursor in.
"""
[path, focusColumn] = self.getTextAttributesView.get_cursor()
if focusColumn:
noColumns = len(self.getTextAttributesView.get_columns())
for i in range(0, noColumns):
col = self.getTextAttributesView.get_column(i)
if focusColumn == col:
self.getTextAttributesView.set_search_column(i)
break
def _createTextAttributesTreeView(self):
"""Create the text attributes tree view. The view is the
textAttributesTreeView GtkTreeView widget. The view will consist
of a list containing three columns:
IS_SPOKEN - a checkbox whose state indicates whether this text
attribute will be spoken or not.
NAME - the text attribute name.
VALUE - if set, (and this attributes is enabled for speaking),
then this attribute will be spoken unless it equals
this value.
"""
self.getTextAttributesView = self.get_widget("textAttributesTreeView")
if self.getTextAttributesView.get_columns():
for column in self.getTextAttributesView.get_columns():
self.getTextAttributesView.remove_column(column)
model = Gtk.ListStore(GObject.TYPE_STRING,
GObject.TYPE_BOOLEAN,
GObject.TYPE_BOOLEAN,
GObject.TYPE_STRING)
# Initially setup the list store model based on the values of all
# the known text attributes.
#
[allAttrList, allAttrDict] = self.script.utilities.stringToKeysAndDict(
_settingsManager.getSetting('allTextAttributes'))
for i in range(0, len(allAttrList)):
thisIter = model.append()
localizedKey = text_attribute_names.getTextAttributeName(
allAttrList[i], self.script)
localizedValue = text_attribute_names.getTextAttributeName(
allAttrDict[allAttrList[i]], self.script)
model.set_value(thisIter, NAME, localizedKey)
model.set_value(thisIter, IS_SPOKEN, False)
model.set_value(thisIter, IS_BRAILLED, False)
model.set_value(thisIter, VALUE, localizedValue)
self.getTextAttributesView.set_model(model)
# Attribute Name column (NAME).
column = Gtk.TreeViewColumn(guilabels.TEXT_ATTRIBUTE_NAME)
column.set_min_width(250)
column.set_resizable(True)
renderer = Gtk.CellRendererText()
column.pack_end(renderer, True)
column.add_attribute(renderer, 'text', NAME)
self.getTextAttributesView.insert_column(column, 0)
# Attribute Speak column (IS_SPOKEN).
speakAttrColumnLabel = guilabels.PRESENTATION_SPEAK
column = Gtk.TreeViewColumn(speakAttrColumnLabel)
renderer = Gtk.CellRendererToggle()
column.pack_start(renderer, False)
column.add_attribute(renderer, 'active', IS_SPOKEN)
renderer.connect("toggled",
self.textAttributeSpokenToggled,
model)
self.getTextAttributesView.insert_column(column, 1)
column.clicked()
# Attribute Mark in Braille column (IS_BRAILLED).
markAttrColumnLabel = guilabels.PRESENTATION_MARK_IN_BRAILLE
column = Gtk.TreeViewColumn(markAttrColumnLabel)
renderer = Gtk.CellRendererToggle()
column.pack_start(renderer, False)
column.add_attribute(renderer, 'active', IS_BRAILLED)
renderer.connect("toggled",
self.textAttributeBrailledToggled,
model)
self.getTextAttributesView.insert_column(column, 2)
column.clicked()
# Attribute Value column (VALUE)
column = Gtk.TreeViewColumn(guilabels.PRESENTATION_PRESENT_UNLESS)
renderer = Gtk.CellRendererText()
renderer.set_property('editable', True)
column.pack_end(renderer, True)
column.add_attribute(renderer, 'text', VALUE)
renderer.connect("edited", self.textAttrValueEdited, model)
self.getTextAttributesView.insert_column(column, 4)
# Check all the enabled (spoken) text attributes.
#
self._setSpokenTextAttributes(
self.getTextAttributesView,
_settingsManager.getSetting('enabledSpokenTextAttributes'),
True, True)
# Check all the enabled (brailled) text attributes.
#
self._setBrailledTextAttributes(
self.getTextAttributesView,
_settingsManager.getSetting('enabledBrailledTextAttributes'),
True)
# Connect a handler for when the user changes columns within the
# view, so that we can adjust the search column for item lookups.
#
self.getTextAttributesView.connect("cursor_changed",
self.textAttrCursorChanged)
def pronActualValueEdited(self, cell, path, new_text, model):
"""The user has edited the value of one of the actual strings in
the pronunciation dictionary. Update our model to reflect this.
Arguments:
- cell: the cell that changed.
- path: the path of that cell.
- new_text: the new pronunciation dictionary actual string.
- model: the model that the cell is part of.
"""
thisIter = model.get_iter(path)
model.set(thisIter, ACTUAL, new_text)
def pronReplacementValueEdited(self, cell, path, new_text, model):
"""The user has edited the value of one of the replacement strings
in the pronunciation dictionary. Update our model to reflect this.
Arguments:
- cell: the cell that changed.
- path: the path of that cell.
- new_text: the new pronunciation dictionary replacement string.
- model: the model that the cell is part of.
"""
thisIter = model.get_iter(path)
model.set(thisIter, REPLACEMENT, new_text)
def pronunciationFocusChange(self, widget, event, isFocused):
"""Callback for the pronunciation tree's focus-{in,out}-event signal."""
_settingsManager.setSetting('usePronunciationDictionary', not isFocused)
def pronunciationCursorChanged(self, widget):
"""Set the search column in the pronunciation dictionary tree view
depending upon which column the user currently has the cursor in.
"""
[path, focusColumn] = self.pronunciationView.get_cursor()
if focusColumn:
noColumns = len(self.pronunciationView.get_columns())
for i in range(0, noColumns):
col = self.pronunciationView.get_column(i)
if focusColumn == col:
self.pronunciationView.set_search_column(i)
break
def _createPronunciationTreeView(self):
"""Create the pronunciation dictionary tree view. The view is the
pronunciationTreeView GtkTreeView widget. The view will consist
of a list containing two columns:
ACTUAL - the actual text string (word).
REPLACEMENT - the string that is used to pronounce that word.
"""
self.pronunciationView = self.get_widget("pronunciationTreeView")
if self.pronunciationView.get_columns():
for column in self.pronunciationView.get_columns():
self.pronunciationView.remove_column(column)
model = Gtk.ListStore(GObject.TYPE_STRING,
GObject.TYPE_STRING)
# Initially setup the list store model based on the values of all
# existing entries in the pronunciation dictionary -- unless it's
# the default script.
#
if not self.script.app:
_profile = self.prefsDict.get('activeProfile')[1]
pronDict = _settingsManager.getPronunciations(_profile)
else:
pronDict = pronunciation_dict.pronunciation_dict
for pronKey in sorted(pronDict.keys()):
thisIter = model.append()
try:
actual, replacement = pronDict[pronKey]
except:
# Try to do something sensible for the previous format of
# pronunciation dictionary entries. See bug #464754 for
# more details.
#
actual = pronKey
replacement = pronDict[pronKey]
model.set(thisIter,
ACTUAL, actual,
REPLACEMENT, replacement)
self.pronunciationView.set_model(model)
# Pronunciation Dictionary actual string (word) column (ACTUAL).
column = Gtk.TreeViewColumn(guilabels.DICTIONARY_ACTUAL_STRING)
column.set_min_width(250)
column.set_resizable(True)
renderer = Gtk.CellRendererText()
renderer.set_property('editable', True)
column.pack_end(renderer, True)
column.add_attribute(renderer, 'text', ACTUAL)
renderer.connect("edited", self.pronActualValueEdited, model)
self.pronunciationView.insert_column(column, 0)
# Pronunciation Dictionary replacement string column (REPLACEMENT)
column = Gtk.TreeViewColumn(guilabels.DICTIONARY_REPLACEMENT_STRING)
renderer = Gtk.CellRendererText()
renderer.set_property('editable', True)
column.pack_end(renderer, True)
column.add_attribute(renderer, 'text', REPLACEMENT)
renderer.connect("edited", self.pronReplacementValueEdited, model)
self.pronunciationView.insert_column(column, 1)
self.pronunciationModel = model
# Connect a handler for when the user changes columns within the
# view, so that we can adjust the search column for item lookups.
#
self.pronunciationView.connect("cursor_changed",
self.pronunciationCursorChanged)
self.pronunciationView.connect(
"focus_in_event", self.pronunciationFocusChange, True)
self.pronunciationView.connect(
"focus_out_event", self.pronunciationFocusChange, False)
def _initGUIState(self):
"""Adjust the settings of the various components on the
configuration GUI depending upon the users preferences.
"""
prefs = self.prefsDict
# Speech pane.
#
enable = prefs["enableSpeech"]
self.get_widget("speechSupportCheckButton").set_active(enable)
self.get_widget("speechOptionsGrid").set_sensitive(enable)
enable = prefs["onlySpeakDisplayedText"]
self.get_widget("onlySpeakDisplayedTextCheckButton").set_active(enable)
self.get_widget("contextOptionsGrid").set_sensitive(not enable)
if prefs["verbalizePunctuationStyle"] == \
settings.PUNCTUATION_STYLE_NONE:
self.get_widget("noneButton").set_active(True)
elif prefs["verbalizePunctuationStyle"] == \
settings.PUNCTUATION_STYLE_SOME:
self.get_widget("someButton").set_active(True)
elif prefs["verbalizePunctuationStyle"] == \
settings.PUNCTUATION_STYLE_MOST:
self.get_widget("mostButton").set_active(True)
else:
self.get_widget("allButton").set_active(True)
if prefs["speechVerbosityLevel"] == settings.VERBOSITY_LEVEL_BRIEF:
self.get_widget("speechBriefButton").set_active(True)
else:
self.get_widget("speechVerboseButton").set_active(True)
self.get_widget("onlySpeakDisplayedTextCheckButton").set_active(
prefs["onlySpeakDisplayedText"])
self.get_widget("enableSpeechIndentationCheckButton").set_active(\
prefs["enableSpeechIndentation"])
self.get_widget("speakBlankLinesCheckButton").set_active(\
prefs["speakBlankLines"])
self.get_widget("speakMultiCaseStringsAsWordsCheckButton").set_active(\
prefs["speakMultiCaseStringsAsWords"])
self.get_widget("speakNumbersAsDigitsCheckButton").set_active(
prefs.get("speakNumbersAsDigits", settings.speakNumbersAsDigits))
self.get_widget("enableTutorialMessagesCheckButton").set_active(\
prefs["enableTutorialMessages"])
self.get_widget("enablePauseBreaksCheckButton").set_active(\
prefs["enablePauseBreaks"])
self.get_widget("enablePositionSpeakingCheckButton").set_active(\
prefs["enablePositionSpeaking"])
self.get_widget("enableMnemonicSpeakingCheckButton").set_active(\
prefs["enableMnemonicSpeaking"])
self.get_widget("speakMisspelledIndicatorCheckButton").set_active(
prefs.get("speakMisspelledIndicator", settings.speakMisspelledIndicator))
self.get_widget("speakDescriptionCheckButton").set_active(
prefs.get("speakDescription", settings.speakDescription))
self.get_widget("speakContextBlockquoteCheckButton").set_active(
prefs.get("speakContextBlockquote", settings.speakContextList))
self.get_widget("speakContextLandmarkCheckButton").set_active(
prefs.get("speakContextLandmark", settings.speakContextLandmark))
self.get_widget("speakContextNonLandmarkFormCheckButton").set_active(
prefs.get("speakContextNonLandmarkForm", settings.speakContextNonLandmarkForm))
self.get_widget("speakContextListCheckButton").set_active(
prefs.get("speakContextList", settings.speakContextList))
self.get_widget("speakContextPanelCheckButton").set_active(
prefs.get("speakContextPanel", settings.speakContextPanel))
self.get_widget("speakContextTableCheckButton").set_active(
prefs.get("speakContextTable", settings.speakContextTable))
enable = prefs.get("messagesAreDetailed", settings.messagesAreDetailed)
self.get_widget("messagesAreDetailedCheckButton").set_active(enable)
enable = prefs.get("useColorNames", settings.useColorNames)
self.get_widget("useColorNamesCheckButton").set_active(enable)
enable = prefs.get("readFullRowInGUITable", settings.readFullRowInGUITable)
self.get_widget("readFullRowInGUITableCheckButton").set_active(enable)
enable = prefs.get("readFullRowInDocumentTable", settings.readFullRowInDocumentTable)
self.get_widget("readFullRowInDocumentTableCheckButton").set_active(enable)
enable = prefs.get("readFullRowInSpreadSheet", settings.readFullRowInSpreadSheet)
self.get_widget("readFullRowInSpreadSheetCheckButton").set_active(enable)
style = prefs.get("capitalizationStyle", settings.capitalizationStyle)
combobox = self.get_widget("capitalizationStyle")
options = [guilabels.CAPITALIZATION_STYLE_NONE,
guilabels.CAPITALIZATION_STYLE_ICON,
guilabels.CAPITALIZATION_STYLE_SPELL]
self.populateComboBox(combobox, options)
if style == settings.CAPITALIZATION_STYLE_ICON:
value = guilabels.CAPITALIZATION_STYLE_ICON
elif style == settings.CAPITALIZATION_STYLE_SPELL:
value = guilabels.CAPITALIZATION_STYLE_SPELL
else:
value = guilabels.CAPITALIZATION_STYLE_NONE
combobox.set_active(options.index(value))
combobox2 = self.get_widget("dateFormatCombo")
sdtime = time.strftime
ltime = time.localtime
self.populateComboBox(combobox2,
[sdtime(messages.DATE_FORMAT_LOCALE, ltime()),
sdtime(messages.DATE_FORMAT_NUMBERS_DM, ltime()),
sdtime(messages.DATE_FORMAT_NUMBERS_MD, ltime()),
sdtime(messages.DATE_FORMAT_NUMBERS_DMY, ltime()),
sdtime(messages.DATE_FORMAT_NUMBERS_MDY, ltime()),
sdtime(messages.DATE_FORMAT_NUMBERS_YMD, ltime()),
sdtime(messages.DATE_FORMAT_FULL_DM, ltime()),
sdtime(messages.DATE_FORMAT_FULL_MD, ltime()),
sdtime(messages.DATE_FORMAT_FULL_DMY, ltime()),
sdtime(messages.DATE_FORMAT_FULL_MDY, ltime()),
sdtime(messages.DATE_FORMAT_FULL_YMD, ltime()),
sdtime(messages.DATE_FORMAT_ABBREVIATED_DM, ltime()),
sdtime(messages.DATE_FORMAT_ABBREVIATED_MD, ltime()),
sdtime(messages.DATE_FORMAT_ABBREVIATED_DMY, ltime()),
sdtime(messages.DATE_FORMAT_ABBREVIATED_MDY, ltime()),
sdtime(messages.DATE_FORMAT_ABBREVIATED_YMD, ltime())
])
indexdate = DATE_FORMAT_LOCALE
dateFormat = self.prefsDict["presentDateFormat"]
if dateFormat == messages.DATE_FORMAT_LOCALE:
indexdate = DATE_FORMAT_LOCALE
elif dateFormat == messages.DATE_FORMAT_NUMBERS_DM:
indexdate = DATE_FORMAT_NUMBERS_DM
elif dateFormat == messages.DATE_FORMAT_NUMBERS_MD:
indexdate = DATE_FORMAT_NUMBERS_MD
elif dateFormat == messages.DATE_FORMAT_NUMBERS_DMY:
indexdate = DATE_FORMAT_NUMBERS_DMY
elif dateFormat == messages.DATE_FORMAT_NUMBERS_MDY:
indexdate = DATE_FORMAT_NUMBERS_MDY
elif dateFormat == messages.DATE_FORMAT_NUMBERS_YMD:
indexdate = DATE_FORMAT_NUMBERS_YMD
elif dateFormat == messages.DATE_FORMAT_FULL_DM:
indexdate = DATE_FORMAT_FULL_DM
elif dateFormat == messages.DATE_FORMAT_FULL_MD:
indexdate = DATE_FORMAT_FULL_MD
elif dateFormat == messages.DATE_FORMAT_FULL_DMY:
indexdate = DATE_FORMAT_FULL_DMY
elif dateFormat == messages.DATE_FORMAT_FULL_MDY:
indexdate = DATE_FORMAT_FULL_MDY
elif dateFormat == messages.DATE_FORMAT_FULL_YMD:
indexdate = DATE_FORMAT_FULL_YMD
elif dateFormat == messages.DATE_FORMAT_ABBREVIATED_DM:
indexdate = DATE_FORMAT_ABBREVIATED_DM
elif dateFormat == messages.DATE_FORMAT_ABBREVIATED_MD:
indexdate = DATE_FORMAT_ABBREVIATED_MD
elif dateFormat == messages.DATE_FORMAT_ABBREVIATED_DMY:
indexdate = DATE_FORMAT_ABBREVIATED_DMY
elif dateFormat == messages.DATE_FORMAT_ABBREVIATED_MDY:
indexdate = DATE_FORMAT_ABBREVIATED_MDY
elif dateFormat == messages.DATE_FORMAT_ABBREVIATED_YMD:
indexdate = DATE_FORMAT_ABBREVIATED_YMD
combobox2.set_active (indexdate)
combobox3 = self.get_widget("timeFormatCombo")
self.populateComboBox(combobox3,
[sdtime(messages.TIME_FORMAT_LOCALE, ltime()),
sdtime(messages.TIME_FORMAT_12_HM, ltime()),
sdtime(messages.TIME_FORMAT_12_HMS, ltime()),
sdtime(messages.TIME_FORMAT_24_HMS, ltime()),
sdtime(messages.TIME_FORMAT_24_HMS_WITH_WORDS, ltime()),
sdtime(messages.TIME_FORMAT_24_HM, ltime()),
sdtime(messages.TIME_FORMAT_24_HM_WITH_WORDS, ltime())])
indextime = TIME_FORMAT_LOCALE
timeFormat = self.prefsDict["presentTimeFormat"]
if timeFormat == messages.TIME_FORMAT_LOCALE:
indextime = TIME_FORMAT_LOCALE
elif timeFormat == messages.TIME_FORMAT_12_HM:
indextime = TIME_FORMAT_12_HM
elif timeFormat == messages.TIME_FORMAT_12_HMS:
indextime = TIME_FORMAT_12_HMS
elif timeFormat == messages.TIME_FORMAT_24_HMS:
indextime = TIME_FORMAT_24_HMS
elif timeFormat == messages.TIME_FORMAT_24_HMS_WITH_WORDS:
indextime = TIME_FORMAT_24_HMS_WITH_WORDS
elif timeFormat == messages.TIME_FORMAT_24_HM:
indextime = TIME_FORMAT_24_HM
elif timeFormat == messages.TIME_FORMAT_24_HM_WITH_WORDS:
indextime = TIME_FORMAT_24_HM_WITH_WORDS
combobox3.set_active (indextime)
self.get_widget("speakProgressBarUpdatesCheckButton").set_active(
prefs.get("speakProgressBarUpdates", settings.speakProgressBarUpdates))
self.get_widget("brailleProgressBarUpdatesCheckButton").set_active(
prefs.get("brailleProgressBarUpdates", settings.brailleProgressBarUpdates))
self.get_widget("beepProgressBarUpdatesCheckButton").set_active(
prefs.get("beepProgressBarUpdates", settings.beepProgressBarUpdates))
interval = prefs["progressBarUpdateInterval"]
self.get_widget("progressBarUpdateIntervalSpinButton").set_value(interval)
comboBox = self.get_widget("progressBarVerbosity")
levels = [guilabels.PROGRESS_BAR_ALL,
guilabels.PROGRESS_BAR_APPLICATION,
guilabels.PROGRESS_BAR_WINDOW]
self.populateComboBox(comboBox, levels)
comboBox.set_active(prefs["progressBarVerbosity"])
enable = prefs["enableMouseReview"]
self.get_widget("enableMouseReviewCheckButton").set_active(enable)
# Braille pane.
#
self.get_widget("enableBrailleCheckButton").set_active( \
prefs["enableBraille"])
state = prefs["brailleRolenameStyle"] == \
settings.BRAILLE_ROLENAME_STYLE_SHORT
self.get_widget("abbrevRolenames").set_active(state)
self.get_widget("disableBrailleEOLCheckButton").set_active(
prefs["disableBrailleEOL"])
if louis is None:
self.get_widget( \
"contractedBrailleCheckButton").set_sensitive(False)
else:
self.get_widget("contractedBrailleCheckButton").set_active( \
prefs["enableContractedBraille"])
# Set up contraction table combo box and set it to the
# currently used one.
#
tablesCombo = self.get_widget("contractionTableCombo")
tableDict = braille.listTables()
selectedTableIter = None
selectedTable = prefs["brailleContractionTable"] or \
braille.getDefaultTable()
if tableDict:
tablesModel = Gtk.ListStore(str, str)
names = sorted(tableDict.keys())
for name in names:
fname = tableDict[name]
it = tablesModel.append([name, fname])
if os.path.join(braille.tablesdir, fname) == \
selectedTable:
selectedTableIter = it
cell = self.planeCellRendererText
tablesCombo.clear()
tablesCombo.pack_start(cell, True)
tablesCombo.add_attribute(cell, 'text', 0)
tablesCombo.set_model(tablesModel)
if selectedTableIter:
tablesCombo.set_active_iter(selectedTableIter)
else:
tablesCombo.set_active(0)
else:
tablesCombo.set_sensitive(False)
if prefs["brailleVerbosityLevel"] == settings.VERBOSITY_LEVEL_BRIEF:
self.get_widget("brailleBriefButton").set_active(True)
else:
self.get_widget("brailleVerboseButton").set_active(True)
self.get_widget("enableBrailleWordWrapCheckButton").set_active(
prefs.get("enableBrailleWordWrap", settings.enableBrailleWordWrap))
selectionIndicator = prefs["brailleSelectorIndicator"]
if selectionIndicator == settings.BRAILLE_UNDERLINE_7:
self.get_widget("brailleSelection7Button").set_active(True)
elif selectionIndicator == settings.BRAILLE_UNDERLINE_8:
self.get_widget("brailleSelection8Button").set_active(True)
elif selectionIndicator == settings.BRAILLE_UNDERLINE_BOTH:
self.get_widget("brailleSelectionBothButton").set_active(True)
else:
self.get_widget("brailleSelectionNoneButton").set_active(True)
linkIndicator = prefs["brailleLinkIndicator"]
if linkIndicator == settings.BRAILLE_UNDERLINE_7:
self.get_widget("brailleLink7Button").set_active(True)
elif linkIndicator == settings.BRAILLE_UNDERLINE_8:
self.get_widget("brailleLink8Button").set_active(True)
elif linkIndicator == settings.BRAILLE_UNDERLINE_BOTH:
self.get_widget("brailleLinkBothButton").set_active(True)
else:
self.get_widget("brailleLinkNoneButton").set_active(True)
enable = prefs.get("enableFlashMessages", settings.enableFlashMessages)
self.get_widget("enableFlashMessagesCheckButton").set_active(enable)
enable = prefs.get("flashIsPersistent", settings.flashIsPersistent)
self.get_widget("flashIsPersistentCheckButton").set_active(enable)
enable = prefs.get("flashIsDetailed", settings.flashIsDetailed)
self.get_widget("flashIsDetailedCheckButton").set_active(enable)
duration = prefs["brailleFlashTime"]
self.get_widget("brailleFlashTimeSpinButton").set_value(duration / 1000)
# Key Echo pane.
#
self.get_widget("keyEchoCheckButton").set_active( \
prefs["enableKeyEcho"])
self.get_widget("enableAlphabeticKeysCheckButton").set_active(
prefs.get("enableAlphabeticKeys", settings.enableAlphabeticKeys))
self.get_widget("enableNumericKeysCheckButton").set_active(
prefs.get("enableNumericKeys", settings.enableNumericKeys))
self.get_widget("enablePunctuationKeysCheckButton").set_active(
prefs.get("enablePunctuationKeys", settings.enablePunctuationKeys))
self.get_widget("enableSpaceCheckButton").set_active(
prefs.get("enableSpace", settings.enableSpace))
self.get_widget("enableModifierKeysCheckButton").set_active( \
prefs["enableModifierKeys"])
self.get_widget("enableFunctionKeysCheckButton").set_active( \
prefs["enableFunctionKeys"])
self.get_widget("enableActionKeysCheckButton").set_active( \
prefs["enableActionKeys"])
self.get_widget("enableNavigationKeysCheckButton").set_active( \
prefs["enableNavigationKeys"])
self.get_widget("enableDiacriticalKeysCheckButton").set_active( \
prefs["enableDiacriticalKeys"])
self.get_widget("enableEchoByCharacterCheckButton").set_active( \
prefs["enableEchoByCharacter"])
self.get_widget("enableEchoByWordCheckButton").set_active( \
prefs["enableEchoByWord"])
self.get_widget("enableEchoBySentenceCheckButton").set_active( \
prefs["enableEchoBySentence"])
# Text attributes pane.
#
self._createTextAttributesTreeView()
brailleIndicator = prefs["textAttributesBrailleIndicator"]
if brailleIndicator == settings.BRAILLE_UNDERLINE_7:
self.get_widget("textBraille7Button").set_active(True)
elif brailleIndicator == settings.BRAILLE_UNDERLINE_8:
self.get_widget("textBraille8Button").set_active(True)
elif brailleIndicator == settings.BRAILLE_UNDERLINE_BOTH:
self.get_widget("textBrailleBothButton").set_active(True)
else:
self.get_widget("textBrailleNoneButton").set_active(True)
# Pronunciation dictionary pane.
#
self._createPronunciationTreeView()
# General pane.
#
self.get_widget("presentToolTipsCheckButton").set_active(
prefs["presentToolTips"])
if prefs["keyboardLayout"] == settings.GENERAL_KEYBOARD_LAYOUT_DESKTOP:
self.get_widget("generalDesktopButton").set_active(True)
else:
self.get_widget("generalLaptopButton").set_active(True)
combobox = self.get_widget("sayAllStyle")
self.populateComboBox(combobox, [guilabels.SAY_ALL_STYLE_LINE,
guilabels.SAY_ALL_STYLE_SENTENCE])
combobox.set_active(prefs["sayAllStyle"])
self.get_widget("rewindAndFastForwardInSayAllCheckButton").set_active(
prefs.get("rewindAndFastForwardInSayAll", settings.rewindAndFastForwardInSayAll))
self.get_widget("structNavInSayAllCheckButton").set_active(
prefs.get("structNavInSayAll", settings.structNavInSayAll))
self.get_widget("sayAllContextBlockquoteCheckButton").set_active(
prefs.get("sayAllContextBlockquote", settings.sayAllContextBlockquote))
self.get_widget("sayAllContextLandmarkCheckButton").set_active(
prefs.get("sayAllContextLandmark", settings.sayAllContextLandmark))
self.get_widget("sayAllContextNonLandmarkFormCheckButton").set_active(
prefs.get("sayAllContextNonLandmarkForm", settings.sayAllContextNonLandmarkForm))
self.get_widget("sayAllContextListCheckButton").set_active(
prefs.get("sayAllContextList", settings.sayAllContextList))
self.get_widget("sayAllContextPanelCheckButton").set_active(
prefs.get("sayAllContextPanel", settings.sayAllContextPanel))
self.get_widget("sayAllContextTableCheckButton").set_active(
prefs.get("sayAllContextTable", settings.sayAllContextTable))
# Orca User Profiles
#
self.profilesCombo = self.get_widget('availableProfilesComboBox1')
self.startingProfileCombo = self.get_widget('availableProfilesComboBox2')
self.profilesComboModel = self.get_widget('model9')
self.__initProfileCombo()
if self.script.app:
self.get_widget('profilesFrame').set_sensitive(False)
def __initProfileCombo(self):
"""Adding available profiles and setting active as the active one"""
availableProfiles = self.__getAvailableProfiles()
self.profilesComboModel.clear()
if not len(availableProfiles):
self.profilesComboModel.append(self._defaultProfile)
else:
for profile in availableProfiles:
self.profilesComboModel.append(profile)
activeProfile = self.prefsDict.get('activeProfile') or self._defaultProfile
startingProfile = self.prefsDict.get('startingProfile') or self._defaultProfile
activeProfileIter = self.getComboBoxIndex(self.profilesCombo,
activeProfile[0])
startingProfileIter = self.getComboBoxIndex(self.startingProfileCombo,
startingProfile[0])
self.profilesCombo.set_active(activeProfileIter)
self.startingProfileCombo.set_active(startingProfileIter)
def __getAvailableProfiles(self):
"""Get available user profiles."""
return _settingsManager.availableProfiles()
def _updateOrcaModifier(self):
combobox = self.get_widget("orcaModifierComboBox")
keystring = ", ".join(self.prefsDict["orcaModifierKeys"])
combobox.set_active(self.getComboBoxIndex(combobox, keystring))
def populateComboBox(self, combobox, items):
"""Populates the combobox with the items provided.
Arguments:
- combobox: the GtkComboBox to populate
- items: the list of strings with which to populate it
"""
model = Gtk.ListStore(str)
for item in items:
model.append([item])
combobox.set_model(model)
def getComboBoxIndex(self, combobox, searchStr, col=0):
""" For each of the entries in the given combo box, look for searchStr.
Return the index of the entry if searchStr is found.
Arguments:
- combobox: the GtkComboBox to search.
- searchStr: the string to search for.
Returns the index of the first entry in combobox with searchStr, or
0 if not found.
"""
model = combobox.get_model()
myiter = model.get_iter_first()
for i in range(0, len(model)):
name = model.get_value(myiter, col)
if name == searchStr:
return i
myiter = model.iter_next(myiter)
return 0
def getComboBoxList(self, combobox):
"""Get the list of values from the active combox
"""
active = combobox.get_active()
model = combobox.get_model()
activeIter = model.get_iter(active)
activeLabel = model.get_value(activeIter, 0)
activeName = model.get_value(activeIter, 1)
return [activeLabel, activeName]
def getKeyBindingsModelDict(self, model, modifiedOnly=True):
modelDict = {}
node = model.get_iter_first()
while node:
child = model.iter_children(node)
while child:
key, modified = model.get(child, HANDLER, MODIF)
if modified or not modifiedOnly:
value = []
value.append(list(model.get(
child, KEY1, MOD_MASK1, MOD_USED1, CLICK_COUNT1)))
modelDict[key] = value
child = model.iter_next(child)
node = model.iter_next(node)
return modelDict
def getModelDict(self, model):
"""Get the list of values from a list[str,str] model
"""
pronunciation_dict.pronunciation_dict = {}
currentIter = model.get_iter_first()
while currentIter is not None:
key, value = model.get(currentIter, ACTUAL, REPLACEMENT)
if key and value:
pronunciation_dict.setPronunciation(key, value)
currentIter = model.iter_next(currentIter)
modelDict = pronunciation_dict.pronunciation_dict
return modelDict
def showGUI(self):
"""Show the Orca configuration GUI window. This assumes that
the GUI has already been created.
"""
orcaSetupWindow = self.get_widget("orcaSetupWindow")
accelGroup = Gtk.AccelGroup()
orcaSetupWindow.add_accel_group(accelGroup)
helpButton = self.get_widget("helpButton")
(keyVal, modifierMask) = Gtk.accelerator_parse("F1")
helpButton.add_accelerator("clicked",
accelGroup,
keyVal,
modifierMask,
0)
try:
ts = orca_state.lastInputEvent.timestamp
except:
ts = 0
if ts == 0:
ts = Gtk.get_current_event_time()
orcaSetupWindow.present_with_time(ts)
# We always want to re-order the text attributes page so that enabled
# items are consistently at the top.
#
self._setSpokenTextAttributes(
self.getTextAttributesView,
_settingsManager.getSetting('enabledSpokenTextAttributes'),
True, True)
if self.script.app:
title = guilabels.PREFERENCES_APPLICATION_TITLE % self.script.app.name
orcaSetupWindow.set_title(title)
orcaSetupWindow.show()
def _initComboBox(self, combobox):
"""Initialize the given combo box to take a list of int/str pairs.
Arguments:
- combobox: the GtkComboBox to initialize.
"""
cell = Gtk.CellRendererText()
combobox.pack_start(cell, True)
# We only want to display one column; not two.
#
try:
columnToDisplay = combobox.get_cells()[0]
combobox.add_attribute(columnToDisplay, 'text', 1)
except:
combobox.add_attribute(cell, 'text', 1)
model = Gtk.ListStore(int, str)
combobox.set_model(model)
# Force the display comboboxes to be left aligned.
#
if isinstance(combobox, Gtk.ComboBoxText):
size = combobox.size_request()
cell.set_fixed_size(size[0] - 29, -1)
return model
def _setKeyEchoItems(self):
"""[In]sensitize the checkboxes for the various types of key echo,
depending upon whether the value of the key echo check button is set.
"""
enable = self.get_widget("keyEchoCheckButton").get_active()
self.get_widget("enableAlphabeticKeysCheckButton").set_sensitive(enable)
self.get_widget("enableNumericKeysCheckButton").set_sensitive(enable)
self.get_widget("enablePunctuationKeysCheckButton").set_sensitive(enable)
self.get_widget("enableSpaceCheckButton").set_sensitive(enable)
self.get_widget("enableModifierKeysCheckButton").set_sensitive(enable)
self.get_widget("enableFunctionKeysCheckButton").set_sensitive(enable)
self.get_widget("enableActionKeysCheckButton").set_sensitive(enable)
self.get_widget("enableNavigationKeysCheckButton").set_sensitive(enable)
self.get_widget("enableDiacriticalKeysCheckButton").set_sensitive( \
enable)
<|fim▁hole|>
Arguments:
- text: the text to present
- interrupt: if True, interrupt any speech currently being spoken
"""
self.script.speakMessage(text, interrupt=interrupt)
try:
self.script.displayBrailleMessage(text, flashTime=-1)
except:
pass
def _createNode(self, appName):
"""Create a new root node in the TreeStore model with the name of the
application.
Arguments:
- appName: the name of the TreeStore Node (the same of the application)
"""
model = self.keyBindingsModel
myiter = model.append(None)
model.set_value(myiter, DESCRIP, appName)
model.set_value(myiter, MODIF, False)
return myiter
def _getIterOf(self, appName):
"""Returns the Gtk.TreeIter of the TreeStore model
that matches the application name passed as argument
Arguments:
- appName: a string with the name of the application of the node wanted
it's the same that the field DESCRIP of the model treeStore
"""
model = self.keyBindingsModel
for row in model:
if ((model.iter_depth(row.iter) == 0) \
and (row[DESCRIP] == appName)):
return row.iter
return None
def _clickCountToString(self, clickCount):
"""Given a numeric clickCount, returns a string for inclusion
in the list of keybindings.
Argument:
- clickCount: the number of clicks associated with the keybinding.
"""
clickCountString = ""
if clickCount == 2:
clickCountString = " (%s)" % guilabels.CLICK_COUNT_DOUBLE
elif clickCount == 3:
clickCountString = " (%s)" % guilabels.CLICK_COUNT_TRIPLE
return clickCountString
def _insertRow(self, handl, kb, parent=None, modif=False):
"""Appends a new row with the new keybinding data to the treeview
Arguments:
- handl: the name of the handler associated to the keyBinding
- kb: the new keybinding.
- parent: the parent node of the treeview, where to append the kb
- modif: whether to check the modified field or not.
Returns a Gtk.TreeIter pointing at the new row.
"""
model = self.keyBindingsModel
if parent is None:
parent = self._getIterOf(guilabels.KB_GROUP_DEFAULT)
if parent is not None:
myiter = model.append(parent)
if not kb.keysymstring:
text = None
else:
clickCount = self._clickCountToString(kb.click_count)
modifierNames = keybindings.getModifierNames(kb.modifiers)
keysymstring = kb.keysymstring
text = keybindings.getModifierNames(kb.modifiers) \
+ keysymstring \
+ clickCount
model.set_value(myiter, HANDLER, handl)
model.set_value(myiter, DESCRIP, kb.handler.description)
model.set_value(myiter, MOD_MASK1, str(kb.modifier_mask))
model.set_value(myiter, MOD_USED1, str(kb.modifiers))
model.set_value(myiter, KEY1, kb.keysymstring)
model.set_value(myiter, CLICK_COUNT1, str(kb.click_count))
if text is not None:
model.set_value(myiter, OLDTEXT1, text)
model.set_value(myiter, TEXT1, text)
model.set_value(myiter, MODIF, modif)
model.set_value(myiter, EDITABLE, True)
return myiter
else:
return None
def _insertRowBraille(self, handl, com, inputEvHand,
parent=None, modif=False):
"""Appends a new row with the new braille binding data to the treeview
Arguments:
- handl: the name of the handler associated to the brailleBinding
- com: the BrlTTY command
- inputEvHand: the inputEventHandler with the new brailleBinding
- parent: the parent node of the treeview, where to append the kb
- modif: whether to check the modified field or not.
Returns a Gtk.TreeIter pointing at the new row.
"""
model = self.keyBindingsModel
if parent is None:
parent = self._getIterOf(guilabels.KB_GROUP_BRAILLE)
if parent is not None:
myiter = model.append(parent)
model.set_value(myiter, HANDLER, handl)
model.set_value(myiter, DESCRIP, inputEvHand.description)
model.set_value(myiter, KEY1, str(com))
model.set_value(myiter, TEXT1, braille.command_name[com])
model.set_value(myiter, MODIF, modif)
model.set_value(myiter, EDITABLE, False)
return myiter
else:
return None
def _markModified(self):
""" Mark as modified the user custom key bindings:
"""
try:
self.script.setupInputEventHandlers()
keyBinds = keybindings.KeyBindings()
keyBinds = _settingsManager.overrideKeyBindings(self.script, keyBinds)
keyBind = keybindings.KeyBinding(None, None, None, None)
treeModel = self.keyBindingsModel
myiter = treeModel.get_iter_first()
while myiter is not None:
iterChild = treeModel.iter_children(myiter)
while iterChild is not None:
descrip = treeModel.get_value(iterChild, DESCRIP)
keyBind.handler = \
input_event.InputEventHandler(None, descrip)
if keyBinds.hasKeyBinding(keyBind,
typeOfSearch="description"):
treeModel.set_value(iterChild, MODIF, True)
iterChild = treeModel.iter_next(iterChild)
myiter = treeModel.iter_next(myiter)
except:
debug.printException(debug.LEVEL_SEVERE)
def _populateKeyBindings(self, clearModel=True):
"""Fills the TreeView with the list of Orca keybindings
Arguments:
- clearModel: if True, initially clear out the key bindings model.
"""
self.keyBindView.set_model(None)
self.keyBindView.set_headers_visible(False)
self.keyBindView.hide()
if clearModel:
self.keyBindingsModel.clear()
self.kbindings = None
try:
appName = self.script.app.name
except:
appName = ""
iterApp = self._createNode(appName)
iterOrca = self._createNode(guilabels.KB_GROUP_DEFAULT)
iterUnbound = self._createNode(guilabels.KB_GROUP_UNBOUND)
if not self.kbindings:
self.kbindings = keybindings.KeyBindings()
self.script.setupInputEventHandlers()
allKeyBindings = self.script.getKeyBindings()
defKeyBindings = self.script.getDefaultKeyBindings()
for kb in allKeyBindings.keyBindings:
if not self.kbindings.hasKeyBinding(kb, "strict"):
handl = self.script.getInputEventHandlerKey(kb.handler)
if not defKeyBindings.hasKeyBinding(kb, "description"):
self._insertRow(handl, kb, iterApp)
elif kb.keysymstring:
self._insertRow(handl, kb, iterOrca)
else:
self._insertRow(handl, kb, iterUnbound)
self.kbindings.add(kb)
if not self.keyBindingsModel.iter_has_child(iterApp):
self.keyBindingsModel.remove(iterApp)
if not self.keyBindingsModel.iter_has_child(iterUnbound):
self.keyBindingsModel.remove(iterUnbound)
self._updateOrcaModifier()
self._markModified()
iterBB = self._createNode(guilabels.KB_GROUP_BRAILLE)
self.bbindings = self.script.getBrailleBindings()
for com, inputEvHand in self.bbindings.items():
handl = self.script.getInputEventHandlerKey(inputEvHand)
self._insertRowBraille(handl, com, inputEvHand, iterBB)
self.keyBindView.set_model(self.keyBindingsModel)
self.keyBindView.set_headers_visible(True)
self.keyBindView.expand_all()
self.keyBindingsModel.set_sort_column_id(OLDTEXT1, Gtk.SortType.ASCENDING)
self.keyBindView.show()
# Keep track of new/unbound keybindings that have yet to be applied.
#
self.pendingKeyBindings = {}
def _cleanupSpeechServers(self):
"""Remove unwanted factories and drivers for the current active
factory, when the user dismisses the Orca Preferences dialog."""
for workingFactory in self.workingFactories:
if not (workingFactory == self.speechSystemsChoice):
workingFactory.SpeechServer.shutdownActiveServers()
else:
servers = workingFactory.SpeechServer.getSpeechServers()
for server in servers:
if not (server == self.speechServersChoice):
server.shutdown()
def speechSupportChecked(self, widget):
"""Signal handler for the "toggled" signal for the
speechSupportCheckButton GtkCheckButton widget. The user has
[un]checked the 'Enable Speech' checkbox. Set the 'enableSpeech'
preference to the new value. Set the rest of the speech pane items
[in]sensensitive depending upon whether this checkbox is checked.
Arguments:
- widget: the component that generated the signal.
"""
enable = widget.get_active()
self.prefsDict["enableSpeech"] = enable
self.get_widget("speechOptionsGrid").set_sensitive(enable)
def onlySpeakDisplayedTextToggled(self, widget):
"""Signal handler for the "toggled" signal for the GtkCheckButton
onlySpeakDisplayedText. In addition to updating the preferences,
set the sensitivity of the contextOptionsGrid.
Arguments:
- widget: the component that generated the signal.
"""
enable = widget.get_active()
self.prefsDict["onlySpeakDisplayedText"] = enable
self.get_widget("contextOptionsGrid").set_sensitive(not enable)
def speechSystemsChanged(self, widget):
"""Signal handler for the "changed" signal for the speechSystems
GtkComboBox widget. The user has selected a different speech
system. Clear the existing list of speech servers, and setup
a new list of speech servers based on the new choice. Setup a
new list of voices for the first speech server in the list.
Arguments:
- widget: the component that generated the signal.
"""
if self.initializingSpeech:
return
selectedIndex = widget.get_active()
self.speechSystemsChoice = self.speechSystemsChoices[selectedIndex]
self._setupSpeechServers()
def speechServersChanged(self, widget):
"""Signal handler for the "changed" signal for the speechServers
GtkComboBox widget. The user has selected a different speech
server. Clear the existing list of voices, and setup a new
list of voices based on the new choice.
Arguments:
- widget: the component that generated the signal.
"""
if self.initializingSpeech:
return
selectedIndex = widget.get_active()
self.speechServersChoice = self.speechServersChoices[selectedIndex]
# Whenever the speech servers change, we need to make sure we
# clear whatever family was in use by the current voice types.
# Otherwise, we can end up with family names from one server
# bleeding over (e.g., "Paul" from Fonix ends up getting in
# the "Default" voice type after we switch to eSpeak).
#
try:
del self.defaultVoice[acss.ACSS.FAMILY]
del self.uppercaseVoice[acss.ACSS.FAMILY]
del self.hyperlinkVoice[acss.ACSS.FAMILY]
del self.systemVoice[acss.ACSS.FAMILY]
except:
pass
self._setupVoices()
def speechLanguagesChanged(self, widget):
"""Signal handler for the "value_changed" signal for the languages
GtkComboBox widget. The user has selected a different voice
language. Save the new voice language name based on the new choice.
Arguments:
- widget: the component that generated the signal.
"""
if self.initializingSpeech:
return
selectedIndex = widget.get_active()
try:
self.speechLanguagesChoice = self.speechLanguagesChoices[selectedIndex]
if (self.speechServersChoice, self.speechLanguagesChoice) in \
self.selectedFamilyChoices:
i = self.selectedFamilyChoices[self.speechServersChoice, \
self.speechLanguagesChoice]
family = self.speechFamiliesChoices[i]
name = family[speechserver.VoiceFamily.NAME]
language = family[speechserver.VoiceFamily.LANG]
dialect = family[speechserver.VoiceFamily.DIALECT]
variant = family[speechserver.VoiceFamily.VARIANT]
voiceType = self.get_widget("voiceTypesCombo").get_active()
self._setFamilyNameForVoiceType(voiceType, name, language, dialect, variant)
except:
debug.printException(debug.LEVEL_SEVERE)
# Remember the last family manually selected by the user for the
# current speech server.
#
if not selectedIndex == -1:
self.selectedLanguageChoices[self.speechServersChoice] = selectedIndex
self._setupFamilies()
def speechFamiliesChanged(self, widget):
"""Signal handler for the "value_changed" signal for the families
GtkComboBox widget. The user has selected a different voice
family. Save the new voice family name based on the new choice.
Arguments:
- widget: the component that generated the signal.
"""
if self.initializingSpeech:
return
selectedIndex = widget.get_active()
try:
family = self.speechFamiliesChoices[selectedIndex]
name = family[speechserver.VoiceFamily.NAME]
language = family[speechserver.VoiceFamily.LANG]
dialect = family[speechserver.VoiceFamily.DIALECT]
variant = family[speechserver.VoiceFamily.VARIANT]
voiceType = self.get_widget("voiceTypesCombo").get_active()
self._setFamilyNameForVoiceType(voiceType, name, language, dialect, variant)
except:
debug.printException(debug.LEVEL_SEVERE)
# Remember the last family manually selected by the user for the
# current speech server.
#
if not selectedIndex == -1:
self.selectedFamilyChoices[self.speechServersChoice, \
self.speechLanguagesChoice] = selectedIndex
def voiceTypesChanged(self, widget):
"""Signal handler for the "changed" signal for the voiceTypes
GtkComboBox widget. The user has selected a different voice
type. Setup the new family, rate, pitch and volume component
values based on the new choice.
Arguments:
- widget: the component that generated the signal.
"""
if self.initializingSpeech:
return
voiceType = widget.get_active()
self._setVoiceSettingsForVoiceType(voiceType)
def rateValueChanged(self, widget):
"""Signal handler for the "value_changed" signal for the rateScale
GtkScale widget. The user has changed the current rate value.
Save the new rate value based on the currently selected voice
type.
Arguments:
- widget: the component that generated the signal.
"""
rate = widget.get_value()
voiceType = self.get_widget("voiceTypesCombo").get_active()
self._setRateForVoiceType(voiceType, rate)
voices = _settingsManager.getSetting('voices')
voices[settings.DEFAULT_VOICE][acss.ACSS.RATE] = rate
_settingsManager.setSetting('voices', voices)
def pitchValueChanged(self, widget):
"""Signal handler for the "value_changed" signal for the pitchScale
GtkScale widget. The user has changed the current pitch value.
Save the new pitch value based on the currently selected voice
type.
Arguments:
- widget: the component that generated the signal.
"""
pitch = widget.get_value()
voiceType = self.get_widget("voiceTypesCombo").get_active()
self._setPitchForVoiceType(voiceType, pitch)
voices = _settingsManager.getSetting('voices')
voices[settings.DEFAULT_VOICE][acss.ACSS.AVERAGE_PITCH] = pitch
_settingsManager.setSetting('voices', voices)
def volumeValueChanged(self, widget):
"""Signal handler for the "value_changed" signal for the voiceScale
GtkScale widget. The user has changed the current volume value.
Save the new volume value based on the currently selected voice
type.
Arguments:
- widget: the component that generated the signal.
"""
volume = widget.get_value()
voiceType = self.get_widget("voiceTypesCombo").get_active()
self._setVolumeForVoiceType(voiceType, volume)
voices = _settingsManager.getSetting('voices')
voices[settings.DEFAULT_VOICE][acss.ACSS.GAIN] = volume
_settingsManager.setSetting('voices', voices)
def checkButtonToggled(self, widget):
"""Signal handler for "toggled" signal for basic GtkCheckButton
widgets. The user has altered the state of the checkbox.
Set the preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
# To use this default handler please make sure:
# The name of the setting that will be changed is: settingName
# The id of the widget in the ui should be: settingNameCheckButton
#
settingName = Gtk.Buildable.get_name(widget)
# strip "CheckButton" from the end.
settingName = settingName[:-11]
self.prefsDict[settingName] = widget.get_active()
def keyEchoChecked(self, widget):
"""Signal handler for the "toggled" signal for the
keyEchoCheckbutton GtkCheckButton widget. The user has
[un]checked the 'Enable Key Echo' checkbox. Set the
'enableKeyEcho' preference to the new value. [In]sensitize
the checkboxes for the various types of key echo, depending
upon whether this value is checked or unchecked.
Arguments:
- widget: the component that generated the signal.
"""
self.prefsDict["enableKeyEcho"] = widget.get_active()
self._setKeyEchoItems()
def brailleSelectionChanged(self, widget):
"""Signal handler for the "toggled" signal for the
brailleSelectionNoneButton, brailleSelection7Button,
brailleSelection8Button or brailleSelectionBothButton
GtkRadioButton widgets. The user has toggled the braille
selection indicator value. If this signal was generated
as the result of a radio button getting selected (as
opposed to a radio button losing the selection), set the
'brailleSelectorIndicator' preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
if widget.get_label() == guilabels.BRAILLE_DOT_7:
self.prefsDict["brailleSelectorIndicator"] = \
settings.BRAILLE_UNDERLINE_7
elif widget.get_label() == guilabels.BRAILLE_DOT_8:
self.prefsDict["brailleSelectorIndicator"] = \
settings.BRAILLE_UNDERLINE_8
elif widget.get_label() == guilabels.BRAILLE_DOT_7_8:
self.prefsDict["brailleSelectorIndicator"] = \
settings.BRAILLE_UNDERLINE_BOTH
else:
self.prefsDict["brailleSelectorIndicator"] = \
settings.BRAILLE_UNDERLINE_NONE
def brailleLinkChanged(self, widget):
"""Signal handler for the "toggled" signal for the
brailleLinkNoneButton, brailleLink7Button,
brailleLink8Button or brailleLinkBothButton
GtkRadioButton widgets. The user has toggled the braille
link indicator value. If this signal was generated
as the result of a radio button getting selected (as
opposed to a radio button losing the selection), set the
'brailleLinkIndicator' preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
if widget.get_label() == guilabels.BRAILLE_DOT_7:
self.prefsDict["brailleLinkIndicator"] = \
settings.BRAILLE_UNDERLINE_7
elif widget.get_label() == guilabels.BRAILLE_DOT_8:
self.prefsDict["brailleLinkIndicator"] = \
settings.BRAILLE_UNDERLINE_8
elif widget.get_label() == guilabels.BRAILLE_DOT_7_8:
self.prefsDict["brailleLinkIndicator"] = \
settings.BRAILLE_UNDERLINE_BOTH
else:
self.prefsDict["brailleLinkIndicator"] = \
settings.BRAILLE_UNDERLINE_NONE
def brailleIndicatorChanged(self, widget):
"""Signal handler for the "toggled" signal for the
textBrailleNoneButton, textBraille7Button, textBraille8Button
or textBrailleBothButton GtkRadioButton widgets. The user has
toggled the text attributes braille indicator value. If this signal
was generated as the result of a radio button getting selected
(as opposed to a radio button losing the selection), set the
'textAttributesBrailleIndicator' preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
if widget.get_label() == guilabels.BRAILLE_DOT_7:
self.prefsDict["textAttributesBrailleIndicator"] = \
settings.BRAILLE_UNDERLINE_7
elif widget.get_label() == guilabels.BRAILLE_DOT_8:
self.prefsDict["textAttributesBrailleIndicator"] = \
settings.BRAILLE_UNDERLINE_8
elif widget.get_label() == guilabels.BRAILLE_DOT_7_8:
self.prefsDict["textAttributesBrailleIndicator"] = \
settings.BRAILLE_UNDERLINE_BOTH
else:
self.prefsDict["textAttributesBrailleIndicator"] = \
settings.BRAILLE_UNDERLINE_NONE
def punctuationLevelChanged(self, widget):
"""Signal handler for the "toggled" signal for the noneButton,
someButton or allButton GtkRadioButton widgets. The user has
toggled the speech punctuation level value. If this signal
was generated as the result of a radio button getting selected
(as opposed to a radio button losing the selection), set the
'verbalizePunctuationStyle' preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
if widget.get_label() == guilabels.PUNCTUATION_STYLE_NONE:
self.prefsDict["verbalizePunctuationStyle"] = \
settings.PUNCTUATION_STYLE_NONE
elif widget.get_label() == guilabels.PUNCTUATION_STYLE_SOME:
self.prefsDict["verbalizePunctuationStyle"] = \
settings.PUNCTUATION_STYLE_SOME
elif widget.get_label() == guilabels.PUNCTUATION_STYLE_MOST:
self.prefsDict["verbalizePunctuationStyle"] = \
settings.PUNCTUATION_STYLE_MOST
else:
self.prefsDict["verbalizePunctuationStyle"] = \
settings.PUNCTUATION_STYLE_ALL
def orcaModifierChanged(self, widget):
"""Signal handler for the changed signal for the orcaModifierComboBox
Set the 'orcaModifierKeys' preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
model = widget.get_model()
myIter = widget.get_active_iter()
orcaModifier = model[myIter][0]
self.prefsDict["orcaModifierKeys"] = orcaModifier.split(', ')
def progressBarVerbosityChanged(self, widget):
"""Signal handler for the changed signal for the progressBarVerbosity
GtkComboBox widget. Set the 'progressBarVerbosity' preference to
the new value.
Arguments:
- widget: the component that generated the signal.
"""
model = widget.get_model()
myIter = widget.get_active_iter()
progressBarVerbosity = model[myIter][0]
if progressBarVerbosity == guilabels.PROGRESS_BAR_ALL:
self.prefsDict["progressBarVerbosity"] = \
settings.PROGRESS_BAR_ALL
elif progressBarVerbosity == guilabels.PROGRESS_BAR_WINDOW:
self.prefsDict["progressBarVerbosity"] = \
settings.PROGRESS_BAR_WINDOW
else:
self.prefsDict["progressBarVerbosity"] = \
settings.PROGRESS_BAR_APPLICATION
def capitalizationStyleChanged(self, widget):
model = widget.get_model()
myIter = widget.get_active_iter()
capitalizationStyle = model[myIter][0]
if capitalizationStyle == guilabels.CAPITALIZATION_STYLE_ICON:
self.prefsDict["capitalizationStyle"] = settings.CAPITALIZATION_STYLE_ICON
elif capitalizationStyle == guilabels.CAPITALIZATION_STYLE_SPELL:
self.prefsDict["capitalizationStyle"] = settings.CAPITALIZATION_STYLE_SPELL
else:
self.prefsDict["capitalizationStyle"] = settings.CAPITALIZATION_STYLE_NONE
speech.updateCapitalizationStyle()
def sayAllStyleChanged(self, widget):
"""Signal handler for the "changed" signal for the sayAllStyle
GtkComboBox widget. Set the 'sayAllStyle' preference to the
new value.
Arguments:
- widget: the component that generated the signal.
"""
model = widget.get_model()
myIter = widget.get_active_iter()
sayAllStyle = model[myIter][0]
if sayAllStyle == guilabels.SAY_ALL_STYLE_LINE:
self.prefsDict["sayAllStyle"] = settings.SAYALL_STYLE_LINE
elif sayAllStyle == guilabels.SAY_ALL_STYLE_SENTENCE:
self.prefsDict["sayAllStyle"] = settings.SAYALL_STYLE_SENTENCE
def dateFormatChanged(self, widget):
"""Signal handler for the "changed" signal for the dateFormat
GtkComboBox widget. Set the 'dateFormat' preference to the
new value.
Arguments:
- widget: the component that generated the signal.
"""
dateFormatCombo = widget.get_active()
if dateFormatCombo == DATE_FORMAT_LOCALE:
newFormat = messages.DATE_FORMAT_LOCALE
elif dateFormatCombo == DATE_FORMAT_NUMBERS_DM:
newFormat = messages.DATE_FORMAT_NUMBERS_DM
elif dateFormatCombo == DATE_FORMAT_NUMBERS_MD:
newFormat = messages.DATE_FORMAT_NUMBERS_MD
elif dateFormatCombo == DATE_FORMAT_NUMBERS_DMY:
newFormat = messages.DATE_FORMAT_NUMBERS_DMY
elif dateFormatCombo == DATE_FORMAT_NUMBERS_MDY:
newFormat = messages.DATE_FORMAT_NUMBERS_MDY
elif dateFormatCombo == DATE_FORMAT_NUMBERS_YMD:
newFormat = messages.DATE_FORMAT_NUMBERS_YMD
elif dateFormatCombo == DATE_FORMAT_FULL_DM:
newFormat = messages.DATE_FORMAT_FULL_DM
elif dateFormatCombo == DATE_FORMAT_FULL_MD:
newFormat = messages.DATE_FORMAT_FULL_MD
elif dateFormatCombo == DATE_FORMAT_FULL_DMY:
newFormat = messages.DATE_FORMAT_FULL_DMY
elif dateFormatCombo == DATE_FORMAT_FULL_MDY:
newFormat = messages.DATE_FORMAT_FULL_MDY
elif dateFormatCombo == DATE_FORMAT_FULL_YMD:
newFormat = messages.DATE_FORMAT_FULL_YMD
elif dateFormatCombo == DATE_FORMAT_ABBREVIATED_DM:
newFormat = messages.DATE_FORMAT_ABBREVIATED_DM
elif dateFormatCombo == DATE_FORMAT_ABBREVIATED_MD:
newFormat = messages.DATE_FORMAT_ABBREVIATED_MD
elif dateFormatCombo == DATE_FORMAT_ABBREVIATED_DMY:
newFormat = messages.DATE_FORMAT_ABBREVIATED_DMY
elif dateFormatCombo == DATE_FORMAT_ABBREVIATED_MDY:
newFormat = messages.DATE_FORMAT_ABBREVIATED_MDY
elif dateFormatCombo == DATE_FORMAT_ABBREVIATED_YMD:
newFormat = messages.DATE_FORMAT_ABBREVIATED_YMD
self.prefsDict["presentDateFormat"] = newFormat
def timeFormatChanged(self, widget):
"""Signal handler for the "changed" signal for the timeFormat
GtkComboBox widget. Set the 'timeFormat' preference to the
new value.
Arguments:
- widget: the component that generated the signal.
"""
timeFormatCombo = widget.get_active()
if timeFormatCombo == TIME_FORMAT_LOCALE:
newFormat = messages.TIME_FORMAT_LOCALE
elif timeFormatCombo == TIME_FORMAT_12_HM:
newFormat = messages.TIME_FORMAT_12_HM
elif timeFormatCombo == TIME_FORMAT_12_HMS:
newFormat = messages.TIME_FORMAT_12_HMS
elif timeFormatCombo == TIME_FORMAT_24_HMS:
newFormat = messages.TIME_FORMAT_24_HMS
elif timeFormatCombo == TIME_FORMAT_24_HMS_WITH_WORDS:
newFormat = messages.TIME_FORMAT_24_HMS_WITH_WORDS
elif timeFormatCombo == TIME_FORMAT_24_HM:
newFormat = messages.TIME_FORMAT_24_HM
elif timeFormatCombo == TIME_FORMAT_24_HM_WITH_WORDS:
newFormat = messages.TIME_FORMAT_24_HM_WITH_WORDS
self.prefsDict["presentTimeFormat"] = newFormat
def speechVerbosityChanged(self, widget):
"""Signal handler for the "toggled" signal for the speechBriefButton,
or speechVerboseButton GtkRadioButton widgets. The user has
toggled the speech verbosity level value. If this signal was
generated as the result of a radio button getting selected
(as opposed to a radio button losing the selection), set the
'speechVerbosityLevel' preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
if widget.get_label() == guilabels.VERBOSITY_LEVEL_BRIEF:
self.prefsDict["speechVerbosityLevel"] = \
settings.VERBOSITY_LEVEL_BRIEF
else:
self.prefsDict["speechVerbosityLevel"] = \
settings.VERBOSITY_LEVEL_VERBOSE
def progressBarUpdateIntervalValueChanged(self, widget):
"""Signal handler for the "value_changed" signal for the
progressBarUpdateIntervalSpinButton GtkSpinButton widget.
Arguments:
- widget: the component that generated the signal.
"""
self.prefsDict["progressBarUpdateInterval"] = widget.get_value_as_int()
def brailleFlashTimeValueChanged(self, widget):
self.prefsDict["brailleFlashTime"] = widget.get_value_as_int() * 1000
def abbrevRolenamesChecked(self, widget):
"""Signal handler for the "toggled" signal for the abbrevRolenames
GtkCheckButton widget. The user has [un]checked the 'Abbreviated
Rolenames' checkbox. Set the 'brailleRolenameStyle' preference
to the new value.
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
self.prefsDict["brailleRolenameStyle"] = \
settings.BRAILLE_ROLENAME_STYLE_SHORT
else:
self.prefsDict["brailleRolenameStyle"] = \
settings.BRAILLE_ROLENAME_STYLE_LONG
def brailleVerbosityChanged(self, widget):
"""Signal handler for the "toggled" signal for the brailleBriefButton,
or brailleVerboseButton GtkRadioButton widgets. The user has
toggled the braille verbosity level value. If this signal was
generated as the result of a radio button getting selected
(as opposed to a radio button losing the selection), set the
'brailleVerbosityLevel' preference to the new value.
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
if widget.get_label() == guilabels.VERBOSITY_LEVEL_BRIEF:
self.prefsDict["brailleVerbosityLevel"] = \
settings.VERBOSITY_LEVEL_BRIEF
else:
self.prefsDict["brailleVerbosityLevel"] = \
settings.VERBOSITY_LEVEL_VERBOSE
def keyModifiedToggle(self, cell, path, model, col):
"""When the user changes a checkbox field (boolean field)"""
model[path][col] = not model[path][col]
return
def editingKey(self, cell, editable, path, treeModel):
"""Starts user input of a Key for a selected key binding"""
self._presentMessage(messages.KB_ENTER_NEW_KEY)
orca_state.capturingKeys = True
editable.connect('key-press-event', self.kbKeyPressed)
return
def editingCanceledKey(self, editable):
"""Stops user input of a Key for a selected key binding"""
orca_state.capturingKeys = False
self._capturedKey = []
return
def _processKeyCaptured(self, keyPressedEvent):
"""Called when a new key event arrives and we are capturing keys.
(used for key bindings redefinition)
"""
# We want the keyname rather than the printable character.
# If it's not on the keypad, get the name of the unshifted
# character. (i.e. "1" instead of "!")
#
keycode = keyPressedEvent.hardware_keycode
keymap = Gdk.Keymap.get_default()
entries_for_keycode = keymap.get_entries_for_keycode(keycode)
entries = entries_for_keycode[-1]
eventString = Gdk.keyval_name(entries[0])
eventState = keyPressedEvent.state
orcaMods = settings.orcaModifierKeys
if eventString in orcaMods:
self._capturedKey = ['', keybindings.ORCA_MODIFIER_MASK, 0]
return False
modifierKeys = ['Alt_L', 'Alt_R', 'Control_L', 'Control_R',
'Shift_L', 'Shift_R', 'Meta_L', 'Meta_R',
'Num_Lock', 'Caps_Lock', 'Shift_Lock']
if eventString in modifierKeys:
return False
eventState = eventState & Gtk.accelerator_get_default_mod_mask()
if not self._capturedKey \
or eventString in ['Return', 'Escape']:
self._capturedKey = [eventString, eventState, 1]
return True
string, modifiers, clickCount = self._capturedKey
isOrcaModifier = modifiers & keybindings.ORCA_MODIFIER_MASK
if isOrcaModifier:
eventState |= keybindings.ORCA_MODIFIER_MASK
self._capturedKey = [eventString, eventState, clickCount + 1]
return True
def kbKeyPressed(self, editable, event):
"""Special handler for the key_pressed events when editing the
keybindings. This lets us control what gets inserted into the
entry.
"""
keyProcessed = self._processKeyCaptured(event)
if not keyProcessed:
return True
if not self._capturedKey:
return False
keyName, modifiers, clickCount = self._capturedKey
if not keyName or keyName in ["Return", "Escape"]:
return False
isOrcaModifier = modifiers & keybindings.ORCA_MODIFIER_MASK
if keyName in ["Delete", "BackSpace"] and not isOrcaModifier:
editable.set_text("")
self._presentMessage(messages.KB_DELETED)
self._capturedKey = []
self.newBinding = None
return True
self.newBinding = keybindings.KeyBinding(keyName,
keybindings.defaultModifierMask,
modifiers,
None,
clickCount)
modifierNames = keybindings.getModifierNames(modifiers)
clickCountString = self._clickCountToString(clickCount)
newString = modifierNames + keyName + clickCountString
description = self.pendingKeyBindings.get(newString)
if description is None:
match = lambda x: x.keysymstring == keyName \
and x.modifiers == modifiers \
and x.click_count == clickCount \
and x.handler
matches = list(filter(match, self.kbindings.keyBindings))
if matches:
description = matches[0].handler.description
if description:
msg = messages.KB_ALREADY_BOUND % description
delay = int(1000 * settings.doubleClickTimeout)
GLib.timeout_add(delay, self._presentMessage, msg)
else:
msg = messages.KB_CAPTURED % newString
editable.set_text(newString)
self._presentMessage(msg)
return True
def editedKey(self, cell, path, new_text, treeModel,
modMask, modUsed, key, click_count, text):
"""The user changed the key for a Keybinding: update the model of
the treeview.
"""
orca_state.capturingKeys = False
self._capturedKey = []
myiter = treeModel.get_iter_from_string(path)
try:
originalBinding = treeModel.get_value(myiter, text)
except:
originalBinding = ''
modified = (originalBinding != new_text)
try:
string = self.newBinding.keysymstring
mods = self.newBinding.modifiers
clickCount = self.newBinding.click_count
except:
string = ''
mods = 0
clickCount = 1
mods = mods & Gdk.ModifierType.MODIFIER_MASK
if mods & (1 << pyatspi.MODIFIER_SHIFTLOCK) \
and mods & keybindings.ORCA_MODIFIER_MASK:
mods ^= (1 << pyatspi.MODIFIER_SHIFTLOCK)
treeModel.set(myiter,
modMask, str(keybindings.defaultModifierMask),
modUsed, str(int(mods)),
key, string,
text, new_text,
click_count, str(clickCount),
MODIF, modified)
speech.stop()
if new_text:
message = messages.KB_CAPTURED_CONFIRMATION % new_text
description = treeModel.get_value(myiter, DESCRIP)
self.pendingKeyBindings[new_text] = description
else:
message = messages.KB_DELETED_CONFIRMATION
if modified:
self._presentMessage(message)
self.pendingKeyBindings[originalBinding] = ""
return
def presentToolTipsChecked(self, widget):
"""Signal handler for the "toggled" signal for the
presentToolTipsCheckButton GtkCheckButton widget.
The user has [un]checked the 'Present ToolTips'
checkbox. Set the 'presentToolTips'
preference to the new value if the user can present tooltips.
Arguments:
- widget: the component that generated the signal.
"""
self.prefsDict["presentToolTips"] = widget.get_active()
def keyboardLayoutChanged(self, widget):
"""Signal handler for the "toggled" signal for the generalDesktopButton,
or generalLaptopButton GtkRadioButton widgets. The user has
toggled the keyboard layout value. If this signal was
generated as the result of a radio button getting selected
(as opposed to a radio button losing the selection), set the
'keyboardLayout' preference to the new value. Also set the
matching list of Orca modifier keys
Arguments:
- widget: the component that generated the signal.
"""
if widget.get_active():
if widget.get_label() == guilabels.KEYBOARD_LAYOUT_DESKTOP:
self.prefsDict["keyboardLayout"] = \
settings.GENERAL_KEYBOARD_LAYOUT_DESKTOP
self.prefsDict["orcaModifierKeys"] = \
settings.DESKTOP_MODIFIER_KEYS
else:
self.prefsDict["keyboardLayout"] = \
settings.GENERAL_KEYBOARD_LAYOUT_LAPTOP
self.prefsDict["orcaModifierKeys"] = \
settings.LAPTOP_MODIFIER_KEYS
def pronunciationAddButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
pronunciationAddButton GtkButton widget. The user has clicked
the Add button on the Pronunciation pane. A new row will be
added to the end of the pronunciation dictionary list. Both the
actual and replacement strings will initially be set to an empty
string. Focus will be moved to that row.
Arguments:
- widget: the component that generated the signal.
"""
model = self.pronunciationView.get_model()
thisIter = model.append()
model.set(thisIter, ACTUAL, "", REPLACEMENT, "")
path = model.get_path(thisIter)
col = self.pronunciationView.get_column(0)
self.pronunciationView.grab_focus()
self.pronunciationView.set_cursor(path, col, True)
def pronunciationDeleteButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
pronunciationDeleteButton GtkButton widget. The user has clicked
the Delete button on the Pronunciation pane. The row in the
pronunciation dictionary list with focus will be deleted.
Arguments:
- widget: the component that generated the signal.
"""
model, oldIter = self.pronunciationView.get_selection().get_selected()
model.remove(oldIter)
def textSelectAllButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
textSelectAllButton GtkButton widget. The user has clicked
the Speak all button. Check all the text attributes and
then update the "enabledSpokenTextAttributes" and
"enabledBrailledTextAttributes" preference strings.
Arguments:
- widget: the component that generated the signal.
"""
attributes = _settingsManager.getSetting('allTextAttributes')
self._setSpokenTextAttributes(
self.getTextAttributesView, attributes, True)
self._setBrailledTextAttributes(
self.getTextAttributesView, attributes, True)
self._updateTextDictEntry()
def textUnselectAllButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
textUnselectAllButton GtkButton widget. The user has clicked
the Speak none button. Uncheck all the text attributes and
then update the "enabledSpokenTextAttributes" and
"enabledBrailledTextAttributes" preference strings.
Arguments:
- widget: the component that generated the signal.
"""
attributes = _settingsManager.getSetting('allTextAttributes')
self._setSpokenTextAttributes(
self.getTextAttributesView, attributes, False)
self._setBrailledTextAttributes(
self.getTextAttributesView, attributes, False)
self._updateTextDictEntry()
def textResetButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
textResetButton GtkButton widget. The user has clicked
the Reset button. Reset all the text attributes to their
initial state and then update the "enabledSpokenTextAttributes"
and "enabledBrailledTextAttributes" preference strings.
Arguments:
- widget: the component that generated the signal.
"""
attributes = _settingsManager.getSetting('allTextAttributes')
self._setSpokenTextAttributes(
self.getTextAttributesView, attributes, False)
self._setBrailledTextAttributes(
self.getTextAttributesView, attributes, False)
attributes = _settingsManager.getSetting('enabledSpokenTextAttributes')
self._setSpokenTextAttributes(
self.getTextAttributesView, attributes, True)
attributes = \
_settingsManager.getSetting('enabledBrailledTextAttributes')
self._setBrailledTextAttributes(
self.getTextAttributesView, attributes, True)
self._updateTextDictEntry()
def textMoveToTopButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
textMoveToTopButton GtkButton widget. The user has clicked
the Move to top button. Move the selected rows in the text
attribute view to the very top of the list and then update
the "enabledSpokenTextAttributes" and "enabledBrailledTextAttributes"
preference strings.
Arguments:
- widget: the component that generated the signal.
"""
textSelection = self.getTextAttributesView.get_selection()
[model, paths] = textSelection.get_selected_rows()
for path in paths:
thisIter = model.get_iter(path)
model.move_after(thisIter, None)
self._updateTextDictEntry()
def textMoveUpOneButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
textMoveUpOneButton GtkButton widget. The user has clicked
the Move up one button. Move the selected rows in the text
attribute view up one row in the list and then update the
"enabledSpokenTextAttributes" and "enabledBrailledTextAttributes"
preference strings.
Arguments:
- widget: the component that generated the signal.
"""
textSelection = self.getTextAttributesView.get_selection()
[model, paths] = textSelection.get_selected_rows()
for path in paths:
thisIter = model.get_iter(path)
indices = path.get_indices()
if indices[0]:
otherIter = model.iter_nth_child(None, indices[0]-1)
model.swap(thisIter, otherIter)
self._updateTextDictEntry()
def textMoveDownOneButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
textMoveDownOneButton GtkButton widget. The user has clicked
the Move down one button. Move the selected rows in the text
attribute view down one row in the list and then update the
"enabledSpokenTextAttributes" and "enabledBrailledTextAttributes"
preference strings.
Arguments:
- widget: the component that generated the signal.
"""
textSelection = self.getTextAttributesView.get_selection()
[model, paths] = textSelection.get_selected_rows()
noRows = model.iter_n_children(None)
for path in paths:
thisIter = model.get_iter(path)
indices = path.get_indices()
if indices[0] < noRows-1:
otherIter = model.iter_next(thisIter)
model.swap(thisIter, otherIter)
self._updateTextDictEntry()
def textMoveToBottomButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the
textMoveToBottomButton GtkButton widget. The user has clicked
the Move to bottom button. Move the selected rows in the text
attribute view to the bottom of the list and then update the
"enabledSpokenTextAttributes" and "enabledBrailledTextAttributes"
preference strings.
Arguments:
- widget: the component that generated the signal.
"""
textSelection = self.getTextAttributesView.get_selection()
[model, paths] = textSelection.get_selected_rows()
for path in paths:
thisIter = model.get_iter(path)
model.move_before(thisIter, None)
self._updateTextDictEntry()
def helpButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the helpButton
GtkButton widget. The user has clicked the Help button.
Arguments:
- widget: the component that generated the signal.
"""
orca.helpForOrca(page="preferences")
def restoreSettings(self):
"""Restore the settings we saved away when opening the preferences
dialog."""
# Restore the default rate/pitch/gain,
# in case the user played with the sliders.
#
voices = _settingsManager.getSetting('voices')
defaultVoice = voices[settings.DEFAULT_VOICE]
defaultVoice[acss.ACSS.GAIN] = self.savedGain
defaultVoice[acss.ACSS.AVERAGE_PITCH] = self.savedPitch
defaultVoice[acss.ACSS.RATE] = self.savedRate
def saveBasicSettings(self):
if not self._isInitialSetup:
self.restoreSettings()
enable = self.get_widget("speechSupportCheckButton").get_active()
self.prefsDict["enableSpeech"] = enable
if self.speechSystemsChoice:
self.prefsDict["speechServerFactory"] = \
self.speechSystemsChoice.__name__
if self.speechServersChoice:
self.prefsDict["speechServerInfo"] = \
self.speechServersChoice.getInfo()
if self.defaultVoice is not None:
self.prefsDict["voices"] = {
settings.DEFAULT_VOICE: acss.ACSS(self.defaultVoice),
settings.UPPERCASE_VOICE: acss.ACSS(self.uppercaseVoice),
settings.HYPERLINK_VOICE: acss.ACSS(self.hyperlinkVoice),
settings.SYSTEM_VOICE: acss.ACSS(self.systemVoice),
}
def applyButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the applyButton
GtkButton widget. The user has clicked the Apply button.
Write out the users preferences. If GNOME accessibility hadn't
previously been enabled, warn the user that they will need to
log out. Shut down any active speech servers that were started.
Reload the users preferences to get the new speech, braille and
key echo value to take effect. Do not dismiss the configuration
window.
Arguments:
- widget: the component that generated the signal.
"""
self.saveBasicSettings()
activeProfile = self.getComboBoxList(self.profilesCombo)
startingProfile = self.getComboBoxList(self.startingProfileCombo)
self.prefsDict['profile'] = activeProfile
self.prefsDict['activeProfile'] = activeProfile
self.prefsDict['startingProfile'] = startingProfile
_settingsManager.setStartingProfile(startingProfile)
self.writeUserPreferences()
orca.loadUserSettings(self.script)
braille.checkBrailleSetting()
self._initSpeechState()
self._populateKeyBindings()
self.__initProfileCombo()
def cancelButtonClicked(self, widget):
"""Signal handler for the "clicked" signal for the cancelButton
GtkButton widget. The user has clicked the Cancel button.
Don't write out the preferences. Destroy the configuration window.
Arguments:
- widget: the component that generated the signal.
"""
self.windowClosed(widget)
self.get_widget("orcaSetupWindow").destroy()
def okButtonClicked(self, widget=None):
"""Signal handler for the "clicked" signal for the okButton
GtkButton widget. The user has clicked the OK button.
Write out the users preferences. If GNOME accessibility hadn't
previously been enabled, warn the user that they will need to
log out. Shut down any active speech servers that were started.
Reload the users preferences to get the new speech, braille and
key echo value to take effect. Hide the configuration window.
Arguments:
- widget: the component that generated the signal.
"""
self.applyButtonClicked(widget)
self._cleanupSpeechServers()
self.get_widget("orcaSetupWindow").destroy()
def windowClosed(self, widget):
"""Signal handler for the "closed" signal for the orcaSetupWindow
GtkWindow widget. This is effectively the same as pressing the
cancel button, except the window is destroyed for us.
Arguments:
- widget: the component that generated the signal.
"""
factory = _settingsManager.getSetting('speechServerFactory')
if factory:
self._setSpeechSystemsChoice(factory)
server = _settingsManager.getSetting('speechServerInfo')
if server:
self._setSpeechServersChoice(server)
self._cleanupSpeechServers()
self.restoreSettings()
def windowDestroyed(self, widget):
"""Signal handler for the "destroyed" signal for the orcaSetupWindow
GtkWindow widget. Reset orca_state.orcaOS to None, so that the
GUI can be rebuilt from the GtkBuilder file the next time the user
wants to display the configuration GUI.
Arguments:
- widget: the component that generated the signal.
"""
self.keyBindView.set_model(None)
self.getTextAttributesView.set_model(None)
self.pronunciationView.set_model(None)
self.keyBindView.set_headers_visible(False)
self.getTextAttributesView.set_headers_visible(False)
self.pronunciationView.set_headers_visible(False)
self.keyBindView.hide()
self.getTextAttributesView.hide()
self.pronunciationView.hide()
orca_state.orcaOS = None
def showProfileGUI(self, widget):
"""Show profile Dialog to add a new one"""
orca_gui_profile.showProfileUI(self)
def saveProfile(self, profileToSaveLabel):
"""Creates a new profile based on the name profileToSaveLabel and
updates the Preferences dialog combo boxes accordingly."""
if not profileToSaveLabel:
return
profileToSave = profileToSaveLabel.replace(' ', '_').lower()
profile = [profileToSaveLabel, profileToSave]
def saveActiveProfile(newProfile = True):
if newProfile:
activeProfileIter = self.profilesComboModel.append(profile)
self.profilesCombo.set_active_iter(activeProfileIter)
self.prefsDict['profile'] = profile
self.prefsDict['activeProfile'] = profile
self.saveBasicSettings()
self.writeUserPreferences()
availableProfiles = [p[1] for p in self.__getAvailableProfiles()]
if isinstance(profileToSave, str) \
and profileToSave != '' \
and not profileToSave in availableProfiles \
and profileToSave != self._defaultProfile[1]:
saveActiveProfile()
else:
if profileToSave is not None:
message = guilabels.PROFILE_CONFLICT_MESSAGE % \
("<b>%s</b>" % GLib.markup_escape_text(profileToSaveLabel))
dialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.MODAL,
type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.YES_NO)
dialog.set_markup("<b>%s</b>" % guilabels.PROFILE_CONFLICT_LABEL)
dialog.format_secondary_markup(message)
dialog.set_title(guilabels.PROFILE_CONFLICT_TITLE)
response = dialog.run()
if response == Gtk.ResponseType.YES:
dialog.destroy()
saveActiveProfile(False)
else:
dialog.destroy()
def removeProfileButtonClicked(self, widget):
"""Remove profile button clicked handler
If we removed the last profile, a default one will automatically get
added back by the settings manager.
"""
oldProfile = self.getComboBoxList(self.profilesCombo)
message = guilabels.PROFILE_REMOVE_MESSAGE % \
("<b>%s</b>" % GLib.markup_escape_text(oldProfile[0]))
dialog = Gtk.MessageDialog(self.window, Gtk.DialogFlags.MODAL,
type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.YES_NO)
dialog.set_markup("<b>%s</b>" % guilabels.PROFILE_REMOVE_LABEL)
dialog.format_secondary_markup(message)
if dialog.run() == Gtk.ResponseType.YES:
# If we remove the currently used starting profile, fallback on
# the first listed profile, or the default one if there's
# nothing better
newStartingProfile = self.prefsDict.get('startingProfile')
if not newStartingProfile or newStartingProfile == oldProfile:
newStartingProfile = self._defaultProfile
for row in self.profilesComboModel:
rowProfile = row[:]
if rowProfile != oldProfile:
newStartingProfile = rowProfile
break
# Update the current profile to the active profile unless we're
# removing that one, in which case we use the new starting
# profile
newProfile = self.prefsDict.get('activeProfile')
if not newProfile or newProfile == oldProfile:
newProfile = newStartingProfile
_settingsManager.removeProfile(oldProfile[1])
self.loadProfile(newProfile)
# Make sure nothing is referencing the removed profile anymore
startingProfile = self.prefsDict.get('startingProfile')
if not startingProfile or startingProfile == oldProfile:
self.prefsDict['startingProfile'] = newStartingProfile
_settingsManager.setStartingProfile(newStartingProfile)
self.writeUserPreferences()
dialog.destroy()
def loadProfileButtonClicked(self, widget):
"""Load profile button clicked handler"""
if self._isInitialSetup:
return
dialog = Gtk.MessageDialog(None,
Gtk.DialogFlags.MODAL,
type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.YES_NO)
dialog.set_markup("<b>%s</b>" % guilabels.PROFILE_LOAD_LABEL)
dialog.format_secondary_markup(guilabels.PROFILE_LOAD_MESSAGE)
response = dialog.run()
if response == Gtk.ResponseType.YES:
dialog.destroy()
self.loadSelectedProfile()
else:
dialog.destroy()
def loadSelectedProfile(self):
"""Load selected profile"""
activeProfile = self.getComboBoxList(self.profilesCombo)
self.loadProfile(activeProfile)
def loadProfile(self, profile):
"""Load profile"""
self.saveBasicSettings()
self.prefsDict['activeProfile'] = profile
_settingsManager.setProfile(profile[1])
self.prefsDict = _settingsManager.getGeneralSettings(profile[1])
orca.loadUserSettings(skipReloadMessage=True)
self._initGUIState()
braille.checkBrailleSetting()
self._initSpeechState()
self._populateKeyBindings()
self.__initProfileCombo()<|fim▁end|> | def _presentMessage(self, text, interrupt=False):
"""If the text field is not None, presents the given text, optionally
interrupting anything currently being spoken. |
<|file_name|>rot300.py<|end_file_name|><|fim▁begin|>#7/5/2014
import Image
from pytesser import *
import telnetlib
import base64
import StringIO
def main():
tn = telnetlib.Telnet("41.231.53.40",9090)
ret = tn.read_until("\n")
print ret
base64_str = ret.strip()
decode = base64.b64decode(base64_str)
buff = StringIO.StringIO()
buff.write(decode)
buff.seek(0)
img = Image.open(buff)
#construct new image
img = img.rotate(90)
img2 = img.rotate(180)
new_img = Image.blend(img,img2,0.5)
new_img = new_img.convert("RGBA")
pixels = new_img.load()
width, height = new_img.size
for x in range(width):
for y in range(height):
r, g, b, a = pixels[x, y]
#print r,g,b
if g==255 and b==127:
pixels[x,y] = (255,255,255,a)
new_img.save("newnew.png")
text = image_file_to_string("newnew.png")#read text from the image<|fim▁hole|> #new_img.show()
text = text.split("\n")[1]
text = "".join(text.split())
#print text,
ret = tn.read_until("Answer:")
print ret,
print text
tn.write(text + "\n")
ret = tn.read_all()
print ret
if __name__ == "__main__":
main()<|fim▁end|> | |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># coding:utf-8
from django.conf.urls import patterns, include, url
from kylin_log.views import *
urlpatterns = patterns('',
url(r'^list/(\w+)/$', log_list, name='log_list'),
url(r'^detail/(\w+)/$', log_detail, name='log_detail'),<|fim▁hole|> url(r'^history/$', log_history, name='log_history'),
url(r'^log_kill/', log_kill, name='log_kill'),
url(r'^record/$', log_record, name='log_record'),
)<|fim▁end|> | |
<|file_name|>yui-later.js<|end_file_name|><|fim▁begin|>/* YUI 3.9.0 (build 5827) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add('yui-later', function (Y, NAME) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module,
* <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS;
o = o || Y.config.win || Y;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};<|fim▁hole|>Y.Lang.later = Y.later;
}, '3.9.0', {"requires": ["yui-base"]});<|fim▁end|> | |
<|file_name|>SuggestionThreadObjectFactorySpec.ts<|end_file_name|><|fim▁begin|>// Copyright 2018 The Oppia 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.
/**
* @fileoverview Unit tests for SuggestionThreadObjectFactory.
*/
// TODO(#7222): Remove the following block of unnnecessary imports once
// SuggestionThreadObjectFactory.ts is upgraded to Angular 8.
import { SuggestionObjectFactory } from
'domain/suggestion/SuggestionObjectFactory.ts';
// ^^^ This block is to be removed.
require('domain/suggestion/SuggestionThreadObjectFactory.ts');
describe('Suggestion thread object factory', function() {
beforeEach(function() {
angular.mock.module('oppia');
});
beforeEach(angular.mock.module('oppia', function($provide) {
$provide.value('SuggestionObjectFactory', new SuggestionObjectFactory());
}));
var SuggestionThreadObjectFactory = null;
var suggestionObjectFactory = null;
beforeEach(angular.mock.inject(function($injector) {
SuggestionThreadObjectFactory = $injector.get(
'SuggestionThreadObjectFactory');
suggestionObjectFactory = $injector.get('SuggestionObjectFactory');
}));
it('should create a new suggestion thread from a backend dict.', function() {
var suggestionThreadBackendDict = {
last_updated: 1000,
original_author_username: 'author',
status: 'accepted',
subject: 'sample subject',
summary: 'sample summary',
message_count: 10,
state_name: 'state 1',
thread_id: 'exploration.exp1.thread1'
};
var suggestionBackendDict = {
suggestion_id: 'exploration.exp1.thread1',
suggestion_type: 'edit_exploration_state_content',
target_type: 'exploration',
target_id: 'exp1',
target_version_at_submission: 1,
status: 'accepted',
author_name: 'author',
change: {
cmd: 'edit_state_property',<|fim▁hole|> html: 'new suggestion content'
},
old_value: {
html: 'old suggestion content'
}
},
last_updated: 1000
};
var suggestionThread = SuggestionThreadObjectFactory.createFromBackendDicts(
suggestionThreadBackendDict, suggestionBackendDict);
expect(suggestionThread.status).toEqual('accepted');
expect(suggestionThread.subject).toEqual('sample subject');
expect(suggestionThread.summary).toEqual('sample summary');
expect(suggestionThread.originalAuthorName).toEqual('author');
expect(suggestionThread.lastUpdated).toEqual(1000);
expect(suggestionThread.messageCount).toEqual(10);
expect(suggestionThread.threadId).toEqual('exploration.exp1.thread1');
expect(suggestionThread.suggestion.suggestionType).toEqual(
'edit_exploration_state_content');
expect(suggestionThread.suggestion.targetType).toEqual('exploration');
expect(suggestionThread.suggestion.targetId).toEqual('exp1');
expect(suggestionThread.suggestion.suggestionId).toEqual(
'exploration.exp1.thread1');
expect(suggestionThread.suggestion.status).toEqual('accepted');
expect(suggestionThread.suggestion.authorName).toEqual('author');
expect(suggestionThread.suggestion.newValue.html).toEqual(
'new suggestion content');
expect(suggestionThread.suggestion.oldValue.html).toEqual(
'old suggestion content');
expect(suggestionThread.suggestion.lastUpdated).toEqual(1000);
expect(suggestionThread.suggestion.getThreadId()).toEqual(
'exploration.exp1.thread1');
expect(suggestionThread.isSuggestionThread()).toEqual(true);
expect(suggestionThread.isSuggestionHandled()).toEqual(true);
suggestionThread.suggestion.status = 'review';
expect(suggestionThread.isSuggestionHandled()).toEqual(false);
expect(suggestionThread.getSuggestionStatus()).toEqual('review');
expect(suggestionThread.getSuggestionStateName()).toEqual('state_1');
expect(suggestionThread.getReplacementHtmlFromSuggestion()).toEqual(
'new suggestion content');
var messages = [{
text: 'message1'
}, {
text: 'message2'
}];
suggestionThread.setMessages(messages);
expect(suggestionThread.messages).toEqual(messages);
});
});<|fim▁end|> | property_name: 'content',
state_name: 'state_1',
new_value: { |
<|file_name|>ColorStackOption.js<|end_file_name|><|fim▁begin|>import React from 'react'
import PropTypes from 'prop-types'
import FormGroup from '../forms/FormGroup'
import InputColor from '../forms/InputColor'
const ColorStackOption = ({ label, name, value, definitions, required, onChange, error }) => {
// default value may be null
if (value === null) {
value = ''
}
return (
<FormGroup label={label} htmlFor={name} error={error} required={required}>
<InputColor
name={name}
id={name}
value={value}
defaultValue={definitions.default}
onChange={onChange}
/>
</FormGroup>
)
}<|fim▁hole|> name: PropTypes.string.isRequired,
definitions: PropTypes.object.isRequired,
required: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
error: PropTypes.string
}
export default ColorStackOption<|fim▁end|> | ColorStackOption.propTypes = {
label: PropTypes.string.isRequired, |
<|file_name|>unstrap.js<|end_file_name|><|fim▁begin|>/*
* unstrap v1.1.3
* https://unstrap.org
* 2015-2020
* MIT license
*/
const version = '1.1.3',
collection = {};
function extendUnstrap (v) {
var list;
if (!collection[v].selectors) {
collection[v].selectors = ['.' + collection[v].name];
}
collection[v].selectors.forEach(function (sel) {
list = document.querySelectorAll(sel);
for (var i = 0; i < list.length; i++) {
collection[v].extend && collection[v].extend(list.item(i));
}
})
}
function init () {
var observer = new MutationObserver(function (mut) {<|fim▁hole|> var c = n.item(i).classList;
if (c) {
for (var j = 0; j < c.length; j++) {
if (f = collection[c.item(j)]) {
f.extend && f.extend(n.item(i));
}
}
}
}
});
});
Object.keys(collection).forEach(function (v) {
extendUnstrap(v);
})
observer.observe(document.body, {childList: true, subtree: true});
}
function register (...components) {
components.forEach((component) => {
if (component.name) {
collection[component.name] = component;
}
})
}
function unregister (...components) {
components.forEach((component) => {
delete collection[component.name];
})
}
function list () {
return Object.keys(collection).sort();
}
window.onload = init;
export default {
version,
register,
unregister,
list
}<|fim▁end|> | mut.forEach(function (m) {
var n = m.addedNodes,
f;
for (var i=0; i<n.length; i++) { |
<|file_name|>example2.py<|end_file_name|><|fim▁begin|># Example of managed attributes via properties
class String:
def __init__(self, name):
self.name = name
def __get__(self, instance, cls):
if instance is None:
return self
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
instance.__dict__[self.name] = value
class Person:
name = String('name')
def __init__(self, name):
self.name = name
class SubPerson(Person):
@property
def name(self):
print('Getting name')
return super().name
@name.setter
def name(self, value):
print('Setting name to', value)
super(SubPerson, SubPerson).name.__set__(self, value)
@name.deleter<|fim▁hole|> print('Deleting name')
super(SubPerson, SubPerson).name.__delete__(self)
if __name__ == '__main__':
a = Person('Guido')
print(a.name)
a.name = 'Dave'
print(a.name)
try:
a.name = 42
except TypeError as e:
print(e)<|fim▁end|> | def name(self): |
<|file_name|>limits.py<|end_file_name|><|fim▁begin|># Copyright 2011 OpenStack Foundation
# 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.
from nova.api.openstack.api_version_request \
import MAX_IMAGE_META_PROXY_API_VERSION
from nova.api.openstack.api_version_request \
import MAX_PROXY_API_SUPPORT_VERSION
from nova.api.openstack.api_version_request \
import MIN_WITHOUT_IMAGE_META_PROXY_API_VERSION
from nova.api.openstack.api_version_request \
import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION
from nova.api.openstack.compute.schemas import limits<|fim▁hole|>from nova.policies import limits as limits_policies
from nova import quota
QUOTAS = quota.QUOTAS
# This is a list of limits which needs to filter out from the API response.
# This is due to the deprecation of network related proxy APIs, the related
# limit should be removed from the API also.
FILTERED_LIMITS_2_36 = ['floating_ips', 'security_groups',
'security_group_rules']
FILTERED_LIMITS_2_57 = list(FILTERED_LIMITS_2_36)
FILTERED_LIMITS_2_57.extend(['injected_files', 'injected_file_content_bytes'])
class LimitsController(wsgi.Controller):
"""Controller for accessing limits in the OpenStack API."""
@wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION)
@wsgi.expected_errors(())
@validation.query_schema(limits.limits_query_schema)
def index(self, req):
return self._index(req)
@wsgi.Controller.api_version(MIN_WITHOUT_PROXY_API_SUPPORT_VERSION, # noqa
MAX_IMAGE_META_PROXY_API_VERSION) # noqa
@wsgi.expected_errors(())
@validation.query_schema(limits.limits_query_schema)
def index(self, req):
return self._index(req, FILTERED_LIMITS_2_36)
@wsgi.Controller.api_version( # noqa
MIN_WITHOUT_IMAGE_META_PROXY_API_VERSION, '2.56') # noqa
@wsgi.expected_errors(())
@validation.query_schema(limits.limits_query_schema)
def index(self, req):
return self._index(req, FILTERED_LIMITS_2_36, max_image_meta=False)
@wsgi.Controller.api_version('2.57') # noqa
@wsgi.expected_errors(())
@validation.query_schema(limits.limits_query_schema_275, '2.75')
@validation.query_schema(limits.limits_query_schema, '2.57', '2.74')
def index(self, req):
return self._index(req, FILTERED_LIMITS_2_57, max_image_meta=False)
def _index(self, req, filtered_limits=None, max_image_meta=True):
"""Return all global limit information."""
context = req.environ['nova.context']
context.can(limits_policies.BASE_POLICY_NAME)
project_id = req.params.get('tenant_id', context.project_id)
quotas = QUOTAS.get_project_quotas(context, project_id,
usages=True)
builder = limits_views.ViewBuilder()
return builder.build(req, quotas, filtered_limits=filtered_limits,
max_image_meta=max_image_meta)<|fim▁end|> | from nova.api.openstack.compute.views import limits as limits_views
from nova.api.openstack import wsgi
from nova.api import validation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.