file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
handlers.py | """App related signal handlers."""
import redis
from django.conf import settings
from django.db.models import signals
from django.dispatch import receiver
from modoboa.admin import models as admin_models
from . import constants
def | (instance, key):
"""Store message limit in Redis."""
old_message_limit = instance._loaded_values.get("message_limit")
if old_message_limit == instance.message_limit:
return
rclient = redis.Redis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_QUOTA_... | set_message_limit | identifier_name |
handlers.py | """App related signal handlers."""
import redis
from django.conf import settings
from django.db.models import signals
from django.dispatch import receiver
from modoboa.admin import models as admin_models
from . import constants
def set_message_limit(instance, key):
"""Store message limit in Redis."""
old_... | if rclient.hexists(constants.REDIS_HASHNAME, key):
rclient.hdel(constants.REDIS_HASHNAME, key)
return
if old_message_limit is not None:
diff = instance.message_limit - old_message_limit
else:
diff = instance.message_limit
rclient.hincrby(constants.REDIS_HASHNAME, ... | if instance.message_limit is None:
# delete existing key | random_line_split |
handlers.py | """App related signal handlers."""
import redis
from django.conf import settings
from django.db.models import signals
from django.dispatch import receiver
from modoboa.admin import models as admin_models
from . import constants
def set_message_limit(instance, key):
"""Store message limit in Redis."""
old_... | """Store mailbox message limit in Redis."""
set_message_limit(instance, instance.full_address) | identifier_body | |
jinja_template.py | #!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Renders one or more template files using the Jinja template engine."""
import codecs
import argparse
import os
import sys
from u... | (self, loader_base_dir, variables=None):
self.loader_base_dir = loader_base_dir
self.variables = variables or {}
self.loader = _RecordingFileSystemLoader(loader_base_dir)
self.env = jinja2.Environment(loader=self.loader)
self.env.undefined = jinja2.StrictUndefined
self.env.line_comment_prefix = ... | __init__ | identifier_name |
jinja_template.py | #!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Renders one or more template files using the Jinja template engine."""
import codecs
import argparse
import os
import sys
from u... | 'the input. Required if --output-zip is given.')
parser.add_argument('--loader-base-dir', help='Base path used by the '
'template loader. Must be a common ancestor directory of '
'the inputs. Defaults to DIR_SOURCE_ROOT.',
default... | random_line_split | |
jinja_template.py | #!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Renders one or more template files using the Jinja template engine."""
import codecs
import argparse
import os
import sys
from u... |
return template.render(variables or self.variables)
def GetLoadedTemplates(self):
return list(self.loader.loaded_templates)
def _ProcessFile(processor, input_filename, output_filename):
output = processor.Render(input_filename)
with codecs.open(output_filename, 'w', 'utf-8') as output_file:
output... | template = self.env.get_template(input_rel_path)
self._template_cache[input_rel_path] = template | conditional_block |
jinja_template.py | #!/usr/bin/env python
#
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Renders one or more template files using the Jinja template engine."""
import codecs
import argparse
import os
import sys
from u... |
def _ParseVariables(variables_arg, error_func):
variables = {}
for v in build_utils.ParseGnList(variables_arg):
if '=' not in v:
error_func('--variables argument must contain "=": ' + v)
name, _, value = v.partition('=')
variables[name] = value
return variables
def main():
parser = argpar... | with build_utils.TempDir() as temp_dir:
for input_filename in input_filenames:
relpath = os.path.relpath(os.path.abspath(input_filename),
os.path.abspath(inputs_base_dir))
if relpath.startswith(os.pardir):
raise Exception('input file %s is not contained in inputs ... | identifier_body |
bigquery.py | # 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 u... |
@classmethod
def df_to_sql(cls, df: pd.DataFrame, **kwargs: Any) -> None:
"""
Upload data from a Pandas DataFrame to BigQuery. Calls
`DataFrame.to_gbq()` which requires `pandas_gbq` to be installed.
:param df: Dataframe with data to be uploaded
:param kwargs: kwargs to... | return "TIMESTAMP_MILLIS({col})" | identifier_body |
bigquery.py | # 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 u... | (
cls, database: "Database", table_name: str, schema_name: str
) -> Dict[str, Any]:
indexes = database.get_indexes(table_name, schema_name)
if not indexes:
return {}
partitions_columns = [
index.get("column_names", [])
for index in indexes
... | extra_table_metadata | identifier_name |
bigquery.py | # 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 u... |
gbq_kwargs = {}
gbq_kwargs["project_id"] = kwargs["con"].engine.url.host
gbq_kwargs["destination_table"] = f"{kwargs.pop('schema')}.{kwargs.pop('name')}"
# add credentials if they are set on the SQLAlchemy Dialect:
creds = kwargs["con"].dialect.credentials_info
if cred... | raise Exception("name, schema and con need to be defined in kwargs") | conditional_block |
bigquery.py | # 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 u... | return label_mutated
@classmethod
def _truncate_label(cls, label: str) -> str:
"""BigQuery requires column names start with either a letter or
underscore. To make sure this is always the case, an underscore is prefixed
to the md5 hash of the original label.
:param label... | label_mutated = re.sub(r"[^\w]+", "_", label_mutated)
if label_mutated != label:
# add first 5 chars from md5 hash to label to avoid possible collisions
label_mutated += label_hashed[:6]
| random_line_split |
bingrep_dump.py | # BinGrep, version 1.0.0
# Copyright 2017 Hiroki Hada
# coding:UTF-8
import sys, os, time, argparse
import re
import pprint
#import pydot
import math
import cPickle
import ged_node
from idautils import *
from idc import *
import idaapi
def idascript_exit(code=0):
idc.Exit(code)
def get_short_function_name(functi... |
def cfg_to_cft(cfg):
block = cfg[0]
memo = []
memo.append(block.startEA)
return cfg_to_cft_rec(block, memo, (0, 0, 0))
def dump_function_info(cfgs, program, function, f_image, f_all, f_overwrite):
function_num = len(cfgs)
dump_data_list = {}
for cfg in cfgs:
function_name ... | (alpha, beta, gamma) = abr
alpha += 1
marks, gamma = get_marks(block, gamma)
hashed_label = hash_label(marks)
mnems = get_mnems(block)
tree = ged_node.Node(hashed_label)
for b in list(block.succs()):
beta += 1
if b.startEA not in memo:
memo.append(b.... | identifier_body |
bingrep_dump.py | # BinGrep, version 1.0.0
# Copyright 2017 Hiroki Hada
# coding:UTF-8
import sys, os, time, argparse
import re
import pprint
#import pydot
import math
import cPickle
import ged_node
from idautils import *
from idc import *
import idaapi
def idascript_exit(code=0):
idc.Exit(code)
def get_short_function_name(functi... | return tree, (alpha, beta, gamma), mnems
def cfg_to_cft(cfg):
block = cfg[0]
memo = []
memo.append(block.startEA)
return cfg_to_cft_rec(block, memo, (0, 0, 0))
def dump_function_info(cfgs, program, function, f_image, f_all, f_overwrite):
function_num = len(cfgs)
dump_data_list = {}
... | random_line_split | |
bingrep_dump.py | # BinGrep, version 1.0.0
# Copyright 2017 Hiroki Hada
# coding:UTF-8
import sys, os, time, argparse
import re
import pprint
#import pydot
import math
import cPickle
import ged_node
from idautils import *
from idc import *
import idaapi
def idascript_exit(code=0):
idc.Exit(code)
def get_short_function_name(functi... |
return cfgs
def hash_label(marks):
tmp = sorted(set(marks))
tmp = "".join(tmp)
tmp = tmp.upper()
def rot13(string):
return reduce(lambda h,c: ((h>>13 | h<<19)+ord(c)) & 0xFFFFFFFF, [0]+list(string))
hashed_label = rot13(tmp)
hashed_label = hashed_label & 0xFFFFFFFF
return ha... | functions = list(Functions(SegStart(ea), SegEnd(ea)))
functions.append(SegEnd(ea))
for i in range(len(functions) - 1):
function_start = functions[i]
function_end = functions[i+1]
cfg = get_cfg(function_start, function_end)
cfgs.append(cfg) | conditional_block |
bingrep_dump.py | # BinGrep, version 1.0.0
# Copyright 2017 Hiroki Hada
# coding:UTF-8
import sys, os, time, argparse
import re
import pprint
#import pydot
import math
import cPickle
import ged_node
from idautils import *
from idc import *
import idaapi
def idascript_exit(code=0):
idc.Exit(code)
def get_short_function_name(functi... | (cfgs, program, function, f_image, f_all, f_overwrite):
function_num = len(cfgs)
dump_data_list = {}
for cfg in cfgs:
function_name = GetFunctionName(cfg[0].startEA)
(cft, abr, mnems) = cfg_to_cft(cfg)
dump_data_list[function_name] = {}
dump_data_list[function_name]... | dump_function_info | identifier_name |
series_rolling_median.py | # *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... | ():
series = pd.Series([4, 3, 5, 2, 6]) # Series of 4, 3, 5, 2, 6
out_series = series.rolling(3).median()
return out_series # Expect series of NaN, NaN, 4.0, 3.0, 5.0
print(series_rolling_median())
| series_rolling_median | identifier_name |
series_rolling_median.py | # *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... | return out_series # Expect series of NaN, NaN, 4.0, 3.0, 5.0
print(series_rolling_median()) | out_series = series.rolling(3).median()
| random_line_split |
series_rolling_median.py | # *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... |
print(series_rolling_median())
| series = pd.Series([4, 3, 5, 2, 6]) # Series of 4, 3, 5, 2, 6
out_series = series.rolling(3).median()
return out_series # Expect series of NaN, NaN, 4.0, 3.0, 5.0 | identifier_body |
Core.UI.Datepicker.js | // --
// Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
C... |
if (typeof LocalizationData === 'undefined') {
LocalizationData = Core.Config.Get('Datepicker.Localization');
if (typeof LocalizationData === 'undefined') {
throw new Core.Exception.ApplicationError('Datepicker localization data could not be found!', 'InternalError');
... | {
if (Number.toString().length === 1) {
return '0' + Number;
}
else {
return Number;
}
} | identifier_body |
Core.UI.Datepicker.js | // --
// Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
C... |
var $DatepickerElement,
HasDateSelectBoxes = false,
Options,
ErrorMessage;
if (typeof Element.VacationDays === 'object') {
Core.Config.Set('Datepicker.VacationDays', Element.VacationDays);
}
/**
* @private
* @name Leadi... | TargetNS.Init = function (Element) { | random_line_split |
Core.UI.Datepicker.js | // --
// Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
C... |
};
Options.beforeShow = function (Input) {
$(Input).val('');
return {
defaultDate: new Date(Element.Year.val(), Element.Month.val() - 1, Element.Day.val())
};
};
$DatepickerElement.datepicker(Options);
// Add some DOM notes t... | {
Element.Year.val(Year);
Element.Month.val(LeadingZero(Month));
Element.Day.val(LeadingZero(Day));
} | conditional_block |
Core.UI.Datepicker.js | // --
// Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
C... | (Number) {
if (Number.toString().length === 1) {
return '0' + Number;
}
else {
return Number;
}
}
if (typeof LocalizationData === 'undefined') {
LocalizationData = Core.Config.Get('Datepicker.Localization');
... | LeadingZero | identifier_name |
_schema.py | #!/usr/bin/python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is d... |
if path:
messages.insert(0, "The '{}' property does not match the "
"required schema:".format('/'.join(path)))
if e.cause:
messages.append('({})'.format(e.cause))
raise SnapcraftSchemaError(' '.join(messages))
| path.append(str(element)) | conditional_block |
_schema.py | #!/usr/bin/python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is d... | messages.insert(0, "The '{}' property does not match the "
"required schema:".format('/'.join(path)))
if e.cause:
messages.append('({})'.format(e.cause))
raise SnapcraftSchemaError(' '.join(messages)) | else:
path.append(str(element))
if path: | random_line_split |
_schema.py | #!/usr/bin/python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is d... |
@property
def schema(self):
"""Return all schema properties."""
return self._schema['properties'].copy()
@property
def part_schema(self):
"""Return part-specific schema properties."""
sub = self.schema['parts']['patternProperties']
properties = sub['^(?!plugi... | """Create a validation instance for snapcraft_yaml."""
self._snapcraft = snapcraft_yaml if snapcraft_yaml else {}
self._load_schema() | identifier_body |
_schema.py | #!/usr/bin/python3
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is d... | (self, message):
self._message = message
class Validator:
def __init__(self, snapcraft_yaml=None):
"""Create a validation instance for snapcraft_yaml."""
self._snapcraft = snapcraft_yaml if snapcraft_yaml else {}
self._load_schema()
@property
def schema(self):
"""... | __init__ | identifier_name |
usage-builder.js | 'use strict';
const { extend } = require('underscore');
const dbclient = require('abacus-dbclient');
const { testCollectedUsageID, testResourceID, testOrganizationID, testSpaceID, testConsumerID, testPlanID,
testResourceType, testAccountID, testMeteringPlanID, testRatingPlanID,
testPricingPlanID } = require('./f... | const buildUsage = (...builders) => {
const usage = {};
for(let builder of builders)
builder(usage);
return extend(usage, {
id: dbclient.kturi(usage.resource_instance_id, usage.processed)
});
};
const withEndTimestamp = (timestamp) => (usage) => usage.end = timestamp;
const withStartTimestamp = (time... | };
| random_line_split |
index.js | /*global describe, it, assert, clone */
/*jshint browser: true */
describe('clone', function () {
'use strict';
it('should clone an object', function () {
var obj = {
cats: true,
dogs: 2,
fish: [ 0, 1, 2 ]
};
var c = clone(obj);
obj.cats = false;
obj.dogs = 1;
obj.fish[0] = 'stuff';
assert.s... | Cat.prototype.bark = function () {
return 'cats dont bark';
};
var cat = new Cat('Fred'),
c = clone(cat);
assert.deepEqual(cat.name, c.name);
assert.deepEqual(Cat.prototype.bark, c.bark);
assert.deepEqual(Cat.prototype.meow, c.meow);
});
}); |
Cat.prototype.meow = function () {
return 'meow';
};
| random_line_split |
index.js | /*global describe, it, assert, clone */
/*jshint browser: true */
describe('clone', function () {
'use strict';
it('should clone an object', function () {
var obj = {
cats: true,
dogs: 2,
fish: [ 0, 1, 2 ]
};
var c = clone(obj);
obj.cats = false;
obj.dogs = 1;
obj.fish[0] = 'stuff';
assert.s... |
Cat.prototype.meow = function () {
return 'meow';
};
Cat.prototype.bark = function () {
return 'cats dont bark';
};
var cat = new Cat('Fred'),
c = clone(cat);
assert.deepEqual(cat.name, c.name);
assert.deepEqual(Cat.prototype.bark, c.bark);
assert.deepEqual(Cat.prototype.meow, c.meow);
})... | {
this.name = name;
} | identifier_body |
index.js | /*global describe, it, assert, clone */
/*jshint browser: true */
describe('clone', function () {
'use strict';
it('should clone an object', function () {
var obj = {
cats: true,
dogs: 2,
fish: [ 0, 1, 2 ]
};
var c = clone(obj);
obj.cats = false;
obj.dogs = 1;
obj.fish[0] = 'stuff';
assert.s... | (name) {
this.name = name;
}
Cat.prototype.meow = function () {
return 'meow';
};
Cat.prototype.bark = function () {
return 'cats dont bark';
};
var cat = new Cat('Fred'),
c = clone(cat);
assert.deepEqual(cat.name, c.name);
assert.deepEqual(Cat.prototype.bark, c.bark);
assert.deepEqual... | Cat | identifier_name |
how_sexy_is_your_name.py | SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3,
'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25, | name_score = sum(SCORES.get(a, 0) for a in name.upper())
if name_score >= 600:
return 'THE ULTIMATE SEXIEST'
elif name_score >= 301:
return 'VERY SEXY'
elif name_score >= 60:
return 'PRETTY SEXY'
return 'NOT TOO SEXY' | 'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405,
'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23}
def sexy_name(name): | random_line_split |
how_sexy_is_your_name.py | SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3,
'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25,
'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405,
'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23}
def | (name):
name_score = sum(SCORES.get(a, 0) for a in name.upper())
if name_score >= 600:
return 'THE ULTIMATE SEXIEST'
elif name_score >= 301:
return 'VERY SEXY'
elif name_score >= 60:
return 'PRETTY SEXY'
return 'NOT TOO SEXY'
| sexy_name | identifier_name |
how_sexy_is_your_name.py | SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3,
'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25,
'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405,
'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23}
def sexy_name(name):
| name_score = sum(SCORES.get(a, 0) for a in name.upper())
if name_score >= 600:
return 'THE ULTIMATE SEXIEST'
elif name_score >= 301:
return 'VERY SEXY'
elif name_score >= 60:
return 'PRETTY SEXY'
return 'NOT TOO SEXY' | identifier_body | |
how_sexy_is_your_name.py | SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3,
'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25,
'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405,
'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23}
def sexy_name(name):
name_score =... |
elif name_score >= 301:
return 'VERY SEXY'
elif name_score >= 60:
return 'PRETTY SEXY'
return 'NOT TOO SEXY'
| return 'THE ULTIMATE SEXIEST' | conditional_block |
assoc-types.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
// @has assoc_types/fn.cmp_input.html
// @has - '//*[@class="rust fn"]' 'where T::Input: PartialEq<U::Input>'
pub fn cmp_input<T: Feed, U: Feed>(a: &T::Input, b: &U::Input) -> bool
where T::Input: PartialEq<U::Input>
{
a == b
}
| { } | identifier_body |
assoc-types.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T: Index<usize>>(obj: &T, index: usize) -> &T::Output {
obj.index(index)
}
pub trait Feed {
type Input;
}
// @has assoc_types/fn.use_input.html
// @has - '//*[@class="rust fn"]' 'T::Input'
pub fn use_input<T: Feed>(_feed: &T, _element: T::Input) { }
// @has assoc_types/fn.cmp_input.html
// @has - '//*[@clas... | use_output | identifier_name |
assoc-types.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_type="lib"]
// @has assoc_types/trait.Index.html
pub trait Index<I: ?Sized> {
// @has - '//*[@id="associatedtype.Output"]//code' 'type Output: ?Sized'
type Output: ?Sized;
// @has - '//*[@id="tyme... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
display-final-after-month-is-over.py | #!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python | import pyperclip
# Edit Me!
# This script gets run on the first day of the following month, and that month's URL is
# what goes here. E.g. If this directory is the directory for February, this script gets
# run on March 1, and this URL is the URL for the March challenge page.
nextMonthURL = "https://www.reddit.com/r/... |
from participantCollection import ParticipantCollection
import re
import datetime | random_line_split |
display-final-after-month-is-over.py | #!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
from participantCollection import ParticipantCollection
import re
import datetime
import pyperclip
# Edit Me!
# This script gets run on the first day of the following month, and that month's UR... |
def templateToUse():
answer = ""
answer += "The Stay Clean CURRENT_MONTH_NAME challenge is now over. Join us for **[the NEXT_MONTH_NAME challenge](NEXT_MONTH_URL)**.\n"
answer += "\n"
answer += "**NUMBER_STILL_IN** out of INITIAL_NUMBER participants made it all the way through the challenge. That's ... | answer = ""
for participant in participants.participantsWhoAreStillInAndHaveCheckedIn():
answer += "/u/" + participant.name
answer += "\n\n"
return answer | identifier_body |
display-final-after-month-is-over.py | #!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
from participantCollection import ParticipantCollection
import re
import datetime
import pyperclip
# Edit Me!
# This script gets run on the first day of the following month, and that month's UR... | ():
answer = ""
for participant in participants.participantsWhoAreStillInAndHaveCheckedIn():
answer += "/u/" + participant.name
answer += "\n\n"
return answer
def templateToUse():
answer = ""
answer += "The Stay Clean CURRENT_MONTH_NAME challenge is now over. Join us for **[the NE... | templateForParticipants | identifier_name |
display-final-after-month-is-over.py | #!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
from participantCollection import ParticipantCollection
import re
import datetime
import pyperclip
# Edit Me!
# This script gets run on the first day of the following month, and that month's UR... |
return answer
def templateToUse():
answer = ""
answer += "The Stay Clean CURRENT_MONTH_NAME challenge is now over. Join us for **[the NEXT_MONTH_NAME challenge](NEXT_MONTH_URL)**.\n"
answer += "\n"
answer += "**NUMBER_STILL_IN** out of INITIAL_NUMBER participants made it all the way through the ... | answer += "/u/" + participant.name
answer += "\n\n" | conditional_block |
underscore_const_names.rs | // Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
check_impl!(Str, Trt);
check_impl!(Str, Trt);
} | identifier_body | |
underscore_const_names.rs | // Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
check_impl!(Str, Trt);
check_impl!(Str, Trt);
}
| main | identifier_name |
underscore_const_names.rs | // Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
trait Trt {}
struct Str {}
impl Trt for Str {}
macro_rules! check_impl {
($struct:ident,$trait:ident) => {
const _ : () = {
use std::marker::PhantomData;
struct ImplementsTrait<T: $trait>(PhantomData<T>);
let _ = ImplementsTrait::<$struct>(PhantomData);
()
... | // compile-pass
#![feature(const_let)]
#![feature(underscore_const_names)] | random_line_split |
walk-jqueue-2.js | (function () {
"use strict"
// Array.prototype.forEachAsync(next, item, i, collection)
require('futures/forEachAsync');
var fs = require('fs'),
EventEmitter = require('events').EventEmitter;
// 2010-11-25 jorge@jorgechamorro.com
function create(pathname, cb) {
var emitter = new EventEmitter(),
... | (v,i,o) {
o[i]= [curpath, '/', v].join('');
}
curpath = pathname;
walk();
return emitter;
}
module.exports = create;
}());
| fullPath | identifier_name |
walk-jqueue-2.js | (function () {
"use strict"
// Array.prototype.forEachAsync(next, item, i, collection)
require('futures/forEachAsync');
var fs = require('fs'),
EventEmitter = require('events').EventEmitter;
// 2010-11-25 jorge@jorgechamorro.com
function create(pathname, cb) {
var emitter = new EventEmitter(),
... |
if (stat) {
stat.name = file;
stats.push(stat);
emitter.emit('stat', curpath, file, stat);
}
cont();
});
}).then(function () {
var dirs = []
emitter.emit('stats', curpath, files, stats);
stats.... | {
emitter.emit('error', curpath, err);
} | conditional_block |
walk-jqueue-2.js | (function () {
"use strict"
// Array.prototype.forEachAsync(next, item, i, collection)
require('futures/forEachAsync');
var fs = require('fs'),
EventEmitter = require('events').EventEmitter;
// 2010-11-25 jorge@jorgechamorro.com
function create(pathname, cb) {
var emitter = new EventEmitter(),
... | q = queue[queue.length-1];
return next();
}
emitter.emit('end');
}
function fullPath(v,i,o) {
o[i]= [curpath, '/', v].join('');
}
curpath = pathname;
walk();
return emitter;
}
module.exports = create;
}()); | if (q.length) {
curpath = q.pop();
return walk();
}
if (queue.length -= 1) { | random_line_split |
walk-jqueue-2.js | (function () {
"use strict"
// Array.prototype.forEachAsync(next, item, i, collection)
require('futures/forEachAsync');
var fs = require('fs'),
EventEmitter = require('events').EventEmitter;
// 2010-11-25 jorge@jorgechamorro.com
function create(pathname, cb) {
var emitter = new EventEmitter(),
... |
function next() {
if (q.length) {
curpath = q.pop();
return walk();
}
if (queue.length -= 1) {
q = queue[queue.length-1];
return next();
}
emitter.emit('end');
}
function fullPath(v,i,o) {
o[i]= [curpath, '/', v].join('');
}
... | {
fs.readdir(curpath, function(err, files) {
if (err) {
emitter.emit('error', curpath, err);
}
// XXX bug was here. next() was omitted
if (!files || 0 == files.length) {
return next();
}
var stats = [];
emitter.emit('names', curpath, fil... | identifier_body |
navigation.js | /**
* Custom script that builds a SELECT drop-down with all menu links.
*
* Selects are great since they support CSS3
*
*/
jQuery(document).ready(function(){
jQuery('ul:first').attr("id", "primary-menu");
jQuery("ul#primary-menu > li:has(ul)").addClass("hasChildren");
jQuery("ul#primary-menu > li:has(ul) > ul ... |
jQuery("nav a").each(function() {
var el = jQuery(this);
jQuery("<option />", {
"value" : el.attr("href"),
"text" : el.text(),
"class" : el.attr("class")
}).appendTo("#masthead select");
});
jQuery("nav select").change(function() {
window.location = jQuery(this).find("option:selected").val(... | jQuery("<option />", {
"selected": "selected",
"value" : "",
"text" : "Menu",
}).appendTo("#masthead select"); | random_line_split |
navigation.js | /**
* Custom script that builds a SELECT drop-down with all menu links.
*
* Selects are great since they support CSS3
*
*/
jQuery(document).ready(function(){
jQuery('ul:first').attr("id", "primary-menu");
jQuery("ul#primary-menu > li:has(ul)").addClass("hasChildren");
jQuery("ul#primary-menu > li:has(ul) > ul ... |
});
}); | {
jQuery(el.prepend("- "))
} | conditional_block |
label.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Tuukka Turto
#
# This file is part of satin-python.
#
# pyherc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... |
def _matches(self, item):
"""
Check if matcher matches item
:param item: object to match against
:returns: True if matching, otherwise False
:rtype: Boolean
"""
widgets = all_widgets(item)
for widget in widgets:
if hasattr(widget, 'text... | self.text = wrap_matcher(text) | conditional_block |
label.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Tuukka Turto
#
# This file is part of satin-python.
#
# pyherc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | (BaseMatcher):
"""
Check if Widget has label with given text
"""
def __init__(self, text):
"""
Default constructor
"""
super(LabelMatcher, self).__init__()
if hasattr(text, 'matches'):
self.text = text
else:
self.text = wrap_match... | LabelMatcher | identifier_name |
label.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Tuukka Turto
#
# This file is part of satin-python.
#
# pyherc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | """
Check if Widget has label with given text
"""
return LabelMatcher(text) | identifier_body | |
label.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Tuukka Turto
#
# This file is part of satin-python. | # (at your option) any later version.
#
# pyherc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a c... | #
# pyherc is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or | random_line_split |
ml-levenberg-marquardt-tests.ts | import LM = require('ml-levenberg-marquardt');
function | ([a, b]: number[]) {
return (t: number) => a * Math.sin(b * t);
}
const data = {
x: [
0, Math.PI / 2, Math.PI, Math.PI * 3 / 2
],
y: [
0, 1, 0, -1
]
};
const initialValues = [ 2, 4 ];
const options = {
damping: 1.5,
initialValues,
gradientDifference: 10e-2,
maxIterations: 100,
errorTolera... | sinFunction | identifier_name |
ml-levenberg-marquardt-tests.ts | import LM = require('ml-levenberg-marquardt');
function sinFunction([a, b]: number[]) {
return (t: number) => a * Math.sin(b * t);
}
const data = {
x: [
0, Math.PI / 2, Math.PI, Math.PI * 3 / 2
],
y: [
0, 1, 0, -1
]
};
const initialValues = [ 2, 4 ];
const options = {
damping: 1.5,
initialValu... | {
fittedParams.parameterValues[0] += fittedParams.parameterError;
} | conditional_block | |
ml-levenberg-marquardt-tests.ts | import LM = require('ml-levenberg-marquardt');
function sinFunction([a, b]: number[]) {
return (t: number) => a * Math.sin(b * t);
}
const data = {
x: [
0, Math.PI / 2, Math.PI, Math.PI * 3 / 2
],
y: [
0, 1, 0, -1
]
};
const initialValues = [ 2, 4 ];
const options = {
damping: 1.5,
initialValu... | if (fittedParams.iterations < 10) {
fittedParams.parameterValues[0] += fittedParams.parameterError;
} | random_line_split | |
ml-levenberg-marquardt-tests.ts | import LM = require('ml-levenberg-marquardt');
function sinFunction([a, b]: number[]) |
const data = {
x: [
0, Math.PI / 2, Math.PI, Math.PI * 3 / 2
],
y: [
0, 1, 0, -1
]
};
const initialValues = [ 2, 4 ];
const options = {
damping: 1.5,
initialValues,
gradientDifference: 10e-2,
maxIterations: 100,
errorTolerance: 10e-3
};
const fittedParams = LM(data, sinFunction, options);... | {
return (t: number) => a * Math.sin(b * t);
} | identifier_body |
fib_fac.py | #-*- coding: utf-8 -*-
def factorial(n):
"""Return the factorial of n"""
if n < 2:
|
return n * factorial(n - 1)
def fibonacci(n):
"""Return the nth fibonacci number"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def fib_fac(x=30, y=900):
fib = fibonacci(x)
fac = factorial(y)
print "fibonacci({}):".format(x), fib
print "factorial({}):".form... | return 1 | conditional_block |
fib_fac.py | #-*- coding: utf-8 -*-
def factorial(n):
|
def fibonacci(n):
"""Return the nth fibonacci number"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def fib_fac(x=30, y=900):
fib = fibonacci(x)
fac = factorial(y)
print "fibonacci({}):".format(x), fib
print "factorial({}):".format(y), fac
if __name__ == "__m... | """Return the factorial of n"""
if n < 2:
return 1
return n * factorial(n - 1) | identifier_body |
fib_fac.py | #-*- coding: utf-8 -*-
def factorial(n):
"""Return the factorial of n"""
if n < 2:
return 1
return n * factorial(n - 1)
def fibonacci(n):
"""Return the nth fibonacci number"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def | (x=30, y=900):
fib = fibonacci(x)
fac = factorial(y)
print "fibonacci({}):".format(x), fib
print "factorial({}):".format(y), fac
if __name__ == "__main__":
def opc1():
fruits = tuple(str(i) for i in xrange(100))
out = ''
for fruit in fruits:
out += fruit +':'
... | fib_fac | identifier_name |
fib_fac.py | #-*- coding: utf-8 -*- | return 1
return n * factorial(n - 1)
def fibonacci(n):
"""Return the nth fibonacci number"""
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def fib_fac(x=30, y=900):
fib = fibonacci(x)
fac = factorial(y)
print "fibonacci({}):".format(x), fib
print "fact... |
def factorial(n):
"""Return the factorial of n"""
if n < 2: | random_line_split |
CreateChart.js | var results;
function viewData()
{
var resultsTable = $('<table></table>').attr('id', 'results');
var tableHead = $("<thead></thead>");
var tableBody = $("<tbody></tbody>");
var temp;
$.post("/api/Data/Query/",
{
name: $('#name').val(),
query: $('#query').val(),
server: $('#server').val(... |
//
//
//
function persistChart()
{
$.post("/api/Charts/Create/",
{
name: $('#name').val(),
query: $('#query').val(),
server: $('#server').val(),
description: $('#description').val(),
dependent: $('#Dependent').find(":selected").text(),
independent: $('#Independent').find(":sele... | {
var division = $('<div class="input-field col s12" id="'+ID+'"></div>');
var selectBox = $("<select id='"+name+"'></select>");
for(var x in options)
{
var option = $("<option value="+options[x]+">"+options[x]+"</option>");
selectBox.append(option);
}
var option = $('<option value="0" disabled sele... | identifier_body |
CreateChart.js | var results;
function viewData()
{
var resultsTable = $('<table></table>').attr('id', 'results');
var tableHead = $("<thead></thead>");
var tableBody = $("<tbody></tbody>");
var temp;
$.post("/api/Data/Query/",
{
name: $('#name').val(),
query: $('#query').val(),
server: $('#server').val(... | {
tableBodyRow.append($('<td/>').html(field));
});
tableBody.append(tableBodyRow);
}
buildSelect("Dependent",columnSet,"Dependent");
buildSelect("Independent",columnSet,"Independent");
$('#main').append('<button class="btn grey" type="button" onclick="buildChart()">Build Chart<... | $.each(row, function(j, field) | random_line_split |
CreateChart.js | var results;
function viewData()
{
var resultsTable = $('<table></table>').attr('id', 'results');
var tableHead = $("<thead></thead>");
var tableBody = $("<tbody></tbody>");
var temp;
$.post("/api/Data/Query/",
{
name: $('#name').val(),
query: $('#query').val(),
server: $('#server').val(... |
buildSelect("Dependent",columnSet,"Dependent");
buildSelect("Independent",columnSet,"Independent");
$('#main').append('<button class="btn grey" type="button" onclick="buildChart()">Build Chart</button>');
$('#main').append('<br>');
$('#main').append('<br>');
$('#main').append('<br>');
resu... | {
row = data[i];
var tableBodyRow = $("<tr></tr>");
$.each(row, function(j, field)
{
tableBodyRow.append($('<td/>').html(field));
});
tableBody.append(tableBodyRow);
} | conditional_block |
CreateChart.js | var results;
function viewData()
{
var resultsTable = $('<table></table>').attr('id', 'results');
var tableHead = $("<thead></thead>");
var tableBody = $("<tbody></tbody>");
var temp;
$.post("/api/Data/Query/",
{
name: $('#name').val(),
query: $('#query').val(),
server: $('#server').val(... | ()
{
$('#myChart').remove();
$('#main').append('<canvas id="myChart" width="500" height="500"></canvas>');
var depend = $('#Dependent').find(":selected").text();
var independ = $('#Independent').find(":selected").text();
var labels = [];
var data = [];
var color = [];
$.each(results, function(j, row)... | buildChart | identifier_name |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os... | }
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool { *self == -1 }
}
impl IsMinusOne for isize {
fn is_minus_one(&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> ::io::Result<T> {
use std::io;
if t.is_minus_one() {
Err(io::Error::last_os_error())
} else {
Ok... |
trait IsMinusOne {
fn is_minus_one(&self) -> bool; | random_line_split |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os... |
}
| {
Ok(t)
} | conditional_block |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os... | (&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> ::io::Result<T> {
use std::io;
if t.is_minus_one() {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
| is_minus_one | identifier_name |
mod.rs | use libc::{self, c_int};
#[macro_use]
pub mod dlsym;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod epoll;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::epoll::{Events, Selector};
#[cfg(any(target_os = "bitrig", target_os = "dragonfly",
target_os = "freebsd", target_os... |
trait IsMinusOne {
fn is_minus_one(&self) -> bool;
}
impl IsMinusOne for i32 {
fn is_minus_one(&self) -> bool { *self == -1 }
}
impl IsMinusOne for isize {
fn is_minus_one(&self) -> bool { *self == -1 }
}
fn cvt<T: IsMinusOne>(t: T) -> ::io::Result<T> {
use std::io;
if t.is_minus_one() {
... | {
// Use pipe2 for atomically setting O_CLOEXEC if we can, but otherwise
// just fall back to using `pipe`.
dlsym!(fn pipe2(*mut c_int, c_int) -> c_int);
let mut pipes = [0; 2];
let flags = libc::O_NONBLOCK | libc::O_CLOEXEC;
unsafe {
match pipe2.get() {
Some(pipe2_fn) => {
... | identifier_body |
epitopefinder_plotdistributioncomparison.py | #!python
"""Script for plotting distributions of epitopes per site for two sets of sites.
Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py.
Written by Jesse Bloom."""
import os
import sys
import random
import epitopefinder.io
import epitopefinder.plot
def main():
|
if __name__ == '__main__':
main() # run the script
| """Main body of script."""
random.seed(1) # seed random number generator in case P values are being computed
if not epitopefinder.plot.PylabAvailable():
raise ImportError("Cannot import matplotlib / pylab, which are required by this script.")
# output is written to out, currently set to standard out... | identifier_body |
epitopefinder_plotdistributioncomparison.py | #!python
"""Script for plotting distributions of epitopes per site for two sets of sites.
Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py.
Written by Jesse Bloom."""
import os
import sys
import random
import epitopefinder.io
import epitopefinder.plot
def main():
"""Main body of sc... | out.write('\nNow creating the plot file %s\n' % plotfile)
epitopefinder.plot.PlotDistributionComparison(epitopesbysite1_list, epitopesbysite2_list, set1name, set2name, plotfile, 'number of epitopes', 'fraction of sites', title, pvalue, pvaluewithreplacement, ymax=ymax)
out.write("\nScript is complete.\n")
... | random_line_split | |
epitopefinder_plotdistributioncomparison.py | #!python
"""Script for plotting distributions of epitopes per site for two sets of sites.
Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py.
Written by Jesse Bloom."""
import os
import sys
import random
import epitopefinder.io
import epitopefinder.plot
def | ():
"""Main body of script."""
random.seed(1) # seed random number generator in case P values are being computed
if not epitopefinder.plot.PylabAvailable():
raise ImportError("Cannot import matplotlib / pylab, which are required by this script.")
# output is written to out, currently set to stan... | main | identifier_name |
epitopefinder_plotdistributioncomparison.py | #!python
"""Script for plotting distributions of epitopes per site for two sets of sites.
Uses matplotlib. Designed to analyze output of epitopefinder_getepitopes.py.
Written by Jesse Bloom."""
import os
import sys
import random
import epitopefinder.io
import epitopefinder.plot
def main():
"""Main body of sc... |
if not xlist:
raise ValueError("%s failed to specify information for any sites" % xf)
set1name = epitopefinder.io.ParseStringValue(d, 'set1name')
set2name = epitopefinder.io.ParseStringValue(d, 'set2name')
title = epitopefinder.io.ParseStringValue(d, 'title').strip()
if title.upper(... | (site, n) = line.split(',')
(site, n) = (int(site), int(n))
xlist.append(n) | conditional_block |
mod.rs | mod handlers;
use crate::server::Server;
use log::{debug, error};
use protocol::frame::Framed;
use protocol::Decode;
use runtime::net::TcpStream;
use std::sync::Arc;
const SALT_LEN: usize = 32;
const AES_KEY_LEN: usize = 32;
const AES_IV_LEN: usize = 16;
#[derive(PartialEq, Eq, Debug)]
enum State {
Init,
Log... |
}
| {
use futures::StreamExt;
use protocol::messages::connection::HelloConnectMessage;
use protocol::messages::connection::IdentificationMessage;
use protocol::messages::connection::ServerSelectionMessage;
use protocol::messages::handshake::ProtocolRequired;
use rand::Rng;
... | identifier_body |
mod.rs | mod handlers;
use crate::server::Server;
use log::{debug, error};
use protocol::frame::Framed;
use protocol::Decode;
use runtime::net::TcpStream;
use std::sync::Arc;
const SALT_LEN: usize = 32;
const AES_KEY_LEN: usize = 32;
const AES_IV_LEN: usize = 16;
#[derive(PartialEq, Eq, Debug)]
enum | {
Init,
Logged {
aes_key: [u8; AES_KEY_LEN],
ticket: String,
},
}
pub struct Session {
stream: Framed<TcpStream>,
state: State,
server: Arc<Server>,
}
impl Session {
pub fn new(stream: TcpStream, server: Arc<Server>) -> Self {
Self {
stream: Framed::new... | State | identifier_name |
mod.rs | mod handlers;
use crate::server::Server;
use log::{debug, error};
use protocol::frame::Framed;
use protocol::Decode;
use runtime::net::TcpStream;
use std::sync::Arc;
const SALT_LEN: usize = 32;
const AES_KEY_LEN: usize = 32;
const AES_IV_LEN: usize = 16;
#[derive(PartialEq, Eq, Debug)]
enum State {
Init,
Log... | match IdentificationMessage::decode(&mut frame.payload()) {
Ok(msg) => self.handle_identification(msg).await?,
Err(err) => error!("decode error: {}", err),
}
}
<ServerSelectionMessage<'_> as Decode<'... | debug!("received message with id {}", frame.id());
match frame.id() {
<IdentificationMessage<'_> as Decode<'_>>::ID => { | random_line_split |
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn | () {
//initialize sdl
let sdl_context = sdl2::init().video().events().build()
.ok().expect("Failed to initialize SDL.");
//create a window
let window = sdl_context.window("Rust-Man", 640, 480)
.position_centered()
.build()
.ok().expect("Failed to create window.");
//create a renderer
l... | main | identifier_name |
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn main() | {
//initialize sdl
let sdl_context = sdl2::init().video().events().build()
.ok().expect("Failed to initialize SDL.");
//create a window
let window = sdl_context.window("Rust-Man", 640, 480)
.position_centered()
.build()
.ok().expect("Failed to create window.");
//create a renderer
let ... | identifier_body | |
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn main() { | let window = sdl_context.window("Rust-Man", 640, 480)
.position_centered()
.build()
.ok().expect("Failed to create window.");
//create a renderer
let mut renderer = window.renderer().accelerated().build()
.ok().expect("Failed to create accelerated renderer.");
//create a new player
let... | //initialize sdl
let sdl_context = sdl2::init().video().events().build()
.ok().expect("Failed to initialize SDL.");
//create a window | random_line_split |
main.rs | extern crate sdl2;
extern crate rustc_serialize;
use sdl2::keycode::KeyCode;
use sdl2::event::Event;
use sdl2::timer::get_ticks;
mod sprite;
mod assets;
mod draw;
mod player;
mod tile;
mod map;
mod physics;
use sprite::Sprite;
use player::Player;
use player::PlayerStatus;
use draw::Draw;
fn main() {
//initialize ... |
}
println!("Goodbye, world!");
}
| {
//handle event queue
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown {keycode: KeyCode::Escape, .. } => {
running = false
},
Event::KeyDown {keycode: KeyCode::Left, .. } => {
player.status = PlayerStatus::M... | conditional_block |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... |
}
impl<T: Hash + Eq + Clone> IndexMut<T> for Counter<T> {
fn index_mut(&mut self, idx: T) -> &mut Self::Output {
if self.map.contains_key(&idx) {
let cntp = self.map[&idx].as_ptr();
unsafe { &mut *cntp }
} else {
self.map.insert(idx.clone(), Cell::new(0));
... | {
if self.map.contains_key(&idx) {
let cntp = self.map[&idx].as_ptr();
unsafe { &*cntp }
} else {
//map.insert(idx, Cell::new(0));
//let mut cntp = map[&idx].as_ptr();
//unsafe {& *cntp}
&ZERO
}
} | identifier_body |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... | // Pythonesque Counter implementation
// XXX Move to a separate module
static ZERO: usize = 0;
pub struct Counter<T: Hash + Eq + Clone> {
pub map: HashMap<T, Cell<usize>>,
}
impl<T: Hash + Eq + Clone> Counter<T> {
pub fn new() -> Self {
Counter { map: HashMap::new() }
}
pub fn len(&self) -> usiz... | }
| random_line_split |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... | () -> Self {
Counter { map: HashMap::new() }
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn remove(&mut self, idx: &T) {
self.map.remove(idx);
}
}
impl<T: Hash + Eq + Clone> Index<T> for Counter<T> {
type Output = usize;
fn index(&self, idx: T) -> &Self::Outpu... | new | identifier_name |
unsafe_lib.rs | use std::collections::HashMap;
use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::ops::{Index, IndexMut};
use std::fmt::Debug;
pub struct MutMap<K, V: Default> {
map: HashMap<K, RefCell<V>>,
}
impl<K: Eq + Hash, V: Default> MutMap<K, V> {
pub fn new() -> Self {
MutMap { map: HashMap::new() ... | else {
self.map.insert(idx.clone(), Cell::new(0));
let cntp = self.map[&idx].as_ptr();
unsafe { &mut *cntp }
}
}
}
| {
let cntp = self.map[&idx].as_ptr();
unsafe { &mut *cntp }
} | conditional_block |
index.tsx | import { QueryFilterActions, logQueryFilterReducer } from './logQueryFilterReducer';
import { LogQueryActions, logQueryReducer } from './logQueryReducer';
type State = {
queryFilters: LogQueryFilter;
savedQueries: LogQuery[];
}
const initialState: State = {
queryFilters: { queryText: undefined, dateFilter... | import React, { createContext, useReducer } from 'react';
import { LogQueryFilter, LogQuery } from '../Models'; | random_line_split | |
cli.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any l... | @click.option('--force', '-f', is_flag=True, default=False)
@with_appcontext
def loadpages_cli(force):
"""Load pages."""
loadpages(force=force)
click.secho('Created pages', fg='green')
@fixtures.command('loadlocation')
@with_appcontext
def loadlocation_cli():
"""Load data store location."""
loc = ... | @fixtures.command('loadpages') | random_line_split |
cli.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any l... | (force):
"""Load pages."""
loadpages(force=force)
click.secho('Created pages', fg='green')
@fixtures.command('loadlocation')
@with_appcontext
def loadlocation_cli():
"""Load data store location."""
loc = loadlocation()
click.secho('Created location {0}'.format(loc.uri), fg='green')
@fixtures... | loadpages_cli | identifier_name |
cli.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any l... |
@fixtures.command('loaddemofiles')
@click.argument('source', type=click.Path(exists=True, dir_okay=False,
resolve_path=True))
@with_appcontext
def loaddemofiles_cli(source):
"""Load demo files."""
loaddemofiles(source)
@fixtures.command('loadlicenses')
@with_appcon... | """Load demo records."""
click.echo('Loading demo data...')
with open(join(dirname(__file__), 'data/records.json'), 'r') as fp:
data = json.load(fp)
click.echo('Sending tasks to queue...')
with click.progressbar(data) as records:
loaddemorecords(records)
click.echo("1. Start Celery... | identifier_body |
c_win32.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
func
})
})
}
/// Macro for creating a compatibility fallback for a Windows function
///
/// # Example
/// ```
/// compat_fn!(adll32::SomeFunctionW(_arg: LPCWSTR) {
/// // Fallback implementation
/// })
/// ```
///
/// Note that... | {
fallback
} | conditional_block |
c_win32.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | unsafe { SetLastError(ERROR_CALL_NOT_IMPLEMENTED as DWORD); }
0
})
compat_fn!(kernel32::GetFinalPathNameByHandleW(_hFile: HANDLE,
_lpszFilePath: LPCWSTR,
_cchFilePath: D... | compat_fn!(kernel32::CreateSymbolicLinkW(_lpSymlinkFileName: LPCWSTR,
_lpTargetFileName: LPCWSTR,
_dwFlags: DWORD) -> BOOLEAN { | random_line_split |
c_win32.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (ptr: *mut uint, module: &str, symbol: &str, fallback: uint) {
let module: Vec<u16> = module.utf16_units().collect();
let module = module.append_one(0);
symbol.with_c_str(|symbol| {
let handle = GetModuleHandleW(module.as_ptr());
let func: uint = transmute(GetProcAddress(... | store_func | identifier_name |
viewporter-tests.ts | /// <reference types="jquery"/>
/// <reference types="google-maps"/>
function test_map() {
viewporter.preventPageScroll = true;
var eventName = viewporter.ACTIVE ? 'viewportready' : "load";
google.maps.event.addDomListener(window, eventName, function () {
var map = new google.maps.Map(document.getE... |
navigator.geolocation.getCurrentPosition(success);
}
});
}
function test_swipey() {
function rainbow(numOfSteps, step) {
var r, g, b, h = step / numOfSteps, i = ~~(h * 6), f = h * 6 - i, q = 1 - f;
switch (i % 6) {
case 0: r = 1, g = f, b = 0; break;
... | {
var coords = [position.coords.latitude, position.coords.longitude]
document.getElementById("coords").innerHTML = coords.join(", ");
} | identifier_body |
viewporter-tests.ts | /// <reference types="jquery"/>
/// <reference types="google-maps"/>
function test_map() {
viewporter.preventPageScroll = true;
var eventName = viewporter.ACTIVE ? 'viewportready' : "load";
google.maps.event.addDomListener(window, eventName, function () {
var map = new google.maps.Map(document.getE... |
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
};
};
$(window).bind(viewporter.ACTIVE ? 'viewportready' : 'load', function () {
var canvas = <HTMLCanvasElement>$('canvas')[0];
var context = canv... | {
context.moveTo(clickX[i] - 1, clickY[i]);
} | conditional_block |
viewporter-tests.ts | /// <reference types="jquery"/>
/// <reference types="google-maps"/>
function test_map() {
viewporter.preventPageScroll = true;
var eventName = viewporter.ACTIVE ? 'viewportready' : "load";
google.maps.event.addDomListener(window, eventName, function () {
var map = new google.maps.Map(document.getE... | $(window).bind(viewporter.ACTIVE ? 'viewportchange' : 'resize', function () {
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight
}).trigger(viewporter.ACTIVE ? 'viewportchange' : 'resize');
$('canvas').bind(iOS ? 'touchstart' : 'mousedow... | var iOS = (/iphone|ipad/i).test(navigator.userAgent);
var pointers = {};
// handle resizing / rotating of the viewport
var width, height; | random_line_split |
viewporter-tests.ts | /// <reference types="jquery"/>
/// <reference types="google-maps"/>
function test_map() {
viewporter.preventPageScroll = true;
var eventName = viewporter.ACTIVE ? 'viewportready' : "load";
google.maps.event.addDomListener(window, eventName, function () {
var map = new google.maps.Map(document.getE... | () {
viewporter.preventPageScroll = true;
document.addEventListener('DOMContentLoaded', function () {
// listen for "resize" events and trigger "refresh" method.
window.addEventListener("resize", function () {
viewporter.refresh();
document.getElementById("events").innerH... | test_resize | identifier_name |
tile-stitcher-spec.js | describe('tile-stitcher.js', function() {
describe('stitch', function() {
var ts = tileStitcher('src/tiles/{z}/{x}/{y}.png'),
async = new AsyncSpec(this);
async.it('should stitch tiles together in the proper order', function(done) {
ts.stitch(19084, 24821, 19085, 24822, 16, function(stitchedCa... |
done();
});
});
});
});
}); | {
expect(stitchedImageData.data[i]).toBe(expectedImageData.data[i]);
} | conditional_block |
tile-stitcher-spec.js | describe('tile-stitcher.js', function() {
describe('stitch', function() {
var ts = tileStitcher('src/tiles/{z}/{x}/{y}.png'),
async = new AsyncSpec(this);
async.it('should stitch tiles together in the proper order', function(done) {
ts.stitch(19084, 24821, 19085, 24822, 16, function(stitchedCa... | });
});
}); | });
}); | random_line_split |
ChildNodeInterface.js | /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is goverened by a BSD-style
* license that can be found in the LICENSE file.
*/
suite('ChildNodeInterface', function() {
function | () {
var tree = {};
var div = tree.div = document.createElement('div');
div.innerHTML = 'a<b></b>c<d></d>e';
var a = tree.a = div.firstChild;
var b = tree.b = a.nextSibling;
var c = tree.c = b.nextSibling;
var d = tree.d = c.nextSibling;
var e = tree.e = d.nextSibling;
var sr = tree... | getTree | identifier_name |
ChildNodeInterface.js | /*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is goverened by a BSD-style
* license that can be found in the LICENSE file.
*/
suite('ChildNodeInterface', function() {
function getTree() |
test('nextElementSibling', function() {
var tree = getTree();
assert.equal(tree.b.nextElementSibling, tree.d);
assert.equal(tree.d.nextElementSibling, null);
assert.equal(tree.g.nextElementSibling, tree.content);
assert.equal(tree.content.nextElementSibling, tree.j);
assert.equal(tree.j.nex... | {
var tree = {};
var div = tree.div = document.createElement('div');
div.innerHTML = 'a<b></b>c<d></d>e';
var a = tree.a = div.firstChild;
var b = tree.b = a.nextSibling;
var c = tree.c = b.nextSibling;
var d = tree.d = c.nextSibling;
var e = tree.e = d.nextSibling;
var sr = tree.sr... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.