text
stringlengths 2
1.04M
| meta
dict |
---|---|
Decimal128: [decq641] fold-down full sequence (Clamped)
--DESCRIPTION--
Generated by scripts/convert-bson-corpus-tests.php
DO NOT EDIT THIS FILE
--FILE--
<?php
require_once __DIR__ . '/../utils/tools.php';
$canonicalBson = hex2bin('1800000013640000A0724E18090000000000000000FE5F00');
$canonicalExtJson = '{"d" : {"$numberDecimal" : "1.0000000000000E+6124"}}';
$degenerateExtJson = '{"d" : {"$numberDecimal" : "1E+6124"}}';
// Canonical BSON -> Native -> Canonical BSON
echo bin2hex(fromPHP(toPHP($canonicalBson))), "\n";
// Canonical BSON -> Canonical extJSON
echo json_canonicalize(toCanonicalExtendedJSON($canonicalBson)), "\n";
// Canonical extJSON -> Canonical BSON
echo bin2hex(fromJSON($canonicalExtJson)), "\n";
// Degenerate extJSON -> Canonical BSON
echo bin2hex(fromJSON($degenerateExtJson)), "\n";
?>
===DONE===
<?php exit(0); ?>
--EXPECT--
1800000013640000a0724e18090000000000000000fe5f00
{"d":{"$numberDecimal":"1.0000000000000E+6124"}}
1800000013640000a0724e18090000000000000000fe5f00
1800000013640000a0724e18090000000000000000fe5f00
===DONE=== | {
"content_hash": "3259ba4a4500d16ed417c510ae39fb12",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 77,
"avg_line_length": 30.571428571428573,
"alnum_prop": 0.7373831775700934,
"repo_name": "derickr/mongo-php-driver",
"id": "a1d071c102149653a6209d2983ace6bd781d3423",
"size": "1079",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/bson-corpus/decimal128-5-valid-055.phpt",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6867"
},
{
"name": "C",
"bytes": "701736"
},
{
"name": "C++",
"bytes": "22773"
},
{
"name": "GDB",
"bytes": "190"
},
{
"name": "JavaScript",
"bytes": "13354"
},
{
"name": "M4",
"bytes": "85893"
},
{
"name": "Makefile",
"bytes": "3096"
},
{
"name": "PHP",
"bytes": "1840743"
},
{
"name": "Python",
"bytes": "1597432"
},
{
"name": "Shell",
"bytes": "23664"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Wed Mar 04 22:48:16 CET 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package org.optaplanner.examples.cloudbalancing.persistence (OptaPlanner distribution 6.2.0.Final API)
</TITLE>
<META NAME="date" CONTENT="2015-03-04">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.optaplanner.examples.cloudbalancing.persistence (OptaPlanner distribution 6.2.0.Final API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>OptaPlanner distribution 6.2.0.Final</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/optaplanner/examples/cloudbalancing/persistence/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Package<br>org.optaplanner.examples.cloudbalancing.persistence</B></H2>
</CENTER>
No usage of org.optaplanner.examples.cloudbalancing.persistence
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>OptaPlanner distribution 6.2.0.Final</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/optaplanner/examples/cloudbalancing/persistence/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2006-2015 <a href="http://www.jboss.org/">JBoss by Red Hat</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "491e48007986b15682ab11e704e59368",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 159,
"avg_line_length": 41.88275862068966,
"alnum_prop": 0.6267083813601185,
"repo_name": "jormunmor/doctorado",
"id": "61df4354b2f494e87c97312fed2bbb6c0c20cde7",
"size": "6073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "optaplanner-distribution-6.2.0.Final/javadocs/org/optaplanner/examples/cloudbalancing/persistence/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2671"
},
{
"name": "C",
"bytes": "14433"
},
{
"name": "C#",
"bytes": "18659"
},
{
"name": "C++",
"bytes": "2923396"
},
{
"name": "CMake",
"bytes": "38809"
},
{
"name": "CSS",
"bytes": "949322"
},
{
"name": "GAP",
"bytes": "24568"
},
{
"name": "HTML",
"bytes": "62229389"
},
{
"name": "Java",
"bytes": "2437530"
},
{
"name": "JavaScript",
"bytes": "8047306"
},
{
"name": "Makefile",
"bytes": "293709"
},
{
"name": "Objective-C++",
"bytes": "7535732"
},
{
"name": "PostScript",
"bytes": "13039"
},
{
"name": "Python",
"bytes": "4330"
},
{
"name": "QMake",
"bytes": "5527"
},
{
"name": "Shell",
"bytes": "2037"
},
{
"name": "TeX",
"bytes": "2066789"
}
],
"symlink_target": ""
} |
""" This module defines a Python-level wrapper around the C++
AsyncTaskManager interface. It replaces the old full-Python
implementation of the Task system. """
__all__ = ['Task', 'TaskManager',
'cont', 'done', 'again', 'pickup', 'exit',
'sequence', 'loop', 'pause']
from direct.directnotify.DirectNotifyGlobal import *
from direct.showbase import ExceptionVarDump
from direct.showbase.PythonUtil import *
from direct.showbase.MessengerGlobal import messenger
import types
import random
import importlib
try:
import signal
except ImportError:
signal = None
from panda3d.core import *
from direct.extensions_native import HTTPChannel_extensions
def print_exc_plus():
"""
Print the usual traceback information, followed by a listing of all the
local variables in each frame.
"""
import sys
import traceback
tb = sys.exc_info()[2]
while 1:
if not tb.tb_next:
break
tb = tb.tb_next
stack = []
f = tb.tb_frame
while f:
stack.append(f)
f = f.f_back
stack.reverse()
traceback.print_exc()
print("Locals by frame, innermost last")
for frame in stack:
print("")
print("Frame %s in %s at line %s" % (frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno))
for key, value in list(frame.f_locals.items()):
#We have to be careful not to cause a new error in our error
#printer! Calling str() on an unknown object could cause an
#error we don't want.
try:
valueStr = str(value)
except:
valueStr = "<ERROR WHILE PRINTING VALUE>"
print("\t%20s = %s" % (key, valueStr))
# For historical purposes, we remap the C++-defined enumeration to
# these Python names, and define them both at the module level, here,
# and at the class level (below). The preferred access is via the
# class level.
done = AsyncTask.DSDone
cont = AsyncTask.DSCont
again = AsyncTask.DSAgain
pickup = AsyncTask.DSPickup
exit = AsyncTask.DSExit
# Alias PythonTask to Task for historical purposes.
Task = PythonTask
# Copy the module-level enums above into the class level. This funny
# syntax is necessary because it's a C++-wrapped extension type, not a
# true Python class.
Task.DtoolClassDict['done'] = done
Task.DtoolClassDict['cont'] = cont
Task.DtoolClassDict['again'] = again
Task.DtoolClassDict['pickup'] = pickup
Task.DtoolClassDict['exit'] = exit
# Alias the AsyncTaskPause constructor as Task.pause().
pause = AsyncTaskPause
Task.DtoolClassDict['pause'] = staticmethod(pause)
def sequence(*taskList):
seq = AsyncTaskSequence('sequence')
for task in taskList:
seq.addTask(task)
return seq
Task.DtoolClassDict['sequence'] = staticmethod(sequence)
def loop(*taskList):
seq = AsyncTaskSequence('loop')
for task in taskList:
seq.addTask(task)
seq.setRepeatCount(-1)
return seq
Task.DtoolClassDict['loop'] = staticmethod(loop)
class TaskManager:
notify = directNotify.newCategory("TaskManager")
taskTimerVerbose = ConfigVariableBool('task-timer-verbose', False)
extendedExceptions = ConfigVariableBool('extended-exceptions', False)
pStatsTasks = ConfigVariableBool('pstats-tasks', False)
MaxEpochSpeed = 1.0/30.0
def __init__(self):
self.mgr = AsyncTaskManager.getGlobalPtr()
self.resumeFunc = None
self.globalClock = self.mgr.getClock()
self.stepping = False
self.running = False
self.destroyed = False
self.fKeyboardInterrupt = False
self.interruptCount = 0
self._frameProfileQueue = Queue()
# this will be set when it's safe to import StateVar
self._profileFrames = None
self._frameProfiler = None
self._profileTasks = None
self._taskProfiler = None
self._taskProfileInfo = ScratchPad(
taskId = None,
profiled = False,
session = None,
)
def finalInit(self):
# This function should be called once during startup, after
# most things are imported.
from direct.fsm.StatePush import StateVar
self._profileTasks = StateVar(False)
self.setProfileTasks(ConfigVariableBool('profile-task-spikes', 0).getValue())
self._profileFrames = StateVar(False)
self.setProfileFrames(ConfigVariableBool('profile-frames', 0).getValue())
def destroy(self):
# This should be safe to call multiple times.
self.running = False
self.notify.info("TaskManager.destroy()")
self.destroyed = True
self._frameProfileQueue.clear()
self.mgr.cleanup()
def setClock(self, clockObject):
self.mgr.setClock(clockObject)
self.globalClock = clockObject
clock = property(lambda self: self.mgr.getClock(), setClock)
def invokeDefaultHandler(self, signalNumber, stackFrame):
print('*** allowing mid-frame keyboard interrupt.')
# Restore default interrupt handler
if signal:
signal.signal(signal.SIGINT, signal.default_int_handler)
# and invoke it
raise KeyboardInterrupt
def keyboardInterruptHandler(self, signalNumber, stackFrame):
self.fKeyboardInterrupt = 1
self.interruptCount += 1
if self.interruptCount == 1:
print('* interrupt by keyboard')
elif self.interruptCount == 2:
print('** waiting for end of frame before interrupting...')
# The user must really want to interrupt this process
# Next time around invoke the default handler
signal.signal(signal.SIGINT, self.invokeDefaultHandler)
def getCurrentTask(self):
""" Returns the task currently executing on this thread, or
None if this is being called outside of the task manager. """
return Thread.getCurrentThread().getCurrentTask()
def hasTaskChain(self, chainName):
""" Returns true if a task chain with the indicated name has
already been defined, or false otherwise. Note that
setupTaskChain() will implicitly define a task chain if it has
not already been defined, or modify an existing one if it has,
so in most cases there is no need to check this method
first. """
return (self.mgr.findTaskChain(chainName) != None)
def setupTaskChain(self, chainName, numThreads = None, tickClock = None,
threadPriority = None, frameBudget = None,
frameSync = None, timeslicePriority = None):
"""Defines a new task chain. Each task chain executes tasks
potentially in parallel with all of the other task chains (if
numThreads is more than zero). When a new task is created, it
may be associated with any of the task chains, by name (or you
can move a task to another task chain with
task.setTaskChain()). You can have any number of task chains,
but each must have a unique name.
numThreads is the number of threads to allocate for this task
chain. If it is 1 or more, then the tasks on this task chain
will execute in parallel with the tasks on other task chains.
If it is greater than 1, then the tasks on this task chain may
execute in parallel with themselves (within tasks of the same
sort value).
If tickClock is True, then this task chain will be responsible
for ticking the global clock each frame (and thereby
incrementing the frame counter). There should be just one
task chain responsible for ticking the clock, and usually it
is the default, unnamed task chain.
threadPriority specifies the priority level to assign to
threads on this task chain. It may be one of TPLow, TPNormal,
TPHigh, or TPUrgent. This is passed to the underlying
threading system to control the way the threads are scheduled.
frameBudget is the maximum amount of time (in seconds) to
allow this task chain to run per frame. Set it to -1 to mean
no limit (the default). It's not directly related to
threadPriority.
frameSync is true to force the task chain to sync to the
clock. When this flag is false, the default, the task chain
will finish all of its tasks and then immediately start from
the first task again, regardless of the clock frame. When it
is true, the task chain will finish all of its tasks and then
wait for the clock to tick to the next frame before resuming
the first task. This only makes sense for threaded tasks
chains; non-threaded task chains are automatically
synchronous.
timeslicePriority is False in the default mode, in which each
task runs exactly once each frame, round-robin style,
regardless of the task's priority value; or True to change the
meaning of priority so that certain tasks are run less often,
in proportion to their time used and to their priority value.
See AsyncTaskManager.setTimeslicePriority() for more.
"""
chain = self.mgr.makeTaskChain(chainName)
if numThreads is not None:
chain.setNumThreads(numThreads)
if tickClock is not None:
chain.setTickClock(tickClock)
if threadPriority is not None:
chain.setThreadPriority(threadPriority)
if frameBudget is not None:
chain.setFrameBudget(frameBudget)
if frameSync is not None:
chain.setFrameSync(frameSync)
if timeslicePriority is not None:
chain.setTimeslicePriority(timeslicePriority)
def hasTaskNamed(self, taskName):
"""Returns true if there is at least one task, active or
sleeping, with the indicated name. """
return bool(self.mgr.findTask(taskName))
def getTasksNamed(self, taskName):
"""Returns a list of all tasks, active or sleeping, with the
indicated name. """
return self.__makeTaskList(self.mgr.findTasks(taskName))
def getTasksMatching(self, taskPattern):
"""Returns a list of all tasks, active or sleeping, with a
name that matches the pattern, which can include standard
shell globbing characters like *, ?, and []. """
return self.__makeTaskList(self.mgr.findTasksMatching(GlobPattern(taskPattern)))
def getAllTasks(self):
"""Returns list of all tasks, active and sleeping, in
arbitrary order. """
return self.__makeTaskList(self.mgr.getTasks())
def getTasks(self):
"""Returns list of all active tasks in arbitrary order. """
return self.__makeTaskList(self.mgr.getActiveTasks())
def getDoLaters(self):
"""Returns list of all sleeping tasks in arbitrary order. """
return self.__makeTaskList(self.mgr.getSleepingTasks())
def __makeTaskList(self, taskCollection):
l = []
for i in range(taskCollection.getNumTasks()):
l.append(taskCollection.getTask(i))
return l
def doMethodLater(self, delayTime, funcOrTask, name, extraArgs = None,
sort = None, priority = None, taskChain = None,
uponDeath = None, appendTask = False, owner = None):
"""Adds a task to be performed at some time in the future.
This is identical to add(), except that the specified
delayTime is applied to the Task object first, which means
that the task will not begin executing until at least the
indicated delayTime (in seconds) has elapsed.
After delayTime has elapsed, the task will become active, and
will run in the soonest possible frame thereafter. If you
wish to specify a task that will run in the next frame, use a
delayTime of 0.
"""
if delayTime < 0:
assert self.notify.warning('doMethodLater: added task: %s with negative delay: %s' % (name, delayTime))
task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
task.setDelay(delayTime)
self.mgr.add(task)
return task
do_method_later = doMethodLater
def add(self, funcOrTask, name = None, sort = None, extraArgs = None,
priority = None, uponDeath = None, appendTask = False,
taskChain = None, owner = None):
"""
Add a new task to the taskMgr. The task will begin executing
immediately, or next frame if its sort value has already
passed this frame.
The parameters are:
funcOrTask - either an existing Task object (not already added
to the task manager), or a callable function object. If this
is a function, a new Task object will be created and returned.
name - the name to assign to the Task. Required, unless you
are passing in a Task object that already has a name.
extraArgs - the list of arguments to pass to the task
function. If this is omitted, the list is just the task
object itself.
appendTask - a boolean flag. If this is true, then the task
object itself will be appended to the end of the extraArgs
list before calling the function.
sort - the sort value to assign the task. The default sort is
0. Within a particular task chain, it is guaranteed that the
tasks with a lower sort value will all run before tasks with a
higher sort value run.
priority - the priority at which to run the task. The default
priority is 0. Higher priority tasks are run sooner, and/or
more often. For historical purposes, if you specify a
priority without also specifying a sort, the priority value is
understood to actually be a sort value. (Previously, there
was no priority value, only a sort value, and it was called
"priority".)
uponDeath - a function to call when the task terminates,
either because it has run to completion, or because it has
been explicitly removed.
taskChain - the name of the task chain to assign the task to.
owner - an optional Python object that is declared as the
"owner" of this task for maintenance purposes. The owner must
have two methods: owner._addTask(self, task), which is called
when the task begins, and owner._clearTask(self, task), which
is called when the task terminates. This is all the owner
means.
The return value of add() is the new Task object that has been
added, or the original Task object that was passed in.
"""
task = self.__setupTask(funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath)
self.mgr.add(task)
return task
def __setupTask(self, funcOrTask, name, priority, sort, extraArgs, taskChain, appendTask, owner, uponDeath):
if isinstance(funcOrTask, AsyncTask):
task = funcOrTask
elif hasattr(funcOrTask, '__call__'):
task = PythonTask(funcOrTask)
else:
self.notify.error(
'add: Tried to add a task that was not a Task or a func')
if hasattr(task, 'setArgs'):
# It will only accept arguments if it's a PythonTask.
if extraArgs is None:
extraArgs = []
appendTask = True
task.setArgs(extraArgs, appendTask)
elif extraArgs is not None:
self.notify.error(
'Task %s does not accept arguments.' % (repr(task)))
if name is not None:
task.setName(name)
assert task.hasName()
# For historical reasons, if priority is specified but not
# sort, it really means sort.
if priority is not None and sort is None:
task.setSort(priority)
else:
if priority is not None:
task.setPriority(priority)
if sort is not None:
task.setSort(sort)
if taskChain is not None:
task.setTaskChain(taskChain)
if owner is not None:
task.setOwner(owner)
if uponDeath is not None:
task.setUponDeath(uponDeath)
return task
def remove(self, taskOrName):
"""Removes a task from the task manager. The task is stopped,
almost as if it had returned task.done. (But if the task is
currently executing, it will finish out its current frame
before being removed.) You may specify either an explicit
Task object, or the name of a task. If you specify a name,
all tasks with the indicated name are removed. Returns the
number of tasks removed. """
if isinstance(taskOrName, AsyncTask):
return self.mgr.remove(taskOrName)
elif isinstance(taskOrName, list):
for task in taskOrName:
self.remove(task)
else:
tasks = self.mgr.findTasks(taskOrName)
return self.mgr.remove(tasks)
def removeTasksMatching(self, taskPattern):
"""Removes all tasks whose names match the pattern, which can
include standard shell globbing characters like *, ?, and [].
See also remove().
Returns the number of tasks removed.
"""
tasks = self.mgr.findTasksMatching(GlobPattern(taskPattern))
return self.mgr.remove(tasks)
def step(self):
"""Invokes the task manager for one frame, and then returns.
Normally, this executes each task exactly once, though task
chains that are in sub-threads or that have frame budgets
might execute their tasks differently. """
# Replace keyboard interrupt handler during task list processing
# so we catch the keyboard interrupt but don't handle it until
# after task list processing is complete.
self.fKeyboardInterrupt = 0
self.interruptCount = 0
if signal:
signal.signal(signal.SIGINT, self.keyboardInterruptHandler)
startFrameTime = self.globalClock.getRealTime()
self.mgr.poll()
# This is the spot for an internal yield function
nextTaskTime = self.mgr.getNextWakeTime()
self.doYield(startFrameTime, nextTaskTime)
# Restore default interrupt handler
if signal:
signal.signal(signal.SIGINT, signal.default_int_handler)
if self.fKeyboardInterrupt:
raise KeyboardInterrupt
def run(self):
"""Starts the task manager running. Does not return until an
exception is encountered (including KeyboardInterrupt). """
if PandaSystem.getPlatform() == 'emscripten':
return
# Set the clock to have last frame's time in case we were
# Paused at the prompt for a long time
t = self.globalClock.getFrameTime()
timeDelta = t - self.globalClock.getRealTime()
self.globalClock.setRealTime(t)
messenger.send("resetClock", [timeDelta])
if self.resumeFunc != None:
self.resumeFunc()
if self.stepping:
self.step()
else:
self.running = True
while self.running:
try:
if len(self._frameProfileQueue):
numFrames, session, callback = self._frameProfileQueue.pop()
def _profileFunc(numFrames=numFrames):
self._doProfiledFrames(numFrames)
session.setFunc(_profileFunc)
session.run()
_profileFunc = None
if callback:
callback()
session.release()
else:
self.step()
except KeyboardInterrupt:
self.stop()
except SystemExit:
self.stop()
raise
except IOError as ioError:
code, message = self._unpackIOError(ioError)
# Since upgrading to Python 2.4.1, pausing the execution
# often gives this IOError during the sleep function:
# IOError: [Errno 4] Interrupted function call
# So, let's just handle that specific exception and stop.
# All other IOErrors should still get raised.
# Only problem: legit IOError 4s will be obfuscated.
if code == 4:
self.stop()
else:
raise
except Exception as e:
if self.extendedExceptions:
self.stop()
print_exc_plus()
else:
if (ExceptionVarDump.wantStackDumpLog and
ExceptionVarDump.dumpOnExceptionInit):
ExceptionVarDump._varDump__print(e)
raise
except:
if self.extendedExceptions:
self.stop()
print_exc_plus()
else:
raise
self.mgr.stopThreads()
def _unpackIOError(self, ioError):
# IOError unpack from http://www.python.org/doc/essays/stdexceptions/
# this needs to be in its own method, exceptions that occur inside
# a nested try block are not caught by the inner try block's except
try:
(code, message) = ioError
except:
code = 0
message = ioError
return code, message
def stop(self):
# Set a flag so we will stop before beginning next frame
self.running = False
def __tryReplaceTaskMethod(self, task, oldMethod, newFunction):
if not isinstance(task, PythonTask):
return 0
method = task.getFunction()
if (type(method) == types.MethodType):
function = method.__func__
else:
function = method
if (function == oldMethod):
newMethod = types.MethodType(newFunction,
method.__self__,
method.__self__.__class__)
task.setFunction(newMethod)
# Found a match
return 1
return 0
def replaceMethod(self, oldMethod, newFunction):
numFound = 0
for task in self.getAllTasks():
numFound += self.__tryReplaceTaskMethod(task, oldMethod, newFunction)
return numFound
def popupControls(self):
# Don't use a regular import, to prevent ModuleFinder from picking
# it up as a dependency when building a .p3d package.
TaskManagerPanel = importlib.import_module('direct.tkpanels.TaskManagerPanel')
return TaskManagerPanel.TaskManagerPanel(self)
def getProfileSession(self, name=None):
# call to get a profile session that you can modify before passing to profileFrames()
if name is None:
name = 'taskMgrFrameProfile'
# Defer this import until we need it: some Python
# distributions don't provide the profile and pstats modules.
PS = importlib.import_module('direct.showbase.ProfileSession')
return PS.ProfileSession(name)
def profileFrames(self, num=None, session=None, callback=None):
if num is None:
num = 1
if session is None:
session = self.getProfileSession()
# make sure the profile session doesn't get destroyed before we're done with it
session.acquire()
self._frameProfileQueue.push((num, session, callback))
def _doProfiledFrames(self, numFrames):
for i in range(numFrames):
result = self.step()
return result
def getProfileFrames(self):
return self._profileFrames.get()
def getProfileFramesSV(self):
return self._profileFrames
def setProfileFrames(self, profileFrames):
self._profileFrames.set(profileFrames)
if (not self._frameProfiler) and profileFrames:
# import here due to import dependencies
FP = importlib.import_module('direct.task.FrameProfiler')
self._frameProfiler = FP.FrameProfiler()
def getProfileTasks(self):
return self._profileTasks.get()
def getProfileTasksSV(self):
return self._profileTasks
def setProfileTasks(self, profileTasks):
self._profileTasks.set(profileTasks)
if (not self._taskProfiler) and profileTasks:
# import here due to import dependencies
TP = importlib.import_module('direct.task.TaskProfiler')
self._taskProfiler = TP.TaskProfiler()
def logTaskProfiles(self, name=None):
if self._taskProfiler:
self._taskProfiler.logProfiles(name)
def flushTaskProfiles(self, name=None):
if self._taskProfiler:
self._taskProfiler.flush(name)
def _setProfileTask(self, task):
if self._taskProfileInfo.session:
self._taskProfileInfo.session.release()
self._taskProfileInfo.session = None
self._taskProfileInfo = ScratchPad(
taskFunc = task.getFunction(),
taskArgs = task.getArgs(),
task = task,
profiled = False,
session = None,
)
# Temporarily replace the task's own function with our
# _profileTask method.
task.setFunction(self._profileTask)
task.setArgs([self._taskProfileInfo], True)
def _profileTask(self, profileInfo, task):
# This is called instead of the task function when we have
# decided to profile a task.
assert profileInfo.task == task
# don't profile the same task twice in a row
assert not profileInfo.profiled
# Restore the task's proper function for next time.
appendTask = False
taskArgs = profileInfo.taskArgs
if taskArgs and taskArgs[-1] == task:
appendTask = True
taskArgs = taskArgs[:-1]
task.setArgs(taskArgs, appendTask)
task.setFunction(profileInfo.taskFunc)
# Defer this import until we need it: some Python
# distributions don't provide the profile and pstats modules.
PS = importlib.import_module('direct.showbase.ProfileSession')
profileSession = PS.ProfileSession('profiled-task-%s' % task.getName(),
Functor(profileInfo.taskFunc, *profileInfo.taskArgs))
ret = profileSession.run()
# set these values *after* profiling in case we're profiling the TaskProfiler
profileInfo.session = profileSession
profileInfo.profiled = True
return ret
def _hasProfiledDesignatedTask(self):
# have we run a profile of the designated task yet?
return self._taskProfileInfo.profiled
def _getLastTaskProfileSession(self):
return self._taskProfileInfo.session
def _getRandomTask(self):
# Figure out when the next frame is likely to expire, so we
# won't grab any tasks that are sleeping for a long time.
now = self.globalClock.getFrameTime()
avgFrameRate = self.globalClock.getAverageFrameRate()
if avgFrameRate < .00001:
avgFrameDur = 0.
else:
avgFrameDur = (1. / self.globalClock.getAverageFrameRate())
next = now + avgFrameDur
# Now grab a task at random, until we find one that we like.
tasks = self.mgr.getTasks()
i = random.randrange(tasks.getNumTasks())
task = tasks.getTask(i)
while not isinstance(task, PythonTask) or \
task.getWakeTime() > next:
tasks.removeTask(i)
i = random.randrange(tasks.getNumTasks())
task = tasks.getTask(i)
return task
def __repr__(self):
return str(self.mgr)
# In the event we want to do frame time managment, this is the
# function to replace or overload.
def doYield(self, frameStartTime, nextScheduledTaskTime):
pass
"""
def doYieldExample(self, frameStartTime, nextScheduledTaskTime):
minFinTime = frameStartTime + self.MaxEpochSpeed
if nextScheduledTaskTime > 0 and nextScheduledTaskTime < minFinTime:
print ' Adjusting Time'
minFinTime = nextScheduledTaskTime
delta = minFinTime - self.globalClock.getRealTime()
while(delta > 0.002):
print ' sleep %s'% (delta)
time.sleep(delta)
delta = minFinTime - self.globalClock.getRealTime()
"""
if __debug__:
# to catch memory leaks during the tests at the bottom of the file
def _startTrackingMemLeaks(self):
pass
def _stopTrackingMemLeaks(self):
pass
def _checkMemLeaks(self):
pass
def _runTests(self):
if __debug__:
tm = TaskManager()
tm.setClock(ClockObject())
tm.setupTaskChain("default", tickClock = True)
# check for memory leaks after every test
tm._startTrackingMemLeaks()
tm._checkMemLeaks()
# run-once task
l = []
def _testDone(task, l=l):
l.append(None)
return task.done
tm.add(_testDone, 'testDone')
tm.step()
assert len(l) == 1
tm.step()
assert len(l) == 1
_testDone = None
tm._checkMemLeaks()
# remove by name
def _testRemoveByName(task):
return task.done
tm.add(_testRemoveByName, 'testRemoveByName')
assert tm.remove('testRemoveByName') == 1
assert tm.remove('testRemoveByName') == 0
_testRemoveByName = None
tm._checkMemLeaks()
# duplicate named tasks
def _testDupNamedTasks(task):
return task.done
tm.add(_testDupNamedTasks, 'testDupNamedTasks')
tm.add(_testDupNamedTasks, 'testDupNamedTasks')
assert tm.remove('testRemoveByName') == 0
_testDupNamedTasks = None
tm._checkMemLeaks()
# continued task
l = []
def _testCont(task, l = l):
l.append(None)
return task.cont
tm.add(_testCont, 'testCont')
tm.step()
assert len(l) == 1
tm.step()
assert len(l) == 2
tm.remove('testCont')
_testCont = None
tm._checkMemLeaks()
# continue until done task
l = []
def _testContDone(task, l = l):
l.append(None)
if len(l) >= 2:
return task.done
else:
return task.cont
tm.add(_testContDone, 'testContDone')
tm.step()
assert len(l) == 1
tm.step()
assert len(l) == 2
tm.step()
assert len(l) == 2
assert not tm.hasTaskNamed('testContDone')
_testContDone = None
tm._checkMemLeaks()
# hasTaskNamed
def _testHasTaskNamed(task):
return task.done
tm.add(_testHasTaskNamed, 'testHasTaskNamed')
assert tm.hasTaskNamed('testHasTaskNamed')
tm.step()
assert not tm.hasTaskNamed('testHasTaskNamed')
_testHasTaskNamed = None
tm._checkMemLeaks()
# task sort
l = []
def _testPri1(task, l = l):
l.append(1)
return task.cont
def _testPri2(task, l = l):
l.append(2)
return task.cont
tm.add(_testPri1, 'testPri1', sort = 1)
tm.add(_testPri2, 'testPri2', sort = 2)
tm.step()
assert len(l) == 2
assert l == [1, 2,]
tm.step()
assert len(l) == 4
assert l == [1, 2, 1, 2,]
tm.remove('testPri1')
tm.remove('testPri2')
_testPri1 = None
_testPri2 = None
tm._checkMemLeaks()
# task extraArgs
l = []
def _testExtraArgs(arg1, arg2, l=l):
l.extend([arg1, arg2,])
return done
tm.add(_testExtraArgs, 'testExtraArgs', extraArgs=[4,5])
tm.step()
assert len(l) == 2
assert l == [4, 5,]
_testExtraArgs = None
tm._checkMemLeaks()
# task appendTask
l = []
def _testAppendTask(arg1, arg2, task, l=l):
l.extend([arg1, arg2,])
return task.done
tm.add(_testAppendTask, '_testAppendTask', extraArgs=[4,5], appendTask=True)
tm.step()
assert len(l) == 2
assert l == [4, 5,]
_testAppendTask = None
tm._checkMemLeaks()
# task uponDeath
l = []
def _uponDeathFunc(task, l=l):
l.append(task.name)
def _testUponDeath(task):
return done
tm.add(_testUponDeath, 'testUponDeath', uponDeath=_uponDeathFunc)
tm.step()
assert len(l) == 1
assert l == ['testUponDeath']
_testUponDeath = None
_uponDeathFunc = None
tm._checkMemLeaks()
# task owner
class _TaskOwner:
def _addTask(self, task):
self.addedTaskName = task.name
def _clearTask(self, task):
self.clearedTaskName = task.name
to = _TaskOwner()
l = []
def _testOwner(task):
return done
tm.add(_testOwner, 'testOwner', owner=to)
tm.step()
assert getattr(to, 'addedTaskName', None) == 'testOwner'
assert getattr(to, 'clearedTaskName', None) == 'testOwner'
_testOwner = None
del to
_TaskOwner = None
tm._checkMemLeaks()
doLaterTests = [0,]
# doLater
l = []
def _testDoLater1(task, l=l):
l.append(1)
def _testDoLater2(task, l=l):
l.append(2)
def _monitorDoLater(task, tm=tm, l=l, doLaterTests=doLaterTests):
if task.time > .03:
assert l == [1, 2,]
doLaterTests[0] -= 1
return task.done
return task.cont
tm.doMethodLater(.01, _testDoLater1, 'testDoLater1')
tm.doMethodLater(.02, _testDoLater2, 'testDoLater2')
doLaterTests[0] += 1
# make sure we run this task after the doLaters if they all occur on the same frame
tm.add(_monitorDoLater, 'monitorDoLater', sort=10)
_testDoLater1 = None
_testDoLater2 = None
_monitorDoLater = None
# don't check until all the doLaters are finished
#tm._checkMemLeaks()
# doLater sort
l = []
def _testDoLaterPri1(task, l=l):
l.append(1)
def _testDoLaterPri2(task, l=l):
l.append(2)
def _monitorDoLaterPri(task, tm=tm, l=l, doLaterTests=doLaterTests):
if task.time > .02:
assert l == [1, 2,]
doLaterTests[0] -= 1
return task.done
return task.cont
tm.doMethodLater(.01, _testDoLaterPri1, 'testDoLaterPri1', sort=1)
tm.doMethodLater(.01, _testDoLaterPri2, 'testDoLaterPri2', sort=2)
doLaterTests[0] += 1
# make sure we run this task after the doLaters if they all occur on the same frame
tm.add(_monitorDoLaterPri, 'monitorDoLaterPri', sort=10)
_testDoLaterPri1 = None
_testDoLaterPri2 = None
_monitorDoLaterPri = None
# don't check until all the doLaters are finished
#tm._checkMemLeaks()
# doLater extraArgs
l = []
def _testDoLaterExtraArgs(arg1, l=l):
l.append(arg1)
def _monitorDoLaterExtraArgs(task, tm=tm, l=l, doLaterTests=doLaterTests):
if task.time > .02:
assert l == [3,]
doLaterTests[0] -= 1
return task.done
return task.cont
tm.doMethodLater(.01, _testDoLaterExtraArgs, 'testDoLaterExtraArgs', extraArgs=[3,])
doLaterTests[0] += 1
# make sure we run this task after the doLaters if they all occur on the same frame
tm.add(_monitorDoLaterExtraArgs, 'monitorDoLaterExtraArgs', sort=10)
_testDoLaterExtraArgs = None
_monitorDoLaterExtraArgs = None
# don't check until all the doLaters are finished
#tm._checkMemLeaks()
# doLater appendTask
l = []
def _testDoLaterAppendTask(arg1, task, l=l):
assert task.name == 'testDoLaterAppendTask'
l.append(arg1)
def _monitorDoLaterAppendTask(task, tm=tm, l=l, doLaterTests=doLaterTests):
if task.time > .02:
assert l == [4,]
doLaterTests[0] -= 1
return task.done
return task.cont
tm.doMethodLater(.01, _testDoLaterAppendTask, 'testDoLaterAppendTask',
extraArgs=[4,], appendTask=True)
doLaterTests[0] += 1
# make sure we run this task after the doLaters if they all occur on the same frame
tm.add(_monitorDoLaterAppendTask, 'monitorDoLaterAppendTask', sort=10)
_testDoLaterAppendTask = None
_monitorDoLaterAppendTask = None
# don't check until all the doLaters are finished
#tm._checkMemLeaks()
# doLater uponDeath
l = []
def _testUponDeathFunc(task, l=l):
assert task.name == 'testDoLaterUponDeath'
l.append(10)
def _testDoLaterUponDeath(arg1, l=l):
return done
def _monitorDoLaterUponDeath(task, tm=tm, l=l, doLaterTests=doLaterTests):
if task.time > .02:
assert l == [10,]
doLaterTests[0] -= 1
return task.done
return task.cont
tm.doMethodLater(.01, _testDoLaterUponDeath, 'testDoLaterUponDeath',
uponDeath=_testUponDeathFunc)
doLaterTests[0] += 1
# make sure we run this task after the doLaters if they all occur on the same frame
tm.add(_monitorDoLaterUponDeath, 'monitorDoLaterUponDeath', sort=10)
_testUponDeathFunc = None
_testDoLaterUponDeath = None
_monitorDoLaterUponDeath = None
# don't check until all the doLaters are finished
#tm._checkMemLeaks()
# doLater owner
class _DoLaterOwner:
def _addTask(self, task):
self.addedTaskName = task.name
def _clearTask(self, task):
self.clearedTaskName = task.name
doLaterOwner = _DoLaterOwner()
l = []
def _testDoLaterOwner(l=l):
pass
def _monitorDoLaterOwner(task, tm=tm, l=l, doLaterOwner=doLaterOwner,
doLaterTests=doLaterTests):
if task.time > .02:
assert getattr(doLaterOwner, 'addedTaskName', None) == 'testDoLaterOwner'
assert getattr(doLaterOwner, 'clearedTaskName', None) == 'testDoLaterOwner'
doLaterTests[0] -= 1
return task.done
return task.cont
tm.doMethodLater(.01, _testDoLaterOwner, 'testDoLaterOwner',
owner=doLaterOwner)
doLaterTests[0] += 1
# make sure we run this task after the doLaters if they all occur on the same frame
tm.add(_monitorDoLaterOwner, 'monitorDoLaterOwner', sort=10)
_testDoLaterOwner = None
_monitorDoLaterOwner = None
del doLaterOwner
_DoLaterOwner = None
# don't check until all the doLaters are finished
#tm._checkMemLeaks()
# run the doLater tests
while doLaterTests[0] > 0:
tm.step()
del doLaterTests
tm._checkMemLeaks()
# getTasks
def _testGetTasks(task):
return task.cont
# No doLaterProcessor in the new world.
assert len(tm.getTasks()) == 0
tm.add(_testGetTasks, 'testGetTasks1')
assert len(tm.getTasks()) == 1
assert (tm.getTasks()[0].name == 'testGetTasks1' or
tm.getTasks()[1].name == 'testGetTasks1')
tm.add(_testGetTasks, 'testGetTasks2')
tm.add(_testGetTasks, 'testGetTasks3')
assert len(tm.getTasks()) == 3
tm.remove('testGetTasks2')
assert len(tm.getTasks()) == 2
tm.remove('testGetTasks1')
tm.remove('testGetTasks3')
assert len(tm.getTasks()) == 0
_testGetTasks = None
tm._checkMemLeaks()
# getDoLaters
def _testGetDoLaters():
pass
assert len(tm.getDoLaters()) == 0
tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater1')
assert len(tm.getDoLaters()) == 1
assert tm.getDoLaters()[0].name == 'testDoLater1'
tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater2')
tm.doMethodLater(.1, _testGetDoLaters, 'testDoLater3')
assert len(tm.getDoLaters()) == 3
tm.remove('testDoLater2')
assert len(tm.getDoLaters()) == 2
tm.remove('testDoLater1')
tm.remove('testDoLater3')
assert len(tm.getDoLaters()) == 0
_testGetDoLaters = None
tm._checkMemLeaks()
# duplicate named doLaters removed via taskMgr.remove
def _testDupNameDoLaters():
pass
# the doLaterProcessor is always running
tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
tm.doMethodLater(.1, _testDupNameDoLaters, 'testDupNameDoLater')
assert len(tm.getDoLaters()) == 2
tm.remove('testDupNameDoLater')
assert len(tm.getDoLaters()) == 0
_testDupNameDoLaters = None
tm._checkMemLeaks()
# duplicate named doLaters removed via remove()
def _testDupNameDoLatersRemove():
pass
# the doLaterProcessor is always running
dl1 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
dl2 = tm.doMethodLater(.1, _testDupNameDoLatersRemove, 'testDupNameDoLaterRemove')
assert len(tm.getDoLaters()) == 2
dl2.remove()
assert len(tm.getDoLaters()) == 1
dl1.remove()
assert len(tm.getDoLaters()) == 0
_testDupNameDoLatersRemove = None
# nameDict etc. isn't cleared out right away with task.remove()
tm._checkMemLeaks()
# getTasksNamed
def _testGetTasksNamed(task):
return task.cont
assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
tm.add(_testGetTasksNamed, 'testGetTasksNamed')
assert len(tm.getTasksNamed('testGetTasksNamed')) == 1
assert tm.getTasksNamed('testGetTasksNamed')[0].name == 'testGetTasksNamed'
tm.add(_testGetTasksNamed, 'testGetTasksNamed')
tm.add(_testGetTasksNamed, 'testGetTasksNamed')
assert len(tm.getTasksNamed('testGetTasksNamed')) == 3
tm.remove('testGetTasksNamed')
assert len(tm.getTasksNamed('testGetTasksNamed')) == 0
_testGetTasksNamed = None
tm._checkMemLeaks()
# removeTasksMatching
def _testRemoveTasksMatching(task):
return task.cont
tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching')
assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 1
tm.removeTasksMatching('testRemoveTasksMatching')
assert len(tm.getTasksNamed('testRemoveTasksMatching')) == 0
tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1')
tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2')
assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 1
assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 1
tm.removeTasksMatching('testRemoveTasksMatching*')
assert len(tm.getTasksNamed('testRemoveTasksMatching1')) == 0
assert len(tm.getTasksNamed('testRemoveTasksMatching2')) == 0
tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching1a')
tm.add(_testRemoveTasksMatching, 'testRemoveTasksMatching2a')
assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 1
assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 1
tm.removeTasksMatching('testRemoveTasksMatching?a')
assert len(tm.getTasksNamed('testRemoveTasksMatching1a')) == 0
assert len(tm.getTasksNamed('testRemoveTasksMatching2a')) == 0
_testRemoveTasksMatching = None
tm._checkMemLeaks()
# create Task object and add to mgr
l = []
def _testTaskObj(task, l=l):
l.append(None)
return task.cont
t = Task(_testTaskObj)
tm.add(t, 'testTaskObj')
tm.step()
assert len(l) == 1
tm.step()
assert len(l) == 2
tm.remove('testTaskObj')
tm.step()
assert len(l) == 2
_testTaskObj = None
tm._checkMemLeaks()
# remove Task via task.remove()
l = []
def _testTaskObjRemove(task, l=l):
l.append(None)
return task.cont
t = Task(_testTaskObjRemove)
tm.add(t, 'testTaskObjRemove')
tm.step()
assert len(l) == 1
tm.step()
assert len(l) == 2
t.remove()
tm.step()
assert len(l) == 2
del t
_testTaskObjRemove = None
tm._checkMemLeaks()
"""
# this test fails, and it's not clear what the correct behavior should be.
# sort passed to Task.__init__ is always overridden by taskMgr.add()
# even if no sort is specified, and calling Task.setSort() has no
# effect on the taskMgr's behavior.
# set/get Task sort
l = []
def _testTaskObjSort(arg, task, l=l):
l.append(arg)
return task.cont
t1 = Task(_testTaskObjSort, sort=1)
t2 = Task(_testTaskObjSort, sort=2)
tm.add(t1, 'testTaskObjSort1', extraArgs=['a',], appendTask=True)
tm.add(t2, 'testTaskObjSort2', extraArgs=['b',], appendTask=True)
tm.step()
assert len(l) == 2
assert l == ['a', 'b']
assert t1.getSort() == 1
assert t2.getSort() == 2
t1.setSort(3)
assert t1.getSort() == 3
tm.step()
assert len(l) == 4
assert l == ['a', 'b', 'b', 'a',]
t1.remove()
t2.remove()
tm.step()
assert len(l) == 4
del t1
del t2
_testTaskObjSort = None
tm._checkMemLeaks()
"""
del l
tm.destroy()
del tm
if __debug__:
def checkLeak():
import sys
import gc
gc.enable()
from direct.showbase.DirectObject import DirectObject
class TestClass(DirectObject):
def doTask(self, task):
return task.done
obj = TestClass()
startRefCount = sys.getrefcount(obj)
print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
print('** addTask')
t = obj.addTask(obj.doTask, 'test')
print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
print('task.getRefCount(): %s' % t.getRefCount())
print('** removeTask')
obj.removeTask('test')
print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
print('task.getRefCount(): %s' % t.getRefCount())
print('** step')
taskMgr.step()
taskMgr.step()
taskMgr.step()
print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
print('task.getRefCount(): %s' % t.getRefCount())
print('** task release')
t = None
print('sys.getrefcount(obj): %s' % sys.getrefcount(obj))
assert sys.getrefcount(obj) == startRefCount
| {
"content_hash": "ea875bfc644620199d5eb6198b68f104",
"timestamp": "",
"source": "github",
"line_count": 1282,
"max_line_length": 117,
"avg_line_length": 38.968798751950075,
"alnum_prop": 0.5783458104808039,
"repo_name": "tobspr/panda3d",
"id": "215b240d16fcf9b688968ba911a3e379d888076b",
"size": "49958",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "direct/src/task/Task.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4004"
},
{
"name": "C",
"bytes": "6724918"
},
{
"name": "C++",
"bytes": "25480688"
},
{
"name": "Emacs Lisp",
"bytes": "229264"
},
{
"name": "Groff",
"bytes": "3106"
},
{
"name": "HTML",
"bytes": "8081"
},
{
"name": "Java",
"bytes": "3113"
},
{
"name": "JavaScript",
"bytes": "7003"
},
{
"name": "Logos",
"bytes": "5504"
},
{
"name": "MAXScript",
"bytes": "1745"
},
{
"name": "NSIS",
"bytes": "92320"
},
{
"name": "Nemerle",
"bytes": "4403"
},
{
"name": "Objective-C",
"bytes": "28865"
},
{
"name": "Objective-C++",
"bytes": "257446"
},
{
"name": "Perl",
"bytes": "206982"
},
{
"name": "Perl6",
"bytes": "30484"
},
{
"name": "Puppet",
"bytes": "2627"
},
{
"name": "Python",
"bytes": "5537773"
},
{
"name": "R",
"bytes": "421"
},
{
"name": "Shell",
"bytes": "55940"
},
{
"name": "Visual Basic",
"bytes": "136"
}
],
"symlink_target": ""
} |
'use strict';
var bcrypt = require('bcrypt');
exports.genSalt = function genSlat (rounds) {
return function (cb) {
return bcrypt.genSalt(rounds, cb);
}
};
exports.hash = function hash (value, salt) {
return function (cb) {
return bcrypt.hash(value, salt, cb);
}
};
exports.compare = function compare (value, hash) {
return function (cb) {
return bcrypt.compare(value, hash, cb);
}
};
| {
"content_hash": "3808b59b1ba5279f6ac705dcdd780a80",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 50,
"avg_line_length": 20.761904761904763,
"alnum_prop": 0.6146788990825688,
"repo_name": "elementron/elementron",
"id": "8e89b976be9888c62e6d69c9619d89d3b464b51a",
"size": "436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/util/bcrypt.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6975"
},
{
"name": "HTML",
"bytes": "64257"
},
{
"name": "JavaScript",
"bytes": "76810"
},
{
"name": "Shell",
"bytes": "1669"
}
],
"symlink_target": ""
} |
FROM docker.io/richarvey/nginx-php-fpm:latest
# Add application artifacts
ADD userguide/. /var/app/userguide/
ADD scripts/* /var/scripts/
# Install the requirements
RUN apk update && \
apk add postgresql-dev && \
docker-php-ext-install pdo pdo_pgsql && \
mkdir /var/app/userguide/data && \
ls -la /var/app/userguide && \
chmod 755 /var/scripts && \
chown -R nginx:nginx /var/app/userguide
ENV WEBROOT='/var/app'
ENV DATA_DIR='/var/app/userguide/data'
ENV SCRIPTS_DIR='/var/scripts'
ENV RUN_SCRIPTS='1'
| {
"content_hash": "c8a5ada4bb830553ebe8806a25e08401",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 45,
"avg_line_length": 27.842105263157894,
"alnum_prop": 0.6899810964083176,
"repo_name": "haiku/userguide-translator",
"id": "37a274a2c7097be9828b90a350c0e78b8e780557",
"size": "529",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12371"
},
{
"name": "Dockerfile",
"bytes": "529"
},
{
"name": "HTML",
"bytes": "20846"
},
{
"name": "Hack",
"bytes": "31"
},
{
"name": "JavaScript",
"bytes": "15896"
},
{
"name": "Makefile",
"bytes": "253"
},
{
"name": "PHP",
"bytes": "137005"
},
{
"name": "Shell",
"bytes": "656"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_271) on Tue Jun 07 11:07:31 CEST 2022 -->
<title>DataModel.NoPrimaryKeyException (Jailer Subsetter API)</title>
<meta name="date" content="2022-06-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DataModel.NoPrimaryKeyException (Jailer Subsetter API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/DataModel.NoPrimaryKeyException.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/sf/jailer/datamodel/DataModel.ColumnOrderPriority.html" title="enum in net.sf.jailer.datamodel"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../net/sf/jailer/datamodel/DataModel.XmlSettings.html" title="class in net.sf.jailer.datamodel"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/sf/jailer/datamodel/DataModel.NoPrimaryKeyException.html" target="_top">Frames</a></li>
<li><a href="DataModel.NoPrimaryKeyException.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#methods.inherited.from.class.java.lang.Throwable">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">net.sf.jailer.datamodel</div>
<h2 title="Class DataModel.NoPrimaryKeyException" class="title">Class DataModel.NoPrimaryKeyException</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Throwable</li>
<li>
<ul class="inheritance">
<li>java.lang.Exception</li>
<li>
<ul class="inheritance">
<li>java.lang.RuntimeException</li>
<li>
<ul class="inheritance">
<li>net.sf.jailer.datamodel.DataModel.NoPrimaryKeyException</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable</dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../net/sf/jailer/datamodel/DataModel.html" title="class in net.sf.jailer.datamodel">DataModel</a></dd>
</dl>
<hr>
<br>
<pre>public static class <span class="typeNameLabel">DataModel.NoPrimaryKeyException</span>
extends java.lang.RuntimeException</pre>
<div class="block">Thrown if a table has no primary key.</div>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../serialized-form.html#net.sf.jailer.datamodel.DataModel.NoPrimaryKeyException">Serialized Form</a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../net/sf/jailer/datamodel/Table.html" title="class in net.sf.jailer.datamodel">Table</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../net/sf/jailer/datamodel/DataModel.NoPrimaryKeyException.html#table">table</a></span></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../net/sf/jailer/datamodel/DataModel.NoPrimaryKeyException.html#NoPrimaryKeyException-net.sf.jailer.datamodel.Table-">NoPrimaryKeyException</a></span>(<a href="../../../../net/sf/jailer/datamodel/Table.html" title="class in net.sf.jailer.datamodel">Table</a> table)</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../net/sf/jailer/datamodel/DataModel.NoPrimaryKeyException.html#NoPrimaryKeyException-net.sf.jailer.datamodel.Table-java.lang.String-">NoPrimaryKeyException</a></span>(<a href="../../../../net/sf/jailer/datamodel/Table.html" title="class in net.sf.jailer.datamodel">Table</a> table,
java.lang.String message)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Throwable">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Throwable</h3>
<code>addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="table">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>table</h4>
<pre>public final <a href="../../../../net/sf/jailer/datamodel/Table.html" title="class in net.sf.jailer.datamodel">Table</a> table</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="NoPrimaryKeyException-net.sf.jailer.datamodel.Table-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>NoPrimaryKeyException</h4>
<pre>public NoPrimaryKeyException(<a href="../../../../net/sf/jailer/datamodel/Table.html" title="class in net.sf.jailer.datamodel">Table</a> table,
java.lang.String message)</pre>
</li>
</ul>
<a name="NoPrimaryKeyException-net.sf.jailer.datamodel.Table-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>NoPrimaryKeyException</h4>
<pre>public NoPrimaryKeyException(<a href="../../../../net/sf/jailer/datamodel/Table.html" title="class in net.sf.jailer.datamodel">Table</a> table)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/DataModel.NoPrimaryKeyException.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../net/sf/jailer/datamodel/DataModel.ColumnOrderPriority.html" title="enum in net.sf.jailer.datamodel"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../net/sf/jailer/datamodel/DataModel.XmlSettings.html" title="class in net.sf.jailer.datamodel"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?net/sf/jailer/datamodel/DataModel.NoPrimaryKeyException.html" target="_top">Frames</a></li>
<li><a href="DataModel.NoPrimaryKeyException.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#methods.inherited.from.class.java.lang.Throwable">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "68e8b688c8b218d1ee7424c7d843301c",
"timestamp": "",
"source": "github",
"line_count": 322,
"max_line_length": 360,
"avg_line_length": 37.22049689440994,
"alnum_prop": 0.6324572382144347,
"repo_name": "Wisser/Jailer",
"id": "646f7894cdc096d3193008eab511af09c99fe451",
"size": "11985",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/api/net/sf/jailer/datamodel/DataModel.NoPrimaryKeyException.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5128"
},
{
"name": "CSS",
"bytes": "476"
},
{
"name": "HTML",
"bytes": "5533"
},
{
"name": "Java",
"bytes": "5221254"
},
{
"name": "NSIS",
"bytes": "2899"
},
{
"name": "SQLPL",
"bytes": "1376"
},
{
"name": "Shell",
"bytes": "7708"
}
],
"symlink_target": ""
} |
using autofill::PasswordForm;
using content::BrowserThread;
// Handles requests to WebDataService.
class PasswordStoreWin::DBHandler : public WebDataServiceConsumer {
public:
DBHandler(WebDataService* web_data_service,
PasswordStoreWin* password_store)
: web_data_service_(web_data_service),
password_store_(password_store) {
}
~DBHandler();
// Requests the IE7 login for |form|. This is async. |callback_runner| will be
// run when complete.
void GetIE7Login(
const PasswordForm& form,
const PasswordStoreWin::ConsumerCallbackRunner& callback_runner);
private:
struct RequestInfo {
RequestInfo() {}
RequestInfo(PasswordForm* request_form,
const PasswordStoreWin::ConsumerCallbackRunner& runner)
: form(request_form),
callback_runner(runner) {}
PasswordForm* form;
PasswordStoreWin::ConsumerCallbackRunner callback_runner;
};
// Holds info associated with in-flight GetIE7Login requests.
typedef std::map<WebDataService::Handle, RequestInfo> PendingRequestMap;
// Gets logins from IE7 if no others are found. Also copies them into
// Chrome's WebDatabase so we don't need to look next time.
std::vector<autofill::PasswordForm*> GetIE7Results(
const WDTypedResult* result,
const PasswordForm& form);
// WebDataServiceConsumer implementation.
virtual void OnWebDataServiceRequestDone(
WebDataService::Handle handle,
const WDTypedResult* result) OVERRIDE;
scoped_refptr<WebDataService> web_data_service_;
// This creates a cycle between us and PasswordStore. The cycle is broken
// from PasswordStoreWin::Shutdown, which deletes us.
scoped_refptr<PasswordStoreWin> password_store_;
PendingRequestMap pending_requests_;
DISALLOW_COPY_AND_ASSIGN(DBHandler);
};
PasswordStoreWin::DBHandler::~DBHandler() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
for (PendingRequestMap::const_iterator i = pending_requests_.begin();
i != pending_requests_.end();
++i) {
web_data_service_->CancelRequest(i->first);
delete i->second.form;
}
}
void PasswordStoreWin::DBHandler::GetIE7Login(
const PasswordForm& form,
const PasswordStoreWin::ConsumerCallbackRunner& callback_runner) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
IE7PasswordInfo info;
info.url_hash =
ie7_password::GetUrlHash(base::UTF8ToWide(form.origin.spec()));
WebDataService::Handle handle = web_data_service_->GetIE7Login(info, this);
pending_requests_[handle] =
RequestInfo(new PasswordForm(form), callback_runner);
}
std::vector<PasswordForm*> PasswordStoreWin::DBHandler::GetIE7Results(
const WDTypedResult *result,
const PasswordForm& form) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
std::vector<PasswordForm*> matching_forms;
const WDResult<IE7PasswordInfo>* r =
static_cast<const WDResult<IE7PasswordInfo>*>(result);
IE7PasswordInfo info = r->GetValue();
if (!info.encrypted_data.empty()) {
// We got a result.
// Delete the entry. If it's good we will add it to the real saved password
// table.
web_data_service_->RemoveIE7Login(info);
std::vector<ie7_password::DecryptedCredentials> credentials;
std::wstring url = base::ASCIIToWide(form.origin.spec());
if (ie7_password::DecryptPasswords(url,
info.encrypted_data,
&credentials)) {
for (size_t i = 0; i < credentials.size(); ++i) {
PasswordForm* autofill = new PasswordForm();
autofill->username_value = credentials[i].username;
autofill->password_value = credentials[i].password;
autofill->signon_realm = form.signon_realm;
autofill->origin = form.origin;
autofill->preferred = true;
autofill->ssl_valid = form.origin.SchemeIsSecure();
autofill->date_created = info.date_created;
matching_forms.push_back(autofill);
// Add this PasswordForm to the saved password table. We're on the DB
// thread already, so we use AddLoginImpl.
password_store_->AddLoginImpl(*autofill);
}
}
}
return matching_forms;
}
void PasswordStoreWin::DBHandler::OnWebDataServiceRequestDone(
WebDataService::Handle handle,
const WDTypedResult* result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
PendingRequestMap::iterator i = pending_requests_.find(handle);
DCHECK(i != pending_requests_.end());
scoped_ptr<PasswordForm> form(i->second.form);
PasswordStoreWin::ConsumerCallbackRunner callback_runner(
i->second.callback_runner);
pending_requests_.erase(i);
if (!result) {
// The WDS returns NULL if it is shutting down. Run callback with empty
// result.
callback_runner.Run(std::vector<autofill::PasswordForm*>());
return;
}
DCHECK_EQ(PASSWORD_IE7_RESULT, result->GetType());
std::vector<autofill::PasswordForm*> matched_forms =
GetIE7Results(result, *form);
callback_runner.Run(matched_forms);
}
PasswordStoreWin::PasswordStoreWin(
scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner,
scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner,
LoginDatabase* login_database,
WebDataService* web_data_service)
: PasswordStoreDefault(main_thread_runner,
db_thread_runner,
login_database) {
db_handler_.reset(new DBHandler(web_data_service, this));
}
PasswordStoreWin::~PasswordStoreWin() {
}
void PasswordStoreWin::ShutdownOnDBThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
db_handler_.reset();
}
void PasswordStoreWin::Shutdown() {
BrowserThread::PostTask(
BrowserThread::DB, FROM_HERE,
base::Bind(&PasswordStoreWin::ShutdownOnDBThread, this));
PasswordStoreDefault::Shutdown();
}
void PasswordStoreWin::GetIE7LoginIfNecessary(
const PasswordForm& form,
const ConsumerCallbackRunner& callback_runner,
const std::vector<autofill::PasswordForm*>& matched_forms) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
if (matched_forms.empty() && db_handler_.get()) {
db_handler_->GetIE7Login(form, callback_runner);
} else {
// No need to get IE7 login.
callback_runner.Run(matched_forms);
}
}
void PasswordStoreWin::GetLoginsImpl(
const PasswordForm& form,
AuthorizationPromptPolicy prompt_policy,
const ConsumerCallbackRunner& callback_runner) {
ConsumerCallbackRunner get_ie7_login =
base::Bind(&PasswordStoreWin::GetIE7LoginIfNecessary,
this, form, callback_runner);
PasswordStoreDefault::GetLoginsImpl(form, prompt_policy, get_ie7_login);
}
| {
"content_hash": "e46370224253e9c5a38ba2582e6eae00",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 80,
"avg_line_length": 34.50769230769231,
"alnum_prop": 0.701441521771437,
"repo_name": "anirudhSK/chromium",
"id": "c50509b793857d2e52cf26c7b266d5acb08fc520",
"size": "7379",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/browser/password_manager/password_store_win.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "52960"
},
{
"name": "Awk",
"bytes": "8660"
},
{
"name": "C",
"bytes": "42502191"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "201859263"
},
{
"name": "CSS",
"bytes": "946557"
},
{
"name": "DOT",
"bytes": "2984"
},
{
"name": "Java",
"bytes": "5687122"
},
{
"name": "JavaScript",
"bytes": "22163714"
},
{
"name": "M",
"bytes": "2190"
},
{
"name": "Matlab",
"bytes": "2496"
},
{
"name": "Objective-C",
"bytes": "7670589"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "672770"
},
{
"name": "Python",
"bytes": "10873885"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Shell",
"bytes": "1315894"
},
{
"name": "Tcl",
"bytes": "277091"
},
{
"name": "TypeScript",
"bytes": "1560024"
},
{
"name": "XSLT",
"bytes": "13493"
},
{
"name": "nesC",
"bytes": "15206"
}
],
"symlink_target": ""
} |
@class DBTEAMLOGOutdatedLinkViewReportFailedType;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - API Object
///
/// The `OutdatedLinkViewReportFailedType` struct.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBTEAMLOGOutdatedLinkViewReportFailedType : NSObject <DBSerializable, NSCopying>
#pragma mark - Instance fields
/// (no description).
@property (nonatomic, readonly, copy) NSString *description_;
#pragma mark - Constructors
///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param description_ (no description).
///
/// @return An initialized instance.
///
- (instancetype)initWithDescription_:(NSString *)description_;
- (instancetype)init NS_UNAVAILABLE;
@end
#pragma mark - Serializer Object
///
/// The serialization class for the `OutdatedLinkViewReportFailedType` struct.
///
@interface DBTEAMLOGOutdatedLinkViewReportFailedTypeSerializer : NSObject
///
/// Serializes `DBTEAMLOGOutdatedLinkViewReportFailedType` instances.
///
/// @param instance An instance of the
/// `DBTEAMLOGOutdatedLinkViewReportFailedType` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBTEAMLOGOutdatedLinkViewReportFailedType` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMLOGOutdatedLinkViewReportFailedType *)instance;
///
/// Deserializes `DBTEAMLOGOutdatedLinkViewReportFailedType` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBTEAMLOGOutdatedLinkViewReportFailedType` API object.
///
/// @return An instantiation of the `DBTEAMLOGOutdatedLinkViewReportFailedType`
/// object.
///
+ (DBTEAMLOGOutdatedLinkViewReportFailedType *)deserialize:(NSDictionary<NSString *, id> *)dict;
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "332ba96db9bb8ef7ab801c7acf3613bd",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 107,
"avg_line_length": 28.19402985074627,
"alnum_prop": 0.7691900476442562,
"repo_name": "dropbox/dropbox-sdk-obj-c",
"id": "66a538d3efbb98c9910dce85e89502f97faa402a",
"size": "2075",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/TeamLog/Headers/DBTEAMLOGOutdatedLinkViewReportFailedType.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1288"
},
{
"name": "CSS",
"bytes": "6608"
},
{
"name": "Objective-C",
"bytes": "18903013"
},
{
"name": "Python",
"bytes": "7087"
},
{
"name": "Ruby",
"bytes": "1819"
},
{
"name": "Shell",
"bytes": "4527"
}
],
"symlink_target": ""
} |
<!--
Copyright (C) 2015 The Android Open Source Project
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.
--><!-- Master layout. -->
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="56dp"
android:orientation="vertical">
<!-- Header: Day, Date -->
<TextView
android:id="@+id/detail_day_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:minWidth="120dp"
android:textSize="24sp" />
<TextView
android:id="@+id/detail_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:textColor="@color/grey_700"
android:textSize="20sp" />
</LinearLayout>
<!-- Main content: high, low, art, weather state -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:orientation="vertical">
<TextView
android:id="@+id/detail_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:textSize="96sp" />
<TextView
android:id="@+id/detail_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:textColor="@color/grey_700"
android:textSize="48sp" />
<!-- Humidity, wind, pressure -->
<TextView
android:id="@+id/detail_humidity_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:fontFamily="sans-serif-condensed"
android:textAppearance="?android:textAppearanceLarge" />
<TextView
android:id="@+id/detail_pressure_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:fontFamily="sans-serif-condensed"
android:textAppearance="?android:textAppearanceLarge" />
<TextView
android:id="@+id/detail_wind_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:fontFamily="sans-serif-condensed"
android:textAppearance="?android:textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="@+id/detail_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
<TextView
android:id="@+id/detail_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:textAppearance="?android:textAppearanceLarge"
android:textColor="@color/grey_700" />
</LinearLayout>
</LinearLayout>
</ScrollView> | {
"content_hash": "b8ef405d0f62ef9423ed7690ef9ea3be",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 77,
"avg_line_length": 40.131147540983605,
"alnum_prop": 0.5812908496732027,
"repo_name": "ThomasJacob-IdentityMine/SunshineV2",
"id": "4feba315c11713d8ff2ff94ee119fb4e039bb59c",
"size": "4896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/fragment_detail_wide.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "168255"
}
],
"symlink_target": ""
} |
namespace NorthWind
{
using System;
using System.Collections.Generic;
public partial class Sales_by_Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string ProductName { get; set; }
public Nullable<decimal> ProductSales { get; set; }
}
}
| {
"content_hash": "e25c6fd86a58703d02a6f8cca4876e69",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 59,
"avg_line_length": 26.23076923076923,
"alnum_prop": 0.6275659824046921,
"repo_name": "StoikoNeykov/Telerik",
"id": "1ca152f584da66fab63ccec005ab9e201dba2207",
"size": "765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DataBase/11. Entity Framework/NorthWind/Sales_by_Category.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2432895"
},
{
"name": "CSS",
"bytes": "38164"
},
{
"name": "HTML",
"bytes": "109867"
},
{
"name": "JavaScript",
"bytes": "657282"
},
{
"name": "Smalltalk",
"bytes": "634"
},
{
"name": "XSLT",
"bytes": "3526"
}
],
"symlink_target": ""
} |
var Board = require("./board"),
Pin = require("./pin.js"),
lcdCharacters = require("./lcd-chars.js"),
converter = require("color-convert")();
var priv = new Map();
/**
* This atrocitity is unfortunately necessary.
* If any other approach can be found, patches
* will gratefully be accepted.
*/
function sleep(ms) {
var start = Date.now();
while (Date.now() < start + ms) {}
}
// TODO: Migrate this to the new codified Expander class.
//
// - add portMode to PCF8574 controller
// - add portWrite to PCF8574 controller
//
//
// TODO: Investigate adding the above methods to
// all expander controllers.
//
function Expander(address, io) {
this.address = address;
this.mask = 0xFF;
this.shadow = 0x00;
this.io = io;
}
Expander.prototype.pinMode = function(pin, dir) {
if (dir === 0x01) {
this.mask &= ~(1 << pin);
} else {
this.mask |= 1 << pin;
}
};
Expander.prototype.portMode = function(dir) {
this.mask = dir === 0x00 ? 0xFF : 0x00;
};
Expander.prototype.write = function(value) {
this.shadow = value & ~(this.mask);
this.io.i2cWrite(this.address, this.shadow);
};
// const-caps throughout serve to indicate the
// "const-ness" of the binding to the reader
// and nothing more.
var OPS = {
DEFAULT: {
SHIFT_LEFT: 0x04,
CLEAR: 0x01,
HOME: 0x02,
ENTRY: 0x04,
DISPLAY: 0x08,
DIMENSIONS: 0x20,
CURSORSHIFT: 0x10,
SETCGRAMADDR: 0x40,
SETDDRAMADDR: 0x80,
// Command And Control
DATA: 0x40,
COMMAND: 0x80,
// flags for display entry mode
ENTRYRIGHT: 0x00,
ENTRYLEFT: 0x02,
ENTRYSHIFTINCREMENT: 0x01,
ENTRYSHIFTDECREMENT: 0x00,
// flags for display on/off control
DISPLAYON: 0x04,
DISPLAYOFF: 0x00,
CURSORON: 0x02,
CURSOROFF: 0x00,
BLINKON: 0x01,
BLINKOFF: 0x00,
// flags for display/cursor shift
DISPLAYMOVE: 0x08,
CURSORMOVE: 0x00,
MOVERIGHT: 0x04,
MOVELEFT: 0x00,
// flags for function set
BITMODE: {
4: 0x00,
8: 0x10,
},
LINE: {
1: 0x00,
2: 0x08
},
DOTS: {
"5x10": 0x04,
"5x8": 0x00
},
// flags for backlight control
BACKLIGHT_ON: 0x08,
BACKLIGHT_OFF: 0x00,
MEMORYLIMIT: 0x08,
// Control
// Enable
EN: 0x04,
// Read/Write
RW: 0x02,
// Register Select
RS: 0x01,
// DATA
D4: 0x04,
D5: 0x05,
D6: 0x06,
D7: 0x07,
}
};
var Controllers = {
JHD1313M1: {
OP: {
value: OPS.DEFAULT,
},
CHARS: {
value: lcdCharacters.DEFAULT,
},
initialize: {
value: function(opts) {
this.io.i2cConfig(opts);
this.lines = opts.lines || 2;
this.rows = opts.rows || 2;
this.cols = opts.cols || 16;
this.dots = opts.dots || "5x8";
// LCD: 0x3E
// RGB: 0x62
this.address = {
lcd: opts.address || 0x3E,
rgb: 0x62
};
var display = this.OP.DISPLAY | this.OP.DISPLAYON | this.OP.CURSOROFF | this.OP.BLINKOFF;
var state = {
display: display,
characters: {},
index: this.OP.MEMORYLIMIT - 1,
backlight: {
polarity: 1,
pin: null,
value: null
}
};
priv.set(this, state);
// Operations within the following labelled block are init-only,
// but _do_ block the process negligible number of milliseconds.
blocking: {
var lines = this.OP.DIMENSIONS | this.OP.LINE[2];
// Copied from Grove Studio lib.
// SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
// according to datasheet, we need at least 40ms after
// power rises above 2.7V before sending commands.
// Arduino can turn on way befer 4.5V so we'll wait 50
sleep(50);
this.command(lines);
sleep(5);
this.command(lines);
this.command(lines);
this.command(lines);
sleep(5);
this.command(
this.OP.ENTRY |
this.OP.ENTRYLEFT |
this.OP.ENTRYSHIFTDECREMENT
);
this.on();
this.clear();
this.home();
}
// Backlight initialization
this.io.i2cWrite(this.address.rgb, [0, 0]);
this.io.i2cWrite(this.address.rgb, [1, 0]);
this.io.i2cWrite(this.address.rgb, [0x08, 0xAA]);
this.bgColor(opts.color || "white");
},
},
clear: {
value: function() {
return this.command(this.OP.CLEAR);
}
},
setCursor: {
value: function(col, row) {
return this.command(row === 0 ? col | 0x80 : col | 0xc0);
}
},
bgColor: {
value: function(r, g, b) {
var rgb = [r, g, b];
if (arguments.length === 1) {
if (Array.isArray(r)) {
rgb = r;
}
if (typeof r === "string") {
rgb = converter.keyword(r).rgb();
}
}
[0x04, 0x03, 0x02].forEach(function(cmd, i) {
this.io.i2cWrite(this.address.rgb, [cmd, rgb[i]]);
}, this);
return this;
}
},
command: {
value: function(mode, value) {
if (arguments.length === 1) {
value = mode;
mode = this.OP.COMMAND;
}
if (mode === this.OP.DATA) {
return this.send(value);
}
return this.writeBits(this.OP.COMMAND, value);
}
},
send: {
value: function(value) {
return this.writeBits(this.OP.DATA, value);
}
},
writeBits: {
value: function(mode, value) {
this.io.i2cWrite(this.address.lcd, [mode, value]);
return this;
}
},
hilo: {
value: function(callback) {
callback.call(this);
}
},
},
PCF8574: {
OP: {
value: Object.assign({}, OPS.DEFAULT, {
COMMAND: 0x00,
DATA: 0x01,
BACKLIGHT_ON: 0xFF,
BACKLIGHT_OFF: 0X00
}),
},
CHARS: {
value: lcdCharacters.DEFAULT,
},
initialize: {
value: function(opts) {
this.io.i2cConfig(opts);
this.bitMode = opts.bitMode || 4;
this.lines = opts.lines || 2;
this.rows = opts.rows || 2;
this.cols = opts.cols || 16;
this.dots = opts.dots || "5x8";
if (!opts.address) {
opts.address = ["PCF8574A", "PCF8574AT"].includes(opts.controller) ?
0x3F : 0x27;
/*
| A2 | A1 | A0 | PCF8574(T) | PCF8574A(T) |
|----|----|----|---------|----------|
| L | L | L | 0x20 | 0x38 |
| L | L | H | 0x21 | 0x39 |
| L | H | L | 0x22 | 0x3A |
| L | H | H | 0x23 | 0x3B |
| H | L | L | 0x24 | 0x3C |
| H | L | H | 0x25 | 0x3D |
| H | H | L | 0x26 | 0x3E |
| H | H | H | 0x27 | 0x3F |
TODO: move to API docs
*/
}
this.address = {
lcd: opts.address
};
// Ported from https://bitbucket.org/fmalpartida/new-liquidcrystal
this.expander = new Expander(this.address.lcd, this.io);
this.expander.portMode(this.io.MODES.OUTPUT);
this.expander.write(0);
var backlight = opts.backlight || {
polarity: 0,
pin: 3
};
backlight.pin = typeof backlight.pin === "undefined" ? 3 : backlight.pin;
backlight.polarity = typeof backlight.polarity === "undefined" ? 0 : backlight.polarity;
var dimensions = this.OP.BITMODE[this.bitMode] |
this.OP.LINE[this.lines] |
this.OP.DOTS[this.dots];
var display = this.OP.DISPLAY |
this.OP.DISPLAYON |
this.OP.CURSOROFF |
this.OP.BLINKOFF;
var entry = this.OP.ENTRYLEFT |
this.OP.ENTRYSHIFTDECREMENT;
var state = {
display: display,
characters: {},
index: this.OP.MEMORYLIMIT - 1,
backlight: {
polarity: backlight.polarity,
pinMask: 1 << backlight.pin,
statusMask: 0x00
},
data: [
1 << this.OP.D4,
1 << this.OP.D5,
1 << this.OP.D6,
1 << this.OP.D7
]
};
priv.set(this, state);
// Operations within the following labelled block are init-only,
// but _do_ block the process for negligible number of milliseconds.
blocking: {
//
// Toggle wrte/pulse to reset the LCD component.
//
this.expander.write(0x03 << this.OP.SHIFT_LEFT);
this.pulse(0x03 << this.OP.SHIFT_LEFT);
sleep(4);
this.expander.write(0x03 << this.OP.SHIFT_LEFT);
this.pulse(0x03 << this.OP.SHIFT_LEFT);
sleep(4);
this.expander.write(0x03 << this.OP.SHIFT_LEFT);
this.pulse(0x03 << this.OP.SHIFT_LEFT);
this.expander.write(0x02 << this.OP.SHIFT_LEFT);
this.pulse(0x02 << this.OP.SHIFT_LEFT);
// Initialize the reset component
this.command(this.OP.DIMENSIONS | dimensions);
this.on();
this.clear();
this.command(this.OP.ENTRY | entry);
this.backlight();
}
},
},
clear: {
value: function() {
this.command(this.OP.CLEAR);
sleep(2);
return this;
}
},
backlight: {
value: function(value) {
var state = priv.get(this);
var mask;
value = typeof value === "undefined" ? 255 : value;
if (state.backlight.pinMask !== 0x00) {
if ((state.backlight.polarity === 0 && value > 0) ||
(state.backlight.polarity === 1 && value === 0)) {
mask = 0xFF;
} else {
mask = 0x00;
}
state.backlight.statusMask = state.backlight.pinMask & mask;
this.expander.write(state.backlight.statusMask);
}
return this;
}
},
createChar: {
value: function(name, charMap) {
var state = priv.get(this);
var address;
if (typeof name === "number") {
address = name & 0x07;
} else {
address = state.index;
state.index--;
if (state.index === -1) {
state.index = this.OP.MEMORYLIMIT - 1;
}
}
this.command(this.OP.SETCGRAMADDR | (address << 3));
blocking: {
sleep(1);
for (var i = 0; i < 8; i++) {
this.command(this.OP.DATA, charMap[i]);
sleep(1);
}
}
state.characters[name] = address;
return address;
}
},
noBacklight: {
value: function() {
this.backlight(0);
}
},
hilo: {
value: function(callback) {
callback.call(this);
}
},
command: {
value: function(mode, value) {
if (arguments.length === 1) {
value = mode;
mode = this.OP.COMMAND;
}
this.send(mode, value);
return this;
}
},
send: {
writable: true,
value: function(mode, value) {
this.writeBits(mode, value >> 4);
this.writeBits(mode, value & 0x0F);
return this;
}
},
writeBits: {
writable: true,
value: function(mode, value) {
var state = priv.get(this);
var pinMapValue = 0;
for (var i = 0; i < 4; i++) {
if ((value & 0x01) === 1) {
pinMapValue |= state.data[i];
}
value = (value >> 1);
}
if (mode === this.OP.DATA) {
mode = this.OP.RS;
}
pinMapValue |= mode | state.backlight.statusMask;
this.pulse(pinMapValue);
return this;
}
},
pulse: {
writable: true,
value: function(data) {
this.expander.write(data | this.OP.EN); // En HIGH
this.expander.write(data & ~this.OP.EN); // En LOW
}
}
},
PARALLEL: {
OP: {
value: OPS.DEFAULT,
},
CHARS: {
value: lcdCharacters.DEFAULT,
},
initialize: {
value: function(opts) {
this.bitMode = opts.bitMode || 4;
this.lines = opts.lines || 2;
this.rows = opts.rows || 2;
this.cols = opts.cols || 16;
this.dots = opts.dots || "5x8";
if (Array.isArray(opts.pins)) {
this.pins = {
rs: opts.pins[0],
en: opts.pins[1],
// TODO: Move to device map profile
data: [
opts.pins[5],
opts.pins[4],
opts.pins[3],
opts.pins[2]
]
};
} else {
this.pins = opts.pins;
}
var display = this.OP.DISPLAY | this.OP.DISPLAYON;
var state = {
display: display,
characters: {},
index: this.OP.MEMORYLIMIT - 1,
backlight: {
polarity: 1,
pin: null,
value: null
}
};
priv.set(this, state);
opts.pins.forEach(function(pin) {
this.io.pinMode(pin, 1);
}, this);
this.io.digitalWrite(this.pins.rs, this.io.LOW);
this.io.digitalWrite(this.pins.en, this.io.LOW);
if (opts.backlight) {
if (typeof opts.backlight === "number") {
var temp = opts.backlight;
opts.backlight = {
pin: temp
};
}
if (opts.backlight.pin) {
state.backlight.pin = new Pin({
pin: opts.backlight.pin,
board: this.board
});
state.backlight.pin.high();
}
}
// Operations within the following labelled block are init-only,
// but _do_ block the process negligible number of milliseconds.
blocking: {
// Send 0b00000011 thrice to make sure LCD
// is initialized properly
this.command(0x03);
sleep(4);
this.command(0x03);
sleep(4);
this.command(0x03);
// Switch to 4-bit mode
if (this.bitMode === 4) {
// this.OP.DIMENSIONS |
this.command(0x02);
}
// Set number of lines and dots
// TODO: Move to device map profile
this.command(
this.OP.LINE[this.lines] |
this.OP.DOTS[this.dots]
);
// Clear display and turn it on
this.command(display);
this.clear();
this.home();
}
}
}
}
};
// Alias controllers
Controllers.HD44780 = Controllers.JHD1313M1;
Controllers.LCM1602 = Controllers.LCD1602 = Controllers.LCM1602IIC = Controllers.LCD2004 = Controllers.PCF8574A = Controllers.PCF8574AT = Controllers.PCF8574T = Controllers.PCF8574;
Controllers.MJKDZ = Object.assign({}, Controllers.PCF8574, {
OP: {
value: Object.assign({}, OPS.DEFAULT, {
SHIFT_LEFT: 0x00,
COMMAND: 0x00,
DATA: 0x06,
// Control
// Enable
EN: 0x10,
// Read/Write
RW: 0x05,
// Register Select
RS: 0x06,
D4: 0x00,
D5: 0x01,
D6: 0x02,
D7: 0x03
})
},
writeBits: {
writable: true,
value: function(mode, value) {
var state = priv.get(this);
var pinMapValue = 0;
for (var i = 0; i < 4; i++) {
if ((value & 0x01) === 1) {
pinMapValue |= state.data[i];
}
value = (value >> 1);
}
if (mode === this.OP.DATA) {
mode = (1 << this.OP.RS);
}
pinMapValue |= mode | state.backlight.statusMask;
this.pulse(pinMapValue);
return this;
}
},
});
/**
* LCD
* @param {[type]} opts [description]
*/
function LCD(opts) {
if (!(this instanceof LCD)) {
return new LCD(opts);
}
Board.Component.call(
this, opts = Board.Options(opts)
);
var controller;
if (opts.controller) {
controller = typeof opts.controller === "string" ?
Controllers[opts.controller.toUpperCase()] :
opts.controller;
}
if (!controller) {
controller = Controllers.PARALLEL;
}
Board.Controller.call(this, controller, opts);
this.ctype = opts.controller;
if (this.initialize) {
this.initialize(opts);
}
}
LCD.prototype.command = function(mode, value) {
if (typeof value === "undefined") {
value = mode;
mode = 0x80;
}
if (this.bitMode === 4) {
this.send(value >> 4);
}
this.send(value);
return this;
};
LCD.prototype.send = function(value) {
var pin = 0;
var mask = {
4: 8,
8: 128
}[this.bitMode];
for (; mask > 0; mask = mask >> 1) {
this.io.digitalWrite(
this.pins.data[pin],
this.io[value & mask ? "HIGH" : "LOW"]
);
pin++;
}
["LOW", "HIGH", "LOW"].forEach(function(val) {
this.io.digitalWrite(this.pins.en, this.io[val]);
}, this);
return this;
};
LCD.prototype.hilo = function(callback) {
// RS High for write mode
this.io.digitalWrite(this.pins.rs, this.io.HIGH);
callback.call(this);
// RS Low for command mode
this.io.digitalWrite(this.pins.rs, this.io.LOW);
};
var RE_SPECIALS = /:(\w+):/g;
LCD.prototype.print = function(message, opts) {
var state, dontProcessSpecials, hasCharacters, processed;
message = message + "";
opts = opts || {};
state = priv.get(this);
dontProcessSpecials = opts.dontProcessSpecials || false;
hasCharacters = !dontProcessSpecials && RE_SPECIALS.test(message);
if (message.length === 1) {
this.hilo(function() {
this.command(this.OP.DATA, message.charCodeAt(0));
});
} else {
if (hasCharacters) {
processed = message.replace(RE_SPECIALS, function(match, name) {
var address = state.characters[name];
return typeof address === "number" ? String.fromCharCode(address) : match;
});
this.print(processed, {
dontProcessSpecials: true
});
} else {
this.hilo(function() {
Array.from(message).forEach(function(character) {
this.command(this.OP.DATA, character.charCodeAt(0));
}, this);
});
}
}
return this;
};
LCD.prototype.write = function(charCode) {
this.hilo.call(this, function() {
this.command(this.OP.DATA, charCode);
});
return this;
};
LCD.prototype.clear = function() {
this.command(this.OP.CLEAR);
sleep(2);
return this;
};
LCD.prototype.home = function() {
this.command(this.OP.HOME);
sleep(2);
return this;
};
LCD.prototype.setCursor = function(col, row) {
var rowOffsets = [0x00, 0x40, 0x14, 0x54];
this.command(this.OP.SETDDRAMADDR | (col + rowOffsets[row]));
return this;
};
LCD.prototype.backlight = function(highOrLow) {
var state = priv.get(this);
highOrLow = typeof highOrLow === "undefined" ? true : false;
if (state.backlight.pin instanceof Pin) {
if (highOrLow) {
state.backlight.pin.high();
} else {
state.backlight.pin.low();
}
}
if (highOrLow) {
state.display |= this.OP.DISPLAYON;
} else {
state.display &= ~this.OP.DISPLAYON;
}
this.command(state.display);
return this;
};
LCD.prototype.noBacklight = function() {
var state = priv.get(this);
if (state.backlight.pin instanceof Pin) {
state.backlight.pin.high();
}
// if (highOrLow) {
// state.display |= this.OP.DISPLAYON;
// } else {
// state.display &= ~this.OP.DISPLAYON;
// }
// this.command(state.display);
return this.backlight(false);
};
LCD.prototype.on = function() {
var state = priv.get(this);
state.display |= this.OP.DISPLAYON;
this.command(state.display);
return this;
};
LCD.prototype.off = function() {
var state = priv.get(this);
state.display &= ~this.OP.DISPLAYON;
this.command(state.display);
return this;
};
LCD.prototype.cursor = function(row, col) {
// When provided with col & row, cursor will behave like setCursor,
// except that it has row and col in the order that most people
// intuitively expect it to be in.
if (typeof col !== "undefined" && typeof row !== "undefined") {
return this.setCursor(col, row);
}
var state = priv.get(this);
state.display |= this.OP.CURSORON;
this.command(state.display);
return this;
};
LCD.prototype.noCursor = function() {
var state = priv.get(this);
state.display &= ~this.OP.CURSORON;
this.command(state.display);
return this;
};
LCD.prototype.blink = function() {
var state = priv.get(this);
state.display |= this.OP.BLINKON;
this.command(state.display);
return this;
};
LCD.prototype.noBlink = function() {
var state = priv.get(this);
state.display &= ~this.OP.BLINKON;
this.command(state.display);
return this;
};
LCD.prototype.autoscroll = function() {
var state = priv.get(this);
state.display |= this.OP.ENTRYSHIFTINCREMENT;
this.command(this.OP.ENTRY | state.display);
return this;
};
LCD.prototype.noAutoscroll = function() {
var state = priv.get(this);
state.display &= ~this.OP.ENTRYSHIFTINCREMENT;
this.command(this.OP.ENTRY | state.display);
return this;
};
LCD.prototype.createChar = function(name, charMap) {
// Ensure location is never above 7
var state = priv.get(this);
var address;
if (typeof name === "number") {
address = name & 0x07;
} else {
address = state.index;
state.index--;
if (state.index === -1) {
state.index = this.OP.MEMORYLIMIT - 1;
}
}
this.command(this.OP.SETCGRAMADDR | (address << 3));
this.hilo(function() {
for (var i = 0; i < 8; i++) {
this.command(this.OP.DATA, charMap[i]);
}
});
// Fill in address
state.characters[name] = address;
return address;
};
LCD.prototype.useChar = function(name) {
var state = priv.get(this);
if (!state.characters[name]) {
// Create the character in LCD memory and
// Add character to current LCD character map
state.characters[name] = this.createChar(name, this.CHARS[name]);
}
return this;
};
/**
*
TODO:
burst()
scrollDisplayLeft()
scrollDisplayRight()
leftToRight()
rightToLeft()
*/
LCD.POSITIVE = 0;
LCD.NEGATIVE = 1;
LCD.Characters = lcdCharacters;
module.exports = LCD;
| {
"content_hash": "24cde972bb3fa334efba3cf74962a21b",
"timestamp": "",
"source": "github",
"line_count": 1025,
"max_line_length": 181,
"avg_line_length": 21.85560975609756,
"alnum_prop": 0.5352200696366396,
"repo_name": "MaxZoosk/johnny-five-build-light",
"id": "09d3f204ff076438fd5d4e6737ff79f5e8fe477b",
"size": "22402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/johnny-five/lib/lcd.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "873"
},
{
"name": "Shell",
"bytes": "356"
}
],
"symlink_target": ""
} |
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from contests.models import Contest, Tag
class Quiz(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=25, unique=True)
description = models.CharField(max_length=256, blank=True)
tags = models.ManyToManyField(Tag)
score = models.IntegerField(editable=False, default=0)
# make score dependent on problems contained or some final normalized score
DIFF_CHOICES = (('n00b', 'n00b'), ('Easy', 'Easy'), ('Medium', 'Medium'), ('Hard', 'Hard'), ('1337', '1337'))
difficulty = models.CharField(max_length=10, choices=DIFF_CHOICES)
contest = models.ForeignKey(Contest, on_delete=models.CASCADE, null=True, blank=True)
creators = models.ManyToManyField(User)
hidden = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.name)
class Question(models.Model):
question = models.CharField(max_length=256)
slug = models.SlugField(max_length=16, unique=True)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
hints = models.CharField(max_length=256, blank=True)
tags = models.ManyToManyField(Tag)
score = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.slug)
class SimpleQuestion(Question):
answer = models.CharField(max_length=64)
is_mcq = models.BooleanField(default=False, editable=False)
class MCQ(Question):
choices = models.CharField(choices=[], max_length=256)
answer = models.IntegerField()
is_mcq = models.BooleanField(default=True, editable=False)
@classmethod
def create(cls, question, slug, hints, choices, correct, score, quiz):
CHOICES = [(index, item) for index, item in enumerate(choices)]
mcq = cls(question=question, slug=slug, hints=hints, choices=CHOICES, correct=correct, answer=answer, score=score, quiz=quiz)
return mcq
class QuestionAdmin(admin.ModelAdmin):
list_display = ('quiz', 'question', 'score', 'created', 'modified')
search_fields = ('quiz', 'question')
list_filter = ('tags', 'score', 'modified', 'created')
ordering = ['score', 'modified', 'created']
class SimpleQuestionAdmin(QuestionAdmin):
pass
class MCQAdmin(QuestionAdmin):
pass
class QuizAdmin(admin.ModelAdmin):
list_display = ('name', 'score', 'contest', 'hidden', 'created', 'modified')
search_fields = ('name', 'description', 'contest')
raw_id_fields = ('creators',)
list_filter = ('tags', 'score', 'modified', 'created', 'creators')
ordering = ['name', 'score', 'creators', 'modified', 'created']
| {
"content_hash": "72e17e59a784e8f7031df6e0939ef468",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 133,
"avg_line_length": 34.795180722891565,
"alnum_prop": 0.6897506925207756,
"repo_name": "super1337/Super1337-CTF",
"id": "598fdc716edc2ca8253985f5a63883f30b30566b",
"size": "2888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "questionnaire/models.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "151967"
},
{
"name": "HTML",
"bytes": "77118"
},
{
"name": "JavaScript",
"bytes": "151922"
},
{
"name": "Python",
"bytes": "41684"
}
],
"symlink_target": ""
} |
package mtail
import (
"fmt"
"runtime"
"testing"
)
func TestBuildInfo(t *testing.T) {
buildInfo := BuildInfo{
Branch: "foo",
Version: "bar",
Revision: "baz",
}
buildInfoWant := fmt.Sprintf(
"mtail version bar git revision baz go version %s go arch %s go os %s",
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
)
buildInfoGot := buildInfo.String()
if buildInfoWant != buildInfoGot {
t.Errorf("Unexpected build info string, want: %q, got: %q", buildInfoWant, buildInfoGot)
}
}
| {
"content_hash": "fc6278e96daba7738829d4f3ae4e7d7b",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 90,
"avg_line_length": 18.85185185185185,
"alnum_prop": 0.6699410609037328,
"repo_name": "SuperQ/mtail",
"id": "ec4665b29610ac96b3d82892c20e730da2b293b7",
"size": "613",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "internal/mtail/mtail_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "445"
},
{
"name": "Dockerfile",
"bytes": "1234"
},
{
"name": "Emacs Lisp",
"bytes": "3487"
},
{
"name": "Go",
"bytes": "655333"
},
{
"name": "Makefile",
"bytes": "9265"
},
{
"name": "Shell",
"bytes": "1631"
},
{
"name": "Yacc",
"bytes": "12302"
}
],
"symlink_target": ""
} |
package pt.org.apec.services.users.common.json
import play.api.libs.json._
import play.api.libs.functional.syntax._
import pt.org.apec.services.users.common._
trait JsonProtocol {
implicit val userREgistrationFormat = Json.format[UserRegistration]
implicit val userCredentialsFormat = Json.format[UserCredentials]
implicit val authenticationResultReads: Reads[AuthenticationResult] = {
implicit val authenticationSuccessReads = Json.reads[AuthenticationSuccess]
implicit val authenticationPasswordExpiredReads = Json.reads[AuthenticationPasswordExpired]
implicit val authenticationNotActiveReads = Json.reads[AuthenticationNotActive]
(__ \ "success").read[AuthenticationSuccess].map(_.asInstanceOf[AuthenticationResult]) |
(__ \ "failure").read(AuthenticationFailure.asInstanceOf[AuthenticationResult]) |
(__ \ "notActive").read[AuthenticationNotActive].map(_.asInstanceOf[AuthenticationResult]) |
(__ \ "passwordExpired").read[AuthenticationPasswordExpired].map(_.asInstanceOf[AuthenticationResult])
}
implicit val authenticationResultWrites = Writes[AuthenticationResult] { result =>
implicit val authenticationSuccessWrites = Json.writes[AuthenticationSuccess]
implicit val authenticationNotActiveWrites = Json.writes[AuthenticationNotActive]
implicit val authenticationPasswordExpiredWrites = Json.writes[AuthenticationPasswordExpired]
result match {
case s: AuthenticationSuccess => Writes.at[AuthenticationSuccess](__ \ "success").writes(s)
case n: AuthenticationNotActive => Writes.at[AuthenticationNotActive](__ \ "notActive").writes(n)
case e: AuthenticationPasswordExpired => Writes.at[AuthenticationPasswordExpired](__ \ "passwordExpired").writes(e)
case AuthenticationFailure => Writes.at[JsValue](__ \ "failure").writes(JsObject.apply(Seq.empty))
}
}
implicit val userRegistrationSuccessFormat = Json.format[UserRegistrationSuccess]
implicit val userRegistrationResultWrites: Writes[UserRegistrationResult] = Writes[UserRegistrationResult] { result =>
result match {
case s: UserRegistrationSuccess => userRegistrationSuccessFormat.writes(s)
case _ => ???
}
}
} | {
"content_hash": "a080d78682bce584425fee8eff70f3c7",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 121,
"avg_line_length": 56.256410256410255,
"alnum_prop": 0.7739288969917958,
"repo_name": "ragb/apec-users-service",
"id": "634647703b661b4d9ae20c68458c4b064eb5679c",
"size": "2194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/src/main/scala/pt/org/apec/services/users/common/json/JsonProtocol.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "22730"
}
],
"symlink_target": ""
} |
module ProblemsHelper
def problem_confirm
Errbit::Config.confirm_resolve_err === false ? nil : 'Seriously?'
end
def truncated_problem_message(problem)
unless (msg = problem.message).blank?
# Truncate & insert invisible chars so that firefox can emulate 'word-wrap: break-word' CSS rule
truncate(msg, :length => 300).scan(/.{1,5}/).map { |s| h(s) }.join("​").html_safe
end
end
def gravatar_tag(email, options = {})
image_tag gravatar_url(email, options), :alt => email, :class => 'gravatar'
end
def gravatar_url(email, options = {})
default_options = {
:d => Errbit::Config.gravatar_default,
}
options.reverse_merge! default_options
params = options.extract!(:s, :d).delete_if { |k, v| v.blank? }
email_hash = Digest::MD5.hexdigest(email)
"http://www.gravatar.com/avatar/#{email_hash}?#{params.to_query}"
end
end
| {
"content_hash": "2fbfefb952e7e2d805007b1069336eaa",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 102,
"avg_line_length": 33.18518518518518,
"alnum_prop": 0.6473214285714286,
"repo_name": "smonsalve/lacasona-errbit",
"id": "0e0c8070ccff3093f2714f184d2c6e1ee86c1399",
"size": "896",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/helpers/problems_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "77042"
},
{
"name": "Ruby",
"bytes": "278284"
}
],
"symlink_target": ""
} |
Add folders to your current project by right clicking on them in the tree view

| {
"content_hash": "e804cf376764ca5c3aed766aafdbdedf",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 78,
"avg_line_length": 42,
"alnum_prop": 0.7698412698412699,
"repo_name": "forivall/atom-promote-folder-to-project",
"id": "97b81da2e9fc43ce61a7f671f2eca95046595d80",
"size": "163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "2093"
}
],
"symlink_target": ""
} |
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
print("Request:")
print(json.dumps(req, indent=4))
res = processRequest(req)
res = json.dumps(res, indent=4)
# print(res)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
if req.get("result").get("action") != "yahooWeatherForecast":
return {}
baseurl = "https://query.yahooapis.com/v1/public/yql?"
yql_query = makeYqlQuery(req)
if yql_query is None:
return {}
yql_url = baseurl + urllib.urlencode({'q': yql_query}) + "&format=json"
print(yql_url)
result = urllib.urlopen(yql_url).read()
print("yql result: ")
print(result)
data = json.loads(result)
res = makeWebhookResult(data)
return res
def makeYqlQuery(req):
result = req.get("result")
parameters = result.get("parameters")
city = parameters.get("geo-city")
if city is None:
return None
return "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='" + city + "')"
def makeWebhookResult(data):
query = data.get('query')
if query is None:
return {}
result = query.get('results')
if result is None:
return {}
channel = result.get('channel')
if channel is None:
return {}
item = channel.get('item')
location = channel.get('location')
units = channel.get('units')
if (location is None) or (item is None) or (units is None):
return {}
condition = item.get('condition')
if condition is None:
return {}
# print(json.dumps(item, indent=4))
speech = "Today in " + location.get('city') + ": " + condition.get('text') + \
", the temperature is " + condition.get('temp') + " " + units.get('temperature')
print("Response:")
print(speech)
slack_message = {
"text": speech,
"attachments": [
{
"title": channel.get('title'),
"title_link": channel.get('link'),
"color": "#36a64f",
"fields": [
{
"title": "Condition",
"value": "Temp " + condition.get('temp') +
" " + units.get('temperature'),
"short": "false"
},
{
"title": "Wind",
"value": "Speed: " + channel.get('wind').get('speed') +
", direction: " + channel.get('wind').get('direction'),
"short": "true"
},
{
"title": "Atmosphere",
"value": "Humidity " + channel.get('atmosphere').get('humidity') +
" pressure " + channel.get('atmosphere').get('pressure'),
"short": "true"
}
],
"thumb_url": "http://l.yimg.com/a/i/us/we/52/" + condition.get('code') + ".gif"
}
]
}
print(json.dumps(slack_message))
return {
"speech": speech,
"displayText": speech,
"data": {"slack": slack_message},
# "contextOut": [],
"source": "apiai-weather-webhook-sample"
}
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
print "Starting app on port %d" % port
app.run(debug=False, port=port, host='0.0.0.0')
| {
"content_hash": "efd0626fc5d2f39a13a935781cbbe4b4",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 118,
"avg_line_length": 27.280575539568346,
"alnum_prop": 0.509493670886076,
"repo_name": "isitkonferensen2016/isitkonferensen2016",
"id": "ab5c747b034b9007be5ae86c5b7c9c988e4f37d8",
"size": "3815",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3815"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.PostEditor.ContentSources;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
/// <summary>
/// The WYSIWYG editor mangles some types of HTML. When we detect
/// such chunks of HTML, we wrap them in a <span class="wlWriterPreserve">...</span>
/// and save the original contents for later. Whenever pulling data
/// out of the WYSIWYG editor, we go back and restore those spans to
/// their original state.
/// </summary>
public class HtmlPreserver
{
public const string PRESERVE_CLASS = "wlWriterPreserve";
private readonly Dictionary<string, string> preserved = new Dictionary<string, string>();
public HtmlPreserver()
{
}
public void Reset()
{
preserved.Clear();
}
public string ScanAndPreserve(string html)
{
StringBuilder sb = new StringBuilder(html.Length);
SimpleHtmlParser p = new SimpleHtmlParser(html);
Element e;
while (null != (e = p.Next()))
{
if (!(e is BeginTag))
{
sb.Append(html, e.Offset, e.Length);
continue;
}
BeginTag bt = (BeginTag)e;
if (bt.NameEquals("div"))
{
switch (bt.GetAttributeValue("class"))
{
case ContentSourceManager.EDITABLE_SMART_CONTENT:
case ContentSourceManager.SMART_CONTENT:
sb.Append(html, e.Offset, e.Length);
sb.Append(p.CollectHtmlUntil("div"));
sb.Append("</div>");
continue;
}
}
if (!(bt.NameEquals("object")
|| bt.NameEquals("embed")
|| bt.NameEquals("noembed")
|| bt.NameEquals("script")))
{
sb.Append(html, e.Offset, e.Length);
continue;
}
else
{
string collected = p.CollectHtmlUntil(bt.Name);
string preserve = bt.RawText + collected + "</" + bt.Name + ">";
string preserveId = Guid.NewGuid().ToString("N");
preserved[preserveId] = preserve;
sb.AppendFormat("<span id=\"preserve{0}\" class=\"{1}\">", preserveId, PRESERVE_CLASS);
sb.Append(preserve);
sb.Append("</span>");
}
}
return sb.ToString();
}
public string RestorePreserved(string html)
{
StringBuilder sb = new StringBuilder();
HtmlExtractor ex = new HtmlExtractor(html);
int pos = 0;
while (ex.Seek("<span class='" + PRESERVE_CLASS + "'>").Success)
{
sb.Append(html, pos, ex.Element.Offset - pos);
pos = ex.Element.Offset;
BeginTag bt = (BeginTag)ex.Element;
string elementId = bt.GetAttributeValue("id");
Match m = Regex.Match(elementId ?? "", @"^preserve([a-zA-Z0-9]+)$");
if (m.Success)
{
string preserveId = m.Groups[1].Value;
string preservedValue;
if (preserved.TryGetValue(preserveId, out preservedValue))
{
sb.Append(preservedValue);
ex.CollectTextUntil("span");
if (ex.Element == null)
pos = html.Length;
else
pos = ex.Parser.Position;
}
}
}
sb.Append(html, pos, html.Length - pos);
return sb.ToString();
}
}
}
| {
"content_hash": "808bddeb493da5f8136bd91a908e7c2c",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 107,
"avg_line_length": 36.06956521739131,
"alnum_prop": 0.4720347155255545,
"repo_name": "timheuer/OpenLiveWriter-1",
"id": "87104cac7c9ff089ccafc2eaac719e495b44564e",
"size": "4289",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/managed/OpenLiveWriter.PostEditor/PostHtmlEditing/HtmlPreserver.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4499"
},
{
"name": "C",
"bytes": "3658"
},
{
"name": "C#",
"bytes": "17275134"
},
{
"name": "C++",
"bytes": "47615"
},
{
"name": "CSS",
"bytes": "1124"
},
{
"name": "HTML",
"bytes": "44830"
},
{
"name": "JavaScript",
"bytes": "432"
},
{
"name": "Smalltalk",
"bytes": "18056"
},
{
"name": "XSLT",
"bytes": "6823"
}
],
"symlink_target": ""
} |
@!(model, intf)
var @(model.Service.toLowerCase()) = {};
module.exports = @(model.Service.toLowerCase());
@for(var i=0; i<model.Types.length; i++) {
@{ var typ=model.Types[i];
var typPrms=Object.getOwnPropertyNames(typ.Parameters);}
@(model.Service.toLowerCase()).@(typ.Name) = function _@(typ.Name)() {
var that={};
@for(var p=0;p<typPrms.length;p++){
@{var prm=typ.Parameters[typPrms[p]];}
this.@(prm.Name)=null;
}
return that;
}
} | {
"content_hash": "7b8f24b3606a7d5a97cc5f369378362d",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 70,
"avg_line_length": 25.055555555555557,
"alnum_prop": 0.6407982261640798,
"repo_name": "rravuri/tidl_noderestify",
"id": "33f088ba32e5eccb29cd0482db8ed9a902a8446b",
"size": "451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/$.Service$_types.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "17354"
}
],
"symlink_target": ""
} |
title: ':/2 (colon)'
predicates:
- {sig: ':/2', desc: 'calls a goal in the specified module'}
---
## FORMS
```
Module : Goal
```
## DESCRIPTION
'Module' should be instantiated to a name of a an existing, loaded module, and `Goal` should be instantiated to a non-variable term. The `Goal` will be executed as if the call to `Goal` appeared in the module named `Module`. Any module-dependent procedures such as [`assert/1`](assert.html) or [`retract/1`](retract.html) will operate on the procedures defined in `Module`. Any cuts appearing in `Goal` will cut back through the head of the clause that contained the call to `:/2`.
## EXAMPLES
```
?- listing.
% behavior:eats_linguini/1
eats_linguini(mike).
eats_linguini(jane).
% behavior:eats_salad/1
eats_salad(phil).
yes.
?- eats_linguini(mike).
Error: Operation attempted on object of type procedure which does not exist.
Operation attempted on: user:eats_linguini(mike).
- Goal: user:eats_linguini(mike)
- Throw pattern: error(existence_error(procedure,user:eats_linguini(mike)),
[user:eats_linguini(mike)])
?- behavior:eats_linguini(mike).
yes.
?- builtins:setof(Person, behavior:eats_linguini(Person), Persons).
Person=Person
Persons=[jane,mike]
yes.
?- behavior:setof(Person, eats_linguini(Person), Persons).
Person=Person
Persons=[jane,mike]
yes.
```
## ERRORS
If `Module` is unbound or not bound to a valid module name, the call to `:/2` will fail.
## SEE ALSO
- [`call/1`](call.html)
- [User Guide (Modules)](../guide/3-Modules.html)
| {
"content_hash": "195ef530439a3cbaa90732ba3c7da755",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 481,
"avg_line_length": 24.919354838709676,
"alnum_prop": 0.6990291262135923,
"repo_name": "AppliedLogicSystems/ALSProlog",
"id": "d9c8f3c6c4d1eb0cb7b1f94b2796ab137a3878e1",
"size": "1549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/docs/ref/colon.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "35412"
},
{
"name": "Batchfile",
"bytes": "10839"
},
{
"name": "C",
"bytes": "3909673"
},
{
"name": "C++",
"bytes": "45760"
},
{
"name": "Crystal",
"bytes": "86"
},
{
"name": "DIGITAL Command Language",
"bytes": "4506"
},
{
"name": "Dockerfile",
"bytes": "2614"
},
{
"name": "HTML",
"bytes": "38888"
},
{
"name": "Java",
"bytes": "1537"
},
{
"name": "M4",
"bytes": "114256"
},
{
"name": "Makefile",
"bytes": "47698"
},
{
"name": "Objective-C",
"bytes": "751"
},
{
"name": "PHP",
"bytes": "1580"
},
{
"name": "PLSQL",
"bytes": "272945"
},
{
"name": "Prolog",
"bytes": "3007478"
},
{
"name": "Python",
"bytes": "592"
},
{
"name": "R",
"bytes": "2229"
},
{
"name": "Roff",
"bytes": "32605"
},
{
"name": "Ruby",
"bytes": "2700"
},
{
"name": "Shell",
"bytes": "59158"
},
{
"name": "Tcl",
"bytes": "376910"
},
{
"name": "TeX",
"bytes": "19114"
},
{
"name": "sed",
"bytes": "1912"
}
],
"symlink_target": ""
} |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF 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.
/**
* ResetImageAttributeType.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.5.6 Built on : Aug 30, 2011 (10:01:01 CEST)
*/
package com.amazon.ec2;
/**
* ResetImageAttributeType bean class
*/
public class ResetImageAttributeType
implements org.apache.axis2.databinding.ADBBean{
/* This type was generated from the piece of schema that had
name = ResetImageAttributeType
Namespace URI = http://ec2.amazonaws.com/doc/2012-08-15/
Namespace Prefix = ns1
*/
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://ec2.amazonaws.com/doc/2012-08-15/")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* field for ImageId
*/
protected java.lang.String localImageId ;
/**
* Auto generated getter method
* @return java.lang.String
*/
public java.lang.String getImageId(){
return localImageId;
}
/**
* Auto generated setter method
* @param param ImageId
*/
public void setImageId(java.lang.String param){
this.localImageId=param;
}
/**
* field for ResetImageAttributesGroup
*/
protected com.amazon.ec2.ResetImageAttributesGroup localResetImageAttributesGroup ;
/**
* Auto generated getter method
* @return com.amazon.ec2.ResetImageAttributesGroup
*/
public com.amazon.ec2.ResetImageAttributesGroup getResetImageAttributesGroup(){
return localResetImageAttributesGroup;
}
/**
* Auto generated setter method
* @param param ResetImageAttributesGroup
*/
public void setResetImageAttributesGroup(com.amazon.ec2.ResetImageAttributesGroup param){
this.localResetImageAttributesGroup=param;
}
/**
* isReaderMTOMAware
* @return true if the reader supports MTOM
*/
public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) {
boolean isReaderMTOMAware = false;
try{
isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE));
}catch(java.lang.IllegalArgumentException e){
isReaderMTOMAware = false;
}
return isReaderMTOMAware;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName){
public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
ResetImageAttributeType.this.serialize(parentQName,factory,xmlWriter);
}
};
return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl(
parentQName,factory,dataSource);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,factory,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory,
org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
if ((namespace != null) && (namespace.trim().length() > 0)) {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, parentQName.getLocalPart());
} else {
if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
} else {
xmlWriter.writeStartElement(parentQName.getLocalPart());
}
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2012-08-15/");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":ResetImageAttributeType",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"ResetImageAttributeType",
xmlWriter);
}
}
namespace = "http://ec2.amazonaws.com/doc/2012-08-15/";
if (! namespace.equals("")) {
prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
xmlWriter.writeStartElement(prefix,"imageId", namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
} else {
xmlWriter.writeStartElement(namespace,"imageId");
}
} else {
xmlWriter.writeStartElement("imageId");
}
if (localImageId==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("imageId cannot be null!!");
}else{
xmlWriter.writeCharacters(localImageId);
}
xmlWriter.writeEndElement();
if (localResetImageAttributesGroup==null){
throw new org.apache.axis2.databinding.ADBException("ResetImageAttributesGroup cannot be null!!");
}
localResetImageAttributesGroup.serialize(null,factory,xmlWriter);
xmlWriter.writeEndElement();
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals(""))
{
xmlWriter.writeAttribute(attName,attValue);
}
else
{
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) {
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
"imageId"));
if (localImageId != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localImageId));
} else {
throw new org.apache.axis2.databinding.ADBException("imageId cannot be null!!");
}
elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/",
"ResetImageAttributesGroup"));
if (localResetImageAttributesGroup==null){
throw new org.apache.axis2.databinding.ADBException("ResetImageAttributesGroup cannot be null!!");
}
elementList.add(localResetImageAttributesGroup);
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static ResetImageAttributeType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
ResetImageAttributeType object =
new ResetImageAttributeType();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"ResetImageAttributeType".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (ResetImageAttributeType)com.amazon.ec2.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","imageId").equals(reader.getName())){
java.lang.String content = reader.getElementText();
object.setImageId(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() ){
object.setResetImageAttributesGroup(com.amazon.ec2.ResetImageAttributesGroup.Factory.parse(reader));
} // End of if for expected property start element
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
| {
"content_hash": "374d3619ff75396007a6ab2dd972a8ac",
"timestamp": "",
"source": "github",
"line_count": 552,
"max_line_length": 177,
"avg_line_length": 45.13768115942029,
"alnum_prop": 0.4709825012040456,
"repo_name": "mufaddalq/cloudstack-datera-driver",
"id": "339e74edfdb1c5fc32c159626be77b89fdd3e6bc",
"size": "24916",
"binary": false,
"copies": "1",
"ref": "refs/heads/4.2",
"path": "awsapi/src/com/amazon/ec2/ResetImageAttributeType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "250"
},
{
"name": "Batchfile",
"bytes": "6317"
},
{
"name": "CSS",
"bytes": "302008"
},
{
"name": "FreeMarker",
"bytes": "4917"
},
{
"name": "HTML",
"bytes": "38671"
},
{
"name": "Java",
"bytes": "79758943"
},
{
"name": "JavaScript",
"bytes": "4237188"
},
{
"name": "Perl",
"bytes": "1879"
},
{
"name": "Python",
"bytes": "5187499"
},
{
"name": "Shell",
"bytes": "803262"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="#E3F2FD"/>
<corners android:radius="@dimen/padding3"/>
</shape>
</item>
<item>
<shape>
<solid android:color="#BBDEFB"/>
<corners android:radius="@dimen/padding3"/>
</shape>
</item>
</selector> | {
"content_hash": "3958bfadee5c4583b2070bc393080f01",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 69,
"avg_line_length": 29,
"alnum_prop": 0.5538793103448276,
"repo_name": "skyofthinking/AndRapid",
"id": "b65e551298b37a82280ac97b03d4b7c357618454",
"size": "464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rapid/src/main/res/drawable/background_tag_selector.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "273307"
}
],
"symlink_target": ""
} |
package org.opensingular.flow.core.renderer;
import com.google.common.math.StatsAccumulator;
import javax.annotation.Nonnull;
import java.util.Date;
import java.util.Optional;
/**
* Represents the execution statistics of the flow as whole.
*
* @author Daniel C. Bordin
* @since 2018-08-28
*/
public final class StatisticsFlow {
private final StatsAccumulator statsOnlyStarted = new StatsAccumulator();
private final StatsAccumulator statsStartMilli = new StatsAccumulator();
private final StatsAccumulator statsEndMilli = new StatsAccumulator();
public void registerInstance(@Nonnull Date dtStart) {
statsOnlyStarted.add(dtStart.getTime());
}
public void registerInstance(@Nonnull Date dtStart, @Nonnull Date dtEndLastEvent) {
statsStartMilli.add(dtStart.getTime());
statsEndMilli.add(dtEndLastEvent.getTime());
}
@Nonnull
public Optional<Double> getMeanTimeExecuting() {
return statsStartMilli.count() > 0 ? Optional.of(statsEndMilli.mean() - statsStartMilli.mean()) :
Optional.empty();
}
public long getMaxEndDateEventOfSamples() {
return (long) statsEndMilli.max();
}
@Nonnull
public StatsAccumulator getStatsOnlyStarted() {
return statsOnlyStarted;
}
@Nonnull
public StatsAccumulator getStatsStartMilli() {
return statsStartMilli;
}
@Nonnull
public StatsAccumulator getStatsEndMilli() {
return statsEndMilli;
}
}
| {
"content_hash": "442d7cad4c3bcf36cc12f8f3290abb4c",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 105,
"avg_line_length": 27.72222222222222,
"alnum_prop": 0.7047428189712759,
"repo_name": "opensingular/singular-core",
"id": "77f699a34a53ddff529c34ed9b0ce77d94067cb3",
"size": "1497",
"binary": false,
"copies": "1",
"ref": "refs/heads/feature_1.9.x",
"path": "flow/core/src/main/java/org/opensingular/flow/core/renderer/StatisticsFlow.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3919351"
},
{
"name": "CoffeeScript",
"bytes": "83631"
},
{
"name": "HTML",
"bytes": "1038610"
},
{
"name": "Java",
"bytes": "6990606"
},
{
"name": "JavaScript",
"bytes": "15861962"
},
{
"name": "Shell",
"bytes": "444"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Example article resource (full-featured example) -->
<resource primaryKey="id" xmlns:flora="urn:flora:options">
<!-- Primary DataSource (without name) -->
<flora:dataSource type="mysql" database="contents" table="article"/>
<!-- Select body from separate table without LEFT JOIN. Alternatively, primary
DataSource can be transparently rewritten as one query with LEFT JOIN on
article_body -->
<flora:dataSource name="articleBody" type="mysql" database="contents" table="article_body"/>
<!-- Use Solr for fulltext search -->
<flora:dataSource name="fulltextSearch" type="solr" core="article" searchable="true"/>
<!-- Aggregate statistics for article comments -->
<flora:dataSource name="statistics" type="mysql" database="contents">
<flora:option name="query">
<![CDATA[SELECT articleId AS articleId, COUNT(id) AS commentCount FROM comments GROUP BY articleId]]></flora:option>
</flora:dataSource>
<!-- Enable article-filter by author IDs (filter by sub-resource primary key) -->
<flora:subFilter attribute="author.id" filter="true" rewriteTo="authorId"/>
<!-- Enable article-filter by video youtubeId (filter by sub-resource-attribute) -->
<flora:subFilter attribute="video.youtubeId" filter="true"/>
<!-- Enable article-filter by comments by user ID (filter by sub-sub-resource) -->
<flora:subFilter attribute="comments.user.id" filter="true"/>
<!-- Enable article-filter by category IDs (filter by sub-resource with joinVia) -->
<flora:subFilter attribute="categories.id" filter="true"/>
<!-- Primary key must always be mapped to all DataSources -->
<id type="int" map="id;articleBody:articleId;fulltextSearch:articleId;statistics:articleId"/>
<!-- Map date to different name in primary DataSource.
Enable "=>" and "<=" filter, enable order asc/desc -->
<date type="datetime" map="timestamp" filter="greaterOrEqual,lessOrEqual" order="true"/>
<!-- Standard case: string-attribute with same name in database -->
<title/>
<!-- Backward-compatible attribute with fixed null-value
(i.e. for breaking changes in your API) -->
<subTitle deprecated="true" value="null"/>
<!-- Relation: Article has one author (n : 1) - article has authorId -->
<authorId hidden="true" type="int"/>
<author resource="user" parentKey="authorId" childKey="{primary}"/>
<!-- Relation: Article has multiple categories (m : n - with join-table).
Join-table "article_category" with "articleId, categoryId" -->
<categories primaryKey="id" parentKey="{primary}" childKey="{primary}"
joinVia="articleCategories" many="true">
<flora:dataSource type="mysql" database="contents" table="category"/>
<flora:dataSource name="articleCategories" type="mysql" database="contents"
table="article_category" joinParentKey="articleId" joinChildKey="categoryId"/>
<articleId hidden="true" type="int" map="articleCategories:articleId"/>
<categoryId hidden="true" type="int" map="articleCategories:categoryId"/>
<id type="int"/>
<name/>
<isImportant type="boolean"/>
<!-- Select additional fields from join-table: -->
<order type="int" map="articleCategories:order"/>
</categories>
<!-- Relation: Article has multiple countries (m : n - with multi-values).
Attribute "countries" as a SET of ISO-codes - it will be split by "," here.
Some DataSources may natively support multi-value-fields (i.e. Lucene) where
delimiter is not needed.
This is an example for a "legacy" data-model which can then be transparently
redesigned "when needed" -->
<countryIsoList hidden="true" multiValued="true" type="string" map="countries" delimiter=","/>
<countries primaryKey="id" parentKey="countryIsoList" childKey="iso" many="true">
<flora:dataSource type="mysql" database="contents" table="country"/>
<id type="int"/>
<name/>
<iso/>
<iso3/>
</countries>
<!-- Select body from separate DataSource - only queried if selected -->
<body map="articleBody:body"/>
<!-- Relation: Attributes for video-articles (1 : 1) - article_video has
articleId as primary key.
This can transparently be rewritten as an additional DataSource (or part of
primary DataSource) of main-resource.
To avoid redundant attributes, primaryKey is not needed if childKey is present.
This is also an example for an inline defined sub-resource. -->
<video primaryKey="articleId" parentKey="{primary}" childKey="{primary}">
<flora:dataSource type="mysql" database="contents" table="article_video"/>
<articleId hidden="true" type="int"/>
<url/>
<previewImage/>
<youtubeId filter="true"/>
</video>
<!-- Grouping of attributes (without own DataSource).
This can transparently be rewritten as a sub-resource when needed. -->
<source>
<name map="sourceName"/>
<externalId map="externalId"/>
<externalUrl map="externalUrl"/>
</source>
<!-- Copyright signature is dynamically generated via callback which needs some
additional info.
Fixed empty value to disable selection of inexistent "copyright" attribute
from DataSource -->
<copyright depends="author[firstname,lastname],categories.name,secretInfo" value=""/>
<!-- Hidden fields can never be selected, but you can depend on them (see "copyright") -->
<secretInfo hidden="true"/>
<!-- Count of comments per article - only queried if selected -->
<commentCount type="int" map="statistics:commentCount"/>
<!-- Article has multiple comments (1 : n) - comment has articleId -->
<comments primaryKey="id" parentKey="{primary}" childKey="articleId" many="true">
<flora:dataSource type="mysql" database="contents" table="article_comment"/>
<flora:dataSource name="likes" type="mysql" database="contents" table="comment_likes"/>
<articleId hidden="true" type="int"/>
<id type="int" map="id;likes:commentId"/>
<userId hidden="true" type="int"/>
<user resource="user" parentKey="userId" childKey="{primary}"/>
<content/>
<likes type="int" map="likes:count"/>
</comments>
<!-- Primary key is a composite key - but link to parent only by articleId -->
<versions primaryKey="articleId,versionId" parentKey="{primary}" childKey="articleId" many="true">
<flora:dataSource type="mysql" database="contents" table="article_versions"/>
<articleId hidden="true" type="int"/>
<versionId type="int"/>
<title/>
<body/>
<!-- Link by composite key -->
<versioninfo primaryKey="articleId,versionId" parentKey="{primary}" childKey="{primary}">
<flora:dataSource type="mysql" database="contents" table="article_versioninfo"/>
<articleId hidden="true" type="int"/>
<versionId hidden="true" type="int"/>
<modified type="datetime"/>
<username/>
</versioninfo>
</versions>
</resource>
| {
"content_hash": "8a578edf83e17d2ac6861edfeecb931a",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 128,
"avg_line_length": 44.27439024390244,
"alnum_prop": 0.6548684754166093,
"repo_name": "godmodelabs/flora",
"id": "7efbaf9f0be2eff093e8e179b6a06fce3aa3f3d6",
"size": "7261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/fixtures/resources/article/config.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "542625"
}
],
"symlink_target": ""
} |
@import "../tokens/tokens";
@import "custom-properties";
@import "custom-media";
@import "mixin"; | {
"content_hash": "0e2f1705745af4949b316f6019882117",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 28,
"avg_line_length": 24.25,
"alnum_prop": 0.7010309278350515,
"repo_name": "nabaroa/nakDS-core",
"id": "8960eba16498947ca3dde85a535c9173fc6e8449",
"size": "97",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/css/variables/core-utils.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "52196"
},
{
"name": "JavaScript",
"bytes": "1420"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "357935d91004eda116887c766e6a492c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "77eb48ac987b57498b928526762e77f576fcb08b",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Joseanthus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
var searchData=
[
['pointmass',['PointMass',['../class_fractal_tree_1_1_point_mass.html',1,'FractalTree']]]
];
| {
"content_hash": "bf86f75fc99d3891da34683a3c4b01c7",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 91,
"avg_line_length": 28.25,
"alnum_prop": 0.6548672566371682,
"repo_name": "GandhiGames/fractal_trees_with_spring",
"id": "2daee1a5132f2a5ccb22a3e1944f329e3e7e61a5",
"size": "113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "documentation/generated/html/search/classes_5.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "71691"
}
],
"symlink_target": ""
} |
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
<?php foreach ($urls as $url): ?>
<url>
<loc><?= yii\helpers\Url::to($url['loc'], true) ?></loc>
<?php if (isset($url['lastmod'])): ?>
<lastmod><?= is_string($url['lastmod']) ?
$url['lastmod'] : date(DATE_W3C, $url['lastmod']) ?></lastmod>
<?php endif; ?>
<?php if (isset($url['changefreq'])): ?>
<changefreq><?= $url['changefreq'] ?></changefreq>
<?php endif; ?>
<?php if (isset($url['priority'])): ?>
<priority><?= $url['priority'] ?></priority>
<?php endif; ?>
<?php if (isset($url['news'])): ?>
<news:news>
<news:publication>
<news:name><?= $url['news']['publication']['name'] ?></news:name>
<news:language><?= $url['news']['publication']['language'] ?></news:language>
</news:publication>
<?php
echo isset($url['news']['access']) ? "<news:access>{$url['news']['access']}</news:access>" : '';
echo isset($url['news']['genres']) ? "<news:genres>{$url['news']['genres']}</news:genres>" : '';
?>
<news:publication_date>
<?= is_string($url['news']['publication_date']) ?
$url['news']['publication_date'] : date(DATE_W3C, $url['news']['publication_date']) ?>
</news:publication_date>
<news:title> <?= $url['news']['title'] ?></news:title>
<?php
echo isset($url['news']['keywords']) ?
"<news:keywords>{$url['news']['keywords']}</news:keywords>" : '';
echo isset($url['news']['stock_tickers']) ?
"<news:stock_tickers>{$url['news']['stock_tickers']}</news:stock_tickers>" : '';
?>
</news:news>
<?php endif; ?>
<?php if (isset($url['images'])):
foreach ($url['images'] as $image): ?>
<image:image>
<image:loc><?= yii\helpers\Url::to($image['loc'], true) ?></image:loc>
<?php
echo isset($image['caption']) ?
"<image:caption>{$image['caption']}</image:caption>" : '';
echo isset($image['geo_location']) ?
"<image:geo_location>{$image['geo_location']}</image:geo_location>" : '';
echo isset($image['title']) ?
"<image:title>{$image['title']}</image:title>" : '';
echo isset($image['license']) ?
"<image:license>{$image['license']}</image:license>" : '';
?>
</image:image>
<?php endforeach;
endif; ?>
</url>
<?php endforeach; ?>
</urlset>
| {
"content_hash": "fe0d5f7c7e655184f7eb45e7a59c88d7",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 116,
"avg_line_length": 53.46774193548387,
"alnum_prop": 0.41990950226244345,
"repo_name": "katech91/yii2-sitemap-module",
"id": "e1301432036b5b6a33695b389fd02326b7b756c2",
"size": "3315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "views/default/sitemap.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "13768"
}
],
"symlink_target": ""
} |
require "LuaScripts/Utilities/Sample"
local scene_ = nil
local cameraNode = nil
local yaw = 0.0
local pitch = 0.0
local drawDebug = false
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Hook up to the frame update and render post-update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
-- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
-- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
-- Finally, create a DebugRenderer component so that we can draw physics debug geometry
scene_:CreateComponent("Octree")
scene_:CreateComponent("PhysicsWorld")
scene_:CreateComponent("DebugRenderer")
-- Create a Zone component for ambient lighting & fog control
local zoneNode = scene_:CreateChild("Zone")
local zone = zoneNode:CreateComponent("Zone")
zone.boundingBox = BoundingBox(-1000.0, 1000.0)
zone.ambientColor = Color(0.15, 0.15, 0.15)
zone.fogColor = Color(1.0, 1.0, 1.0)
zone.fogStart = 300.0
zone.fogEnd = 500.0
-- Create a directional light to the world. Enable cascaded shadows on it
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.6, -1.0, 0.8)
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
light.castShadows = true
light.shadowBias = BiasParameters(0.00025, 0.5)
-- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
-- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
-- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
-- generate the necessary 3D texture coordinates for cube mapping
local skyNode = scene_:CreateChild("Sky")
skyNode:SetScale(500.0) -- The scale actually does not matter
local skybox = skyNode:CreateComponent("Skybox")
skybox.model = cache:GetResource("Model", "Models/Box.mdl")
skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
-- Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
local floorNode = scene_:CreateChild("Floor")
floorNode.position = Vector3(0.0, -0.5, 0.0)
floorNode.scale = Vector3(1000.0, 1.0, 1000.0)
local floorObject = floorNode:CreateComponent("StaticModel")
floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
-- Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
-- parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
-- in the physics simulation
local body = floorNode:CreateComponent("RigidBody")
local shape = floorNode:CreateComponent("CollisionShape")
-- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
-- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
shape:SetBox(Vector3(1.0, 1.0, 1.0))
-- Create a pyramid of movable physics objects
for y = 0, 7 do
for x = -y, y do
local boxNode = scene_:CreateChild("Box")
boxNode.position = Vector3(x, -y + 8.0, 0.0)
local boxObject = boxNode:CreateComponent("StaticModel")
boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
boxObject.castShadows = true
-- Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
-- and also adjust friction. The actual mass is not important only the mass ratios between colliding
-- objects are significant
local body = boxNode:CreateComponent("RigidBody")
body.mass = 1.0
body.friction = 0.75
local shape = boxNode:CreateComponent("CollisionShape")
shape:SetBox(Vector3(1.0, 1.0, 1.0))
end
end
-- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
-- the scene, because we want it to be unaffected by scene load / save
cameraNode = Node()
local camera = cameraNode:CreateComponent("Camera")
camera.farClip = 500.0
-- Set an initial position for the camera scene node above the floor
cameraNode.position = Vector3(0.0, 5.0, -20.0)
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move\n"..
"LMB to spawn physics objects\n"..
"F5 to save scene, F7 to load\n"..
"Space to toggle physics debug geometry")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- The text has multiple rows. Center them in relation to each other
instructionText.textAlignment = HA_CENTER
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
-- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
-- debug geometry
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
local mouseMove = input.mouseMove
yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
-- "Shoot" a physics object with left mousebutton
if input:GetMouseButtonPress(MOUSEB_LEFT) then
SpawnObject()
end
-- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
-- directory
if input:GetKeyPress(KEY_F5) then
scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
end
if input:GetKeyPress(KEY_F7) then
scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
end
-- Toggle debug geometry with space
if input:GetKeyPress(KEY_SPACE) then
drawDebug = not drawDebug
end
end
function SpawnObject()
-- Create a smaller box at camera position
local boxNode = scene_:CreateChild("SmallBox")
boxNode.position = cameraNode.position
boxNode.rotation = cameraNode.rotation
boxNode:SetScale(0.25)
local boxObject = boxNode:CreateComponent("StaticModel")
boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
boxObject.castShadows = true
-- Create physics components, use a smaller mass also
local body = boxNode:CreateComponent("RigidBody")
body.mass = 0.25
body.friction = 0.75
local shape = boxNode:CreateComponent("CollisionShape")
shape:SetBox(Vector3(1.0, 1.0, 1.0))
local OBJECT_VELOCITY = 10.0
-- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
-- to overcome gravity better
body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData:GetFloat("TimeStep")
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
function HandlePostRenderUpdate(eventType, eventData)
-- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
-- Note the convenience accessor to the physics world component
if drawDebug then
scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
end
end
| {
"content_hash": "66dc1eafd9aedd042337c707cccacff8",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 124,
"avg_line_length": 42.41004184100419,
"alnum_prop": 0.7032359905288083,
"repo_name": "nonconforme/Urho3DEditor",
"id": "da12ad338e8dfe62050c7d10f25e6b1c2d1b284c",
"size": "10441",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Prime/Data/Data/LuaScripts/11_Physics.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "752844"
},
{
"name": "Batchfile",
"bytes": "656"
},
{
"name": "C",
"bytes": "725"
},
{
"name": "C++",
"bytes": "637022"
},
{
"name": "GLSL",
"bytes": "70229"
},
{
"name": "HTML",
"bytes": "9848"
},
{
"name": "Lua",
"bytes": "278468"
}
],
"symlink_target": ""
} |
"""
If you know error code, use `get_for_code(code)` to retrieve exception instance.
"""
__all__ = ['Success', 'InvalidOperation', 'HostNotFound', 'ConnectionRefused',
'SendError', 'ReceiveError', 'RecordExists', 'RecordNotFound',
'MiscellaneousError', 'get_for_code']
class TyrantError(Exception):
"""
Tyrant error, socket and communication errors are not included here.
"""
pass
class Success(TyrantError):
"""
Don't laugh at me. I represent a constant from the protocol. Honestly!
"""
pass
class InvalidOperation(TyrantError):
pass
class HostNotFound(TyrantError):
pass
class ConnectionRefused(TyrantError):
pass
class SendError(TyrantError):
pass
class ReceiveError(TyrantError):
pass
class RecordExists(TyrantError):
message = 'Record already exists'
class RecordNotFound(TyrantError):
pass
class MiscellaneousError(TyrantError):
pass
ERROR_CODE_TO_CLASS = {
0: Success,
1: InvalidOperation,
2: HostNotFound,
3: ConnectionRefused,
4: SendError,
5: ReceiveError,
6: RecordExists,
7: RecordNotFound,
9999: MiscellaneousError,
}
def get_for_code(error_code, message=None):
try:
int(error_code)
except ValueError:
raise TypeError(u'Could not map error code to exception class: expected '
'a number, got "%s"' % error_code)
else:
try:
cls = ERROR_CODE_TO_CLASS[error_code]
except KeyError:
raise ValueError('Unknown error code "%d"' % error_code)
else:
return cls(message) if message else cls()
| {
"content_hash": "921c6f97667c618cad7dec36bf9cba96",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 81,
"avg_line_length": 22.86111111111111,
"alnum_prop": 0.6476306196840826,
"repo_name": "Reflejo/pyrant",
"id": "d2531db4c8b80aeff70abc952f2c29495bf11e09",
"size": "1671",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pyrant/exceptions.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Lua",
"bytes": "78"
},
{
"name": "Python",
"bytes": "119549"
},
{
"name": "Shell",
"bytes": "165"
}
],
"symlink_target": ""
} |
@implementation FEMObjectMapping
#pragma mark - Init
- (id)initWithObjectClass:(Class)objectClass rootPath:(NSString *)rootPath {
self = [self initWithRootPath:rootPath];
if (self) {
_objectClass = objectClass;
}
return self;
}
- (id)initWithObjectClass:(Class)objectClass {
return [self initWithObjectClass:objectClass rootPath:nil];
}
+ (instancetype)mappingForClass:(Class)objectClass configuration:(void (^)(FEMObjectMapping *mapping))configuration {
FEMObjectMapping *mapping = [[self alloc] initWithObjectClass:objectClass];
configuration(mapping);
return mapping;
}
+ (instancetype)mappingForClass:(Class)objectClass
rootPath:(NSString *)rootPath
configuration:(void (^)(FEMObjectMapping *mapping))configuration {
FEMObjectMapping *mapping = [[self alloc] initWithObjectClass:objectClass rootPath:rootPath];
configuration(mapping);
return mapping;
}
@end | {
"content_hash": "6c8878d6dab0013c610e0a3a776ea27f",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 117,
"avg_line_length": 29.516129032258064,
"alnum_prop": 0.7519125683060109,
"repo_name": "xslim/iOS-Mappers-Tests",
"id": "cf4f39ffa4163973b7ef26a8df7298aee89b6b07",
"size": "2059",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pods/FastEasyMapping/FastEasyMapping/Source/Core/Mapping/Object/FEMObjectMapping.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1330"
},
{
"name": "Objective-C",
"bytes": "13486"
},
{
"name": "Ruby",
"bytes": "88"
}
],
"symlink_target": ""
} |
import logging
from django.http import Http404
from rest_framework import exceptions
from rest_framework.settings import api_settings
from mimeparser import MIMEParser
log = logging.getLogger('api.common.negotiation')
class ContentNegotiation(MIMEParser):
def __init__(self):
MIMEParser.__init__(self)
def select_parser(self, request, parsers):
"""
Given a list of parsers and a media type, return the appropriate
parser to handle the incoming request.
"""
result = None
for parser in parsers:
if self.best_match([parser.media_type], request.content_type):
result = parser
break
log.debug("mimetype: %s", result)
return result
def select_renderer(self, request, renderers, format_suffix=None):
"""
Given a request and a list of renderers, return a two-tuple of:
(renderer, media type).
"""
# Allow URL style format override. eg. ?format=json
format_query_param = api_settings.URL_FORMAT_OVERRIDE
fmt = format_suffix or request.query_params.get(format_query_param)
if fmt: # pragma: no cover
renderers = self.filter_renderers(renderers, fmt)
accept = request.META.get('HTTP_ACCEPT', '*/*')
# Check the best match media type against each renderer.
renderer_map = {renderer.media_type: renderer
for renderer in renderers}
best_match = self.best_match(list(renderer_map), accept)
result = (renderer_map.get(best_match), best_match)
if result[0] is None: # pragma: no cover
raise exceptions.NotAcceptable(available_renderers=renderers)
log.debug("mimetype: %s", result)
return result
def filter_renderers(self, renderers, format): # pragma: no cover
"""
If there is a '.json' style format suffix, filter the renderers
so that we only negotiate against those that accept that format.
"""
renderers = [renderer for renderer in renderers
if format.lower() in renderer.format]
if not renderers:
raise Http404
return renderers
| {
"content_hash": "517da0a03b575dbb8b990059e403c633",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 75,
"avg_line_length": 32.34782608695652,
"alnum_prop": 0.6263440860215054,
"repo_name": "cnobile2012/inventory",
"id": "a884d5a35ff789f2de1ae9093d1131a95df069b4",
"size": "2299",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "inventory/common/api/negotiation.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12728"
},
{
"name": "HTML",
"bytes": "23634"
},
{
"name": "JavaScript",
"bytes": "84845"
},
{
"name": "Makefile",
"bytes": "1972"
},
{
"name": "Python",
"bytes": "906059"
},
{
"name": "Shell",
"bytes": "3013"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
-->
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="service_name" msgid="4841491635055379553">"Багц хандалтын тусламж"</string>
</resources>
| {
"content_hash": "4b35af5fbcc34261040fada3f1545806",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 93,
"avg_line_length": 31.77777777777778,
"alnum_prop": 0.6958041958041958,
"repo_name": "Ant-Droid/android_frameworks_base_OLD",
"id": "d9fe6477ca11e4a167703657319920f761b90914",
"size": "923",
"binary": false,
"copies": "5",
"ref": "refs/heads/mm600",
"path": "packages/DefaultContainerService/res/values-mn-rMN/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "167132"
},
{
"name": "C++",
"bytes": "7099875"
},
{
"name": "GLSL",
"bytes": "20654"
},
{
"name": "HTML",
"bytes": "224185"
},
{
"name": "Java",
"bytes": "79415679"
},
{
"name": "Makefile",
"bytes": "419370"
},
{
"name": "Python",
"bytes": "42309"
},
{
"name": "RenderScript",
"bytes": "153826"
},
{
"name": "Shell",
"bytes": "21079"
}
],
"symlink_target": ""
} |
module Cuba::Sugar
module As
# Public: Sugar to do some common response tasks
#
# http_code - Response status code (default: 200)
# extra_headers - Extra headers hash (default: {})
#
# Examples:
#
# on post, "users" do
# as 201 do
# "User successfully created!"
# end
# end
def as(http_code = 200, extra_headers = {}, &block)
res.status = http_code
res.headers.merge! extra_headers
yield if block
end
# Public: Sugar to do some common response tasks as_json
#
# http_code - Response status code (default: 200)
# extra_headers - Extra headers hash (default: {})
# Examples:
#
# on post, "users" do
# as_json 201 do
# "User successfully created!"
# end
# end
def as_json(http_code = 200, extra_headers = {}, &block)
require 'json'
extra_headers["Content-Type"] ||= "application/json"
as(http_code, extra_headers) { yield.to_json if block }
end
end
end
| {
"content_hash": "379ec806358379e6be754d482df78124",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 61,
"avg_line_length": 27.44736842105263,
"alnum_prop": 0.5675934803451582,
"repo_name": "cj/cuba-tracks",
"id": "52948a77dc54339036e5636288122b7f63d15964",
"size": "1043",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/cuba/sugar/as.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "71550"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<title>Software | ContentMine</title>
<meta name="description" content="">
<meta name="author" content="Cottage Labs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript" src="http://static.cottagelabs.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://static.cottagelabs.com/bootstrap-3.0.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://static.cottagelabs.com/bootstrap-3.0.3/css/bootstrap.min.css">
<script type="text/javascript" src="http://static.cottagelabs.com/holder/jquery.holder.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- CM light green is #92ce73 and dark green is #187c83 -->
<style>
.label-cm {
font-size:0.9em;
background-color:#ddd;
color:#333;
}
</style>
</head>
<body>
<div class="container" style="margin-top:50px;width:1200px;">
<div class="row">
<div class="col-md-3">
<div class="well" style="border:3px solid #187c83;background-color:white;height:270px;">
<a href="/"><img src="http://static.cottagelabs.com/CM_small.png" style="padding-top:50px;padding-bottom:10px;width:100%;"></a>
</div>
</div>
<div class="col-md-3">
<div class="well" style="border:3px solid #187c83;background-color:white;height:270px;">
<h1 style="margin-top:10px;">SOFTWARE</h1>
</div>
</div>
<div class="col-md-6">
<div class="well" style="border:3px solid #187c83;background-color:white;height:270px;">
</div>
</div>
</div>
</div>
<div class="container" style="margin-top:20px;margin-bottom:50px;width:1200px;">
<div class="row">
<div class="col-md-3">
<div class="well" style="border:3px solid #187c83;background-color:white;height:270px;">
<p>The <a href="/">ContentMine</a> project.</p>
<p>© <a href="https://www.shuttleworthfoundation.org/">Shuttleworth Foundation</a>, for whom Peter Murray-Rust is a fellow.</p>
<p>Unless otherwise noted, the content of the <span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">
ContentMine Website</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">
Creative Commons Attribution 4.0 International License</a>.</p>
<p>The extracted facts are <a rel="license" href="http://creativecommons.org/publicdomain/zero/1.0/">CC0</a>.</p>
</div>
</div>
<div class="col-md-3">
<div class="well" style="border:3px solid #187c83;background-color:white;height:270px;">
<a href="mailto:[email protected]"><i class="fa fa-envelope" style="font-size:16.2em;color:#187c83;"></i></a>
</div>
</div>
<div class="col-md-3">
<div class="well" style="border:3px solid #187c83;background-color:white;height:270px;">
<a href="https://twitter.com/TheContentMine" title="@TheContentMine"><i class="fa fa-twitter" style="font-size:16.2em;padding-left:10px;color:#187c83;"></i></a>
</div>
</div>
<div class="col-md-3">
<div class="well" style="border:3px solid #187c83;background-color:white;height:270px;">
<a href="http://github.com/ContentMine" title="ContentMine"><i class="fa fa-github" style="font-size:16.2em;padding-left:15px;color:#187c83;"></i></a>
</div>
</div>
</div>
</div>
<script>
jQuery(document).ready(function() {
});
</script>
</body>
</html> | {
"content_hash": "1516f7c6741f843a03bed3c38fde7d59",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 168,
"avg_line_length": 36.23076923076923,
"alnum_prop": 0.6480891719745223,
"repo_name": "tarrow/canary",
"id": "5933d50f7887dde2787028c04af970235ae6a032",
"size": "3768",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/static/co/software/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "597"
},
{
"name": "HTML",
"bytes": "84790"
},
{
"name": "JavaScript",
"bytes": "31610"
},
{
"name": "Python",
"bytes": "1161"
}
],
"symlink_target": ""
} |
use libfuzzer_sys::fuzz_target;
use manticore::mem::BumpArena;
use manticore::protocol::Command;
use manticore::protocol::wire::FromWire;
use manticore::protocol::cerberus::DeviceCapabilities as C;
fuzz_target!(|data: &[u8]| {
let mut arena = vec![0; data.len()];
let arena = BumpArena::new(&mut arena);
let mut data = data;
let _ = <C as Command<'_>>::Resp::from_wire(&mut data, &arena);
});
| {
"content_hash": "109005861f5c251b6d401ef16ca4c7d5",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 67,
"avg_line_length": 27.533333333333335,
"alnum_prop": 0.6634382566585957,
"repo_name": "lowRISC/manticore",
"id": "77f77c96c9deaac8dce1fc264a2b548eef2ed591",
"size": "689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fuzz/gen/manticore_protocol_cerberus_DeviceCapabilities__resp_from_wire.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Logos",
"bytes": "32"
},
{
"name": "Python",
"bytes": "22176"
},
{
"name": "Rust",
"bytes": "645600"
},
{
"name": "Shell",
"bytes": "8309"
},
{
"name": "Smarty",
"bytes": "4241"
},
{
"name": "Yacc",
"bytes": "32"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.312
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Banshee.Base.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| {
"content_hash": "e383323d949c02c9c6be51c97f8390e8",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 150,
"avg_line_length": 41.92307692307692,
"alnum_prop": 0.5660550458715596,
"repo_name": "google-code/banshee32",
"id": "84fe5647e0373e30e4aac24d3f8e1bd10ab086f1",
"size": "1092",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Banshee.Base/Properties/Settings.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2955061"
},
{
"name": "Inno Setup",
"bytes": "3967"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Atk4\Data\Tests\ContainsMany;
use Atk4\Data\Model;
/**
* @property string $name @Atk4\Field()
* @property int $rate @Atk4\Field()
*/
class VatRate extends Model
{
public $table = 'vat_rate';
protected function init(): void
{
parent::init();
$this->addField($this->fieldName()->name);
$this->addField($this->fieldName()->rate, ['type' => 'integer']);
}
}
| {
"content_hash": "95716ce6727a4fccfc4a123cfc5c0ac5",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 73,
"avg_line_length": 18.625,
"alnum_prop": 0.6017897091722595,
"repo_name": "atk4/data",
"id": "1b62ceaaa5bfe26df54e46b342af10230f3e31b0",
"size": "447",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/ContainsMany/VatRate.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "964184"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Arr. Brit. Pl. (London), Edn 3 4: 78 (1796)
#### Original name
Tremella sarcoides With.
### Remarks
null | {
"content_hash": "50599d3a962e231b5d8761752c6e311b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 43,
"avg_line_length": 12.923076923076923,
"alnum_prop": 0.6726190476190477,
"repo_name": "mdoering/backbone",
"id": "845f131e2c852da628c10c028ceb67740e81113d",
"size": "216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Tremellomycetes/Tremellales/Tremellaceae/Tremella/Tremella sarcoides/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
'use strict';
const jwt = require('jsonwebtoken');
const env = require('../config/envVariables');
const rolesConfig = require('../config/rolesConfig');
function createUserToken(user) {
let scopes = [];
rolesConfig.forEach((role) => {
if (user[role.name]) {
scopes.push(role.name);
}
})
// Sign the JWT
return jwt.sign({ id: user._id, username: user.username, scope: scopes }, env.secret, { algorithm: 'HS256', expiresIn: "1h" } );
}
module.exports = createUserToken;
| {
"content_hash": "c7027067127d928b6ed67a09dd0268d2",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 130,
"avg_line_length": 25.842105263157894,
"alnum_prop": 0.6578411405295316,
"repo_name": "zdizzle6717/universal-react-movie-app",
"id": "5badc699397083d074e9f7e2e9c6e40e0a8c39d9",
"size": "491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/utils/createToken.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "97171"
},
{
"name": "HTML",
"bytes": "6157"
},
{
"name": "JavaScript",
"bytes": "171244"
}
],
"symlink_target": ""
} |
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 2017-2021 Authors of Cilium
// SPDX-License-Identifier: Apache-2.0
package endpoint
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
)
// PatchEndpointIDHandlerFunc turns a function with the right signature into a patch endpoint ID handler
type PatchEndpointIDHandlerFunc func(PatchEndpointIDParams) middleware.Responder
// Handle executing the request and returning a response
func (fn PatchEndpointIDHandlerFunc) Handle(params PatchEndpointIDParams) middleware.Responder {
return fn(params)
}
// PatchEndpointIDHandler interface for that can handle valid patch endpoint ID params
type PatchEndpointIDHandler interface {
Handle(PatchEndpointIDParams) middleware.Responder
}
// NewPatchEndpointID creates a new http.Handler for the patch endpoint ID operation
func NewPatchEndpointID(ctx *middleware.Context, handler PatchEndpointIDHandler) *PatchEndpointID {
return &PatchEndpointID{Context: ctx, Handler: handler}
}
/*PatchEndpointID swagger:route PATCH /endpoint/{id} endpoint patchEndpointId
Modify existing endpoint
Applies the endpoint change request to an existing endpoint
*/
type PatchEndpointID struct {
Context *middleware.Context
Handler PatchEndpointIDHandler
}
func (o *PatchEndpointID) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
var Params = NewPatchEndpointIDParams()
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}
| {
"content_hash": "378db3f33c5cba7d33c2908ab80cf706",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 104,
"avg_line_length": 29.15625,
"alnum_prop": 0.7792068595927116,
"repo_name": "tgraf/cilium",
"id": "b3d5728f2e748bc58a8e756df4e3aeb59a144fd1",
"size": "1866",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "api/v1/server/restapi/endpoint/patch_endpoint_id.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1109708"
},
{
"name": "C++",
"bytes": "6557"
},
{
"name": "Dockerfile",
"bytes": "27333"
},
{
"name": "Go",
"bytes": "9930421"
},
{
"name": "HCL",
"bytes": "1127"
},
{
"name": "Makefile",
"bytes": "72210"
},
{
"name": "Mustache",
"bytes": "1457"
},
{
"name": "Python",
"bytes": "11099"
},
{
"name": "Ruby",
"bytes": "392"
},
{
"name": "Shell",
"bytes": "369722"
},
{
"name": "SmPL",
"bytes": "6540"
},
{
"name": "Smarty",
"bytes": "10858"
},
{
"name": "TeX",
"bytes": "416"
},
{
"name": "sed",
"bytes": "1336"
}
],
"symlink_target": ""
} |
package org.schedoscope.dsl.transformations
import org.scalatest.{FlatSpec, Matchers}
import org.schedoscope.dsl.View
import org.schedoscope.dsl.transformations.Export.BigQuery
import org.schedoscope.dsl.transformations.HiveTransformation._
case class HiveView() extends View {
val f = fieldOf[String]
transformVia {
() =>
HiveTransformation(
insertInto(this, "select * from view"))
.defineVersion("v2.2")
}
exportTo(() => BigQuery(this))
}
class TransformationTest extends FlatSpec with Matchers {
"the define version method" should "change a checksum" in {
//new transformation
val transformation = HiveTransformation("select * from view")
val checksum1 = transformation.checksum
//overwrite checksum with the same string as the hiveql
transformation.defineVersion("select * from view")
val checksum2 = transformation.checksum
//change checksum with version
transformation.defineVersion("v2.2")
val checksum3 = transformation.checksum
checksum1 shouldBe Checksum.digest("select * from view")
checksum1 shouldBe checksum2
checksum3 should not be checksum1
checksum3 should not be checksum2
}
it should "change the checksum of a transformation in a view" in {
//new transformation
val view = new HiveView()
view.transformation().checksum shouldBe Checksum.digest("v2.2")
}
}
| {
"content_hash": "5f79f5e52d96eaae47ef75a25683ac22",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 68,
"avg_line_length": 25,
"alnum_prop": 0.7264285714285714,
"repo_name": "utzwestermann/schedoscope",
"id": "e03c324fc39b7ba74c873d072e8230724130c2ab",
"size": "1400",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "schedoscope-core/src/test/scala/org/schedoscope/dsl/transformations/TransformationTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "181599"
},
{
"name": "FreeMarker",
"bytes": "1867"
},
{
"name": "HTML",
"bytes": "187285"
},
{
"name": "Java",
"bytes": "931203"
},
{
"name": "JavaScript",
"bytes": "337257"
},
{
"name": "PigLatin",
"bytes": "652"
},
{
"name": "Scala",
"bytes": "953560"
},
{
"name": "Shell",
"bytes": "376"
}
],
"symlink_target": ""
} |
/*!!
* @atlassian/aui - Atlassian User Interface Framework
* @version v7.7.0-beta-3
* @link https://docs.atlassian.com/aui/latest/
* @license SEE LICENSE IN LICENSE.md
* @author Atlassian Pty Ltd.
*/
// src/js/aui/header-async.js
(typeof window === 'undefined' ? global : window).__f4243cbdeeb31de2885ed6caf30d3f96 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createHeader = __35216236d580390febfda7200c89a5b6;
var _createHeader2 = _interopRequireDefault(_createHeader);
var _skate = __7a6521db1039cb333e437aa8031353cf;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Header = (0, _skate2.default)('aui-header', {
type: _skate2.default.type.CLASSNAME,
created: function created(element) {
(0, _createHeader2.default)(element);
}
});
exports.default = Header;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui-header-async.js
(typeof window === 'undefined' ? global : window).__adc62a3293570a8cd4d623fd6b6da805 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
__f4243cbdeeb31de2885ed6caf30d3f96;
exports.default = window.AJS;
module.exports = exports['default'];
return module.exports;
}).call(this); | {
"content_hash": "39de972fa52ea0944991505f44884295",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 101,
"avg_line_length": 25.870967741935484,
"alnum_prop": 0.655860349127182,
"repo_name": "cdnjs/cdnjs",
"id": "cd60aeac1066bb2f5b2e3da6be483b21159c9270",
"size": "1604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/aui/7.7.0-beta-3/aui/js/aui-header-async.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package game.control.packets;
import game.control.GameClient;
import game.control.GameServer;
/**
* Packet sent when a player takes damage.
*
* DAMAGE - 04 + "," + String hitPlayer + "," + String attacker + "," + double
* damage
*
* @author Cameron Bryers 300326848 MMXV
*
*/
public class Packet04Damage extends Packet {
private String hitPlayer;
private String attacker;
private double damage;
/**
* Constructor intended for sending data.
*
* @param data
* - message to be sent
*/
public Packet04Damage(byte data[]) {
super(04);
// Having commas in the byte array makes it easier to read the
// information off it
String[] dataArray = readData(data).split(",");
// Read the information
hitPlayer = dataArray[0];
attacker = dataArray[1];
damage = Double.parseDouble(dataArray[2]);
}
/**
* Constructor intended for receiving data
*
* @param hitPlayer
* - player that is hit
* @param attacker
* - player that is attacking
* @param damage
* - damage hit player receives
*/
public Packet04Damage(String hitPlayer, String attacker, double damage) {
super(04);
this.hitPlayer = hitPlayer;
this.attacker = attacker;
this.damage = damage;
}
@Override
public void writeData(GameClient client) {
client.sendData(getData());
}
@Override
public void writeData(GameServer server) {
server.sendDataToAllClients(getData());
}
@Override
public byte[] getData() {
return ("04" + hitPlayer + "," + attacker + "," + damage).getBytes();
}
/**
* Get the hitPlayer's username.
*
* @return player's username
*/
public final String getHitPlayer() {
return hitPlayer.trim();
}
/**
* Get the attackingPlayer's username.
*
* @return player's username
*/
public final String getAttacker() {
return attacker.trim();
}
/**
* Damage that the player sustains.
*
* @return damage for player
*/
public final double getDamage() {
return damage;
}
}
| {
"content_hash": "4fc372639933de3b84f075e63fa7c98a",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 78,
"avg_line_length": 20.151515151515152,
"alnum_prop": 0.6546365914786968,
"repo_name": "Cambis/SWEN222_Game",
"id": "27ad92fd285db06450685789f75383143050b1b5",
"size": "1995",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Final_Project/src/game/control/packets/Packet04Damage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12842"
},
{
"name": "HTML",
"bytes": "2042972"
},
{
"name": "Java",
"bytes": "210555"
},
{
"name": "JavaScript",
"bytes": "827"
}
],
"symlink_target": ""
} |
package com.sksamuel.elastic4s
import com.sksamuel.elastic4s.mappings.FieldType.StringType
import com.sksamuel.elastic4s.testkit.ElasticSugar
import org.scalatest.mock.MockitoSugar
import org.scalatest.{ FlatSpec, Matchers }
import com.sksamuel.elastic4s.ElasticDsl._
/** @author Stephen Samuel */
class PercolateTest extends FlatSpec with Matchers with MockitoSugar with ElasticSugar {
client.execute {
create index "percolate" mappings {
"teas" as {
"flavour" typed StringType
}
}
}.await
client.execute {
register id "a" into "percolate" query {
termQuery("flavour", "assam")
}
}.await
client.execute {
register id "b" into "percolate" query {
termQuery("flavour", "earl")
}
}.await
client.execute {
register id "c" into "percolate" query {
termQuery("flavour", "darjeeling")
}
}.await
"a percolate request" should "return queries that match the document" in {
val matches = client.execute {
percolate in "percolate/teas" doc "flavour" -> "assam"
}.await.getMatches
matches.size shouldBe 1
matches(0).getId.string shouldBe "a"
}
"a percolate request for existing document" should "return queries that match the document" in {
val _id = client.execute {
index into "percolate/teas" source """{"flavour" : "earl"}"""
}.await.id
refresh("percolate").await
val matches = client.execute {
percolate in "percolate/teas" id _id
}.await.getMatches
matches.size shouldBe 1
matches(0).getId.string shouldBe "b"
}
}
| {
"content_hash": "1a7ca4d792dff3b8d7780471f6213222",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 98,
"avg_line_length": 24.307692307692307,
"alnum_prop": 0.6746835443037975,
"repo_name": "muuki88/elastic4s",
"id": "07adb05ff241f3f1b7614e57ef873e405f4e3b0f",
"size": "1580",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "elastic4s-core-tests/src/test/scala/com/sksamuel/elastic4s/PercolateTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "655957"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Auxano.Osm.Api
{
/// <summary>
/// Manager for working with terms.
/// </summary>
public class TermManager
{
private readonly Connection connection;
internal TermManager(Connection connection)
{
this.connection = connection;
}
/// <summary>
/// Lists all the terms.
/// </summary>
/// <param name="section">The <see cref="Section"/> to list the terms for.</param>
/// <returns>A list of all the terms.</returns>
public async Task<TermArray> ListForSectionAsync(Section section)
{
var parsedTerms = await connection.PostAsync<Dictionary<string, TermResponse[]>>("api.php?action=getTerms", null);
TermResponse[] termsToConvert;
if (parsedTerms.TryGetValue(section.Id, out termsToConvert))
{
var terms = termsToConvert
.Select(t => new Term(t.name, t.termid, Utils.ParseDate(t.startdate).Value, Utils.ParseDate(t.enddate).Value, section));
return new TermArray(section, terms);
}
return new TermArray(section, new Term[0]);
}
private class TermResponse
{
public string enddate { get; set; }
public string name { get; set; }
public string sectionid { get; set; }
public string startdate { get; set; }
public string termid { get; set; }
}
}
} | {
"content_hash": "cc97b0ba6f1dbf9544a001df308665b1",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 140,
"avg_line_length": 33.53191489361702,
"alnum_prop": 0.5793147208121827,
"repo_name": "craigsammisutherland/osm.api",
"id": "93e1f3969efb10bf3bc7b5420308b0261e78e1d7",
"size": "1578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Auxano.Osm.Api/TermManager.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "101571"
}
],
"symlink_target": ""
} |
using System.Linq.Expressions;
using GlobalsFramework.Linq.ExpressionProcessing;
using GlobalsFramework.Linq.Helpers;
using GlobalsFramework.Utils.InstanceCreation;
namespace GlobalsFramework.Linq.QueryProcessing
{
internal sealed class ElementAtOrDefaultQueryProcessor : IQueryProcessor
{
public bool CanProcess(MethodCallExpression query)
{
return query.Method.Name == "ElementAtOrDefault";
}
public ProcessingResult ProcessQuery(MethodCallExpression query, ProcessingResult parentResult, DataContext context)
{
var index = (int)((ConstantExpression)query.Arguments[1]).Value;
var enumerator = parentResult.GetItems().GetEnumerator();
var elementType = QueryProcessingHelper.GetReturnParameterType(query);
while (index >= 0)
{
if (!enumerator.MoveNext())
return new ProcessingResult(true, InstanceCreator.GetDefaultValue(elementType), true);
index--;
}
return new ProcessingResult(true, enumerator.Current, true);
}
}
}
| {
"content_hash": "ab58ed558d05a75f6ca24b5107270e66",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 124,
"avg_line_length": 35.484848484848484,
"alnum_prop": 0.6498719043552519,
"repo_name": "intersystems-ru/Globals-EF",
"id": "5a2f0350418a88e16ea362909116ef0e14972546",
"size": "1173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GlobalsFrameworkModel/Linq/QueryProcessing/ElementAtOrDefaultQueryProcessor.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "360732"
}
],
"symlink_target": ""
} |
package org.slf4j.simple;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
import static org.slf4j.simple.SimpleLogger.DEFAULT_LOG_LEVEL_KEY;
import static org.slf4j.simple.SimpleLogger.SHOW_THREAD_NAME_KEY;
/**
* A testing utility to allow control over {@link org.slf4j.impl.SimpleLogger}. In some cases,
* reflection is used to bypass access restrictions.
*/
public final class RecordingSimpleLogger implements TestRule {
private String expectedMessages = "";
/**
* Resets {@link org.slf4j.impl.SimpleLogger} to the new log level.
*/
public RecordingSimpleLogger logLevel(String logLevel) throws Exception {
System.setProperty(SHOW_THREAD_NAME_KEY, "false");
System.setProperty(DEFAULT_LOG_LEVEL_KEY, logLevel);
SimpleLogger.init();
((SimpleLoggerFactory) LoggerFactory.getILoggerFactory()).reset();
return this;
}
/**
* Newline delimited output that would be sent to stderr.
*/
public RecordingSimpleLogger expectMessages(String expectedMessages) {
this.expectedMessages = expectedMessages;
return this;
}
/**
* Steals the output of stderr as that's where the log events go.
*/
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
ByteArrayOutputStream buff = new ByteArrayOutputStream();
PrintStream stderr = System.err;
try {
System.setErr(new PrintStream(buff));
base.evaluate();
assertEquals(expectedMessages, buff.toString());
} finally {
System.setErr(stderr);
}
}
};
}
}
| {
"content_hash": "60d085c2c4008b6e23098c8cdf25bdc1",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 94,
"avg_line_length": 30.29032258064516,
"alnum_prop": 0.7108626198083067,
"repo_name": "OpenFeign/feign",
"id": "169ad14bde62e25063f3d33185943c0140078010",
"size": "2473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "slf4j/src/test/java/org/slf4j/simple/RecordingSimpleLogger.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1672805"
},
{
"name": "Kotlin",
"bytes": "12568"
},
{
"name": "Mustache",
"bytes": "1491"
},
{
"name": "Shell",
"bytes": "2672"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
import os
import sys
from datetime import datetime
import shutil
import tempfile
import time
from nose.plugins.skip import SkipTest
sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))))
sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
import helper
from elodie.media.media import Media
from elodie.media.photo import Photo
os.environ['TZ'] = 'GMT'
setup_module = helper.setup_module
teardown_module = helper.teardown_module
def test_photo_extensions():
photo = Photo()
extensions = photo.extensions
assert 'arw' in extensions
assert 'cr2' in extensions
assert 'dng' in extensions
assert 'gif' in extensions
assert 'heic' in extensions
assert 'jpg' in extensions
assert 'jpeg' in extensions
assert 'nef' in extensions
assert 'png' in extensions
assert 'rw2' in extensions
valid_extensions = Photo.get_valid_extensions()
assert extensions == valid_extensions, valid_extensions
def test_empty_album():
photo = Photo(helper.get_file('plain.jpg'))
assert photo.get_album() is None
def test_has_album():
photo = Photo(helper.get_file('with-album.jpg'))
album = photo.get_album()
assert album == 'Test Album', album
def test_is_valid():
photo = Photo(helper.get_file('plain.jpg'))
assert photo.is_valid()
def test_is_not_valid():
photo = Photo(helper.get_file('text.txt'))
assert not photo.is_valid()
def test_get_metadata_of_invalid_photo():
photo = Photo(helper.get_file('invalid.jpg'))
metadata = photo.get_metadata()
assert metadata is None
def test_get_coordinate_default():
photo = Photo(helper.get_file('with-location.jpg'))
coordinate = photo.get_coordinate()
assert helper.isclose(coordinate,37.3667027222), coordinate
def test_get_coordinate_latitude():
photo = Photo(helper.get_file('with-location.jpg'))
coordinate = photo.get_coordinate('latitude')
assert helper.isclose(coordinate,37.3667027222), coordinate
def test_get_coordinate_latitude_minus():
photo = Photo(helper.get_file('with-location-inv.jpg'))
coordinate = photo.get_coordinate('latitude')
assert helper.isclose(coordinate,-37.3667027222), coordinate
def test_get_coordinate_longitude():
photo = Photo(helper.get_file('with-location.jpg'))
coordinate = photo.get_coordinate('longitude')
assert helper.isclose(coordinate,-122.033383611), coordinate
def test_get_coordinate_longitude_plus():
photo = Photo(helper.get_file('with-location-inv.jpg'))
coordinate = photo.get_coordinate('longitude')
assert helper.isclose(coordinate,122.033383611), coordinate
def test_get_coordinates_without_exif():
photo = Photo(helper.get_file('no-exif.jpg'))
latitude = photo.get_coordinate('latitude')
longitude = photo.get_coordinate('longitude')
assert latitude is None, latitude
assert longitude is None, longitude
def test_get_coordinates_with_zero_coordinate():
photo = Photo(helper.get_file('with-location-zero-coordinate.jpg'))
latitude = photo.get_coordinate('latitude')
longitude = photo.get_coordinate('longitude')
assert helper.isclose(latitude,51.55325), latitude
assert helper.isclose(longitude,-0.00417777777778), longitude
def test_get_coordinates_with_null_coordinate():
photo = Photo(helper.get_file('with-null-coordinates.jpg'))
latitude = photo.get_coordinate('latitude')
longitude = photo.get_coordinate('longitude')
assert latitude is None, latitude
assert longitude is None, longitude
def test_get_date_taken():
photo = Photo(helper.get_file('plain.jpg'))
date_taken = photo.get_date_taken()
#assert date_taken == (2015, 12, 5, 0, 59, 26, 5, 339, 0), date_taken
assert date_taken == helper.time_convert((2015, 12, 5, 0, 59, 26, 5, 339, 0)), date_taken
def test_get_date_taken_without_exif():
source = helper.get_file('no-exif.jpg')
photo = Photo(source)
date_taken = photo.get_date_taken()
date_taken_from_file = time.gmtime(min(os.path.getmtime(source), os.path.getctime(source)))
assert date_taken == date_taken_from_file, date_taken
def test_get_camera_make():
photo = Photo(helper.get_file('with-location.jpg'))
make = photo.get_camera_make()
assert make == 'Canon', make
def test_get_camera_make_not_set():
photo = Photo(helper.get_file('no-exif.jpg'))
make = photo.get_camera_make()
assert make is None, make
def test_get_camera_model():
photo = Photo(helper.get_file('with-location.jpg'))
model = photo.get_camera_model()
assert model == 'Canon EOS REBEL T2i', model
def test_get_camera_model_not_set():
photo = Photo(helper.get_file('no-exif.jpg'))
model = photo.get_camera_model()
assert model is None, model
def test_is_valid():
photo = Photo(helper.get_file('with-location.jpg'))
assert photo.is_valid()
def test_is_not_valid():
photo = Photo(helper.get_file('text.txt'))
assert not photo.is_valid()
def test_is_valid_fallback_using_pillow():
photo = Photo(helper.get_file('imghdr-error.jpg'))
assert photo.is_valid()
def test_pillow_not_loaded():
photo = Photo(helper.get_file('imghdr-error.jpg'))
photo.pillow = None
assert photo.is_valid() == False
def test_set_album():
temporary_folder, folder = helper.create_working_folder()
origin = '%s/photo.jpg' % folder
shutil.copyfile(helper.get_file('plain.jpg'), origin)
photo = Photo(origin)
metadata = photo.get_metadata()
assert metadata['album'] is None, metadata['album']
status = photo.set_album('Test Album')
assert status == True, status
photo_new = Photo(origin)
metadata_new = photo_new.get_metadata()
shutil.rmtree(folder)
assert metadata_new['album'] == 'Test Album', metadata_new['album']
def test_set_date_taken_with_missing_datetimeoriginal():
# When datetimeoriginal (or other key) is missing we have to add it gh-74
# https://github.com/jmathai/elodie/issues/74
temporary_folder, folder = helper.create_working_folder()
origin = '%s/photo.jpg' % folder
shutil.copyfile(helper.get_file('no-exif.jpg'), origin)
photo = Photo(origin)
status = photo.set_date_taken(datetime(2013, 9, 30, 7, 6, 5))
assert status == True, status
photo_new = Photo(origin)
metadata = photo_new.get_metadata()
date_taken = metadata['date_taken']
shutil.rmtree(folder)
#assert date_taken == (2013, 9, 30, 7, 6, 5, 0, 273, 0), metadata['date_taken']
assert date_taken == helper.time_convert((2013, 9, 30, 7, 6, 5, 0, 273, 0)), metadata['date_taken']
def test_set_date_taken():
temporary_folder, folder = helper.create_working_folder()
origin = '%s/photo.jpg' % folder
shutil.copyfile(helper.get_file('plain.jpg'), origin)
photo = Photo(origin)
status = photo.set_date_taken(datetime(2013, 9, 30, 7, 6, 5))
assert status == True, status
photo_new = Photo(origin)
metadata = photo_new.get_metadata()
date_taken = metadata['date_taken']
shutil.rmtree(folder)
#assert date_taken == (2013, 9, 30, 7, 6, 5, 0, 273, 0), metadata['date_taken']
assert date_taken == helper.time_convert((2013, 9, 30, 7, 6, 5, 0, 273, 0)), metadata['date_taken']
def test_set_location():
temporary_folder, folder = helper.create_working_folder()
origin = '%s/photo.jpg' % folder
shutil.copyfile(helper.get_file('plain.jpg'), origin)
photo = Photo(origin)
origin_metadata = photo.get_metadata()
# Verify that original photo has different location info that what we
# will be setting and checking
assert not helper.isclose(origin_metadata['latitude'], 11.1111111111), origin_metadata['latitude']
assert not helper.isclose(origin_metadata['longitude'], 99.9999999999), origin_metadata['longitude']
status = photo.set_location(11.1111111111, 99.9999999999)
assert status == True, status
photo_new = Photo(origin)
metadata = photo_new.get_metadata()
shutil.rmtree(folder)
assert helper.isclose(metadata['latitude'], 11.1111111111), metadata['latitude']
assert helper.isclose(metadata['longitude'], 99.9999999999), metadata['longitude']
def test_set_location_minus():
temporary_folder, folder = helper.create_working_folder()
origin = '%s/photo.jpg' % folder
shutil.copyfile(helper.get_file('plain.jpg'), origin)
photo = Photo(origin)
origin_metadata = photo.get_metadata()
# Verify that original photo has different location info that what we
# will be setting and checking
assert not helper.isclose(origin_metadata['latitude'], 11.1111111111), origin_metadata['latitude']
assert not helper.isclose(origin_metadata['longitude'], 99.9999999999), origin_metadata['longitude']
status = photo.set_location(-11.1111111111, -99.9999999999)
assert status == True, status
photo_new = Photo(origin)
metadata = photo_new.get_metadata()
shutil.rmtree(folder)
assert helper.isclose(metadata['latitude'], -11.1111111111), metadata['latitude']
assert helper.isclose(metadata['longitude'], -99.9999999999), metadata['longitude']
def test_set_title():
temporary_folder, folder = helper.create_working_folder()
origin = '%s/photo.jpg' % folder
shutil.copyfile(helper.get_file('plain.jpg'), origin)
photo = Photo(origin)
origin_metadata = photo.get_metadata()
status = photo.set_title('my photo title')
assert status == True, status
photo_new = Photo(origin)
metadata = photo_new.get_metadata()
shutil.rmtree(folder)
assert metadata['title'] == 'my photo title', metadata['title']
def test_set_title_non_ascii():
temporary_folder, folder = helper.create_working_folder()
origin = '%s/photo.jpg' % folder
shutil.copyfile(helper.get_file('plain.jpg'), origin)
photo = Photo(origin)
origin_metadata = photo.get_metadata()
unicode_title = u'形声字 / 形聲字'
status = photo.set_title(unicode_title)
assert status == True, status
photo_new = Photo(origin)
metadata = photo_new.get_metadata()
shutil.rmtree(folder)
assert metadata['title'] == unicode_title, metadata['title']
# This is a test generator that will test reading and writing to
# various RAW formats. Each sample file has a different date which
# is the only information which needs to be added to run the tests
# for that file type.
# https://nose.readthedocs.io/en/latest/writing_tests.html#test-generators
def test_various_types():
types = Photo.extensions
#extensions = ('arw', 'cr2', 'dng', 'gif', 'jpeg', 'jpg', 'nef', 'rw2')
dates = {
'arw': (2007, 4, 8, 17, 41, 18, 6, 98, 0),
'cr2': (2005, 10, 29, 16, 14, 44, 5, 302, 0),
'dng': (2009, 10, 20, 9, 10, 46, 1, 293, 0),
'heic': (2019, 5, 26, 10, 33, 20, 6, 146, 0),
'nef': (2008, 10, 24, 9, 12, 56, 4, 298, 0),
'png': (2015, 1, 18, 12, 1, 1, 6, 18, 0),
'rw2': (2014, 11, 19, 23, 7, 44, 2, 323, 0)
}
for type in types:
if type in dates:
yield (_test_photo_type_get, type, dates[type])
yield (_test_photo_type_set, type, dates[type])
def _test_photo_type_get(type, date):
temporary_folder, folder = helper.create_working_folder()
photo_name = 'photo.{}'.format(type)
photo_file = helper.get_file(photo_name)
origin = '{}/{}'.format(folder, photo_name)
if not photo_file:
photo_file = helper.download_file(photo_name, folder)
if not photo_file or not os.path.isfile(photo_file):
raise SkipTest('{} file not downlaoded'.format(type))
# downloading for each test is costly so we save it in the working directory
file_path_save_as = helper.get_file_path(photo_name)
if os.path.isfile(photo_file):
shutil.copyfile(photo_file, file_path_save_as)
shutil.copyfile(photo_file, origin)
photo = Photo(origin)
metadata = photo.get_metadata()
shutil.rmtree(folder)
assert metadata['date_taken'] == helper.time_convert(date), '{} date {}'.format(type, metadata['date_taken'])
def _test_photo_type_set(type, date):
temporary_folder, folder = helper.create_working_folder()
photo_name = 'photo.{}'.format(type)
photo_file = helper.get_file(photo_name)
origin = '{}/{}'.format(folder, photo_name)
if not photo_file:
photo_file = helper.download_file(photo_name, folder)
if not photo_file or not os.path.isfile(photo_file):
raise SkipTest('{} file not downlaoded'.format(type))
shutil.copyfile(photo_file, origin)
photo = Photo(origin)
origin_metadata = photo.get_metadata()
status = photo.set_location(11.1111111111, 99.9999999999)
assert status == True, status
photo_new = Photo(origin)
metadata = photo_new.get_metadata()
shutil.rmtree(folder)
assert metadata['date_taken'] == helper.time_convert(date), '{} date {}'.format(type, metadata['date_taken'])
assert helper.isclose(metadata['latitude'], 11.1111111111), '{} lat {}'.format(type, metadata['latitude'])
assert helper.isclose(metadata['longitude'], 99.9999999999), '{} lon {}'.format(type, metadata['latitude'])
| {
"content_hash": "87f6b41d9bfeb8390126e6e1dfe3c0ac",
"timestamp": "",
"source": "github",
"line_count": 420,
"max_line_length": 131,
"avg_line_length": 31.8,
"alnum_prop": 0.6740790655884995,
"repo_name": "jmathai/elodie",
"id": "dd391ee1eb2c227adc368b737641e109cd3c185c",
"size": "13406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "elodie/tests/media/photo_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12517"
},
{
"name": "Dockerfile",
"bytes": "1231"
},
{
"name": "HTML",
"bytes": "8996"
},
{
"name": "JavaScript",
"bytes": "17406"
},
{
"name": "Python",
"bytes": "284527"
},
{
"name": "Shell",
"bytes": "89"
}
],
"symlink_target": ""
} |
#ifndef ASF_H
#define ASF_H
/*
* This file includes all API header files for the selected drivers from ASF.
* Note: There might be duplicate includes required by more than one driver.
*
* The file is automatically generated and will be re-written when
* running the ASF driver selector tool. Any changes will be discarded.
*/
// From module: CPU specific features
#include <ccp.h>
#include <xmega_reset_cause.h>
// From module: GPIO - General purpose Input/Output
#include <gpio.h>
// From module: Generic board support
#include <board.h>
// From module: Generic components of unit test framework
#include <unit_test/suite.h>
// From module: IOPORT - General purpose I/O service
#include <ioport.h>
// From module: Interrupt management - XMEGA implementation
#include <interrupt.h>
// From module: PMIC - Programmable Multi-level Interrupt Controller
#include <pmic.h>
// From module: Part identification macros
#include <parts.h>
// From module: RTC - Real Time Counter
#include <rtc.h>
// From module: Sleep Controller driver
#include <sleep.h>
// From module: Sleep manager - XMEGA A/AU/B/D implementation
#include <sleepmgr.h>
#include <xmega/sleepmgr.h>
// From module: Standard serial I/O (stdio) - XMEGA implementation
#include <stdio_serial.h>
// From module: System Clock Control - XMEGA A1/A3/A3B/A4/D/E implementation
#include <sysclk.h>
// From module: Timeout Service XMEGA
#include <timeout.h>
// From module: USART - Serial interface - XMEGA implementation
#include <serial.h>
// From module: USART - Universal Synchronous/Asynchronous Receiver/Transmitter
#include <usart.h>
// From module: XMEGA compiler driver
#include <compiler.h>
#include <status_codes.h>
// From module: XMEGA-A1 Xplained LED support enabled
#include <led.h>
#endif // ASF_H
| {
"content_hash": "2ef540f9c281df58f6f9f4b23721cb0b",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 79,
"avg_line_length": 26.04225352112676,
"alnum_prop": 0.7160627366143861,
"repo_name": "femtoio/femto-usb-blink-example",
"id": "e3012543fc7d47fbc4b63da422eeab6f3654c15f",
"size": "3641",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "blinky/blinky/asf-3.21.0/xmega/services/timeout/unit_tests/atxmega128a1_xmega_a1_xplained/iar/asf.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "178794"
},
{
"name": "C",
"bytes": "251878780"
},
{
"name": "C++",
"bytes": "47991929"
},
{
"name": "CSS",
"bytes": "2147"
},
{
"name": "HTML",
"bytes": "107322"
},
{
"name": "JavaScript",
"bytes": "588817"
},
{
"name": "Logos",
"bytes": "570108"
},
{
"name": "Makefile",
"bytes": "64558964"
},
{
"name": "Matlab",
"bytes": "10660"
},
{
"name": "Objective-C",
"bytes": "15780083"
},
{
"name": "Perl",
"bytes": "12845"
},
{
"name": "Python",
"bytes": "67293"
},
{
"name": "Scilab",
"bytes": "88572"
},
{
"name": "Shell",
"bytes": "126729"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "076e4a25b8c407bae2871163cbf7584f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "66507fadf25f47fdf89ee24812d7f989e1aeac22",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Acanthophyllum/Acanthophyllum maimanense/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
fn main() {
let original:f64=15.0;//value seems irrelevant (take 1% 459 times to get down to 1%)
let percent_to_take:f64=1.;//take this % of original until it's:
let target_percent:f64=0.0;//down to % of the original value
//TODO: use 0.0 ^ and make the below if work, also this: http://floating-point-gui.de/
let mut total:f64 = original;
let mut count=0;
let mut taken_value;
let cached_target=target_percent*original/100.;
/* let mut a=0.0;
let b:f64=target_percent*original/100.;
loop {
if a <= b {
break;
}*/
loop {
if total as f64 <= cached_target as f64 {
break;
}
taken_value=total * percent_to_take/100.;
total-=taken_value;
count+=1;
println!("[{}] {} {} target={}", count, total, taken_value, cached_target);
if count>1715 {
break;
}
}
println!("Takes {} times to take {}% from initial value of {} to get it down to {} which is {}%(that is: {})",
count, percent_to_take, original, total, target_percent, cached_target);
}
| {
"content_hash": "2bd8e859f472f0daeea01b6373d3b2c3",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 114,
"avg_line_length": 34.96875,
"alnum_prop": 0.5674709562109026,
"repo_name": "respeccing/rustLearnage",
"id": "479ce3577a9a3e833bcae45d98ef3a8f03b64bac",
"size": "1119",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "rust_sandbox/take1percent/src/main.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Rust",
"bytes": "69349"
},
{
"name": "Shell",
"bytes": "2126"
}
],
"symlink_target": ""
} |
namespace Google.Cloud.AIPlatform.V1.Snippets
{
// [START aiplatform_v1_generated_DatasetService_ImportData_async]
using Google.Cloud.AIPlatform.V1;
using Google.LongRunning;
using System.Threading.Tasks;
public sealed partial class GeneratedDatasetServiceClientSnippets
{
/// <summary>Snippet for ImportDataAsync</summary>
/// <remarks>
/// This snippet has been automatically generated and should be regarded as a code template only.
/// It will require modifications to work:
/// - It may require correct/in-range values for request initialization.
/// - It may require specifying regional endpoints when creating the service client as shown in
/// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
/// </remarks>
public async Task ImportDataRequestObjectAsync()
{
// Create client
DatasetServiceClient datasetServiceClient = await DatasetServiceClient.CreateAsync();
// Initialize request argument(s)
ImportDataRequest request = new ImportDataRequest
{
DatasetName = DatasetName.FromProjectLocationDataset("[PROJECT]", "[LOCATION]", "[DATASET]"),
ImportConfigs =
{
new ImportDataConfig(),
},
};
// Make the request
Operation<ImportDataResponse, ImportDataOperationMetadata> response = await datasetServiceClient.ImportDataAsync(request);
// Poll until the returned long-running operation is complete
Operation<ImportDataResponse, ImportDataOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ImportDataResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ImportDataResponse, ImportDataOperationMetadata> retrievedResponse = await datasetServiceClient.PollOnceImportDataAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ImportDataResponse retrievedResult = retrievedResponse.Result;
}
}
}
// [END aiplatform_v1_generated_DatasetService_ImportData_async]
}
| {
"content_hash": "b75d2c7fe39e32a4406039721dee740b",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 157,
"avg_line_length": 50.25,
"alnum_prop": 0.6624569460390356,
"repo_name": "googleapis/google-cloud-dotnet",
"id": "036ba07e0235217fb23c01815e1d35e4f42425a1",
"size": "3235",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "apis/Google.Cloud.AIPlatform.V1/Google.Cloud.AIPlatform.V1.GeneratedSnippets/DatasetServiceClient.ImportDataRequestObjectAsyncSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "767"
},
{
"name": "C#",
"bytes": "319820004"
},
{
"name": "Dockerfile",
"bytes": "3415"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Python",
"bytes": "2744"
},
{
"name": "Shell",
"bytes": "65881"
}
],
"symlink_target": ""
} |
Test ResourceBundle::__construct() - existing/missing bundles/locales
--SKIPIF--
<?php if( !extension_loaded( 'intl' ) ) print 'skip'; ?>
--FILE--
<?php
include "resourcebundle.inc";
function ut_main() {
$str_res = '';
// all fine
$r1 = ut_resourcebundle_create( 'root', BUNDLE );
$str_res .= debug( $r1 );
$str_res .= print_r( $r1['teststring'], true)."\n";
// non-root one
$r1 = ut_resourcebundle_create( 'es', BUNDLE );
$str_res .= debug( $r1 );
$str_res .= print_r( $r1['teststring'], true)."\n";
// fall back
$r1 = ut_resourcebundle_create( 'en_US', BUNDLE );
$str_res .= debug( $r1 );
$str_res .= print_r( $r1['testsring'], true);
// fall out
$r2 = ut_resourcebundle_create( 'en_US', BUNDLE, false );
$str_res .= debug( $r2 );
// missing
$r3 = ut_resourcebundle_create( 'en_US', 'nonexisting' );
$str_res .= debug( $r3 );
return $str_res;
}
include_once( 'ut_common.inc' );
ut_run();
?>
--EXPECTF--
ResourceBundle Object
(
)
0: U_ZERO_ERROR
Hello World!
ResourceBundle Object
(
)
0: U_ZERO_ERROR
Hola Mundo!
ResourceBundle Object
(
)
-127: U_USING_DEFAULT_WARNING
NULL
2: resourcebundle_ctor: Cannot load libICU resource bundle: U_MISSING_RESOURCE_ERROR
NULL
2: resourcebundle_ctor: Cannot load libICU resource bundle: U_MISSING_RESOURCE_ERROR
| {
"content_hash": "f53d593baaab84b2b77bca1bba88dc49",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 88,
"avg_line_length": 21.688524590163933,
"alnum_prop": 0.6281179138321995,
"repo_name": "lunaczp/learning",
"id": "2bf4f556a8609515fd000361680925315c23a201",
"size": "1332",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "language/c/testPhpSrc/php-5.6.17/ext/intl/tests/resourcebundle_create.phpt",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "4526"
},
{
"name": "Assembly",
"bytes": "14500403"
},
{
"name": "Awk",
"bytes": "21252"
},
{
"name": "Batchfile",
"bytes": "2526"
},
{
"name": "C",
"bytes": "381839655"
},
{
"name": "C++",
"bytes": "10162228"
},
{
"name": "CMake",
"bytes": "68196"
},
{
"name": "CSS",
"bytes": "3943"
},
{
"name": "D",
"bytes": "1022"
},
{
"name": "DTrace",
"bytes": "4528"
},
{
"name": "Fortran",
"bytes": "1834"
},
{
"name": "GAP",
"bytes": "4344"
},
{
"name": "GDB",
"bytes": "31864"
},
{
"name": "Gnuplot",
"bytes": "148"
},
{
"name": "Go",
"bytes": "732"
},
{
"name": "HTML",
"bytes": "86756"
},
{
"name": "Java",
"bytes": "8286"
},
{
"name": "JavaScript",
"bytes": "238365"
},
{
"name": "Lex",
"bytes": "121233"
},
{
"name": "Limbo",
"bytes": "1609"
},
{
"name": "Lua",
"bytes": "96"
},
{
"name": "M4",
"bytes": "483288"
},
{
"name": "Makefile",
"bytes": "1915601"
},
{
"name": "Nix",
"bytes": "180099"
},
{
"name": "Objective-C",
"bytes": "1742504"
},
{
"name": "OpenEdge ABL",
"bytes": "4238"
},
{
"name": "PHP",
"bytes": "27984629"
},
{
"name": "Pascal",
"bytes": "74868"
},
{
"name": "Perl",
"bytes": "317465"
},
{
"name": "Perl 6",
"bytes": "6916"
},
{
"name": "Python",
"bytes": "21547"
},
{
"name": "R",
"bytes": "1112"
},
{
"name": "Roff",
"bytes": "435717"
},
{
"name": "Scilab",
"bytes": "22980"
},
{
"name": "Shell",
"bytes": "468206"
},
{
"name": "UnrealScript",
"bytes": "20840"
},
{
"name": "Vue",
"bytes": "563"
},
{
"name": "XSLT",
"bytes": "7946"
},
{
"name": "Yacc",
"bytes": "172805"
},
{
"name": "sed",
"bytes": "2073"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= webpackConfig.metadata.title %></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="<%= webpackConfig.metadata.title %>">
<!-- base url -->
<base href="<%= webpackConfig.metadata.baseUrl %>">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="app/vendor/materialize-css/css/materialize.css">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="<%= webpackConfig.metadata.bootstrapCss %>">
<link rel="stylesheet" href="<%= webpackConfig.metadata.mainCss %>">
</head>
<body>
<!-- Application Component -->
<app>
Loading...
</app>
<% if (webpackConfig.metadata.ENV === 'development') { %>
<!-- Webpack Dev Server reload -->
<script src="/webpack-dev-server.js"></script>
<% } %>
</body>
</html>
| {
"content_hash": "95abd3e0ff0c1d9c3922280425c3a556",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 87,
"avg_line_length": 26.05128205128205,
"alnum_prop": 0.6614173228346457,
"repo_name": "IcodeNet/angular2-webpack-typescript",
"id": "641f50fcf8376372cadf2021a3a3edbf5b5c6025",
"size": "1016",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1061"
},
{
"name": "HTML",
"bytes": "1114"
},
{
"name": "JavaScript",
"bytes": "9364"
},
{
"name": "TypeScript",
"bytes": "5096"
}
],
"symlink_target": ""
} |
/* ************************************************************************
************************************************************************ */
qx.Mixin.define("dev.layout.LayoutVerticalBoxLayout", {
members: {
createVerticalBoxLayout : function ( theThis, elem, parent ) {
var obj = new qx.ui.container.Composite( new qx.ui.layout.VBox );
this.processAttributes( theThis, elem, obj );
this.processChildren( theThis, elem, obj );
return obj;
}
}
});
| {
"content_hash": "b0c44edff25404ef13ac2647fbf6e156",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 75,
"avg_line_length": 30,
"alnum_prop": 0.46875,
"repo_name": "smc314/helix",
"id": "4c90ddf1433f2d99930ad4af43519991706899bc",
"size": "730",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "qd/dev/source/class/dev/layout/LayoutVerticalBoxLayout.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "144970"
},
{
"name": "C#",
"bytes": "149673"
},
{
"name": "C++",
"bytes": "1273269"
},
{
"name": "CSS",
"bytes": "33151"
},
{
"name": "HTML",
"bytes": "13682406"
},
{
"name": "Java",
"bytes": "2214"
},
{
"name": "JavaScript",
"bytes": "7725953"
},
{
"name": "Makefile",
"bytes": "7470"
},
{
"name": "Python",
"bytes": "19101"
},
{
"name": "Shell",
"bytes": "71831"
}
],
"symlink_target": ""
} |
module ProfitBricksProvision
class ServerGetIp
include Server::Base
include Server::Config
include Server::DataCenter
def self.run
new.run
end
def run
dc = ProfitBricks::Datacenter.find_by_name(dc_name)
unless dc
error "Datacenter #{dc_name.inspect} not exist"
end
server = dc.server_by_name(server_name)
if server
print server.ips.first
else
error "Server '#{server_name}' not found in data_center '#{dc_name}'"
end
end
end
end
| {
"content_hash": "036148331a166f3c27a18ffcf238e328",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 77,
"avg_line_length": 19.285714285714285,
"alnum_prop": 0.6185185185185185,
"repo_name": "webhoernchen/profitbricks_provision",
"id": "5af1af4395098dec07b8a3b68146aa1e78c77212",
"size": "540",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/profitbricks_provision/server_get_ip.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "33651"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
class FootballStandings
{
static void Main()
{
string key = Console.ReadLine();
string line = Console.ReadLine();
var teams = new Dictionary<string, Team>();
while (line != "final")
{
var splitedLine = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
string teamsPattern = key + @"{1,}(.*?)" + key + "{1,}";
Regex regex = new Regex(teamsPattern);
MatchCollection match = regex.Matches(line);
string teamA = Reverse(match[0].Groups[1].Value).ToLower();
string teamB = Reverse(match[1].Groups[1].Value).ToLower();
var goalsBothTeams = splitedLine[2].Split(':');
ulong goalsTeamA = ulong.Parse(goalsBothTeams[0]);
ulong goalsTeamB = ulong.Parse(goalsBothTeams[1]);
ulong pointsTeamA = 0;
ulong pointsTeamB = 0;
if (goalsTeamA > goalsTeamB)
{
pointsTeamA = 3;
}
else if (goalsTeamA == goalsTeamB)
{
pointsTeamA = 1;
pointsTeamB = 1;
}
else
{
pointsTeamB = 3;
}
if (!teams.ContainsKey(teamA))
{
teams[teamA] = new Team();
teams[teamA].goals += goalsTeamA;
teams[teamA].points += pointsTeamA;
}
else
{
teams[teamA].goals += goalsTeamA;
teams[teamA].points += pointsTeamA;
}
if (!teams.ContainsKey(teamB))
{
teams[teamB] = new Team();
teams[teamB].goals += goalsTeamB;
teams[teamB].points += pointsTeamB;
}
else
{
teams[teamB].goals += goalsTeamB;
teams[teamB].points += pointsTeamB;
}
line = Console.ReadLine();
}
Console.WriteLine("League standings:");
int i = 1;
foreach (var team in teams.OrderByDescending(p => p.Value.points).ThenBy(n => n.Key))
{
Console.WriteLine($"{i}. {team.Key.ToUpper()} {team.Value.points}");
i++;
}
Console.WriteLine("Top 3 scored goals:");
var topScoredGoals = teams.OrderByDescending(g => g.Value.goals).ThenBy(n => n.Key).Take(3);
foreach (var team in topScoredGoals)
{
Console.WriteLine($"- {team.Key.ToUpper()} -> {team.Value.goals}");
}
}
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
class Team
{
public ulong goals { get; set; }
public ulong points { get; set; }
}
| {
"content_hash": "3b3fdd63560e21db385d2cb749a601ce",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 106,
"avg_line_length": 29.647058823529413,
"alnum_prop": 0.5089285714285714,
"repo_name": "sevdalin/Software-University-SoftUni",
"id": "f19fe1b91a77a4e6f2fc98d142692fcc22b34895",
"size": "3026",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Programming-Fundamentals/All EXAMS/ProgFundamentals Exam - 12 June 2016/ProgFundnExam 12-06-16/03. Football Standings/FootballStandings.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "388"
},
{
"name": "C#",
"bytes": "3998101"
},
{
"name": "CSS",
"bytes": "161101"
},
{
"name": "HTML",
"bytes": "261529"
},
{
"name": "Java",
"bytes": "20909"
},
{
"name": "JavaScript",
"bytes": "609440"
},
{
"name": "PHP",
"bytes": "16185"
},
{
"name": "PLSQL",
"bytes": "723"
},
{
"name": "PLpgSQL",
"bytes": "4714"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Ruby",
"bytes": "1030"
},
{
"name": "SQLPL",
"bytes": "3383"
},
{
"name": "Smalltalk",
"bytes": "2065"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.s3.internal;
import com.amazonaws.http.HttpResponse;
/**
* Assistant response handler that can pull an HTTP header out of the response
* and apply it to a response object.
*/
public interface HeaderHandler<T> {
/**
* Applies one or more headers to the response object given.
*
* @param result
* The response object to be returned to the client.
* @param response
* The HTTP response from s3.
*/
public void handle(T result, HttpResponse response);
}
| {
"content_hash": "fba183f71972d2076ce532d492435bf4",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 78,
"avg_line_length": 27.38095238095238,
"alnum_prop": 0.6347826086956522,
"repo_name": "aws/aws-sdk-java",
"id": "119c919f7d88b42a6c4014fe7f0fe186ba67e140",
"size": "1099",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/internal/HeaderHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
\input{query-cards/interactive-short-read-01}
\input{query-cards/interactive-short-read-02}
\input{query-cards/interactive-short-read-03}
\input{query-cards/interactive-short-read-04}
\input{query-cards/interactive-short-read-05}
\input{query-cards/interactive-short-read-06}
\input{query-cards/interactive-short-read-07}
| {
"content_hash": "49a1bb07d5905824a7514133ee303fa7",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 45,
"avg_line_length": 46,
"alnum_prop": 0.8043478260869565,
"repo_name": "ldbc/ldbc_snb_docs",
"id": "2755c595b7e2a81985a1a67fe6b5489b62de69c0",
"size": "322",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "interactive-short-reads.tex",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "42"
},
{
"name": "Dockerfile",
"bytes": "96"
},
{
"name": "Makefile",
"bytes": "1120"
},
{
"name": "Perl",
"bytes": "13847"
},
{
"name": "Python",
"bytes": "16809"
},
{
"name": "Shell",
"bytes": "5213"
},
{
"name": "TeX",
"bytes": "572504"
}
],
"symlink_target": ""
} |
Hallo,<br>
<br>
Hier ist der Link zu unserem Holzmarkt Beauty Contest.
Wenn du da rauf klickst bekommst du in deinem Webbrowser immer zwei Bilder nebeneinander
angezeigt. Sei spontan, welches sagt dir mehr zu?<br>
Klicke drauf, dann kommt ein neues Bildpaar, usf.<br>
Das Ergebnis sagt dir und uns, wie Holzmarktig du bisti, d.h. wie sehr du mit deiner Wahl mit unserem Durchschnitt zusammenpasst.
Das ist nur ein Experiment, wenn du keine Lust drauf hast, mach es nicht.
Du kannst den Link nur einmal klicken, also vertuh' dich nicht.
<br>
<br>
Viel Spass,<br>
Steini
<br>
<br>
<a href="{{ url }}">Holzmarkt Beauty-Contest</a>
| {
"content_hash": "233038afa5a569b79caf00d0950fd3f3",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 131,
"avg_line_length": 33.31578947368421,
"alnum_prop": 0.7551342812006319,
"repo_name": "rickgr/holzmarkt",
"id": "61859a2f206ea3be43eb0f4a6132bdccd58d7f33",
"size": "633",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/beautycontest/templates/testeemail.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "0"
},
{
"name": "Python",
"bytes": "19183"
},
{
"name": "Shell",
"bytes": "621"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/UsbongDefaultParentLayout">
<LinearLayout
style="@style/UsbongDefaultMainLayout">
<TextView android:id="@+id/difficulty_textview"
style="@style/UsbongDefaultTextView"
android:text="Did you see a fishkill incident today?: " />
<RadioGroup android:id="@+id/yes_no_radiogroup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/yes_radiobutton"
style="@style/UsbongYesNoRadioButton"
android:checked="true"
android:text=" Yes" />
<RadioButton android:id="@+id/no_radiobutton"
style="@style/UsbongYesNoRadioButton"
android:checked="false"
android:text=" No" />
</RadioGroup>
<LinearLayout
style="@style/UsbongDefaultBackNextButtonLayout">
<Button android:id="@+id/back_button"
style="@style/UsbongDefaultBackNextButton"
android:text="Back"/>
<Button android:id="@+id/next_button"
style="@style/UsbongDefaultBackNextButton"
android:text="Next"/>
</LinearLayout>
</LinearLayout>
</LinearLayout> | {
"content_hash": "d67b66c7b72151b3c497b358ab93634d",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 72,
"avg_line_length": 34.97222222222222,
"alnum_prop": 0.6751389992057188,
"repo_name": "usbong/usbong_pagtsing",
"id": "3b2b0f0830c0376aecf8588251d33e3ccb1b2786",
"size": "1259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/layout/engine.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "407336"
}
],
"symlink_target": ""
} |
.class public Landroid/webkit/WebStorage$Origin;
.super Ljava/lang/Object;
.source "WebStorage.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/webkit/WebStorage;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x9
name = "Origin"
.end annotation
# instance fields
.field private mOrigin:Ljava/lang/String;
.field private mQuota:J
.field private mUsage:J
# direct methods
.method protected constructor <init>(Ljava/lang/String;)V
.locals 3
.parameter "origin"
.prologue
const-wide/16 v1, 0x0
.line 78
invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V
.line 60
const/4 v0, 0x0
iput-object v0, p0, Landroid/webkit/WebStorage$Origin;->mOrigin:Ljava/lang/String;
.line 61
iput-wide v1, p0, Landroid/webkit/WebStorage$Origin;->mQuota:J
.line 62
iput-wide v1, p0, Landroid/webkit/WebStorage$Origin;->mUsage:J
.line 79
iput-object p1, p0, Landroid/webkit/WebStorage$Origin;->mOrigin:Ljava/lang/String;
.line 80
return-void
.end method
.method protected constructor <init>(Ljava/lang/String;J)V
.locals 3
.parameter "origin"
.parameter "quota"
.prologue
const-wide/16 v1, 0x0
.line 72
invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V
.line 60
const/4 v0, 0x0
iput-object v0, p0, Landroid/webkit/WebStorage$Origin;->mOrigin:Ljava/lang/String;
.line 61
iput-wide v1, p0, Landroid/webkit/WebStorage$Origin;->mQuota:J
.line 62
iput-wide v1, p0, Landroid/webkit/WebStorage$Origin;->mUsage:J
.line 73
iput-object p1, p0, Landroid/webkit/WebStorage$Origin;->mOrigin:Ljava/lang/String;
.line 74
iput-wide p2, p0, Landroid/webkit/WebStorage$Origin;->mQuota:J
.line 75
return-void
.end method
.method protected constructor <init>(Ljava/lang/String;JJ)V
.locals 3
.parameter "origin"
.parameter "quota"
.parameter "usage"
.prologue
const-wide/16 v1, 0x0
.line 65
invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V
.line 60
const/4 v0, 0x0
iput-object v0, p0, Landroid/webkit/WebStorage$Origin;->mOrigin:Ljava/lang/String;
.line 61
iput-wide v1, p0, Landroid/webkit/WebStorage$Origin;->mQuota:J
.line 62
iput-wide v1, p0, Landroid/webkit/WebStorage$Origin;->mUsage:J
.line 66
iput-object p1, p0, Landroid/webkit/WebStorage$Origin;->mOrigin:Ljava/lang/String;
.line 67
iput-wide p2, p0, Landroid/webkit/WebStorage$Origin;->mQuota:J
.line 68
iput-wide p4, p0, Landroid/webkit/WebStorage$Origin;->mUsage:J
.line 69
return-void
.end method
# virtual methods
.method public getOrigin()Ljava/lang/String;
.locals 1
.prologue
.line 93
iget-object v0, p0, Landroid/webkit/WebStorage$Origin;->mOrigin:Ljava/lang/String;
return-object v0
.end method
.method public getQuota()J
.locals 2
.prologue
.line 104
iget-wide v0, p0, Landroid/webkit/WebStorage$Origin;->mQuota:J
return-wide v0
.end method
.method public getUsage()J
.locals 2
.prologue
.line 114
iget-wide v0, p0, Landroid/webkit/WebStorage$Origin;->mUsage:J
return-wide v0
.end method
| {
"content_hash": "948e600c2cf2fe7661ca0179f07574ff",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 86,
"avg_line_length": 21.605263157894736,
"alnum_prop": 0.6830085261875761,
"repo_name": "baidurom/devices-n7108",
"id": "8b554ca5193db699b703ecc732d22c2e64e26df9",
"size": "3284",
"binary": false,
"copies": "2",
"ref": "refs/heads/coron-4.1",
"path": "framework.jar.out/smali/android/webkit/WebStorage$Origin.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "12697"
},
{
"name": "Shell",
"bytes": "1974"
}
],
"symlink_target": ""
} |
module Denotificator
VERSION = "0.0.3"
end
| {
"content_hash": "bd18b9219bf4914d0547206a6519150d",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 20,
"avg_line_length": 15,
"alnum_prop": 0.7111111111111111,
"repo_name": "marcosvm/denotificator",
"id": "675a25d05c539d2e19a5cbb4e1886653363fafcb",
"size": "45",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/denotificator/version.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "4682"
}
],
"symlink_target": ""
} |
/*!
* jQuery QueryBuilder 2.5.2
* Locale: English (en)
* Author: Damien "Mistic" Sorel, http://www.strangeplanet.fr
* Licensed under MIT (https://opensource.org/licenses/MIT)
*/
(function(root, factory) {
if (typeof define == 'function' && define.amd) {
define(['jquery', 'query-builder'], factory);
}
else {
factory(root.jQuery);
}
}(this, function($) {
"use strict";
var QueryBuilder = $.fn.queryBuilder;
QueryBuilder.regional['en'] = {
"__locale": "English (en)",
"__author": "Damien \"Mistic\" Sorel, http://www.strangeplanet.fr",
"add_rule": "Add rule",
"add_group": "Add group",
"delete_rule": "Delete",
"delete_group": "Delete",
"conditions": {
"AND": "AND",
"OR": "OR"
},
"operators": {
"equal": "equal",
"not_equal": "not equal",
"in": "in",
"not_in": "not in",
"less": "less",
"less_or_equal": "less or equal",
"greater": "greater",
"greater_or_equal": "greater or equal",
"between": "between",
"not_between": "not between",
"begins_with": "begins with",
"not_begins_with": "doesn't begin with",
"contains": "contains",
"not_contains": "doesn't contain",
"ends_with": "ends with",
"not_ends_with": "doesn't end with",
"is_empty": "is empty",
"is_not_empty": "is not empty",
"is_null": "is null",
"is_not_null": "is not null"
},
"errors": {
"no_filter": "No filter selected",
"empty_group": "The group is empty",
"radio_empty": "No value selected",
"checkbox_empty": "No value selected",
"select_empty": "No value selected",
"string_empty": "Empty value",
"string_exceed_min_length": "Must contain at least {0} characters",
"string_exceed_max_length": "Must not contain more than {0} characters",
"string_invalid_format": "Invalid format ({0})",
"number_nan": "Not a number",
"number_not_integer": "Not an integer",
"number_not_double": "Not a real number",
"number_exceed_min": "Must be greater than {0}",
"number_exceed_max": "Must be lower than {0}",
"number_wrong_step": "Must be a multiple of {0}",
"number_between_invalid": "Invalid values, {0} is greater than {1}",
"datetime_empty": "Empty value",
"datetime_invalid": "Invalid date format ({0})",
"datetime_exceed_min": "Must be after {0}",
"datetime_exceed_max": "Must be before {0}",
"datetime_between_invalid": "Invalid values, {0} is greater than {1}",
"boolean_not_valid": "Not a boolean",
"operator_not_multiple": "Operator \"{1}\" cannot accept multiple values"
},
"invert": "Invert",
"NOT": "NOT"
};
QueryBuilder.defaults({ lang_code: 'en' });
}));
/*! Select2 4.0.13 | https://github.com/select2/select2/blob/master/LICENSE.md */
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;e.define("select2/i18n/en",[],function(){return{errorLoading:function(){return"The results could not be loaded."},inputTooLong:function(e){var n=e.input.length-e.maximum,r="Please delete "+n+" character";return 1!=n&&(r+="s"),r},inputTooShort:function(e){return"Please enter "+(e.minimum-e.input.length)+" or more characters"},loadingMore:function(){return"Loading more results…"},maximumSelected:function(e){var n="You can only select "+e.maximum+" item";return 1!=e.maximum&&(n+="s"),n},noResults:function(){return"No results found"},searching:function(){return"Searching…"},removeAllItems:function(){return"Remove all items"}}}),e.define,e.require}();
/*!
* Bootstrap-select v1.13.17 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Nothing selected',
noneResultsText: 'No results match {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? '{0} item selected' : '{0} items selected';
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
(numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
];
},
selectAllText: 'Select All',
deselectAllText: 'Deselect All',
multipleSeparator: ', '
};
})(jQuery);
}));
//# sourceMappingURL=defaults-en_US.js.map
/*!
* Ajax Bootstrap Select
*
* Extends existing [Bootstrap Select] implementations by adding the ability to search via AJAX requests as you type. Originally for CROSCON.
*
* @version 1.4.5
* @author Adam Heim - https://github.com/truckingsim
* @link https://github.com/truckingsim/Ajax-Bootstrap-Select
* @copyright 2019 Adam Heim
* @license Released under the MIT license.
*
* Contributors:
* Mark Carver - https://github.com/markcarver
*
* Last build: 2019-04-23 12:18:55 PM EDT
*/
!(function ($) {
/*
* Note: You do not have to load this translation file. English is the
* default language of this plugin and is compiled into it automatically.
*
* This file is just to serve as the default string mappings and as a
* template for future translations.
* @see: ./src/js/locale/en-US.js
*
* Four character language codes are supported ("en-US") and will always
* take precedence over two character language codes ("en") if present.
*
* When copying this file, remove all comments except the one above the
* definition objection giving credit to the translation author.
*/
/*!
* English translation for the "en-US" and "en" language codes.
* Mark Carver <[email protected]>
*/
$.fn.ajaxSelectPicker.locale['en-US'] = {
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} currentlySelected = 'Currently Selected'
* @markdown
* The text to use for the label of the option group when currently selected options are preserved.
*/
currentlySelected: 'Currently Selected',
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} emptyTitle = 'Select and begin typing'
* @markdown
* The text to use as the title for the select element when there are no items to display.
*/
emptyTitle: 'Select and begin typing',
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} errorText = ''Unable to retrieve results'
* @markdown
* The text to use in the status container when a request returns with an error.
*/
errorText: 'Unable to retrieve results',
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} searchPlaceholder = 'Search...'
* @markdown
* The text to use for the search input placeholder attribute.
*/
searchPlaceholder: 'Search...',
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} statusInitialized = 'Start typing a search query'
* @markdown
* The text used in the status container when it is initialized.
*/
statusInitialized: 'Start typing a search query',
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} statusNoResults = 'No Results'
* @markdown
* The text used in the status container when the request returns no results.
*/
statusNoResults: 'No Results',
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} statusSearching = 'Searching...'
* @markdown
* The text to use in the status container when a request is being initiated.
*/
statusSearching: 'Searching...',
/**
* @member $.fn.ajaxSelectPicker.locale
* @cfg {String} statusTooShort = 'Please enter more characters'
* @markdown
* The text used in the status container when the request returns no results.
*/
statusTooShort: 'Please enter more characters'
};
$.fn.ajaxSelectPicker.locale.en = $.fn.ajaxSelectPicker.locale['en-US'];
})(jQuery);
//! moment.js locale configuration
//! locale : English (United Kingdom) [en-gb]
//! author : Chris Gedrim : https://github.com/chrisgedrim
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
//! moment.js locale configuration
var enGb = moment.defineLocale('en-gb', {
months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
'_'
),
monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(
'_'
),
weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd, D MMMM YYYY HH:mm',
},
calendar: {
sameDay: '[Today at] LT',
nextDay: '[Tomorrow at] LT',
nextWeek: 'dddd [at] LT',
lastDay: '[Yesterday at] LT',
lastWeek: '[Last] dddd [at] LT',
sameElse: 'L',
},
relativeTime: {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
ss: '%d seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years',
},
dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/,
ordinal: function (number) {
var b = number % 10,
output =
~~((number % 100) / 10) === 1
? 'th'
: b === 1
? 'st'
: b === 2
? 'nd'
: b === 3
? 'rd'
: 'th';
return number + output;
},
week: {
dow: 1, // Monday is the first day of the week.
doy: 4, // The week that contains Jan 4th is the first week of the year.
},
});
return enGb;
})));
| {
"content_hash": "11bb551f6e0b669b1a98bfa32f0f7a39",
"timestamp": "",
"source": "github",
"line_count": 315,
"max_line_length": 757,
"avg_line_length": 35.476190476190474,
"alnum_prop": 0.5986577181208054,
"repo_name": "swayok/PeskyCMF",
"id": "19e366cb1ece2a4a0fbf0ed15f54be5d3a4a8cca",
"size": "11179",
"binary": false,
"copies": "1",
"ref": "refs/heads/v2",
"path": "npm/dist/packed/js/locale/en_GB.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "56036"
},
{
"name": "CSS",
"bytes": "184094"
},
{
"name": "HTML",
"bytes": "3753"
},
{
"name": "Hack",
"bytes": "578"
},
{
"name": "JavaScript",
"bytes": "1226543"
},
{
"name": "Less",
"bytes": "87154"
},
{
"name": "PHP",
"bytes": "1195012"
},
{
"name": "SCSS",
"bytes": "3129"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.opsworks.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.opsworks.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateInstanceResult JSON Unmarshaller
*/
public class CreateInstanceResultJsonUnmarshaller implements
Unmarshaller<CreateInstanceResult, JsonUnmarshallerContext> {
public CreateInstanceResult unmarshall(JsonUnmarshallerContext context)
throws Exception {
CreateInstanceResult createInstanceResult = new CreateInstanceResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("InstanceId", targetDepth)) {
context.nextToken();
createInstanceResult.setInstanceId(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return createInstanceResult;
}
private static CreateInstanceResultJsonUnmarshaller instance;
public static CreateInstanceResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateInstanceResultJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "32f232fad18f8442a9a50a036f000687",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 79,
"avg_line_length": 34.15151515151515,
"alnum_prop": 0.6251109139307897,
"repo_name": "trasa/aws-sdk-java",
"id": "d87847466d0b46fe41c561a91274dcb8babb27d2",
"size": "2838",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/transform/CreateInstanceResultJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "100011199"
},
{
"name": "Scilab",
"bytes": "2354"
}
],
"symlink_target": ""
} |
#ifndef SRC_LIBCRYPTOBOX_BASE64_BASE64_H_
#define SRC_LIBCRYPTOBOX_BASE64_BASE64_H_
#include "config.h"
const char* base64_load (void);
#endif /* SRC_LIBCRYPTOBOX_BASE64_BASE64_H_ */
| {
"content_hash": "99a6c3110e299845630302b1292266e2",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 46,
"avg_line_length": 20.77777777777778,
"alnum_prop": 0.7379679144385026,
"repo_name": "AlexeySa/rspamd",
"id": "e7c639d585adc081255d7b9a280b3856b702ecf0",
"size": "785",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/libcryptobox/base64/base64.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "297971"
},
{
"name": "C",
"bytes": "11099110"
},
{
"name": "C++",
"bytes": "91123"
},
{
"name": "CMake",
"bytes": "170769"
},
{
"name": "CSS",
"bytes": "14178"
},
{
"name": "HTML",
"bytes": "14747"
},
{
"name": "Java",
"bytes": "13174"
},
{
"name": "JavaScript",
"bytes": "102041"
},
{
"name": "Lua",
"bytes": "2234819"
},
{
"name": "Makefile",
"bytes": "12428"
},
{
"name": "PHP",
"bytes": "58538"
},
{
"name": "Pascal",
"bytes": "87"
},
{
"name": "Perl",
"bytes": "73903"
},
{
"name": "Python",
"bytes": "7698"
},
{
"name": "Ragel",
"bytes": "26306"
},
{
"name": "RobotFramework",
"bytes": "74060"
},
{
"name": "Roff",
"bytes": "22"
},
{
"name": "Shell",
"bytes": "7684"
},
{
"name": "SourcePawn",
"bytes": "3118"
},
{
"name": "Standard ML",
"bytes": "128"
}
],
"symlink_target": ""
} |
This is the repository for fast_log, a logging library previously used in the chef-server. The Chef server now uses lager <https://github.com/basho/lager>
Chef is a system integration framework written in erlang and ruby and designed to bring the benefits of configuration management to your entire infrastructure.
The Chef Docs site is the definitive source of user documentation. <https://docs.chef.io/>
This README focuses on developers who want to modify Chef source code. For users who just want to run the latest and greatest Chef development version in their environment, see: <https://www.chef.io/>
## Development
Before working on the code, if you plan to contribute your changes, you need to read the Chef Contributing document.
<https://github.com/chef/chef/blob/master/CONTRIBUTING.md>
You will also need to set up the repository with the appropriate branches. We document the process on the Chef Wiki.
Once your repository is set up, you can start working on the code.
## Links
Source:
<https://github.com/chef/fast-log-erlang>
Documentation:
<https://docs.chef.io/>
## Contributing
For information on contributing to this project see <https://github.com/chef/chef/blob/master/CONTRIBUTING.md>
## License
- Copyright:: Copyright 2011-2016 Chef Software, Inc.
- License:: Apache License, Version 2.0
```text
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.
```
| {
"content_hash": "598aba955b9ab808c94be29a5abfed28",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 200,
"avg_line_length": 37.32,
"alnum_prop": 0.7781350482315113,
"repo_name": "chef/fast-log-erlang",
"id": "813f875b0cbdf238dd8b5cc33955e6aa178738d6",
"size": "1878",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Erlang",
"bytes": "18416"
},
{
"name": "Makefile",
"bytes": "321"
}
],
"symlink_target": ""
} |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
// {{{ Header
/**
* Calculates, manipulates and retrieves dates
*
* It does not rely on 32-bit system time stamps, so it works dates
* before 1970 and after 2038.
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 1999-2007 Monte Ohrt, Pierre-Alain Joye, Daniel Convissor,
* C.A. Woodcock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted under the terms of the BSD License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @category Date and Time
* @package Date
* @author Monte Ohrt <[email protected]>
* @author Pierre-Alain Joye <[email protected]>
* @author Daniel Convissor <[email protected]>
* @author C.A. Woodcock <[email protected]>
* @copyright 1999-2007 Monte Ohrt, Pierre-Alain Joye, Daniel Convissor, C.A. Woodcock
* @license http://www.opensource.org/licenses/bsd-license.php
* BSD License
* @version CVS: $Id: Calc.php,v 1.56 2007/12/08 19:59:39 c01234 Exp $
* @link http://pear.php.net/package/Date
* @since File available since Release 1.2
*/
// }}}
// {{{ General constants:
if (!defined('DATE_CALC_BEGIN_WEEKDAY')) {
/**
* Defines what day starts the week
*
* Monday (1) is the international standard.
* Redefine this to 0 if you want weeks to begin on Sunday.
*/
define('DATE_CALC_BEGIN_WEEKDAY', 1);
}
if (!defined('DATE_CALC_FORMAT')) {
/**
* The default value for each method's $format parameter
*
* The default is '%Y%m%d'. To override this default, define
* this constant before including Calc.php.
*
* @since Constant available since Release 1.4.4
*/
define('DATE_CALC_FORMAT', '%Y%m%d');
}
// {{{ Date precision constants (used in 'round()' and 'trunc()'):
define('DATE_PRECISION_YEAR', -2);
define('DATE_PRECISION_MONTH', -1);
define('DATE_PRECISION_DAY', 0);
define('DATE_PRECISION_HOUR', 1);
define('DATE_PRECISION_10MINUTES', 2);
define('DATE_PRECISION_MINUTE', 3);
define('DATE_PRECISION_10SECONDS', 4);
define('DATE_PRECISION_SECOND', 5);
// }}}
// {{{ Class: Date_Calc
/**
* Calculates, manipulates and retrieves dates
*
* It does not rely on 32-bit system time stamps, so it works dates
* before 1970 and after 2038.
*
* @category Date and Time
* @package Date
* @author Monte Ohrt <[email protected]>
* @author Daniel Convissor <[email protected]>
* @author C.A. Woodcock <[email protected]>
* @copyright 1999-2007 Monte Ohrt, Pierre-Alain Joye, Daniel Convissor, C.A. Woodcock
* @license http://www.opensource.org/licenses/bsd-license.php
* BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/Date
* @since Class available since Release 1.2
*/
class Date_Calc
{
// {{{ dateFormat()
/**
* Formats the date in the given format, much like strfmt()
*
* This function is used to alleviate the problem with 32-bit numbers for
* dates pre 1970 or post 2038, as strfmt() has on most systems.
* Most of the formatting options are compatible.
*
* Formatting options:
* <pre>
* %a abbreviated weekday name (Sun, Mon, Tue)
* %A full weekday name (Sunday, Monday, Tuesday)
* %b abbreviated month name (Jan, Feb, Mar)
* %B full month name (January, February, March)
* %d day of month (range 00 to 31)
* %e day of month, single digit (range 0 to 31)
* %E number of days since unspecified epoch (integer)
* (%E is useful for passing a date in a URL as
* an integer value. Then simply use
* daysToDate() to convert back to a date.)
* %j day of year (range 001 to 366)
* %m month as decimal number (range 1 to 12)
* %n newline character (\n)
* %t tab character (\t)
* %w weekday as decimal (0 = Sunday)
* %U week number of current year, first sunday as first week
* %y year as decimal (range 00 to 99)
* %Y year as decimal including century (range 0000 to 9999)
* %% literal '%'
* </pre>
*
* @param int $day the day of the month
* @param int $month the month
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
* @param string $format the format string
*
* @return string the date in the desired format
* @access public
* @static
*/
function dateFormat($day, $month, $year, $format)
{
if (!Date_Calc::isValidDate($day, $month, $year)) {
$year = Date_Calc::dateNow('%Y');
$month = Date_Calc::dateNow('%m');
$day = Date_Calc::dateNow('%d');
}
$output = '';
for ($strpos = 0; $strpos < strlen($format); $strpos++) {
$char = substr($format, $strpos, 1);
if ($char == '%') {
$nextchar = substr($format, $strpos + 1, 1);
switch($nextchar) {
case 'a':
$output .= Date_Calc::getWeekdayAbbrname($day, $month, $year);
break;
case 'A':
$output .= Date_Calc::getWeekdayFullname($day, $month, $year);
break;
case 'b':
$output .= Date_Calc::getMonthAbbrname($month);
break;
case 'B':
$output .= Date_Calc::getMonthFullname($month);
break;
case 'd':
$output .= sprintf('%02d', $day);
break;
case 'e':
$output .= $day;
break;
case 'E':
$output .= Date_Calc::dateToDays($day, $month, $year);
break;
case 'j':
$output .= Date_Calc::dayOfYear($day, $month, $year);
break;
case 'm':
$output .= sprintf('%02d', $month);
break;
case 'n':
$output .= "\n";
break;
case 't':
$output .= "\t";
break;
case 'w':
$output .= Date_Calc::dayOfWeek($day, $month, $year);
break;
case 'U':
$output .= Date_Calc::weekOfYear($day, $month, $year);
break;
case 'y':
$output .= sprintf('%0' .
($year < 0 ? '3' : '2') .
'd',
$year % 100);
break;
case "Y":
$output .= sprintf('%0' .
($year < 0 ? '5' : '4') .
'd',
$year);
break;
case '%':
$output .= '%';
break;
default:
$output .= $char.$nextchar;
}
$strpos++;
} else {
$output .= $char;
}
}
return $output;
}
// }}}
// {{{ dateNow()
/**
* Returns the current local date
*
* NOTE: This function retrieves the local date using strftime(),
* which may or may not be 32-bit safe on your system.
*
* @param string $format the string indicating how to format the output
*
* @return string the current date in the specified format
* @access public
* @static
*/
function dateNow($format = DATE_CALC_FORMAT)
{
return strftime($format, time());
}
// }}}
// {{{ getYear()
/**
* Returns the current local year in format CCYY
*
* @return string the current year in four digit format
* @access public
* @static
*/
function getYear()
{
return Date_Calc::dateNow('%Y');
}
// }}}
// {{{ getMonth()
/**
* Returns the current local month in format MM
*
* @return string the current month in two digit format
* @access public
* @static
*/
function getMonth()
{
return Date_Calc::dateNow('%m');
}
// }}}
// {{{ getDay()
/**
* Returns the current local day in format DD
*
* @return string the current day of the month in two digit format
* @access public
* @static
*/
function getDay()
{
return Date_Calc::dateNow('%d');
}
// }}}
// {{{ defaultCentury()
/**
* Turns a two digit year into a four digit year
*
* Return value depends on current year; the century chosen
* will be the one which forms the year that is closest
* to the current year. If the two possibilities are
* equidistant to the current year (i.e. 50 years in the past
* and 50 years in the future), then the past year is chosen.
*
* For example, if the current year is 2007:
* 03 - returns 2003
* 09 - returns 2009
* 56 - returns 2056 (closer to 2007 than 1956)
* 57 - returns 1957 (1957 and 2007 are equidistant, so previous century
* chosen)
* 58 - returns 1958
*
* @param int $year the 2 digit year
*
* @return int the 4 digit year
* @access public
* @static
*/
function defaultCentury($year)
{
$hn_century = intval(($hn_currentyear = date("Y")) / 100);
$hn_currentyear = $hn_currentyear % 100;
if ($year < 0 || $year >= 100)
$year = $year % 100;
if ($year - $hn_currentyear < -50)
return ($hn_century + 1) * 100 + $year;
else if ($year - $hn_currentyear < 50)
return $hn_century * 100 + $year;
else
return ($hn_century - 1) * 100 + $year;
}
// }}}
// {{{ getSecondsInYear()
/**
* Returns the total number of seconds in the given year
*
* This takes into account leap seconds.
*
* @param int $pn_year the year in four digit format
*
* @return int
* @access public
* @static
* @since Method available since Release [next version]
*/
function getSecondsInYear($pn_year)
{
$pn_year = intval($pn_year);
static $ha_leapseconds;
if (!isset($ha_leapseconds)) {
$ha_leapseconds = array(1972 => 2,
1973 => 1,
1974 => 1,
1975 => 1,
1976 => 1,
1977 => 1,
1978 => 1,
1979 => 1,
1981 => 1,
1982 => 1,
1983 => 1,
1985 => 1,
1987 => 1,
1989 => 1,
1990 => 1,
1992 => 1,
1993 => 1,
1994 => 1,
1995 => 1,
1997 => 1,
1998 => 1,
2005 => 1);
}
$ret = Date_Calc::daysInYear($pn_year) * 86400;
if (isset($ha_leapseconds[$pn_year])) {
return $ret + $ha_leapseconds[$pn_year];
} else {
return $ret;
}
}
// }}}
// {{{ getSecondsInMonth()
/**
* Returns the total number of seconds in the given month
*
* This takes into account leap seconds.
*
* @param int $pn_month the month
* @param int $pn_year the year in four digit format
*
* @return int
* @access public
* @static
* @since Method available since Release [next version]
*/
function getSecondsInMonth($pn_month, $pn_year)
{
$pn_month = intval($pn_month);
$pn_year = intval($pn_year);
static $ha_leapseconds;
if (!isset($ha_leapseconds)) {
$ha_leapseconds = array(1972 => array(6 => 1,
12 => 1),
1973 => array(12 => 1),
1974 => array(12 => 1),
1975 => array(12 => 1),
1976 => array(12 => 1),
1977 => array(12 => 1),
1978 => array(12 => 1),
1979 => array(12 => 1),
1981 => array(6 => 1),
1982 => array(6 => 1),
1983 => array(6 => 1),
1985 => array(6 => 1),
1987 => array(12 => 1),
1989 => array(12 => 1),
1990 => array(12 => 1),
1992 => array(6 => 1),
1993 => array(6 => 1),
1994 => array(6 => 1),
1995 => array(12 => 1),
1997 => array(6 => 1),
1998 => array(12 => 1),
2005 => array(12 => 1));
}
$ret = Date_Calc::daysInMonth($pn_month, $pn_year) * 86400;
if (isset($ha_leapseconds[$pn_year][$pn_month])) {
return $ret + $ha_leapseconds[$pn_year][$pn_month];
} else {
return $ret;
}
}
// }}}
// {{{ getSecondsInDay()
/**
* Returns the total number of seconds in the day of the given date
*
* This takes into account leap seconds.
*
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year in four digit format
*
* @return int
* @access public
* @static
* @since Method available since Release [next version]
*/
function getSecondsInDay($pn_day, $pn_month, $pn_year)
{
// Note to developers:
//
// The leap seconds listed here are a matter of historical fact,
// that is, it is known on which exact day they occurred.
// However, the implementation of the class as a whole depends
// on the fact that they always occur at the end of the month
// (although it is assumed that they could occur in any month,
// even though practically they only occur in June or December).
//
// Do not define a leap second on a day of the month other than
// the last day without altering the implementation of the
// functions that depend on this one.
//
// It is possible, though, to define an un-leap second (i.e. a skipped
// second (I do not know what they are called), or a number of
// consecutive leap seconds).
$pn_day = intval($pn_day);
$pn_month = intval($pn_month);
$pn_year = intval($pn_year);
static $ha_leapseconds;
if (!isset($ha_leapseconds)) {
$ha_leapseconds = array(1972 => array(6 => array(30 => 1),
12 => array(31 => 1)),
1973 => array(12 => array(31 => 1)),
1974 => array(12 => array(31 => 1)),
1975 => array(12 => array(31 => 1)),
1976 => array(12 => array(31 => 1)),
1977 => array(12 => array(31 => 1)),
1978 => array(12 => array(31 => 1)),
1979 => array(12 => array(31 => 1)),
1981 => array(6 => array(30 => 1)),
1982 => array(6 => array(30 => 1)),
1983 => array(6 => array(30 => 1)),
1985 => array(6 => array(30 => 1)),
1987 => array(12 => array(31 => 1)),
1989 => array(12 => array(31 => 1)),
1990 => array(12 => array(31 => 1)),
1992 => array(6 => array(30 => 1)),
1993 => array(6 => array(30 => 1)),
1994 => array(6 => array(30 => 1)),
1995 => array(12 => array(31 => 1)),
1997 => array(6 => array(30 => 1)),
1998 => array(12 => array(31 => 1)),
2005 => array(12 => array(31 => 1)));
}
if (isset($ha_leapseconds[$pn_year][$pn_month][$pn_day])) {
return 86400 + $ha_leapseconds[$pn_year][$pn_month][$pn_day];
} else {
return 86400;
}
}
// }}}
// {{{ getSecondsInHour()
/**
* Returns the total number of seconds in the hour of the given date
*
* This takes into account leap seconds.
*
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year in four digit format
* @param int $pn_hour the hour
*
* @return int
* @access public
* @static
*/
function getSecondsInHour($pn_day, $pn_month, $pn_year, $pn_hour)
{
if ($pn_hour < 23)
return 3600;
else
return Date_Calc::getSecondsInDay($pn_day, $pn_month, $pn_year) -
82800;
}
// }}}
// {{{ getSecondsInMinute()
/**
* Returns the total number of seconds in the minute of the given hour
*
* This takes into account leap seconds.
*
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year in four digit format
* @param int $pn_hour the hour
* @param int $pn_minute the minute
*
* @return int
* @access public
* @static
* @since Method available since Release [next version]
*/
function getSecondsInMinute($pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute)
{
if ($pn_hour < 23 || $pn_minute < 59)
return 60;
else
return Date_Calc::getSecondsInDay($pn_day, $pn_month, $pn_year) -
86340;
}
// }}}
// {{{ secondsPastMidnight()
/**
* Returns the no of seconds since midnight (0-86399)
*
* @param int $pn_hour the hour of the day
* @param int $pn_minute the minute
* @param mixed $pn_second the second as integer or float
*
* @return mixed integer or float from 0-86399
* @access public
* @static
* @since Method available since Release [next version]
*/
function secondsPastMidnight($pn_hour, $pn_minute, $pn_second)
{
return 3600 * $pn_hour + 60 * $pn_minute + $pn_second;
}
// }}}
// {{{ secondsPastMidnightToTime()
/**
* Returns the time as an array (i.e. hour, minute, second)
*
* @param mixed $pn_seconds the no of seconds since midnight (0-86399)
*
* @return mixed array of hour, minute (both as integers), second (as
* integer or float, depending on parameter)
* @access public
* @static
* @since Method available since Release [next version]
*/
function secondsPastMidnightToTime($pn_seconds)
{
if ($pn_seconds >= 86400) {
return array(23, 59, $pn_seconds - 86340);
}
$hn_hour = intval($pn_seconds / 3600);
$hn_minute = intval(($pn_seconds - $hn_hour * 3600) / 60);
$hn_second = is_float($pn_seconds) ?
fmod($pn_seconds, 60) :
$pn_seconds % 60;
return array($hn_hour, $hn_minute, $hn_second);
}
// }}}
// {{{ secondsPastTheHour()
/**
* Returns the no of seconds since the last hour o'clock (0-3599)
*
* @param int $pn_minute the minute
* @param mixed $pn_second the second as integer or float
*
* @return mixed integer or float from 0-3599
* @access public
* @static
* @since Method available since Release [next version]
*/
function secondsPastTheHour($pn_minute, $pn_second)
{
return 60 * $pn_minute + $pn_second;
}
// }}}
// {{{ addHours()
/**
* Returns the date the specified no of hours from the given date
*
* To subtract hours use a negative value for the '$pn_hours' parameter
*
* @param int $pn_hours hours to add
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
*
* @return array array of year, month, day, hour
* @access public
* @static
* @since Method available since Release [next version]
*/
function addHours($pn_hours, $pn_day, $pn_month, $pn_year, $pn_hour)
{
if ($pn_hours == 0)
return array((int) $pn_year,
(int) $pn_month,
(int) $pn_day,
(int) $pn_hour);
$hn_days = intval($pn_hours / 24);
$hn_hour = $pn_hour + $pn_hours % 24;
if ($hn_hour >= 24) {
++$hn_days;
$hn_hour -= 24;
} else if ($hn_hour < 0) {
--$hn_days;
$hn_hour += 24;
}
if ($hn_days == 0) {
$hn_year = $pn_year;
$hn_month = $pn_month;
$hn_day = $pn_day;
} else {
list($hn_year, $hn_month, $hn_day) =
explode(" ",
Date_Calc::addDays($hn_days,
$pn_day,
$pn_month,
$pn_year,
"%Y %m %d"));
}
return array((int) $hn_year, (int) $hn_month, (int) $hn_day, $hn_hour);
}
// }}}
// {{{ addMinutes()
/**
* Returns the date the specified no of minutes from the given date
*
* To subtract minutes use a negative value for the '$pn_minutes' parameter
*
* @param int $pn_minutes minutes to add
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
*
* @return array array of year, month, day, hour, minute
* @access public
* @static
* @since Method available since Release [next version]
*/
function addMinutes($pn_minutes,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute)
{
if ($pn_minutes == 0)
return array((int) $pn_year,
(int) $pn_month,
(int) $pn_day,
(int) $pn_hour,
(int) $pn_minute);
$hn_hours = intval($pn_minutes / 60);
$hn_minute = $pn_minute + $pn_minutes % 60;
if ($hn_minute >= 60) {
++$hn_hours;
$hn_minute -= 60;
} else if ($hn_minute < 0) {
--$hn_hours;
$hn_minute += 60;
}
if ($hn_hours == 0) {
$hn_year = $pn_year;
$hn_month = $pn_month;
$hn_day = $pn_day;
$hn_hour = $pn_hour;
} else {
list($hn_year, $hn_month, $hn_day, $hn_hour) =
Date_Calc::addHours($hn_hours,
$pn_day,
$pn_month,
$pn_year,
$pn_hour);
}
return array($hn_year, $hn_month, $hn_day, $hn_hour, $hn_minute);
}
// }}}
// {{{ addSeconds()
/**
* Returns the date the specified no of seconds from the given date
*
* If leap seconds are specified to be counted, the passed time must be UTC.
* To subtract seconds use a negative value for the '$pn_seconds' parameter.
*
* N.B. the return type of the second part of the date is float if
* either '$pn_seconds' or '$pn_second' is a float; otherwise, it
* is integer.
*
* @param mixed $pn_seconds seconds to add as integer or float
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
* @param mixed $pn_second the second as integer or float
* @param bool $pb_countleap whether to count leap seconds (defaults to
* DATE_COUNT_LEAP_SECONDS)
*
* @return array array of year, month, day, hour, minute, second
* @access public
* @static
* @since Method available since Release [next version]
*/
function addSeconds($pn_seconds,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pb_countleap = DATE_COUNT_LEAP_SECONDS)
{
if ($pn_seconds == 0)
return array((int) $pn_year,
(int) $pn_month,
(int) $pn_day,
(int) $pn_hour,
(int) $pn_minute,
$pn_second);
if ($pb_countleap) {
$hn_seconds = $pn_seconds;
$hn_day = (int) $pn_day;
$hn_month = (int) $pn_month;
$hn_year = (int) $pn_year;
$hn_hour = (int) $pn_hour;
$hn_minute = (int) $pn_minute;
$hn_second = $pn_second;
$hn_days = Date_Calc::dateToDays($pn_day,
$pn_month,
$pn_year);
$hn_secondsofmonth = 86400 * ($hn_days -
Date_Calc::firstDayOfMonth($pn_month,
$pn_year)) +
Date_Calc::secondsPastMidnight($pn_hour,
$pn_minute,
$pn_second);
if ($hn_seconds > 0) {
// Advance to end of month:
//
if ($hn_secondsofmonth != 0 &&
$hn_secondsofmonth + $hn_seconds >=
($hn_secondsinmonth =
Date_Calc::getSecondsInMonth($hn_month, $hn_year))) {
$hn_seconds -= $hn_secondsinmonth - $hn_secondsofmonth;
$hn_secondsofmonth = 0;
list($hn_year, $hn_month) =
Date_Calc::nextMonth($hn_month, $hn_year);
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
$hn_year);
$hn_hour = $hn_minute = $hn_second = 0;
}
// Advance to end of year:
//
if ($hn_secondsofmonth == 0 &&
$hn_month != Date_Calc::getFirstMonthOfYear($hn_year)) {
while ($hn_year == $pn_year &&
$hn_seconds >= ($hn_secondsinmonth =
Date_Calc::getSecondsInMonth($hn_month,
$hn_year))) {
$hn_seconds -= $hn_secondsinmonth;
list($hn_year, $hn_month) =
Date_Calc::nextMonth($hn_month, $hn_year);
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
$hn_year);
}
}
if ($hn_secondsofmonth == 0) {
// Add years:
//
if ($hn_month == Date_Calc::getFirstMonthOfYear($hn_year)) {
while ($hn_seconds >= ($hn_secondsinyear =
Date_Calc::getSecondsInYear($hn_year))) {
$hn_seconds -= $hn_secondsinyear;
$hn_month = Date_Calc::getFirstMonthOfYear(++$hn_year);
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
$hn_year);
}
}
// Add months:
//
while ($hn_seconds >= ($hn_secondsinmonth =
Date_Calc::getSecondsInMonth($hn_month, $hn_year))) {
$hn_seconds -= $hn_secondsinmonth;
list($hn_year, $hn_month) =
Date_Calc::nextMonth($hn_month, $hn_year);
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month, $hn_year);
}
}
} else {
//
// (if $hn_seconds < 0)
// Go back to start of month:
//
if ($hn_secondsofmonth != 0 &&
-$hn_seconds >= $hn_secondsofmonth) {
$hn_seconds += $hn_secondsofmonth;
$hn_secondsofmonth = 0;
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
$hn_year);
$hn_hour = $hn_minute = $hn_second = 0;
}
// Go back to start of year:
//
if ($hn_secondsofmonth == 0) {
while ($hn_month !=
Date_Calc::getFirstMonthOfYear($hn_year)) {
list($hn_year, $hn_prevmonth) =
Date_Calc::prevMonth($hn_month, $hn_year);
if (-$hn_seconds >= ($hn_secondsinmonth =
Date_Calc::getSecondsInMonth($hn_prevmonth,
$hn_year))) {
$hn_seconds += $hn_secondsinmonth;
$hn_month = $hn_prevmonth;
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
$hn_year);
} else {
break;
}
}
}
if ($hn_secondsofmonth == 0) {
// Subtract years:
//
if ($hn_month == Date_Calc::getFirstMonthOfYear($hn_year)) {
while (-$hn_seconds >= ($hn_secondsinyear =
Date_Calc::getSecondsInYear($hn_year - 1))) {
$hn_seconds += $hn_secondsinyear;
$hn_month = Date_Calc::getFirstMonthOfYear(--$hn_year);
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
$hn_year);
}
}
// Subtract months:
//
list($hn_pmyear, $hn_prevmonth) =
Date_Calc::prevMonth($hn_month, $hn_year);
while (-$hn_seconds >= ($hn_secondsinmonth =
Date_Calc::getSecondsInMonth($hn_prevmonth,
$hn_pmyear))) {
$hn_seconds += $hn_secondsinmonth;
$hn_year = $hn_pmyear;
$hn_month = $hn_prevmonth;
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month,
$hn_year);
list($hn_pmyear, $hn_prevmonth) =
Date_Calc::prevMonth($hn_month, $hn_year);
}
}
}
if ($hn_seconds < 0 && $hn_secondsofmonth == 0) {
list($hn_year, $hn_month) =
Date_Calc::prevMonth($hn_month, $hn_year);
$hn_day = Date_Calc::getFirstDayOfMonth($hn_month, $hn_year);
$hn_seconds += Date_Calc::getSecondsInMonth($hn_month, $hn_year);
}
$hn_seconds += Date_Calc::secondsPastMidnight($hn_hour,
$hn_minute,
$hn_second);
if ($hn_seconds < 0) {
$hn_daysadd = intval($hn_seconds / 86400) - 1;
} else if ($hn_seconds < 86400) {
$hn_daysadd = 0;
} else {
$hn_daysadd = intval($hn_seconds / 86400) - 1;
}
if ($hn_daysadd != 0) {
list($hn_year, $hn_month, $hn_day) =
explode(" ",
Date_Calc::addDays($hn_daysadd,
$hn_day,
$hn_month,
$hn_year,
"%Y %m %d"));
$hn_seconds -= $hn_daysadd * 86400;
}
$hn_secondsinday = Date_Calc::getSecondsInDay($hn_day,
$hn_month,
$hn_year);
if ($hn_seconds >= $hn_secondsinday) {
list($hn_year, $hn_month, $hn_day) =
explode(" ",
Date_Calc::addDays(1,
$hn_day,
$hn_month,
$hn_year,
"%Y %m %d"));
$hn_seconds -= $hn_secondsinday;
}
list($hn_hour, $hn_minute, $hn_second) =
Date_Calc::secondsPastMidnightToTime($hn_seconds);
return array((int) $hn_year,
(int) $hn_month,
(int) $hn_day,
$hn_hour,
$hn_minute,
$hn_second);
} else {
// Assume every day has 86400 seconds exactly (ignore leap seconds):
//
$hn_minutes = intval($pn_seconds / 60);
if (is_float($pn_seconds)) {
$hn_second = $pn_second + fmod($pn_seconds, 60);
} else {
$hn_second = $pn_second + $pn_seconds % 60;
}
if ($hn_second >= 60) {
++$hn_minutes;
$hn_second -= 60;
} else if ($hn_second < 0) {
--$hn_minutes;
$hn_second += 60;
}
if ($hn_minutes == 0) {
$hn_year = $pn_year;
$hn_month = $pn_month;
$hn_day = $pn_day;
$hn_hour = $pn_hour;
$hn_minute = $pn_minute;
} else {
list($hn_year, $hn_month, $hn_day, $hn_hour, $hn_minute) =
Date_Calc::addMinutes($hn_minutes,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute);
}
return array($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_second);
}
}
// }}}
// {{{ dateToDays()
/**
* Converts a date in the proleptic Gregorian calendar to the no of days
* since 24th November, 4714 B.C.
*
* Returns the no of days since Monday, 24th November, 4714 B.C. in the
* proleptic Gregorian calendar (which is 24th November, -4713 using
* 'Astronomical' year numbering, and 1st January, 4713 B.C. in the
* proleptic Julian calendar). This is also the first day of the 'Julian
* Period' proposed by Joseph Scaliger in 1583, and the number of days
* since this date is known as the 'Julian Day'. (It is not directly
* to do with the Julian calendar, although this is where the name
* is derived from.)
*
* The algorithm is valid for all years (positive and negative), and
* also for years preceding 4714 B.C.
*
* @param int $day the day of the month
* @param int $month the month
* @param int $year the year (using 'Astronomical' year numbering)
*
* @return int the number of days since 24th November, 4714 B.C.
* @access public
* @static
*/
function dateToDays($day, $month, $year)
{
if ($month > 2) {
// March = 0, April = 1, ..., December = 9,
// January = 10, February = 11
$month -= 3;
} else {
$month += 9;
--$year;
}
$hb_negativeyear = $year < 0;
$century = intval($year / 100);
$year = $year % 100;
if ($hb_negativeyear) {
// Subtract 1 because year 0 is a leap year;
// And N.B. that we must treat the leap years as occurring
// one year earlier than they do, because for the purposes
// of calculation, the year starts on 1st March:
//
return intval((14609700 * $century + ($year == 0 ? 1 : 0)) / 400) +
intval((1461 * $year + 1) / 4) +
intval((153 * $month + 2) / 5) +
$day + 1721118;
} else {
return intval(146097 * $century / 4) +
intval(1461 * $year / 4) +
intval((153 * $month + 2) / 5) +
$day + 1721119;
}
}
// }}}
// {{{ daysToDate()
/**
* Converts no of days since 24th November, 4714 B.C. (in the proleptic
* Gregorian calendar, which is year -4713 using 'Astronomical' year
* numbering) to Gregorian calendar date
*
* Returned date belongs to the proleptic Gregorian calendar, using
* 'Astronomical' year numbering.
*
* The algorithm is valid for all years (positive and negative), and
* also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'),
* and so the only limitation is platform-dependent (for 32-bit systems
* the maximum year would be something like about 1,465,190 A.D.).
*
* N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'.
*
* @param int $days the number of days since 24th November, 4714 B.C.
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function daysToDate($days, $format = DATE_CALC_FORMAT)
{
$days = intval($days);
$days -= 1721119;
$century = floor((4 * $days - 1) / 146097);
$days = floor(4 * $days - 1 - 146097 * $century);
$day = floor($days / 4);
$year = floor((4 * $day + 3) / 1461);
$day = floor(4 * $day + 3 - 1461 * $year);
$day = floor(($day + 4) / 4);
$month = floor((5 * $day - 3) / 153);
$day = floor(5 * $day - 3 - 153 * $month);
$day = floor(($day + 5) / 5);
$year = $century * 100 + $year;
if ($month < 10) {
$month +=3;
} else {
$month -=9;
++$year;
}
return Date_Calc::dateFormat($day, $month, $year, $format);
}
// }}}
// {{{ getMonths()
/**
* Returns array of the month numbers, in order, for the given year
*
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return array array of integer month numbers, in order
* @access public
* @static
* @since Method available since Release [next version]
*/
function getMonths($pn_year)
{
// N.B. Month numbers can be skipped but not duplicated:
//
return array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
}
// }}}
// {{{ getMonthNames()
/**
* Returns an array of month names
*
* Used to take advantage of the setlocale function to return
* language specific month names.
*
* TODO: cache values to some global array to avoid performance
* hits when called more than once.
*
* @param int $pb_abbreviated whether to return the abbreviated form of the
* months
*
* @return array associative array of integer month numbers, in
* order, to month names
* @access public
* @static
*/
function getMonthNames($pb_abbreviated = false)
{
$ret = array();
foreach (Date_Calc::getMonths(2001) as $i) {
$ret[$i] = strftime($pb_abbreviated ? '%b' : '%B',
mktime(0, 0, 0, $i, 1, 2001));
}
return $ret;
}
// }}}
// {{{ prevMonth()
/**
* Returns month and year of previous month
*
* @param int $pn_month the month
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return array array of year, month as integers
* @access public
* @static
* @since Method available since Release [next version]
*/
function prevMonth($pn_month, $pn_year)
{
$ha_months = Date_Calc::getMonths($pn_year);
$hn_monthkey = array_search($pn_month, $ha_months);
if (array_key_exists($hn_monthkey - 1, $ha_months)) {
return array((int) $pn_year, $ha_months[$hn_monthkey - 1]);
} else {
$ha_months = Date_Calc::getMonths($pn_year - 1);
return array($pn_year - 1, end($ha_months));
}
}
// }}}
// {{{ nextMonth()
/**
* Returns month and year of next month
*
* @param int $pn_month the month
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return array array of year, month as integers
* @access public
* @static
* @since Method available since Release [next version]
*/
function nextMonth($pn_month, $pn_year)
{
$ha_months = Date_Calc::getMonths($pn_year);
$hn_monthkey = array_search($pn_month, $ha_months);
if (array_key_exists($hn_monthkey + 1, $ha_months)) {
return array((int) $pn_year, $ha_months[$hn_monthkey + 1]);
} else {
$ha_months = Date_Calc::getMonths($pn_year + 1);
return array($pn_year + 1, $ha_months[0]);
}
}
// }}}
// {{{ addMonthsToDays()
/**
* Returns 'Julian Day' of the date the specified no of months
* from the given date
*
* To subtract months use a negative value for the '$pn_months'
* parameter
*
* @param int $pn_months months to add
* @param int $pn_days 'Julian Day', i.e. the no of days since 1st
* January, 4713 B.C.
*
* @return int 'Julian Day', i.e. the no of days since 1st January,
* 4713 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function addMonthsToDays($pn_months, $pn_days)
{
if ($pn_months == 0)
return (int) $pn_days;
list($hn_year, $hn_month, $hn_day) =
explode(" ", Date_Calc::daysToDate($pn_days, "%Y %m %d"));
$hn_retmonth = $hn_month + $pn_months % 12;
$hn_retyear = $hn_year + intval($pn_months / 12);
if ($hn_retmonth < 1) {
$hn_retmonth += 12;
--$hn_retyear;
} else if ($hn_retmonth > 12) {
$hn_retmonth -= 12;
++$hn_retyear;
}
if (Date_Calc::isValidDate($hn_day, $hn_retmonth, $hn_retyear))
return Date_Calc::dateToDays($hn_day, $hn_retmonth, $hn_retyear);
// Calculate days since first of month:
//
$hn_dayoffset = $pn_days -
Date_Calc::firstDayOfMonth($hn_month, $hn_year);
$hn_retmonthfirstday = Date_Calc::firstDayOfMonth($hn_retmonth,
$hn_retyear);
$hn_retmonthlastday = Date_Calc::lastDayOfMonth($hn_retmonth,
$hn_retyear);
if ($hn_dayoffset > $hn_retmonthlastday - $hn_retmonthfirstday) {
return $hn_retmonthlastday;
} else {
return $hn_retmonthfirstday + $hn_dayoffset;
}
}
// }}}
// {{{ addMonths()
/**
* Returns the date the specified no of months from the given date
*
* To subtract months use a negative value for the '$pn_months'
* parameter
*
* @param int $pn_months months to add
* @param int $pn_day the day of the month, default is current local
* day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is
* current local year
* @param string $ps_format string specifying how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @since Method available since Release [next version]
*/
function addMonths($pn_months,
$pn_day,
$pn_month,
$pn_year,
$ps_format = DATE_CALC_FORMAT)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
if ($pn_months == 0)
return Date_Calc::dateFormat($pn_day,
$pn_month,
$pn_year,
$ps_format);
$hn_days = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
return Date_Calc::daysToDate(Date_Calc::addMonthsToDays($pn_months,
$hn_days),
$ps_format);
}
// }}}
// {{{ addYearsToDays()
/**
* Returns 'Julian Day' of the date the specified no of years
* from the given date
*
* To subtract years use a negative value for the '$pn_years'
* parameter
*
* @param int $pn_years years to add
* @param int $pn_days 'Julian Day', i.e. the no of days since 1st January,
* 4713 B.C.
*
* @return int 'Julian Day', i.e. the no of days since 1st January,
* 4713 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function addYearsToDays($pn_years, $pn_days)
{
if ($pn_years == 0)
return (int) $pn_days;
list($hn_year, $hn_month, $hn_day) =
explode(" ", Date_Calc::daysToDate($pn_days, "%Y %m %d"));
$hn_retyear = $hn_year + $pn_years;
if (Date_Calc::isValidDate($hn_day, $hn_month, $hn_retyear))
return Date_Calc::dateToDays($hn_day, $hn_month, $hn_retyear);
$ha_months = Date_Calc::getMonths($hn_retyear);
if (in_array($hn_month, $ha_months)) {
$hn_retmonth = $hn_month;
// Calculate days since first of month:
//
$hn_dayoffset = $pn_days - Date_Calc::firstDayOfMonth($hn_month,
$hn_year);
$hn_retmonthfirstday = Date_Calc::firstDayOfMonth($hn_retmonth,
$hn_retyear);
$hn_retmonthlastday = Date_Calc::lastDayOfMonth($hn_retmonth,
$hn_retyear);
if ($hn_dayoffset > $hn_retmonthlastday - $hn_retmonthfirstday) {
return $hn_retmonthlastday;
} else {
return $hn_retmonthfirstday + $hn_dayoffset;
}
} else {
// Calculate days since first of year:
//
$hn_dayoffset = $pn_days - Date_Calc::firstDayOfYear($hn_year);
$hn_retyearfirstday = Date_Calc::firstDayOfYear($hn_retyear);
$hn_retyearlastday = Date_Calc::lastDayOfYear($hn_retyear);
if ($hn_dayoffset > $hn_retyearlastday - $hn_retyearfirstday) {
return $hn_retyearlastday;
} else {
return $hn_retyearfirstday + $hn_dayoffset;
}
}
}
// }}}
// {{{ addYears()
/**
* Returns the date the specified no of years from the given date
*
* To subtract years use a negative value for the '$pn_years'
* parameter
*
* @param int $pn_years years to add
* @param int $pn_day the day of the month, default is current local
* day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is
* current local year
* @param string $ps_format string specifying how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @since Method available since Release [next version]
*/
function addYears($pn_years,
$pn_day,
$pn_month,
$pn_year,
$ps_format = DATE_CALC_FORMAT)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
if ($pn_years == 0)
return Date_Calc::dateFormat($pn_day,
$pn_month,
$pn_year,
$ps_format);
$hn_days = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
return Date_Calc::daysToDate(Date_Calc::addYearsToDays($pn_years,
$hn_days),
$ps_format);
}
// }}}
// {{{ addDays()
/**
* Returns the date the specified no of days from the given date
*
* To subtract days use a negative value for the '$pn_days' parameter
*
* @param int $pn_days days to add
* @param int $pn_day the day of the month, default is current local
* day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is
* current local year
* @param string $ps_format string specifying how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @since Method available since Release [next version]
*/
function addDays($pn_days,
$pn_day,
$pn_month,
$pn_year,
$ps_format = DATE_CALC_FORMAT)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
if ($pn_days == 0)
return Date_Calc::dateFormat($pn_day,
$pn_month,
$pn_year,
$ps_format);
return Date_Calc::daysToDate(Date_Calc::dateToDays($pn_day,
$pn_month,
$pn_year) +
$pn_days,
$ps_format);
}
// }}}
// {{{ getFirstDayOfMonth()
/**
* Returns first day of the specified month of specified year as integer
*
* @param int $pn_month the month
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return int number of first day of month
* @access public
* @static
* @since Method available since Release [next version]
*/
function getFirstDayOfMonth($pn_month, $pn_year)
{
return 1;
}
// }}}
// {{{ getLastDayOfMonth()
/**
* Returns last day of the specified month of specified year as integer
*
* @param int $pn_month the month
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return int number of last day of month
* @access public
* @static
* @since Method available since Release [next version]
*/
function getLastDayOfMonth($pn_month, $pn_year)
{
return Date_Calc::daysInMonth($pn_month, $pn_year);
}
// }}}
// {{{ firstDayOfMonth()
/**
* Returns the Julian Day of the first day of the month of the specified
* year (i.e. the no of days since 24th November, 4714 B.C.)
*
* @param int $pn_month the month
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return integer the number of days since 24th November, 4714 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function firstDayOfMonth($pn_month, $pn_year)
{
return Date_Calc::dateToDays(Date_Calc::getFirstDayOfMonth($pn_month,
$pn_year),
$pn_month,
$pn_year);
}
// }}}
// {{{ lastDayOfMonth()
/**
* Returns the Julian Day of the last day of the month of the specified
* year (i.e. the no of days since 24th November, 4714 B.C.)
*
* @param int $pn_month the month
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return integer the number of days since 24th November, 4714 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function lastDayOfMonth($pn_month, $pn_year)
{
list($hn_nmyear, $hn_nextmonth) = Date_Calc::nextMonth($pn_month,
$pn_year);
return Date_Calc::firstDayOfMonth($hn_nextmonth, $hn_nmyear) - 1;
}
// }}}
// {{{ getFirstMonthOfYear()
/**
* Returns first month of specified year as integer
*
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return int number of first month of year
* @access public
* @static
* @since Method available since Release [next version]
*/
function getFirstMonthOfYear($pn_year)
{
$ha_months = Date_Calc::getMonths($pn_year);
return $ha_months[0];
}
// }}}
// {{{ firstDayOfYear()
/**
* Returns the Julian Day of the first day of the year (i.e. the no of
* days since 24th November, 4714 B.C.)
*
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return integer the number of days since 24th November, 4714 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function firstDayOfYear($pn_year)
{
return Date_Calc::firstDayOfMonth(Date_Calc::getFirstMonthOfYear($pn_year),
$pn_year);
}
// }}}
// {{{ lastDayOfYear()
/**
* Returns the Julian Day of the last day of the year (i.e. the no of
* days since 24th November, 4714 B.C.)
*
* @param int $pn_year the year (using 'Astronomical' year numbering)
*
* @return integer the number of days since 24th November, 4714 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function lastDayOfYear($pn_year)
{
return Date_Calc::firstDayOfYear($pn_year + 1) - 1;
}
// }}}
// {{{ dateToDaysJulian()
/**
* Converts a date in the proleptic Julian calendar to the no of days
* since 1st January, 4713 B.C.
*
* Returns the no of days since Monday, 1st January, 4713 B.C. in the
* proleptic Julian calendar (which is 1st January, -4712 using
* 'Astronomical' year numbering, and 24th November, 4713 B.C. in the
* proleptic Gregorian calendar). This is also the first day of the 'Julian
* Period' proposed by Joseph Scaliger in 1583, and the number of days
* since this date is known as the 'Julian Day'. (It is not directly
* to do with the Julian calendar, although this is where the name
* is derived from.)
*
* The algorithm is valid for all years (positive and negative), and
* also for years preceding 4713 B.C.
*
* @param int $day the day of the month
* @param int $month the month
* @param int $year the year (using 'Astronomical' year numbering)
*
* @return int the number of days since 1st January, 4713 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function dateToDaysJulian($day, $month, $year)
{
if ($month > 2) {
// March = 0, April = 1, ..., December = 9,
// January = 10, February = 11
$month -= 3;
} else {
$month += 9;
--$year;
}
$hb_negativeyear = $year < 0;
if ($hb_negativeyear) {
// Subtract 1 because year 0 is a leap year;
// And N.B. that we must treat the leap years as occurring
// one year earlier than they do, because for the purposes
// of calculation, the year starts on 1st March:
//
return intval((1461 * $year + 1) / 4) +
intval((153 * $month + 2) / 5) +
$day + 1721116;
} else {
return intval(1461 * $year / 4) +
floor((153 * $month + 2) / 5) +
$day + 1721117;
}
}
// }}}
// {{{ daysToDateJulian()
/**
* Converts no of days since 1st January, 4713 B.C. (in the proleptic
* Julian calendar, which is year -4712 using 'Astronomical' year
* numbering) to Julian calendar date
*
* Returned date belongs to the proleptic Julian calendar, using
* 'Astronomical' year numbering.
*
* @param int $days the number of days since 1st January, 4713 B.C.
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @since Method available since Release [next version]
*/
function daysToDateJulian($days, $format = DATE_CALC_FORMAT)
{
$days = intval($days);
$days -= 1721117;
$days = floor(4 * $days - 1);
$day = floor($days / 4);
$year = floor((4 * $day + 3) / 1461);
$day = floor(4 * $day + 3 - 1461 * $year);
$day = floor(($day + 4) / 4);
$month = floor((5 * $day - 3) / 153);
$day = floor(5 * $day - 3 - 153 * $month);
$day = floor(($day + 5) / 5);
if ($month < 10) {
$month +=3;
} else {
$month -=9;
++$year;
}
return Date_Calc::dateFormat($day, $month, $year, $format);
}
// }}}
// {{{ isoWeekDate()
/**
* Returns array defining the 'ISO Week Date' as defined in ISO 8601
*
* Expects a date in the proleptic Gregorian calendar using 'Astronomical'
* year numbering, that is, with a year 0. Algorithm is valid for all
* years (positive and negative).
*
* N.B. the ISO week day no for Sunday is defined as 7, whereas this
* class and its related functions defines Sunday as 0.
*
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year
*
* @return array array of ISO Year, ISO Week No, ISO Day No as
* integers
* @access public
* @static
* @since Method available since Release [next version]
*/
function isoWeekDate($pn_day = 0, $pn_month = 0, $pn_year = null)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$hn_jd = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
$hn_wd = Date_Calc::daysToDayOfWeek($hn_jd);
if ($hn_wd == 0)
$hn_wd = 7;
$hn_jd1 = Date_Calc::firstDayOfYear($pn_year);
$hn_day = $hn_jd - $hn_jd1 + 1;
if ($hn_wd <= $hn_jd - Date_Calc::lastDayOfYear($pn_year) + 3) {
// ISO week is the first week of the next ISO year:
//
$hn_year = $pn_year + 1;
$hn_isoweek = 1;
} else {
switch ($hn_wd1 = Date_Calc::daysToDayOfWeek($hn_jd1)) {
case 1:
case 2:
case 3:
case 4:
// Monday - Thursday:
//
$hn_year = $pn_year;
$hn_isoweek = floor(($hn_day + $hn_wd1 - 2) / 7) + 1;
break;
case 0:
$hn_wd1 = 7;
case 5:
case 6:
// Friday - Sunday:
//
if ($hn_day <= 8 - $hn_wd1) {
// ISO week is the last week of the previous ISO year:
//
list($hn_year, $hn_lastmonth, $hn_lastday) =
explode(" ",
Date_Calc::daysToDate($hn_jd1 - 1, "%Y %m %d"));
list($hn_year, $hn_isoweek, $hn_pisoday) =
Date_Calc::isoWeekDate($hn_lastday,
$hn_lastmonth,
$hn_year);
} else {
$hn_year = $pn_year;
$hn_isoweek = floor(($hn_day + $hn_wd1 - 9) / 7) + 1;
}
break;
}
}
return array((int) $hn_year, (int) $hn_isoweek, (int) $hn_wd);
}
// }}}
// {{{ gregorianToISO()
/**
* Converts from Gregorian Year-Month-Day to ISO Year-WeekNumber-WeekDay
*
* Uses ISO 8601 definitions.
*
* @param int $day the day of the month
* @param int $month the month
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return string the date in ISO Year-WeekNumber-WeekDay format
* @access public
* @static
*/
function gregorianToISO($day, $month, $year)
{
list($yearnumber, $weeknumber, $weekday) =
Date_Calc::isoWeekDate($day, $month, $year);
return sprintf("%04d", $yearnumber) .
'-' .
sprintf("%02d", $weeknumber) .
'-' .
$weekday;
}
// }}}
// {{{ weekOfYear4th()
/**
* Returns week of the year counting week 1 as the week that contains 4th
* January
*
* Week 1 is determined to be the week that includes the 4th January, and
* therefore can be defined as the first week of the year that has at least
* 4 days. The previous week is counted as week 52 or 53 of the previous
* year. Note that this definition depends on which day is the first day of
* the week, and that if this is not passed as the '$pn_firstdayofweek'
* parameter, the default is assumed.
*
* Note also that the last day week of the year is likely to extend into
* the following year, except in the case that the last day of the week
* falls on 31st December.
*
* Also note that this is very similar to the ISO week returned by
* 'isoWeekDate()', the difference being that the ISO week always has
* 7 days, and if the 4th of January is a Friday, for example,
* ISO week 1 would start on Monday, 31st December in the previous year,
* whereas the week defined by this function would start on 1st January,
* but would be only 6 days long. Of course you can also set the day
* of the week, whereas the ISO week starts on a Monday by definition.
*
* Returned week is an integer from 1 to 53.
*
* @param int $pn_day the day of the month, default is current
* local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is
* current local year
* @param int $pn_firstdayofweek optional integer specifying the first day
* of the week
*
* @return array array of year, week no as integers
* @access public
* @static
* @since Method available since Release [next version]
*/
function weekOfYear4th($pn_day = 0,
$pn_month = 0,
$pn_year = null,
$pn_firstdayofweek = DATE_CALC_BEGIN_WEEKDAY)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$hn_wd1 = Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfYear($pn_year));
$hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
$hn_week = floor(($hn_day +
(10 + $hn_wd1 - $pn_firstdayofweek) % 7 +
3) / 7);
if ($hn_week > 0) {
$hn_year = $pn_year;
} else {
// Week number is the last week of the previous year:
//
list($hn_year, $hn_lastmonth, $hn_lastday) =
explode(" ",
Date_Calc::daysToDate(Date_Calc::lastDayOfYear($pn_year - 1),
"%Y %m %d"));
list($hn_year, $hn_week) =
Date_Calc::weekOfYear4th($hn_lastday,
$hn_lastmonth,
$hn_year,
$pn_firstdayofweek);
}
return array((int) $hn_year, (int) $hn_week);
}
// }}}
// {{{ weekOfYear7th()
/**
* Returns week of the year counting week 1 as the week that contains 7th
* January
*
* Week 1 is determined to be the week that includes the 7th January, and
* therefore can be defined as the first full week of the year. The
* previous week is counted as week 52 or 53 of the previous year. Note
* that this definition depends on which day is the first day of the week,
* and that if this is not passed as the '$pn_firstdayofweek' parameter, the
* default is assumed.
*
* Note also that the last day week of the year is likely to extend into
* the following year, except in the case that the last day of the week
* falls on 31st December.
*
* Returned week is an integer from 1 to 53.
*
* @param int $pn_day the day of the month, default is current
* local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is
* current local year
* @param int $pn_firstdayofweek optional integer specifying the first day
* of the week
*
* @return array array of year, week no as integers
* @access public
* @static
* @since Method available since Release [next version]
*/
function weekOfYear7th($pn_day = 0,
$pn_month = 0,
$pn_year = null,
$pn_firstdayofweek = DATE_CALC_BEGIN_WEEKDAY)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$hn_wd1 = Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfYear($pn_year));
$hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
$hn_week = floor(($hn_day + (6 + $hn_wd1 - $pn_firstdayofweek) % 7) / 7);
if ($hn_week > 0) {
$hn_year = $pn_year;
} else {
// Week number is the last week of the previous ISO year:
//
list($hn_year, $hn_lastmonth, $hn_lastday) = explode(" ", Date_Calc::daysToDate(Date_Calc::lastDayOfYear($pn_year - 1), "%Y %m %d"));
list($hn_year, $hn_week) = Date_Calc::weekOfYear7th($hn_lastday, $hn_lastmonth, $hn_year, $pn_firstdayofweek);
}
return array((int) $hn_year, (int) $hn_week);
}
// }}}
// {{{ dateSeason()
/**
* Determines julian date of the given season
*
* Adapted from previous work in Java by James Mark Hamilton.
*
* @param string $season the season to get the date for: VERNALEQUINOX,
* SUMMERSOLSTICE, AUTUMNALEQUINOX,
* or WINTERSOLSTICE
* @param string $year the year in four digit format. Must be between
* -1000 B.C. and 3000 A.D.
*
* @return float the julian date the season starts on
* @access public
* @static
*/
function dateSeason($season, $year = 0)
{
if ($year == '') {
$year = Date_Calc::dateNow('%Y');
}
if (($year >= -1000) && ($year <= 1000)) {
$y = $year / 1000.0;
switch ($season) {
case 'VERNALEQUINOX':
$juliandate = (((((((-0.00071 * $y) - 0.00111) * $y) + 0.06134) * $y) + 365242.1374) * $y) + 1721139.29189;
break;
case 'SUMMERSOLSTICE':
$juliandate = (((((((0.00025 * $y) + 0.00907) * $y) - 0.05323) * $y) + 365241.72562) * $y) + 1721233.25401;
break;
case 'AUTUMNALEQUINOX':
$juliandate = (((((((0.00074 * $y) - 0.00297) * $y) - 0.11677) * $y) + 365242.49558) * $y) + 1721325.70455;
break;
case 'WINTERSOLSTICE':
default:
$juliandate = (((((((-0.00006 * $y) - 0.00933) * $y) - 0.00769) * $y) + 365242.88257) * $y) + 1721414.39987;
}
} elseif (($year > 1000) && ($year <= 3000)) {
$y = ($year - 2000) / 1000;
switch ($season) {
case 'VERNALEQUINOX':
$juliandate = (((((((-0.00057 * $y) - 0.00411) * $y) + 0.05169) * $y) + 365242.37404) * $y) + 2451623.80984;
break;
case 'SUMMERSOLSTICE':
$juliandate = (((((((-0.0003 * $y) + 0.00888) * $y) + 0.00325) * $y) + 365241.62603) * $y) + 2451716.56767;
break;
case 'AUTUMNALEQUINOX':
$juliandate = (((((((0.00078 * $y) + 0.00337) * $y) - 0.11575) * $y) + 365242.01767) * $y) + 2451810.21715;
break;
case 'WINTERSOLSTICE':
default:
$juliandate = (((((((0.00032 * $y) - 0.00823) * $y) - 0.06223) * $y) + 365242.74049) * $y) + 2451900.05952;
}
}
return $juliandate;
}
// }}}
// {{{ dayOfYear()
/**
* Returns number of days since 31 December of year before given date
*
* @param int $pn_day the day of the month, default is current local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is current
* local year
*
* @return int
* @access public
* @static
* @since Method available since Release [next version]
*/
function dayOfYear($pn_day = 0, $pn_month = 0, $pn_year = null)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$hn_jd = Date_Calc::dateToDays($pn_day, $pn_month, $pn_year);
$hn_jd1 = Date_Calc::firstDayOfYear($pn_year);
return $hn_jd - $hn_jd1 + 1;
}
// }}}
// {{{ julianDate()
/**
* Returns number of days since 31 December of year before given date
*
* @param int $pn_day the day of the month, default is current local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is current
* local year
*
* @return int
* @access public
* @static
* @deprecated Method deprecated in Release [next version]
*/
function julianDate($pn_day = 0, $pn_month = 0, $pn_year = null)
{
return Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
}
// }}}
// {{{ getWeekdayFullname()
/**
* Returns the full weekday name for the given date
*
* @param int $pn_day the day of the month, default is current local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is current
* local year
*
* @return string the full name of the day of the week
* @access public
* @static
*/
function getWeekdayFullname($pn_day = 0, $pn_month = 0, $pn_year = null)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$weekday_names = Date_Calc::getWeekDays();
$weekday = Date_Calc::dayOfWeek($pn_day, $pn_month, $pn_year);
return $weekday_names[$weekday];
}
// }}}
// {{{ getWeekdayAbbrname()
/**
* Returns the abbreviated weekday name for the given date
*
* @param int $pn_day the day of the month, default is current local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is current
* local year
* @param int $length the length of abbreviation
*
* @return string the abbreviated name of the day of the week
* @access public
* @static
* @see Date_Calc::getWeekdayFullname()
*/
function getWeekdayAbbrname($pn_day = 0,
$pn_month = 0,
$pn_year = null,
$length = 3)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$weekday_names = Date_Calc::getWeekDays(true);
$weekday = Date_Calc::dayOfWeek($pn_day, $pn_month, $pn_year);
return $weekday_names[$weekday];
}
// }}}
// {{{ getMonthFullname()
/**
* Returns the full month name for the given month
*
* @param int $month the month
*
* @return string the full name of the month
* @access public
* @static
*/
function getMonthFullname($month)
{
$month = (int)$month;
if (empty($month)) {
$month = (int)Date_Calc::dateNow('%m');
}
$month_names = Date_Calc::getMonthNames();
return $month_names[$month];
}
// }}}
// {{{ getMonthAbbrname()
/**
* Returns the abbreviated month name for the given month
*
* @param int $month the month
* @param int $length the length of abbreviation
*
* @return string the abbreviated name of the month
* @access public
* @static
* @see Date_Calc::getMonthFullname
*/
function getMonthAbbrname($month, $length = 3)
{
$month = (int)$month;
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
$month_names = Date_Calc::getMonthNames(true);
return $month_names[$month];
}
// }}}
// {{{ getMonthFromFullname()
/**
* Returns the numeric month from the month name or an abreviation
*
* Both August and Aug would return 8.
*
* @param string $month the name of the month to examine.
* Case insensitive.
*
* @return int the month's number
* @access public
* @static
*/
function getMonthFromFullName($month)
{
$month = strtolower($month);
$months = Date_Calc::getMonthNames();
while (list($id, $name) = each($months)) {
if (ereg($month, strtolower($name))) {
return $id;
}
}
return 0;
}
// }}}
// {{{ getWeekDays()
/**
* Returns an array of week day names
*
* Used to take advantage of the setlocale function to return language
* specific week days.
*
* @param int $pb_abbreviated whether to return the abbreviated form of the
* days
*
* @return array an array of week-day names
* @access public
* @static
*/
function getWeekDays($pb_abbreviated = false)
{
for ($i = 0; $i < 7; $i++) {
$weekdays[$i] = strftime($pb_abbreviated ? '%a' : '%A',
mktime(0, 0, 0, 1, $i, 2001));
}
return $weekdays;
}
// }}}
// {{{ daysToDayOfWeek()
/**
* Returns day of week for specified 'Julian Day'
*
* The algorithm is valid for all years (positive and negative), and
* also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'),
* and so the only limitation is platform-dependent (for 32-bit systems
* the maximum year would be something like about 1,465,190 A.D.).
*
* N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'.
*
* @param int $pn_days the number of days since 24th November, 4714 B.C.
*
* @return int integer from 0 to 7 where 0 represents Sunday
* @access public
* @static
* @since Method available since Release [next version]
*/
function daysToDayOfWeek($pn_days)
{
// On Julian day 0 the day is Monday (PHP day 1):
//
$ret = ($pn_days + 1) % 7;
return $ret < 0 ? $ret + 7 : $ret;
}
// }}}
// {{{ dayOfWeek()
/**
* Returns day of week for given date (0 = Sunday)
*
* The algorithm is valid for all years (positive and negative).
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
*
* @return int the number of the day in the week
* @access public
* @static
*/
function dayOfWeek($day = null, $month = null, $year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
// if ($month <= 2) {
// $month += 12;
// --$year;
// }
// $wd = ($day +
// intval((13 * $month + 3) / 5) +
// $year +
// floor($year / 4) -
// floor($year / 100) +
// floor($year / 400) +
// 1) % 7;
// return (int) ($wd < 0 ? $wd + 7 : $wd);
return Date_Calc::daysToDayOfWeek(Date_Calc::dateToDays($day,
$month,
$year));
}
// }}}
// {{{ weekOfYearAbsolute()
/**
* Returns week of the year counting week 1 as 1st-7th January,
* regardless of what day 1st January falls on
*
* Returned value is an integer from 1 to 53. Week 53 will start on
* 31st December and have only one day, except in a leap year, in
* which it will start a day earlier and contain two days.
*
* @param int $pn_day the day of the month, default is current local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is current
* local year
*
* @return int integer from 1 to 53
* @access public
* @static
* @since Method available since Release [next version]
*/
function weekOfYearAbsolute($pn_day = 0, $pn_month = 0, $pn_year = null)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
return intval(($hn_day + 6) / 7);
}
// }}}
// {{{ weekOfYear1st()
/**
* Returns week of the year counting week 1 as the week that contains 1st
* January
*
* Week 1 is determined to be the week that includes the 1st January, even
* if this week extends into the previous year, in which case the week will
* only contain between 1 and 6 days of the current year. Note that this
* definition depends on which day is the first day of the week, and that if
* this is not passed as the '$pn_firstdayofweek' parameter, the default is
* assumed.
*
* Note also that the last day week of the year is also likely to contain
* less than seven days, except in the case that the last day of the week
* falls on 31st December.
*
* Returned value is an integer from 1 to 54. The year will only contain
* 54 weeks in the case of a leap year in which 1st January is the last day
* of the week, and 31st December is the first day of the week. In this
* case, both weeks 1 and 54 will contain one day only.
*
* @param int $pn_day the day of the month, default is current
* local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is
* current local year
* @param int $pn_firstdayofweek optional integer specifying the first day
* of the week
*
* @return int integer from 1 to 54
* @access public
* @static
* @since Method available since Release [next version]
*/
function weekOfYear1st($pn_day = 0,
$pn_month = 0,
$pn_year = null,
$pn_firstdayofweek = DATE_CALC_BEGIN_WEEKDAY)
{
if (is_null($pn_year)) {
$pn_year = Date_Calc::dateNow('%Y');
}
if (empty($pn_month)) {
$pn_month = Date_Calc::dateNow('%m');
}
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
$hn_wd1 = Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfYear($pn_year));
$hn_day = Date_Calc::dayOfYear($pn_day, $pn_month, $pn_year);
return floor(($hn_day + (7 + $hn_wd1 - $pn_firstdayofweek) % 7 + 6) / 7);
}
// }}}
// {{{ weekOfYear()
/**
* Returns week of the year, where first Sunday is first day of first week
*
* N.B. this function is equivalent to calling:
*
* <code>Date_Calc::weekOfYear7th($day, $month, $year, 0)</code>
*
* Returned week is an integer from 1 to 53.
*
* @param int $pn_day the day of the month, default is current local day
* @param int $pn_month the month, default is current local month
* @param int $pn_year the year in four digit format, default is current
* local year
*
* @return int integer from 1 to 53
* @access public
* @static
* @see Date_Calc::weekOfYear7th
* @deprecated Method deprecated in Release [next version]
*/
function weekOfYear($pn_day = 0, $pn_month = 0, $pn_year = null)
{
$ha_week = Date_Calc::weekOfYear7th($pn_day, $pn_month, $pn_year, 0);
return $ha_week[1];
}
// }}}
// {{{ weekOfMonthAbsolute()
/**
* Returns week of the month counting week 1 as 1st-7th of the month,
* regardless of what day the 1st falls on
*
* Returned value is an integer from 1 to 5. Week 5 will start on
* the 29th of the month and have between 1 and 3 days, except
* in February in a non-leap year, when there will be 4 weeks only.
*
* @param int $pn_day the day of the month, default is current local day
*
* @return int integer from 1 to 5
* @access public
* @static
* @since Method available since Release [next version]
*/
function weekOfMonthAbsolute($pn_day = 0)
{
if (empty($pn_day)) {
$pn_day = Date_Calc::dateNow('%d');
}
return intval(($pn_day + 6) / 7);
}
// }}}
// {{{ weekOfMonth()
/**
* Alias for 'weekOfMonthAbsolute()'
*
* @param int $pn_day the day of the month, default is current local day
*
* @return int integer from 1 to 5
* @access public
* @static
* @since Method available since Release [next version]
*/
function weekOfMonth($pn_day = 0)
{
return Date_Calc::weekOfMonthAbsolute($pn_day);
}
// }}}
// {{{ quarterOfYear()
/**
* Returns quarter of the year for given date
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
*
* @return int the number of the quarter in the year
* @access public
* @static
*/
function quarterOfYear($day = 0, $month = 0, $year = null)
{
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
return intval(($month - 1) / 3 + 1);
}
// }}}
// {{{ daysInMonth()
/**
* Returns the number of days in the given month
*
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
*
* @return int the number of days the month has
* @access public
* @static
*/
function daysInMonth($month = 0, $year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
return Date_Calc::lastDayOfMonth($month, $year) -
Date_Calc::firstDayOfMonth($month, $year) +
1;
}
// }}}
// {{{ daysInYear()
/**
* Returns the number of days in the given year
*
* @param int $year the year in four digit format, default is current local
* year
*
* @return int the number of days the year has
* @access public
* @static
*/
function daysInYear($year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
return Date_Calc::firstDayOfYear($year + 1) -
Date_Calc::firstDayOfYear($year);
}
// }}}
// {{{ weeksInMonth()
/**
* Returns the number of rows on a calendar month
*
* Useful for determining the number of rows when displaying a typical
* month calendar.
*
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
*
* @return int the number of weeks the month has
* @access public
* @static
*/
function weeksInMonth($month = 0, $year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
$FDOM = Date_Calc::firstOfMonthWeekday($month, $year);
if (DATE_CALC_BEGIN_WEEKDAY==1 && $FDOM==0) {
$first_week_days = 7 - $FDOM + DATE_CALC_BEGIN_WEEKDAY;
$weeks = 1;
} elseif (DATE_CALC_BEGIN_WEEKDAY==0 && $FDOM == 6) {
$first_week_days = 7 - $FDOM + DATE_CALC_BEGIN_WEEKDAY;
$weeks = 1;
} else {
$first_week_days = DATE_CALC_BEGIN_WEEKDAY - $FDOM;
$weeks = 0;
}
$first_week_days %= 7;
return ceil((Date_Calc::daysInMonth($month, $year)
- $first_week_days) / 7) + $weeks;
}
// }}}
// {{{ getCalendarWeek()
/**
* Return an array with days in week
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return array $week[$weekday]
* @access public
* @static
*/
function getCalendarWeek($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
$week_array = array();
// date for the column of week
$curr_day = Date_Calc::beginOfWeek($day, $month, $year, '%E');
for ($counter = 0; $counter <= 6; $counter++) {
$week_array[$counter] = Date_Calc::daysToDate($curr_day, $format);
$curr_day++;
}
return $week_array;
}
// }}}
// {{{ getCalendarMonth()
/**
* Return a set of arrays to construct a calendar month for the given date
*
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return array $month[$row][$col]
* @access public
* @static
*/
function getCalendarMonth($month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
$month_array = array();
// date for the first row, first column of calendar month
if (DATE_CALC_BEGIN_WEEKDAY == 1) {
if (Date_Calc::firstOfMonthWeekday($month, $year) == 0) {
$curr_day = Date_Calc::firstDayOfMonth($month, $year) - 6;
} else {
$curr_day = Date_Calc::firstDayOfMonth($month, $year)
- Date_Calc::firstOfMonthWeekday($month, $year) + 1;
}
} else {
$curr_day = (Date_Calc::firstDayOfMonth($month, $year)
- Date_Calc::firstOfMonthWeekday($month, $year));
}
// number of days in this month
$daysInMonth = Date_Calc::daysInMonth($month, $year);
$weeksInMonth = Date_Calc::weeksInMonth($month, $year);
for ($row_counter = 0; $row_counter < $weeksInMonth; $row_counter++) {
for ($column_counter = 0; $column_counter <= 6; $column_counter++) {
$month_array[$row_counter][$column_counter] =
Date_Calc::daysToDate($curr_day, $format);
$curr_day++;
}
}
return $month_array;
}
// }}}
// {{{ getCalendarYear()
/**
* Return a set of arrays to construct a calendar year for the given date
*
* @param int $year the year in four digit format, default current
* local year
* @param string $format the string indicating how to format the output
*
* @return array $year[$month][$row][$col]
* @access public
* @static
*/
function getCalendarYear($year = null, $format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
$year_array = array();
for ($curr_month = 0; $curr_month <= 11; $curr_month++) {
$year_array[$curr_month] =
Date_Calc::getCalendarMonth($curr_month + 1,
$year, $format);
}
return $year_array;
}
// }}}
// {{{ prevDay()
/**
* Returns date of day before given date
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function prevDay($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
return Date_Calc::addDays(-1, $day, $month, $year, $format);
}
// }}}
// {{{ nextDay()
/**
* Returns date of day after given date
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function nextDay($day = 0,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
return Date_Calc::addDays(1, $day, $month, $year, $format);
}
// }}}
// {{{ prevWeekday()
/**
* Returns date of the previous weekday, skipping from Monday to Friday
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function prevWeekday($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
$days = Date_Calc::dateToDays($day, $month, $year);
if (Date_Calc::dayOfWeek($day, $month, $year) == 1) {
$days -= 3;
} elseif (Date_Calc::dayOfWeek($day, $month, $year) == 0) {
$days -= 2;
} else {
$days -= 1;
}
return Date_Calc::daysToDate($days, $format);
}
// }}}
// {{{ nextWeekday()
/**
* Returns date of the next weekday of given date, skipping from
* Friday to Monday
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function nextWeekday($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
$days = Date_Calc::dateToDays($day, $month, $year);
if (Date_Calc::dayOfWeek($day, $month, $year) == 5) {
$days += 3;
} elseif (Date_Calc::dayOfWeek($day, $month, $year) == 6) {
$days += 2;
} else {
$days += 1;
}
return Date_Calc::daysToDate($days, $format);
}
// }}}
// {{{ daysToPrevDayOfWeek()
/**
* Returns 'Julian Day' of the previous specific day of the week
* from the given date.
*
* @param int $dow the day of the week (0 = Sunday)
* @param int $days 'Julian Day', i.e. the no of days since 1st
* January, 4713 B.C.
* @param bool $onorbefore if true and days are same, returns current day
*
* @return int 'Julian Day', i.e. the no of days since 1st January,
* 4713 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function daysToPrevDayOfWeek($dow, $days, $onorbefore = false)
{
$curr_weekday = Date_Calc::daysToDayOfWeek($days);
if ($curr_weekday == $dow) {
if ($onorbefore) {
return $days;
} else {
return $days - 7;
}
} else if ($curr_weekday < $dow) {
return $days - 7 + $dow - $curr_weekday;
} else {
return $days - $curr_weekday + $dow;
}
}
// }}}
// {{{ prevDayOfWeek()
/**
* Returns date of the previous specific day of the week
* from the given date
*
* @param int $dow the day of the week (0 = Sunday)
* @param int $day the day of the month, default is current local
* day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is
* current local year
* @param string $format the string indicating how to format the output
* @param bool $onorbefore if true and days are same, returns current day
*
* @return string the date in the desired format
* @access public
* @static
*/
function prevDayOfWeek($dow,
$day = 0,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT,
$onorbefore = false)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
$days = Date_Calc::dateToDays($day, $month, $year);
$days = Date_Calc::daysToPrevDayOfWeek($dow, $days, $onorbefore);
return Date_Calc::daysToDate($days, $format);
}
// }}}
// {{{ daysToNextDayOfWeek()
/**
* Returns 'Julian Day' of the next specific day of the week
* from the given date.
*
* @param int $dow the day of the week (0 = Sunday)
* @param int $days 'Julian Day', i.e. the no of days since 1st
* January, 4713 B.C.
* @param bool $onorafter if true and days are same, returns current day
*
* @return int 'Julian Day', i.e. the no of days since 1st January,
* 4713 B.C.
* @access public
* @static
* @since Method available since Release [next version]
*/
function daysToNextDayOfWeek($dow, $days, $onorafter = false)
{
$curr_weekday = Date_Calc::daysToDayOfWeek($days);
if ($curr_weekday == $dow) {
if ($onorafter) {
return $days;
} else {
return $days + 7;
}
} else if ($curr_weekday > $dow) {
return $days + 7 - $curr_weekday + $dow;
} else {
return $days + $dow - $curr_weekday;
}
}
// }}}
// {{{ nextDayOfWeek()
/**
* Returns date of the next specific day of the week
* from the given date
*
* @param int $dow the day of the week (0 = Sunday)
* @param int $day the day of the month, default is current local
* day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is
* current local year
* @param string $format the string indicating how to format the output
* @param bool $onorafter if true and days are same, returns current day
*
* @return string the date in the desired format
* @access public
* @static
*/
function nextDayOfWeek($dow,
$day = 0,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT,
$onorafter = false)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
$days = Date_Calc::dateToDays($day, $month, $year);
$days = Date_Calc::daysToNextDayOfWeek($dow, $days, $onorafter);
return Date_Calc::daysToDate($days, $format);
}
// }}}
// {{{ prevDayOfWeekOnOrBefore()
/**
* Returns date of the previous specific day of the week
* on or before the given date
*
* @param int $dow the day of the week (0 = Sunday)
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function prevDayOfWeekOnOrBefore($dow,
$day = 0,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
return Date_Calc::prevDayOfWeek($dow,
$day,
$month,
$year,
$format,
true);
}
// }}}
// {{{ nextDayOfWeekOnOrAfter()
/**
* Returns date of the next specific day of the week
* on or after the given date
*
* @param int $dow the day of the week (0 = Sunday)
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function nextDayOfWeekOnOrAfter($dow,
$day = 0,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
return Date_Calc::nextDayOfWeek($dow,
$day,
$month,
$year,
$format,
true);
}
// }}}
// {{{ beginOfWeek()
/**
* Find the month day of the beginning of week for given date,
* using DATE_CALC_BEGIN_WEEKDAY
*
* Can return weekday of prev month.
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function beginOfWeek($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
$hn_days = Date_Calc::dateToDays($day, $month, $year);
$this_weekday = Date_Calc::daysToDayOfWeek($hn_days);
$interval = (7 - DATE_CALC_BEGIN_WEEKDAY + $this_weekday) % 7;
return Date_Calc::daysToDate($hn_days - $interval, $format);
}
// }}}
// {{{ endOfWeek()
/**
* Find the month day of the end of week for given date,
* using DATE_CALC_BEGIN_WEEKDAY
*
* Can return weekday of following month.
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function endOfWeek($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
$hn_days = Date_Calc::dateToDays($day, $month, $year);
$this_weekday = Date_Calc::daysToDayOfWeek($hn_days);
$interval = (6 + DATE_CALC_BEGIN_WEEKDAY - $this_weekday) % 7;
return Date_Calc::daysToDate($hn_days + $interval, $format);
}
// }}}
// {{{ beginOfPrevWeek()
/**
* Find the month day of the beginning of week before given date,
* using DATE_CALC_BEGIN_WEEKDAY
*
* Can return weekday of prev month.
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function beginOfPrevWeek($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
list($hn_pwyear, $hn_pwmonth, $hn_pwday) =
explode(" ", Date_Calc::daysToDate(Date_Calc::dateToDays($day,
$month,
$year) - 7,
'%Y %m %d'));
return Date_Calc::beginOfWeek($hn_pwday,
$hn_pwmonth,
$hn_pwyear,
$format);
}
// }}}
// {{{ beginOfNextWeek()
/**
* Find the month day of the beginning of week after given date,
* using DATE_CALC_BEGIN_WEEKDAY
*
* Can return weekday of prev month.
*
* @param int $day the day of the month, default is current local day
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function beginOfNextWeek($day = 0, $month = 0, $year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
if (empty($day)) {
$day = Date_Calc::dateNow('%d');
}
list($hn_pwyear, $hn_pwmonth, $hn_pwday) =
explode(" ",
Date_Calc::daysToDate(Date_Calc::dateToDays($day,
$month,
$year) + 7,
'%Y %m %d'));
return Date_Calc::beginOfWeek($hn_pwday,
$hn_pwmonth,
$hn_pwyear,
$format);
}
// }}}
// {{{ beginOfMonth()
/**
* Return date of first day of month of given date
*
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @see Date_Calc::beginOfMonthBySpan()
* @deprecated Method deprecated in Release 1.4.4
*/
function beginOfMonth($month = 0, $year = null, $format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
return Date_Calc::dateFormat(Date_Calc::getFirstDayOfMonth($month,
$year),
$month,
$year,
$format);
}
// }}}
// {{{ endOfMonth()
/**
* Return date of last day of month of given date
*
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @see Date_Calc::beginOfMonthBySpan()
* @since Method available since Release [next version]
* @deprecated Method deprecated in Release [next version]
*/
function endOfMonth($month = 0, $year = null, $format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
return Date_Calc::daysToDate(Date_Calc::lastDayOfMonth($month, $year),
$format);
}
// }}}
// {{{ beginOfPrevMonth()
/**
* Returns date of the first day of previous month of given date
*
* @param mixed $dummy irrelevant parameter
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @see Date_Calc::beginOfMonthBySpan()
* @deprecated Method deprecated in Release 1.4.4
*/
function beginOfPrevMonth($dummy = null,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
list($hn_pmyear, $hn_prevmonth) = Date_Calc::prevMonth($month, $year);
return Date_Calc::dateFormat(Date_Calc::getFirstDayOfMonth($hn_prevmonth,
$hn_pmyear),
$hn_prevmonth,
$hn_pmyear,
$format);
}
// }}}
// {{{ endOfPrevMonth()
/**
* Returns date of the last day of previous month for given date
*
* @param mixed $dummy irrelevant parameter
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @see Date_Calc::endOfMonthBySpan()
* @deprecated Method deprecated in Release 1.4.4
*/
function endOfPrevMonth($dummy = null,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
return Date_Calc::daysToDate(Date_Calc::firstDayOfMonth($month,
$year) - 1,
$format);
}
// }}}
// {{{ beginOfNextMonth()
/**
* Returns date of begin of next month of given date
*
* @param mixed $dummy irrelevant parameter
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @see Date_Calc::beginOfMonthBySpan()
* @deprecated Method deprecated in Release 1.4.4
*/
function beginOfNextMonth($dummy = null,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
list($hn_nmyear, $hn_nextmonth) = Date_Calc::nextMonth($month, $year);
return Date_Calc::dateFormat(Date_Calc::getFirstDayOfMonth($hn_nextmonth,
$hn_nmyear),
$hn_nextmonth,
$hn_nmyear,
$format);
}
// }}}
// {{{ endOfNextMonth()
/**
* Returns date of the last day of next month of given date
*
* @param mixed $dummy irrelevant parameter
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @see Date_Calc::endOfMonthBySpan()
* @deprecated Method deprecated in Release 1.4.4
*/
function endOfNextMonth($dummy = null,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
list($hn_nmyear, $hn_nextmonth) = Date_Calc::nextMonth($month, $year);
return Date_Calc::daysToDate(Date_Calc::lastDayOfMonth($hn_nextmonth,
$hn_nmyear),
$format);
}
// }}}
// {{{ beginOfMonthBySpan()
/**
* Returns date of the first day of the month in the number of months
* from the given date
*
* @param int $months the number of months from the date provided.
* Positive numbers go into the future.
* Negative numbers go into the past.
* 0 is the month presented in $month.
* @param string $month the month, default is current local month
* @param string $year the year in four digit format, default is the
* current local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @since Method available since Release 1.4.4
*/
function beginOfMonthBySpan($months = 0,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
return Date_Calc::addMonths($months,
Date_Calc::getFirstDayOfMonth($month, $year),
$month,
$year,
$format);
}
// }}}
// {{{ endOfMonthBySpan()
/**
* Returns date of the last day of the month in the number of months
* from the given date
*
* @param int $months the number of months from the date provided.
* Positive numbers go into the future.
* Negative numbers go into the past.
* 0 is the month presented in $month.
* @param string $month the month, default is current local month
* @param string $year the year in four digit format, default is the
* current local year
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
* @since Method available since Release 1.4.4
*/
function endOfMonthBySpan($months = 0,
$month = 0,
$year = null,
$format = DATE_CALC_FORMAT)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
$hn_days = Date_Calc::addMonthsToDays($months + 1,
Date_Calc::firstDayOfMonth($month, $year)) - 1;
return Date_Calc::daysToDate($hn_days, $format);
}
// }}}
// {{{ firstOfMonthWeekday()
/**
* Find the day of the week for the first of the month of given date
*
* @param int $month the month, default is current local month
* @param int $year the year in four digit format, default is current
* local year
*
* @return int number of weekday for the first day, 0=Sunday
* @access public
* @static
*/
function firstOfMonthWeekday($month = 0, $year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if (empty($month)) {
$month = Date_Calc::dateNow('%m');
}
return Date_Calc::daysToDayOfWeek(Date_Calc::firstDayOfMonth($month,
$year));
}
// }}}
// {{{ nWeekdayOfMonth()
/**
* Calculates the date of the Nth weekday of the month,
* such as the second Saturday of January 2000
*
* @param int $week the number of the week to get
* (1 = first, etc. Also can be 'last'.)
* @param int $dow the day of the week (0 = Sunday)
* @param int $month the month
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
* @param string $format the string indicating how to format the output
*
* @return string the date in the desired format
* @access public
* @static
*/
function nWeekdayOfMonth($week, $dow, $month, $year,
$format = DATE_CALC_FORMAT)
{
if (is_numeric($week)) {
$DOW1day = ($week - 1) * 7 + 1;
$DOW1 = Date_Calc::dayOfWeek($DOW1day, $month, $year);
$wdate = ($week - 1) * 7 + 1 + (7 + $dow - $DOW1) % 7;
if ($wdate > Date_Calc::daysInMonth($month, $year)) {
return -1;
} else {
return Date_Calc::dateFormat($wdate, $month, $year, $format);
}
} elseif ($week == 'last' && $dow < 7) {
$lastday = Date_Calc::daysInMonth($month, $year);
$lastdow = Date_Calc::dayOfWeek($lastday, $month, $year);
$diff = $dow - $lastdow;
if ($diff > 0) {
return Date_Calc::dateFormat($lastday - (7 - $diff), $month,
$year, $format);
} else {
return Date_Calc::dateFormat($lastday + $diff, $month,
$year, $format);
}
} else {
return -1;
}
}
// }}}
// {{{ isValidDate()
/**
* Returns true for valid date, false for invalid date
*
* Uses the proleptic Gregorian calendar, with the year 0 (1 B.C.)
* assumed to be valid and also assumed to be a leap year.
*
* @param int $day the day of the month
* @param int $month the month
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return bool
* @access public
* @static
*/
function isValidDate($day, $month, $year)
{
if ($day < 1 || $month < 1 || $month > 12)
return false;
if ($month == 2) {
if (Date_Calc::isLeapYearGregorian($year)) {
return $day <= 29;
} else {
return $day <= 28;
}
} elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
return $day <= 30;
} else {
return $day <= 31;
}
}
// }}}
// {{{ isLeapYearGregorian()
/**
* Returns true for a leap year, else false
*
* Uses the proleptic Gregorian calendar. The year 0 (1 B.C.) is
* assumed in this algorithm to be a leap year. The function is
* valid for all years, positive and negative.
*
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return bool
* @access public
* @static
* @since Method available since Release [next version]
*/
function isLeapYearGregorian($year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
return (($year % 4 == 0) &&
($year % 100 != 0)) ||
($year % 400 == 0);
}
// }}}
// {{{ isLeapYearJulian()
/**
* Returns true for a leap year, else false
*
* Uses the proleptic Julian calendar. The year 0 (1 B.C.) is
* assumed in this algorithm to be a leap year. The function is
* valid for all years, positive and negative.
*
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return boolean
* @access public
* @static
* @since Method available since Release [next version]
*/
function isLeapYearJulian($year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
return $year % 4 == 0;
}
// }}}
// {{{ isLeapYear()
/**
* Returns true for a leap year, else false
*
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return boolean
* @access public
* @static
*/
function isLeapYear($year = null)
{
if (is_null($year)) {
$year = Date_Calc::dateNow('%Y');
}
if ($year < 1582) {
// pre Gregorio XIII - 1582
return Date_Calc::isLeapYearJulian($year);
} else {
// post Gregorio XIII - 1582
return Date_Calc::isLeapYearGregorian($year);
}
}
// }}}
// {{{ isFutureDate()
/**
* Determines if given date is a future date from now
*
* @param int $day the day of the month
* @param int $month the month
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return bool
* @access public
* @static
*/
function isFutureDate($day, $month, $year)
{
$this_year = Date_Calc::dateNow('%Y');
$this_month = Date_Calc::dateNow('%m');
$this_day = Date_Calc::dateNow('%d');
if ($year > $this_year) {
return true;
} elseif ($year == $this_year) {
if ($month > $this_month) {
return true;
} elseif ($month == $this_month) {
if ($day > $this_day) {
return true;
}
}
}
return false;
}
// }}}
// {{{ isPastDate()
/**
* Determines if given date is a past date from now
*
* @param int $day the day of the month
* @param int $month the month
* @param int $year the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return boolean
* @access public
* @static
*/
function isPastDate($day, $month, $year)
{
$this_year = Date_Calc::dateNow('%Y');
$this_month = Date_Calc::dateNow('%m');
$this_day = Date_Calc::dateNow('%d');
if ($year < $this_year) {
return true;
} elseif ($year == $this_year) {
if ($month < $this_month) {
return true;
} elseif ($month == $this_month) {
if ($day < $this_day) {
return true;
}
}
}
return false;
}
// }}}
// {{{ dateDiff()
/**
* Returns number of days between two given dates
*
* @param int $day1 the day of the month
* @param int $month1 the month
* @param int $year1 the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
* @param int $day2 the day of the month
* @param int $month2 the month
* @param int $year2 the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return int the absolute number of days between the two dates.
* If an error occurs, -1 is returned.
* @access public
* @static
*/
function dateDiff($day1, $month1, $year1, $day2, $month2, $year2)
{
if (!Date_Calc::isValidDate($day1, $month1, $year1)) {
return -1;
}
if (!Date_Calc::isValidDate($day2, $month2, $year2)) {
return -1;
}
return abs(Date_Calc::dateToDays($day1, $month1, $year1)
- Date_Calc::dateToDays($day2, $month2, $year2));
}
// }}}
// {{{ compareDates()
/**
* Compares two dates
*
* @param int $day1 the day of the month
* @param int $month1 the month
* @param int $year1 the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
* @param int $day2 the day of the month
* @param int $month2 the month
* @param int $year2 the year. Use the complete year instead of the
* abbreviated version. E.g. use 2005, not 05.
*
* @return int 0 if the dates are equal. 1 if date 1 is later, -1
* if date 1 is earlier.
* @access public
* @static
*/
function compareDates($day1, $month1, $year1, $day2, $month2, $year2)
{
$ndays1 = Date_Calc::dateToDays($day1, $month1, $year1);
$ndays2 = Date_Calc::dateToDays($day2, $month2, $year2);
if ($ndays1 == $ndays2) {
return 0;
}
return ($ndays1 > $ndays2) ? 1 : -1;
}
// }}}
// {{{ round()
/**
* Rounds the date according to the specified precision
*
* The precision parameter must be one of the following constants:
*
* <code>DATE_PRECISION_YEAR</code>
* <code>DATE_PRECISION_MONTH</code>
* <code>DATE_PRECISION_DAY</code>
* <code>DATE_PRECISION_HOUR</code>
* <code>DATE_PRECISION_10MINUTES</code>
* <code>DATE_PRECISION_MINUTE</code>
* <code>DATE_PRECISION_10SECONDS</code>
* <code>DATE_PRECISION_SECOND</code>
*
* The precision can also be specified as an integral offset from
* one of these constants, where the offset reflects a precision
* of 10 to the power of the offset greater than the constant.
* For example:
*
* <code>DATE_PRECISION_YEAR - 1</code> rounds the date to the nearest 10
* years
* <code>DATE_PRECISION_YEAR - 3</code> rounds the date to the nearest 1000
* years
* <code>DATE_PRECISION_SECOND + 1</code> rounds the date to 1 decimal
* point of a second
* <code>DATE_PRECISION_SECOND + 1</code> rounds the date to 3 decimal
* points of a second
* <code>DATE_PRECISION_SECOND + 1</code> rounds the date to the nearest 10
* seconds (thus it is equivalent to
* DATE_PRECISION_10SECONDS)
*
* N.B. This function requires a time in UTC if both the precision is at
* least DATE_PRECISION_SECOND and leap seconds are being counted, otherwise
* any local time is acceptable.
*
* @param int $pn_precision a 'DATE_PRECISION_*' constant
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
* @param mixed $pn_second the second as integer or float
* @param bool $pb_countleap whether to count leap seconds (defaults to
* DATE_COUNT_LEAP_SECONDS)
*
* @return array array of year, month, day, hour, minute, second
* @access public
* @static
* @since Method available since Release [next version]
*/
function round($pn_precision,
$pn_day,
$pn_month,
$pn_year,
$pn_hour = 0,
$pn_minute = 0,
$pn_second = 0,
$pb_countleap = DATE_COUNT_LEAP_SECONDS)
{
if ($pn_precision <= DATE_PRECISION_YEAR) {
$hn_month = 0;
$hn_day = 0;
$hn_hour = 0;
$hn_minute = 0;
$hn_second = 0;
if ($pn_precision < DATE_PRECISION_YEAR) {
$hn_year = round($pn_year, $pn_precision - DATE_PRECISION_YEAR);
} else {
// Check part-year:
//
$hn_midyear = (Date_Calc::firstDayOfYear($pn_year + 1) -
Date_Calc::firstDayOfYear($pn_year)) / 2;
if (($hn_days = Date_Calc::dayOfYear($pn_day,
$pn_month,
$pn_year)) <=
$hn_midyear - 1) {
$hn_year = $pn_year;
} else if ($hn_days >= $hn_midyear) {
// Round up:
//
$hn_year = $pn_year + 1;
} else {
// Take time into account:
//
$hn_partday = Date_Calc::secondsPastMidnight($pn_hour,
$pn_minute,
$pn_second) /
86400;
if ($hn_partday >= $hn_midyear - $hn_days) {
// Round up:
//
$hn_year = $pn_year + 1;
} else {
$hn_year = $pn_year;
}
}
}
} else if ($pn_precision == DATE_PRECISION_MONTH) {
$hn_year = $pn_year;
$hn_day = 0;
$hn_hour = 0;
$hn_minute = 0;
$hn_second = 0;
$hn_firstofmonth = Date_Calc::firstDayOfMonth($pn_month, $pn_year);
$hn_midmonth = (Date_Calc::lastDayOfMonth($pn_month, $pn_year) +
1 -
$hn_firstofmonth) / 2;
if (($hn_days = Date_Calc::dateToDays($pn_day,
$pn_month,
$pn_year) -
$hn_firstofmonth) <= $hn_midmonth - 1) {
$hn_month = $pn_month;
} else if ($hn_days >= $hn_midmonth) {
// Round up:
//
list($hn_year, $hn_month) = Date_Calc::nextMonth($pn_month,
$pn_year);
} else {
// Take time into account:
//
$hn_partday = Date_Calc::secondsPastMidnight($pn_hour,
$pn_minute,
$pn_second) /
86400;
if ($hn_partday >= $hn_midmonth - $hn_days) {
// Round up:
//
list($hn_year, $hn_month) = Date_Calc::nextMonth($pn_month,
$pn_year);
} else {
$hn_month = $pn_month;
}
}
} else if ($pn_precision == DATE_PRECISION_DAY) {
$hn_year = $pn_year;
$hn_month = $pn_month;
$hn_hour = 0;
$hn_minute = 0;
$hn_second = 0;
if (Date_Calc::secondsPastMidnight($pn_hour,
$pn_minute,
$pn_second) >= 43200) {
// Round up:
//
list($hn_year, $hn_month, $hn_day) =
explode(" ", Date_Calc::nextDay($pn_day,
$pn_month,
$pn_year,
"%Y %m %d"));
} else {
$hn_day = $pn_day;
}
} else if ($pn_precision == DATE_PRECISION_HOUR) {
$hn_year = $pn_year;
$hn_month = $pn_month;
$hn_day = $pn_day;
$hn_minute = 0;
$hn_second = 0;
if (Date_Calc::secondsPastTheHour($pn_minute, $pn_second) >= 1800) {
// Round up:
//
list($hn_year, $hn_month, $hn_day, $hn_hour) =
Date_Calc::addHours(1,
$pn_day,
$pn_month,
$pn_year,
$pn_hour);
} else {
$hn_hour = $pn_hour;
}
} else if ($pn_precision <= DATE_PRECISION_MINUTE) {
$hn_year = $pn_year;
$hn_month = $pn_month;
$hn_day = $pn_day;
$hn_hour = $pn_hour;
$hn_second = 0;
if ($pn_precision < DATE_PRECISION_MINUTE) {
$hn_minute = round($pn_minute,
$pn_precision - DATE_PRECISION_MINUTE);
} else {
// Check seconds:
//
if ($pn_second >= 30) {
// Round up:
//
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute) =
Date_Calc::addMinutes(1,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute);
} else {
$hn_minute = $pn_minute;
}
}
} else {
// Precision is at least (DATE_PRECISION_SECOND - 1):
//
$hn_year = $pn_year;
$hn_month = $pn_month;
$hn_day = $pn_day;
$hn_hour = $pn_hour;
$hn_minute = $pn_minute;
$hn_second = round($pn_second,
$pn_precision - DATE_PRECISION_SECOND);
if (fmod($hn_second, 1) == 0.0) {
$hn_second = (int) $hn_second;
if ($hn_second != intval($pn_second)) {
list($hn_year,
$hn_month,
$hn_day,
$hn_hour,
$hn_minute,
$hn_second) =
Date_Calc::addSeconds($hn_second - intval($pn_second),
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
intval($pn_second),
$pn_precision >=
DATE_PRECISION_SECOND &&
$pb_countleap);
//
// (N.B. if rounded to nearest 10 seconds,
// user does not expect seconds to be '60')
}
}
}
return array((int) $hn_year,
(int) $hn_month,
(int) $hn_day,
(int) $hn_hour,
(int) $hn_minute,
$hn_second);
}
// }}}
// {{{ roundSeconds()
/**
* Rounds seconds up or down to the nearest specified unit
*
* @param int $pn_precision number of digits after the decimal point
* @param int $pn_day the day of the month
* @param int $pn_month the month
* @param int $pn_year the year
* @param int $pn_hour the hour
* @param int $pn_minute the minute
* @param mixed $pn_second the second as integer or float
* @param bool $pb_countleap whether to count leap seconds (defaults to
* DATE_COUNT_LEAP_SECONDS)
*
* @return array array of year, month, day, hour, minute, second
* @access public
* @static
* @since Method available since Release [next version]
*/
function roundSeconds($pn_precision,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second,
$pb_countleap = DATE_COUNT_LEAP_SECONDS)
{
return Date_Calc::round(DATE_PRECISION_SECOND + $pn_precision,
$pn_day,
$pn_month,
$pn_year,
$pn_hour,
$pn_minute,
$pn_second);
}
// }}}
}
// }}}
/*
* Local variables:
* mode: php
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
?> | {
"content_hash": "3bc50a8902e9ac96288381c36b0668a3",
"timestamp": "",
"source": "github",
"line_count": 4363,
"max_line_length": 145,
"avg_line_length": 34.391473756589505,
"alnum_prop": 0.46372542485838053,
"repo_name": "BigBlueHat/atmailopen",
"id": "dfaade5dd416a71d89a15491a46b315e7fcfd4f7",
"size": "150050",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/PEAR/Date/Calc.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "417054"
},
{
"name": "PHP",
"bytes": "2039705"
},
{
"name": "Perl",
"bytes": "25877"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('book', '0009_auto_20161119_1214'),
]
operations = [
migrations.AddField(
model_name='item',
name='slag',
field=models.SlugField(allow_unicode=True, blank=True, max_length=16, null=True),
),
]
| {
"content_hash": "e75dab53795059a177d3af1b202af9c0",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 93,
"avg_line_length": 22.88888888888889,
"alnum_prop": 0.5995145631067961,
"repo_name": "wkomor/pickthebook",
"id": "5e0dbbe782cc70de7890fe5307f4bd7c2d3f16a4",
"size": "482",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "book/migrations/0010_item_slag.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "370"
},
{
"name": "HTML",
"bytes": "19326"
},
{
"name": "JavaScript",
"bytes": "7148"
},
{
"name": "Python",
"bytes": "18870"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="en">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Bitcoin</source>
<translation>About Fu</translation>
</message>
<message>
<location line="+39"/>
<source><b>Bitcoin</b> version</source>
<translation><b>Fu</b> version</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING 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 ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING 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 ([email protected]) and UPnP software written by Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The Bitcoin developers</source>
<translation>The Bitcoin developers</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Address Book</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Double-click to edit address or label</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Create a new address</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copy the currently selected address to the system clipboard</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&New Address</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Bitcoin 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>These are your Fu 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.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copy Address</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Show &QR Code</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Bitcoin address</source>
<translation>Sign a message to prove you own a Fu address</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Sign &Message</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Delete the currently selected address from the list</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Export the data in the current tab to a file</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Bitcoin address</source>
<translation>Verify a message to ensure it was signed with a specified Fu address</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Delete</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>These are your Fu addresses for sending payments. Always check the amount and the receiving address before sending coins.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copy &Label</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Edit</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Send &Coins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Export Address Book Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(no label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Passphrase Dialog</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Enter passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>New passphrase</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repeat new passphrase</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<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>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>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Encrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>This operation needs your wallet passphrase to unlock the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Unlock wallet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>This operation needs your wallet passphrase to decrypt the wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Decrypt wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Change passphrase</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Enter the old and new passphrase to the wallet.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirm wallet encryption</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR FUS</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Are you sure you wish to encrypt your wallet?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Warning: The Caps Lock key is on!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Wallet encrypted</translation>
</message>
<message>
<location line="-56"/>
<source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>Fu will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your fus from being stolen by malware infecting your computer.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Wallet encryption failed</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>The supplied passphrases do not match.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Wallet unlock failed</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>The passphrase entered for the wallet decryption was incorrect.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Wallet decryption failed</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Wallet passphrase was successfully changed.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Sign &message...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synchronizing with network...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Overview</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Show general overview of wallet</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transactions</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Browse transaction history</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Edit the list of stored addresses and labels</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Show the list of addresses for receiving payments</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>E&xit</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Quit application</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Bitcoin</source>
<translation>Show information about Fu</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>About &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Show information about Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Options...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Encrypt Wallet...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup Wallet...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Change Passphrase...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importing blocks from disk...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Reindexing blocks on disk...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Bitcoin address</source>
<translation>Send coins to a Fu address</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Bitcoin</source>
<translation>Modify configuration options for Fu</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Backup wallet to another location</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Change the passphrase used for wallet encryption</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debug window</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Open debugging and diagnostic console</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verify message...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Bitcoin</source>
<translation>Fu</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Send</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Receive</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Addresses</translation>
</message>
<message>
<location line="+22"/>
<source>&About Bitcoin</source>
<translation>&About Fu</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Show / Hide</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Show or hide the main Window</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Encrypt the private keys that belong to your wallet</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Bitcoin addresses to prove you own them</source>
<translation>Sign messages with your Fu addresses to prove you own them</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Bitcoin addresses</source>
<translation>Verify messages to ensure they were signed with specified Fu addresses</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&File</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Settings</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Help</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Tabs toolbar</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Bitcoin client</source>
<translation>Fu client</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Bitcoin network</source>
<translation>
<numerusform>%n active connection to Fu network</numerusform>
<numerusform>%n active connections to Fu network</numerusform>
</translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>No block source available...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Processed %1 of %2 (estimated) blocks of transaction history.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Processed %1 blocks of transaction history.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation>
<numerusform>%n hour</numerusform>
<numerusform>%n hours</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation>
<numerusform>%n day</numerusform>
<numerusform>%n days</numerusform>
</translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation>
<numerusform>%n week</numerusform>
<numerusform>%n weeks</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 behind</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Last received block was generated %1 ago.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transactions after this will not yet be visible.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Up to date</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Catching up...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirm transaction fee</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sent transaction</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Incoming transaction</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Date: %1
Amount: %2
Type: %3
Address: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI handling</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source>
<translation>URI can not be parsed! This can be caused by an invalid Fu address or malformed URI parameters.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>unlocked</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Wallet is <b>encrypted</b> and currently <b>locked</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source>
<translation>A fatal error occurred. Fu can no longer continue safely and will quit.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Network Alert</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Edit Address</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>The label associated with this address book entry</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Address</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>The address associated with this address book entry. This can only be modified for sending addresses.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>New receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>New sending address</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Edit receiving address</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Edit sending address</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>The entered address "%1" is already in the address book.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Bitcoin address.</source>
<translation>The entered address "%1" is not a valid Fu address.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Could not unlock wallet.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>New key generation failed.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Bitcoin-Qt</source>
<translation>Fu-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>command-line options</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI options</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Set language, for example "de_DE" (default: system locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Start minimized</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Show splash screen on startup (default: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Options</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Main</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Pay transaction &fee</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Bitcoin after logging in to the system.</source>
<translation>Automatically start Fu after logging in to the system.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Bitcoin on system login</source>
<translation>&Start Fu on system login</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Reset all client options to default.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Reset Options</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Network</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatically open the Fu client port on the router. This only works when your router supports UPnP and it is enabled.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Map port using &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Bitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Connect to the Fu network through a SOCKS proxy (e.g. when connecting through Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Connect through SOCKS proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP address of the proxy (e.g. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port of the proxy (e.g. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Version:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS version of the proxy (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Window</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Show only a tray icon after minimizing the window.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimize to the tray instead of the taskbar</translation>
</message>
<message>
<location line="+7"/>
<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>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.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimize on close</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Display</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>User Interface &language:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source>
<translation>The user interface language can be set here. This setting will take effect after restarting Fu.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unit to show amounts in:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Choose the default subdivision unit to show in the interface and when sending coins.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Bitcoin addresses in the transaction list or not.</source>
<translation>Whether to show Fu addresses in the transaction list or not.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Display addresses in transaction list</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancel</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Apply</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>default</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirm options reset</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Some settings may require a client restart to take effect.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Do you want to proceed?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Bitcoin.</source>
<translation>This setting will take effect after restarting Fu.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>The supplied proxy address is invalid.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<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>The displayed information may be out of date. Your wallet automatically synchronizes with the Fu network after a connection is established, but this process has not completed yet.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Unconfirmed:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Wallet</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Immature:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Mined balance that has not yet matured</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Recent transactions</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Your current balance</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>out of sync</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start bitcoin: click-to-pay handler</source>
<translation>Cannot start fu: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Code Dialog</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Request Payment</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Amount:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Label:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Message:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Save As...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Error encoding URI into QR Code.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>The entered amount is invalid, please check.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Resulting URI too long, try to reduce the text for label / message.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Save QR Code</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Images (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Client name</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Client version</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Information</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Using OpenSSL version</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Startup time</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Network</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Number of connections</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>On testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Block chain</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Current number of blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Estimated total blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Last block time</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Command-line options</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Bitcoin-Qt help message to get a list with possible Bitcoin command-line options.</source>
<translation>Show the Fu-Qt help message to get a list with possible Fu command-line options.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Show</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Build date</translation>
</message>
<message>
<location line="-104"/>
<source>Bitcoin - Debug window</source>
<translation>Fu - Debug window</translation>
</message>
<message>
<location line="+25"/>
<source>Bitcoin Core</source>
<translation>Fu Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debug log file</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Open the Fu debug log file from the current data directory. This can take a few seconds for large log files.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Clear console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Bitcoin RPC console.</source>
<translation>Welcome to the Fu RPC console.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Type <b>help</b> for an overview of available commands.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Send to multiple recipients at once</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Add &Recipient</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Remove all transaction fields</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balance:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 FU</source>
<translation>123.456 FU</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Confirm the send action</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirm send coins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Are you sure you want to send %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> and </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>The recipient address is not valid, please recheck.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>The amount to pay must be larger than 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>The amount exceeds your balance.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>The total exceeds your balance when the %1 transaction fee is included.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Duplicate address found, can only send to each address once per send operation.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Error: Transaction creation failed!</translation>
</message>
<message>
<location line="+5"/>
<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>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.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>A&mount:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Pay &To:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Enter a label for this address to add it to your address book</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Choose address from address book</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Remove this recipient</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Enter a Fu address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Sign / Verify a Message</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Sign Message</translation>
</message>
<message>
<location line="+6"/>
<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>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.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Choose an address from the address book</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Paste address from clipboard</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Enter the message you want to sign here</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Signature</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copy the current signature to the system clipboard</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Bitcoin address</source>
<translation>Sign the message to prove you own this Fu address</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Sign &Message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Reset all sign message fields</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verify Message</translation>
</message>
<message>
<location line="+6"/>
<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>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.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Bitcoin address</source>
<translation>Verify the message to ensure it was signed with the specified Fu address</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verify &Message</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Reset all verify message fields</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Enter a Fu address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Click "Sign Message" to generate signature</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Bitcoin signature</source>
<translation>Enter Fu signature</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>The entered address is invalid.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Please check the address and try again.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>The entered address does not refer to a key.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Wallet unlock was cancelled.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Private key for the entered address is not available.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Message signing failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Message signed.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>The signature could not be decoded.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Please check the signature and try again.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>The signature did not match the message digest.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Message verification failed.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Message verified.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Bitcoin developers</source>
<translation>The Bitcoin developers</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/offline</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/unconfirmed</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation>
<numerusform>, broadcast through %n node</numerusform>
<numerusform>, broadcast through %n nodes</numerusform>
</translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generated</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>From</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>To</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>own address</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>label</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation>
<numerusform>matures in %n more block</numerusform>
<numerusform>matures in %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>not accepted</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaction fee</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net amount</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comment</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaction ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 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, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Generated coins must mature 120 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, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug information</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>true</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>false</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, has not been successfully broadcast yet</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>unknown</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaction details</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>This pane shows a detailed description of the transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation>
<numerusform>Open for %n more block</numerusform>
<numerusform>Open for %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 confirmations)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Unconfirmed (%1 of %2 confirmations)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmed (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation>
<numerusform>Mined balance will be available when it matures in %n more block</numerusform>
<numerusform>Mined balance will be available when it matures in %n more blocks</numerusform>
</translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>This block was not received by any other nodes and will probably not be accepted!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generated but not accepted</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Received from</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Payment to yourself</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaction status. Hover over this field to show number of confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date and time that the transaction was received.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Destination address of transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Amount removed from or added to balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>All</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Today</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>This week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>This month</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Last month</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>This year</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Range...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>To yourself</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Other</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Enter address or label to search</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min amount</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copy address</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copy label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copy amount</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copy transaction ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Edit label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Show transaction details</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Export Transaction Data</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmed</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Address</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Amount</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exporting</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Could not write to file %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Range:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>to</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Export</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Export the data in the current tab to a file</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Backup Wallet</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Wallet Data (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Backup Failed</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>There was an error trying to save the wallet data to the new location.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Backup Successful</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>The wallet data was successfully saved to the new location.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Bitcoin version</source>
<translation>Fu version</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Usage:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or bitcoind</source>
<translation>Send command to -server or fud</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>List commands</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Get help for a command</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Options:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>Specify configuration file (default: fu.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>Specify pid file (default: fud.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Specify data directory</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Set database cache size in megabytes (default: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 11065 or testnet: 5744)</source>
<translation>Listen for connections on <port> (default: 11065 or testnet: 5744)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Maintain at most <n> connections to peers (default: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Connect to a node to retrieve peer addresses, and disconnect</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Specify your own public address</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Threshold for disconnecting misbehaving peers (default: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>An error occurred while setting up the RPC port %u for listening on IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 21065 or testnet: 5745)</source>
<translation>Listen for JSON-RPC connections on <port> (default: 21065 or testnet: 5745)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accept command line and JSON-RPC commands</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Run in the background as a daemon and accept commands</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Use the test network</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accept connections from outside (default: 1 if no -proxy or -connect)</translation>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Bitcoin Alert" [email protected]
</source>
<translation>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Bitcoin Alert" [email protected]
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Bind to given address and always listen on it. Use [host]:port notation for IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source>
<translation>Cannot obtain a lock on data directory %s. Fu is probably already running.</translation>
</message>
<message>
<location line="+3"/>
<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>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.</translation>
</message>
<message>
<location line="+4"/>
<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>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Execute command when a relevant alert is received (%s in cmd is replaced by message)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly.</source>
<translation>Warning: Please check that your computer's date and time are correct! If your clock is wrong Fu will not work properly.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Attempt to recover private keys from a corrupt wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Block creation options:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Connect only to the specified node(s)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Corrupted block database detected</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Discover own IP address (default: 1 when listening and no -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Do you want to rebuild the block database now?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Error initializing block database</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Error initializing wallet database environment %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Error loading block database</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Error opening block database</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Error: Disk space is low!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Error: Wallet locked, unable to create transaction!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Error: system error: </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Failed to listen on any port. Use -listen=0 if you want this.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Failed to read block info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Failed to read block</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Failed to sync block index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Failed to write block index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Failed to write block info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Failed to write block</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Failed to write file info</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Failed to write to coin database</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Failed to write transaction index</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Failed to write undo data</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Find peers using DNS lookup (default: 1 unless -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Generate coins (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>How many blocks to check at startup (default: 288, 0 = all)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>How thorough the block verification is (0-4, default: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Not enough file descriptors available.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Rebuild block chain index from current blk000??.dat files</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Set the number of threads to service RPC calls (default: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verifying blocks...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifying wallet...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Imports blocks from external blk000??.dat file</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Invalid -tor address: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Invalid amount for -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Invalid amount for -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Maintain a full transaction index (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Only accept block chain matching built-in checkpoints (default: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Output extra debugging information. Implies all other -debug* options</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Output extra network debugging information</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Prepend debug output with timestamp</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL options: (see the Fu Wiki for SSL setup instructions)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Select the version of socks proxy to use (4-5, default: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Send trace/debug info to console instead of debug.log file</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Send trace/debug info to debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Set maximum block size in bytes (default: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Set minimum block size in bytes (default: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Shrink debug.log file on client startup (default: 1 when no -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Signing transaction failed</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Specify connection timeout in milliseconds (default: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>System error: </translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Transaction amount too small</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Transaction amounts must be positive</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transaction too large</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Use UPnP to map the listening port (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Use UPnP to map the listening port (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Use proxy to reach tor hidden services (default: same as -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Username for JSON-RPC connections</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Warning</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Warning: This version is obsolete, upgrade required!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>You need to rebuild the databases using -reindex to change -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupt, salvage failed</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Password for JSON-RPC connections</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Allow JSON-RPC connections from specified IP address</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send commands to node running on <ip> (default: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Execute command when the best block changes (%s in cmd is replaced by block hash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Upgrade wallet to latest format</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Set key pool size to <n> (default: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Rescan the block chain for missing wallet transactions</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Use OpenSSL (https) for JSON-RPC connections</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Server certificate file (default: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Server private key (default: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>This help message</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Unable to bind to %s on this computer (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Connect through socks proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Allow DNS lookups for -addnode, -seednode and -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Loading addresses...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error loading wallet.dat: Wallet corrupted</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source>
<translation>Error loading wallet.dat: Wallet requires newer version of Fu</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Bitcoin to complete</source>
<translation>Wallet needed to be rewritten: restart Fu to complete</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error loading wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Invalid -proxy address: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Unknown network specified in -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Unknown -socks proxy version requested: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Cannot resolve -bind address: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Cannot resolve -externalip address: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Invalid amount for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Invalid amount</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Insufficient funds</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Loading block index...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Add a node to connect to and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source>
<translation>Unable to bind to %s on this computer. Fu is probably already running.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Fee per KB to add to transactions you send</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Loading wallet...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Cannot downgrade wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Cannot write default address</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Rescanning...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Done loading</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>To use the %s option</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="-31"/>
<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>
<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>
</context>
</TS>
| {
"content_hash": "421b4131da64b28abe85710d5a17c6aa",
"timestamp": "",
"source": "github",
"line_count": 2967,
"max_line_length": 405,
"avg_line_length": 38.73407482305359,
"alnum_prop": 0.6249956492986669,
"repo_name": "fucoinasia/fucoin",
"id": "cea146bcee2a26c291bedfd1d4baadcf0b047f00",
"size": "114924",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/bitcoin_en.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "30189"
},
{
"name": "C++",
"bytes": "2494293"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "2734"
},
{
"name": "Python",
"bytes": "3763"
},
{
"name": "Shell",
"bytes": "7983"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Rack::EncodingGuard::RejectStrategy do
include_examples 'Strategy'
let! :env do
Rack::MockRequest.env_for('http://example.com/some/path?and=query&string=set')
end
let :app_response do
[200, {}, ['Default']]
end
context 'with valid environment' do
it 'cascades to the app response' do
strategy = described_class.new
expect(strategy.process(env) { app_response }).to eq app_response
end
end
INVALID_ENV_VARS = {
'HTTP_REFERER' => "http://example.com/so\255me/ref\255erer/path",
'PATH_INFO' => "/some/pa\255th",
'REQUEST_URI' => "/so\255me/request/path?a\255nd=query",
'REQUEST_PATH' => "/some/pa\255th",
'QUERY_STRING' => "and=que\255ry&str\255ing=set"
}
INVALID_ENV_VARS.each do |name, value|
context "with invalid #{name}" do
before do
env[name] = value
end
it 'responds with bad request status' do
expected_response = [400, {}, ['Bad Request']]
strategy = described_class.new
expect(strategy.process(env) { app_response }).to eq expected_response
end
context 'with response text configured' do
it 'responds with bad request status and custom message' do
custom_text = 'Something went wrong'
expected_response = [400, {}, [custom_text]]
strategy = described_class.new(with: custom_text)
expect(strategy.process(env) { app_response }).to eq expected_response
end
end
end
end
end
| {
"content_hash": "fead49ebe4872650a9a6c798b3d08774",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 82,
"avg_line_length": 29.862745098039216,
"alnum_prop": 0.6316480630334865,
"repo_name": "tlux/rack-encoding_guard",
"id": "a4e45e8e967a407ca9ef5d4dc80157d53d97865b",
"size": "1523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/lib/rack/encoding_guard/reject_strategy_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "16763"
}
],
"symlink_target": ""
} |
DOUBTFUL
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "8e062638bcb1248994cd343006bc3a19",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "1e9f3334ebb4f8a8251898f34f68f80bc9adb5b4",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Artemisia/Artemisia afra/Artemisia afra arussorum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('todos', { path: '/todos/:status' }, function() {
this.route('todo-message', { path: '/:todo-id' } );
});
this.route('todos.new', { path: '/todos/new' });
});
export default Router;
| {
"content_hash": "452e3d1a92dbce8d8d52b4c2badb8888",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 62,
"avg_line_length": 22.38888888888889,
"alnum_prop": 0.6426799007444168,
"repo_name": "thoov/ember-state-services",
"id": "d285c69cd1be2a5984df041d7069d211fa660e66",
"size": "403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/dummy/app/router.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1532"
},
{
"name": "HTML",
"bytes": "4732"
},
{
"name": "JavaScript",
"bytes": "17425"
}
],
"symlink_target": ""
} |
module RuboCop
module Cop
module Performance
# This cop identifies unnecessary use of a regex where `String#end_with?`
# would suffice.
#
# @example
# @bad
# 'abc' =~ /bc\Z/
# 'abc'.match(/bc\Z/)
#
# @good
# 'abc' =~ /ab/
# 'abc' =~ /\w*\Z/
class EndWith < Cop
MSG = 'Use `String#end_with?` instead of a regex match anchored to ' \
'the end of the string.'.freeze
SINGLE_QUOTE = "'".freeze
def_node_matcher :redundant_regex?, <<-END
{(send $!nil {:match :=~} (regexp (str $#literal_at_end?) (regopt)))
(send (regexp (str $#literal_at_end?) (regopt)) {:match :=~} $_)}
END
def literal_at_end?(regex_str)
# is this regexp 'literal' in the sense of only matching literal
# chars, rather than using metachars like . and * and so on?
# also, is it anchored at the end of the string?
regex_str =~ /\A(?:#{LITERAL_REGEX})+\\z\z/
end
def on_send(node)
add_offense(node, :expression, MSG) if redundant_regex?(node)
end
def autocorrect(node)
redundant_regex?(node) do |receiver, regex_str|
receiver, regex_str = regex_str, receiver if receiver.is_a?(String)
regex_str = regex_str[0..-3] # drop \Z anchor
regex_str = interpret_string_escapes(regex_str)
lambda do |corrector|
new_source = receiver.source + '.end_with?(' +
to_string_literal(regex_str) + ')'
corrector.replace(node.source_range, new_source)
end
end
end
end
end
end
end
| {
"content_hash": "e37f367acf5e4eca2cdd9375fceffe57",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 79,
"avg_line_length": 33.26923076923077,
"alnum_prop": 0.523121387283237,
"repo_name": "legendetm/rubocop",
"id": "4080d30370d2cdd37e7b0bd2fd8779925480883d",
"size": "1779",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/rubocop/cop/performance/end_with.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "355"
},
{
"name": "HTML",
"bytes": "7106"
},
{
"name": "Ruby",
"bytes": "3268739"
}
],
"symlink_target": ""
} |
package com.juanathan.movebox;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import java.util.ArrayList;
/**
* Created by Jonathan on 23/04/2015.
*/
public class BoldBox extends GameObject {
//enum BoxType {STRAIGHT_SHOOTER, SIDE_SWITCHER, CARDBOARD_CONCENTRATOR, CONFUSED_CRATE, PAUSING_PACKAGE}
ArrayList<ColourPair> cPs;
Paint paint = new Paint();
private boolean fancy;
public BoldBox(int x, int y, int width, int height){
super.x= x;
super.y = y;
super.width = width;
super.height = height;
fancy = true;
cPs = new ArrayList<ColourPair>(3);
cPs.add(new ColourPair(0, true, 5, 255));
cPs.add(new ColourPair(128, true, 5, 255));
cPs.add(new ColourPair(255, false, 5, 255));
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.MAGENTA);
}
public void update() {
if (fancy) {
for (ColourPair cp : cPs) {
cp.update();
}
paint.setColor(Color.rgb(cPs.get(0).getcVal(), cPs.get(1).getcVal(), cPs.get(2).getcVal()));
}
dy +=1;
if (dy > 10) dy = 10;
y+=dy;
}
public void draw(Canvas canvas){
canvas.drawRect((x - width / 2), (y - height / 2), (x + width / 2), (y + height / 2), paint);
}
}
| {
"content_hash": "5e45a1620120a3cf051a46241cab2fea",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 109,
"avg_line_length": 25.537037037037038,
"alnum_prop": 0.5786802030456852,
"repo_name": "jamtot/MoveBox",
"id": "ea7a72f7101494d035ade12677efcb193bf323f4",
"size": "1379",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/juanathan/movebox/BoldBox.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "19533"
}
],
"symlink_target": ""
} |
package com.syaku.modules.menu;
import java.util.*;
import org.apache.log4j.Logger;
import org.apache.commons.lang.*;
import org.apache.commons.configuration.*;
import com.syaku.core.util.*;
import com.syaku.modules.module.*;
import com.syaku.modules.install.*;
public class MenuInstall extends MenuObject {
private Logger log = Logger.getLogger( this.getClass() );
private ModuleObject daoModule = new ModuleObject();
private InstallObject daoInstall = new InstallObject();
private PropertiesConfiguration CONFIG;
private String module = modConfig.getString("mei.module.name");
private String title = modConfig.getString("mei.module.title");
private String rdate;
private String config_name = "mei.install." + module;
private String module_orl; // 싱글인 경우
public void getInstallBefore() throws Exception {
try {
sqlMap.startTransaction();
prepare();
getTableCreate();
sqlMap.commitTransaction();
} catch (Exception e) {
log.error(e.toString());
} finally {
sqlMap.endTransaction();
}
}
public void getInstallAfter() throws Exception {
try {
sqlMap.startTransaction();
prepare();
getDataModuleInsert();
getDataMenuInsert();
getPropModule();
sqlMap.commitTransaction();
} catch (Exception e) {
log.error(e.toString());
} finally {
sqlMap.endTransaction();
}
}
//install
public void prepare() throws Exception {
CONFIG = (PropertiesConfiguration) daoInstall.setModuleProperties();
CONFIG.setAutoSave(true);
}
public void getTableCreate() throws Exception {
sqlMenuCreate(null);
sqlMenuItemCreate(null);
rdate = DateUtils.date("yyyyMMddHHmmss");
CONFIG.setProperty(config_name + ".rdate" , rdate);
CONFIG.setProperty(config_name , true);
}
public void getPropModule() throws Exception {
//생성된 모듈 데이터 프로퍼티 생성
String get_module_orl = daoModule.getModule_orl(module);
ModuleProperties prop = new ModuleProperties();
prop.config2prop(get_module_orl);
}
public void getDataModuleInsert() throws Exception {
String get_module_orl = daoModule.getModule_orl(module);
this.module_orl = CONFIG.getString(config_name + ".module_orl" , get_module_orl );
if ( StringUtils.isEmpty(module_orl) ) {
ModuleBean modulebean = new ModuleBean();
modulebean.setModule(module);
modulebean.setMid(module);
modulebean.setBrowser_title(title);
modulebean.setRdate(rdate);
module_orl = daoModule.moduleInsert(modulebean);
}
CONFIG.setProperty(config_name + ".module_orl",module_orl);
}
public void getDataMenuInsert() throws Exception {
String menu_orl = "1";
String parent_orl = "2";
String menu_item_orl = CONFIG.getString(config_name + ".menu_item_orl");
String url = "dispMenuAdminList.me?mid=admin";
if ( StringUtils.isEmpty(menu_item_orl) ) {
menu_item_orl = getMenu_item_orl(title,url);
if ( StringUtils.isEmpty(menu_item_orl) ) {
MenuItemBean data = new MenuItemBean();
data.setMenu_item_orl(null);
data.setParent_orl(parent_orl);
data.setNum( getMenuItemNumSort(menu_orl,parent_orl) );
data.setMenu_orl(menu_orl);
data.setUrl(url);
data.setName(title);
data.setOpen_window("0");
data.setExpand("1");
data.setIs_mobile("0");
data.setRdate(rdate);
menu_item_orl = sqlMenuItemInsert(data);
}
CONFIG.setProperty(config_name + ".menu_item_orl",menu_item_orl);
}
}
} | {
"content_hash": "173d74ae58f533a091be88d6dca9221f",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 86,
"avg_line_length": 28.158730158730158,
"alnum_prop": 0.6747463359639233,
"repo_name": "syakuis/java-mei",
"id": "1ee6d7460e2d27a18d505643237ce3f61ab3f33b",
"size": "3795",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WEB-INF/src/com/syaku/modules/menu/MenuInstall.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "202062"
},
{
"name": "Java",
"bytes": "767133"
},
{
"name": "JavaScript",
"bytes": "3352921"
},
{
"name": "PHP",
"bytes": "1487"
},
{
"name": "Shell",
"bytes": "4068"
}
],
"symlink_target": ""
} |
package se.danielkonsult.fsm4j.states;
public class TestState5 extends BaseState {
}
| {
"content_hash": "9f93c7442bfdd7666f6921e2ee81bf73",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 43,
"avg_line_length": 21.5,
"alnum_prop": 0.813953488372093,
"repo_name": "bolddp/fsm4j",
"id": "09c650185b1b8d4c04e4afd13cf172f8c4d0f414",
"size": "86",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/se/danielkonsult/fsm4j/states/TestState5.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "56057"
}
],
"symlink_target": ""
} |
@extends('layouts.master')
@section('app-content')
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h1 class="text-center">Register</h1>
<form method="POST" action="/register">
{!! csrf_field() !!}
<div class="col-md-12 raw-margin-top-24">
<label>Name</label>
<input class="form-control" type="text" name="name" value="{{ old('name') }}">
</div>
<div class="col-md-12 raw-margin-top-24">
<label>Email</label>
<input class="form-control" type="email" name="email" value="{{ old('email') }}">
</div>
<div class="col-md-12 raw-margin-top-24">
<label>Password</label>
<input class="form-control" type="password" name="password">
</div>
<div class="col-md-12 raw-margin-top-24">
<label>Confirm Password</label>
<input class="form-control" type="password" name="password_confirmation">
</div>
<div class="col-md-12 raw-margin-top-24">
<a class="btn btn-default pull-left" href="/login">Login</a>
<button class="btn btn-primary pull-right" type="submit">Register</button>
</div>
</form>
</div>
</div>
@stop | {
"content_hash": "4669eac5cab4cac908ec741ce5459f89",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 101,
"avg_line_length": 38.18421052631579,
"alnum_prop": 0.4727773949000689,
"repo_name": "miscbits/kyle",
"id": "63f629229d2de432d357fc95ad3b409b791b3aec",
"size": "1451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/views/auth/register.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "HTML",
"bytes": "50459"
},
{
"name": "JavaScript",
"bytes": "280745"
},
{
"name": "PHP",
"bytes": "189221"
},
{
"name": "Vue",
"bytes": "563"
}
],
"symlink_target": ""
} |
<!-- The box-footer-->
<div id="footer_text"> <!-- The footer_text -->
<strong>Thành công mobile.</strong>
<p>Chuyên mua bán, sửa chữa, cung cấp linh kiện điện thoại. </p>
<p>Video hướng dẫn: <a href="https://www.youtube.com/watch?list=PLml7xFCO5p8rlpbV-9bDdz74cCXQCmeDk&v=YRyzBuA_O4A">Xem video</a></p>
<p>Website: <a href="http://thanhcongmobile.com">thanhcongmobile.com</a></p>
<p>Fanpage: <a href="https://www.facebook.com/ChoDienThoaiViet/">https://www.facebook.com/ChoDienThoaiViet/</a></p>
</div><!-- End footer_text -->
<div id="footer_face"> <!-- The footer_face -->
<a title="trên facebook" target="_blank" href="https://www.facebook.com/ChoDienThoaiViet" rel="nofollow">
<img alt="trên facebook" src="<?php echo public_url()?>site/images/facebook.png">
</a>
<a title="trên twitter" target="_blank" href="https://twitter.com/" rel="nofollow">
<img alt="trên twitter" src="<?php echo public_url()?>site/images/twitter.png">
</a>
<a title="trên google" target="_blank" href="https://plus.google.com/" rel="nofollow">
<img alt="trên google" src="<?php echo public_url()?>site/images/google.png">
</a>
</div>
<!-- End footer_face -->
<div class='clear'></div><!-- clear float -->
<!-- End box-footer --> | {
"content_hash": "7324fd4d46ce4113cb4ee2ec96e80553",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 135,
"avg_line_length": 49.30769230769231,
"alnum_prop": 0.6380655226209049,
"repo_name": "pvtam2a/thanhcongmobile",
"id": "8232795a4aa87bda080b8ad364253cf6c9bf3120",
"size": "1310",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/views/site/footer.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1188"
},
{
"name": "CSS",
"bytes": "299838"
},
{
"name": "HTML",
"bytes": "8756101"
},
{
"name": "JavaScript",
"bytes": "1466786"
},
{
"name": "PHP",
"bytes": "1882388"
}
],
"symlink_target": ""
} |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where
import Import
import System.Random (getStdRandom, randomR, StdGen)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Control.Monad (replicateM)
import Control.Monad.Trans.State
import Data.Time (getCurrentTime)
import Crypto.Hash.SHA512 (hash)
import qualified Data.ByteString as S
import Data.Bits (shiftR, (.&.))
import Yesod.Auth.GoogleEmail2
predictForm :: Form Prediction
predictForm token = do
maid <- fmap entityKey <$> lift maybeAuth
(nameRes, nameView) <- mreq textField "Name"
{ fsAttrs = [("placeholder", "your name"), ("class", "name")]
} Nothing
(contentRes, contentView) <- mreq textareaField "Content" Nothing
(errs, res) <-
case (,) <$> nameRes <*> contentRes of
FormSuccess (name, content) -> do
let go :: State StdGen Text
go = T.pack <$> replicateM 10 goC
goC :: State StdGen Char
goC = state $ randomR ('A', 'Z')
(public, private) <- liftIO
$ getStdRandom
$ runState
$ (,) <$> go <*> go
now <- liftIO getCurrentTime
return ([], FormSuccess $ Prediction name content public private now maid)
FormFailure errs -> return (errs, FormFailure errs)
FormMissing -> return ([], FormMissing)
let widget = [whamlet|
$if not $ null errs
<p>There were some errors with your submission:
<ul>
$forall err <- errs
<li>#{err}
<div .row>
<div .span6 .offset2>
<form method=post>
<p>I, ^{fvInput nameView}, predict that:
<p>
^{fvInput contentView}
<p>
\#{token}
<input .btn type=submit value="Make my prediction">
|]
return (res, widget)
-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getHomeR :: Handler Html
getHomeR = do
muser <- maybeAuth
((result, formWidget), _) <- runFormPost predictForm
case result of
FormSuccess predict -> do
_ <- runDB $ insert predict
setMessage "Your prediction has been made"
redirect $ PrivateR $ predictionPrivate predict
_ -> defaultLayout $ do
setTitle "I predict that..."
$(widgetFile "homepage")
postHomeR :: Handler Html
postHomeR = getHomeR
getPrivateR :: Text -> Handler Html
getPrivateR private = do
Entity _ predict <- runDB $ getBy404 $ UniquePrivate private
defaultLayout $ do
setTitle "Private prediction page"
$(widgetFile "private")
getPublicR :: Text -> Handler Html
getPublicR public = do
Entity _ predict <- runDB $ getBy404 $ UniquePublic public
let Textarea raw = predictionContent predict
let sha512 = decodeUtf8 $ toHex $ hash $ encodeUtf8 raw
defaultLayout $ do
setTitle "Public prediction page"
$(widgetFile "public")
toHex :: S.ByteString -> S.ByteString
toHex bs0 =
fst $ S.unfoldrN (S.length bs0 * 2) go (Left bs0)
where
go (Left bs) =
case S.uncons bs of
Nothing -> Nothing
Just (w, bs') ->
let w1 = w `shiftR` 4
w2 = w .&. 15
c1 = toC w1
c2 = toC w2
in Just (c1, Right (c2, bs'))
go (Right (c, bs)) = Just (c, Left bs)
toC w
| w < 10 = w + 48
| otherwise = w + 87
getMyPredictionsR :: Handler Html
getMyPredictionsR = do
Entity uid _user <- requireAuth
predictions <- map entityVal <$> runDB (selectList [PredictionUser ==. Just uid] [Desc PredictionCreated])
defaultLayout $ do
setTitle "My Predictions"
$(widgetFile "my-predictions")
where
predictionSummary = ellipsis 100 . unTextarea . predictionContent
ellipsis l t
| T.length t > l = T.take (l - 3) t `T.append` "..."
| otherwise = t
| {
"content_hash": "82849b7fe3be778841533bc9d970421e",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 110,
"avg_line_length": 34.73809523809524,
"alnum_prop": 0.590815627141878,
"repo_name": "snoyberg/whosawthatcoming",
"id": "a9eedfce85397bea00a27ad66b1d552c30f673d6",
"size": "4377",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Handler/Home.hs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Haskell",
"bytes": "17259"
},
{
"name": "Shell",
"bytes": "731"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'><head><title>/Library/Ruby/Gems/1.8/gems/ruby-openid-2.0.1/lib/openid/association.rb - C0 code coverage information</title>
<style type='text/css'>body { background-color: rgb(240, 240, 245); }</style>
<style type='text/css'>span.cross-ref-title {
font-size: 140%;
}
span.cross-ref a {
text-decoration: none;
}
span.cross-ref {
background-color:#f3f7fa;
border: 1px dashed #333;
margin: 1em;
padding: 0.5em;
overflow: hidden;
}
a.crossref-toggle {
text-decoration: none;
}
span.marked0 {
background-color: rgb(185, 210, 200);
display: block;
}
span.marked1 {
background-color: rgb(190, 215, 205);
display: block;
}
span.inferred0 {
background-color: rgb(175, 200, 200);
display: block;
}
span.inferred1 {
background-color: rgb(180, 205, 205);
display: block;
}
span.uncovered0 {
background-color: rgb(225, 110, 110);
display: block;
}
span.uncovered1 {
background-color: rgb(235, 120, 120);
display: block;
}
span.overview {
border-bottom: 8px solid black;
}
div.overview {
border-bottom: 8px solid black;
}
body {
font-family: verdana, arial, helvetica;
}
div.footer {
font-size: 68%;
margin-top: 1.5em;
}
h1, h2, h3, h4, h5, h6 {
margin-bottom: 0.5em;
}
h5 {
margin-top: 0.5em;
}
.hidden {
display: none;
}
div.separator {
height: 10px;
}
/* Commented out for better readability, esp. on IE */
/*
table tr td, table tr th {
font-size: 68%;
}
td.value table tr td {
font-size: 11px;
}
*/
table.percent_graph {
height: 12px;
border: #808080 1px solid;
empty-cells: show;
}
table.percent_graph td.covered {
height: 10px;
background: #00f000;
}
table.percent_graph td.uncovered {
height: 10px;
background: #e00000;
}
table.percent_graph td.NA {
height: 10px;
background: #eaeaea;
}
table.report {
border-collapse: collapse;
width: 100%;
}
table.report td.heading {
background: #dcecff;
border: #d0d0d0 1px solid;
font-weight: bold;
text-align: center;
}
table.report td.heading:hover {
background: #c0ffc0;
}
table.report td.text {
border: #d0d0d0 1px solid;
}
table.report td.value,
table.report td.lines_total,
table.report td.lines_code {
text-align: right;
border: #d0d0d0 1px solid;
}
table.report tr.light {
background-color: rgb(240, 240, 245);
}
table.report tr.dark {
background-color: rgb(230, 230, 235);
}
</style>
<script type='text/javascript'>
// <![CDATA[
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make cross-references hidden by default
document.writeln( "<style type=\"text/css\">span.cross-ref { display: none }</style>" )
// ]]>
</script>
<style type='text/css'>span.run0 {
background-color: rgb(178, 204, 255);
display: block;
}
span.run1 {
background-color: rgb(178, 206, 255);
display: block;
}
span.run2 {
background-color: rgb(178, 209, 255);
display: block;
}
span.run3 {
background-color: rgb(178, 211, 255);
display: block;
}
span.run4 {
background-color: rgb(178, 214, 255);
display: block;
}
span.run5 {
background-color: rgb(178, 218, 255);
display: block;
}
span.run6 {
background-color: rgb(178, 220, 255);
display: block;
}
span.run7 {
background-color: rgb(178, 223, 255);
display: block;
}
span.run8 {
background-color: rgb(178, 225, 255);
display: block;
}
span.run9 {
background-color: rgb(178, 228, 255);
display: block;
}
span.run10 {
background-color: rgb(178, 232, 255);
display: block;
}
span.run11 {
background-color: rgb(178, 234, 255);
display: block;
}
span.run12 {
background-color: rgb(178, 237, 255);
display: block;
}
span.run13 {
background-color: rgb(178, 239, 255);
display: block;
}
span.run14 {
background-color: rgb(178, 242, 255);
display: block;
}
span.run15 {
background-color: rgb(178, 246, 255);
display: block;
}
span.run16 {
background-color: rgb(178, 248, 255);
display: block;
}
span.run17 {
background-color: rgb(178, 251, 255);
display: block;
}
span.run18 {
background-color: rgb(178, 253, 255);
display: block;
}
span.run19 {
background-color: rgb(178, 255, 253);
display: block;
}
span.run20 {
background-color: rgb(178, 255, 249);
display: block;
}
span.run21 {
background-color: rgb(178, 255, 247);
display: block;
}
span.run22 {
background-color: rgb(178, 255, 244);
display: block;
}
span.run23 {
background-color: rgb(178, 255, 242);
display: block;
}
span.run24 {
background-color: rgb(178, 255, 239);
display: block;
}
span.run25 {
background-color: rgb(178, 255, 235);
display: block;
}
span.run26 {
background-color: rgb(178, 255, 233);
display: block;
}
span.run27 {
background-color: rgb(178, 255, 230);
display: block;
}
span.run28 {
background-color: rgb(178, 255, 228);
display: block;
}
span.run29 {
background-color: rgb(178, 255, 225);
display: block;
}
span.run30 {
background-color: rgb(178, 255, 221);
display: block;
}
span.run31 {
background-color: rgb(178, 255, 219);
display: block;
}
span.run32 {
background-color: rgb(178, 255, 216);
display: block;
}
span.run33 {
background-color: rgb(178, 255, 214);
display: block;
}
span.run34 {
background-color: rgb(178, 255, 211);
display: block;
}
span.run35 {
background-color: rgb(178, 255, 207);
display: block;
}
span.run36 {
background-color: rgb(178, 255, 205);
display: block;
}
span.run37 {
background-color: rgb(178, 255, 202);
display: block;
}
span.run38 {
background-color: rgb(178, 255, 200);
display: block;
}
span.run39 {
background-color: rgb(178, 255, 197);
display: block;
}
span.run40 {
background-color: rgb(178, 255, 193);
display: block;
}
span.run41 {
background-color: rgb(178, 255, 191);
display: block;
}
span.run42 {
background-color: rgb(178, 255, 188);
display: block;
}
span.run43 {
background-color: rgb(178, 255, 186);
display: block;
}
span.run44 {
background-color: rgb(178, 255, 183);
display: block;
}
span.run45 {
background-color: rgb(178, 255, 179);
display: block;
}
span.run46 {
background-color: rgb(179, 255, 178);
display: block;
}
span.run47 {
background-color: rgb(182, 255, 178);
display: block;
}
span.run48 {
background-color: rgb(184, 255, 178);
display: block;
}
span.run49 {
background-color: rgb(187, 255, 178);
display: block;
}
span.run50 {
background-color: rgb(191, 255, 178);
display: block;
}
span.run51 {
background-color: rgb(193, 255, 178);
display: block;
}
span.run52 {
background-color: rgb(196, 255, 178);
display: block;
}
span.run53 {
background-color: rgb(198, 255, 178);
display: block;
}
span.run54 {
background-color: rgb(201, 255, 178);
display: block;
}
span.run55 {
background-color: rgb(205, 255, 178);
display: block;
}
span.run56 {
background-color: rgb(207, 255, 178);
display: block;
}
span.run57 {
background-color: rgb(210, 255, 178);
display: block;
}
span.run58 {
background-color: rgb(212, 255, 178);
display: block;
}
span.run59 {
background-color: rgb(215, 255, 178);
display: block;
}
span.run60 {
background-color: rgb(219, 255, 178);
display: block;
}
span.run61 {
background-color: rgb(221, 255, 178);
display: block;
}
span.run62 {
background-color: rgb(224, 255, 178);
display: block;
}
span.run63 {
background-color: rgb(226, 255, 178);
display: block;
}
span.run64 {
background-color: rgb(229, 255, 178);
display: block;
}
span.run65 {
background-color: rgb(233, 255, 178);
display: block;
}
span.run66 {
background-color: rgb(235, 255, 178);
display: block;
}
span.run67 {
background-color: rgb(238, 255, 178);
display: block;
}
span.run68 {
background-color: rgb(240, 255, 178);
display: block;
}
span.run69 {
background-color: rgb(243, 255, 178);
display: block;
}
span.run70 {
background-color: rgb(247, 255, 178);
display: block;
}
span.run71 {
background-color: rgb(249, 255, 178);
display: block;
}
span.run72 {
background-color: rgb(252, 255, 178);
display: block;
}
span.run73 {
background-color: rgb(255, 255, 178);
display: block;
}
span.run74 {
background-color: rgb(255, 252, 178);
display: block;
}
span.run75 {
background-color: rgb(255, 248, 178);
display: block;
}
span.run76 {
background-color: rgb(255, 246, 178);
display: block;
}
span.run77 {
background-color: rgb(255, 243, 178);
display: block;
}
span.run78 {
background-color: rgb(255, 240, 178);
display: block;
}
span.run79 {
background-color: rgb(255, 238, 178);
display: block;
}
span.run80 {
background-color: rgb(255, 234, 178);
display: block;
}
span.run81 {
background-color: rgb(255, 232, 178);
display: block;
}
span.run82 {
background-color: rgb(255, 229, 178);
display: block;
}
span.run83 {
background-color: rgb(255, 226, 178);
display: block;
}
span.run84 {
background-color: rgb(255, 224, 178);
display: block;
}
span.run85 {
background-color: rgb(255, 220, 178);
display: block;
}
span.run86 {
background-color: rgb(255, 218, 178);
display: block;
}
span.run87 {
background-color: rgb(255, 215, 178);
display: block;
}
span.run88 {
background-color: rgb(255, 212, 178);
display: block;
}
span.run89 {
background-color: rgb(255, 210, 178);
display: block;
}
span.run90 {
background-color: rgb(255, 206, 178);
display: block;
}
span.run91 {
background-color: rgb(255, 204, 178);
display: block;
}
span.run92 {
background-color: rgb(255, 201, 178);
display: block;
}
span.run93 {
background-color: rgb(255, 198, 178);
display: block;
}
span.run94 {
background-color: rgb(255, 196, 178);
display: block;
}
span.run95 {
background-color: rgb(255, 192, 178);
display: block;
}
span.run96 {
background-color: rgb(255, 189, 178);
display: block;
}
span.run97 {
background-color: rgb(255, 187, 178);
display: block;
}
span.run98 {
background-color: rgb(255, 184, 178);
display: block;
}
span.run99 {
background-color: rgb(255, 182, 178);
display: block;
}
span.run100 {
background-color: rgb(255, 178, 178);
display: block;
}
</style>
</head>
<body><h3>C0 code coverage information</h3>
<p>Generated on Sun Jan 06 23:15:42 -0500 2008 with <a href='http://eigenclass.org/hiki/rcov'>rcov 0.8.1.2</a>
</p>
<hr/>
<pre><span class='marked0'>Code reported as executed by Ruby looks like this...
</span><span class='marked1'>and this: this line is also marked as covered.
</span><span class='inferred0'>Lines considered as run by rcov, but not reported by Ruby, look like this,
</span><span class='inferred1'>and this: these lines were inferred by rcov (using simple heuristics).
</span><span class='uncovered0'>Finally, here's a line marked as not executed.
</span></pre>
<table class='report'><thead><tr><td class='heading'>Name</td>
<td class='heading'>Total lines</td>
<td class='heading'>Lines of code</td>
<td class='heading'>Total coverage</td>
<td class='heading'>Code coverage</td>
</tr>
</thead>
<tbody><tr class='light'><td><a href='-Library-Ruby-Gems-1_8-gems-ruby-openid-2_0_1-lib-openid-association_rb.html'>/Library/Ruby/Gems/1.8/gems/ruby-openid-2.0.1/lib/openid/association.rb</a>
</td>
<td class='lines_total'><tt>249</tt>
</td>
<td class='lines_code'><tt>197</tt>
</td>
<td><table cellspacing='0' cellpadding='0' align='right'><tr><td><tt class='coverage_total'>37.8%</tt>
</td>
<td><table cellspacing='0' class='percent_graph' cellpadding='0' width='100'><tr><td class='covered' width='38'/>
<td class='uncovered' width='62'/>
</tr>
</table>
</td>
</tr>
</table>
</td>
<td><table cellspacing='0' cellpadding='0' align='right'><tr><td><tt class='coverage_code'>27.9%</tt>
</td>
<td><table cellspacing='0' class='percent_graph' cellpadding='0' width='100'><tr><td class='covered' width='28'/>
<td class='uncovered' width='72'/>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
<pre><span class="marked1"><a name="line1"></a> 1 require "openid/kvform"
</span><span class="marked0"><a name="line2"></a> 2 require "openid/util"
</span><span class="marked1"><a name="line3"></a> 3 require "openid/cryptutil"
</span><span class="marked0"><a name="line4"></a> 4 require "openid/message"
</span><span class="inferred1"><a name="line5"></a> 5
</span><span class="marked0"><a name="line6"></a> 6 module OpenID
</span><span class="inferred1"><a name="line7"></a> 7
</span><span class="marked0"><a name="line8"></a> 8 def self.get_secret_size(assoc_type)
</span><span class="uncovered1"><a name="line9"></a> 9 if assoc_type == 'HMAC-SHA1'
</span><span class="uncovered0"><a name="line10"></a> 10 return 20
</span><span class="uncovered1"><a name="line11"></a> 11 elsif assoc_type == 'HMAC-SHA256'
</span><span class="uncovered0"><a name="line12"></a> 12 return 32
</span><span class="uncovered1"><a name="line13"></a> 13 else
</span><span class="uncovered0"><a name="line14"></a> 14 raise ArgumentError("Unsupported association type: #{assoc_type}")
</span><span class="uncovered1"><a name="line15"></a> 15 end
</span><span class="uncovered0"><a name="line16"></a> 16 end
</span><span class="inferred1"><a name="line17"></a> 17
</span><span class="inferred0"><a name="line18"></a> 18 # An Association holds the shared secret between a relying party and
</span><span class="inferred1"><a name="line19"></a> 19 # an OpenID provider.
</span><span class="marked0"><a name="line20"></a> 20 class Association
</span><span class="marked1"><a name="line21"></a> 21 attr_reader :handle, :secret, :issued, :lifetime, :assoc_type
</span><span class="inferred0"><a name="line22"></a> 22
</span><span class="marked1"><a name="line23"></a> 23 FIELD_ORDER =
</span><span class="inferred0"><a name="line24"></a> 24 [:version, :handle, :secret, :issued, :lifetime, :assoc_type,]
</span><span class="inferred1"><a name="line25"></a> 25
</span><span class="inferred0"><a name="line26"></a> 26 # Load a serialized Association
</span><span class="marked1"><a name="line27"></a> 27 def self.deserialize(serialized)
</span><span class="uncovered0"><a name="line28"></a> 28 parsed = Util.kv_to_seq(serialized)
</span><span class="uncovered1"><a name="line29"></a> 29 parsed_fields = parsed.map{|k, v| k.to_sym}
</span><span class="uncovered0"><a name="line30"></a> 30 if parsed_fields != FIELD_ORDER
</span><span class="uncovered1"><a name="line31"></a> 31 raise StandardError, 'Unexpected fields in serialized association'\
</span><span class="uncovered0"><a name="line32"></a> 32 " (Expected #{FIELD_ORDER.inspect}, got #{parsed_fields.inspect})"
</span><span class="uncovered1"><a name="line33"></a> 33 end
</span><span class="uncovered0"><a name="line34"></a> 34 version, handle, secret64, issued_s, lifetime_s, assoc_type =
</span><span class="uncovered1"><a name="line35"></a> 35 parsed.map {|field, value| value}
</span><span class="uncovered0"><a name="line36"></a> 36 if version != '2'
</span><span class="uncovered1"><a name="line37"></a> 37 raise StandardError, "Attempted to deserialize unsupported version "\
</span><span class="uncovered0"><a name="line38"></a> 38 "(#{parsed[0][1].inspect})"
</span><span class="uncovered1"><a name="line39"></a> 39 end
</span><span class="uncovered0"><a name="line40"></a> 40
</span><span class="uncovered1"><a name="line41"></a> 41 self.new(handle,
</span><span class="uncovered0"><a name="line42"></a> 42 Util.from_base64(secret64),
</span><span class="uncovered1"><a name="line43"></a> 43 Time.at(issued_s.to_i),
</span><span class="uncovered0"><a name="line44"></a> 44 lifetime_s.to_i,
</span><span class="uncovered1"><a name="line45"></a> 45 assoc_type)
</span><span class="uncovered0"><a name="line46"></a> 46 end
</span><span class="inferred1"><a name="line47"></a> 47
</span><span class="inferred0"><a name="line48"></a> 48 # Create an Association with an issued time of now
</span><span class="marked1"><a name="line49"></a> 49 def self.from_expires_in(expires_in, handle, secret, assoc_type)
</span><span class="uncovered0"><a name="line50"></a> 50 issued = Time.now
</span><span class="uncovered1"><a name="line51"></a> 51 self.new(handle, secret, issued, expires_in, assoc_type)
</span><span class="uncovered0"><a name="line52"></a> 52 end
</span><span class="inferred1"><a name="line53"></a> 53
</span><span class="marked0"><a name="line54"></a> 54 def initialize(handle, secret, issued, lifetime, assoc_type)
</span><span class="uncovered1"><a name="line55"></a> 55 @handle = handle
</span><span class="uncovered0"><a name="line56"></a> 56 @secret = secret
</span><span class="uncovered1"><a name="line57"></a> 57 @issued = issued
</span><span class="uncovered0"><a name="line58"></a> 58 @lifetime = lifetime
</span><span class="uncovered1"><a name="line59"></a> 59 @assoc_type = assoc_type
</span><span class="uncovered0"><a name="line60"></a> 60 end
</span><span class="inferred1"><a name="line61"></a> 61
</span><span class="inferred0"><a name="line62"></a> 62 # Serialize the association to a form that's consistent across
</span><span class="inferred1"><a name="line63"></a> 63 # JanRain OpenID libraries.
</span><span class="marked0"><a name="line64"></a> 64 def serialize
</span><span class="uncovered1"><a name="line65"></a> 65 data = {
</span><span class="uncovered0"><a name="line66"></a> 66 :version => '2',
</span><span class="uncovered1"><a name="line67"></a> 67 :handle => handle,
</span><span class="uncovered0"><a name="line68"></a> 68 :secret => Util.to_base64(secret),
</span><span class="uncovered1"><a name="line69"></a> 69 :issued => issued.to_i.to_s,
</span><span class="uncovered0"><a name="line70"></a> 70 :lifetime => lifetime.to_i.to_s,
</span><span class="uncovered1"><a name="line71"></a> 71 :assoc_type => assoc_type,
</span><span class="uncovered0"><a name="line72"></a> 72 }
</span><span class="uncovered1"><a name="line73"></a> 73
</span><span class="uncovered0"><a name="line74"></a> 74 Util.assert(data.length == FIELD_ORDER.length)
</span><span class="uncovered1"><a name="line75"></a> 75
</span><span class="uncovered0"><a name="line76"></a> 76 pairs = FIELD_ORDER.map{|field| [field.to_s, data[field]]}
</span><span class="uncovered1"><a name="line77"></a> 77 return Util.seq_to_kv(pairs, strict=true)
</span><span class="uncovered0"><a name="line78"></a> 78 end
</span><span class="inferred1"><a name="line79"></a> 79
</span><span class="inferred0"><a name="line80"></a> 80 # The number of seconds until this association expires
</span><span class="marked1"><a name="line81"></a> 81 def expires_in(now=nil)
</span><span class="uncovered0"><a name="line82"></a> 82 if now.nil?
</span><span class="uncovered1"><a name="line83"></a> 83 now = Time.now.to_i
</span><span class="uncovered0"><a name="line84"></a> 84 else
</span><span class="uncovered1"><a name="line85"></a> 85 now = now.to_i
</span><span class="uncovered0"><a name="line86"></a> 86 end
</span><span class="uncovered1"><a name="line87"></a> 87 time_diff = (issued.to_i + lifetime) - now
</span><span class="uncovered0"><a name="line88"></a> 88 if time_diff < 0
</span><span class="uncovered1"><a name="line89"></a> 89 return 0
</span><span class="uncovered0"><a name="line90"></a> 90 else
</span><span class="uncovered1"><a name="line91"></a> 91 return time_diff
</span><span class="uncovered0"><a name="line92"></a> 92 end
</span><span class="uncovered1"><a name="line93"></a> 93 end
</span><span class="inferred0"><a name="line94"></a> 94
</span><span class="inferred1"><a name="line95"></a> 95 # Generate a signature for a sequence of [key, value] pairs
</span><span class="marked0"><a name="line96"></a> 96 def sign(pairs)
</span><span class="uncovered1"><a name="line97"></a> 97 kv = Util.seq_to_kv(pairs)
</span><span class="uncovered0"><a name="line98"></a> 98 case assoc_type
</span><span class="uncovered1"><a name="line99"></a> 99 when 'HMAC-SHA1'
</span><span class="uncovered0"><a name="line100"></a>100 CryptUtil.hmac_sha1(@secret, kv)
</span><span class="uncovered1"><a name="line101"></a>101 when 'HMAC-SHA256'
</span><span class="uncovered0"><a name="line102"></a>102 CryptUtil.hmac_sha256(@secret, kv)
</span><span class="uncovered1"><a name="line103"></a>103 else
</span><span class="uncovered0"><a name="line104"></a>104 raise StandardError, "Association has unknown type: "\
</span><span class="uncovered1"><a name="line105"></a>105 "#{assoc_type.inspect}"
</span><span class="uncovered0"><a name="line106"></a>106 end
</span><span class="uncovered1"><a name="line107"></a>107 end
</span><span class="inferred0"><a name="line108"></a>108
</span><span class="inferred1"><a name="line109"></a>109 # Generate the list of pairs that form the signed elements of the
</span><span class="inferred0"><a name="line110"></a>110 # given message
</span><span class="marked1"><a name="line111"></a>111 def make_pairs(message)
</span><span class="uncovered0"><a name="line112"></a>112 signed = message.get_arg(OPENID_NS, 'signed')
</span><span class="uncovered1"><a name="line113"></a>113 if signed.nil?
</span><span class="uncovered0"><a name="line114"></a>114 raise StandardError, 'Missing signed list'
</span><span class="uncovered1"><a name="line115"></a>115 end
</span><span class="uncovered0"><a name="line116"></a>116 signed_fields = signed.split(',', -1)
</span><span class="uncovered1"><a name="line117"></a>117 data = message.to_post_args
</span><span class="uncovered0"><a name="line118"></a>118 signed_fields.map {|field| [field, data.fetch('openid.'+field,'')] }
</span><span class="uncovered1"><a name="line119"></a>119 end
</span><span class="inferred0"><a name="line120"></a>120
</span><span class="inferred1"><a name="line121"></a>121 # Return whether the message's signature passes
</span><span class="marked0"><a name="line122"></a>122 def check_message_signature(message)
</span><span class="uncovered1"><a name="line123"></a>123 message_sig = message.get_arg(OPENID_NS, 'sig')
</span><span class="uncovered0"><a name="line124"></a>124 if message_sig.nil?
</span><span class="uncovered1"><a name="line125"></a>125 raise StandardError, "#{message} has no sig."
</span><span class="uncovered0"><a name="line126"></a>126 end
</span><span class="uncovered1"><a name="line127"></a>127 calculated_sig = get_message_signature(message)
</span><span class="uncovered0"><a name="line128"></a>128 return calculated_sig == message_sig
</span><span class="uncovered1"><a name="line129"></a>129 end
</span><span class="inferred0"><a name="line130"></a>130
</span><span class="inferred1"><a name="line131"></a>131 # Get the signature for this message
</span><span class="marked0"><a name="line132"></a>132 def get_message_signature(message)
</span><span class="uncovered1"><a name="line133"></a>133 Util.to_base64(sign(make_pairs(message)))
</span><span class="uncovered0"><a name="line134"></a>134 end
</span><span class="inferred1"><a name="line135"></a>135
</span><span class="marked0"><a name="line136"></a>136 def ==(other)
</span><span class="uncovered1"><a name="line137"></a>137 (other.class == self.class and
</span><span class="uncovered0"><a name="line138"></a>138 other.handle == self.handle and
</span><span class="uncovered1"><a name="line139"></a>139 other.secret == self.secret and
</span><span class="uncovered0"><a name="line140"></a>140
</span><span class="uncovered1"><a name="line141"></a>141 # The internals of the time objects seemed to differ
</span><span class="uncovered0"><a name="line142"></a>142 # in an opaque way when serializing/unserializing.
</span><span class="uncovered1"><a name="line143"></a>143 # I don't think this will be a problem.
</span><span class="uncovered0"><a name="line144"></a>144 other.issued.to_i == self.issued.to_i and
</span><span class="uncovered1"><a name="line145"></a>145
</span><span class="uncovered0"><a name="line146"></a>146 other.lifetime == self.lifetime and
</span><span class="uncovered1"><a name="line147"></a>147 other.assoc_type == self.assoc_type)
</span><span class="uncovered0"><a name="line148"></a>148 end
</span><span class="inferred1"><a name="line149"></a>149
</span><span class="inferred0"><a name="line150"></a>150 # Add a signature (and a signed list) to a message.
</span><span class="marked1"><a name="line151"></a>151 def sign_message(message)
</span><span class="uncovered0"><a name="line152"></a>152 if (message.has_key?(OPENID_NS, 'sig') or
</span><span class="uncovered1"><a name="line153"></a>153 message.has_key?(OPENID_NS, 'signed'))
</span><span class="uncovered0"><a name="line154"></a>154 raise ArgumentError, 'Message already has signed list or signature'
</span><span class="uncovered1"><a name="line155"></a>155 end
</span><span class="uncovered0"><a name="line156"></a>156
</span><span class="uncovered1"><a name="line157"></a>157 extant_handle = message.get_arg(OPENID_NS, 'assoc_handle')
</span><span class="uncovered0"><a name="line158"></a>158 if extant_handle and extant_handle != self.handle
</span><span class="uncovered1"><a name="line159"></a>159 raise ArgumentError, "Message has a different association handle"
</span><span class="uncovered0"><a name="line160"></a>160 end
</span><span class="uncovered1"><a name="line161"></a>161
</span><span class="uncovered0"><a name="line162"></a>162 signed_message = message.copy()
</span><span class="uncovered1"><a name="line163"></a>163 signed_message.set_arg(OPENID_NS, 'assoc_handle', self.handle)
</span><span class="uncovered0"><a name="line164"></a>164 message_keys = signed_message.to_post_args.keys()
</span><span class="uncovered1"><a name="line165"></a>165
</span><span class="uncovered0"><a name="line166"></a>166 signed_list = []
</span><span class="uncovered1"><a name="line167"></a>167 message_keys.each { |k|
</span><span class="uncovered0"><a name="line168"></a>168 if k.starts_with?('openid.')
</span><span class="uncovered1"><a name="line169"></a>169 signed_list << k[7..-1]
</span><span class="uncovered0"><a name="line170"></a>170 end
</span><span class="uncovered1"><a name="line171"></a>171 }
</span><span class="uncovered0"><a name="line172"></a>172
</span><span class="uncovered1"><a name="line173"></a>173 signed_list << 'signed'
</span><span class="uncovered0"><a name="line174"></a>174 signed_list.sort!
</span><span class="uncovered1"><a name="line175"></a>175
</span><span class="uncovered0"><a name="line176"></a>176 signed_message.set_arg(OPENID_NS, 'signed', signed_list.join(','))
</span><span class="uncovered1"><a name="line177"></a>177 sig = get_message_signature(signed_message)
</span><span class="uncovered0"><a name="line178"></a>178 signed_message.set_arg(OPENID_NS, 'sig', sig)
</span><span class="uncovered1"><a name="line179"></a>179 return signed_message
</span><span class="uncovered0"><a name="line180"></a>180 end
</span><span class="uncovered1"><a name="line181"></a>181 end
</span><span class="inferred0"><a name="line182"></a>182
</span><span class="marked1"><a name="line183"></a>183 class AssociationNegotiator
</span><span class="marked0"><a name="line184"></a>184 attr_reader :allowed_types
</span><span class="inferred1"><a name="line185"></a>185
</span><span class="marked0"><a name="line186"></a>186 def self.get_session_types(assoc_type)
</span><span class="marked1"><a name="line187"></a>187 case assoc_type
</span><span class="marked0"><a name="line188"></a>188 when 'HMAC-SHA1'
</span><span class="marked1"><a name="line189"></a>189 ['DH-SHA1', 'no-encryption']
</span><span class="marked0"><a name="line190"></a>190 when 'HMAC-SHA256'
</span><span class="marked1"><a name="line191"></a>191 ['DH-SHA256', 'no-encryption']
</span><span class="uncovered0"><a name="line192"></a>192 else
</span><span class="uncovered1"><a name="line193"></a>193 raise StandardError, "Unknown association type #{assoc_type.inspect}"
</span><span class="uncovered0"><a name="line194"></a>194 end
</span><span class="marked1"><a name="line195"></a>195 end
</span><span class="inferred0"><a name="line196"></a>196
</span><span class="marked1"><a name="line197"></a>197 def self.check_session_type(assoc_type, session_type)
</span><span class="marked0"><a name="line198"></a>198 if !get_session_types(assoc_type).include?(session_type)
</span><span class="uncovered1"><a name="line199"></a>199 raise StandardError, "Session type #{session_type.inspect} not "\
</span><span class="uncovered0"><a name="line200"></a>200 "valid for association type #{assoc_type.inspect}"
</span><span class="uncovered1"><a name="line201"></a>201 end
</span><span class="marked0"><a name="line202"></a>202 end
</span><span class="inferred1"><a name="line203"></a>203
</span><span class="marked0"><a name="line204"></a>204 def initialize(allowed_types)
</span><span class="marked1"><a name="line205"></a>205 self.allowed_types=(allowed_types)
</span><span class="marked0"><a name="line206"></a>206 end
</span><span class="inferred1"><a name="line207"></a>207
</span><span class="marked0"><a name="line208"></a>208 def copy
</span><span class="uncovered1"><a name="line209"></a>209 Marshal.load(Marshal.dump(self))
</span><span class="uncovered0"><a name="line210"></a>210 end
</span><span class="inferred1"><a name="line211"></a>211
</span><span class="marked0"><a name="line212"></a>212 def allowed_types=(allowed_types)
</span><span class="marked1"><a name="line213"></a>213 allowed_types.each do |assoc_type, session_type|
</span><span class="marked0"><a name="line214"></a>214 self.class.check_session_type(assoc_type, session_type)
</span><span class="inferred1"><a name="line215"></a>215 end
</span><span class="marked0"><a name="line216"></a>216 @allowed_types = allowed_types
</span><span class="inferred1"><a name="line217"></a>217 end
</span><span class="inferred0"><a name="line218"></a>218
</span><span class="marked1"><a name="line219"></a>219 def add_allowed_type(assoc_type, session_type=nil)
</span><span class="uncovered0"><a name="line220"></a>220 if session_type.nil?
</span><span class="uncovered1"><a name="line221"></a>221 session_types = self.class.get_session_types(assoc_type)
</span><span class="uncovered0"><a name="line222"></a>222 else
</span><span class="uncovered1"><a name="line223"></a>223 self.class.check_session_type(assoc_type, session_type)
</span><span class="uncovered0"><a name="line224"></a>224 session_types = [session_type]
</span><span class="uncovered1"><a name="line225"></a>225 end
</span><span class="uncovered0"><a name="line226"></a>226 session_types.each do |session_type|
</span><span class="uncovered1"><a name="line227"></a>227 @allowed_types << [assoc_type, session_type]
</span><span class="uncovered0"><a name="line228"></a>228 end
</span><span class="uncovered1"><a name="line229"></a>229 end
</span><span class="inferred0"><a name="line230"></a>230
</span><span class="marked1"><a name="line231"></a>231 def allowed?(assoc_type, session_type)
</span><span class="uncovered0"><a name="line232"></a>232 @allowed_types.include?([assoc_type, session_type])
</span><span class="uncovered1"><a name="line233"></a>233 end
</span><span class="inferred0"><a name="line234"></a>234
</span><span class="marked1"><a name="line235"></a>235 def get_allowed_type
</span><span class="uncovered0"><a name="line236"></a>236 @allowed_types.empty? ? nil : @allowed_types[0]
</span><span class="uncovered1"><a name="line237"></a>237 end
</span><span class="uncovered0"><a name="line238"></a>238 end
</span><span class="inferred1"><a name="line239"></a>239
</span><span class="marked0"><a name="line240"></a>240 DefaultNegotiator =
</span><span class="marked1"><a name="line241"></a>241 AssociationNegotiator.new([['HMAC-SHA1', 'DH-SHA1'],
</span><span class="inferred0"><a name="line242"></a>242 ['HMAC-SHA1', 'no-encryption'],
</span><span class="inferred1"><a name="line243"></a>243 ['HMAC-SHA256', 'DH-SHA256'],
</span><span class="inferred0"><a name="line244"></a>244 ['HMAC-SHA256', 'no-encryption']])
</span><span class="inferred1"><a name="line245"></a>245
</span><span class="marked0"><a name="line246"></a>246 EncryptedNegotiator =
</span><span class="marked1"><a name="line247"></a>247 AssociationNegotiator.new([['HMAC-SHA1', 'DH-SHA1'],
</span><span class="inferred0"><a name="line248"></a>248 ['HMAC-SHA256', 'DH-SHA256']])
</span><span class="inferred1"><a name="line249"></a>249 end
</span></pre><hr/>
<p>Generated using the <a href='http://eigenclass.org/hiki.rb?rcov'>rcov code coverage analysis tool for Ruby</a>
version 0.8.1.2.</p>
<p><a href='http://validator.w3.org/check/referer'><img src='http://www.w3.org/Icons/valid-xhtml10' height='31' alt='Valid XHTML 1.0!' width='88'/>
</a>
<a href='http://jigsaw.w3.org/css-validator/check/referer'><img src='http://jigsaw.w3.org/css-validator/images/vcss' alt='Valid CSS!' style='border:0;width:88px;height:31px'/>
</a>
</p>
</body>
</html>
| {
"content_hash": "93fa4c12c4945fb81b62d3a6c1242fee",
"timestamp": "",
"source": "github",
"line_count": 859,
"max_line_length": 193,
"avg_line_length": 40.809080325960416,
"alnum_prop": 0.6423905291684496,
"repo_name": "jared/ygo_classic",
"id": "ccf83f9c8781353247c4f328962fde0487685183",
"size": "35055",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "coverage/-Library-Ruby-Gems-1_8-gems-ruby-openid-2_0_1-lib-openid-association_rb.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "319705"
},
{
"name": "Ruby",
"bytes": "82138"
}
],
"symlink_target": ""
} |
Some snippets for working with the [Meteor](http://meteor.com) framework (v1.0).
Includes snippets for
* CoffeeScript (✔)
* HTML (✔)
* JavaScript (✔) - Updated to 1.0
## Installation
You can install them now via [Package Control](http://wbond.net/sublime_packages/package_control) (search for "Meteor Snippets") or manually via git:
##### OS X
```
git clone git://github.com/mrtnbroder/meteor-snippets.git ~/Library/Application Support/Sublime Text 2/Packages/Meteor Snippets
```
##### Linux
```
git clone git://github.com/mrtnbroder/meteor-snippets.git ~/.config/sublime-text-2/Packages/Meteor Snippets
```
##### Windows
```
git clone git://github.com/mrtnbroder/meteor-snippets.git %userprofile%\AppData\Roaming\Sublime Text 2\Packages\Meteor Snippets
```
## Examples
__tp__
```html
<template name='main'>
...
</template>
```
__Meteor.render__
```javascript
Meteor.render(function () {
...
});
```
__Meteor.publish__
```javascript
Meteor.publish('name', function () {
...
});
```
__if__
```handlebars
{{#if guyIs 'male'}}
...
{{/if}}
```
__ea__
```handlebars
{{#each player}}
...
{{/each}}
```
... and a whole lot more!
## Todo's
* remap some tab triggers
* fix some snippets (missing semicolons, whitespace, tab behaviour etc.)
## Contributing
Got some neat Meteor snippets you want to share?
fork this repro and send me a pull request!
| {
"content_hash": "24e50fcba1c7b35194e68b5a1e2325bd",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 149,
"avg_line_length": 18.24,
"alnum_prop": 0.6732456140350878,
"repo_name": "anisku11/sublimeku",
"id": "2e4c6f310866763545722eae74a74c61a7313fd6",
"size": "1414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Packages/Meteor Snippets/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17282"
},
{
"name": "Go",
"bytes": "5456"
},
{
"name": "HTML",
"bytes": "4990"
},
{
"name": "JavaScript",
"bytes": "1714"
},
{
"name": "PHP",
"bytes": "43942"
},
{
"name": "Python",
"bytes": "9058676"
},
{
"name": "Shell",
"bytes": "95"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/Users/tonychiang/CloudPrint4AndroidManager/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-h720dp/values-h720dp.xml -->
<eat-comment/>
<dimen name="abc_alert_dialog_button_bar_height">54dip</dimen>
</resources> | {
"content_hash": "1fdd81b944701471f09608ce1601968c",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 180,
"avg_line_length": 55,
"alnum_prop": 0.7333333333333333,
"repo_name": "TonyChiangUSA/UPrint-Orange",
"id": "acdc7bcb53c8ea9e143290ea3fbec8252121da1b",
"size": "330",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/build/intermediates/res/debug/values-h720dp/values-h720dp.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "903557"
}
],
"symlink_target": ""
} |
/*************************************************************************/
/* code_edit.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#ifndef CODE_EDIT_H
#define CODE_EDIT_H
#include "scene/gui/text_edit.h"
class CodeEdit : public TextEdit {
GDCLASS(CodeEdit, TextEdit)
public:
/* Keep enum in sync with: */
/* /core/object/script_language.h - ScriptLanguage::CodeCompletionKind */
enum CodeCompletionKind {
KIND_CLASS,
KIND_FUNCTION,
KIND_SIGNAL,
KIND_VARIABLE,
KIND_MEMBER,
KIND_ENUM,
KIND_CONSTANT,
KIND_NODE_PATH,
KIND_FILE_PATH,
KIND_PLAIN_TEXT,
};
private:
/* Indent management */
int indent_size = 4;
String indent_text = "\t";
bool auto_indent = false;
HashSet<char32_t> auto_indent_prefixes;
bool indent_using_spaces = false;
int _calculate_spaces_till_next_left_indent(int p_column) const;
int _calculate_spaces_till_next_right_indent(int p_column) const;
void _new_line(bool p_split_current_line = true, bool p_above = false);
/* Auto brace completion */
bool auto_brace_completion_enabled = false;
/* BracePair open_key must be uniquie and ordered by length. */
struct BracePair {
String open_key = "";
String close_key = "";
};
Vector<BracePair> auto_brace_completion_pairs;
int _get_auto_brace_pair_open_at_pos(int p_line, int p_col);
int _get_auto_brace_pair_close_at_pos(int p_line, int p_col);
/* Main Gutter */
enum MainGutterType {
MAIN_GUTTER_BREAKPOINT = 0x01,
MAIN_GUTTER_BOOKMARK = 0x02,
MAIN_GUTTER_EXECUTING = 0x04
};
int main_gutter = -1;
void _update_draw_main_gutter();
void _main_gutter_draw_callback(int p_line, int p_gutter, const Rect2 &p_region);
// breakpoints
HashMap<int, bool> breakpointed_lines;
bool draw_breakpoints = false;
Color breakpoint_color = Color(1, 1, 1);
Ref<Texture2D> breakpoint_icon = Ref<Texture2D>();
// bookmarks
bool draw_bookmarks = false;
Color bookmark_color = Color(1, 1, 1);
Ref<Texture2D> bookmark_icon = Ref<Texture2D>();
// executing lines
bool draw_executing_lines = false;
Color executing_line_color = Color(1, 1, 1);
Ref<Texture2D> executing_line_icon = Ref<Texture2D>();
/* Line numbers */
int line_number_gutter = -1;
int line_number_digits = 0;
String line_number_padding = " ";
Color line_number_color = Color(1, 1, 1);
void _line_number_draw_callback(int p_line, int p_gutter, const Rect2 &p_region);
/* Fold Gutter */
int fold_gutter = -1;
bool draw_fold_gutter = false;
Color folding_color = Color(1, 1, 1);
Ref<Texture2D> can_fold_icon = Ref<Texture2D>();
Ref<Texture2D> folded_icon = Ref<Texture2D>();
void _fold_gutter_draw_callback(int p_line, int p_gutter, Rect2 p_region);
void _gutter_clicked(int p_line, int p_gutter);
void _update_gutter_indexes();
/* Line Folding */
bool line_folding_enabled = false;
/* Delimiters */
enum DelimiterType {
TYPE_STRING,
TYPE_COMMENT,
};
struct Delimiter {
DelimiterType type;
String start_key = "";
String end_key = "";
bool line_only = true;
};
bool setting_delimiters = false;
Vector<Delimiter> delimiters;
/*
* Vector entry per line, contains a Map of column numbers to delimiter index, -1 marks the end of a region.
* e.g the following text will be stored as so:
*
* 0: nothing here
* 1:
* 2: # test
* 3: "test" text "multiline
* 4:
* 5: test
* 6: string"
*
* Vector [
* 0 = []
* 1 = []
* 2 = [
* 1 = 1
* 6 = -1
* ]
* 3 = [
* 1 = 0
* 6 = -1
* 13 = 0
* ]
* 4 = [
* 0 = 0
* ]
* 5 = [
* 5 = 0
* ]
* 6 = [
* 7 = -1
* ]
* ]
*/
Vector<RBMap<int, int>> delimiter_cache;
void _update_delimiter_cache(int p_from_line = 0, int p_to_line = -1);
int _is_in_delimiter(int p_line, int p_column, DelimiterType p_type) const;
void _add_delimiter(const String &p_start_key, const String &p_end_key, bool p_line_only, DelimiterType p_type);
void _remove_delimiter(const String &p_start_key, DelimiterType p_type);
bool _has_delimiter(const String &p_start_key, DelimiterType p_type) const;
void _set_delimiters(const TypedArray<String> &p_delimiters, DelimiterType p_type);
void _clear_delimiters(DelimiterType p_type);
TypedArray<String> _get_delimiters(DelimiterType p_type) const;
/* Code Hint */
String code_hint = "";
bool code_hint_draw_below = true;
int code_hint_xpos = -0xFFFF;
/* Code Completion */
bool code_completion_enabled = false;
bool code_completion_forced = false;
int code_completion_max_width = 0;
int code_completion_max_lines = 7;
int code_completion_scroll_width = 0;
Color code_completion_scroll_color = Color(0, 0, 0, 0);
Color code_completion_scroll_hovered_color = Color(0, 0, 0, 0);
Color code_completion_background_color = Color(0, 0, 0, 0);
Color code_completion_selected_color = Color(0, 0, 0, 0);
Color code_completion_existing_color = Color(0, 0, 0, 0);
bool code_completion_active = false;
bool is_code_completion_scroll_hovered = false;
bool is_code_completion_scroll_pressed = false;
Vector<ScriptLanguage::CodeCompletionOption> code_completion_options;
int code_completion_line_ofs = 0;
int code_completion_current_selected = 0;
int code_completion_longest_line = 0;
Rect2i code_completion_rect;
Rect2i code_completion_scroll_rect;
HashSet<char32_t> code_completion_prefixes;
List<ScriptLanguage::CodeCompletionOption> code_completion_option_submitted;
List<ScriptLanguage::CodeCompletionOption> code_completion_option_sources;
String code_completion_base;
void _update_scroll_selected_line(float p_mouse_y);
void _filter_code_completion_candidates_impl();
/* Line length guidelines */
TypedArray<int> line_length_guideline_columns;
Color line_length_guideline_color;
/* Symbol lookup */
bool symbol_lookup_on_click_enabled = false;
String symbol_lookup_new_word = "";
String symbol_lookup_word = "";
/* Visual */
Ref<StyleBox> style_normal;
Ref<Font> font;
int font_size = 16;
int line_spacing = 1;
/* Callbacks */
int lines_edited_changed = 0;
int lines_edited_from = -1;
int lines_edited_to = -1;
void _lines_edited_from(int p_from_line, int p_to_line);
void _text_set();
void _text_changed();
protected:
void _notification(int p_what);
static void _bind_methods();
/* Text manipulation */
// Overridable actions
virtual void _handle_unicode_input_internal(const uint32_t p_unicode, int p_caret) override;
virtual void _backspace_internal(int p_caret) override;
GDVIRTUAL1(_confirm_code_completion, bool)
GDVIRTUAL1(_request_code_completion, bool)
GDVIRTUAL1RC(TypedArray<Dictionary>, _filter_code_completion_candidates, TypedArray<Dictionary>)
public:
/* General overrides */
virtual void gui_input(const Ref<InputEvent> &p_gui_input) override;
virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const override;
/* Indent management */
void set_indent_size(const int p_size);
int get_indent_size() const;
void set_indent_using_spaces(const bool p_use_spaces);
bool is_indent_using_spaces() const;
void set_auto_indent_enabled(bool p_enabled);
bool is_auto_indent_enabled() const;
void set_auto_indent_prefixes(const TypedArray<String> &p_prefixes);
TypedArray<String> get_auto_indent_prefixes() const;
void do_indent();
void do_unindent();
void indent_lines();
void unindent_lines();
/* Auto brace completion */
void set_auto_brace_completion_enabled(bool p_enabled);
bool is_auto_brace_completion_enabled() const;
void set_highlight_matching_braces_enabled(bool p_enabled);
bool is_highlight_matching_braces_enabled() const;
void add_auto_brace_completion_pair(const String &p_open_key, const String &p_close_key);
void set_auto_brace_completion_pairs(const Dictionary &p_auto_brace_completion_pairs);
Dictionary get_auto_brace_completion_pairs() const;
bool has_auto_brace_completion_open_key(const String &p_open_key) const;
bool has_auto_brace_completion_close_key(const String &p_close_key) const;
String get_auto_brace_completion_close_key(const String &p_open_key) const;
/* Main Gutter */
void set_draw_breakpoints_gutter(bool p_draw);
bool is_drawing_breakpoints_gutter() const;
void set_draw_bookmarks_gutter(bool p_draw);
bool is_drawing_bookmarks_gutter() const;
void set_draw_executing_lines_gutter(bool p_draw);
bool is_drawing_executing_lines_gutter() const;
// breakpoints
void set_line_as_breakpoint(int p_line, bool p_breakpointed);
bool is_line_breakpointed(int p_line) const;
void clear_breakpointed_lines();
PackedInt32Array get_breakpointed_lines() const;
// bookmarks
void set_line_as_bookmarked(int p_line, bool p_bookmarked);
bool is_line_bookmarked(int p_line) const;
void clear_bookmarked_lines();
PackedInt32Array get_bookmarked_lines() const;
// executing lines
void set_line_as_executing(int p_line, bool p_executing);
bool is_line_executing(int p_line) const;
void clear_executing_lines();
PackedInt32Array get_executing_lines() const;
/* Line numbers */
void set_draw_line_numbers(bool p_draw);
bool is_draw_line_numbers_enabled() const;
void set_line_numbers_zero_padded(bool p_zero_padded);
bool is_line_numbers_zero_padded() const;
/* Fold gutter */
void set_draw_fold_gutter(bool p_draw);
bool is_drawing_fold_gutter() const;
/* Line Folding */
void set_line_folding_enabled(bool p_enabled);
bool is_line_folding_enabled() const;
bool can_fold_line(int p_line) const;
void fold_line(int p_line);
void unfold_line(int p_line);
void fold_all_lines();
void unfold_all_lines();
void toggle_foldable_line(int p_line);
bool is_line_folded(int p_line) const;
TypedArray<int> get_folded_lines() const;
/* Delimiters */
void add_string_delimiter(const String &p_start_key, const String &p_end_key, bool p_line_only = false);
void remove_string_delimiter(const String &p_start_key);
bool has_string_delimiter(const String &p_start_key) const;
void set_string_delimiters(const TypedArray<String> &p_string_delimiters);
void clear_string_delimiters();
TypedArray<String> get_string_delimiters() const;
int is_in_string(int p_line, int p_column = -1) const;
void add_comment_delimiter(const String &p_start_key, const String &p_end_key, bool p_line_only = false);
void remove_comment_delimiter(const String &p_start_key);
bool has_comment_delimiter(const String &p_start_key) const;
void set_comment_delimiters(const TypedArray<String> &p_comment_delimiters);
void clear_comment_delimiters();
TypedArray<String> get_comment_delimiters() const;
int is_in_comment(int p_line, int p_column = -1) const;
String get_delimiter_start_key(int p_delimiter_idx) const;
String get_delimiter_end_key(int p_delimiter_idx) const;
Point2 get_delimiter_start_position(int p_line, int p_column) const;
Point2 get_delimiter_end_position(int p_line, int p_column) const;
/* Code hint */
void set_code_hint(const String &p_hint);
void set_code_hint_draw_below(bool p_below);
/* Code Completion */
void set_code_completion_enabled(bool p_enable);
bool is_code_completion_enabled() const;
void set_code_completion_prefixes(const TypedArray<String> &p_prefixes);
TypedArray<String> get_code_completion_prefixes() const;
String get_text_for_code_completion() const;
void request_code_completion(bool p_force = false);
void add_code_completion_option(CodeCompletionKind p_type, const String &p_display_text, const String &p_insert_text, const Color &p_text_color = Color(1, 1, 1), const Ref<Resource> &p_icon = Ref<Resource>(), const Variant &p_value = Variant::NIL);
void update_code_completion_options(bool p_forced = false);
TypedArray<Dictionary> get_code_completion_options() const;
Dictionary get_code_completion_option(int p_index) const;
int get_code_completion_selected_index() const;
void set_code_completion_selected_index(int p_index);
void confirm_code_completion(bool p_replace = false);
void cancel_code_completion();
/* Line length guidelines */
void set_line_length_guidelines(TypedArray<int> p_guideline_columns);
TypedArray<int> get_line_length_guidelines() const;
/* Symbol lookup */
void set_symbol_lookup_on_click_enabled(bool p_enabled);
bool is_symbol_lookup_on_click_enabled() const;
String get_text_for_symbol_lookup();
void set_symbol_lookup_word_as_valid(bool p_valid);
CodeEdit();
~CodeEdit();
};
VARIANT_ENUM_CAST(CodeEdit::CodeCompletionKind);
#endif // CODE_EDIT_H
| {
"content_hash": "41f0ef4fe9762e1152847099cda4829c",
"timestamp": "",
"source": "github",
"line_count": 436,
"max_line_length": 249,
"avg_line_length": 33.408256880733944,
"alnum_prop": 0.6674447343127832,
"repo_name": "guilhermefelipecgs/godot",
"id": "09c7ef80bf86a3868362a4eb64286bc597f957ee",
"size": "14566",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "scene/gui/code_edit.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AIDL",
"bytes": "1633"
},
{
"name": "C",
"bytes": "1045182"
},
{
"name": "C#",
"bytes": "1617601"
},
{
"name": "C++",
"bytes": "39733933"
},
{
"name": "CMake",
"bytes": "606"
},
{
"name": "GAP",
"bytes": "62"
},
{
"name": "GDScript",
"bytes": "66469"
},
{
"name": "GLSL",
"bytes": "844888"
},
{
"name": "Java",
"bytes": "596320"
},
{
"name": "JavaScript",
"bytes": "188917"
},
{
"name": "Kotlin",
"bytes": "93069"
},
{
"name": "Makefile",
"bytes": "1421"
},
{
"name": "Objective-C",
"bytes": "20550"
},
{
"name": "Objective-C++",
"bytes": "395520"
},
{
"name": "PowerShell",
"bytes": "2713"
},
{
"name": "Python",
"bytes": "470837"
},
{
"name": "Shell",
"bytes": "33647"
}
],
"symlink_target": ""
} |
package org.sakaiproject.calendar.api;
import java.util.Iterator;
import java.util.Vector;
import org.sakaiproject.time.api.TimeRange;
/**
* <p>CalendarEventVector is a helper class for the Calendar service. It will read in
* a bunch of CalendarEvents from an iterator, place them into a vector, and provide
* time range controlled access to the events.</p>
* <p>Use this to make larger, more user action aligned service requests, but still have fine
* grained time range access to the events returned.</p>
*/
public class CalendarEventVector
extends Vector
{
/**
* Construct empty.
*/
public CalendarEventVector()
{
super();
}
/**
* Construct
* @param events An interator on CalendarEvents to load into the vector.
*/
public CalendarEventVector(Iterator events)
{
super();
while (events.hasNext())
{
add(events.next());
}
} // CalendarEventVector
/**
* Return an iterator on events in the CalendarEventVector.
* The order in which the events will be found in the iteration is by event start date.
* @param range A time range to limit the iterated events. May be null; all events will be returned.
* @return an iterator on CalendarEvent objects in the CalendarEventVector (may be empty).
*/
public Iterator getEvents(TimeRange range)
{
// pull the range of events from vector
Vector events = new Vector();
Iterator it = iterator();
while (it.hasNext())
{
CalendarEvent test = (CalendarEvent)it.next();
if (range.overlaps(test.getRange()))
{
events.add(test);
}
// %%% if test is past range, we can stop now...
}
return events.iterator();
} // getEvents
} // CalendarEventVector
| {
"content_hash": "dfa3ec6ffa1943bb4472be34abf27873",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 101,
"avg_line_length": 23.43661971830986,
"alnum_prop": 0.7085336538461539,
"repo_name": "eemirtekin/Sakai-10.6-TR",
"id": "815df08f270bfdf0db4fe0eff8c6bafbeeeb7309",
"size": "2805",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "calendar/calendar-api/api/src/java/org/sakaiproject/calendar/api/CalendarEventVector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "59098"
},
{
"name": "Batchfile",
"bytes": "6366"
},
{
"name": "C++",
"bytes": "6402"
},
{
"name": "CSS",
"bytes": "2616828"
},
{
"name": "ColdFusion",
"bytes": "146057"
},
{
"name": "HTML",
"bytes": "5982358"
},
{
"name": "Java",
"bytes": "49585098"
},
{
"name": "JavaScript",
"bytes": "6722774"
},
{
"name": "Lasso",
"bytes": "26436"
},
{
"name": "PHP",
"bytes": "223840"
},
{
"name": "PLSQL",
"bytes": "2163243"
},
{
"name": "Perl",
"bytes": "102776"
},
{
"name": "Python",
"bytes": "87575"
},
{
"name": "Ruby",
"bytes": "3606"
},
{
"name": "Shell",
"bytes": "33041"
},
{
"name": "SourcePawn",
"bytes": "2274"
},
{
"name": "XSLT",
"bytes": "607759"
}
],
"symlink_target": ""
} |
<?php
namespace AframeVR\Core\Exceptions;
final class BadShaderCallException extends \BadMethodCallException
{
public function __construct(string $message = 'null')
{
$this->message = sprintf("Requested shader (%s) could not be loaded!\n", $message);
}
}
| {
"content_hash": "00241a9b287f1f6ac64ad4e849149d6d",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 91,
"avg_line_length": 23.166666666666668,
"alnum_prop": 0.6942446043165468,
"repo_name": "mkungla/aframe-php",
"id": "425c0280470c256757107a1659d374aeb036fabf",
"size": "1115",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Core/Exceptions/BadShaderCallException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "7490"
},
{
"name": "JavaScript",
"bytes": "7766"
},
{
"name": "PHP",
"bytes": "426789"
},
{
"name": "Shell",
"bytes": "40"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "367807f596b4d944e1b1705a7ac8fffa",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "66e503210a0a84ca99509a32bd8d542fb7a5c7a7",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Chenopodiaceae/Atriplex/Atriplex truncata/Atriplex truncata saccaria/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "test/core/util/test_config.h"
static void test_malloc_aligned() {
for (size_t size = 1; size <= 256; ++size) {
void* ptr = gpr_malloc_aligned(size, 16);
GPR_ASSERT(ptr != nullptr);
GPR_ASSERT(((intptr_t)ptr & 0xf) == 0);
memset(ptr, 0, size);
gpr_free_aligned(ptr);
}
}
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(&argc, argv);
test_malloc_aligned();
return 0;
}
| {
"content_hash": "75fb39533289e514e102e6639b9c891e",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 50,
"avg_line_length": 21.5,
"alnum_prop": 0.6317829457364341,
"repo_name": "vjpai/grpc",
"id": "35fa8bc31560a3b464a17cc91e1b50298a2d54d9",
"size": "1118",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/core/gpr/alloc_test.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "5444"
},
{
"name": "Batchfile",
"bytes": "39116"
},
{
"name": "C",
"bytes": "1416244"
},
{
"name": "C#",
"bytes": "106367"
},
{
"name": "C++",
"bytes": "15813558"
},
{
"name": "CMake",
"bytes": "29311"
},
{
"name": "CSS",
"bytes": "1519"
},
{
"name": "Cython",
"bytes": "258757"
},
{
"name": "DTrace",
"bytes": "147"
},
{
"name": "Dockerfile",
"bytes": "178195"
},
{
"name": "Go",
"bytes": "34794"
},
{
"name": "HTML",
"bytes": "14"
},
{
"name": "Java",
"bytes": "12924"
},
{
"name": "JavaScript",
"bytes": "5572"
},
{
"name": "Objective-C",
"bytes": "697418"
},
{
"name": "Objective-C++",
"bytes": "80936"
},
{
"name": "PHP",
"bytes": "486781"
},
{
"name": "PowerShell",
"bytes": "4516"
},
{
"name": "Python",
"bytes": "3770410"
},
{
"name": "Ruby",
"bytes": "648566"
},
{
"name": "Shell",
"bytes": "755630"
},
{
"name": "Starlark",
"bytes": "750193"
},
{
"name": "Swift",
"bytes": "7487"
},
{
"name": "XSLT",
"bytes": "9846"
}
],
"symlink_target": ""
} |
All notable changes to this project will be documented in this file.
## [v4.0.0] - 2017-08-14
- Bump hoist-non-react-statics and babel-runtime
- Remove Babel and ESLint sections from package.json
- Add a safety check on `componentWillUnmount` of `withStyles` to only `setTimeout` if `this.removeCss` is defined ([#104](https://github.com/kriasoft/isomorphic-style-loader/pull/104))
- Call the insertCss with the spread operator ([#101](https://github.com/kriasoft/isomorphic-style-loader/pull/101))
## [v3.0.0] - 2017-07-07
- Bump hoist-non-react-statics ([#97](https://github.com/kriasoft/isomorphic-style-loader/pull/97))
## [v2.0.0] - 2017-04-20
- Pull `PropTypes` from [prop-types](https://www.npmjs.com/package/prop-types) package for compatibility with **React 15.3.0** and higher ([#90](https://github.com/kriasoft/isomorphic-style-loader/pull/90))
## [v1.1.0] - 2016-10-30
- Disable source maps in IE9 and below, to prevent runtime errors in development mode ([#69](https://github.com/kriasoft/isomorphic-style-loader/pull/69))
- Improve source maps support by making sourceURL field unique ([#44](https://github.com/kriasoft/isomorphic-style-loader/pull/44), [#69](https://github.com/kriasoft/isomorphic-style-loader/pull/69))
- Add access to content to deduplicate server-side generated styles ([#56](https://github.com/kriasoft/isomorphic-style-loader/pull/56))
- Use HMR (Hot Module Replacement) if available, no debug option required ([#57](https://github.com/kriasoft/isomorphic-style-loader/pull/57))
- Use [hoist-non-react-statics](https://github.com/mridgway/hoist-non-react-statics) to copy non-react
specific statics from a child to a parent component inside `withStyles` HOC (Higher-Order Component)
([#38](https://github.com/kriasoft/isomorphic-style-loader/pull/38))
- Add `CHANGELOG.md` file with the past and future (planned) changes to the project
## [v1.0.0] - 2016-04-15
- Improve comparability with Hot Module Replacement (HMR) ([#33](https://github.com/kriasoft/isomorphic-style-loader/pull/33))
- Add support of ES2015+ decorator syntax, e.g. `@withStyles(s) class MyComponent extends Component { .. }`
[PR#21](https://github.com/kriasoft/isomorphic-style-loader/pull/21) (BREAKING CHANGE)
## [v0.0.12] - 2016-03-04
- Fix style not getting removed for multiple instance ([#23](https://github.com/kriasoft/isomorphic-style-loader/pull/23))
[unreleased]: https://github.com/kriasoft/isomorphic-style-loader/compare/v4.0.0...HEAD
[v4.0.0]: https://github.com/kriasoft/isomorphic-style-loader/compare/v3.0.0...v4.0.0
[v3.0.0]: https://github.com/kriasoft/isomorphic-style-loader/compare/v2.0.0...v3.0.0
[v2.0.0]: https://github.com/kriasoft/isomorphic-style-loader/compare/v1.1.0...v2.0.0
[v1.1.0]: https://github.com/kriasoft/isomorphic-style-loader/compare/v1.0.0...v1.1.0
[v1.0.0]: https://github.com/kriasoft/isomorphic-style-loader/compare/v0.0.12...v1.0.0
[v0.0.12]: https://github.com/kriasoft/isomorphic-style-loader/compare/v0.0.11...v0.0.12
| {
"content_hash": "4713215790f06b452dd169fa10636555",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 206,
"avg_line_length": 66.57777777777778,
"alnum_prop": 0.7409879839786382,
"repo_name": "kumarrus/MuffinMan",
"id": "1599fc6eacaf1f25c18a0364d86b6a71eb8ef49e",
"size": "3034",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/isomorphic-style-loader/CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13353"
},
{
"name": "JavaScript",
"bytes": "64397"
}
],
"symlink_target": ""
} |
<footer>
<div id="map-canvas"></div>
<div id="footer-info-box">
<div class="button"><span>Contact Me</span></div>
<a href="https://twitter.com/paigecrum"><img src="/assets/images/twitter.png" alt="twitter" id="twitter-logo"/></a>
<a href="https://github.com/paigecrum"><img src="/assets/images/github.png" alt="github" id="github-logo"/></a>
<a href="https://www.linkedin.com/in/paigecrum"><img src="/assets/images/linkedin.png" alt="linkedin" id="linkedin-logo"/></a>
<div id="copyright-blurb">© Paige Crum 2014. Made with ♥ in Jekyll.</div>
</div>
</footer>
| {
"content_hash": "b4c8811f11eac27bc92679132500f267",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 130,
"avg_line_length": 58.6,
"alnum_prop": 0.6535836177474402,
"repo_name": "paigecrum/paigecrum.github.io",
"id": "b21d97028be0217a4938acfe45938ec7b894bb77",
"size": "589",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/footer.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "103870"
},
{
"name": "JavaScript",
"bytes": "5349"
},
{
"name": "Ruby",
"bytes": "4483"
}
],
"symlink_target": ""
} |
import React from 'react';
import {} from 'prop-types';
import classNames from 'classnames';
const PanelFooter = ({ children, className, ...rest }) => {
return (
<div className={classNames('panel-footer', className)} {...rest}>
{children}
</div>
);
};
/**
* PanelFooter property types.
*/
PanelFooter.propTypes = {};
/**
* PanelFooter default properties.
*/
PanelFooter.defaultProps = {};
export default PanelFooter;
| {
"content_hash": "72d9b08d3b7085c06d6ad9952124433b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 69,
"avg_line_length": 19.26086956521739,
"alnum_prop": 0.6501128668171557,
"repo_name": "Landish/react-spectre-css",
"id": "2fc1384305fd2274cb92dd1c173a7accd4b047d9",
"size": "443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/PanelFooter/PanelFooter.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "166"
},
{
"name": "HTML",
"bytes": "424"
},
{
"name": "JavaScript",
"bytes": "62822"
}
],
"symlink_target": ""
} |
import * as plugins from './bts.plugins'
import { IInvoiceItem } from 'tsclass'
export class InvoiceItem implements IInvoiceItem {
name: string
unitType: string
quantity: number
vatPercentage
}
| {
"content_hash": "ec2fd153eea852a40309048359ff306e",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 50,
"avg_line_length": 22.555555555555557,
"alnum_prop": 0.7536945812807881,
"repo_name": "billtoday/bts",
"id": "01af027c8a320196502b307c18c7b360fb834b35",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ts/bts.classes.invoiceitem.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "TypeScript",
"bytes": "1095"
}
],
"symlink_target": ""
} |
package org.hspconsortium.platform.authorization.service;
import org.junit.Test;
import org.mockito.Mockito;
import org.smartplatforms.oauth2.ScopeValidator;
import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import java.io.Serializable;
import java.util.Map;
public class ScopeValidatorTest {
@Test
public void validateScopeTest() {
AuthorizationRequest mockAuthorizationRequest = Mockito.mock(AuthorizationRequest.class);
ClientDetails clientDetails = Mockito.mock(ClientDetails.class);
ScopeValidator scopeValidator = new ScopeValidator();
scopeValidator.validateScope(mockAuthorizationRequest, clientDetails);
}
@Test(expected = InvalidScopeException.class)
public void validateScopeFailureTest() {
String invalidLaunch = "invalidLaunch";
Map<String, Serializable> mockExtensions = Mockito.mock(Map.class);
Mockito.when(mockExtensions.get("invalid_launch")).thenReturn(invalidLaunch);
AuthorizationRequest mockAuthorizationRequest = Mockito.mock(AuthorizationRequest.class);
Mockito.when(mockAuthorizationRequest.getExtensions()).thenReturn(mockExtensions);
ClientDetails clientDetails = Mockito.mock(ClientDetails.class);
ScopeValidator scopeValidator = new ScopeValidator();
scopeValidator.validateScope(mockAuthorizationRequest, clientDetails);
}
} | {
"content_hash": "cf8b8e1e51a098f763c162b8599e0f86",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 97,
"avg_line_length": 38.073170731707314,
"alnum_prop": 0.7802690582959642,
"repo_name": "nschwertner/reference-auth-server-webapp",
"id": "549af12142261bc85bb5d1901d755c5bf86b215e",
"size": "1561",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/hspconsortium/platform/authorization/service/ScopeValidatorTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "87747"
}
],
"symlink_target": ""
} |
namespace eui
{
namespace window
{
ToolbarPanel::ToolbarPanel(wxWindow* parent, StagePanel* stage_panel)
: ee::ToolbarPanel(parent, NULL)
, m_stage_panel(stage_panel)
{
SetSizer(InitLayout());
RegistSubject(ChangeWindowViewSizeSJ::Instance());
}
std::string ToolbarPanel::GetWindowName() const
{
return m_name_text->GetValue().ToStdString();
}
void ToolbarPanel::SetWindowName(const std::string& name)
{
m_name_text->SetValue(name);
}
wxSizer* ToolbarPanel::InitLayout()
{
wxSizer* top_sizer = new wxBoxSizer(wxVERTICAL);
top_sizer->AddSpacer(10);
top_sizer->Add(InitNameLayout());
top_sizer->AddSpacer(10);
top_sizer->Add(InitViewLayout());
top_sizer->AddSpacer(10);
top_sizer->Add(InitCrossLayout());
return top_sizer;
}
void ToolbarPanel::OnNotify(int sj_id, void* ud)
{
if (sj_id == MSG_CHANGE_WINDOW_VIEW_SIZE)
{
ChangeWindowViewSizeSJ::Params* p = (ChangeWindowViewSizeSJ::Params*)ud;
m_width_text->SetValue(ee::StringHelper::ToString(p->width));
m_height_text->SetValue(ee::StringHelper::ToString(p->height));
}
}
wxSizer* ToolbarPanel::InitNameLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Name"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxVERTICAL);
m_name_text = new wxTextCtrl(this, wxID_ANY);
sizer->Add(m_name_text);
return sizer;
}
wxSizer* ToolbarPanel::InitViewLayout()
{
int width, height;
window::QueryWindowViewSizeSJ::Instance()->Query(width, height);
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("View"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxVERTICAL);
{
wxSizer* sz = new wxBoxSizer(wxHORIZONTAL);
sz->Add(new wxStaticText(this, wxID_ANY, "width"));
m_width_text = new wxTextCtrl(this, wxID_ANY, ee::StringHelper::ToString(width), wxDefaultPosition, wxSize(50, -1), wxTE_PROCESS_ENTER);
Connect(m_width_text->GetId(), wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler(ToolbarPanel::OnChangeSize));
sz->Add(m_width_text);
sizer->Add(sz);
}
sizer->AddSpacer(5);
{
wxSizer* sz = new wxBoxSizer(wxHORIZONTAL);
sz->Add(new wxStaticText(this, wxID_ANY, "height"));
m_height_text = new wxTextCtrl(this, wxID_ANY, ee::StringHelper::ToString(height), wxDefaultPosition, wxSize(50, -1), wxTE_PROCESS_ENTER);
Connect(m_height_text->GetId(), wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler(ToolbarPanel::OnChangeSize));
sz->Add(m_height_text);
sizer->Add(sz);
}
return sizer;
}
// todo copy from eanim::NormalCMPT
wxSizer* ToolbarPanel::InitCrossLayout()
{
wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("¸¨ÖúÏß"));
wxSizer* sizer = new wxStaticBoxSizer(bounding, wxHORIZONTAL);
wxButton* btn_add = new wxButton(this, wxID_ANY, "+", wxDefaultPosition, wxSize(25, 25));
sizer->Add(btn_add, 0, wxLEFT | wxRIGHT, 5);
Connect(btn_add->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(ToolbarPanel::OnAddCross));
wxButton* btn_del = new wxButton(this, wxID_ANY, "-", wxDefaultPosition, wxSize(25, 25));
sizer->Add(btn_del, 0, wxLEFT | wxRIGHT, 5);
Connect(btn_del->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(ToolbarPanel::OnDelCross));
return sizer;
}
void ToolbarPanel::OnChangeSize(wxCommandEvent& event)
{
double width, height;
m_width_text->GetValue().ToDouble(&width);
m_height_text->GetValue().ToDouble(&height);
m_stage_panel->SetViewSize(width, height);
}
void ToolbarPanel::OnAddCross(wxCommandEvent& event)
{
m_stage_panel->GetCrossGuides().Add();
ee::SetCanvasDirtySJ::Instance()->SetDirty();
}
void ToolbarPanel::OnDelCross(wxCommandEvent& event)
{
m_stage_panel->GetCrossGuides().Remove();
ee::SetCanvasDirtySJ::Instance()->SetDirty();
}
}
}
| {
"content_hash": "bc50a707464b3ee316b60aabb23504a9",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 140,
"avg_line_length": 28.6953125,
"alnum_prop": 0.7263817043288865,
"repo_name": "xzrunner/easyeditor",
"id": "e44bc63124a28f6192a596268a478980a927f29d",
"size": "3801",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "easyui/src/easyui/window/ToolbarPanel.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "118661"
},
{
"name": "C++",
"bytes": "5152354"
},
{
"name": "GLSL",
"bytes": "10503"
},
{
"name": "Lua",
"bytes": "127544"
},
{
"name": "Makefile",
"bytes": "210"
}
],
"symlink_target": ""
} |
'use strict';
const CHOOSABLE_TARGETS = new Set(['normal', 'any', 'adjacentAlly', 'adjacentAllyOrSelf', 'adjacentFoe']);
exports.BattleScripts = {
gen: 7,
runMove: function (move, pokemon, targetLoc, sourceEffect, zMove) {
let target = this.getTarget(pokemon, zMove || move, targetLoc);
if (!sourceEffect && toId(move) !== 'struggle' && !zMove) {
let changedMove = this.runEvent('OverrideDecision', pokemon, target, move);
if (changedMove && changedMove !== true) {
move = changedMove;
target = null;
}
}
let baseMove = this.getMove(move);
move = zMove ? this.getZMoveCopy(move, pokemon) : baseMove;
if (!target && target !== false) target = this.resolveTarget(pokemon, move);
// copy the priority for Quick Guard
if (zMove) move.priority = baseMove.priority;
this.setActiveMove(move, pokemon, target);
/* if (pokemon.moveThisTurn) {
// THIS IS PURELY A SANITY CHECK
// DO NOT TAKE ADVANTAGE OF THIS TO PREVENT A POKEMON FROM MOVING;
// USE this.cancelMove INSTEAD
this.debug('' + pokemon.id + ' INCONSISTENT STATE, ALREADY MOVED: ' + pokemon.moveThisTurn);
this.clearActiveMove(true);
return;
} */
if (!this.runEvent('BeforeMove', pokemon, target, move)) {
this.runEvent('MoveAborted', pokemon, target, move);
// Prevent Pursuit from running again against a slower U-turn/Volt Switch/Parting Shot
pokemon.moveThisTurn = true;
this.clearActiveMove(true);
return;
}
if (move.beforeMoveCallback) {
if (move.beforeMoveCallback.call(this, pokemon, target, move)) {
this.clearActiveMove(true);
return;
}
}
pokemon.lastDamage = 0;
let lockedMove = this.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove) {
if (!pokemon.deductPP(baseMove, null, target) && (move.id !== 'struggle')) {
this.add('cant', pokemon, 'nopp', move);
let gameConsole = [null, 'Game Boy', 'Game Boy', 'Game Boy Advance', 'DS', 'DS'][this.gen] || '3DS';
this.add('-hint', "This is not a bug, this is really how it works on the " + gameConsole + "; try it yourself if you don't believe us.");
this.clearActiveMove(true);
return;
}
} else {
sourceEffect = this.getEffect('lockedmove');
}
pokemon.moveUsed(move, targetLoc);
if (zMove) {
this.add('-zpower', pokemon);
pokemon.side.zMoveUsed = true;
}
this.useMove(baseMove, pokemon, target, sourceEffect, zMove);
this.singleEvent('AfterMove', move, null, pokemon, target, move);
this.runEvent('AfterMove', pokemon, target, move);
},
useMove: function (move, pokemon, target, sourceEffect, zMove) {
if (!sourceEffect && this.effect.id) sourceEffect = this.effect;
if (zMove || (sourceEffect && sourceEffect.isZ)) {
move = this.getZMoveCopy(move, pokemon);
} else {
move = this.getMoveCopy(move);
}
if (this.activeMove) {
move.priority = this.activeMove.priority;
move.pranksterBoosted = this.activeMove.pranksterBoosted;
}
let baseTarget = move.target;
if (!target && target !== false) target = this.resolveTarget(pokemon, move);
if (move.target === 'self' || move.target === 'allies') {
target = pokemon;
}
if (sourceEffect) move.sourceEffect = sourceEffect.id;
let moveResult = false;
this.setActiveMove(move, pokemon, target);
this.singleEvent('ModifyMove', move, null, pokemon, target, move, move);
if (baseTarget !== move.target) {
// Target changed in ModifyMove, so we must adjust it here
// Adjust before the next event so the correct target is passed to the
// event
target = this.resolveTarget(pokemon, move);
}
move = this.runEvent('ModifyMove', pokemon, target, move, move);
if (baseTarget !== move.target) {
// Adjust again
target = this.resolveTarget(pokemon, move);
}
if (!move) return false;
let attrs = '';
if (pokemon.fainted) {
return false;
}
if (move.flags['charge'] && !pokemon.volatiles[move.id]) {
attrs = '|[still]'; // suppress the default move animation
}
let movename = move.name;
if (move.id === 'hiddenpower') movename = 'Hidden Power';
if (sourceEffect) attrs += '|[from]' + this.getEffect(sourceEffect);
if (zMove && (move.category === 'Status')) {
attrs = '|[anim]' + movename + attrs;
movename = 'Z-' + movename;
}
this.addMove('move', pokemon, movename, target + attrs);
if (zMove && move.category !== 'Status') {
this.attrLastMove('[zeffect]');
} else if (zMove && move.zMoveBoost) {
this.boost(move.zMoveBoost, pokemon, pokemon, {id: 'zpower'});
} else if (zMove && move.zMoveEffect === 'heal') {
this.heal(pokemon.maxhp, pokemon, pokemon, {id: 'zpower'});
} else if (zMove && move.zMoveEffect === 'healreplacement') {
move.self = {sideCondition: 'healreplacement'};
} else if (zMove && move.zMoveEffect === 'clearnegativeboost') {
let boosts = {};
for (let i in pokemon.boosts) {
if (pokemon.boosts[i] < 0) {
boosts[i] = 0;
}
}
pokemon.setBoost(boosts);
this.add('-clearnegativeboost', pokemon, '[zeffect]');
} else if (zMove && move.zMoveEffect === 'redirect') {
pokemon.addVolatile('followme', pokemon, {id: 'zpower'});
} else if (zMove && move.zMoveEffect === 'crit2') {
pokemon.addVolatile('focusenergy', pokemon, {id: 'zpower'});
} else if (zMove && move.zMoveEffect === 'curse') {
if (pokemon.hasType('Ghost')) {
this.heal(pokemon.maxhp, pokemon, pokemon, {id: 'zpower'});
} else {
this.boost({atk: 1}, pokemon, pokemon, {id: 'zpower'});
}
}
if (target === false) {
this.attrLastMove('[notarget]');
this.add('-notarget');
if (move.target === 'normal') pokemon.isStaleCon = 0;
return true;
}
let targets = pokemon.getMoveTargets(move, target);
if (!sourceEffect) {
let extraPP = 0;
for (let i = 0; i < targets.length; i++) {
let ppDrop = this.singleEvent('DeductPP', targets[i].getAbility(), targets[i].abilityData, targets[i], pokemon, move);
if (ppDrop !== true) {
extraPP += ppDrop || 0;
}
}
if (extraPP > 0) {
pokemon.deductPP(move, extraPP);
}
}
if (!this.runEvent('TryMove', pokemon, target, move)) {
return true;
}
this.singleEvent('UseMoveMessage', move, null, pokemon, target, move);
if (move.ignoreImmunity === undefined) {
move.ignoreImmunity = (move.category === 'Status');
}
let damage = false;
if (move.target === 'all' || move.target === 'foeSide' || move.target === 'allySide' || move.target === 'allyTeam') {
damage = this.tryMoveHit(target, pokemon, move);
if (damage || damage === 0 || damage === undefined) moveResult = true;
} else if (move.target === 'allAdjacent' || move.target === 'allAdjacentFoes') {
if (move.selfdestruct) {
this.faint(pokemon, pokemon, move);
}
if (!targets.length) {
this.attrLastMove('[notarget]');
this.add('-notarget');
return true;
}
if (targets.length > 1) move.spreadHit = true;
damage = 0;
let hitTargets = [];
for (let i = 0; i < targets.length; i++) {
let hitResult = this.tryMoveHit(targets[i], pokemon, move, true);
if (hitResult || hitResult === 0 || hitResult === undefined) {
moveResult = true;
hitTargets.push(targets[i].toString().substr(0, 3));
}
damage += hitResult || 0;
}
if (move.spreadHit) this.attrLastMove('[spread] ' + hitTargets.join(','));
if (!pokemon.hp) pokemon.faint();
} else {
target = targets[0];
let lacksTarget = target.fainted;
if (!lacksTarget) {
if (move.target === 'adjacentFoe' || move.target === 'adjacentAlly' || move.target === 'normal' || move.target === 'randomNormal') {
lacksTarget = !this.isAdjacent(target, pokemon);
}
}
if (lacksTarget) {
this.attrLastMove('[notarget]');
this.add('-notarget');
if (move.target === 'normal') pokemon.isStaleCon = 0;
return true;
}
damage = this.tryMoveHit(target, pokemon, move);
if (damage || damage === 0 || damage === undefined) moveResult = true;
}
if (!pokemon.hp) {
this.faint(pokemon, pokemon, move);
}
if (!moveResult) {
this.singleEvent('MoveFail', move, null, target, pokemon, move);
return true;
}
if (move.selfdestruct) {
this.faint(pokemon, pokemon, move);
}
if (!move.negateSecondary && !(pokemon.hasAbility('sheerforce') && pokemon.volatiles['sheerforce'])) {
this.singleEvent('AfterMoveSecondarySelf', move, null, pokemon, target, move);
this.runEvent('AfterMoveSecondarySelf', pokemon, target, move);
}
return true;
},
tryMoveHit: function (target, pokemon, move, spreadHit) {
if (move.selfdestruct && spreadHit) pokemon.hp = 0;
this.setActiveMove(move, pokemon, target);
let hitResult = true;
hitResult = this.singleEvent('PrepareHit', move, {}, target, pokemon, move);
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return false;
}
this.runEvent('PrepareHit', pokemon, target, move);
if (!this.singleEvent('Try', move, null, pokemon, target, move)) {
return false;
}
if (move.target === 'all' || move.target === 'foeSide' || move.target === 'allySide' || move.target === 'allyTeam') {
if (move.target === 'all') {
hitResult = this.runEvent('TryHitField', target, pokemon, move);
} else {
hitResult = this.runEvent('TryHitSide', target, pokemon, move);
}
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return true;
}
return this.moveHit(target, pokemon, move);
}
if (move.ignoreImmunity === undefined) {
move.ignoreImmunity = (move.category === 'Status');
}
if (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type] && !target.runImmunity(move.type, true)) {
return false;
}
hitResult = this.runEvent('TryHit', target, pokemon, move);
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return false;
}
if (move.flags['powder'] && target !== pokemon && !this.getImmunity('powder', target)) {
this.debug('natural powder immunity');
this.add('-immune', target, '[msg]');
return false;
}
if (this.gen >= 7 && move.pranksterBoosted && target.side !== pokemon.side && !this.getImmunity('prankster', target)) {
this.debug('natural prankster immunity');
this.add('-hint', "In gen 7, Dark is immune to Prankster moves.");
this.add('-immune', target, '[msg]');
return false;
}
let boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
// calculate true accuracy
let accuracy = move.accuracy;
let boosts, boost;
if (accuracy !== true) {
if (!move.ignoreAccuracy) {
boosts = this.runEvent('ModifyBoost', pokemon, null, null, Object.assign({}, pokemon.boosts));
boost = this.clampIntRange(boosts['accuracy'], -6, 6);
if (boost > 0) {
accuracy *= boostTable[boost];
} else {
accuracy /= boostTable[-boost];
}
}
if (!move.ignoreEvasion) {
boosts = this.runEvent('ModifyBoost', target, null, null, Object.assign({}, target.boosts));
boost = this.clampIntRange(boosts['evasion'], -6, 6);
if (boost > 0) {
accuracy /= boostTable[boost];
} else if (boost < 0) {
accuracy *= boostTable[-boost];
}
}
}
if (move.ohko) { // bypasses accuracy modifiers
if (!target.isSemiInvulnerable()) {
accuracy = 30;
if (pokemon.level >= target.level && (move.ohko === true || !target.hasType(move.ohko))) {
// TODO: Research dependency of accuracy on user typing
accuracy += (pokemon.level - target.level);
} else {
this.add('-immune', target, '[ohko]');
return false;
}
}
} else {
accuracy = this.runEvent('ModifyAccuracy', target, pokemon, move, accuracy);
}
if (move.alwaysHit || (move.id === 'toxic' && this.gen >= 6 && pokemon.hasType('Poison'))) {
accuracy = true; // bypasses ohko accuracy modifiers
} else {
accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy);
}
if (accuracy !== true && this.random(100) >= accuracy) {
if (!move.spreadHit) this.attrLastMove('[miss]');
this.add('-miss', pokemon, target);
return false;
}
if (move.breaksProtect) {
let broke = false;
for (let i in {banefulbunker:1, kingsshield:1, protect:1, spikyshield:1}) {
if (target.removeVolatile(i)) broke = true;
}
if (this.gen >= 6 || target.side !== pokemon.side) {
for (let i in {craftyshield:1, matblock:1, quickguard:1, wideguard:1}) {
if (target.side.removeSideCondition(i)) broke = true;
}
}
if (broke) {
if (move.id === 'feint') {
this.add('-activate', target, 'move: Feint');
} else {
this.add('-activate', target, 'move: ' + move.name, '[broken]');
}
}
}
if (move.stealsBoosts) {
let boosts = {};
let stolen = false;
for (let statName in target.boosts) {
let stage = target.boosts[statName];
if (stage > 0) {
boosts[statName] = stage;
stolen = true;
}
}
if (stolen) {
this.attrLastMove('[still]');
this.add('-clearpositiveboost', target, pokemon, 'move: ' + move.name);
this.boost(boosts, pokemon);
for (let statName in boosts) {
boosts[statName] = 0;
}
target.setBoost(boosts);
this.add('-anim', pokemon, "Spectral Thief", target);
}
}
move.totalDamage = 0;
let damage = 0;
pokemon.lastDamage = 0;
if (move.multihit) {
let hits = move.multihit;
if (hits.length) {
// yes, it's hardcoded... meh
if (hits[0] === 2 && hits[1] === 5) {
if (this.gen >= 5) {
hits = [2, 2, 3, 3, 4, 5][this.random(6)];
} else {
hits = [2, 2, 2, 3, 3, 3, 4, 5][this.random(8)];
}
} else {
hits = this.random(hits[0], hits[1] + 1);
}
}
hits = Math.floor(hits);
let nullDamage = true;
let moveDamage;
// There is no need to recursively check the ´sleepUsable´ flag as Sleep Talk can only be used while asleep.
let isSleepUsable = move.sleepUsable || this.getMove(move.sourceEffect).sleepUsable;
let i;
for (i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (pokemon.status === 'slp' && !isSleepUsable) break;
if (move.multiaccuracy && i > 0) {
accuracy = move.accuracy;
if (accuracy !== true) {
if (!move.ignoreAccuracy) {
boosts = this.runEvent('ModifyBoost', pokemon, null, null, Object.assign({}, pokemon.boosts));
boost = this.clampIntRange(boosts['accuracy'], -6, 6);
if (boost > 0) {
accuracy *= boostTable[boost];
} else {
accuracy /= boostTable[-boost];
}
}
if (!move.ignoreEvasion) {
boosts = this.runEvent('ModifyBoost', target, null, null, Object.assign({}, target.boosts));
boost = this.clampIntRange(boosts['evasion'], -6, 6);
if (boost > 0) {
accuracy /= boostTable[boost];
} else if (boost < 0) {
accuracy *= boostTable[-boost];
}
}
}
accuracy = this.runEvent('ModifyAccuracy', target, pokemon, move, accuracy);
if (!move.alwaysHit) {
accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy);
if (accuracy !== true && this.random(100) >= accuracy) break;
}
}
moveDamage = this.moveHit(target, pokemon, move);
if (moveDamage === false) break;
if (nullDamage && (moveDamage || moveDamage === 0 || moveDamage === undefined)) nullDamage = false;
// Damage from each hit is individually counted for the
// purposes of Counter, Metal Burst, and Mirror Coat.
damage = (moveDamage || 0);
// Total damage dealt is accumulated for the purposes of recoil (Parental Bond).
move.totalDamage += damage;
this.eachEvent('Update');
}
if (i === 0) return true;
if (nullDamage) damage = false;
this.add('-hitcount', target, i);
} else {
damage = this.moveHit(target, pokemon, move);
move.totalDamage = damage;
}
if (move.recoil && move.totalDamage) {
this.damage(this.calcRecoilDamage(move.totalDamage, move), pokemon, target, 'recoil');
}
if (move.struggleRecoil) {
this.directDamage(this.clampIntRange(Math.round(pokemon.maxhp / 4), 1), pokemon, pokemon, {id: 'strugglerecoil'});
}
if (target && pokemon !== target) target.gotAttacked(move, damage, pokemon);
if (move.ohko) this.add('-ohko');
if (!damage && damage !== 0) return damage;
this.eachEvent('Update');
if (target && !move.negateSecondary && !(pokemon.hasAbility('sheerforce') && pokemon.volatiles['sheerforce'])) {
this.singleEvent('AfterMoveSecondary', move, null, target, pokemon, move);
this.runEvent('AfterMoveSecondary', target, pokemon, move);
}
return damage;
},
moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
let damage;
move = this.getMoveCopy(move);
if (!moveData) moveData = move;
if (!moveData.flags) moveData.flags = {};
let hitResult = true;
// TryHit events:
// STEP 1: we see if the move will succeed at all:
// - TryHit, TryHitSide, or TryHitField are run on the move,
// depending on move target (these events happen in useMove
// or tryMoveHit, not below)
// == primary hit line ==
// Everything after this only happens on the primary hit (not on
// secondary or self-hits)
// STEP 2: we see if anything blocks the move from hitting:
// - TryFieldHit is run on the target
// STEP 3: we see if anything blocks the move from hitting the target:
// - If the move's target is a pokemon, TryHit is run on that pokemon
// Note:
// If the move target is `foeSide`:
// event target = pokemon 0 on the target side
// If the move target is `allySide` or `all`:
// event target = the move user
//
// This is because events can't accept actual sides or fields as
// targets. Choosing these event targets ensures that the correct
// side or field is hit.
//
// It is the `TryHitField` event handler's responsibility to never
// use `target`.
// It is the `TryFieldHit` event handler's responsibility to read
// move.target and react accordingly.
// An exception is `TryHitSide` as a single event (but not as a normal
// event), which is passed the target side.
if (move.target === 'all' && !isSelf) {
hitResult = this.singleEvent('TryHitField', moveData, {}, target, pokemon, move);
} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
hitResult = this.singleEvent('TryHitSide', moveData, {}, target.side, pokemon, move);
} else if (target) {
hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
}
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return false;
}
if (target && !isSecondary && !isSelf) {
if (move.target !== 'all' && move.target !== 'allySide' && move.target !== 'foeSide') {
hitResult = this.runEvent('TryPrimaryHit', target, pokemon, moveData);
if (hitResult === 0) {
// special Substitute flag
hitResult = true;
target = null;
}
}
}
if (target && isSecondary && !moveData.self) {
hitResult = true;
}
if (!hitResult) {
return false;
}
if (target) {
let didSomething = false;
damage = this.getDamage(pokemon, target, moveData);
// getDamage has several possible return values:
//
// a number:
// means that much damage is dealt (0 damage still counts as dealing
// damage for the purposes of things like Static)
// false:
// gives error message: "But it failed!" and move ends
// null:
// the move ends, with no message (usually, a custom fail message
// was already output by an event handler)
// undefined:
// means no damage is dealt and the move continues
//
// basically, these values have the same meanings as they do for event
// handlers.
if ((damage || damage === 0) && !target.fainted) {
if (move.noFaint && damage >= target.hp) {
damage = target.hp - 1;
}
damage = this.damage(damage, target, pokemon, move);
if (!(damage || damage === 0)) {
this.debug('damage interrupted');
return false;
}
didSomething = true;
}
if (damage === false || damage === null) {
if (damage === false && !isSecondary && !isSelf) {
this.add('-fail', target);
}
this.debug('damage calculation interrupted');
return false;
}
if (moveData.boosts && !target.fainted) {
hitResult = this.boost(moveData.boosts, target, pokemon, move, isSecondary, isSelf);
didSomething = didSomething || hitResult;
}
if (moveData.heal && !target.fainted) {
let d = target.heal((this.gen < 5 ? Math.floor : Math.round)(target.maxhp * moveData.heal[0] / moveData.heal[1]));
if (!d && d !== 0) {
this.add('-fail', target);
this.debug('heal interrupted');
return false;
}
this.add('-heal', target, target.getHealth);
didSomething = true;
}
if (moveData.status) {
hitResult = target.trySetStatus(moveData.status, pokemon, moveData.ability ? moveData.ability : move);
if (!hitResult && move.status) return hitResult;
didSomething = didSomething || hitResult;
}
if (moveData.forceStatus) {
hitResult = target.setStatus(moveData.forceStatus, pokemon, move);
didSomething = didSomething || hitResult;
}
if (moveData.volatileStatus) {
hitResult = target.addVolatile(moveData.volatileStatus, pokemon, move);
didSomething = didSomething || hitResult;
}
if (moveData.sideCondition) {
hitResult = target.side.addSideCondition(moveData.sideCondition, pokemon, move);
didSomething = didSomething || hitResult;
}
if (moveData.weather) {
hitResult = this.setWeather(moveData.weather, pokemon, move);
didSomething = didSomething || hitResult;
}
if (moveData.terrain) {
hitResult = this.setTerrain(moveData.terrain, pokemon, move);
didSomething = didSomething || hitResult;
}
if (moveData.pseudoWeather) {
hitResult = this.addPseudoWeather(moveData.pseudoWeather, pokemon, move);
didSomething = didSomething || hitResult;
}
if (moveData.forceSwitch) {
if (this.canSwitch(target.side)) didSomething = true; // at least defer the fail message to later
}
if (moveData.selfSwitch) {
if (this.canSwitch(pokemon.side)) didSomething = true; // at least defer the fail message to later
}
// Hit events
// These are like the TryHit events, except we don't need a FieldHit event.
// Scroll up for the TryHit event documentation, and just ignore the "Try" part. ;)
hitResult = null;
if (move.target === 'all' && !isSelf) {
if (moveData.onHitField) hitResult = this.singleEvent('HitField', moveData, {}, target, pokemon, move);
} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
if (moveData.onHitSide) hitResult = this.singleEvent('HitSide', moveData, {}, target.side, pokemon, move);
} else {
if (moveData.onHit) hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move);
if (!isSelf && !isSecondary) {
this.runEvent('Hit', target, pokemon, move);
}
if (moveData.onAfterHit) hitResult = this.singleEvent('AfterHit', moveData, {}, target, pokemon, move);
}
if (!hitResult && !didSomething && !moveData.self && !moveData.selfdestruct) {
if (!isSelf && !isSecondary) {
if (hitResult === false || didSomething === false) this.add('-fail', target);
}
this.debug('move failed because it did nothing');
return false;
}
}
if (moveData.self) {
let selfRoll;
if (!isSecondary && moveData.self.boosts) selfRoll = this.random(100);
// This is done solely to mimic in-game RNG behaviour. All self drops have a 100% chance of happening but still grab a random number.
if (typeof moveData.self.chance === 'undefined' || selfRoll < moveData.self.chance) {
this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
}
}
if (moveData.secondaries) {
let secondaryRoll;
let secondaries = this.runEvent('ModifySecondaries', target, pokemon, moveData, moveData.secondaries.slice());
for (let i = 0; i < secondaries.length; i++) {
secondaryRoll = this.random(100);
if (typeof secondaries[i].chance === 'undefined' || secondaryRoll < secondaries[i].chance) {
this.moveHit(target, pokemon, move, secondaries[i], true, isSelf);
}
}
}
if (target && target.hp > 0 && pokemon.hp > 0 && moveData.forceSwitch && this.canSwitch(target.side)) {
hitResult = this.runEvent('DragOut', target, pokemon, move);
if (hitResult) {
target.forceSwitchFlag = true;
} else if (hitResult === false && move.category === 'Status') {
this.add('-fail', target);
}
}
if (move.selfSwitch && pokemon.hp) {
pokemon.switchFlag = move.selfSwitch;
}
return damage;
},
calcRecoilDamage: function (damageDealt, move) {
return this.clampIntRange(Math.round(damageDealt * move.recoil[0] / move.recoil[1]), 1);
},
zMoveTable: {
Poison: "Acid Downpour",
Fighting: "All-Out Pummeling",
Dark: "Black Hole Eclipse",
Grass: "Bloom Doom",
Normal: "Breakneck Blitz",
Rock: "Continental Crush",
Steel: "Corkscrew Crash",
Dragon: "Devastating Drake",
Electric: "Gigavolt Havoc",
Water: "Hydro Vortex",
Fire: "Inferno Overdrive",
Ghost: "Never-Ending Nightmare",
Bug: "Savage Spin-Out",
Psychic: "Shattered Psyche",
Ice: "Subzero Slammer",
Flying: "Supersonic Skystrike",
Ground: "Tectonic Rage",
Fairy: "Twinkle Tackle",
},
getZMove: function (move, pokemon, skipChecks) {
let item = pokemon.getItem();
if (!skipChecks) {
if (pokemon.side.zMoveUsed) return;
if (!item.zMove) return;
if (item.zMoveUser && !item.zMoveUser.includes(pokemon.species)) return;
let moveData = pokemon.getMoveData(move);
if (!moveData || !moveData.pp) return; // Draining the PP of the base move prevents the corresponding Z-move from being used.
}
if (item.zMoveFrom) {
if (move.name === item.zMoveFrom) return item.zMove;
} else if (item.zMove === true) {
if (move.type === item.zMoveType) {
if (move.category === "Status") {
return move.name;
} else {
return this.zMoveTable[move.type];
}
}
}
},
getZMoveCopy: function (move, pokemon) {
move = this.getMove(move);
let zMove;
if (pokemon) {
let item = pokemon.getItem();
if (move.name === item.zMoveFrom) {
return this.getMoveCopy(item.zMove);
}
}
if (move.category === 'Status') {
zMove = this.getMoveCopy(move);
zMove.isZ = true;
return zMove;
}
zMove = this.getMoveCopy(this.zMoveTable[move.type]);
zMove.basePower = move.zMovePower;
zMove.category = move.category;
return zMove;
},
canZMove: function (pokemon) {
if (pokemon.side.zMoveUsed) return;
let item = pokemon.getItem();
if (!item.zMove) return;
if (item.zMoveUser && !item.zMoveUser.includes(pokemon.species)) return;
let atLeastOne = false;
let zMoves = [];
for (let i = 0; i < pokemon.moves.length; i++) {
let move = this.getMove(pokemon.moves[i]);
let zMoveName = this.getZMove(move, pokemon, true) || '';
if (zMoveName) {
let zMove = this.getMove(zMoveName);
if (!zMove.isZ && zMove.category === 'Status') zMoveName = "Z-" + zMoveName;
zMoves.push({move: zMoveName, target: zMove.target});
} else {
zMoves.push(null);
}
if (zMoveName) atLeastOne = true;
}
if (atLeastOne) return zMoves;
},
canMegaEvo: function (pokemon) {
let altForme = pokemon.baseTemplate.otherFormes && this.getTemplate(pokemon.baseTemplate.otherFormes[0]);
let item = pokemon.getItem();
if (altForme && altForme.isMega && altForme.requiredMove && pokemon.moves.includes(toId(altForme.requiredMove)) && !item.zMove) return altForme.species;
if (item.megaEvolves !== pokemon.baseTemplate.baseSpecies || item.megaStone === pokemon.species) return false;
return item.megaStone;
},
runMegaEvo: function (pokemon) {
let template = this.getTemplate(pokemon.canMegaEvo);
let side = pokemon.side;
// Pokémon affected by Sky Drop cannot mega evolve. Enforce it here for now.
let foeActive = side.foe.active;
for (let i = 0; i < foeActive.length; i++) {
if (foeActive[i].volatiles['skydrop'] && foeActive[i].volatiles['skydrop'].source === pokemon) {
return false;
}
}
pokemon.formeChange(template);
pokemon.baseTemplate = template; // mega evolution is permanent
pokemon.details = template.species + (pokemon.level === 100 ? '' : ', L' + pokemon.level) + (pokemon.gender === '' ? '' : ', ' + pokemon.gender) + (pokemon.set.shiny ? ', shiny' : '');
if (pokemon.illusion) {
pokemon.ability = ''; // Don't allow Illusion to wear off
this.add('-mega', pokemon, pokemon.illusion.template.baseSpecies, template.requiredItem);
} else {
this.add('detailschange', pokemon, pokemon.details);
this.add('-mega', pokemon, template.baseSpecies, template.requiredItem);
}
pokemon.setAbility(template.abilities['0']);
pokemon.baseAbility = pokemon.ability;
// Limit one mega evolution
for (let i = 0; i < side.pokemon.length; i++) {
side.pokemon[i].canMegaEvo = false;
}
this.runEvent('AfterMega', pokemon);
return true;
},
isAdjacent: function (pokemon1, pokemon2) {
if (pokemon1.fainted || pokemon2.fainted) return false;
if (pokemon1.side === pokemon2.side) return Math.abs(pokemon1.position - pokemon2.position) === 1;
return Math.abs(pokemon1.position + pokemon2.position + 1 - pokemon1.side.active.length) <= 1;
},
targetTypeChoices: function (targetType) {
return CHOOSABLE_TARGETS.has(targetType);
},
checkAbilities: function (selectedAbilities, defaultAbilities) {
if (!selectedAbilities.length) return true;
let selectedAbility = selectedAbilities.pop();
let isValid = false;
for (let i = 0; i < defaultAbilities.length; i++) {
let defaultAbility = defaultAbilities[i];
if (!defaultAbility) break;
if (defaultAbility.includes(selectedAbility)) {
defaultAbilities.splice(i, 1);
isValid = this.checkAbilities(selectedAbilities, defaultAbilities);
if (isValid) break;
defaultAbilities.splice(i, 0, defaultAbility);
}
}
if (!isValid) selectedAbilities.push(selectedAbility);
return isValid;
},
fastPop: function (list, index) {
// If an array doesn't need to be in order, replacing the
// element at the given index with the removed element
// is much, much faster than using list.splice(index, 1).
let length = list.length;
let element = list[index];
list[index] = list[length - 1];
list.pop();
return element;
},
sampleNoReplace: function (list) {
// The cute code to sample no replace is:
// return list.splice(this.random(length), 1)[0];
// However manually removing the element is twice as fast.
// In fact, we don't even need to keep the array in order, so
// we just replace the removed element with the last element.
let length = list.length;
let index = this.random(length);
return this.fastPop(list, index);
},
checkBattleForme: function (template) {
// If the Pokémon has a Mega or Primal alt forme, that's its preferred battle forme.
// No randomization, no choice. We are just checking its existence.
// Returns a Pokémon template for further details.
if (!template.otherFormes) return null;
let firstForme = this.getTemplate(template.otherFormes[0]);
if (firstForme.isMega || firstForme.isPrimal) return firstForme;
return null;
},
hasMegaEvo: function (template) {
if (!template.otherFormes) return false;
let firstForme = this.getTemplate(template.otherFormes[0]);
return !!firstForme.isMega;
},
getTeam: function (side, team) {
const format = this.getFormat();
const teamGenerator = typeof format.team === 'string' && format.team.startsWith('random') ? format.team + 'Team' : '';
if (!teamGenerator && team) return team;
// Reinitialize the RNG seed to create random teams.
this.seed = this.generateSeed();
this.startingSeed = this.startingSeed.concat(this.seed);
team = this[teamGenerator || 'randomTeam'](side);
// Restore the default seed
this.seed = this.startingSeed.slice(0, 4);
return team;
},
randomCCTeam: function (side) {
let team = [];
let natures = Object.keys(this.data.Natures);
let items = Object.keys(this.data.Items);
let hasDexNumber = {};
let formes = [[], [], [], [], [], []];
// Pick six random pokemon--no repeats, even among formes
// Also need to either normalize for formes or select formes at random
// Unreleased are okay but no CAP
const format = this.getFormat();
let num;
for (let i = 0; i < 6; i++) {
do {
num = this.random(721) + 1;
} while (num in hasDexNumber);
hasDexNumber[num] = i;
}
for (let id in this.data.Pokedex) {
if (!(this.data.Pokedex[id].num in hasDexNumber)) continue;
let template = this.getTemplate(id);
if (template.species !== 'Pichu-Spiky-eared') {
formes[hasDexNumber[template.num]].push(template.species);
}
}
let random6 = this.random6Pokemon();
for (let i = 0; i < 6; i++) {
let species = random6[i];
let template = this.getTemplate(species);
// Random legal item
let item = '';
if (this.gen >= 2) {
do {
item = items[this.random(items.length)];
} while (this.getItem(item).gen > this.gen || this.data.Items[item].isNonstandard);
}
// Make sure forme is legal
if (template.battleOnly || template.requiredItems && !template.requiredItems.some(req => toId(req) === item)) {
template = this.getTemplate(template.baseSpecies);
species = template.name;
}
// Make sure that a base forme does not hold any forme-modifier items.
let itemData = this.getItem(item);
if (itemData.forcedForme && species === this.getTemplate(itemData.forcedForme).baseSpecies) {
do {
item = items[this.random(items.length)];
itemData = this.getItem(item);
} while (itemData.gen > this.gen || itemData.isNonstandard || itemData.forcedForme && species === this.getTemplate(itemData.forcedForme).baseSpecies);
}
// Random ability
let abilities = Object.values(template.abilities);
let ability = this.gen <= 2 ? 'None' : abilities[this.random(abilities.length)];
// Move Assignment Based on Format
let moves;
if (format.id === "metronomechallengecup") {
moves = ['metronome'];
} else {
let pool = ['struggle'];
if (species === 'Smeargle') {
pool = Object.keys(this.data.Movedex).filter(moveid => !(moveid in {'chatter':1, 'struggle':1, 'paleowave':1, 'shadowstrike':1, 'magikarpsrevenge':1}));
} else if (template.learnset) {
pool = Object.keys(template.learnset);
if (template.species.substr(0, 6) === 'Rotom-') {
pool = Array.from(new Set(pool.concat(Object.keys(this.getTemplate(template.baseSpecies).learnset))));
}
} else {
const learnset = this.getTemplate(template.baseSpecies).learnset;
pool = Object.keys(learnset);
}
if (pool.length <= 4) {
moves = pool;
} else {
moves = [this.sampleNoReplace(pool), this.sampleNoReplace(pool), this.sampleNoReplace(pool), this.sampleNoReplace(pool)];
}
}
// Random EVs
let evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
let s = ["hp", "atk", "def", "spa", "spd", "spe"];
let evpool = 510;
do {
let x = s[this.random(s.length)];
let y = this.random(Math.min(256 - evs[x], evpool + 1));
evs[x] += y;
evpool -= y;
} while (evpool > 0);
// Random IVs
let ivs = {hp: this.random(32), atk: this.random(32), def: this.random(32), spa: this.random(32), spd: this.random(32), spe: this.random(32)};
// Random nature
let nature = natures[this.random(natures.length)];
// Level balance--calculate directly from stats rather than using some silly lookup table
let mbstmin = 1307; // Sunkern has the lowest modified base stat total, and that total is 807
let stats = template.baseStats;
// Modified base stat total assumes 31 IVs, 85 EVs in every stat
let mbst = (stats["hp"] * 2 + 31 + 21 + 100) + 10;
mbst += (stats["atk"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["def"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["spa"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["spd"] * 2 + 31 + 21 + 100) + 5;
mbst += (stats["spe"] * 2 + 31 + 21 + 100) + 5;
let level = Math.floor(100 * mbstmin / mbst); // Initial level guess will underestimate
while (level < 100) {
mbst = Math.floor((stats["hp"] * 2 + 31 + 21 + 100) * level / 100 + 10);
mbst += Math.floor(((stats["atk"] * 2 + 31 + 21 + 100) * level / 100 + 5) * level / 100); // Since damage is roughly proportional to level
mbst += Math.floor((stats["def"] * 2 + 31 + 21 + 100) * level / 100 + 5);
mbst += Math.floor(((stats["spa"] * 2 + 31 + 21 + 100) * level / 100 + 5) * level / 100);
mbst += Math.floor((stats["spd"] * 2 + 31 + 21 + 100) * level / 100 + 5);
mbst += Math.floor((stats["spe"] * 2 + 31 + 21 + 100) * level / 100 + 5);
if (mbst >= mbstmin) break;
level++;
}
// Random gender--already handled by PS
// Random happiness
let happiness = this.random(256);
// Random shininess
let shiny = !this.random(1024);
team.push({
name: template.baseSpecies,
species: template.species,
item: item,
ability: ability,
moves: moves,
evs: evs,
ivs: ivs,
nature: nature,
level: level,
happiness: happiness,
shiny: shiny,
});
}
return team;
},
random6Pokemon: function () {
// Pick six random pokemon--no repeats, even among formes
// Also need to either normalize for formes or select formes at random
// Unreleased are okay but no CAP
let last = [0, 151, 251, 386, 493, 649, 721, 802][this.gen];
let hasDexNumber = {};
for (let i = 0; i < 6; i++) {
let num;
do {
num = this.random(last) + 1;
} while (num in hasDexNumber);
hasDexNumber[num] = i;
}
let formes = [[], [], [], [], [], []];
for (let id in this.data.Pokedex) {
if (!(this.data.Pokedex[id].num in hasDexNumber)) continue;
let template = this.getTemplate(id);
if (template.gen <= this.gen && template.learnset && template.species !== 'Pichu-Spiky-eared' && template.species.substr(0, 8) !== 'Pikachu-') {
formes[hasDexNumber[template.num]].push(template.species);
}
}
let sixPokemon = [];
for (let i = 0; i < 6; i++) {
if (!formes[i].length) {
// console.log("Could not find pokemon " + i);
// for (var k in hasDexNumber) {
// if (hasDexNumber[k] === i) {
// console.log("dexNumber was " + k);
// console.log("dex found: " + JSON.stringify(Object.values(this.data.Pokedex).filter(t => t.num == Number(k)).map(t => t.species)));
// }
// }
throw new Error("Invalid pokemon gen " + this.gen + ": " + JSON.stringify(formes) + " numbers " + JSON.stringify(hasDexNumber));
}
sixPokemon.push(formes[i][this.random(formes[i].length)]);
}
return sixPokemon;
},
randomHCTeam: function (side) {
let team = [];
let itemPool = Object.keys(this.data.Items);
let abilityPool = Object.keys(this.data.Abilities);
let movePool = Object.keys(this.data.Movedex);
let naturePool = Object.keys(this.data.Natures);
let random6 = this.random6Pokemon();
for (let i = 0; i < 6; i++) {
// Choose forme
let template = this.getTemplate(random6[i]);
// Random unique item
let item = '';
if (this.gen >= 2) {
do {
item = this.sampleNoReplace(itemPool);
} while (this.getItem(item).gen > this.gen || this.data.Items[item].isNonstandard);
}
// Random unique ability
let ability = 'None';
if (this.gen >= 3) {
do {
ability = this.sampleNoReplace(abilityPool);
} while (this.getAbility(ability).gen > this.gen || this.data.Abilities[ability].isNonstandard);
}
// Random unique moves
let m = [];
do {
let moveid = this.sampleNoReplace(movePool);
if (this.getMove(moveid).gen <= this.gen && !this.data.Movedex[moveid].isNonstandard && (moveid === 'hiddenpower' || moveid.substr(0, 11) !== 'hiddenpower')) {
m.push(moveid);
}
} while (m.length < 4);
// Random EVs
let evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
let s = ['hp', 'atk', 'def', 'spa', 'spd', 'spe'];
let evpool = 510;
do {
let x = s[this.random(s.length)];
let y = this.random(Math.min(256 - evs[x], evpool + 1));
evs[x] += y;
evpool -= y;
} while (evpool > 0);
// Random IVs
let ivs = {hp: this.random(32), atk: this.random(32), def: this.random(32), spa: this.random(32), spd: this.random(32), spe: this.random(32)};
// Random nature
let nature = naturePool[this.random(naturePool.length)];
// Level balance
let mbstmin = 1307;
let stats = template.baseStats;
let mbst = (stats['hp'] * 2 + 31 + 21 + 100) + 10;
mbst += (stats['atk'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['def'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['spa'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['spd'] * 2 + 31 + 21 + 100) + 5;
mbst += (stats['spe'] * 2 + 31 + 21 + 100) + 5;
let level = Math.floor(100 * mbstmin / mbst);
while (level < 100) {
mbst = Math.floor((stats['hp'] * 2 + 31 + 21 + 100) * level / 100 + 10);
mbst += Math.floor(((stats['atk'] * 2 + 31 + 21 + 100) * level / 100 + 5) * level / 100);
mbst += Math.floor((stats['def'] * 2 + 31 + 21 + 100) * level / 100 + 5);
mbst += Math.floor(((stats['spa'] * 2 + 31 + 21 + 100) * level / 100 + 5) * level / 100);
mbst += Math.floor((stats['spd'] * 2 + 31 + 21 + 100) * level / 100 + 5);
mbst += Math.floor((stats['spe'] * 2 + 31 + 21 + 100) * level / 100 + 5);
if (mbst >= mbstmin) break;
level++;
}
// Random happiness
let happiness = this.random(256);
// Random shininess
let shiny = !this.random(1024);
team.push({
name: template.baseSpecies,
species: template.species,
item: item,
ability: ability,
moves: m,
evs: evs,
ivs: ivs,
nature: nature,
level: level,
happiness: happiness,
shiny: shiny,
});
}
return team;
},
queryMoves: function (moves, hasType, hasAbility, movePool) {
// This is primarily a helper function for random setbuilder functions.
let counter = {
Physical: 0, Special: 0, Status: 0, damage: 0, recovery: 0, stab: 0, inaccurate: 0, priority: 0, recoil: 0, drain: 0,
adaptability: 0, bite: 0, contrary: 0, hustle: 0, ironfist: 0, serenegrace: 0, sheerforce: 0, skilllink: 0, technician: 0,
physicalsetup: 0, specialsetup: 0, mixedsetup: 0, defensesetup: 0, speedsetup: 0, physicalpool: 0, specialpool: 0,
damagingMoves: [],
damagingMoveIndex: {},
setupType: '',
};
for (let type in Tools.data.TypeChart) {
counter[type] = 0;
}
if (!moves || !moves.length) return counter;
if (!hasType) hasType = {};
if (!hasAbility) hasAbility = {};
if (!movePool) movePool = [];
// Moves that heal a fixed amount:
let RecoveryMove = {
healorder: 1, milkdrink: 1, recover: 1, roost: 1, slackoff: 1, softboiled: 1,
};
// Moves which drop stats:
let ContraryMove = {
closecombat: 1, leafstorm: 1, overheat: 1, superpower: 1, vcreate: 1,
};
// Moves that boost Attack:
let PhysicalSetup = {
bellydrum:1, bulkup:1, coil:1, curse:1, dragondance:1, honeclaws:1, howl:1, poweruppunch:1, shiftgear:1, swordsdance:1,
};
// Moves which boost Special Attack:
let SpecialSetup = {
calmmind:1, chargebeam:1, geomancy:1, nastyplot:1, quiverdance:1, tailglow:1,
};
// Moves which boost Attack AND Special Attack:
let MixedSetup = {
conversion: 1, growth:1, shellsmash:1, workup:1,
};
// Moves which boost Defense and/or Special Defense:
let DefenseSetup = {
cosmicpower:1, cottonguard:1, defendorder:1,
};
// Moves which boost Speed:
let SpeedSetup = {
agility:1, autotomize:1, rockpolish:1,
};
// Moves that shouldn't be the only STAB moves:
let NoStab = {
aquajet:1, bounce:1, explosion:1, fakeout:1, flamecharge:1, iceshard:1, pursuit:1, quickattack:1, skyattack:1,
chargebeam:1, clearsmog:1, eruption:1, vacuumwave:1, waterspout:1,
};
// Iterate through all moves we've chosen so far and keep track of what they do:
for (let k = 0; k < moves.length; k++) {
let move = this.getMove(moves[k]);
let moveid = move.id;
let movetype = move.type;
if (moveid === 'judgment' || moveid === 'multiattack') movetype = Object.keys(hasType)[0];
if (move.damage || move.damageCallback) {
// Moves that do a set amount of damage:
counter['damage']++;
counter.damagingMoves.push(move);
counter.damagingMoveIndex[moveid] = k;
} else {
// Are Physical/Special/Status moves:
counter[move.category]++;
}
// Moves that have a low base power:
if (moveid === 'lowkick' || (move.basePower && move.basePower <= 60 && moveid !== 'rapidspin')) counter['technician']++;
// Moves that hit up to 5 times:
if (move.multihit && move.multihit[1] === 5) counter['skilllink']++;
if (move.recoil) counter['recoil']++;
if (move.drain) counter['drain']++;
// Moves which have a base power, but aren't super-weak like Rapid Spin:
if (move.basePower > 30 || move.multihit || move.basePowerCallback || moveid === 'naturepower') {
counter[movetype]++;
if (hasType[movetype]) {
counter['adaptability']++;
// STAB:
// Certain moves aren't acceptable as a Pokemon's only STAB attack
if (!(moveid in NoStab) && (moveid !== 'hiddenpower' || Object.keys(hasType).length === 1)) counter['stab']++;
}
if (move.priority === 0 && (hasAbility['Protean'] || moves.includes('conversion')) && !(moveid in NoStab)) counter['stab']++;
if (move.category === 'Physical') counter['hustle']++;
if (movetype === 'Normal' && !(moveid in NoStab)) {
if (hasAbility['Aerilate'] || hasAbility['Pixilate'] || hasAbility['Refrigerate']) counter['stab']++;
}
if (move.flags['bite']) counter['bite']++;
if (move.flags['punch']) counter['ironfist']++;
counter.damagingMoves.push(move);
counter.damagingMoveIndex[moveid] = k;
}
// Moves with secondary effects:
if (move.secondary) {
counter['sheerforce']++;
if (move.secondary.chance >= 20) counter['serenegrace']++;
}
// Moves with low accuracy:
if (move.accuracy && move.accuracy !== true && move.accuracy < 90) counter['inaccurate']++;
// Moves with non-zero priority:
if (move.priority !== 0) counter['priority']++;
// Moves that change stats:
if (RecoveryMove[moveid]) counter['recovery']++;
if (ContraryMove[moveid]) counter['contrary']++;
if (PhysicalSetup[moveid]) counter['physicalsetup']++;
if (SpecialSetup[moveid]) counter['specialsetup']++;
if (MixedSetup[moveid]) counter['mixedsetup']++;
if (DefenseSetup[moveid]) counter['defensesetup']++;
if (SpeedSetup[moveid]) counter['speedsetup']++;
}
// Keep track of the available moves
for (let i = 0; i < movePool.length; i++) {
let move = this.getMove(movePool[i]);
if (move.category === 'Physical') counter['physicalpool']++;
if (move.category === 'Special') counter['specialpool']++;
}
// Choose a setup type:
if (counter['mixedsetup']) {
counter.setupType = 'Mixed';
} else if (counter['physicalsetup'] || counter['specialsetup']) {
let physical = counter.Physical + counter['physicalpool'];
let special = counter.Special + counter['specialpool'];
if (counter['physicalsetup'] && counter['specialsetup']) {
if (physical === special) {
counter.setupType = counter.Physical > counter.Special ? 'Physical' : 'Special';
} else {
counter.setupType = physical > special ? 'Physical' : 'Special';
}
} else if (counter['physicalsetup'] && physical >= 1) {
if (physical >= 2 || moves.includes('rest') && moves.includes('sleeptalk')) {
counter.setupType = 'Physical';
}
} else if (counter['specialsetup'] && special >= 1) {
if (special >= 2 || moves.includes('rest') && moves.includes('sleeptalk')) {
counter.setupType = 'Special';
}
}
}
return counter;
},
randomSet: function (template, slot, teamDetails) {
if (slot === undefined) slot = 1;
let baseTemplate = (template = this.getTemplate(template));
let species = template.species;
if (!template.exists || (!template.randomBattleMoves && !template.learnset)) {
// GET IT? UNOWN? BECAUSE WE CAN'T TELL WHAT THE POKEMON IS
template = this.getTemplate('unown');
let err = new Error('Template incompatible with random battles: ' + species);
require('../crashlogger')(err, 'The randbat set generator');
}
if (typeof teamDetails !== 'object') teamDetails = {megaStone: teamDetails};
if (template.battleOnly) {
// Only change the species. The template has custom moves, and may have different typing and requirements.
species = template.baseSpecies;
}
let battleForme = this.checkBattleForme(template);
if (battleForme && battleForme.randomBattleMoves && (battleForme.isMega ? !teamDetails.megaStone : this.random(2))) {
template = this.getTemplate(template.otherFormes.length >= 2 ? template.otherFormes[this.random(template.otherFormes.length)] : template.otherFormes[0]);
}
let movePool = (template.randomBattleMoves ? template.randomBattleMoves.slice() : Object.keys(template.learnset));
let moves = [];
let ability = '';
let item = '';
let evs = {
hp: 85,
atk: 85,
def: 85,
spa: 85,
spd: 85,
spe: 85,
};
let ivs = {
hp: 31,
atk: 31,
def: 31,
spa: 31,
spd: 31,
spe: 31,
};
let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) {
hasType[template.types[1]] = true;
}
let hasAbility = {};
hasAbility[template.abilities[0]] = true;
if (template.abilities[1]) {
hasAbility[template.abilities[1]] = true;
}
if (template.abilities['H']) {
hasAbility[template.abilities['H']] = true;
}
let availableHP = 0;
for (let i = 0, len = movePool.length; i < len; i++) {
if (movePool[i].substr(0, 11) === 'hiddenpower') availableHP++;
}
// These moves can be used even if we aren't setting up to use them:
let SetupException = {
closecombat:1, extremespeed:1, suckerpunch:1, superpower:1,
dracometeor:1, leafstorm:1, overheat:1,
};
let counterAbilities = {
'Adaptability':1, 'Contrary':1, 'Hustle':1, 'Iron Fist':1, 'Sheer Force':1, 'Skill Link':1,
};
let ateAbilities = {
'Aerilate':1, 'Pixilate':1, 'Refrigerate':1,
};
let hasMove, counter;
do {
// Keep track of all moves we have:
hasMove = {};
for (let k = 0; k < moves.length; k++) {
if (moves[k].substr(0, 11) === 'hiddenpower') {
hasMove['hiddenpower'] = true;
} else {
hasMove[moves[k]] = true;
}
}
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
let moveid = this.sampleNoReplace(movePool);
if (moveid.substr(0, 11) === 'hiddenpower') {
availableHP--;
if (hasMove['hiddenpower']) continue;
hasMove['hiddenpower'] = true;
} else {
hasMove[moveid] = true;
}
moves.push(moveid);
}
counter = this.queryMoves(moves, hasType, hasAbility, movePool);
// Iterate through the moves again, this time to cull them:
for (let k = 0; k < moves.length; k++) {
let moveid = moves[k];
let move = this.getMove(moveid);
let rejected = false;
let isSetup = false;
switch (moveid) {
// Not very useful without their supporting moves
case 'batonpass':
if (!counter.setupType && !counter['speedsetup'] && !hasMove['substitute'] && !hasMove['wish'] && !hasAbility['Speed Boost']) rejected = true;
break;
case 'focuspunch':
if (!hasMove['substitute'] || counter.damagingMoves.length < 2) rejected = true;
break;
case 'perishsong':
if (!hasMove['protect']) rejected = true;
break;
case 'rest': {
if (movePool.includes('sleeptalk')) rejected = true;
break;
}
case 'sleeptalk':
if (!hasMove['rest']) rejected = true;
if (movePool.length > 1) {
let rest = movePool.indexOf('rest');
if (rest >= 0) this.fastPop(movePool, rest);
}
break;
case 'storedpower':
if (!counter.setupType && !hasMove['cosmicpower']) rejected = true;
break;
// Set up once and only if we have the moves for it
case 'bellydrum': case 'bulkup': case 'coil': case 'curse': case 'dragondance': case 'honeclaws': case 'swordsdance':
if (counter.setupType !== 'Physical' || counter['physicalsetup'] > 1) {
if (!hasMove['growth'] || hasMove['sunnyday']) rejected = true;
}
if (counter.Physical + counter['physicalpool'] < 2 && !hasMove['batonpass'] && (!hasMove['rest'] || !hasMove['sleeptalk'])) rejected = true;
isSetup = true;
break;
case 'calmmind': case 'geomancy': case 'nastyplot': case 'quiverdance': case 'tailglow':
if (counter.setupType !== 'Special' || counter['specialsetup'] > 1) rejected = true;
if (counter.Special + counter['specialpool'] < 2 && !hasMove['batonpass'] && (!hasMove['rest'] || !hasMove['sleeptalk'])) rejected = true;
isSetup = true;
break;
case 'growth': case 'shellsmash': case 'workup':
if (counter.setupType !== 'Mixed' || counter['mixedsetup'] > 1) rejected = true;
if (counter.damagingMoves.length + counter['physicalpool'] + counter['specialpool'] < 2 && !hasMove['batonpass']) rejected = true;
if (moveid === 'growth' && !hasMove['sunnyday']) rejected = true;
isSetup = true;
break;
case 'agility': case 'autotomize': case 'rockpolish':
if (counter.damagingMoves.length < 2 && !counter.setupType && !hasMove['batonpass']) rejected = true;
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
if (!counter.setupType) isSetup = true;
break;
case 'flamecharge':
if (counter.damagingMoves.length < 3 && !counter.setupType && !hasMove['batonpass']) rejected = true;
if (hasMove['dracometeor'] || hasMove['overheat']) rejected = true;
break;
case 'conversion':
if (teamDetails.zMove || hasMove['triattack']) rejected = true;
break;
// Bad after setup
case 'circlethrow': case 'dragontail':
if (counter.setupType && ((!hasMove['rest'] && !hasMove['sleeptalk']) || hasMove['stormthrow'])) rejected = true;
if (!!counter['speedsetup'] || hasMove['encore'] || hasMove['raindance'] || hasMove['roar'] || hasMove['whirlwind']) rejected = true;
break;
case 'defog':
if (counter.setupType || hasMove['spikes'] || (hasMove['rest'] && hasMove['sleeptalk']) || teamDetails.hazardClear) rejected = true;
break;
case 'fakeout': case 'superfang':
if (counter.setupType || hasMove['substitute'] || hasMove['switcheroo'] || hasMove['trick']) rejected = true;
break;
case 'foulplay':
if (counter.setupType || !!counter['speedsetup'] || counter['Dark'] > 2 || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
break;
case 'haze': case 'spikes': case 'waterspout':
if (counter.setupType || !!counter['speedsetup'] || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
break;
case 'healbell':
if (counter['speedsetup']) rejected = true;
break;
case 'healingwish': case 'memento':
if (counter.setupType || !!counter['recovery'] || hasMove['substitute']) rejected = true;
break;
case 'nightshade': case 'seismictoss':
if (counter.stab || counter.setupType || counter.damagingMoves.length > 2) rejected = true;
break;
case 'protect':
if (counter.setupType && (hasAbility['Guts'] || hasAbility['Speed Boost']) && !hasMove['batonpass']) rejected = true;
if ((hasMove['lightscreen'] && hasMove['reflect']) || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
break;
case 'pursuit':
if (counter.setupType || (hasMove['rest'] && hasMove['sleeptalk']) || (hasMove['knockoff'] && !hasType['Dark'])) rejected = true;
break;
case 'rapidspin':
if (counter.setupType || teamDetails.hazardClear) rejected = true;
break;
case 'roar': case 'whirlwind':
if (counter.setupType || hasMove['dragontail']) rejected = true;
break;
case 'stealthrock':
if (counter.setupType || !!counter['speedsetup'] || hasMove['rest'] || teamDetails.stealthRock) rejected = true;
break;
case 'switcheroo': case 'trick':
if (counter.Physical + counter.Special < 3 || counter.setupType) rejected = true;
if (hasMove['acrobatics'] || hasMove['lightscreen'] || hasMove['reflect'] || hasMove['suckerpunch'] || hasMove['trickroom']) rejected = true;
break;
case 'toxicspikes':
if (counter.setupType || teamDetails.toxicSpikes) rejected = true;
break;
case 'trickroom':
if (counter.setupType || !!counter['speedsetup'] || counter.damagingMoves.length < 2) rejected = true;
if (hasMove['lightscreen'] || hasMove['reflect']) rejected = true;
break;
case 'uturn':
if (counter.setupType || !!counter['speedsetup'] || hasMove['batonpass']) rejected = true;
if (hasType['Bug'] && counter.stab < 2 && counter.damagingMoves.length > 2 && !hasAbility['Adaptability'] && !hasMove['technoblast']) rejected = true;
break;
case 'voltswitch':
if (counter.setupType || !!counter['speedsetup'] || hasMove['batonpass'] || hasMove['magnetrise'] || hasMove['uturn']) rejected = true;
if (hasMove['nuzzle'] && hasMove['thunderbolt']) rejected = true;
break;
// Bit redundant to have both
// Attacks:
case 'bugbite': case 'bugbuzz': case 'signalbeam':
if (hasMove['uturn'] && !counter.setupType) rejected = true;
break;
case 'lunge':
if (hasMove['leechlife']) rejected = true;
break;
case 'darkpulse':
if (hasMove['shadowball']) rejected = true;
if ((hasMove['crunch'] || hasMove['hyperspacefury']) && counter.setupType !== 'Special') rejected = true;
break;
case 'suckerpunch':
if (counter['Dark'] > 2 || (counter.setupType === 'Special' && hasType['Dark'] && counter.stab < 2)) rejected = true;
if (counter['Dark'] > 1 && !hasType['Dark']) rejected = true;
if (counter.damagingMoves.length < 2 || hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'dragonclaw':
if (hasMove['outrage'] || hasMove['dragontail']) rejected = true;
break;
case 'dracometeor':
if (counter.setupType === 'Physical' && hasMove['outrage']) rejected = true;
break;
case 'dragonpulse': case 'spacialrend':
if (hasMove['dracometeor'] || hasMove['outrage']) rejected = true;
break;
case 'outrage':
if (hasMove['dracometeor'] && counter.damagingMoves.length < 3) rejected = true;
break;
case 'chargebeam':
if (hasMove['thunderbolt'] && counter.Special < 3) rejected = true;
break;
case 'thunder':
if (hasMove['thunderbolt'] && !hasMove['raindance']) rejected = true;
break;
case 'thunderbolt':
if (hasMove['discharge'] || (hasMove['raindance'] && hasMove['thunder']) || (hasMove['voltswitch'] && hasMove['wildcharge'])) rejected = true;
if (!counter.setupType && !counter['speedsetup'] && hasMove['voltswitch'] && template.types.length > 1 && !counter[template.types.find(type => type !== 'Electric')]) rejected = true;
break;
case 'dazzlinggleam':
if (hasMove['playrough'] && counter.setupType !== 'Special') rejected = true;
break;
case 'drainingkiss':
if (hasMove['dazzlinggleam'] || counter.setupType !== 'Special') rejected = true;
break;
case 'aurasphere': case 'focusblast':
if ((hasMove['closecombat'] || hasMove['superpower']) && counter.setupType !== 'Special') rejected = true;
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'drainpunch':
if (!hasMove['bulkup'] && (hasMove['closecombat'] || hasMove['highjumpkick'])) rejected = true;
if (hasMove['focusblast'] || hasMove['superpower']) rejected = true;
break;
case 'closecombat': case 'highjumpkick':
if ((hasMove['aurasphere'] || hasMove['focusblast'] || movePool.includes('aurasphere')) && counter.setupType === 'Special') rejected = true;
if (hasMove['bulkup'] && hasMove['drainpunch']) rejected = true;
break;
case 'machpunch':
if (hasType['Fighting'] && counter.stab < 2 && !hasAbility['Technician']) rejected = true;
break;
case 'stormthrow':
if (hasMove['circlethrow'] && hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'superpower':
if (counter['Fighting'] > 1 && counter.setupType) rejected = true;
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'vacuumwave':
if ((hasMove['closecombat'] || hasMove['machpunch']) && counter.setupType !== 'Special') rejected = true;
break;
case 'blazekick':
if (hasMove['flamethrower'] && counter.setupType !== 'Physical') rejected = true;
break;
case 'fierydance': case 'firefang': case 'flamethrower':
if ((hasMove['fireblast'] && counter.setupType !== 'Physical') || hasMove['overheat']) rejected = true;
break;
case 'fireblast':
if ((hasMove['flareblitz'] || hasMove['lavaplume']) && !counter.setupType && !counter['speedsetup']) rejected = true;
break;
case 'firepunch': case 'sacredfire':
if (hasMove['fireblast'] || hasMove['flareblitz']) rejected = true;
break;
case 'lavaplume':
if (hasMove['fireblast'] && (counter.setupType || !!counter['speedsetup'])) rejected = true;
break;
case 'overheat':
if (hasMove['lavaplume'] || counter.setupType === 'Special') rejected = true;
break;
case 'acrobatics':
if (hasMove['hurricane'] && counter.setupType !== 'Physical') rejected = true;
break;
case 'airslash': case 'oblivionwing':
if (hasMove['acrobatics'] || hasMove['bravebird'] || hasMove['hurricane']) rejected = true;
break;
case 'shadowball':
if (hasMove['hex'] && hasMove['willowisp']) rejected = true;
break;
case 'shadowclaw':
if (hasMove['phantomforce'] || (hasMove['shadowball'] && counter.setupType !== 'Physical') || hasMove['shadowsneak']) rejected = true;
break;
case 'shadowsneak':
if (hasType['Ghost'] && template.types.length > 1 && counter.stab < 2) rejected = true;
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'solarbeam':
if ((!hasAbility['Drought'] && !hasMove['sunnyday']) || hasMove['gigadrain'] || hasMove['leafstorm']) rejected = true;
break;
case 'gigadrain':
if (hasMove['petaldance'] || !counter.setupType && hasMove['leafstorm']) rejected = true;
break;
case 'leafblade': case 'seedbomb': case 'woodhammer':
if (hasMove['gigadrain'] && counter.setupType !== 'Physical') rejected = true;
break;
case 'leafstorm':
if (counter['Grass'] > 1 && counter.setupType) rejected = true;
break;
case 'bonemerang': case 'precipiceblades':
if (hasMove['earthquake']) rejected = true;
break;
case 'earthpower':
if (hasMove['earthquake'] && counter.setupType !== 'Special') rejected = true;
break;
case 'icebeam':
if (hasMove['blizzard'] || hasMove['freezedry']) rejected = true;
break;
case 'iceshard':
if (hasMove['freezedry']) rejected = true;
break;
case 'bodyslam':
if (hasMove['glare'] || hasMove['headbutt']) rejected = true;
break;
case 'endeavor':
if (slot > 0) rejected = true;
break;
case 'explosion':
if (counter.setupType || (hasAbility['Refrigerate'] && hasMove['freezedry']) || hasMove['wish']) rejected = true;
break;
case 'extremespeed':
if (counter.setupType !== 'Physical' && hasMove['vacuumwave']) rejected = true;
break;
case 'facade':
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'hiddenpower':
if (hasMove['rest'] || !counter.stab && counter.damagingMoves.length < 2) rejected = true;
break;
case 'hypervoice':
if (hasMove['naturepower'] || hasMove['return']) rejected = true;
if (hasAbility['Liquid Voice'] && hasMove['scald']) rejected = true;
break;
case 'judgment':
if (counter.setupType !== 'Special' && counter.stab > 1) rejected = true;
break;
case 'quickattack':
if (hasType['Normal'] && counter['Normal'] > 1 && template.types.length > 1 && counter.stab < 2) rejected = true;
break;
case 'return': case 'rockclimb':
if (hasMove['bodyslam'] || hasMove['doubleedge']) rejected = true;
break;
case 'weatherball':
if (!hasMove['raindance'] && !hasMove['sunnyday']) rejected = true;
break;
case 'acidspray':
if (hasMove['sludgebomb'] || counter.Special < 2) rejected = true;
break;
case 'poisonjab':
if (hasMove['gunkshot']) rejected = true;
break;
case 'sludgewave':
if (hasMove['poisonjab']) rejected = true;
break;
case 'psychic':
if (hasMove['psyshock'] || hasMove['storedpower']) rejected = true;
break;
case 'psychocut': case 'zenheadbutt':
if ((hasMove['psychic'] || hasMove['psyshock']) && counter.setupType !== 'Physical') rejected = true;
break;
case 'psyshock':
if (movePool.length > 1) {
let psychic = movePool.indexOf('psychic');
if (psychic >= 0) this.fastPop(movePool, psychic);
}
break;
case 'headsmash':
if (hasMove['stoneedge']) rejected = true;
break;
case 'rockblast': case 'rockslide':
if (hasMove['headsmash'] || hasMove['stoneedge']) rejected = true;
break;
case 'bulletpunch':
if (hasType['Steel'] && counter.stab < 2 && !hasAbility['Adaptability'] && !hasAbility['Technician']) rejected = true;
break;
case 'flashcannon':
if (hasMove['ironhead']) rejected = true;
break;
case 'hydropump':
if (hasMove['razorshell'] || hasMove['scald'] || hasMove['waterfall'] || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
break;
case 'originpulse': case 'surf':
if (hasMove['hydropump'] || hasMove['scald']) rejected = true;
break;
case 'scald':
if (hasMove['liquidation'] || hasMove['waterfall'] || hasMove['waterpulse']) rejected = true;
break;
// Status:
case 'raindance':
if (counter.Physical + counter.Special < 2 || hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
if (!hasType['Water'] && !hasMove['thunder']) rejected = true;
break;
case 'sunnyday':
if (counter.Physical + counter.Special < 2 || hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
if (!hasAbility['Chlorophyll'] && !hasAbility['Flower Gift'] && !hasMove['solarbeam']) rejected = true;
if (rejected && movePool.length > 1) {
let solarbeam = movePool.indexOf('solarbeam');
if (solarbeam >= 0) this.fastPop(movePool, solarbeam);
if (movePool.length > 1) {
let weatherball = movePool.indexOf('weatherball');
if (weatherball >= 0) this.fastPop(movePool, weatherball);
}
}
break;
case 'stunspore': case 'thunderwave':
if (counter.setupType || !!counter['speedsetup'] || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
if (hasMove['discharge'] || hasMove['gyroball'] || hasMove['spore'] || hasMove['toxic'] || hasMove['trickroom'] || hasMove['yawn']) rejected = true;
break;
case 'toxic':
if (counter.setupType || hasMove['flamecharge'] || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
if (hasMove['hypnosis'] || hasMove['sleeppowder'] || hasMove['willowisp'] || hasMove['yawn']) rejected = true;
break;
case 'willowisp':
if (hasMove['scald']) rejected = true;
break;
case 'moonlight': case 'painsplit': case 'recover': case 'roost': case 'softboiled': case 'synthesis':
if (hasMove['rest'] || hasMove['wish']) rejected = true;
break;
case 'safeguard':
if (hasMove['destinybond']) rejected = true;
break;
case 'substitute':
if (hasMove['dracometeor'] || (hasMove['leafstorm'] && !hasAbility['Contrary']) || hasMove['pursuit'] || hasMove['rest'] || hasMove['taunt'] || hasMove['uturn'] || hasMove['voltswitch']) rejected = true;
break;
}
// Increased/decreased priority moves are unneeded with moves that boost only speed
if (move.priority !== 0 && (!!counter['speedsetup'] || hasMove['copycat'])) {
rejected = true;
}
// Certain Pokemon should always have a recovery move
if (!counter.recovery && template.baseStats.hp >= 165 && movePool.includes('wish')) {
if (move.category === 'Status' || !hasType[move.type] && !move.damage) rejected = true;
}
if (template.nfe && !isSetup && !counter.recovery && !!counter['Status'] && (movePool.includes('recover') || movePool.includes('roost'))) {
if (move.category === 'Status' || !hasType[move.type]) rejected = true;
}
// This move doesn't satisfy our setup requirements:
if ((move.category === 'Physical' && counter.setupType === 'Special') || (move.category === 'Special' && counter.setupType === 'Physical')) {
// Reject STABs last in case the setup type changes later on
if (!SetupException[move.id] && (!hasType[move.type] || counter.stab > 1 || counter[move.category] < 2)) rejected = true;
}
if (counter.setupType && !isSetup && counter.setupType !== 'Mixed' && move.category !== counter.setupType && counter[counter.setupType] < 2 && !hasMove['batonpass'] && moveid !== 'rest' && moveid !== 'sleeptalk') {
// Mono-attacking with setup and RestTalk is allowed
// Reject Status moves only if there is nothing else to reject
if (move.category !== 'Status' || counter[counter.setupType] + counter.Status > 3 && counter['physicalsetup'] + counter['specialsetup'] < 2) rejected = true;
}
if (counter.setupType === 'Special' && move.id === 'hiddenpower' && template.types.length > 1 && counter['Special'] <= 2 && !hasType[move.type] && !counter['Physical'] && counter['specialpool']) {
// Hidden Power isn't good enough
rejected = true;
}
// Pokemon should have moves that benefit their Ability/Type/Weather, as well as moves required by its forme
if ((hasType['Bug'] && !hasMove['batonpass'] && (movePool.includes('megahorn') || movePool.includes('pinmissile') || (hasType['Flying'] && !hasMove['hurricane'] && movePool.includes('bugbuzz')))) ||
(hasType['Dark'] && hasMove['suckerpunch'] && counter.stab < template.types.length) ||
(hasType['Dragon'] && !counter['Dragon'] && !hasAbility['Aerilate'] && !hasAbility['Pixilate'] && !hasMove['rest'] && !hasMove['sleeptalk']) ||
(hasType['Electric'] && !counter['Electric']) ||
(hasType['Fighting'] && !counter['Fighting'] && (counter.setupType || !counter['Status'])) ||
(hasType['Fire'] && !counter['Fire']) ||
(hasType['Ground'] && !counter['Ground'] && (counter.setupType || counter['speedsetup'] || hasMove['raindance'] || !counter['Status'])) ||
(hasType['Ice'] && !counter['Ice'] && !hasAbility['Refrigerate']) ||
(hasType['Psychic'] && !!counter['Psychic'] && !hasType['Flying'] && !hasAbility['Pixilate'] && template.types.length > 1 && counter.stab < 2) ||
(hasType['Water'] && !counter['Water'] && (!hasType['Ice'] || !counter['Ice']) && !hasAbility['Protean']) ||
((hasAbility['Adaptability'] && !counter.setupType && template.types.length > 1 && (!counter[template.types[0]] || !counter[template.types[1]])) ||
((hasAbility['Aerilate'] || hasAbility['Pixilate'] || hasAbility['Refrigerate']) && !counter['Normal']) ||
(hasAbility['Contrary'] && !counter['contrary'] && template.species !== 'Shuckle') ||
(hasAbility['Dark Aura'] && !counter['Dark']) ||
(hasAbility['Electric Surge'] && !counter['Electric']) ||
(hasAbility['Gale Wings'] && !counter['Flying']) ||
(hasAbility['Grassy Surge'] && !counter['Grass']) ||
(hasAbility['Guts'] && hasType['Normal'] && movePool.includes('facade')) ||
(hasAbility['Psychic Surge'] && !counter['Psychic']) ||
(hasAbility['Slow Start'] && movePool.includes('substitute')) ||
(hasAbility['Stance Change'] && !counter.setupType && movePool.includes('kingsshield')) ||
(hasAbility['Water Bubble'] && !counter['Water']) ||
(counter['defensesetup'] && !counter.recovery && !hasMove['rest']) ||
(movePool.includes('technoblast') || template.requiredMove && movePool.includes(toId(template.requiredMove)))) &&
(counter['physicalsetup'] + counter['specialsetup'] < 2 && (!counter.setupType || counter.setupType === 'Mixed' || (move.category !== counter.setupType && move.category !== 'Status') || counter[counter.setupType] + counter.Status > 3))) {
// Reject Status or non-STAB
if (!isSetup && !move.weather && moveid !== 'judgment' && moveid !== 'rest' && moveid !== 'sleeptalk') {
if (move.category === 'Status' || !hasType[move.type] || (move.basePower && move.basePower < 40 && !move.multihit)) rejected = true;
}
}
// Sleep Talk shouldn't be selected without Rest
if (moveid === 'rest' && rejected) {
let sleeptalk = movePool.indexOf('sleeptalk');
if (sleeptalk >= 0) {
if (movePool.length < 2) {
rejected = false;
} else {
this.fastPop(movePool, sleeptalk);
}
}
}
// Remove rejected moves from the move list
if (rejected && (movePool.length - availableHP || availableHP && (move.id === 'hiddenpower' || !hasMove['hiddenpower']))) {
moves.splice(k, 1);
break;
}
}
if (moves.length === 4 && !counter.stab && !hasMove['metalburst'] && (counter['physicalpool'] || counter['specialpool'])) {
// Move post-processing:
if (counter.damagingMoves.length === 0) {
// A set shouldn't have no attacking moves
moves.splice(this.random(moves.length), 1);
} else if (counter.damagingMoves.length === 1) {
// In most cases, a set shouldn't have no STAB
let damagingid = counter.damagingMoves[0].id;
if (movePool.length - availableHP || availableHP && (damagingid === 'hiddenpower' || !hasMove['hiddenpower'])) {
let replace = false;
if (!counter.damagingMoves[0].damage && template.species !== 'Porygon2') {
let damagingType = counter.damagingMoves[0].type;
if (damagingType === 'Fairy') {
// Mono-Fairy is acceptable for Psychic types
if (counter.setupType !== 'Special' || template.types.length > 1 || !hasType['Psychic']) replace = true;
} else {
replace = true;
}
}
if (replace) moves.splice(counter.damagingMoveIndex[damagingid], 1);
}
} else if (!counter.damagingMoves[0].damage && !counter.damagingMoves[1].damage && template.species !== 'Porygon2') {
// If you have three or more attacks, and none of them are STAB, reject one of them at random.
let rejectableMoves = [];
let baseDiff = movePool.length - availableHP;
for (let l = 0; l < counter.damagingMoves.length; l++) {
if (counter.damagingMoves[l].id === 'technoblast') continue;
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[l].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[l].id]);
}
}
if (rejectableMoves.length) {
moves.splice(rejectableMoves[this.random(rejectableMoves.length)], 1);
}
}
}
} while (moves.length < 4 && movePool.length);
// Moveset modifications
if (hasMove['autotomize'] && hasMove['heavyslam']) {
moves[moves.indexOf('autotomize')] = 'rockpolish';
}
if (moves[0] === 'conversion') {
moves[0] = moves[3];
moves[3] = 'conversion';
}
let abilities = Object.values(baseTemplate.abilities);
abilities.sort((a, b) => this.getAbility(b).rating - this.getAbility(a).rating);
let ability0 = this.getAbility(abilities[0]);
let ability1 = this.getAbility(abilities[1]);
let ability2 = this.getAbility(abilities[2]);
ability = ability0.name;
if (abilities[1]) {
if (abilities[2] && ability2.rating === ability1.rating) {
if (this.random(2)) ability1 = ability2;
}
if (ability0.rating <= ability1.rating) {
if (this.random(2)) ability = ability1.name;
} else if (ability0.rating - 0.6 <= ability1.rating) {
if (!this.random(3)) ability = ability1.name;
}
let rejectAbility = false;
if (ability in counterAbilities) {
// Adaptability, Contrary, Hustle, Iron Fist, Sheer Force, Skill Link
rejectAbility = !counter[toId(ability)];
} else if (ability in ateAbilities) {
rejectAbility = !counter['Normal'];
} else if (ability === 'Blaze') {
rejectAbility = !counter['Fire'];
} else if (ability === 'Chlorophyll') {
rejectAbility = !hasMove['sunnyday'];
} else if (ability === 'Compound Eyes' || ability === 'No Guard') {
rejectAbility = !counter['inaccurate'];
} else if (ability === 'Defiant' || ability === 'Moxie') {
rejectAbility = !counter['Physical'] && !hasMove['batonpass'];
} else if (ability === 'Flare Boost' || ability === 'Moody') {
rejectAbility = true;
} else if (ability === 'Gluttony') {
rejectAbility = !hasMove['bellydrum'];
} else if (ability === 'Lightning Rod') {
rejectAbility = template.types.includes('Ground');
} else if (ability === 'Limber') {
rejectAbility = template.types.includes('Electric');
} else if (ability === 'Liquid Voice') {
rejectAbility = !hasMove['hypervoice'];
} else if (ability === 'Overgrow') {
rejectAbility = !counter['Grass'];
} else if (ability === 'Poison Heal') {
rejectAbility = abilities.includes('Technician') && !!counter['technician'];
} else if (ability === 'Prankster') {
rejectAbility = !counter['Status'];
} else if (ability === 'Reckless' || ability === 'Rock Head') {
rejectAbility = !counter['recoil'];
} else if (ability === 'Sand Veil') {
rejectAbility = !teamDetails['sand'];
} else if (ability === 'Serene Grace') {
rejectAbility = !counter['serenegrace'] || template.id === 'chansey' || template.id === 'blissey';
} else if (ability === 'Simple') {
rejectAbility = !counter.setupType && !hasMove['cosmicpower'] && !hasMove['flamecharge'];
} else if (ability === 'Snow Cloak') {
rejectAbility = !teamDetails['hail'];
} else if (ability === 'Solar Power') {
rejectAbility = !counter['Special'] || template.isMega;
} else if (ability === 'Strong Jaw') {
rejectAbility = !counter['bite'];
} else if (ability === 'Sturdy') {
rejectAbility = !!counter['recoil'] && !counter['recovery'];
} else if (ability === 'Swift Swim') {
rejectAbility = !hasMove['raindance'] && !teamDetails['rain'];
} else if (ability === 'Swarm') {
rejectAbility = !counter['Bug'];
} else if (ability === 'Synchronize') {
rejectAbility = counter.Status < 2;
} else if (ability === 'Technician') {
rejectAbility = !counter['technician'] || (abilities.includes('Skill Link') && counter['skilllink'] >= counter['technician']);
} else if (ability === 'Tinted Lens') {
rejectAbility = counter['damage'] >= counter.damagingMoves.length;
} else if (ability === 'Torrent') {
rejectAbility = !counter['Water'];
} else if (ability === 'Unburden') {
rejectAbility = !counter.setupType && !hasMove['acrobatics'];
}
if (rejectAbility) {
if (ability === ability1.name) { // or not
ability = ability0.name;
} else if (ability1.rating > 1) { // only switch if the alternative doesn't suck
ability = ability1.name;
}
}
if (abilities.includes('Chlorophyll') && ability !== 'Solar Power' && hasMove['sunnyday']) {
ability = 'Chlorophyll';
}
if (abilities.includes('Guts') && ability !== 'Quick Feet' && (hasMove['facade'] || hasMove['protect'] || (hasMove['rest'] && hasMove['sleeptalk']))) {
ability = 'Guts';
}
if (abilities.includes('Marvel Scale') && hasMove['rest'] && hasMove['sleeptalk']) {
ability = 'Marvel Scale';
}
if (abilities.includes('Swift Swim') && hasMove['raindance']) {
ability = 'Swift Swim';
}
if (abilities.includes('Unburden') && hasMove['acrobatics']) {
ability = 'Unburden';
}
if (abilities.includes('Water Bubble') && counter['Water']) {
ability = 'Water Bubble';
}
if (template.id === 'ambipom' && !counter['technician']) {
// If it doesn't qualify for Technician, Skill Link is useless on it
ability = 'Pickup';
} else if (template.id === 'aurorus' && ability === 'Snow Warning' && hasMove['hypervoice']) {
for (let i = 0; i < moves.length; i++) {
if (moves[i] === 'hypervoice') {
moves[i] = 'blizzard';
counter['Normal'] = 0;
break;
}
}
} else if (template.baseSpecies === 'Basculin') {
ability = 'Adaptability';
} else if (template.id === 'lilligant' && hasMove['petaldance']) {
ability = 'Own Tempo';
} else if (template.id === 'lopunny' && hasMove['switcheroo'] && this.random(3)) {
ability = 'Klutz';
} else if (template.id === 'mawilemega') {
ability = 'Intimidate';
} else if (template.id === 'rampardos' && !hasMove['headsmash']) {
ability = 'Sheer Force';
} else if (template.id === 'rhyperior') {
ability = 'Solid Rock';
} else if (template.id === 'reuniclus' || template.id === 'sigilyph') {
ability = 'Magic Guard';
} else if (template.id === 'togetic' || template.id === 'unfezant') {
ability = 'Super Luck';
} else if (template.id === 'venusaurmega') {
ability = 'Chlorophyll';
}
}
if (hasMove['rockclimb'] && ability !== 'Sheer Force') {
moves[moves.indexOf('rockclimb')] = 'doubleedge';
}
if (hasMove['thunderpunch'] && ability === 'Galvanize') {
moves[moves.indexOf('thunderpunch')] = 'return';
}
item = 'Leftovers';
if (template.requiredItems) {
if (template.baseSpecies === 'Arceus' && hasMove['judgment']) {
// Judgment doesn't change type with Z-Crystals
item = template.requiredItems[0];
} else {
item = template.requiredItems[this.random(template.requiredItems.length)];
}
} else if (hasMove['magikarpsrevenge']) {
// PoTD Magikarp
item = 'Choice Band';
} else if (template.species === 'Rotom-Fan') {
// This is just to amuse Zarel
item = 'Air Balloon';
// First, the extra high-priority items
} else if (template.species === 'Clamperl' && !hasMove['shellsmash']) {
item = 'DeepSeaTooth';
} else if (template.species === 'Cubone' || template.baseSpecies === 'Marowak') {
item = 'Thick Club';
} else if (template.species === 'Dedenne') {
item = 'Petaya Berry';
} else if (template.species === 'Deoxys-Attack') {
item = (slot === 0 && hasMove['stealthrock']) ? 'Focus Sash' : 'Life Orb';
} else if (template.species === 'Farfetch\'d') {
item = 'Stick';
} else if (template.baseSpecies === 'Pikachu') {
item = 'Light Ball';
} else if (template.species === 'Shedinja' || template.species === 'Smeargle') {
item = 'Focus Sash';
} else if (template.species === 'Unfezant' && counter['Physical'] >= 2) {
item = 'Scope Lens';
} else if (template.species === 'Unown') {
item = 'Choice Specs';
} else if (template.species === 'Wobbuffet') {
item = hasMove['destinybond'] ? 'Custap Berry' : ['Leftovers', 'Sitrus Berry'][this.random(2)];
} else if (ability === 'Imposter') {
item = 'Choice Scarf';
} else if (ability === 'Klutz' && hasMove['switcheroo']) {
// To perma-taunt a Pokemon by giving it Assault Vest
item = 'Assault Vest';
} else if (hasMove['conversion']) {
item = 'Normalium Z';
} else if (hasMove['geomancy']) {
item = 'Power Herb';
} else if (hasMove['switcheroo'] || hasMove['trick']) {
let randomNum = this.random(3);
if (counter.Physical >= 3 && (template.baseStats.spe < 60 || template.baseStats.spe > 108 || randomNum)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe < 60 || template.baseStats.spe > 108 || randomNum)) {
item = 'Choice Specs';
} else {
item = 'Choice Scarf';
}
} else if (template.evos.length) {
item = (ability === 'Technician' && counter.Physical >= 4) ? 'Choice Band' : 'Eviolite';
} else if (hasMove['bellydrum']) {
if (ability === 'Gluttony') {
item = ['Aguav', 'Figy', 'Iapapa', 'Mago', 'Wiki'][this.random(5)] + ' Berry';
} else if (template.baseStats.spe <= 50 && !teamDetails.zMove && this.random(2)) {
item = 'Normalium Z';
} else {
item = 'Sitrus Berry';
}
} else if (hasMove['shellsmash']) {
item = (ability === 'Solid Rock' && counter['priority']) ? 'Weakness Policy' : 'White Herb';
} else if (ability === 'Harvest') {
item = hasMove['rest'] ? 'Lum Berry' : 'Sitrus Berry';
} else if (ability === 'Magic Guard' || ability === 'Sheer Force') {
item = hasMove['psychoshift'] ? 'Flame Orb' : 'Life Orb';
} else if (ability === 'Poison Heal' || ability === 'Toxic Boost') {
item = 'Toxic Orb';
} else if (hasMove['rest'] && !hasMove['sleeptalk'] && ability !== 'Natural Cure' && ability !== 'Shed Skin') {
item = (hasMove['raindance'] && ability === 'Hydration') ? 'Damp Rock' : 'Chesto Berry';
} else if (hasMove['raindance']) {
item = (ability === 'Swift Swim' && counter.Status < 2) ? 'Life Orb' : 'Damp Rock';
} else if (hasMove['sunnyday']) {
item = (ability === 'Chlorophyll' && counter.Status < 2) ? 'Life Orb' : 'Heat Rock';
} else if (hasMove['lightscreen'] && hasMove['reflect']) {
item = 'Light Clay';
} else if ((ability === 'Guts' || hasMove['facade']) && !hasMove['sleeptalk']) {
item = (hasType['Fire'] || ability === 'Quick Feet') ? 'Toxic Orb' : 'Flame Orb';
} else if (ability === 'Unburden') {
if (hasMove['fakeout']) {
item = 'Normal Gem';
} else {
item = 'Sitrus Berry';
}
} else if (hasMove['acrobatics']) {
item = '';
// Medium priority
} else if (((ability === 'Speed Boost' && !hasMove['substitute']) || (ability === 'Stance Change')) && counter.Physical + counter.Special > 2) {
item = 'Life Orb';
} else if (template.baseStats.spe <= 50 && hasMove['sleeppowder'] && counter.setupType && !teamDetails.zMove) {
item = 'Grassium Z';
} else if (counter.Physical >= 4 && !hasMove['bodyslam'] && !hasMove['dragontail'] && !hasMove['fakeout'] && !hasMove['flamecharge'] && !hasMove['rapidspin'] && !hasMove['suckerpunch']) {
item = template.baseStats.spe >= 60 && template.baseStats.spe <= 108 && !counter['priority'] && this.random(3) ? 'Choice Scarf' : 'Choice Band';
} else if (counter.Special >= 4 && !hasMove['acidspray'] && !hasMove['chargebeam'] && !hasMove['fierydance']) {
item = template.baseStats.spe >= 60 && template.baseStats.spe <= 108 && !counter['priority'] && this.random(3) ? 'Choice Scarf' : 'Choice Specs';
} else if (counter.Special >= 3 && hasMove['uturn'] && template.baseStats.spe >= 60 && template.baseStats.spe <= 108 && !counter['priority'] && this.random(3)) {
item = 'Choice Scarf';
} else if (ability === 'Defeatist' || hasMove['eruption'] || hasMove['waterspout']) {
item = counter.Status <= 1 ? 'Expert Belt' : 'Leftovers';
} else if ((hasMove['endeavor'] || hasMove['flail'] || hasMove['reversal']) && ability !== 'Sturdy') {
item = 'Focus Sash';
} else if (this.getEffectiveness('Ground', template) >= 2 && ability !== 'Levitate' && !hasMove['magnetrise']) {
item = 'Air Balloon';
} else if (hasMove['outrage'] && (counter.setupType || ability === 'Multiscale')) {
item = 'Lum Berry';
} else if (ability === 'Slow Start' || hasMove['clearsmog'] || hasMove['detect'] || hasMove['protect'] || hasMove['sleeptalk']) {
item = 'Leftovers';
} else if (hasMove['substitute']) {
item = !counter['drain'] || counter.damagingMoves.length < 2 ? 'Leftovers' : 'Life Orb';
} else if (hasMove['lightscreen'] || hasMove['reflect']) {
item = 'Light Clay';
} else if (ability === 'Iron Barbs' || ability === 'Rough Skin') {
item = 'Rocky Helmet';
} else if (counter.Physical + counter.Special >= 4 && template.baseStats.spd >= 65 && (template.baseStats.def + template.baseStats.spd >= 190 || hasMove['rapidspin'])) {
item = 'Assault Vest';
} else if (counter.damagingMoves.length >= 4) {
item = (!!counter['Normal'] || (hasMove['suckerpunch'] && !hasType['Dark'])) ? 'Life Orb' : 'Expert Belt';
} else if (counter.damagingMoves.length >= 3 && !!counter['speedsetup'] && template.baseStats.hp + template.baseStats.def + template.baseStats.spd >= 300) {
item = 'Weakness Policy';
} else if (counter.damagingMoves.length >= 3 && ability !== 'Sturdy' && !hasMove['clearsmog'] && !hasMove['dragontail'] && !hasMove['foulplay'] && !hasMove['superfang']) {
item = (template.baseStats.hp + template.baseStats.def + template.baseStats.spd < 285 || !!counter['speedsetup'] || hasMove['trickroom']) ? 'Life Orb' : 'Leftovers';
} else if (template.species === 'Palkia' && (hasMove['dracometeor'] || hasMove['spacialrend']) && hasMove['hydropump']) {
item = 'Lustrous Orb';
} else if (slot === 0 && ability !== 'Regenerator' && ability !== 'Sturdy' && !counter['recoil'] && !counter['recovery'] && template.baseStats.hp + template.baseStats.def + template.baseStats.spd < 285) {
item = 'Focus Sash';
// This is the "REALLY can't think of a good item" cutoff
} else if (ability === 'Super Luck') {
item = 'Scope Lens';
} else if (ability === 'Sturdy' && hasMove['explosion'] && !counter['speedsetup']) {
item = 'Custap Berry';
} else if (hasType['Poison']) {
item = 'Black Sludge';
} else if (ability === 'Gale Wings' && hasMove['bravebird']) {
item = 'Sharp Beak';
} else if (this.getEffectiveness('Rock', template) >= 1 || hasMove['dragontail']) {
item = 'Leftovers';
} else if (this.getImmunity('Ground', template) && this.getEffectiveness('Ground', template) >= 1 && ability !== 'Levitate' && ability !== 'Solid Rock' && !hasMove['magnetrise'] && !hasMove['sleeptalk']) {
item = 'Air Balloon';
} else if (counter.Status <= 1 && ability !== 'Sturdy' && !hasMove['rapidspin']) {
item = 'Life Orb';
} else {
item = 'Leftovers';
}
// For Trick / Switcheroo
if (item === 'Leftovers' && hasType['Poison']) {
item = 'Black Sludge';
}
let levelScale = {
LC: 87,
'LC Uber': 86,
NFE: 84,
PU: 83,
BL4: 82,
NU: 81,
BL3: 80,
RU: 79,
BL2: 78,
UU: 77,
New: 77,
Bank: 77,
BL: 76,
OU: 75,
Uber: 73,
'Bank-Uber': 73,
AG: 71,
};
let customScale = {
// Between OU and Uber
// Blaziken: 74, 'Blaziken-Mega': 74, 'Lucario-Mega': 74,
// Banned Ability
// Gothitelle: 74, Wobbuffet: 74,
// Holistic judgement
Unown: 100,
};
let tier = template.tier;
if (tier.includes('Unreleased') && template.battleOnly) {
tier = baseTemplate.tier;
}
if (tier.charAt(0) === '(') {
tier = tier.slice(1, -1);
}
let level = levelScale[tier] || 75;
if (customScale[template.name]) level = customScale[template.name];
// if (template.name === 'Slurpuff' && !counter.setupType) level = 81;
// if (template.name === 'Xerneas' && hasMove['geomancy']) level = 71;
// Prepare optimal HP
let hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
if (hasMove['substitute'] && item === 'Sitrus Berry') {
// Two Substitutes should activate Sitrus Berry
while (hp % 4 > 0) {
evs.hp -= 4;
hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
}
} else if (hasMove['bellydrum'] && item === 'Sitrus Berry') {
// Belly Drum should activate Sitrus Berry
if (hp % 2 > 0) evs.hp -= 4;
} else {
// Maximize number of Stealth Rock switch-ins
if (this.getEffectiveness('Rock', template) === 1) {
while (hp % 4 === 0) {
evs.hp -= 4;
hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
}
}
if (this.getEffectiveness('Rock', template) === 2) {
while (hp % 2 === 0) {
evs.hp -= 4;
hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
}
}
}
// Minimize confusion damage
if (!counter['Physical'] && !hasMove['copycat'] && !hasMove['transform']) {
evs.atk = 0;
ivs.atk = 0;
}
if (hasMove['gyroball'] || hasMove['trickroom']) {
evs.spe = 0;
ivs.spe = 0;
}
return {
name: template.baseSpecies,
species: species,
moves: moves,
ability: ability,
evs: evs,
ivs: ivs,
item: item,
level: level,
shiny: !this.random(1024),
};
},
randomTeam: function (side) {
let pokemon = [];
let excludedTiers = {'NFE':1, 'LC Uber':1, 'LC':1};
let allowedNFE = {'Chansey':1, 'Doublade':1, 'Gligar':1, 'Porygon2':1, 'Scyther':1, 'Togetic':1};
// For Monotype
let isMonotype = this.format === 'gen7monotyperandombattle';
let typePool = Object.keys(this.data.TypeChart);
let type = typePool[this.random(typePool.length)];
let pokemonPool = [];
for (let id in this.data.FormatsData) {
let template = this.getTemplate(id);
if (isMonotype) {
let types = template.types;
if (template.battleOnly) types = this.getTemplate(template.baseSpecies).types;
if (types.indexOf(type) < 0) continue;
}
if (template.gen <= this.gen && !excludedTiers[template.tier] && !template.isMega && !template.isPrimal && !template.isNonstandard && template.randomBattleMoves) {
pokemonPool.push(id);
}
}
// PotD stuff
let potd;
if (Config.potd && 'Rule:potd' in this.getBanlistTable(this.getFormat())) {
potd = this.getTemplate(Config.potd);
}
let typeCount = {};
let typeComboCount = {};
let baseFormes = {};
let uberCount = 0;
let puCount = 0;
let teamDetails = {};
while (pokemonPool.length && pokemon.length < 6) {
let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Limit to one of each species (Species Clause)
if (baseFormes[template.baseSpecies]) continue;
// Only certain NFE Pokemon are allowed
if (template.evos.length && !allowedNFE[template.species]) continue;
let tier = template.tier;
switch (tier) {
case 'Uber': case 'Bank-Uber':
// Ubers are limited to 2 but have a 20% chance of being added anyway.
if (uberCount > 1 && this.random(5) >= 1) continue;
break;
case 'PU':
// PUs are limited to 2 but have a 20% chance of being added anyway.
if (puCount > 1 && this.random(5) >= 1) continue;
break;
case 'Unreleased': case 'CAP':
// Unreleased and CAP have 20% the normal rate
if (this.random(5) >= 1) continue;
}
// Adjust rate for species with multiple formes
switch (template.baseSpecies) {
case 'Arceus': case 'Silvally':
if (this.random(18) >= 1) continue;
break;
case 'Pikachu':
if (this.random(7) >= 1) continue;
continue;
case 'Genesect':
if (this.random(5) >= 1) continue;
break;
case 'Castform': case 'Gourgeist': case 'Oricorio':
if (this.random(4) >= 1) continue;
break;
case 'Basculin': case 'Cherrim': case 'Greninja': case 'Hoopa': case 'Meloetta': case 'Meowstic':
if (this.random(2) >= 1) continue;
break;
}
if (potd && potd.exists) {
// The Pokemon of the Day belongs in slot 2
if (pokemon.length === 1) {
template = potd;
if (template.species === 'Magikarp') {
template.randomBattleMoves = ['bounce', 'flail', 'splash', 'magikarpsrevenge'];
} else if (template.species === 'Delibird') {
template.randomBattleMoves = ['present', 'bestow'];
}
} else if (template.species === potd.species) {
continue; // No thanks, I've already got one
}
}
let types = template.types;
if (!isMonotype) {
// Limit 2 of any type
let skip = false;
for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && this.random(5) >= 1) {
skip = true;
break;
}
}
if (skip) continue;
}
let set = this[this.gameType === 'singles' ? 'randomSet' : 'randomDoublesSet'](template, pokemon.length, teamDetails);
// Illusion shouldn't be the last Pokemon of the team
if (set.ability === 'Illusion' && pokemon.length > 4) continue;
// Pokemon shouldn't have Physical and Special setup on the same set
let incompatibleMoves = ['bellydrum', 'swordsdance', 'calmmind', 'nastyplot'];
let intersectMoves = set.moves.filter(move => incompatibleMoves.includes(move));
if (intersectMoves.length > 1) continue;
// Limit 1 of any type combination, 2 in monotype
let typeCombo = types.slice().sort().join();
if (set.ability === 'Drought' || set.ability === 'Drizzle' || set.ability === 'Sand Stream') {
// Drought, Drizzle and Sand Stream don't count towards the type combo limit
typeCombo = set.ability;
if (typeCombo in typeComboCount) continue;
} else {
if (typeComboCount[typeCombo] >= (isMonotype ? 2 : 1)) continue;
}
// Okay, the set passes, add it to our team
pokemon.push(set);
// Now that our Pokemon has passed all checks, we can increment our counters
baseFormes[template.baseSpecies] = 1;
// Increment type counters
for (let t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
typeCount[types[t]] = 1;
}
}
if (typeCombo in typeComboCount) {
typeComboCount[typeCombo]++;
} else {
typeComboCount[typeCombo] = 1;
}
// Increment Uber/Bank-Uber/PU counters
if (tier === 'Uber' || tier === 'Bank-Uber') {
uberCount++;
} else if (tier === 'PU') {
puCount++;
}
// Team has Mega/weather/hazards
let item = this.getItem(set.item);
if (item.megaStone) teamDetails['megaStone'] = 1;
if (item.zMove) teamDetails['zMove'] = 1;
if (set.ability === 'Snow Warning') teamDetails['hail'] = 1;
if (set.ability === 'Drizzle' || set.moves.includes('raindance')) teamDetails['rain'] = 1;
if (set.ability === 'Sand Stream') teamDetails['sand'] = 1;
if (set.moves.includes('stealthrock')) teamDetails['stealthRock'] = 1;
if (set.moves.includes('toxicspikes')) teamDetails['toxicSpikes'] = 1;
if (set.moves.includes('defog') || set.moves.includes('rapidspin')) teamDetails['hazardClear'] = 1;
}
return pokemon;
},
randomDoublesSet: function (template, slot, teamDetails) {
let baseTemplate = (template = this.getTemplate(template));
let species = template.species;
if (!template.exists || (!template.randomDoubleBattleMoves && !template.randomBattleMoves && !template.learnset)) {
template = this.getTemplate('unown');
let err = new Error('Template incompatible with random battles: ' + species);
require('../crashlogger')(err, 'The doubles randbat set generator');
}
if (typeof teamDetails !== 'object') teamDetails = {megaStone: teamDetails};
if (template.battleOnly) {
// Only change the species. The template has custom moves, and may have different typing and requirements.
species = template.baseSpecies;
}
let battleForme = this.checkBattleForme(template);
if (battleForme && (battleForme.isMega ? !teamDetails.megaStone : this.random(2))) {
template = this.getTemplate(template.otherFormes.length >= 2 ? template.otherFormes[this.random(template.otherFormes.length)] : template.otherFormes[0]);
}
let movePool = (template.randomDoubleBattleMoves || template.randomBattleMoves);
movePool = movePool ? movePool.slice() : Object.keys(template.learnset);
let moves = [];
let ability = '';
let item = '';
let evs = {
hp: 0,
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0,
};
let ivs = {
hp: 31,
atk: 31,
def: 31,
spa: 31,
spd: 31,
spe: 31,
};
let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) {
hasType[template.types[1]] = true;
}
let hasAbility = {};
hasAbility[template.abilities[0]] = true;
if (template.abilities[1]) {
hasAbility[template.abilities[1]] = true;
}
if (template.abilities['H']) {
hasAbility[template.abilities['H']] = true;
}
let availableHP = 0;
for (let i = 0, len = movePool.length; i < len; i++) {
if (movePool[i].substr(0, 11) === 'hiddenpower') availableHP++;
}
// These moves can be used even if we aren't setting up to use them:
let SetupException = {
dracometeor:1, leafstorm:1, overheat:1,
extremespeed:1, suckerpunch:1, superpower:1,
};
let counterAbilities = {
'Adaptability':1, 'Contrary':1, 'Hustle':1, 'Iron Fist':1, 'Skill Link':1,
};
// -ate Abilities
let ateAbilities = {
'Aerilate':1, 'Pixilate':1, 'Refrigerate':1,
};
let hasMove, counter;
do {
// Keep track of all moves we have:
hasMove = {};
for (let k = 0; k < moves.length; k++) {
if (moves[k].substr(0, 11) === 'hiddenpower') {
hasMove['hiddenpower'] = true;
} else {
hasMove[moves[k]] = true;
}
}
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
let moveid = toId(this.sampleNoReplace(movePool));
if (moveid.substr(0, 11) === 'hiddenpower') {
availableHP--;
if (hasMove['hiddenpower']) continue;
hasMove['hiddenpower'] = true;
} else {
hasMove[moveid] = true;
}
moves.push(moveid);
}
counter = this.queryMoves(moves, hasType, hasAbility);
// Iterate through the moves again, this time to cull them:
for (let k = 0; k < moves.length; k++) {
let moveid = moves[k];
let move = this.getMove(moveid);
let rejected = false;
switch (moveid) {
// not very useful without their supporting moves
case 'sleeptalk':
if (!hasMove['rest']) rejected = true;
break;
case 'endure':
if (!hasMove['flail'] && !hasMove['endeavor'] && !hasMove['reversal']) rejected = true;
break;
case 'focuspunch':
if (hasMove['sleeptalk'] || !hasMove['substitute']) rejected = true;
break;
case 'storedpower':
if (!hasMove['cosmicpower'] && !counter.setupType) rejected = true;
break;
case 'batonpass':
if (!counter.setupType && !hasMove['substitute'] && !hasMove['cosmicpower'] && !counter['speedsetup'] && !hasAbility['Speed Boost']) rejected = true;
break;
// we only need to set up once
case 'swordsdance': case 'dragondance': case 'coil': case 'curse': case 'bulkup': case 'bellydrum':
if (counter.Physical < 2 && !hasMove['batonpass']) rejected = true;
if (counter.setupType !== 'Physical' || counter['physicalsetup'] > 1) rejected = true;
break;
case 'nastyplot': case 'tailglow': case 'quiverdance': case 'calmmind': case 'geomancy':
if (counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (counter.setupType !== 'Special' || counter['specialsetup'] > 1) rejected = true;
break;
case 'shellsmash': case 'growth': case 'workup':
if (counter.Physical + counter.Special < 2 && !hasMove['batonpass']) rejected = true;
if (counter.setupType !== 'Mixed' || counter['mixedsetup'] > 1) rejected = true;
break;
// bad after setup
case 'seismictoss': case 'nightshade': case 'superfang':
if (counter.setupType) rejected = true;
break;
case 'rapidspin': case 'magiccoat': case 'spikes': case 'toxicspikes':
if (counter.setupType) rejected = true;
break;
case 'uturn': case 'voltswitch':
if (counter.setupType || hasMove['agility'] || hasMove['rockpolish'] || hasMove['magnetrise']) rejected = true;
break;
case 'perishsong':
if (hasMove['roar'] || hasMove['whirlwind'] || hasMove['haze']) rejected = true;
if (counter.setupType || hasMove['agility'] || hasMove['rockpolish'] || hasMove['magnetrise']) rejected = true;
break;
case 'relicsong':
if (counter.setupType) rejected = true;
break;
case 'pursuit': case 'protect': case 'haze': case 'stealthrock':
if (counter.setupType || (hasMove['rest'] && hasMove['sleeptalk'])) rejected = true;
break;
case 'trick': case 'switcheroo':
if (counter.setupType || counter.Physical + counter.Special < 2) rejected = true;
if ((hasMove['rest'] && hasMove['sleeptalk']) || hasMove['trickroom'] || hasMove['reflect'] || hasMove['lightscreen'] || hasMove['acrobatics']) rejected = true;
break;
case 'dragontail': case 'circlethrow':
if (hasMove['agility'] || hasMove['rockpolish']) rejected = true;
if (hasMove['whirlwind'] || hasMove['roar'] || hasMove['encore']) rejected = true;
break;
// bit redundant to have both
// Attacks:
case 'flamethrower': case 'fierydance':
if (hasMove['heatwave'] || hasMove['overheat'] || hasMove['fireblast'] || hasMove['blueflare']) rejected = true;
break;
case 'overheat':
if (counter.setupType === 'Special' || hasMove['fireblast']) rejected = true;
break;
case 'icebeam':
if (hasMove['blizzard'] || hasMove['freezedry']) rejected = true;
break;
case 'iceshard':
if (hasMove['freezedry']) rejected = true;
break;
case 'surf':
if (hasMove['scald'] || hasMove['hydropump'] || hasMove['muddywater']) rejected = true;
break;
case 'hydropump':
if (hasMove['razorshell'] || hasMove['waterfall'] || hasMove['scald'] || hasMove['muddywater']) rejected = true;
break;
case 'waterfall':
if (hasMove['aquatail']) rejected = true;
break;
case 'airslash':
if (hasMove['hurricane']) rejected = true;
break;
case 'acrobatics': case 'pluck': case 'drillpeck':
if (hasMove['bravebird']) rejected = true;
break;
case 'solarbeam':
if ((!hasMove['sunnyday'] && !hasAbility['Drought']) || hasMove['gigadrain'] || hasMove['leafstorm']) rejected = true;
break;
case 'gigadrain':
if ((!counter.setupType && hasMove['leafstorm']) || hasMove['petaldance']) rejected = true;
break;
case 'leafstorm':
if (counter.setupType && hasMove['gigadrain']) rejected = true;
break;
case 'seedbomb': case 'woodhammer':
if (hasMove['gigadrain']) rejected = true;
break;
case 'weatherball':
if (!hasMove['sunnyday']) rejected = true;
break;
case 'firepunch':
if (hasMove['flareblitz'] || hasMove['fireblast']) rejected = true;
break;
case 'crosschop': case 'highjumpkick':
if (hasMove['closecombat']) rejected = true;
break;
case 'drainpunch':
if (hasMove['closecombat'] || hasMove['crosschop']) rejected = true;
break;
case 'machpunch':
if (hasType['Fighting'] && counter.stab < 2 && !hasAbility['Technician']) rejected = true;
break;
case 'thunder':
if (hasMove['thunderbolt']) rejected = true;
break;
case 'thunderbolt': case 'electroweb':
if (hasMove['discharge']) rejected = true;
break;
case 'stoneedge':
if (hasMove['rockslide'] || hasMove['headsmash'] || hasMove['rockblast']) rejected = true;
break;
case 'headsmash':
if (hasMove['rockslide']) rejected = true;
break;
case 'bonemerang': case 'earthpower':
if (hasMove['earthquake']) rejected = true;
break;
case 'outrage':
if (hasMove['dragonclaw'] || hasMove['dragontail']) rejected = true;
break;
case 'ancientpower':
if (hasMove['paleowave']) rejected = true;
break;
case 'dragonpulse':
if (hasMove['dracometeor']) rejected = true;
break;
case 'moonblast':
if (hasMove['dazzlinggleam']) rejected = true;
break;
case 'acidspray':
if (hasMove['sludgebomb']) rejected = true;
break;
case 'return':
if (hasMove['bodyslam'] || hasMove['facade'] || hasMove['doubleedge'] || hasMove['tailslap'] || hasMove['doublehit']) rejected = true;
break;
case 'poisonjab':
if (hasMove['gunkshot']) rejected = true;
break;
case 'psychic':
if (hasMove['psyshock'] || hasMove['hyperspacehole']) rejected = true;
break;
case 'fusionbolt':
if (counter.setupType && hasMove['boltstrike']) rejected = true;
break;
case 'boltstrike':
if (!counter.setupType && hasMove['fusionbolt']) rejected = true;
break;
case 'darkpulse':
if (hasMove['crunch'] && counter.setupType !== 'Special') rejected = true;
break;
case 'quickattack':
if (hasMove['feint']) rejected = true;
break;
case 'bulletpunch':
if (hasType['Steel'] && counter.stab < 2 && !hasAbility['Technician']) rejected = true;
break;
case 'flashcannon':
if (hasMove['ironhead']) rejected = true;
break;
case 'wideguard':
if (hasMove['protect']) rejected = true;
break;
case 'powersplit':
if (hasMove['guardsplit']) rejected = true;
break;
// Status:
case 'rest':
if (hasMove['painsplit'] || hasMove['wish'] || hasMove['recover'] || hasMove['moonlight'] || hasMove['synthesis']) rejected = true;
break;
case 'softboiled': case 'roost':
if (hasMove['wish'] || hasMove['recover']) rejected = true;
break;
case 'roar':
// Whirlwind outclasses Roar because Soundproof
if (hasMove['whirlwind'] || hasMove['dragontail'] || hasMove['haze'] || hasMove['circlethrow']) rejected = true;
break;
case 'substitute':
if (hasMove['uturn'] || hasMove['voltswitch'] || hasMove['pursuit']) rejected = true;
break;
case 'fakeout':
if (hasMove['trick'] || hasMove['switcheroo']) rejected = true;
break;
case 'feint':
if (hasMove['fakeout']) rejected = true;
break;
case 'encore':
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
if (hasMove['whirlwind'] || hasMove['dragontail'] || hasMove['roar'] || hasMove['circlethrow']) rejected = true;
break;
case 'suckerpunch':
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'cottonguard':
if (hasMove['reflect']) rejected = true;
break;
case 'lightscreen':
if (hasMove['calmmind']) rejected = true;
break;
case 'rockpolish': case 'agility': case 'autotomize':
if (!counter.setupType && !hasMove['batonpass'] && hasMove['thunderwave']) rejected = true;
if ((hasMove['stealthrock'] || hasMove['spikes'] || hasMove['toxicspikes']) && !hasMove['batonpass']) rejected = true;
break;
case 'thunderwave':
if (counter.setupType && (hasMove['rockpolish'] || hasMove['agility'])) rejected = true;
if (hasMove['discharge'] || hasMove['trickroom']) rejected = true;
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
if (hasMove['yawn'] || hasMove['spore'] || hasMove['sleeppowder']) rejected = true;
break;
case 'lavaplume':
if (hasMove['willowisp']) rejected = true;
break;
case 'trickroom':
if (hasMove['rockpolish'] || hasMove['agility'] || hasMove['icywind']) rejected = true;
break;
case 'willowisp':
if (hasMove['scald'] || hasMove['yawn'] || hasMove['spore'] || hasMove['sleeppowder']) rejected = true;
break;
case 'toxic':
if (hasMove['thunderwave'] || hasMove['willowisp'] || hasMove['scald'] || hasMove['yawn'] || hasMove['spore'] || hasMove['sleeppowder']) rejected = true;
break;
}
// Increased/decreased priority moves unneeded with moves that boost only speed
if (move.priority !== 0 && (hasMove['rockpolish'] || hasMove['agility'])) {
rejected = true;
}
if (move.category === 'Special' && counter.setupType === 'Physical' && !SetupException[move.id]) {
rejected = true;
}
if (move.category === 'Physical' && (counter.setupType === 'Special' || hasMove['acidspray']) && !SetupException[move.id]) {
rejected = true;
}
// This move doesn't satisfy our setup requirements:
if (counter.setupType === 'Physical' && move.category !== 'Physical' && counter['Physical'] < 2) {
rejected = true;
}
if (counter.setupType === 'Special' && move.category !== 'Special' && counter['Special'] < 2) {
rejected = true;
}
// Hidden Power isn't good enough
if (counter.setupType === 'Special' && move.id === 'hiddenpower' && counter['Special'] <= 2 && (!hasMove['shadowball'] || move.type !== 'Fighting')) {
rejected = true;
}
// Adaptability, Contrary, and Drought should have moves that benefit
if ((hasAbility['Adaptability'] && counter.stab < template.types.length) || (hasAbility['Contrary'] && !counter.contrary && template.species !== 'Shuckle') || ((hasAbility['Drought'] || hasMove['sunnyday']) && hasType['Fire'] && !counter['Fire'] && move.id !== 'solarbeam')) {
// Reject Status or non-STAB
if (move.category === 'Status' || !hasType[move.type]) rejected = true;
}
// Remove rejected moves from the move list.
if (rejected && (movePool.length - availableHP || availableHP && (move.id === 'hiddenpower' || !hasMove['hiddenpower']))) {
moves.splice(k, 1);
break;
}
}
if (movePool.length && moves.length === 4 && !hasMove['judgment']) {
// Move post-processing:
if (counter.damagingMoves.length === 0) {
// A set shouldn't have no attacking moves
moves.splice(this.random(moves.length), 1);
} else if (counter.damagingMoves.length === 1) {
let damagingid = counter.damagingMoves[0].id;
// Night Shade, Seismic Toss, etc. don't count:
if (!counter.damagingMoves[0].damage && (movePool.length - availableHP || availableHP && (damagingid === 'hiddenpower' || !hasMove['hiddenpower']))) {
let replace = false;
if (damagingid in {counter:1, focuspunch:1, mirrorcoat:1, suckerpunch:1} || (damagingid === 'hiddenpower' && !counter.stab)) {
// Unacceptable as the only attacking move
replace = true;
} else {
if (!counter.stab) {
let damagingType = counter.damagingMoves[0].type;
if (damagingType === 'Fairy') {
// Mono-Fairy is acceptable for Psychic types
if (!hasType['Psychic']) replace = true;
} else if (damagingType === 'Ice') {
if (hasType['Normal'] && template.types.length === 1) {
// Mono-Ice is acceptable for special attacking Normal types that lack Boomburst and Hyper Voice
if (counter.Physical >= 2 || movePool.includes('boomburst') || movePool.includes('hypervoice')) replace = true;
} else {
replace = true;
}
} else {
replace = true;
}
}
}
if (replace) moves.splice(counter.damagingMoveIndex[damagingid], 1);
}
} else if (counter.damagingMoves.length === 2 && !counter.stab) {
// If you have two attacks, neither is STAB, and the combo isn't Ice/Electric or Ghost/Fighting, reject one of them at random.
let type1 = counter.damagingMoves[0].type, type2 = counter.damagingMoves[1].type;
let typeCombo = [type1, type2].sort().join('/');
if (typeCombo !== 'Electric/Ice' && typeCombo !== 'Fighting/Ghost') {
let rejectableMoves = [];
let baseDiff = movePool.length - availableHP;
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[0].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[0].id]);
}
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[1].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[1].id]);
}
if (rejectableMoves.length) {
moves.splice(rejectableMoves[this.random(rejectableMoves.length)], 1);
}
}
} else if (!counter.stab || ((hasAbility['Aerilate'] || hasAbility['Pixilate'] || hasAbility['Refrigerate']) && !counter['Normal'])) {
// If you have three or more attacks, and none of them are STAB, reject one of them at random.
// Alternatively, if you have an -ate ability and no Normal moves, reject an attack move at random.
let rejectableMoves = [];
let baseDiff = movePool.length - availableHP;
for (let l = 0; l < counter.damagingMoves.length; l++) {
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[l].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[l].id]);
}
}
if (rejectableMoves.length) {
moves.splice(rejectableMoves[this.random(rejectableMoves.length)], 1);
}
}
}
} while (moves.length < 4 && movePool.length);
// any moveset modification goes here
//moves[0] = 'safeguard';
let changedMove = false;
if (template.requiredItem && template.requiredItem.slice(-5) === 'Drive' && !hasMove['technoblast']) {
delete hasMove[this.getMove(moves[3]).id];
moves[3] = 'technoblast';
hasMove['technoblast'] = true;
changedMove = true;
}
if (template.id === 'meloettapirouette' && !hasMove['relicsong']) {
delete hasMove[this.getMove(moves[3]).id];
moves[3] = 'relicsong';
hasMove['relicsong'] = true;
changedMove = true;
}
if (template.requiredMove && !hasMove[toId(template.requiredMove)]) {
delete hasMove[this.getMove(moves[3]).id];
moves[3] = toId(template.requiredMove);
hasMove[toId(template.requiredMove)] = true;
changedMove = true;
}
// Re-query in case a moveset modification occurred
if (changedMove) counter = this.queryMoves(moves, hasType, hasAbility);
let abilities = Object.values(baseTemplate.abilities);
abilities.sort((a, b) => this.getAbility(b).rating - this.getAbility(a).rating);
let ability0 = this.getAbility(abilities[0]);
let ability1 = this.getAbility(abilities[1]);
let ability2 = this.getAbility(abilities[2]);
ability = ability0.name;
if (abilities[1]) {
if (abilities[2] && ability2.rating === ability1.rating) {
if (this.random(2)) ability1 = ability2;
}
if (ability0.rating <= ability1.rating) {
if (this.random(2)) ability = ability1.name;
} else if (ability0.rating - 0.6 <= ability1.rating) {
if (!this.random(3)) ability = ability1.name;
}
let rejectAbility = false;
if (ability in counterAbilities) {
rejectAbility = !counter[toId(ability)];
} else if (ability in ateAbilities) {
rejectAbility = !counter['Normal'];
} else if (ability === 'Blaze') {
rejectAbility = !counter['Fire'];
} else if (ability === 'Chlorophyll') {
rejectAbility = !hasMove['sunnyday'];
} else if (ability === 'Compound Eyes' || ability === 'No Guard') {
rejectAbility = !counter['inaccurate'];
} else if (ability === 'Defiant' || ability === 'Moxie') {
rejectAbility = !counter['Physical'] && !hasMove['batonpass'];
} else if (ability === 'Gluttony') {
rejectAbility = true;
} else if (ability === 'Limber') {
rejectAbility = template.types.includes('Electric');
} else if (ability === 'Lightning Rod') {
rejectAbility = template.types.includes('Ground');
} else if (ability === 'Moody') {
rejectAbility = template.id !== 'bidoof';
} else if (ability === 'Overgrow') {
rejectAbility = !counter['Grass'];
} else if (ability === 'Poison Heal') {
rejectAbility = abilities.includes('Technician') && !!counter['technician'];
} else if (ability === 'Prankster') {
rejectAbility = !counter['Status'];
} else if (ability === 'Reckless' || ability === 'Rock Head') {
rejectAbility = !counter['recoil'];
} else if (ability === 'Serene Grace') {
rejectAbility = !counter['serenegrace'] || template.id === 'chansey' || template.id === 'blissey';
} else if (ability === 'Sheer Force') {
rejectAbility = !counter['sheerforce'] || hasMove['fakeout'];
} else if (ability === 'Simple') {
rejectAbility = !counter.setupType && !hasMove['cosmicpower'] && !hasMove['flamecharge'];
} else if (ability === 'Snow Cloak') {
rejectAbility = !teamDetails['hail'];
} else if (ability === 'Solar Power') {
rejectAbility = !counter['Special'] || template.isMega;
} else if (ability === 'Strong Jaw') {
rejectAbility = !counter['bite'];
} else if (ability === 'Sturdy') {
rejectAbility = !!counter['recoil'] && !counter['recovery'];
} else if (ability === 'Swift Swim') {
rejectAbility = !hasMove['raindance'] && !teamDetails['rain'];
} else if (ability === 'Swarm') {
rejectAbility = !counter['Bug'];
} else if (ability === 'Technician') {
rejectAbility = !counter['technician'] || (abilities.includes('Skill Link') && counter['skilllink'] >= counter['technician']);
} else if (ability === 'Tinted Lens') {
rejectAbility = counter['damage'] >= counter.damagingMoves.length;
} else if (ability === 'Torrent') {
rejectAbility = !counter['Water'];
} else if (ability === 'Unburden') {
rejectAbility = template.baseStats.spe > 120 || (template.id === 'slurpuff' && !counter.setupType);
}
if (rejectAbility) {
if (ability === ability1.name) { // or not
ability = ability0.name;
} else if (ability1.rating > 0) { // only switch if the alternative doesn't suck
ability = ability1.name;
}
}
if (abilities.includes('Chlorophyll') && ability !== 'Solar Power') {
ability = 'Chlorophyll';
}
if (abilities.includes('Guts') && ability !== 'Quick Feet' && hasMove['facade']) {
ability = 'Guts';
}
if (abilities.includes('Intimidate') || template.id === 'mawilemega') {
ability = 'Intimidate';
}
if (abilities.includes('Swift Swim') && hasMove['raindance']) {
ability = 'Swift Swim';
}
if (template.id === 'ambipom' && !counter['technician']) {
// If it doesn't qualify for Technician, Skill Link is useless on it
// Might as well give it Pickup just in case
ability = 'Pickup';
} else if (template.id === 'aurorus' && ability === 'Snow Warning' && hasMove['hypervoice']) {
for (let i = 0; i < moves.length; i++) {
if (moves[i] === 'hypervoice') {
moves[i] = 'blizzard';
counter['Normal'] = 0;
break;
}
}
} else if (template.baseSpecies === 'Basculin') {
ability = 'Adaptability';
} else if (template.id === 'gligar') {
ability = 'Immunity';
} else if (template.id === 'lilligant' && hasMove['petaldance']) {
ability = 'Own Tempo';
} else if (template.id === 'rampardos' && !hasMove['headsmash']) {
ability = 'Sheer Force';
} else if (template.id === 'rhyperior') {
ability = 'Solid Rock';
} else if (template.id === 'unfezant') {
ability = 'Super Luck';
} else if (template.id === 'venusaurmega') {
ability = 'Chlorophyll';
}
}
// Make EVs comply with the sets.
// Quite simple right now, 252 attack, 252 hp if slow 252 speed if fast, 4 evs for the strong defense.
// TO-DO: Make this more complex
if (counter.Special >= 2) {
evs.atk = 0;
evs.spa = 252;
} else if (counter.Physical >= 2) {
evs.atk = 252;
evs.spa = 0;
} else {
// Fallback in case a Pokémon lacks attacks... go by stats
if (template.baseStats.spa >= template.baseStats.atk) {
evs.atk = 0;
evs.spa = 252;
} else {
evs.atk = 252;
evs.spa = 0;
}
}
if (template.baseStats.spe > 80 || template.species === 'Shedinja') {
evs.spe = 252;
evs.hp = 4;
} else {
evs.hp = 252;
if (template.baseStats.def > template.baseStats.spd) {
evs.def = 4;
} else {
evs.spd = 4;
}
}
// Naturally slow mons already have the proper EVs, check IVs for Gyro Ball and TR
if (hasMove['gyroball'] || hasMove['trickroom']) {
ivs.spe = 0;
}
item = 'Sitrus Berry';
if (template.requiredItems) {
item = template.requiredItems[this.random(template.requiredItems.length)];
// First, the extra high-priority items
} else if (ability === 'Imposter') {
item = 'Choice Scarf';
} else if (hasMove["magikarpsrevenge"]) {
item = 'Mystic Water';
} else if (ability === 'Wonder Guard') {
item = 'Focus Sash';
} else if (template.species === 'Unown') {
item = 'Choice Specs';
} else if (hasMove['trick'] || hasMove['switcheroo']) {
let randomNum = this.random(2);
if (counter.Physical >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe >= 95 || randomNum)) {
item = 'Choice Specs';
} else {
item = 'Choice Scarf';
}
} else if (hasMove['rest'] && !hasMove['sleeptalk'] && ability !== 'Natural Cure' && ability !== 'Shed Skin') {
item = 'Chesto Berry';
} else if (hasMove['naturalgift']) {
item = 'Liechi Berry';
} else if (hasMove['geomancy']) {
item = 'Power Herb';
} else if (ability === 'Harvest') {
item = 'Sitrus Berry';
} else if (template.species === 'Cubone' || template.species === 'Marowak') {
item = 'Thick Club';
} else if (template.baseSpecies === 'Pikachu') {
item = 'Light Ball';
} else if (template.species === 'Clamperl') {
item = 'DeepSeaTooth';
} else if (template.species === 'Spiritomb') {
item = 'Leftovers';
} else if (template.species === 'Scrafty' && counter['Status'] === 0) {
item = 'Assault Vest';
} else if (template.species === 'Farfetch\'d') {
item = 'Stick';
} else if (template.species === 'Amoonguss') {
item = 'Black Sludge';
} else if (template.species === 'Dedenne') {
item = 'Petaya Berry';
} else if (hasMove['focusenergy'] || (template.species === 'Unfezant' && counter['Physical'] >= 2)) {
item = 'Scope Lens';
} else if (template.evos.length) {
item = 'Eviolite';
} else if (hasMove['reflect'] && hasMove['lightscreen']) {
item = 'Light Clay';
} else if (hasMove['shellsmash']) {
if (ability === 'Solid Rock' && counter['priority']) {
item = 'Weakness Policy';
} else {
item = 'White Herb';
}
} else if (hasMove['facade'] || ability === 'Poison Heal' || ability === 'Toxic Boost') {
item = 'Toxic Orb';
} else if (hasMove['raindance']) {
item = 'Damp Rock';
} else if (hasMove['sunnyday']) {
item = 'Heat Rock';
} else if (hasMove['sandstorm']) {
item = 'Smooth Rock';
} else if (hasMove['hail']) {
item = 'Icy Rock';
} else if (ability === 'Magic Guard' && hasMove['psychoshift']) {
item = 'Flame Orb';
} else if (ability === 'Sheer Force' || ability === 'Magic Guard') {
item = 'Life Orb';
} else if (hasMove['acrobatics']) {
item = 'Flying Gem';
} else if (ability === 'Unburden') {
if (hasMove['fakeout']) {
item = 'Normal Gem';
} else if (hasMove['dracometeor'] || hasMove['leafstorm'] || hasMove['overheat']) {
item = 'White Herb';
} else if (hasMove['substitute'] || counter.setupType) {
item = 'Sitrus Berry';
} else {
item = 'Red Card';
for (let m in moves) {
let move = this.getMove(moves[m]);
if (hasType[move.type] && move.basePower >= 90) {
item = move.type + ' Gem';
break;
}
}
}
// medium priority
} else if (ability === 'Guts') {
item = hasMove['drainpunch'] ? 'Flame Orb' : 'Toxic Orb';
if ((hasMove['return'] || hasMove['hyperfang']) && !hasMove['facade']) {
// lol no
for (let j = 0; j < moves.length; j++) {
if (moves[j] === 'Return' || moves[j] === 'Hyper Fang') {
moves[j] = 'Facade';
break;
}
}
}
} else if (ability === 'Marvel Scale' && hasMove['psychoshift']) {
item = 'Flame Orb';
} else if (counter.Physical >= 4 && template.baseStats.spe > 55 && !hasMove['fakeout'] && !hasMove['suckerpunch'] && !hasMove['flamecharge'] && !hasMove['rapidspin'] && ability !== 'Sturdy' && ability !== 'Multiscale') {
item = 'Life Orb';
} else if (counter.Special >= 4 && template.baseStats.spe > 55 && !hasMove['eruption'] && !hasMove['waterspout'] && ability !== 'Sturdy') {
item = 'Life Orb';
} else if (this.getImmunity('Ground', template) && this.getEffectiveness('Ground', template) >= 2 && ability !== 'Levitate' && !hasMove['magnetrise']) {
item = 'Shuca Berry';
} else if (this.getEffectiveness('Ice', template) >= 2) {
item = 'Yache Berry';
} else if (this.getEffectiveness('Rock', template) >= 2) {
item = 'Charti Berry';
} else if (this.getEffectiveness('Fire', template) >= 2) {
item = 'Occa Berry';
} else if (this.getImmunity('Fighting', template) && this.getEffectiveness('Fighting', template) >= 2) {
item = 'Chople Berry';
} else if (ability === 'Iron Barbs' || ability === 'Rough Skin') {
item = 'Rocky Helmet';
} else if (counter.Physical + counter.Special >= 4 && ability === 'Regenerator' && template.baseStats[counter.Special >= 2 ? 'atk' : 'spa'] > 99 && template.baseStats.spe <= 80) {
item = 'Assault Vest';
} else if ((template.baseStats.hp + 75) * (template.baseStats.def + template.baseStats.spd + 175) > 60000 || template.species === 'Skarmory' || template.species === 'Forretress') {
// skarmory and forretress get exceptions for their typing
item = 'Sitrus Berry';
} else if (counter.Physical + counter.Special >= 3 && counter.setupType && ability !== 'Sturdy' && ability !== 'Multiscale') {
item = 'Life Orb';
} else if (counter.Special >= 3 && counter.setupType && ability !== 'Sturdy') {
item = 'Life Orb';
} else if (counter.Physical + counter.Special >= 4 && template.baseStats.def + template.baseStats.spd > 179) {
item = 'Assault Vest';
} else if (counter.Physical + counter.Special >= 4) {
item = 'Expert Belt';
} else if (hasMove['outrage']) {
item = 'Lum Berry';
} else if (hasMove['substitute'] || hasMove['detect'] || hasMove['protect'] || ability === 'Moody') {
item = 'Leftovers';
} else if (this.getImmunity('Ground', template) && this.getEffectiveness('Ground', template) >= 1 && ability !== 'Levitate' && !hasMove['magnetrise']) {
item = 'Shuca Berry';
} else if (this.getEffectiveness('Ice', template) >= 1) {
item = 'Yache Berry';
// this is the "REALLY can't think of a good item" cutoff
} else if (counter.Physical + counter.Special >= 2 && template.baseStats.hp + template.baseStats.def + template.baseStats.spd > 315) {
item = 'Weakness Policy';
} else if (ability === 'Sturdy' && hasMove['explosion'] && !counter['speedsetup']) {
item = 'Custap Berry';
} else if (ability === 'Super Luck') {
item = 'Scope Lens';
} else if (hasType['Poison']) {
item = 'Black Sludge';
} else if (counter.Status <= 1 && ability !== 'Sturdy' && ability !== 'Multiscale') {
item = 'Life Orb';
} else {
item = 'Sitrus Berry';
}
// For Trick / Switcheroo
if (item === 'Leftovers' && hasType['Poison']) {
item = 'Black Sludge';
}
// We choose level based on BST. Min level is 70, max level is 99. 600+ BST is 70, less than 300 is 99. Calculate with those values.
// Every 10.34 BST adds a level from 70 up to 99. Results are floored. Uses the Mega's stats if holding a Mega Stone
let bst = template.baseStats.hp + template.baseStats.atk + template.baseStats.def + template.baseStats.spa + template.baseStats.spd + template.baseStats.spe;
// Adjust levels of mons based on abilities (Pure Power, Sheer Force, etc.) and also Eviolite
// For the stat boosted, treat the Pokemon's base stat as if it were multiplied by the boost. (Actual effective base stats are higher.)
let templateAbility = (baseTemplate === template ? ability : template.abilities[0]);
if (templateAbility === 'Huge Power' || templateAbility === 'Pure Power') {
bst += template.baseStats.atk;
} else if (templateAbility === 'Parental Bond') {
bst += 0.5 * (evs.atk > evs.spa ? template.baseStats.atk : template.baseStats.spa);
} else if (templateAbility === 'Protean') {
// Holistic judgment. Don't boost Protean as much as Parental Bond
bst += 0.3 * (evs.atk > evs.spa ? template.baseStats.atk : template.baseStats.spa);
} else if (templateAbility === 'Fur Coat') {
bst += template.baseStats.def;
}
if (item === 'Eviolite') {
bst += 0.5 * (template.baseStats.def + template.baseStats.spd);
}
let level = 70 + Math.floor(((600 - this.clampIntRange(bst, 300, 600)) / 10.34));
return {
name: template.baseSpecies,
species: species,
moves: moves,
ability: ability,
evs: evs,
ivs: ivs,
item: item,
level: level,
shiny: !this.random(template.id === 'missingno' ? 4 : 1024),
};
},
randomFactorySets: require('./factory-sets.json'),
randomFactorySet: function (template, slot, teamData, tier) {
let speciesId = toId(template.species);
// let flags = this.randomFactorySets[tier][speciesId].flags;
let setList = this.randomFactorySets[tier][speciesId].sets;
let effectivePool, priorityPool;
let itemsMax = {'choicespecs':1, 'choiceband':1, 'choicescarf':1};
let movesMax = {'rapidspin':1, 'batonpass':1, 'stealthrock':1, 'defog':1, 'spikes':1, 'toxicspikes':1};
let requiredMoves = {'stealthrock': 'hazardSet', 'rapidspin': 'hazardClear', 'defog': 'hazardClear'};
let weatherAbilitiesRequire = {
'hydration': 'raindance', 'swiftswim': 'raindance',
'leafguard': 'sunnyday', 'solarpower': 'sunnyday', 'chlorophyll': 'sunnyday',
'sandforce': 'sandstorm', 'sandrush': 'sandstorm', 'sandveil': 'sandstorm',
'snowcloak': 'hail',
};
let weatherAbilitiesSet = {'drizzle':1, 'drought':1, 'snowwarning':1, 'sandstream':1};
// Build a pool of eligible sets, given the team partners
// Also keep track of sets with moves the team requires
effectivePool = [];
priorityPool = [];
for (let i = 0, l = setList.length; i < l; i++) {
let curSet = setList[i];
let itemData = this.getItem(curSet.item);
if (teamData.megaCount > 0 && itemData.megaStone) continue; // reject 2+ mega stones
if (itemsMax[itemData.id] && teamData.has[itemData.id] >= itemsMax[itemData.id]) continue;
let abilityData = this.getAbility(curSet.ability);
if (weatherAbilitiesRequire[abilityData.id] && teamData.weather !== weatherAbilitiesRequire[abilityData.id]) continue;
if (teamData.weather && weatherAbilitiesSet[abilityData.id]) continue; // reject 2+ weather setters
let reject = false;
let hasRequiredMove = false;
let curSetVariants = [];
for (let j = 0, m = curSet.moves.length; j < m; j++) {
let variantIndex = this.random(curSet.moves[j].length);
let moveId = toId(curSet.moves[j][variantIndex]);
if (movesMax[moveId] && teamData.has[moveId] >= movesMax[moveId]) {
reject = true;
break;
}
if (requiredMoves[moveId] && !teamData.has[requiredMoves[moveId]]) {
hasRequiredMove = true;
}
curSetVariants.push(variantIndex);
}
if (reject) continue;
effectivePool.push({set: curSet, moveVariants: curSetVariants});
if (hasRequiredMove) priorityPool.push({set: curSet, moveVariants: curSetVariants});
}
if (priorityPool.length) effectivePool = priorityPool;
if (!effectivePool.length) {
if (!teamData.forceResult) return false;
for (let i = 0; i < setList.length; i++) {
effectivePool.push({set: setList[i]});
}
}
let setData = effectivePool[this.random(effectivePool.length)];
let moves = [];
for (let i = 0; i < setData.set.moves.length; i++) {
let moveSlot = setData.set.moves[i];
moves.push(setData.moveVariants ? moveSlot[setData.moveVariants[i]] : moveSlot[this.random(moveSlot.length)]);
}
return {
name: setData.set.name || template.baseSpecies,
species: setData.set.species,
gender: setData.set.gender || template.gender || (this.random() ? 'M' : 'F'),
item: setData.set.item || '',
ability: setData.set.ability || template.abilities['0'],
shiny: typeof setData.set.shiny === 'undefined' ? !this.random(1024) : setData.set.shiny,
level: 100,
happiness: typeof setData.set.happiness === 'undefined' ? 255 : setData.set.happiness,
evs: setData.set.evs || {hp: 84, atk: 84, def: 84, spa: 84, spd: 84, spe: 84},
ivs: setData.set.ivs || {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31},
nature: setData.set.nature || 'Serious',
moves: moves,
};
},
randomFactoryTeam: function (side, depth) {
if (!depth) depth = 0;
let forceResult = (depth >= 4);
let availableTiers = ['Uber', 'OU', 'UU', 'RU', 'NU', 'PU'];
const prevSeed = this.seed;
this.seed = this.startingSeed.slice(0, 4);
const chosenTier = availableTiers[this.random(availableTiers.length)];
this.seed = prevSeed;
let pokemon = [];
let pokemonPool = Object.keys(this.randomFactorySets[chosenTier]);
let teamData = {typeCount: {}, typeComboCount: {}, baseFormes: {}, megaCount: 0, has: {}, forceResult: forceResult, weaknesses: {}, resistances: {}};
let requiredMoveFamilies = {'hazardSet': 1, 'hazardClear':1};
let requiredMoves = {'stealthrock': 'hazardSet', 'rapidspin': 'hazardClear', 'defog': 'hazardClear'};
let weatherAbilitiesSet = {'drizzle': 'raindance', 'drought': 'sunnyday', 'snowwarning': 'hail', 'sandstream': 'sandstorm'};
let resistanceAbilities = {
'dryskin': ['Water'], 'waterabsorb': ['Water'], 'stormdrain': ['Water'],
'flashfire': ['Fire'], 'heatproof': ['Fire'],
'lightningrod': ['Electric'], 'motordrive': ['Electric'], 'voltabsorb': ['Electric'],
'sapsipper': ['Grass'],
'thickfat': ['Ice', 'Fire'],
'levitate': ['Ground'],
};
while (pokemonPool.length && pokemon.length < 6) {
let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
let speciesFlags = this.randomFactorySets[chosenTier][template.speciesid].flags;
// Limit to one of each species (Species Clause)
if (teamData.baseFormes[template.baseSpecies]) continue;
// Limit the number of Megas to one
if (teamData.megaCount >= 1 && speciesFlags.megaOnly) continue;
// Limit 2 of any type
let types = template.types;
let skip = false;
for (let t = 0; t < types.length; t++) {
if (teamData.typeCount[types[t]] > 1 && this.random(5)) {
skip = true;
break;
}
}
if (skip) continue;
let set = this.randomFactorySet(template, pokemon.length, teamData, chosenTier);
if (!set) continue;
// Limit 1 of any type combination
let typeCombo = types.slice().sort().join();
if (set.ability === 'Drought' || set.ability === 'Drizzle') {
// Drought and Drizzle don't count towards the type combo limit
typeCombo = set.ability;
}
if (typeCombo in teamData.typeComboCount) continue;
// Okay, the set passes, add it to our team
pokemon.push(set);
// Now that our Pokemon has passed all checks, we can update team data:
for (let t = 0; t < types.length; t++) {
if (types[t] in teamData.typeCount) {
teamData.typeCount[types[t]]++;
} else {
teamData.typeCount[types[t]] = 1;
}
}
teamData.typeComboCount[typeCombo] = 1;
teamData.baseFormes[template.baseSpecies] = 1;
let itemData = this.getItem(set.item);
if (itemData.megaStone) teamData.megaCount++;
if (itemData.id in teamData.has) {
teamData.has[itemData.id]++;
} else {
teamData.has[itemData.id] = 1;
}
let abilityData = this.getAbility(set.ability);
if (abilityData.id in weatherAbilitiesSet) {
teamData.weather = weatherAbilitiesSet[abilityData.id];
}
for (let m = 0; m < set.moves.length; m++) {
let moveId = toId(set.moves[m]);
if (moveId in teamData.has) {
teamData.has[moveId]++;
} else {
teamData.has[moveId] = 1;
}
if (moveId in requiredMoves) {
teamData.has[requiredMoves[moveId]] = 1;
}
}
for (let typeName in this.data.TypeChart) {
// Cover any major weakness (3+) with at least one resistance
if (teamData.resistances[typeName] >= 1) continue;
if (resistanceAbilities[abilityData.id] && resistanceAbilities[abilityData.id].includes(typeName) || !this.getImmunity(typeName, types)) {
// Heuristic: assume that Pokémon with these abilities don't have (too) negative typing.
teamData.resistances[typeName] = (teamData.resistances[typeName] || 0) + 1;
if (teamData.resistances[typeName] >= 1) teamData.weaknesses[typeName] = 0;
continue;
}
let typeMod = this.getEffectiveness(typeName, types);
if (typeMod < 0) {
teamData.resistances[typeName] = (teamData.resistances[typeName] || 0) + 1;
if (teamData.resistances[typeName] >= 1) teamData.weaknesses[typeName] = 0;
} else if (typeMod > 0) {
teamData.weaknesses[typeName] = (teamData.weaknesses[typeName] || 0) + 1;
}
}
}
if (pokemon.length < 6) return this.randomFactoryTeam(side, ++depth);
// Quality control
if (!teamData.forceResult) {
for (let requiredFamily in requiredMoveFamilies) {
if (!teamData.has[requiredFamily]) return this.randomFactoryTeam(side, ++depth);
}
for (let type in teamData.weaknesses) {
if (teamData.weaknesses[type] >= 3) return this.randomFactoryTeam(side, ++depth);
}
}
return pokemon;
},
};
| {
"content_hash": "3dbf76e1d5d04f4dd533b3a212a3228b",
"timestamp": "",
"source": "github",
"line_count": 3548,
"max_line_length": 280,
"avg_line_length": 39.640924464487036,
"alnum_prop": 0.625136868449867,
"repo_name": "jd4564/Pokemon-Showdown",
"id": "87ab4b403c219af153ca22cf437521d25d0651b5",
"size": "140653",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/scripts.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1055"
},
{
"name": "CSS",
"bytes": "351"
},
{
"name": "HTML",
"bytes": "2057"
},
{
"name": "JavaScript",
"bytes": "7301311"
}
],
"symlink_target": ""
} |
package com.emistoolbox.lib.pdf.util;
import java.awt.Color;
import java.io.IOException;
import java.io.PrintStream;
import com.emistoolbox.lib.pdf.layout.PDFLayout;
import com.emistoolbox.lib.pdf.layout.PDFLayoutBorderStyle;
import com.emistoolbox.lib.pdf.layout.PDFLayoutElement;
import com.emistoolbox.lib.pdf.layout.PDFLayoutFrameElement;
import com.emistoolbox.lib.pdf.layout.PDFLayoutHighchartElement;
import com.emistoolbox.lib.pdf.layout.PDFLayoutImageElement;
import com.emistoolbox.lib.pdf.layout.PDFLayoutPDFElement;
import com.emistoolbox.lib.pdf.layout.PDFLayoutFont;
import com.emistoolbox.lib.pdf.layout.PDFLayoutTableElement;
import com.emistoolbox.lib.pdf.layout.PDFLayoutTextElement;
import com.emistoolbox.lib.pdf.layout.PDFLayoutVisitor;
import es.jbauer.lib.io.IOOutput;
public class PDFLayoutLogVisitor implements PDFLayoutVisitor<Void>
{
private static final String INDENT = " ";
private int indentCount = 0;
private String indent = "";
private IOOutput out;
private PrintStream os;
public PDFLayoutLogVisitor()
{ os = System.out; }
public PDFLayoutLogVisitor(IOOutput out)
throws IOException
{
this.out = out;
if (out.getEncoding() == null)
this.os = new PrintStream(out.getOutputStream(), true);
else
this.os = new PrintStream(out.getOutputStream(), true, out.getEncoding());
}
@Override
public Void visit(PDFLayout page)
throws IOException
{
if (page == null)
return null;
os.println("Page:");
indent();
try { page.getOuterFrame().accept(this); }
finally { unindent(); }
return null;
}
@Override
public Void visit(PDFLayoutFrameElement frame) throws IOException
{
os.println(indent + "Element - Frame: " + frame.getWidth() + " x " + frame.getHeight());
indent();
try {
output(frame);
for (PDFLayoutElement e : frame.getElements())
e.accept(this);
}
finally { unindent(); }
return null;
}
@Override
public Void visit(PDFLayoutHighchartElement highchartContent) throws IOException {
os.println(indent + "Element - Highchart: " + highchartContent.getInput().getName());
output(highchartContent);
return null;
}
@Override
public Void visit(PDFLayoutImageElement imageContent) throws IOException {
os.println(indent + "Element - Image: " + imageContent.getInput().getName());
output(imageContent);
return null;
}
@Override
public Void visit(PDFLayoutPDFElement pdfContent) throws IOException {
os.println(indent + "Element - PDF: " + pdfContent.getInput().getName());
output(pdfContent);
return null;
}
public Void visit(PDFLayoutTableElement tableContent) throws IOException {
os.println(indent + "Element - Table: " + tableContent.getRowCount() + " x " + tableContent.getColCount());
try {
indent();
output (tableContent);
for (int row = 0;row < tableContent.getRowCount ();row++)
for (int col = 0;col < tableContent.getColCount ();col++) {
os.println (indent + "Table element in row " + row + ", column " + col + ":");
PDFLayoutElement element = tableContent.getElement (row,col);
if (element == null)
os.println (indent + " null");
else
element.accept (this);
}
}
finally { unindent(); }
return null;
}
public Void visit(PDFLayoutFont font)
{
os.println(indent + "Font: " + font.getFontName() + ", size: " + font.getFontSize() + ", style: " + font.getFontStyle() + ", col: " + getColorName(font.getColor()));
return null;
}
private String getColorName(Color color)
{
if (color == null)
return null;
String result = color.toString();
int start = result.indexOf("[");
int end = result.indexOf("]");
if (start == -1 || end == -1)
return result;
return result.substring(start + 1, end);
}
@Override
public Void visit(PDFLayoutTextElement textContent) {
os.println(indent + "Element - Text: " + textContent.getText());
try {
indent();
visit(textContent.getFont());
output(textContent);
}
finally { unindent(); }
return null;
}
private void output(PDFLayoutElement item)
{
PDFLayoutBorderStyle border = item.getBorderStyle();
if (border != null)
{
os.println(indent + "Border Style");
indent();
try {
os.println(indent + "radius=" + border.getBorderRadius());
os.println(indent + "borders: " + border.getLineStyles());
}
finally { unindent(); }
}
os.println(indent + "fit = " + item.getObjectFit());
if (item.getPadding() != null)
os.println(indent + "padding = " + item.getPadding());
if (item.getPlacement() != null)
os.println(indent + "placement = " + item.getPlacement());
if (item.getBackgroundColor() != null)
os.println(indent + "background = " + item.getBackgroundColor ());
}
public void close()
{
os.flush();
if (out != null)
os.close();
}
private void indent()
{
indentCount++;
updateIndent();
}
private void unindent()
{
if (indentCount > 0)
indentCount--;
updateIndent();
}
private void updateIndent()
{ indent = new String(new char[indentCount]).replace("\0", INDENT); }
}
| {
"content_hash": "ecef31e7f45824df42a24ea42da4e62e",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 168,
"avg_line_length": 25.86868686868687,
"alnum_prop": 0.6762983209683717,
"repo_name": "emistoolbox/emistoolbox",
"id": "b3b68c7d656fb19580dc6babaea6f0f7c9db5993",
"size": "5122",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/pdf/src/com/emistoolbox/lib/pdf/util/PDFLayoutLogVisitor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "852"
},
{
"name": "C#",
"bytes": "111691"
},
{
"name": "CSS",
"bytes": "74403"
},
{
"name": "HTML",
"bytes": "34400"
},
{
"name": "Java",
"bytes": "3825395"
},
{
"name": "JavaScript",
"bytes": "40730"
},
{
"name": "Perl",
"bytes": "3782"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
<credit>NOAA's National Weather Service</credit>
<credit_URL>http://weather.gov/</credit_URL>
<image>
<url>http://weather.gov/images/xml_logo.gif</url>
<title>NOAA's National Weather Service</title>
<link>http://weather.gov</link>
</image>
<suggested_pickup>15 minutes after the hour</suggested_pickup>
<suggested_pickup_period>60</suggested_pickup_period>
<location>Unknown Station</location>
<station_id>44029</station_id>
<observation_time>Last Updated on Jan 4 2016, 10:04 pm AST</observation_time>
<observation_time_rfc822>Mon, 04 Jan 2016 22:04:00 -0400</observation_time_rfc822>
<temperature_string>24.8 F (-4.0 C)</temperature_string>
<temp_f>24.8</temp_f>
<temp_c>-4.0</temp_c>
<water_temp_f>45.9</water_temp_f>
<water_temp_c>7.7</water_temp_c>
<wind_string>North at 26.8 MPH (23.33 KT)</wind_string>
<wind_dir>North</wind_dir>
<wind_degrees>360</wind_degrees>
<wind_mph>26.8</wind_mph>
<wind_gust_mph>0.0</wind_gust_mph>
<wind_kt>23.33</wind_kt>
<windchill_string>9 F (-13 C)</windchill_string>
<windchill_f>9</windchill_f>
<windchill_c>-13</windchill_c>
<visibility_mi>1.60</visibility_mi>
<wave_height_m>2.1</wave_height_m>
<wave_height_ft>6.89</wave_height_ft>
<dominant_period_sec>8</dominant_period_sec>
<mean_wave_dir>North</mean_wave_dir>
<mean_wave_degrees></mean_wave_degrees>
<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>
| {
"content_hash": "1d033af4069dcb1da771088a8b178687",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 90,
"avg_line_length": 44.395348837209305,
"alnum_prop": 0.71503404924044,
"repo_name": "pjconsidine/codingclass",
"id": "b02d300768d7f1b05f2c6a876813ef49096930cb",
"size": "1909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WeatherApp/data/44029.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8178"
},
{
"name": "HTML",
"bytes": "12855"
},
{
"name": "JavaScript",
"bytes": "5031361"
},
{
"name": "Python",
"bytes": "305"
},
{
"name": "Shell",
"bytes": "2810"
}
],
"symlink_target": ""
} |
package org.assertj.db.util;
import org.assertj.db.api.assertions.impl.AssertionsOnValueComparison;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test on the utility class {@code AssertionsOnValue} : the private constructor.
*
* @author Régis Pouiller
*/
public class AssertionsOnValue_Constructor_Test {
/**
* This method tests the private constructor of {@code AssertionsOnValue} for the tests coverage..
*
* @throws NoSuchMethodException
* @throws SecurityException
* @throws java.lang.reflect.InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws IllegalArgumentException
*/
@Test
public void test_private_constructor_for_the_tests_coverage()
throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
Constructor<AssertionsOnValueComparison> constructor = AssertionsOnValueComparison.class.getDeclaredConstructor();
assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
constructor.setAccessible(true);
constructor.newInstance();
constructor.setAccessible(false);
}
}
| {
"content_hash": "94528e75f841192ece07cca83299322e",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 118,
"avg_line_length": 33.65853658536585,
"alnum_prop": 0.7782608695652173,
"repo_name": "otoniel-isidoro-sofist/assertj-db",
"id": "75f588874dd7ed6e8093c87f65de038fea843e3d",
"size": "1988",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/test/java/org/assertj/db/util/AssertionsOnValue_Constructor_Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3582361"
},
{
"name": "PLSQL",
"bytes": "1731"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Nizy-le-Comte est
un village
géographiquement positionné dans le département de l'Aisne en Picardie. Elle comptait 257 habitants en 2008.</p>
<p>À proximité de Nizy-le-Comte sont situées les villes de
<a href="{{VLROOT}}/immobilier/thour_08451/">Le Thour</a> à 3 km, 316 habitants,
<a href="{{VLROOT}}/immobilier/hannogne-saint-remy_08210/">Hannogne-Saint-Rémy</a> située à 7 km, 115 habitants,
<a href="{{VLROOT}}/immobilier/selve_02705/">La Selve</a> située à 4 km, 201 habitants,
<a href="{{VLROOT}}/immobilier/villers-devant-le-thour_08476/">Villers-devant-le-Thour</a> à 7 km, 303 habitants,
<a href="{{VLROOT}}/immobilier/saint-quentin-le-petit_08396/">Saint-Quentin-le-Petit</a> située à 2 km, 152 habitants,
<a href="{{VLROOT}}/immobilier/sevigny-waleppe_08418/">Sévigny-Waleppe</a> située à 4 km, 263 habitants,
entre autres. De plus, Nizy-le-Comte est située à seulement 23 km de <a href="{{VLROOT}}/immobilier/rethel_08362/">Rethel</a>.</p>
<p>La ville compte quelques aménagements, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.</p>
<p>Le parc de logements, à Nizy-le-Comte, était réparti en 2011 en neuf appartements et 110 maisons soit
un marché plutôt équilibré.</p>
<p>Si vous pensez demenager à Nizy-le-Comte, vous pourrez facilement trouver une maison à vendre. </p>
</div>
| {
"content_hash": "b8b2947a9e44ffe3bf5c9c87f84a6b43",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 136,
"avg_line_length": 79.16666666666667,
"alnum_prop": 0.7340350877192983,
"repo_name": "donaldinou/frontend",
"id": "c7909e5dc7237d62fcac73ac9a55b35d513b7bbf",
"size": "1455",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/02553.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "111338"
},
{
"name": "HTML",
"bytes": "58634405"
},
{
"name": "JavaScript",
"bytes": "88564"
},
{
"name": "PHP",
"bytes": "841919"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.