id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
003f43fb25c930ff5c8c | def allowed_operations(self) -> Sequence[str]:
return pulumi.get(self, "allowed_operations") | |
003f46c45629be001fde | def get_postgres_conn():
global _pg_conn
if _pg_conn is not None and not _pg_conn.closed:
return _pg_conn
app.logger.info('PostgreSQL connection closed. Connecting...')
dsn = get_environment_setting(DATABASE_URL)
_pg_conn = connect(dsn)
_pg_conn.set_client_encoding('UNICODE')
exte... | |
003f99c4a12e1c1c76c1 | def testAccuracy(clf,validationData,validationLabels):
size = len(validationLabels)
correct = 0.0
for x in range(size):
tru = validationLabels[x]
est = clf.predict(validationData[x])
if int(est) == int(tru):
correct += 1
#else:
#print "Estimation faile... | |
003fc0048126bb86854c | def get_all_compute_sites():
return atmosphere.tools.create_req() | |
003fd5d30579d165217e | def getNumberOfAttacks(self):
board = self.squareArray
# We have the current game board but we also need to have a list of the positions of the queens
# We can store only the rows for this purpose in a single dimensional array
queens = []
for y in range(len(board)):
f... | |
003fe547479feb345a83 | def child(self):
return getattr(self, self.child_type) | |
00400bf9ac36ca02e148 | def exists(self, id, want_source=False):
self._require_objcache()
return self.objcache.exists(id, want_source=want_source) | |
004011c81d6862a9934d | def H(self) -> "LinearMap":
return LinearMap(self.adj_func, self.map_func, self.Wshape, self.Vshape) | |
00401b8c7bb8f95b8f97 | def get_story(self, story_id, token):
uri = self.root_uri + "/stories/{}".format(story_id)
b = json.dumps({})
r = requests.get(uri,
data=b,
headers={'Content-Type': 'Application/json',
'token': token},
... | |
004025ca7c7a1c7608a3 | def __init__(self, token=None, endpoint=None):
self.token = token
if not self.token:
raise Error('token must be provided')
self.endpoint = endpoint
if not self.endpoint:
raise Error('endpoint must be provided')
self.headers = {
'x-api-key': sel... | |
00404a4acf5718bf0504 | def _docs_containing_all_the_query(self, query):
omega = set(self.inverted_index_1[query[0]])
for i in range(1,len(query)):
omega=omega.intersection(self.inverted_index_1[query[i]] )
return omega | |
00404bd1b40c1603950a | def __init__(self, offset=1.0, scale=1.0, **kwargs):
self.offset = offset
self.scale = scale
super(StretchedNormalRegularizer, self).__init__(**kwargs) | |
00408407b6de0426b013 | def load(filename):
try:
f = bz2.BZ2File(filename, 'rb')
except IOError as details:
sys.stderr.write('File ' + filename + ' cannot be read\n')
sys.stderr.write(details)
return
myobj = pickle.load(f)
f.close()
return myobj | |
00408af5c63a4c751ac0 | def test_find_coupled_resource_sets_a():
# Each resource has one activity and all are independent.
independent_resource_constraints_matrix = np.eye(4) # => resource sets are [{0}, {1}, {2}, {3}]
# Run the method for the test case defined above
independent_resource_sets = RLControlledRandomWalk._find_c... | |
004096017e44552c986f | def get_indices_test(self):
return self.dataset.get_indices_test() | |
00409ab05fefd4aa7b76 | def _parse_data(self, image_paths, mask_paths):
image_content = tf.read_file(image_paths)
mask_content = tf.read_file(mask_paths)
images = tf.image.decode_image(image_content, channels=self.channels[0])
masks = tf.image.decode_image(mask_content, channels=self.channels[1])
retu... | |
0040e21d29fbc54b207f | def __print_label__(self, head_node, stack_of_nodes, level_str, label_fun):
leading = ' '
lasting = '|___ '
label = label_fun(head_node)
level = int(level_str)
if level == 0:
print (leading + label)
else:
for l in range(0, level - 1):
... | |
004116d7880906414324 | def moveld(t,length,angle):
pu(t)
lt(t,angle)
fd(t,length)
rt(t,angle)
pd(t) | |
004138efbb4b7046a62a | def _get_parameter_vector(theta, eta_1, eta_2):
theta = np.array(theta).reshape(-1)[:, None]
eta_1 = eta_1.reshape(-1)[:, None]
eta_2 = _lower_triang_mat_to_vec(eta_2)[:, None]
return np.vstack((theta, eta_1, eta_2))[:, 0] | |
00413f311a4b5b0fe21f | def create_city(state_id):
state = storage.get('State', state_id)
if state is None:
abort(404)
data = request.get_json(silent=True)
if data is None:
return jsonify({"error": "Not a JSON"}), 400
if 'name' not in data:
return jsonify({"error": "Missing name"}), 400
data['s... | |
00416d2d2da116de2030 | def unpack(token):
token_str = ""
for pos in xrange(len(token)):
bias = ord(TOKEN_KEY[pos % len(TOKEN_KEY)])
token_str += chr(ord(token[pos]) ^ bias)
try:
token_dict = json.loads(token_str)
user, expiration = token_dict['user'], token_dict['expiration']
except:
us... | |
00417c8e5189e8d882f3 | def test_minimum_branch_length(self, name, solver):
tree = nx.DiGraph()
tree.add_nodes_from(["0", "1", "2", "3", "4", "5", "6"]),
tree.add_edges_from(
[
("0", "1"),
("0", "2"),
("1", "3"),
("1", "4"),
("2... | |
0041ca6c2292bf586b03 | def unescape(self, data):
return urlparse.unquote_plus(data) | |
0041e18e98427d4737cb | def move_right(self):
self._time += 1
if self._position < len(self._list) - 1:
self._position += 1
return True
else:
return False | |
0041edc6c66822cfdb64 | def _build_lattice_file(self,target):
target = path.join(target, "lattice.in")
# We need to create a dictionary of the arguments to pass into
# the template.
settings = {}
settings["template"] = "lattice.in"
settings["min_cell_size"] = self.min_size
settings["ma... | |
00421c672c587256d8cd | def read_version():
return load_module_from_path(os.path.join(mspath(), '__init__.py'), 'autoversion').VERSION | |
00421f2a6fe2d89ea9d4 | def _scan(self, generation: int):
for item in self._current_bucket:
scanner = Scanner(item)
scanner.scan(self, 50) # max links
self._swap_bucket.extend(scanner.output)
self._build_response(scanner.output, item, generation) | |
00422e2a2494b15df1e7 | def crop_scale(img, box=(0, 0, 0, 0), output_size=None):
if not numpy.any(box):
box = (0, 0, *img.shape[:2][::-1])
img = crop(img, box)
if output_size:
return resize(img, output_size)
return img | |
004246a032631dacbbd8 | def csrf_protect():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
abort(403)
else: # Might need to check if token already exists
session['token'] = uuid.uuid4().hex # What is this for? | |
00424c5b7b66a0d7c731 | def predict(self, doc):
words = self.clean_sentence(doc)
max_prop, pre_cls = -1.0, 0
for cls in self.p_class_prop:
p_word_class, p_word = 1.0, 1.0
for w in words:
if w not in self.p_class_prop:
p_word *= 0.00001
else:
p_word *= self.p_class_prop[w]['prop']
try:
if w not ... | |
004252f7cd5b93986adf | def remove_state(self, state):
self.unbind_callback(state)
if isinstance(self.options, list):
self.options.remove(state)
else:
temp = list(self.options)
temp.remove(state)
self.options = tuple(temp)
self.prev = self.calc_prev() | |
0042681d5cc6334e5c88 | def resnet18_q(pretrained=False, **kwargs):
model = ResNetQ(BasicBlockQ, [2, 2, 2, 2], **kwargs)
if pretrained:
load_fake_quantized_state_dict(model, model_zoo.load_url(model_urls['resnet18']), 'resnet18_q_map.json')
return model | |
00426f1f9c56ea0225bf | def k_fold_split_csv(dir_name, filename='train.csv', k=10):
# initialization
seq_list = []
k_list = []
with open(f"data/{dir_name}/{filename}", 'r') as f:
for line in f:
line = line.strip()
seq_list.append(line)
random.shuffle(seq_list)
num_each = int(len(seq_l... | |
0042763c2b53daaeb597 | def moments(data):
total = data.sum()
if total !=0:
#print(total)
X, Y = np.indices(data.shape)
#print(data.shape)
x = (X*data).sum()/total
y = (Y*data).sum()/total
#print(x,y)
col = data[:, int(y)]
width_x = np.sqrt(np.abs((np.arange(col.size)-x)*... | |
0042d52a7e6028209cb0 | def _simulate_pulse_and_ref(self, pulse, trans_duration):
self.arcsim.setInput(pulse['x0'], cs.INTEGRATOR_X0)
self.arcsim.setInput(list(self.paramset) +
[self.y0[-1]*trans_duration],
cs.INTEGRATOR_P)
self.arcsim.evaluate()
trajec... | |
0043086bae9eee497ef2 | def load_preprocess():
return pickle.load(open('preprocess.p', mode='rb')) | |
00431886d8111612bd3b | def shape(self):
return tuple(self.tensor.shape) | |
0043402de2045627414d | def __init__(self):
# Define private dictionary attributes.
# Define private list attributes.
# Define private scalar attributes.
self._dao = None
self._last_id = None
# Define public dictionary attributes.
self.dicIncidents = {}
# Define... | |
00437ebb8171615ff374 | def test_maximum_distance(self):
def disk(radius):
"""Create a disk of radius 'radius' around a center pixel"""
diameter = radius * 2 + 1
A = np.zeros((diameter, diameter))
center_r = radius
center_c = center_r
for r in range(diameter):
... | |
0043866acdd1493a92ef | def bar_chart(self, df, n_groups, dict):
fig, ax = plt.subplots()
# choose bar width (standard 0.8 chosen)
bar_width = 0.35
# get an index to set the ticks for the x axis
index = np.arange(n_groups)
indexes = df.index.tolist()
print(indexes)
df["index"] =... | |
00438f4e44c149fe905f | def read_metadata(fd):
metadata = ''
key = 0
try:
while True:
metadata += getxattr(fd, '%s%s' % (METADATA_KEY, (key or '')))
key += 1
except IOError:
pass
return pickle.loads(metadata) | |
00439ec16754b9eeb087 | def extract_title(page):
match = re.search(
r'<h1 id="firstHeading" class="firstHeading" lang="en">(.*?)</h1>', page
)
return match.groups()[0] | |
0043a1bd1449e9e3ece5 | def old_dominates(self, other, obj=slice(None)):
not_equal = False
for self_wvalue, other_wvalue in zip(self.wvalues[obj], other.wvalues[obj]):
if self_wvalue > other_wvalue:
not_equal = True
elif self_wvalue < other_wvalue:
return False ... | |
0043a7e8896e1c48d10c | def is_won(self):
return self.board.is_complete() | |
0043b2daa13878355c2d | def _filter_chars_and_normalize(str_data):
pattern = re.compile('[\W_]+')
return pattern.sub(' ', str_data).lower() | |
0043ce5795fa34743ba2 | def human_turn(board, human, human_name):
board.print_board()
#user_move = randint(1,7)
user_move = raw_input("%s player, enter a number between 1 and %d: " %(human_name, board.width))
while(not check_move(user_move)):
user_move = raw_input("%s player, enter a number between 1 and %d: " %(human_... | |
004468cfa1209966c528 | def to_html(text):
return text.replace("\n", "<br/>") | |
0044749655e006260bf4 | def dynamic_properties(self):
if self._dynamic_properties is None:
return {}
return self._dynamic_properties.copy() | |
00447b0eda29e9b806c9 | def num_children(self):
# TODO: Determine how many children this node has | |
00448fb0842a7a57c6b2 | def saver(filename = None):
save(self, filename) | |
0044a17662039920be75 | def home():
return ('~Endpoints~<br/>'
'/api/v1.0/precipitation<br/>'
'/api/v1.0/stations<br/>'
'/api/v1.0/tobs<br/>'
'/api/v1.0/"start" <br/>'
'/api/v1.0/"start"/"end" <br/>') | |
0044bd949d83fde60d99 | def frac_to_int_max_GC(k, frac_max_GC):
return min(list(range(k)), key=lambda x: abs(float(x)/k-frac_max_GC)) | |
0044c827a3e047e49c35 | def GetRemote(self, name):
try:
r = self._remotes[name]
except KeyError:
r = Remote(self, name)
self._remotes[r.name] = r
return r | |
0044f89afc6a0ab32ce9 | def test_xml_malformed(self):
self.send_xml_validate("resources/requests/echoxml/malformed.xml") | |
004546c48583ecdbd263 | def list_owners(self):
self.animaldb.list_owners() | |
004564e4abc7273e05e3 | def validate_token(access_token):
if hasattr(sys, "_auth_meta_json") is False:
raise IOError
with open(sys._auth_meta_json) as data_file: # pylint: disable=protected-access,no-member
data = json.load(data_file)
if data["auth_server"]["test"] == 1:
return {
"user_id": "... | |
004565bfd03728f97b09 | async def delete(self, ctx, type : str):
if type not in ('voice', 'v', 'text', 't', 'both', 'b'):
await ctx.send("`Type must be either 'voice', 'text', or 'both'.`")
return
if type in ('voice', 'v', 'both', 'b'):
# Delete your temp channel
if ctx.auth... | |
004565e172f7f0d2bc7b | def get_component_config_file():
return "web.ini" | |
004575fffebac7209966 | def getFullUrl(url):
global baseUrl
if url[:1] == '/':
return baseUrl.strip('/') + url
print(' * Unknown format: %s' % url)
return None | |
00457cebab42e912ad89 | def vec_to_answer(self, ans_symbol):
if self.rev_adict is None:
rev_adict = {}
for k, v in self.adict.items():
rev_adict[v] = k
self.rev_adict = rev_adict
return self.rev_adict[ans_symbol] | |
004592b184acd976a58e | def is_invalid(self) -> bool:
return self.status == PyFunceble.storage.STATUS.invalid | |
0045be2abbf84270a088 | def _check_input_params(self):
# 1. check if lang valid
get_lang(self.iso_code) # check if iso_code valid
# 2. check if any fasttext embeddings for this lang
if not self._is_fasttext_lang_available():
available_embeddings_str = "', '".join(MAP_LANGS_CLTK_FASTTEXT.keys())
... | |
0045c086f9050392210b | def silent_makedirs(path):
try:
os.makedirs(path)
except OSError, e:
if e.errno != errno.EEXIST:
raise | |
0045e03ae2008e3aa0d6 | def get_devices(self):
return self.device_list | |
0045f8cfce4ff770fbec | def read_pickle():
with open("pos_neg_glycosites","rb") as f:
ara_d = pickle.load(f)
if type(ara_d) == dict:
print("Serialization succes!")
else:
print("Serialization failed!")
print(type(ara_d))
sys.exit(1)
return ara_d | |
0046265bd5923d509817 | def cluster(self, method):
df = self.data
for i in range(self.num_classes):
data = df.loc[df['label'] == i, self.features].as_matrix()
# TODO: Find permanent fix for
# ValueError: The number of observations cannot be determined on an empty distance matrix
if len(data)>1:
if method == 'kmeans... | |
004629e873ebf3f59a44 | def Enforce_U_Restriction(U):
hold = U[U_x1:U_x2+1, U_y1:U_y2+1, U_z1:U_z2+1].copy()
U *= 0
U[U_x1:U_x2 + 1,U_y1:U_y2 + 1,U_z1:U_z2 + 1] = hold
return U | |
00462af15d80bebb2cb8 | def collect_coexist(self, ner_sents, ners):
co_list = []
for words in ner_sents:
co_ners = set(ners).intersection(set(words))
co_info = self.combination(list(co_ners))
co_list += co_info
if not co_list:
return []
return {i[0]: i[1] for i in... | |
00464dbe05354bc02964 | def is_available():
from .hsadrv.driver import hsa
return hsa.is_available | |
004670a013b1452c0858 | def write_xyz(structure, filename, write_atomnames=False, prec=6):
if isinstance(structure, mb.Compound):
raise ValueError("Expected a ParmEd structure, got an mbuild.Compound")
xyz = np.array([[atom.xx, atom.xy, atom.xz] for atom in structure.atoms])
if write_atomnames:
names = [atom.name ... | |
00467b662b0805194b34 | def is_ascii(s):
return all(ord(c) < 128 for c in s) | |
004697af2ba3b8d54fa9 | def _get_week_duty_phone_numbers(location=Located.KARALLEN):
plan = planning.BoardWeek.current_week()
on_callduty = [item for sublist in plan.oncall(location=location) for item in sublist]
return [x.profile.mobile_phone for x in on_callduty] | |
0046a0ae43902d50ec13 | def _unique(name):
return name + '_' + str(K.get_uid(name)) | |
0046b1578e5693620e70 | def validate_email(self, email):
if User.objects.filter(email=email).exists():
raise serializers.ValidationError("A user with that email already exists.")
return email | |
0046b19f0c256b59fa2a | def start(self):
if self._replace_mgr is None or not self.is_started():
self._restart() | |
0047345421f16f0cb53d | def detect_aes_block_mode(plaintext, unknown_mode_encryptor):
plaintext = '\x00'*(16*8) + plaintext
encrypted = unknown_mode_encryptor(plaintext)
ECB = False
for prepend in xrange(5):
chunks = split_into_chunks(encrypted[prepend:], 16)
if len(set(chunks)) < len(chunks):
ECB =... | |
00473e7837894299753a | def df_filter_per_month(df, month):
return df[df.index.month == convert_month_to_digit(month)] | |
004745931ec4c847bc13 | def is_valid(self):
self.logger.debug("In is_valid.")
problems = self.validate()
valid = True
if len(problems):
self.logger.error("There were %s problems.", str(len(problems)))
valid = False
self.logger.debug("Valid? %s", str(valid))
return va... | |
004749b0ff15522d1d3e | def play_game():
computer_score = 0
human_score = 0
while not is_game_over(computer_score, human_score):
computer_score = computer_move(computer_score, human_score)
human_score = human_move(computer_score, human_score)
show_results(computer_score, human_score) | |
00475d16b1f24909d320 | def speed_count(self) -> int:
if self.tuya_device.category == "kj":
return self.air_purifier_speed_range_len
return super().speed_count | |
0047668efc0952f8ccd2 | def packages(self):
return list(self._collapse().values()) | |
00478c2118aa42e0bdd4 | def to_projectlink(self):
thumb_image_url = reverse(
'project_serve_file', args=[self.short_name, self.logo]
)
args = {
"abreviation": self.short_name,
"title": self.title if self.title else self.short_name,
"description": self.description,
... | |
00478c6cd9e6b013960b | def train_classifiers(self):
for class_type in self._class_list:
replace = False
fn = lambda obj: obj.loc[np.random.choice(obj.index, size, replace), :]
if (class_type == "BugFix"):
size = 285 # sample size
df_bugfix = self._df.groupby('BugFix... | |
0047ae708032ba405ded | def shape(self):
return self.data.shape | |
0047c1f462e68eebf8ed | def _check_null(string):
if string == 'null':
string = None
return string | |
0047d4e9dd3f75b26c06 | def closingAction(self, text):
exit_message = "*******************EXITING FROM APPLICATION*******************"
if text == 'Yes':
logger.debug(exit_message)
import shutdown
shutdown.doCleanShutdown()
else:
self.dismiss()
toast(text) | |
0047d9c02b5aa7177ff3 | def highest_z(self) -> float:
return self._highest_z | |
0047eaa1e795496ebd1e | def block_diag(*arrs):
if not arrs:
return mnp.zeros((1, 0))
bad_shapes = [i for i, a in enumerate(arrs) if a.ndim > 2]
if bad_shapes:
_raise_value_error("Arguments to mindspore.scipy.linalg.block_diag must have at most 2 dimensions.")
accum = mnp.atleast_2d(arrs[0])
for arr in arrs... | |
0047fdc96a0fb77c0b4f | def accuracy(self):
return accuracy_score(self.y, self.y_hat) | |
004822e2c9c1e0dfe870 | def toggleMaximized(self):
if self.isMinimized():
# Do nothing if window is minimized
return
if self.isMaximized():
self.showNormal()
else:
self.showMaximized() | |
004828e5839e986e9d36 | def get_3d_deadzone(self, cam_info, frame_name):
# A function to convert from the camera frame to the world frame
def frame_convertor(x,y,z):
my_point = np.array([x, y, z, 1]).reshape(4,1)
new_point = (self.__T_ecm__ * my_point)
x = float(new_point[0])
y =... | |
00482f5cde49ba7a7724 | def compile_vprint_function(verbose):
if verbose:
return lambda msg, *args: print(msg.format(*args))
return lambda *_: None | |
00485b3e33e82b920c6f | def flatten(lst):
return [subelem for elem in lst for subelem in elem] | |
004865b9d71aa3e51064 | def test_invalid_old(self):
elem = self.driver.find_element_by_name('old_password')
elem.send_keys('maverick1c')
elem = self.driver.find_element_by_name('new_password1')
elem.send_keys('thetest247')
elem = self.driver.find_element_by_name('new_password2')
elem.send_keys('... | |
004878d1324924d46949 | def outputs(self): | |
004891d90beb8178d63e | def build_deck(self):
for suit in self.suits:
for value in range(2, 15):
self.deck.append(card.Card(suit, value)) | |
0048924e4450cff310d1 | def sort_dictionary(d, by): | |
0048b36e45bb46c554e2 | def reset(self, key=None):
if key is None:
section = None
setting = None
elif "." in key:
section, setting = key.split(".", 1)
else: # key is not None and doesn't have a "."
section = key
setting = None
# Now, do the re... | |
0048e0a74c89a589c060 | def get_form(self, *args, **kwargs):
return self.get_form_class()(*args, **kwargs) | |
00493f73551316cd8856 | def update_product(self, product: Product) -> None:
if not self.is_model_mine(product):
raise ValueError('buyer not bound to this database')
self.exe((
'UPDATE products SET '
' name = :name, producer = :producer, type = :type, '
' tags = :tags, base_pric... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.