language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def govuk_template(context: Context, version='0.23.0', replace_fonts=True):
"""
Installs GOV.UK template
"""
if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')):
# NB: check is only on main template and not the assets included
return
url = 'https://github.com/alph... |
python | def _get_headers(self, environ):
"""The list of headers for this response
"""
headers = self.headers
method = environ['REQUEST_METHOD']
if has_empty_content(self.status_code, method) and method != HEAD:
headers.pop('content-type', None)
headers.pop('conte... |
java | @Override
public CPSpecificationOption findByUUID_G(String uuid, long groupId)
throws NoSuchCPSpecificationOptionException {
CPSpecificationOption cpSpecificationOption = fetchByUUID_G(uuid,
groupId);
if (cpSpecificationOption == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_E... |
java | private static String createFingerprintForUrl(final URI url) {
StringBuilder truncatedUrl = new StringBuilder(url.getHost());
String path = url.getPath();
if (path != null) {
truncatedUrl.append(path);
}
String query = url.getQuery();
if (query != n... |
java | @Override
public boolean listenToResultSet(final BenchmarkMethod meth, final AbstractMeter meter, final double data) {
Method m = meth.getMethodToBench();
try {
return view.updateCurrentElement(meter, (m.getDeclaringClass().getName() + "." + m.getName()));
} catch (final SocketVi... |
java | private RepositoryBrowser infer() {
for( AbstractProject p : Jenkins.getInstance().allItems(AbstractProject.class) ) {
SCM scm = p.getScm();
if (scm!=null && scm.getClass()==owner.getClass() && scm.getBrowser()!=null &&
((SCMDescriptor)scm.getDescriptor()).isBrowserRe... |
java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLInverseObjectPropertiesAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} |
python | def wavelength_match(a, b):
"""Return if two wavelengths are equal.
Args:
a (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
b (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
"""
if type(a) == (type(b) or
isinstance... |
java | public void displayValidation(String entityId, CmsValidationResult validationResult) {
if (m_formTabPanel != null) {
CmsAttributeHandler.clearErrorStyles(m_formTabPanel);
}
m_rootHandler.visit(CmsValidationHandler::clearValidation);
if (validationResult.hasWarnings(ent... |
python | def get_module(self, module_name):
"""Return loaded module from the given name."""
try:
return self.module[module_name]
except KeyError:
return sys.modules[module_name] |
java | @Override
public SIUncoordinatedTransaction createUncoordinatedTransaction()
throws SIConnectionUnavailableException, SIConnectionDroppedException,
SIErrorException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "cre... |
java | public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {
if(referenceDate == null) {
return null;
}
return referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));
} |
java | public static String getReconcileHashCode(Map<String, AtomicInteger> instanceCountMap) {
StringBuilder reconcileHashCode = new StringBuilder(75);
for (Map.Entry<String, AtomicInteger> mapEntry : instanceCountMap.entrySet()) {
reconcileHashCode.append(mapEntry.getKey()).append(STATUS_DELIMITE... |
python | def add(self, document):
"""
Add a document to the database.
"""
docid = int(document.uniqueIdentifier())
text = u' '.join(document.textParts())
self.store.executeSQL(self.addSQL, (docid, text)) |
java | @Override
public void clean() throws IOException {
if (this.isDatasetBlacklisted) {
this.log.info("Dataset blacklisted. Cleanup skipped for " + datasetRoot());
return;
}
boolean atLeastOneFailureSeen = false;
for (VersionFinderAndPolicy<T> versionFinderAndPolicy : getVersionFindersAndPo... |
python | def _priority(s):
"""Return priority for a given object."""
if type(s) in (list, tuple, set, frozenset):
return ITERABLE
if type(s) is dict:
return DICT
if issubclass(type(s), type):
return TYPE
if hasattr(s, "validate"):
return VALIDATOR
if callable(s):
r... |
python | def indirect(self, interface):
"""
Create an L{IConchUser} avatar which will use L{ShellServer} to
interact with the connection.
"""
if interface is IConchUser:
componentized = Componentized()
user = _BetterTerminalUser(componentized, None)
se... |
python | def convert_to_unicode( tscii_input ):
""" convert a byte-ASCII encoded string into equivalent Unicode string
in the UTF-8 notation."""
output = list()
prev = None
prev2x = None
# need a look ahead of 2 tokens atleast
for char in tscii_input:
## print "%2x"%ord(char) # debugging
... |
java | @Override
public void init(final ServletConfig config) throws ServletException {
try {
ContextClassLoaderUtils.doWithClassLoader(jasperClassLoader,
new Callable<Void>() {
@Override
public Void call() throws Exception {
config.getServletContext().setAttribute(
org.apache.... |
java | protected Predicate createPredicate(Path root, CriteriaQuery<?> query, CriteriaBuilder cb, String propertyName,
ComparisonOperator operator, Object argument, PersistenceContext context)
{
logger.debug("Creating criterion: {} {} {}", propertyName, operator, argument);
... |
python | def enabled(name):
'''
Enable the RDP service and make sure access to the RDP
port is allowed in the firewall configuration
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
if __opts... |
java | public static double getSwapAnnuity(double evaluationTime, ScheduleInterface schedule, DiscountCurveInterface discountCurve, AnalyticModelInterface model) {
double value = 0.0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {
double paymentDate = schedule.getPayment(periodIndex... |
python | def popitem(self):
"""Remove and return the `(key, value)` pair least frequently used."""
try:
(key, _), = self.__counter.most_common(1)
except ValueError:
raise KeyError('%s is empty' % self.__class__.__name__)
else:
return (key, self.pop(key)) |
java | public void sendGroupContact(final String groupId, final String[] contactIds) throws NotFoundException, GeneralException, UnauthorizedException {
// reuestByID appends the "ID" to the base path, so this workaround
// lets us add a query string.
String path = String.format("%s%s?%s", groupId, CON... |
python | def get_delay(self, planned, estimated):
"""Min of delay on planned departure."""
delay = 0 # default is no delay
if estimated >= planned: # there is a delay
delay = round((estimated - planned).seconds / 60)
else: # leaving earlier
... |
python | def add_dataset_to_collection(dataset_id, collection_id, **kwargs):
"""
Add a single dataset to a dataset collection.
"""
collection_i = _get_collection(collection_id)
collection_item = _get_collection_item(collection_id, dataset_id)
if collection_item is not None:
raise HydraError("... |
java | public static boolean addFilelistener(String pResourcename, String pListenerPath)
throws FileNotFoundException, IOException, ClassNotFoundException {
mFilelistenerToPaths = new HashMap<String, String>();
File listenerFilePaths = new File(StorageManager.ROOT_PATH + File.separator + "mapping.data... |
java | public static double binomialCdf(int k, double p, int n) {
if(k<0 || p<0 || n<1) {
throw new IllegalArgumentException("All the parameters must be positive and n larger than 1.");
}
k = Math.min(k, n);
double probabilitySum = approxBinomialCdf(k,p,n);
... |
python | def constrain(*objs):
"""Constrain group of DataFrames & Series to intersection of indices.
Parameters
----------
objs : iterable
DataFrames and/or Series to constrain
Returns
-------
new_dfs : list of DataFrames, copied rather than inplace
"""
# TODO: build i... |
java | public Date setMinSelectableDate(Date min) {
if (min == null) {
minSelectableDate = defaultMinSelectableDate;
} else {
minSelectableDate = min;
}
return minSelectableDate;
} |
java | private long grow(PrintStream out, List<ItemSet> list, TotalSupportTree ttree, HeaderTableItem header, int[] itemset, int[] localItemSupport, int[] prefixItemset) {
long n = 1;
int support = header.count;
int item = header.id;
itemset = insert(itemset, item);
collect(out, list, ... |
python | def from_dictionary(cls, dictionary):
"""Parse a dictionary representing all command line parameters."""
if not isinstance(dictionary, dict):
raise TypeError('dictionary has to be a dict type, got: {}'.format(type(dictionary)))
return cls(dictionary) |
java | public String[] getBuildMetaDataParts() {
if (this.buildMetaDataParts.length == 0) {
return EMPTY_ARRAY;
}
return Arrays.copyOf(this.buildMetaDataParts, this.buildMetaDataParts.length);
} |
python | def execute(self, input_data):
''' Execute method '''
# Grab the raw bytes of the sample
raw_bytes = input_data['sample']['raw_bytes']
# Spin up the rekall session and render components
session = MemSession(raw_bytes)
renderer = WorkbenchRenderer(session=session)
... |
java | private boolean hasTextContent(Node child) {
return child.getNodeType() != Node.COMMENT_NODE
&& child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
} |
java | private void executeGlobalPostProcessing(boolean processBundleFlag, StopWatch stopWatch) {
// Launch global postprocessing
if (resourceTypePostprocessor != null) {
if (stopWatch != null) {
stopWatch.start("Global postprocessing");
}
GlobalPostProcessingContext ctx = new GlobalPostProcessingContext(conf... |
java | public static long convertToUtc(long millis, String tz)
{
long ret = millis;
if(tz != null && tz.length() > 0)
{
DateTime dt = new DateTime(millis, DateTimeZone.forID(tz));
ret = dt.withZoneRetainFields(DateTimeZone.forID("UTC")).getMillis();
}
return ... |
python | def mount_control_encode(self, target_system, target_component, input_a, input_b, input_c, save_position):
'''
Message to control a camera mount, directional antenna, etc.
target_system : System ID (uint8_t)
target_component : Compone... |
python | def load_fasta_file(filename):
"""Load a FASTA file and return the sequences as a list of SeqRecords
Args:
filename (str): Path to the FASTA file to load
Returns:
list: list of all sequences in the FASTA file as Biopython SeqRecord objects
"""
with open(filename, "r") as handle:
... |
java | private EDiff diffAlgorithm(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx,
final DepthCounter paramDepth) throws TTIOException {
EDiff diff = null;
// Check if node has been deleted.
if (paramDepth.getOldDepth() > paramDepth.getNewDepth()) {
diff = EDiff.DEL... |
python | def publish(self,message,message_type,topic=''):
"""
Publish the message on the PUB socket with the given topic name.
Args:
- message: the message to publish
- message_type: the type of message being sent
- topic: the topic on which to send the messag... |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString sessionid_validator = new MPSString();
sessionid_validator.setConstraintIsReq(MPSConstants.DELETE_CONSTRAINT, true);
sessionid_validator.validate(operationType, sessionid, "\"sessionid\"");
M... |
python | def read(self):
"""Read a DNS master file and build a zone object.
@raises dns.zone.NoSOA: No SOA RR was found at the zone origin
@raises dns.zone.NoNS: No NS RRset was found at the zone origin
"""
try:
while 1:
token = self.tok.get(True, True).unesc... |
python | def open(filename, frame='unspecified'):
"""Create a Point from data saved in a file.
Parameters
----------
filename : :obj:`str`
The file to load data from.
frame : :obj:`str`
The frame to apply to the created point.
Returns
-------
... |
java | private String toXml(Node node) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
... |
python | def _validate_overriden_fields_are_not_defined_in_superclasses(class_to_field_type_overrides,
schema_graph):
"""Assert that the fields we want to override are not defined in superclasses."""
for class_name, field_type_overrides in six.iteritems(clas... |
python | def inbox_count_for(user):
"""
returns the number of unread messages for the given user but does not
mark them seen
"""
return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count() |
java | private void RGBtoHSV(float red, float green, float blue) {
float min = 0;
float max = 0;
float delta = 0;
min = MIN(red, green, blue);
max = MAX(red, green, blue);
m_bri = max; // v
delta = max - min;
if (max != 0) {
m_sat =... |
python | def main():
"""
NAME
fisher.py
DESCRIPTION
generates set of Fisher distribed data from specified distribution
INPUT (COMMAND LINE ENTRY)
OUTPUT
dec, inc
SYNTAX
fisher.py [-h] [-i] [command line options]
OPTIONS
-h prints help message and quits
... |
java | public Generic onWildcard(Generic wildcard) {
return new OfWildcardType.Latent(wildcard.getUpperBounds().accept(this), wildcard.getLowerBounds().accept(this), wildcard);
} |
java | private void resetCorrectOffsets(ConsumerWorker worker) {
KafkaConsumer<String, Serializable> consumer = worker.consumer;
Map<String, List<PartitionInfo>> topicInfos = consumer.listTopics();
Set<String> topics = topicInfos.keySet();
List<String> expectTopics = new ArrayList<>(topicHandlers.keySet());
... |
python | def nsummary(self,prn=None, lfilter=None):
"""prints a summary of each packet with the packet's number
prn: function to apply to each packet instead of lambda x:x.summary()
lfilter: truth function to apply to each packet to decide whether it will be displayed"""
for i, p in enumerate(self.res):
... |
python | def _parse_method_response(self, method_name, method_response, httpStatus):
'''
Helper function to construct the method response params, models, and integration_params
values needed to configure method response integration/mappings.
'''
method_response_models = {}
method_... |
python | def set_scope(self, include=None, exclude=None):
"""
Sets `scope`, the "start point" for the audit.
Args:
include: A list of css selectors specifying the elements that
contain the portion of the page that should be audited.
Defaults to auditing the e... |
java | public DocumentT findOneAndDelete(final Bson filter) {
return operations.findOneAndModify(
"findOneAndDelete",
filter,
new BsonDocument(),
new RemoteFindOneAndModifyOptions(),
documentClass).execute(service);
} |
java | public static String getBaseHash(Object object) {
return object.getClass().getSimpleName() + "@" + Integer.toString((new Object()).hashCode());
} |
java | public com.google.api.ads.adwords.axis.v201809.cm.AdCustomizerFeedAttribute[] getFeedAttributes() {
return feedAttributes;
} |
java | public Set<ArtifactSpec> getTransientDependencies() {
if (null == allTransient) {
allTransient = getTransientDependencies(true, true);
}
return allTransient;
} |
java | public Stroke getStroke() {
Stroke theStroke = stroke;
if (theStroke == null) {
theStroke = new BasicStroke(strokeWidth);
stroke = theStroke;
}
return theStroke;
} |
java | public static PrimitiveIterator.OfInt of(ThrowingIterator.OfInt<Nothing> itr) {
return of(itr, Nothing.class);
} |
java | public static File toFile(final URL aURL) throws MalformedURLException {
if (aURL.getProtocol().equals(FILE_TYPE)) {
return new File(aURL.toString().replace("file:", ""));
}
throw new MalformedURLException(LOGGER.getI18n(MessageCodes.UTIL_036, aURL));
} |
java | public static ChromPos getChromPosForward(int cdsPos, List<Integer> exonStarts, List<Integer> exonEnds, int cdsStart, int cdsEnd) {
boolean inCoding = false;
int codingLength = 0;
@SuppressWarnings("unused")
int lengthExons = 0;
// map forward
for (int i = 0; i < exonStarts.size(); i++) {
// start can ... |
python | def create_char(self, location, pattern):
"""Fill one of the first 8 CGRAM locations with custom characters.
The location parameter should be between 0 and 7 and pattern should
provide an array of 8 bytes containing the pattern. E.g. you can easyly
design your custom character at http://... |
python | def run_file(path):
"""Run a module from a path and return its variables."""
if PY26:
dirpath, name, _ = splitname(path)
found = imp.find_module(name, [dirpath])
module = imp.load_module("__main__", *found)
return vars(module)
else:
return runpy.run_path(path, run_nam... |
python | def update(self, date, data=None, inow=None):
"""
Update strategy. Updates prices, values, weight, etc.
"""
# resolve stale state
self.root.stale = False
# update helpers on date change
# also set newpt flag
newpt = False
if self.now == 0:
... |
java | @SuppressWarnings("deprecation")
private void addGalleriesForType(Map<String, CmsGalleryTypeInfo> galleryTypeInfos, String typeName)
throws CmsLoaderException {
I_CmsResourceType contentType = getResourceManager().getResourceType(typeName);
for (I_CmsResourceType galleryType : contentType.getGa... |
java | public void setTargetGroupInfoList(java.util.Collection<TargetGroupInfo> targetGroupInfoList) {
if (targetGroupInfoList == null) {
this.targetGroupInfoList = null;
return;
}
this.targetGroupInfoList = new com.amazonaws.internal.SdkInternalList<TargetGroupInfo>(targetGrou... |
java | public Request releaseRequest(Thread thread) {
int threadId = thread.hashCode();
synchronized (requestsByThreadId) {
StandardRequest request = (StandardRequest) requestsByThreadId.get(threadId);
if (request != null) {
if (request.getTimesEntered() > 0) {
request.decreaseTimesEntered();
} else {
... |
java | @RequestMapping(value = "project-sync/{projectId}", method = RequestMethod.GET)
public GitSynchronisationInfo getProjectGitSyncInfo(@PathVariable ID projectId) {
Project project = structureService.getProject(projectId);
return gitService.getProjectGitSyncInfo(project);
} |
java | @Override
public synchronized void free(Page page) {
if (page.isFreeable()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Freeing a {}B buffer from chunk {} &{}", DebuggingUtils.toBase2SuffixedString(page.size()), page.index(), page.address());
}
markAllA... |
python | def _get_real_ip(self):
"""
Get IP from request.
:param request: A usual request object
:type request: HttpRequest
:return: ipv4 string or None
"""
try:
# Trying to work with most common proxy headers
real_ip = self.request.META['HTTP_X_FO... |
java | public void marshall(ExecutionStartedEventDetails executionStartedEventDetails, ProtocolMarshaller protocolMarshaller) {
if (executionStartedEventDetails == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.mars... |
python | def stop_all(self):
"""
Stop all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.stop)
yield from pool.join() |
java | private void writeConstructor(GinjectorBindings bindings, SourceWriteUtil sourceWriteUtil,
SourceWriter writer) {
String implClassName = ginjectorNameGenerator.getClassName(bindings);
if (bindings.getParent() == null) {
// In outputInterfaceField, we verify that we have a bound injector if we
... |
java | protected boolean isConfigLocation(URI location) {
String scheme = location.getScheme();
if (scheme == null) {
// interpret as place holder
try {
String resolvedPlaceholder = getProperty(location.getRawSchemeSpecificPart());
if (resolvedPlaceholder... |
python | def add_librispeech_hparams(hparams):
"""Adding to base hparams the attributes for for librispeech."""
hparams.batch_size = 36
hparams.audio_compression = 8
hparams.hidden_size = 2048
hparams.max_input_seq_length = 600000
hparams.max_target_seq_length = 350
hparams.max_length = hparams.max_input_seq_lengt... |
python | def migrate_autoload_details(autoload_details, shell_name, shell_type):
""" Migrate autoload details. Add namespace for attributes
:param autoload_details:
:param shell_name:
:param shell_type:
:return:
"""
mapping = {}
for resource in autoload_details.resources:
resource.model... |
python | def from_csv(cls, filename):
"""Create gyro stream from CSV data
Load data from a CSV file.
The data must be formatted with three values per line: (x, y, z)
where x, y, z is the measured angular velocity (in radians) of the specified axis.
Parameters
-------------------... |
java | public void marshall(FailWorkflowExecutionDecisionAttributes failWorkflowExecutionDecisionAttributes, ProtocolMarshaller protocolMarshaller) {
if (failWorkflowExecutionDecisionAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
... |
python | def audit_trail_users(self):
'''A set of all usernames recorded in the :attr:`audit_trail`,
if available.'''
if self.audit_trail:
return set([r.user for r in self.audit_trail.records])
return set() |
java | public static float[] asFloatTypeArray(List<Float> input) {
float[] result = new float[input.size()];
for (int i = 0; i < result.length; i++) {
result[i] = input.get(i);
}
return result;
} |
java | public void copyToMasterPrimaryKey(Storable reference, S master) throws FetchException {
try {
mCopyToMasterPkMethod.invoke(reference, master);
} catch (Exception e) {
ThrowUnchecked.fireFirstDeclaredCause(e, FetchException.class);
}
} |
java | private RowKeyBuilder initializeRowKeyBuilder() {
RowKeyBuilder builder = new RowKeyBuilder();
if ( hasIdentifier ) {
builder.addColumns( getIdentifierColumnName() );
}
else {
builder.addColumns( getKeyColumnNames() );
// !isOneToMany() present in delete not in update
if ( !isOneToMany() && hasIndex... |
java | public static byte[] toByteArray(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
bitmap.compress(format, quality, out);
return out.toByteArray();
} finally {
Clo... |
java | @Override
public boolean hasStableIds() {
Collection<? extends Binder<?, ?>> allBinders = getAllBinders();
if (allBinders.size() == 1) {
// Save an allocation by checking for List first.
if (allBinders instanceof List) {
//noinspection unchecked
... |
java | public com.google.api.ads.adwords.axis.v201809.o.StatsEstimate getMaxEstimate() {
return maxEstimate;
} |
java | public static Point multiply(Point p, BigInteger k) {
BigInteger e = k;
BigInteger h = e.multiply(BigInteger.valueOf(3));
Point neg = p.negate();
Point R = p;
for (int i = h.bitLength() - 2; i > 0; --i) {
R = R.twice();
boolean hBit = h.testBit(i);
boolean eBi... |
python | def main(args=None):
"""Call the CLI interface and wait for the result."""
retcode = 0
try:
ci = CliInterface()
args = ci.parser.parse_args()
result = args.func(args)
if result is not None:
print(result)
retcode = 0
except Exception:
retcode = ... |
java | @Nullable
@Override
public String apply(@Nullable String key)
{
if (NullHandling.isNullOrEquivalent(key)) {
return null;
}
return key.toLowerCase(locale);
} |
python | def federation_payment(self,
fed_address,
amount,
asset_code='XLM',
asset_issuer=None,
source=None,
allow_http=False):
"""Append a :class:`Payment <st... |
java | public With andWith(final String alias, final Expression expression) {
this.clauses.add(new ImmutablePair<>(new Name(alias), expression));
return this;
} |
java | public void buildMethodDetails(XMLNode node,
Content memberDetailsTree) throws DocletException {
configuration.getBuilderFactory().
getMethodBuilder(writer).buildChildren(node, memberDetailsTree);
} |
python | def __remove_handler_factory(self, svc_ref):
# type: (ServiceReference) -> None
"""
Removes an handler factory
:param svc_ref: ServiceReference of the handler factory to remove
"""
with self.__handlers_lock:
# Get the handler ID
handler_id = svc_r... |
java | protected void reset()
{
this.active = false;
synchronized (this.cachedChannelsNonTransactional)
{
for (ChannelProxy channel : this.cachedChannelsNonTransactional)
{
try
{
channel.getTargetChannel().close();
... |
java | private void parseRange() throws BadThresholdException {
PushbackReader reader = new PushbackReader(new StringReader(thresholdString));
StringBuilder currentParsedBuffer = new StringBuilder();
byte b;
try {
while ((b = (byte) reader.read()) != -1) {
curren... |
java | public static BizuinInfoResult getCardBizuinInfo(String access_token, BizuinInfo bizuinCube) {
return getCardBizuinInfo(access_token, JsonUtil.toJSONString(bizuinCube));
} |
java | public double getColorPercentage(Area node)
{
int tlen = 0;
double sum = 0;
for (Box box : node.getBoxes())
{
int len = letterLength(box.getText());
if (len > 0)
{
sum += getColorPercentage(box.getColor()) * len;
tlen += len;
}
}
... |
java | public int getOffset(int era, int year, int month,int dom, int dow, int millis, int monthLength){
if ((era != GregorianCalendar.AD && era != GregorianCalendar.BC)
|| month < Calendar.JANUARY
|| month > Calendar.DECEMBER
|| dom < 1
|| dom > monthLength
... |
python | def match(path, glob):
"""Match the path with the glob.
Arguments:
path -- A list of keys representing the path.
glob -- A list of globs to match against the path.
"""
path_len = len(path)
glob_len = len(glob)
ss = -1
ss_glob = glob
if '**' in glob:
ss = glob.index('*... |
java | private void addHighlights(Collection<? extends Point> points, Color color)
{
removeHighlights(points);
Map<Point, Object> newHighlights =
JTextComponents.addHighlights(textComponent, points, color);
highlights.putAll(newHighlights);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.