uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7c0c294f576d1001cfd55d86 | train | class | class Dataset(data.Dataset): # torch.utils.data.Dataset is an abstract class representing a dataset. Your custom dataset should inherit Dataset and override these methods
def __init__(self, imgdirs, phase, attr, rotate, res=128, gamma=3, target_type='heatmap'):
self.imglists = get_imglists(imgdirs)... | class Dataset(data.Dataset): # torch.utils.data.Dataset is an abstract class representing a dataset. Your custom dataset should inherit Dataset and override these methods
| def __init__(self, imgdirs, phase, attr, rotate, res=128, gamma=3, target_type='heatmap'):
self.imglists = get_imglists(imgdirs)
assert phase in ['train', 'test'], 'Only support train and test'
self.phase = phase
self.r = rotate
self.res = res
assert target_t... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 14 18:52:44 2018
@author: xiang
"""
import random
import torch
import torchvision
import torch.utils.data as data
import cv2
import numpy as np
import pickle
from utils import get_imglists, rotatepoints, procrustes, draw_gaussian, enlarge_box, flip... | 131 | 256 | 1,504 | 29 | 101 | face-alignment-group-of-ahucs/SHN-based-2D-face-alignment | dataset.py | Python | Dataset | Dataset | 18 | 136 | 18 | 18 | e23b9a698aa1047cf2b1c949b79f125e68975130 | bigcode/the-stack | train |
d65b7ecdfd81faaa15639325 | train | function | def add_wave_required_zero(wave: list, required_length: int):
n_wave = len(wave)
length = max(n_wave, required_length)
new_wave = np.zeros(length)
for n in range(n_wave):
new_wave[n] = wave[n]
return new_wave
| def add_wave_required_zero(wave: list, required_length: int):
| n_wave = len(wave)
length = max(n_wave, required_length)
new_wave = np.zeros(length)
for n in range(n_wave):
new_wave[n] = wave[n]
return new_wave
| wave['SKIPROWS']
to_meter = wave['TO_METER']
amp = case_conf['AMP']
wave = read_wave(opened_file, col, delimiter, skiprows)*amp*to_meter
return wave
def add_wave_required_zero(wave: list, required_length: int):
| 64 | 64 | 63 | 15 | 48 | adc21/asva | asva/utils/wave.py | Python | add_wave_required_zero | add_wave_required_zero | 40 | 48 | 40 | 40 | 1584899cadbe62f36ed0cd0ace10109c40229c19 | bigcode/the-stack | train |
3ddf36c496909110c2219521 | train | function | def read_wave(file_path: TextIO, col: int, delimiter: Optional[str], skiprows: int):
try:
#df = pd.read_csv(opened_file, header=None, skiprows=skiprows, usecols=[col], delimiter=delimiter)*amp*to_meter
#wave = df[col]
wave = np.loadtxt(file_path, usecols=[col], delimiter=delimiter, skiprows=... | def read_wave(file_path: TextIO, col: int, delimiter: Optional[str], skiprows: int):
| try:
#df = pd.read_csv(opened_file, header=None, skiprows=skiprows, usecols=[col], delimiter=delimiter)*amp*to_meter
#wave = df[col]
wave = np.loadtxt(file_path, usecols=[col], delimiter=delimiter, skiprows=skiprows)
except Exception as error:
raise ValueError(f"check wave settin... | """データの読み込み"""
from typing import TextIO, Optional
import numpy as np
from asva.Types import WaveType, CASESType
#import pandas as pd
def read_wave(file_path: TextIO, col: int, delimiter: Optional[str], skiprows: int):
| 59 | 64 | 114 | 23 | 35 | adc21/asva | asva/utils/wave.py | Python | read_wave | read_wave | 9 | 17 | 9 | 9 | 2657a6545b282c7bae7a0cec3e16737f90afb016 | bigcode/the-stack | train |
96958eeb416567de56ae491d | train | function | def divide_wave(wave: list, n_div: int):
n_wave = len(wave) * n_div
acc_00 = np.zeros(n_wave)
acc_g = 0
for n in range(n_wave):
wave_step = n // n_div
wave_step0 = wave_step - 1
acc_g1 = wave[wave_step0] if wave_step >= 1 else 0
acc_g2 = wave[wave_step]
dacc_g = ... | def divide_wave(wave: list, n_div: int):
| n_wave = len(wave) * n_div
acc_00 = np.zeros(n_wave)
acc_g = 0
for n in range(n_wave):
wave_step = n // n_div
wave_step0 = wave_step - 1
acc_g1 = wave[wave_step0] if wave_step >= 1 else 0
acc_g2 = wave[wave_step]
dacc_g = (acc_g2 - acc_g1) / n_div
acc_g =... | : int):
n_wave = len(wave)
length = max(n_wave, required_length)
new_wave = np.zeros(length)
for n in range(n_wave):
new_wave[n] = wave[n]
return new_wave
def divide_wave(wave: list, n_div: int):
| 64 | 64 | 145 | 13 | 50 | adc21/asva | asva/utils/wave.py | Python | divide_wave | divide_wave | 50 | 64 | 50 | 50 | 36b4419f6614bfc37d573d381f7e791145b491b4 | bigcode/the-stack | train |
f24a1c841ffec54eee14fa83 | train | function | def read_case_wave(wave: WaveType, case_conf: CASESType):
"""ケースとその地震設定に基づき、地震ファイルを読み込んでarrayを返す"""
open_file = wave['INPUT_FILE']
encording_setting = 'ENCORDING' in wave
encording = wave['ENCORDING'] if encording_setting else 'shift-jis'
try:
opened_file = open(open_file, 'r', encoding=enc... | def read_case_wave(wave: WaveType, case_conf: CASESType):
| """ケースとその地震設定に基づき、地震ファイルを読み込んでarrayを返す"""
open_file = wave['INPUT_FILE']
encording_setting = 'ENCORDING' in wave
encording = wave['ENCORDING'] if encording_setting else 'shift-jis'
try:
opened_file = open(open_file, 'r', encoding=encording)
except OSError:
raise ValueError(f"can... | ]
wave = np.loadtxt(file_path, usecols=[col], delimiter=delimiter, skiprows=skiprows)
except Exception as error:
raise ValueError(f"check wave setting: {error}")
return wave
def read_case_wave(wave: WaveType, case_conf: CASESType):
| 64 | 64 | 189 | 16 | 47 | adc21/asva | asva/utils/wave.py | Python | read_case_wave | read_case_wave | 19 | 38 | 19 | 19 | 783b1ad7a36d2758b508a382ecd9f4185e9ae6eb | bigcode/the-stack | train |
e37973bc4093c35290257bcb | train | function | def plotly_stacked_barplot(df, plot_title):
"""Given a dataframe and a plot title, returns a plotly
stacked barplot figure of the taxonomy data"""
fig = go.Figure()
for item, col in df.iteritems():
fig.add_trace(go.Bar(name=item, x=col.index, y=col))
fig.update_layout(barmode='stack')
... | def plotly_stacked_barplot(df, plot_title):
| """Given a dataframe and a plot title, returns a plotly
stacked barplot figure of the taxonomy data"""
fig = go.Figure()
for item, col in df.iteritems():
fig.add_trace(go.Bar(name=item, x=col.index, y=col))
fig.update_layout(barmode='stack')
fig.update_layout(title_text=plot_title, tit... | title_text='Mean Phred Quality Scores by Position; ' +
f'Sampling Depth = {depth}')
fig.update_xaxes(title_text='Position (bp)')
fig.update_yaxes(title_text='phred quality score')
return fig
def plotly_stacked_barplot(df, plot_title):
| 64 | 64 | 123 | 12 | 51 | FastQCS3-direct/fastqcs3 | py_files/make_plots.py | Python | plotly_stacked_barplot | plotly_stacked_barplot | 186 | 198 | 186 | 186 | 2aebe755e4a2c4b61b8f61bdaef292c313b25795 | bigcode/the-stack | train |
92fcc06cee75e083aaca1b14 | train | function | def sum_scores(directory, depth):
"""Middle layer function that iterated through a directory
given as a parameter. Calls the get_scores function on
every file within the directory, appending the score dataframe
to the existing dataframe of scores"""
sum_df = pd.DataFrame()
for file in os.listdir... | def sum_scores(directory, depth):
| """Middle layer function that iterated through a directory
given as a parameter. Calls the get_scores function on
every file within the directory, appending the score dataframe
to the existing dataframe of scores"""
sum_df = pd.DataFrame()
for file in os.listdir(directory):
sample_scores... | 0
for record in fastq_parser:
score = record.letter_annotations["phred_quality"]
count += 1
result.append(score)
if count > depth:
break
sample_scores = pd.DataFrame(result)
return sample_scores
def sum_scores(directory, depth):
| 64 | 64 | 115 | 7 | 56 | FastQCS3-direct/fastqcs3 | py_files/make_plots.py | Python | sum_scores | sum_scores | 64 | 74 | 64 | 64 | 5c3947c4c7ad345e8c42ce97bccc44f6b0c68797 | bigcode/the-stack | train |
ab3f90cd1bca80cb2d0c627c | train | function | def plot_qualities(directory, depth):
"""This function takes a directory and a sampling depth as parameters
and calls the sum_scores function to create dataframe with a sample
of each fastq file quality scores, then generates a plotly object
showing the mean quality score by position with error bars rep... | def plot_qualities(directory, depth):
| """This function takes a directory and a sampling depth as parameters
and calls the sum_scores function to create dataframe with a sample
of each fastq file quality scores, then generates a plotly object
showing the mean quality score by position with error bars representing
the 95% confidence inter... | 4 = next((position for position,
score in enumerate(means) if score < 15), None)
print(
'\n',
'Here is some information about your read quality to help you choose a trim length\n',
'\n',
'your average read quality drops below a phred score of 30 at position',
... | 218 | 218 | 729 | 8 | 209 | FastQCS3-direct/fastqcs3 | py_files/make_plots.py | Python | plot_qualities | plot_qualities | 116 | 183 | 116 | 116 | 74f309f2ddf720910ebec5abe4406e6eb04155aa | bigcode/the-stack | train |
6a33f502d0bd5826439a6da5 | train | function | def find_dropoff(directory, depth):
"""This function find the position in the reads at which the average phred
quality score drops below a certain threshold. This is meant to inform the
user at which base to trim their reads"""
read_pos, sum_df = sum_scores(directory, depth)
means = sum_df.mean()
... | def find_dropoff(directory, depth):
| """This function find the position in the reads at which the average phred
quality score drops below a certain threshold. This is meant to inform the
user at which base to trim their reads"""
read_pos, sum_df = sum_scores(directory, depth)
means = sum_df.mean()
pos1 = next((position for position... | a directory
given as a parameter. Calls the get_scores function on
every file within the directory, appending the score dataframe
to the existing dataframe of scores"""
sum_df = pd.DataFrame()
for file in os.listdir(directory):
sample_scores = get_scores(directory + '/' + file, depth)
... | 107 | 107 | 358 | 8 | 98 | FastQCS3-direct/fastqcs3 | py_files/make_plots.py | Python | find_dropoff | find_dropoff | 77 | 113 | 77 | 77 | 246b49a201e9514e7c7e4f7e3d7aefabdcac87cf | bigcode/the-stack | train |
790d2ed8e13c6295f4458077 | train | function | def get_feature_info(filepath):
"""Given a feature table, will print stats on feature counts"""
colnames = ['sample-id', 'num_features']
features = pd.read_csv(filepath, skiprows=1, names=colnames)
min_feats = np.min(features['num_features'].values).astype(int)
max_feats = np.max(features['num_featu... | def get_feature_info(filepath):
| """Given a feature table, will print stats on feature counts"""
colnames = ['sample-id', 'num_features']
features = pd.read_csv(filepath, skiprows=1, names=colnames)
min_feats = np.min(features['num_features'].values).astype(int)
max_feats = np.max(features['num_features'].values).astype(int)
me... | in df.iteritems():
fig.add_trace(go.Bar(name=item, x=col.index, y=col))
fig.update_layout(barmode='stack')
fig.update_layout(title_text=plot_title, title_x=0.33)
fig.update_xaxes(title_text='Sample')
fig.update_yaxes(title_text='Relative Frequency')
return fig
def get_feature_info(filepath... | 80 | 80 | 268 | 6 | 73 | FastQCS3-direct/fastqcs3 | py_files/make_plots.py | Python | get_feature_info | get_feature_info | 201 | 234 | 201 | 201 | 7547014fcddc4c07033923f675f2152fb2639813 | bigcode/the-stack | train |
f1f6033ee791724c9eba22cf | train | function | def get_scores(filename, depth):
"""Inner most function for quality score plotting, makes a record
of the quality scores in a given fastq file and creates a
dataframe of the resulting scores by position for n = depth
reads"""
if filename.endswith('.gz'):
fastq_parser = SeqIO.parse(gzip.open(... | def get_scores(filename, depth):
| """Inner most function for quality score plotting, makes a record
of the quality scores in a given fastq file and creates a
dataframe of the resulting scores by position for n = depth
reads"""
if filename.endswith('.gz'):
fastq_parser = SeqIO.parse(gzip.open(filename, "rt"),
... | reads_per_hist.update_layout(
title_text='Histogram of reads per sample', # title of plot
xaxis_title_text='Number of sequences', # xaxis label
yaxis_title_text='Number of samples', # yaxis label
)
return reads_per_hist
def get_scores(filename, depth):
| 69 | 69 | 230 | 7 | 61 | FastQCS3-direct/fastqcs3 | py_files/make_plots.py | Python | get_scores | get_scores | 32 | 61 | 32 | 32 | 414b6b09b56f359b22d18000c0875322ca1e603b | bigcode/the-stack | train |
cd6e37d8a95acace98b7fc09 | train | function | def quality_hist():
"""function for quality histogram plotting"""
directory = 'data/exported_demux/'
filename = 'per-sample-fastq-counts.tsv'
reads_per = pd.read_csv(directory + filename, sep='\t')
reads_per_hist = go.Figure(
data=[
go.Histogram(
x=reads_per['forw... | def quality_hist():
| """function for quality histogram plotting"""
directory = 'data/exported_demux/'
filename = 'per-sample-fastq-counts.tsv'
reads_per = pd.read_csv(directory + filename, sep='\t')
reads_per_hist = go.Figure(
data=[
go.Histogram(
x=reads_per['forward sequence count']... | libraries"""
import os
import gzip
import pandas as pd
import plotly.graph_objects as go
import numpy as np
import scipy.stats as st
# Bio needs to be installed by the user,
# can be done with conda install biopython
from Bio import SeqIO
def quality_hist():
| 64 | 64 | 153 | 4 | 59 | FastQCS3-direct/fastqcs3 | py_files/make_plots.py | Python | quality_hist | quality_hist | 14 | 29 | 14 | 14 | 5316ed2840ae3717cfdd27728ba1e80ed3fc9e9e | bigcode/the-stack | train |
3e000f702665b4d1eb86b729 | train | function | def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=1
prog += H(1) # number=2
prog += CNOT(3,0) # number=6
prog += Z(3) # number=7
prog += H(0) # number=9
prog += CZ(3,0) # number=10
prog += H(0) # number=11
prog += H(2) # number=3
prog += ... | def make_circuit()-> Program:
| prog = Program() # circuit begin
prog += H(0) # number=1
prog += H(1) # number=2
prog += CNOT(3,0) # number=6
prog += Z(3) # number=7
prog += H(0) # number=9
prog += CZ(3,0) # number=10
prog += H(0) # number=11
prog += H(2) # number=3
prog += H(3) # number=4
# circuit ... | bit number=4
# total number=12
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
| 64 | 64 | 142 | 7 | 57 | UCLA-SEAL/QDiff | data/p4VQE/R1/benchmark/startPyquil121.py | Python | make_circuit | make_circuit | 11 | 28 | 11 | 12 | c5cfdb71da9a74d87c8de13ac47934982173d234 | bigcode/the-stack | train |
d0ed2916ae9ea06c4eccca16 | train | function | def summrise_results(bitstrings) -> dict:
d = {}
for l in bitstrings:
if d.get(l) is None:
d[l] = 1
else:
d[l] = d[l] + 1
return d
| def summrise_results(bitstrings) -> dict:
| d = {}
for l in bitstrings:
if d.get(l) is None:
d[l] = 1
else:
d[l] = d[l] + 1
return d
| 0) # number=10
prog += H(0) # number=11
prog += H(2) # number=3
prog += H(3) # number=4
# circuit end
return prog
def summrise_results(bitstrings) -> dict:
| 64 | 64 | 57 | 10 | 53 | UCLA-SEAL/QDiff | data/p4VQE/R1/benchmark/startPyquil121.py | Python | summrise_results | summrise_results | 30 | 38 | 30 | 30 | 1bac0d47a135b09fc887db91d45bf4f6a14ec03d | bigcode/the-stack | train |
24039209b5628f51f2fb702d | train | function | def test_find_node():
tree = TreeNode(7)
tree.left = TreeNode(4)
tree.right = TreeNode(3)
tree.right.left = TreeNode(6)
tree.right.right = TreeNode(19)
original = tree
clone = copy.deepcopy(tree)
assert s.getTargetCopy(original, clone, tree.right).val == 3
| def test_find_node():
| tree = TreeNode(7)
tree.left = TreeNode(4)
tree.right = TreeNode(3)
tree.right.left = TreeNode(6)
tree.right.right = TreeNode(19)
original = tree
clone = copy.deepcopy(tree)
assert s.getTargetCopy(original, clone, tree.right).val == 3
| import copy
from .util import TreeNode
from .Day2_FindNodeInBinaryTreeInCloneOfThatTree import Solution
s = Solution()
def test_find_node():
| 36 | 64 | 81 | 5 | 31 | ruarfff/leetcode-jan-2021 | src/Day2_FindNodeInBinaryTreeInCloneOfThatTree_test.py | Python | test_find_node | test_find_node | 8 | 18 | 8 | 8 | 92b6041fc7b5c0ce62e581721422112365f12bea | bigcode/the-stack | train |
6c8ff632a7cf858da4a7d76f | train | class | class MonteCarlo():
def __init__(self, bd, vary, event_table, which=0, samples=1000):
# check if bd and fields are classes
if not isinstance(bd, BrownDwarf):
raise Exception('Brown dwarf must be an instance of the BrownDwarf() class.')
# basic creation of class
... | class MonteCarlo():
| def __init__(self, bd, vary, event_table, which=0, samples=1000):
# check if bd and fields are classes
if not isinstance(bd, BrownDwarf):
raise Exception('Brown dwarf must be an instance of the BrownDwarf() class.')
# basic creation of class
self.bd = bd
... | # basic imports
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import corner
from astropy.io import ascii
from astropy.table import Table
from PyAstronomy import pyasl
# class imports
from mlfinder.bd import BrownDwarf
from mlfinder.fields import Fields
class MonteCarlo():
| 75 | 251 | 838 | 5 | 69 | JudahRockLuberto/mlfinder | mlfinder/mcmc.py | Python | MonteCarlo | MonteCarlo | 19 | 99 | 19 | 19 | 3abaf0a1990e7354a1a5c71492988e15a2a71ac2 | bigcode/the-stack | train |
b95a2e5859e815ed58507794 | train | class | class ipv6_compact(object):
"""An IPv6 dialect class - compact form."""
#: The format string used to converting words into string values.
word_fmt = '%x'
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = True
| class ipv6_compact(object):
| """An IPv6 dialect class - compact form."""
#: The format string used to converting words into string values.
word_fmt = '%x'
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = True
| IPv6 hostmasks to their equivalent CIDR prefixes.
hostmask_to_prefix = dict(
[((2 ** (width - i) - 1), i) for i in range(0, width+1)])
#-----------------------------------------------------------------------------
# Dialect classes.
#-----------------------------------------------------------------------------
... | 63 | 64 | 58 | 7 | 56 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | ipv6_compact | ipv6_compact | 86 | 92 | 86 | 86 | 5ecf37b2bb18798619c0228abc2b886775723f89 | bigcode/the-stack | train |
4e99a73fb2a960d59975c5a4 | train | function | def valid_bits(bits):
return _valid_bits(bits, width, word_sep)
| def valid_bits(bits):
| return _valid_bits(bits, width, word_sep)
| num_words = globals()['num_words']
if word_size is None:
word_size = globals()['word_size']
return _int_to_words(int_val, word_size, num_words)
def words_to_int(words):
return _words_to_int(words, word_size, num_words)
def valid_bits(bits):
| 64 | 64 | 17 | 5 | 59 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | valid_bits | valid_bits | 236 | 237 | 236 | 236 | dfc74c18be3dff0f9d04ccdf71253a4ad1dcc87e | bigcode/the-stack | train |
6e0d18ae79779919ac98275a | train | function | def int_to_packed(int_val):
"""
:param int_val: the integer to be packed.
:return: a packed string that is equivalent to value represented by an
unsigned integer.
"""
words = int_to_words(int_val, 4, 32)
return _struct.pack('>4I', *words)
| def int_to_packed(int_val):
| """
:param int_val: the integer to be packed.
:return: a packed string that is equivalent to value represented by an
unsigned integer.
"""
words = int_to_words(int_val, 4, 32)
return _struct.pack('>4I', *words)
| _verbose)
tokens = list(addr.replace(':', ''))
tokens.reverse()
# We won't support ip6.int here - see RFC 3152 for details.
tokens = tokens + ['ip6', 'arpa', '']
return '.'.join(tokens)
def int_to_packed(int_val):
| 64 | 64 | 72 | 8 | 56 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | int_to_packed | int_to_packed | 190 | 198 | 190 | 190 | 7b241ee1d71d0aa39cad4285bc78091a4aa4b630 | bigcode/the-stack | train |
656ace7bfe9613eee1d0d060 | train | function | def bits_to_int(bits):
return _bits_to_int(bits, width, word_sep)
| def bits_to_int(bits):
| return _bits_to_int(bits, width, word_sep)
| = globals()['word_size']
return _int_to_words(int_val, word_size, num_words)
def words_to_int(words):
return _words_to_int(words, word_size, num_words)
def valid_bits(bits):
return _valid_bits(bits, width, word_sep)
def bits_to_int(bits):
| 64 | 64 | 19 | 6 | 58 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | bits_to_int | bits_to_int | 240 | 241 | 240 | 240 | 559d9ce6e77a581ae5b5634c71424ac976f2ec44 | bigcode/the-stack | train |
a9acbc1011116b3cf6a036eb | train | function | def valid_str(addr, flags=0):
"""
:param addr: An IPv6 address in presentation (string) format.
:param flags: decides which rules are applied to the interpretation of the
addr value. Future use - currently has no effect.
:return: ``True`` if IPv6 address is valid, ``False`` otherwise.
"""
... | def valid_str(addr, flags=0):
| """
:param addr: An IPv6 address in presentation (string) format.
:param flags: decides which rules are applied to the interpretation of the
addr value. Future use - currently has no effect.
:return: ``True`` if IPv6 address is valid, ``False`` otherwise.
"""
if addr == '':
rai... | 6 dialect class - extra wide 'all zeroes' form."""
#: The format string used to converting words into string values.
word_fmt = '%.4x'
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = False
def valid_str(addr, flags=0):
| 64 | 64 | 119 | 9 | 54 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | valid_str | valid_str | 110 | 126 | 110 | 110 | d89284f3067a6bea07d8f6fab7524d2e02b87a90 | bigcode/the-stack | train |
ed6064da2de1a3f0e29cc024 | train | function | def words_to_int(words):
return _words_to_int(words, word_size, num_words)
| def words_to_int(words):
| return _words_to_int(words, word_size, num_words)
| (int_val, num_words=None, word_size=None):
if num_words is None:
num_words = globals()['num_words']
if word_size is None:
word_size = globals()['word_size']
return _int_to_words(int_val, word_size, num_words)
def words_to_int(words):
| 64 | 64 | 20 | 6 | 58 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | words_to_int | words_to_int | 232 | 233 | 232 | 232 | f917a08d3affed2c6b49e668be059aeb66cedb1d | bigcode/the-stack | train |
6d9c05619ba149f0cc30e374 | train | function | def int_to_words(int_val, num_words=None, word_size=None):
if num_words is None:
num_words = globals()['num_words']
if word_size is None:
word_size = globals()['word_size']
return _int_to_words(int_val, word_size, num_words)
| def int_to_words(int_val, num_words=None, word_size=None):
| if num_words is None:
num_words = globals()['num_words']
if word_size is None:
word_size = globals()['word_size']
return _int_to_words(int_val, word_size, num_words)
| (words)):
word = num
word = word << 32 * i
int_val = int_val | word
return int_val
def valid_words(words):
return _valid_words(words, word_size, num_words)
def int_to_words(int_val, num_words=None, word_size=None):
| 64 | 64 | 62 | 15 | 49 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | int_to_words | int_to_words | 224 | 229 | 224 | 224 | 5ac7033543c779765cbc7efdb764bc32f0807721 | bigcode/the-stack | train |
d3c6c4ee95ed8ab52ba2dffd | train | function | def valid_words(words):
return _valid_words(words, word_size, num_words)
| def valid_words(words):
| return _valid_words(words, word_size, num_words)
| list(_struct.unpack('>4I', packed_int))
int_val = 0
for i, num in enumerate(reversed(words)):
word = num
word = word << 32 * i
int_val = int_val | word
return int_val
def valid_words(words):
| 64 | 64 | 18 | 5 | 58 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | valid_words | valid_words | 220 | 221 | 220 | 220 | ba4ac6fcc219989099a57fcfbf3b37db4876b7b4 | bigcode/the-stack | train |
39b5c3f53f06ef898b213c60 | train | function | def int_to_str(int_val, dialect=None):
"""
:param int_val: An unsigned integer.
:param dialect: (optional) a Python class defining formatting options.
:return: The IPv6 presentation (string) format address equivalent to the
unsigned integer provided.
"""
if dialect is None:
dia... | def int_to_str(int_val, dialect=None):
| """
:param int_val: An unsigned integer.
:param dialect: (optional) a Python class defining formatting options.
:return: The IPv6 presentation (string) format address equivalent to the
unsigned integer provided.
"""
if dialect is None:
dialect = ipv6_compact
addr = None
... | .
"""
try:
packed_int = _inet_pton(AF_INET6, addr)
return packed_to_int(packed_int)
except Exception:
raise AddrFormatError('%r is not a valid IPv6 address string!' % (addr,))
def int_to_str(int_val, dialect=None):
| 63 | 64 | 199 | 10 | 54 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | int_to_str | int_to_str | 145 | 172 | 145 | 145 | 1d2a3437bee9d63c42be86ff208039c148dedb26 | bigcode/the-stack | train |
c50dc0722cf8320a6b3c7c49 | train | function | def bin_to_int(bin_val):
return _bin_to_int(bin_val, width)
| def bin_to_int(bin_val):
| return _bin_to_int(bin_val, width)
| globals()['word_sep']
return _int_to_bits(int_val, word_size, num_words, word_sep)
def valid_bin(bin_val):
return _valid_bin(bin_val, width)
def int_to_bin(int_val):
return _int_to_bin(int_val, width)
def bin_to_int(bin_val):
| 64 | 64 | 18 | 7 | 57 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | bin_to_int | bin_to_int | 258 | 259 | 258 | 258 | 986f97ec577089117f72913bf420ce1778a17323 | bigcode/the-stack | train |
ea1b7ec6b894a4eb32278c70 | train | function | def packed_to_int(packed_int):
"""
:param packed_int: a packed string containing an unsigned integer.
It is assumed that string is packed in network byte order.
:return: An unsigned integer equivalent to value of network address
represented by packed binary string.
"""
words = list(... | def packed_to_int(packed_int):
| """
:param packed_int: a packed string containing an unsigned integer.
It is assumed that string is packed in network byte order.
:return: An unsigned integer equivalent to value of network address
represented by packed binary string.
"""
words = list(_struct.unpack('>4I', packed_in... | the integer to be packed.
:return: a packed string that is equivalent to value represented by an
unsigned integer.
"""
words = int_to_words(int_val, 4, 32)
return _struct.pack('>4I', *words)
def packed_to_int(packed_int):
| 64 | 64 | 122 | 8 | 56 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | packed_to_int | packed_to_int | 201 | 217 | 201 | 201 | 508e2d88f51c98580a28eb6fb6b8daff5e48fdd2 | bigcode/the-stack | train |
0bc99cd51f3a9bf6467185b7 | train | function | def int_to_bits(int_val, word_sep=None):
if word_sep is None:
word_sep = globals()['word_sep']
return _int_to_bits(int_val, word_size, num_words, word_sep)
| def int_to_bits(int_val, word_sep=None):
| if word_sep is None:
word_sep = globals()['word_sep']
return _int_to_bits(int_val, word_size, num_words, word_sep)
| _int(words):
return _words_to_int(words, word_size, num_words)
def valid_bits(bits):
return _valid_bits(bits, width, word_sep)
def bits_to_int(bits):
return _bits_to_int(bits, width, word_sep)
def int_to_bits(int_val, word_sep=None):
| 64 | 64 | 45 | 11 | 53 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | int_to_bits | int_to_bits | 244 | 247 | 244 | 244 | b604292b4c621f0d3bb0a2269481a7f5332f3d79 | bigcode/the-stack | train |
4c132dc8e92f6982e1b4ee49 | train | class | class ipv6_verbose(ipv6_compact):
"""An IPv6 dialect class - extra wide 'all zeroes' form."""
#: The format string used to converting words into string values.
word_fmt = '%.4x'
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = False
| class ipv6_verbose(ipv6_compact):
| """An IPv6 dialect class - extra wide 'all zeroes' form."""
#: The format string used to converting words into string values.
word_fmt = '%.4x'
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = False
| should be used.
compact = True
class ipv6_full(ipv6_compact):
"""An IPv6 dialect class - 'all zeroes' form."""
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = False
class ipv6_verbose(ipv6_compact):
| 64 | 64 | 69 | 10 | 53 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | ipv6_verbose | ipv6_verbose | 100 | 107 | 100 | 100 | 3e08da1a20a1a7aabbb1d228ff84cf777387911a | bigcode/the-stack | train |
07aecbdbeda0c08b0346fbbc | train | function | def int_to_arpa(int_val):
"""
:param int_val: An unsigned integer.
:return: The reverse DNS lookup for an IPv6 address in network byte
order integer form.
"""
addr = int_to_str(int_val, ipv6_verbose)
tokens = list(addr.replace(':', ''))
tokens.reverse()
# We won't support ip6.... | def int_to_arpa(int_val):
| """
:param int_val: An unsigned integer.
:return: The reverse DNS lookup for an IPv6 address in network byte
order integer form.
"""
addr = int_to_str(int_val, ipv6_verbose)
tokens = list(addr.replace(':', ''))
tokens.reverse()
# We won't support ip6.int here - see RFC 3152 fo... | packed_int))
tokens = [dialect.word_fmt % word for word in words]
addr = word_sep.join(tokens)
except Exception:
raise ValueError('%r is not a valid 128-bit unsigned integer!' % (int_val,))
return addr
def int_to_arpa(int_val):
| 64 | 64 | 111 | 8 | 55 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | int_to_arpa | int_to_arpa | 175 | 187 | 175 | 175 | f3d0638d3b96bc32bbb9bddc7677b26f8907e430 | bigcode/the-stack | train |
2df2c7b09f5148f563aecb46 | train | function | def str_to_int(addr, flags=0):
"""
:param addr: An IPv6 address in string form.
:param flags: decides which rules are applied to the interpretation of the
addr value. Future use - currently has no effect.
:return: The equivalent unsigned integer for a given IPv6 address.
"""
try:
... | def str_to_int(addr, flags=0):
| """
:param addr: An IPv6 address in string form.
:param flags: decides which rules are applied to the interpretation of the
addr value. Future use - currently has no effect.
:return: The equivalent unsigned integer for a given IPv6 address.
"""
try:
packed_int = _inet_pton(AF_I... | address is valid, ``False`` otherwise.
"""
if addr == '':
raise AddrFormatError('Empty strings are not supported!')
try:
_inet_pton(AF_INET6, addr)
except:
return False
return True
def str_to_int(addr, flags=0):
| 64 | 64 | 120 | 10 | 53 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | str_to_int | str_to_int | 129 | 142 | 129 | 129 | cb51c9848d6001be2a79c2662bb741ef50231a8a | bigcode/the-stack | train |
d1098df4cc82fe77f9b70d41 | train | class | class ipv6_full(ipv6_compact):
"""An IPv6 dialect class - 'all zeroes' form."""
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = False
| class ipv6_full(ipv6_compact):
| """An IPv6 dialect class - 'all zeroes' form."""
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = False
| act(object):
"""An IPv6 dialect class - compact form."""
#: The format string used to converting words into string values.
word_fmt = '%x'
#: Boolean flag indicating if IPv6 compaction algorithm should be used.
compact = True
class ipv6_full(ipv6_compact):
| 64 | 64 | 45 | 10 | 53 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | ipv6_full | ipv6_full | 94 | 98 | 94 | 94 | e11621e39f1fdd13943dcfbf2a3d0cfef51d5c21 | bigcode/the-stack | train |
77a8b87927b974a1dffe4c4a | train | function | def valid_bin(bin_val):
return _valid_bin(bin_val, width)
| def valid_bin(bin_val):
| return _valid_bin(bin_val, width)
| return _bits_to_int(bits, width, word_sep)
def int_to_bits(int_val, word_sep=None):
if word_sep is None:
word_sep = globals()['word_sep']
return _int_to_bits(int_val, word_size, num_words, word_sep)
def valid_bin(bin_val):
| 64 | 64 | 16 | 6 | 58 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | valid_bin | valid_bin | 250 | 251 | 250 | 250 | bffd23080420b8e797efac92583c4a3a3f1d15b9 | bigcode/the-stack | train |
1ea71f970ffdd9d2942a2dd7 | train | function | def int_to_bin(int_val):
return _int_to_bin(int_val, width)
| def int_to_bin(int_val):
| return _int_to_bin(int_val, width)
| (int_val, word_sep=None):
if word_sep is None:
word_sep = globals()['word_sep']
return _int_to_bits(int_val, word_size, num_words, word_sep)
def valid_bin(bin_val):
return _valid_bin(bin_val, width)
def int_to_bin(int_val):
| 64 | 64 | 18 | 7 | 57 | Rockly/netaddr | netaddr/strategy/ipv6.py | Python | int_to_bin | int_to_bin | 254 | 255 | 254 | 254 | 72eb33329e2c0c7a115b5573200f0f1dc7a7c587 | bigcode/the-stack | train |
dcf104f5fafa59f914deea54 | train | class | class IoArgoprojEventsV1alpha1TriggerParameterSource(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for v... | class IoArgoprojEventsV1alpha1TriggerParameterSource(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | """
Argo Server API
You can get examples of requests and responses by using the CLI with `--gloglevel=9`, e.g. `argo list --gloglevel=9` # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from ... | 201 | 256 | 2,769 | 16 | 184 | roofurmston/argo-workflows | sdks/python/client/argo_workflows/model/io_argoproj_events_v1alpha1_trigger_parameter_source.py | Python | IoArgoprojEventsV1alpha1TriggerParameterSource | IoArgoprojEventsV1alpha1TriggerParameterSource | 33 | 275 | 33 | 33 | 302f49337e7f2a4810c7ea60546dd1a93ad5e68e | bigcode/the-stack | train |
b50febcf5c24a1acbf46818c | train | class | class EnclosureGroupsTest(unittest.TestCase):
MINIMAL_DATA_FOR_EG_CREATION = {
"name": "Enclosure Group 1",
"stackingMode": "Enclosure",
"interconnectBayMappings":
[
{
"interconnectBay": 1,
},
{
... | class EnclosureGroupsTest(unittest.TestCase):
| MINIMAL_DATA_FOR_EG_CREATION = {
"name": "Enclosure Group 1",
"stackingMode": "Enclosure",
"interconnectBayMappings":
[
{
"interconnectBay": 1,
},
{
"interconnectBay": 2,
},
... | , copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of th... | 221 | 221 | 739 | 9 | 211 | Manoj-M-97/python-hpOneView | tests/unit/resources/servers/test_enclosure_groups.py | Python | EnclosureGroupsTest | EnclosureGroupsTest | 33 | 120 | 33 | 33 | 3e1c5a4e2316020ca79ba0e935bc6b143202ca40 | bigcode/the-stack | train |
3e09863d84136df85fcf899c | train | function | def main():
MAXLENGTH=1024
Length=args.length if args.length<MAXLENGTH else MAXLENGTH
Interval=args.interval
SortType=args.sort_type
Resampling=args.resample
Sparse=args.sparse
Record=args.record
ColorTheme=args.color_theme
try:
SortMethod=eval(SortType)
except... | def main():
| MAXLENGTH=1024
Length=args.length if args.length<MAXLENGTH else MAXLENGTH
Interval=args.interval
SortType=args.sort_type
Resampling=args.resample
Sparse=args.sparse
Record=args.record
ColorTheme=args.color_theme
try:
SortMethod=eval(SortType)
except:
pr... | .add_argument('-s','--sparse', action='store_true')
parser.add_argument('-rc','--record', action='store_true')
parser.add_argument('-c','--color-theme',type=str,default='blue',
choices=["blue", "green"])
args=parser.parse_args()
def main():
| 64 | 64 | 178 | 3 | 61 | frank-xjh/Sort-Visualization | sortvis/__main__.py | Python | main | main | 18 | 39 | 18 | 18 | e860d01d056ea1263118e23260925d9e64820055 | bigcode/the-stack | train |
b6c90e94d03928e2050cfe7d | train | class | class WMOGroupFile:
def __init__(self, version, root, filepath=None):
self.version = version
self.filepath = filepath
self.root = root
# initialize chunks
self.mver = MVER()
self.mogp = MOGP()
self.mopy = MOPY()
self.movi = MOVI()
self.movt =... | class WMOGroupFile:
| def __init__(self, version, root, filepath=None):
self.version = version
self.filepath = filepath
self.root = root
# initialize chunks
self.mver = MVER()
self.mogp = MOGP()
self.mopy = MOPY()
self.movi = MOVI()
self.movt = MOVT()
self.... | .filepath):
return self.read_chunks()
else:
raise FileNotFoundError('\nError: Unable to find WMO root file or it is corrupted.')
def write(self):
# write root chunks
with open(self.filepath, 'wb') as f:
self.mver.write(f)
... | 215 | 215 | 718 | 6 | 209 | audunknudsroed/pywowlib | wmo_file.py | Python | WMOGroupFile | WMOGroupFile | 132 | 249 | 132 | 133 | 6ef2d811964beff9816003b90b8b8a67685b5452 | bigcode/the-stack | train |
a253a5b1f862a5e9e730ed16 | train | class | class WMOFile:
def __init__(self, version, filepath=None):
self.version = version
self.filepath = filepath
self.display_name = os.path.basename(os.path.splitext(filepath)[0])
self.groups = []
# initialize chunks
self.mver = MVER()
self.mohd = MOHD()
... | class WMOFile:
| def __init__(self, version, filepath=None):
self.version = version
self.filepath = filepath
self.display_name = os.path.basename(os.path.splitext(filepath)[0])
self.groups = []
# initialize chunks
self.mver = MVER()
self.mohd = MOHD()
self.motx = MOTX... | import os
import struct
from .file_formats import wmo_format_root
from .file_formats.wmo_format_root import *
from .file_formats import wmo_format_group
from .file_formats.wmo_format_group import *
from .io_utils.types import uint32
class WMOFile:
| 60 | 241 | 806 | 5 | 54 | audunknudsroed/pywowlib | wmo_file.py | Python | WMOFile | WMOFile | 11 | 129 | 11 | 12 | 0ce4613852dff897c86cf8974780cde678ecbafa | bigcode/the-stack | train |
3f8903be32b5e3492d28d316 | train | function | def track(model:str, folder:str, outdir:str, processes:int=1):
anno_folder = os.path.join(folder, "anno/")
image_folder = os.path.join(folder, "zips/")
print("Folder: %s" % folder)
anno_files = glob.glob(os.path.join(anno_folder, "*.txt"))
time = 0.
ptime = 0.
frames = 0
if p... | def track(model:str, folder:str, outdir:str, processes:int=1):
| anno_folder = os.path.join(folder, "anno/")
image_folder = os.path.join(folder, "zips/")
print("Folder: %s" % folder)
anno_files = glob.glob(os.path.join(anno_folder, "*.txt"))
time = 0.
ptime = 0.
frames = 0
if platform.system() == "Darwin":
multiprocessing.set_start_m... | if not _:
write_bbox((0,0,0,0), f) # failure case
else:
write_bbox(bbox,f)
return model.time, model.ptime, model.frames
def unpack_track(args):
return track_video(*args)
def track(model:str, folder:str, outdir:str, processes:int=1):
| 74 | 74 | 247 | 17 | 57 | maxzuo/CS_4476_CV_Project | evaluate.py | Python | track | track | 52 | 76 | 52 | 53 | 2978515ae69f09e9a164f1a4ef0fee1e46ad3a7f | bigcode/the-stack | train |
22da20b1c5e2db6cfb5dff93 | train | function | def track_video(model:str, anno_file:str, folder:str, outdir:str) -> tracker.Tracker:
def write_bbox(bbox, f):
f.write(','.join(map(str, bbox)) + '\n')
model = tracker.factory(model, timed=True)
anno_folder = os.path.join(folder, "anno/")
image_folder = os.path.join(folder, "zips/")
... | def track_video(model:str, anno_file:str, folder:str, outdir:str) -> tracker.Tracker:
| def write_bbox(bbox, f):
f.write(','.join(map(str, bbox)) + '\n')
model = tracker.factory(model, timed=True)
anno_folder = os.path.join(folder, "anno/")
image_folder = os.path.join(folder, "zips/")
base_name = os.path.basename(anno_file)[:-4]
# get first bbox
with open(ann... | import os
import glob
import argparse
import zipfile
import platform
import multiprocessing
from multiprocessing import Pool
import tqdm
import numpy as np
import tracker
import cv2
from metrics import evaluate
def track_video(model:str, anno_file:str, folder:str, outdir:str) -> tracker.Tracker:
| 66 | 96 | 323 | 22 | 43 | maxzuo/CS_4476_CV_Project | evaluate.py | Python | track_video | track_video | 16 | 47 | 16 | 16 | d4b3312da7e6c5f2a3eb5cd605c37d62508ff825 | bigcode/the-stack | train |
4522b4ee24effa512b310661 | train | function | def unpack_track(args):
return track_video(*args)
| def unpack_track(args):
| return track_video(*args)
| bbox) in model.predict_frames(image_gen, bbox=first_bbox):
if not _:
write_bbox((0,0,0,0), f) # failure case
else:
write_bbox(bbox,f)
return model.time, model.ptime, model.frames
def unpack_track(args):
| 64 | 64 | 12 | 5 | 58 | maxzuo/CS_4476_CV_Project | evaluate.py | Python | unpack_track | unpack_track | 49 | 50 | 49 | 49 | ff40d2af1c413fe5e17cb56074ceb6dd46ba705e | bigcode/the-stack | train |
572042bdabb025f2f8f7fb4f | train | class | class Host(object):
def __init__(self, uri, read_only=False,
conn_event_handler=None,
lifecycle_event_handler=None):
global libvirt
if libvirt is None:
libvirt = importutils.import_module('libvirt')
self._uri = uri
self._read_only = re... | class Host(object):
| def __init__(self, uri, read_only=False,
conn_event_handler=None,
lifecycle_event_handler=None):
global libvirt
if libvirt is None:
libvirt = importutils.import_module('libvirt')
self._uri = uri
self._read_only = read_only
self.... | try:
stats = dom.jobStats()
return cls(**stats)
except libvirt.libvirtError as ex:
if ex.get_error_code() == libvirt.VIR_ERR_NO_SUPPORT:
# Remote libvirt doesn't support new API
LOG.debug("Missing remote virDomainGetJob... | 256 | 256 | 6,627 | 4 | 252 | patanric/nova-fairness | nova/virt/libvirt/host.py | Python | Host | Host | 194 | 1,017 | 194 | 195 | 6ea946c453bc25f279c8f5453a47f59e59803c1f | bigcode/the-stack | train |
635c6961e1d433d63df5083e | train | class | class DomainJobInfo(object):
"""Information about libvirt background jobs
This class encapsulates information about libvirt
background jobs. It provides a mapping from either
the old virDomainGetJobInfo API which returned a
fixed list of fields, or the modern virDomainGetJobStats
which returns ... | class DomainJobInfo(object):
| """Information about libvirt background jobs
This class encapsulates information about libvirt
background jobs. It provides a mapping from either
the old virDomainGetJobInfo API which returned a
fixed list of fields, or the modern virDomainGetJobStats
which returns an extendable dict of fields.... | _utils import excutils
from oslo_utils import importutils
from oslo_utils import units
from oslo_utils import versionutils
import six
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
from nova impor... | 256 | 256 | 1,074 | 6 | 250 | patanric/nova-fairness | nova/virt/libvirt/host.py | Python | DomainJobInfo | DomainJobInfo | 79 | 191 | 79 | 79 | 8d1de331129574fb4649b9381b644995785e0bab | bigcode/the-stack | train |
35f96b9c7cf1aa1e290f8287 | train | function | def _flip_masks_left_right(masks):
"""Left-right flip masks.
Args:
masks: rank 3 float32 tensor with shape
[num_instances, height, width] representing instance masks.
Returns:
flipped masks: rank 3 float32 tensor with shape
[num_instances, height, width] representing instance masks.
"""
... | def _flip_masks_left_right(masks):
| """Left-right flip masks.
Args:
masks: rank 3 float32 tensor with shape
[num_instances, height, width] representing instance masks.
Returns:
flipped masks: rank 3 float32 tensor with shape
[num_instances, height, width] representing instance masks.
"""
return masks[:, :, ::-1]
| flipped_xmin = tf.subtract(1.0, xmax)
flipped_xmax = tf.subtract(1.0, xmin)
flipped_boxes = tf.concat([ymin, flipped_xmin, ymax, flipped_xmax], 1)
return flipped_boxes
def _flip_masks_left_right(masks):
| 64 | 64 | 84 | 9 | 54 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | _flip_masks_left_right | _flip_masks_left_right | 66 | 77 | 66 | 66 | ec046181c0b0690f6e28a24d95041a8d856dbede | bigcode/the-stack | train |
a60a737dc54990b79ab9410a | train | function | def keypoint_flip_horizontal(keypoints, flip_point, flip_permutation,
scope=None):
"""Flips the keypoints horizontally around the flip_point.
This operation flips the x coordinate for each keypoint around the flip_point
and also permutes the keypoints in a manner specified by flip_pe... | def keypoint_flip_horizontal(keypoints, flip_point, flip_permutation,
scope=None):
| """Flips the keypoints horizontally around the flip_point.
This operation flips the x coordinate for each keypoint around the flip_point
and also permutes the keypoints in a manner specified by flip_permutation.
Args:
keypoints: a tensor of shape [num_instances, num_keypoints, 2]
flip_point: (float) ... | _xmax], 1)
return flipped_boxes
def _flip_masks_left_right(masks):
"""Left-right flip masks.
Args:
masks: rank 3 float32 tensor with shape
[num_instances, height, width] representing instance masks.
Returns:
flipped masks: rank 3 float32 tensor with shape
[num_instances, height, width] r... | 114 | 114 | 381 | 19 | 95 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | keypoint_flip_horizontal | keypoint_flip_horizontal | 80 | 110 | 80 | 81 | 42df7d0fcc3fd15346fd59edb6515343a7e5c414 | bigcode/the-stack | train |
62142463b675f3430e87e674 | train | function | def _copy_extra_fields(boxlist_to_copy_to, boxlist_to_copy_from):
"""Copies the extra fields of boxlist_to_copy_from to boxlist_to_copy_to.
Args:
boxlist_to_copy_to: BoxList to which extra fields are copied.
boxlist_to_copy_from: BoxList from which fields are copied.
Returns:
boxlist_to_copy_to with... | def _copy_extra_fields(boxlist_to_copy_to, boxlist_to_copy_from):
| """Copies the extra fields of boxlist_to_copy_from to boxlist_to_copy_to.
Args:
boxlist_to_copy_to: BoxList to which extra fields are copied.
boxlist_to_copy_from: BoxList from which fields are copied.
Returns:
boxlist_to_copy_to with extra fields.
"""
for field in boxlist_to_copy_from.get_extra... | _max_dimension:
new_masks = tf.image.pad_to_bounding_box(
new_masks, 0, 0, max_dimension, max_dimension)
result.append(new_masks)
result.append(new_size)
return result
def _copy_extra_fields(boxlist_to_copy_to, boxlist_to_copy_from):
| 64 | 64 | 125 | 17 | 46 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | _copy_extra_fields | _copy_extra_fields | 354 | 366 | 354 | 354 | 2f2425f523ebda76066e7a92368cef967080b094 | bigcode/the-stack | train |
3dd252e98d08805d2e8923b6 | train | function | def _flip_boxes_left_right(boxes):
"""Left-right flip the boxes.
Args:
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
Each row is in the form of [ymin, xmin, ymax, xmax].
Retur... | def _flip_boxes_left_right(boxes):
| """Left-right flip the boxes.
Args:
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1].
Each row is in the form of [ymin, xmin, ymax, xmax].
Returns:
Flipped boxes.
"""
ymin... | function we squeeze the image to become a rank 3 tensor and then
we pass it to the functions. At the end of the preprocess we expand the image
back to rank 4.
"""
import tensorflow.compat.v1 as tf
from object_detection import box_list
def _flip_boxes_left_right(boxes):
| 64 | 64 | 170 | 9 | 54 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | _flip_boxes_left_right | _flip_boxes_left_right | 47 | 63 | 47 | 47 | 12dc8895365e23656fdfd694b79b1d448b9d9721 | bigcode/the-stack | train |
22f1a239c68d65cc1aae7f08 | train | function | def random_horizontal_flip(image,
boxes=None,
masks=None,
keypoints=None,
keypoint_flip_permutation=None,
seed=None):
"""Randomly flips the image and detections horizontally.
The p... | def random_horizontal_flip(image,
boxes=None,
masks=None,
keypoints=None,
keypoint_flip_permutation=None,
seed=None):
| """Randomly flips the image and detections horizontally.
The probability of flipping the image is 50%.
Args:
image: rank 3 float32 tensor with shape [height, width, channels].
boxes: (optional) rank 2 float32 tensor with shape [N, 4]
containing the bounding boxes.
Boxes are in norm... | flip_permutation might be [0, 2, 1] since we want to swap the 'left_eye'
and 'right_eye' after a horizontal flip.
scope: name scope.
Returns:
new_keypoints: a tensor of shape [num_instances, num_keypoints, 2]
"""
with tf.name_scope(scope, 'FlipHorizontal'):
keypoints = tf.transpose(keypoints, ... | 218 | 218 | 727 | 31 | 186 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | random_horizontal_flip | random_horizontal_flip | 113 | 197 | 113 | 118 | 04ed809d842a4920eeae3d6e9214c118733d912a | bigcode/the-stack | train |
39c29a32d054e2e65f9a47f7 | train | function | def resize_to_range(image,
masks=None,
min_dimension=None,
max_dimension=None,
method=tf.image.ResizeMethod.BILINEAR,
align_corners=False,
pad_to_max_dimension=False):
"""Resizes an image so its dim... | def resize_to_range(image,
masks=None,
min_dimension=None,
max_dimension=None,
method=tf.image.ResizeMethod.BILINEAR,
align_corners=False,
pad_to_max_dimension=False):
| """Resizes an image so its dimensions are within the provided value.
The output size can be described by two cases:
1. If the image can be rescaled so its minimum dimension is equal to the
provided value without the other dimension exceeding max_dimension,
then do so.
2. Otherwise, resize so the larg... | .constant(max_dimension, dtype=tf.float32)
small_scale_factor = max_dimension / orig_max_dim
# Scaling orig_(height|width) by small_scale_factor will make the larger
# dimension equal to max_dimension, save for floating point rounding
# errors. For reasonably-sized images, taking the nearest integer wil... | 225 | 225 | 753 | 44 | 181 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | resize_to_range | resize_to_range | 274 | 351 | 274 | 280 | 0953269536235939c3bbf3dc4900b59d574af42b | bigcode/the-stack | train |
4f173ae99ddca5f46e0a768f | train | function | def box_list_scale(boxlist, y_scale, x_scale, scope=None):
"""scale box coordinates in x and y dimensions.
Args:
boxlist: BoxList holding N boxes
y_scale: (float) scalar tensor
x_scale: (float) scalar tensor
scope: name scope.
Returns:
boxlist: BoxList holding N boxes
"""
with tf.name_sc... | def box_list_scale(boxlist, y_scale, x_scale, scope=None):
| """scale box coordinates in x and y dimensions.
Args:
boxlist: BoxList holding N boxes
y_scale: (float) scalar tensor
x_scale: (float) scalar tensor
scope: name scope.
Returns:
boxlist: BoxList holding N boxes
"""
with tf.name_scope(scope, 'Scale'):
y_scale = tf.cast(y_scale, tf.floa... | Returns:
boxlist_to_copy_to with extra fields.
"""
for field in boxlist_to_copy_from.get_extra_fields():
boxlist_to_copy_to.add_field(field, boxlist_to_copy_from.get_field(field))
return boxlist_to_copy_to
def box_list_scale(boxlist, y_scale, x_scale, scope=None):
| 70 | 70 | 235 | 16 | 53 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | box_list_scale | box_list_scale | 369 | 392 | 369 | 369 | a97ad949ccc753732b7cdef096f64d3473782bb5 | bigcode/the-stack | train |
f4a8af52e61fceb5e4feea98 | train | function | def scale_boxes_to_pixel_coordinates(image, boxes, keypoints=None):
"""Scales boxes from normalized to pixel coordinates.
Args:
image: A 3D float32 tensor of shape [height, width, channels].
boxes: A 2D float32 tensor of shape [num_boxes, 4] containing the bounding
boxes in normalized coordinates. Ea... | def scale_boxes_to_pixel_coordinates(image, boxes, keypoints=None):
| """Scales boxes from normalized to pixel coordinates.
Args:
image: A 3D float32 tensor of shape [height, width, channels].
boxes: A 2D float32 tensor of shape [num_boxes, 4] containing the bounding
boxes in normalized coordinates. Each row is of the form
[ymin, xmin, ymax, xmax].
keypoints:... | _keypoints: a tensor of shape [num_instances, num_keypoints, 2]
"""
with tf.name_scope(scope, 'Scale'):
y_scale = tf.cast(y_scale, tf.float32)
x_scale = tf.cast(x_scale, tf.float32)
new_keypoints = keypoints * [[[y_scale, x_scale]]]
return new_keypoints
def scale_boxes_to_pixel_coordinates(image, bo... | 92 | 92 | 309 | 14 | 77 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | scale_boxes_to_pixel_coordinates | scale_boxes_to_pixel_coordinates | 414 | 442 | 414 | 414 | 7a208da999651b79f16d74b1188ad9353aa75d55 | bigcode/the-stack | train |
a89982fad2374767a974a60d | train | function | def _compute_new_dynamic_size(image, min_dimension, max_dimension):
"""Compute new dynamic shape for resize_to_range method."""
image_shape = tf.shape(image)
orig_height = tf.to_float(image_shape[0])
orig_width = tf.to_float(image_shape[1])
num_channels = image_shape[2]
orig_min_dim = tf.minimum(orig_height... | def _compute_new_dynamic_size(image, min_dimension, max_dimension):
| """Compute new dynamic shape for resize_to_range method."""
image_shape = tf.shape(image)
orig_height = tf.to_float(image_shape[0])
orig_width = tf.to_float(image_shape[1])
num_channels = image_shape[2]
orig_min_dim = tf.minimum(orig_height, orig_width)
# Calculates the larger of the possible sizes
min_... | # dimension equal to max_dimension, save for floating point rounding
# errors. For reasonably-sized images, taking the nearest integer will
# reliably eliminate this error.
small_height = int(round(orig_height * small_scale_factor))
small_width = int(round(orig_width * small_scale_factor))
small_si... | 132 | 132 | 442 | 14 | 118 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | _compute_new_dynamic_size | _compute_new_dynamic_size | 236 | 271 | 236 | 236 | 3b73b43b5bc12d1d62a5dd8e03873bf6f8522d41 | bigcode/the-stack | train |
d90f668bc02be73f23b68df6 | train | function | def _compute_new_static_size(image, min_dimension, max_dimension):
"""Compute new static shape for resize_to_range method."""
image_shape = image.get_shape().as_list()
orig_height = image_shape[0]
orig_width = image_shape[1]
num_channels = image_shape[2]
orig_min_dim = min(orig_height, orig_width)
# Calcu... | def _compute_new_static_size(image, min_dimension, max_dimension):
| """Compute new static shape for resize_to_range method."""
image_shape = image.get_shape().as_list()
orig_height = image_shape[0]
orig_width = image_shape[1]
num_channels = image_shape[2]
orig_min_dim = min(orig_height, orig_width)
# Calculates the larger of the possible sizes
large_scale_factor = min_d... | _flip_masks_left_right(masks),
lambda: masks)
result.append(masks)
# flip keypoints
if keypoints is not None and keypoint_flip_permutation is not None:
permutation = keypoint_flip_permutation
keypoints = tf.cond(
do_a_flip_random,
lambda: keypoint_fl... | 113 | 113 | 378 | 14 | 99 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | _compute_new_static_size | _compute_new_static_size | 200 | 233 | 200 | 200 | 31c61f40a4b71c8d27d5fc843ee2d805083dcab2 | bigcode/the-stack | train |
10fccb4d5eafe657f955ed79 | train | function | def keypoint_scale(keypoints, y_scale, x_scale, scope=None):
"""Scales keypoint coordinates in x and y dimensions.
Args:
keypoints: a tensor of shape [num_instances, num_keypoints, 2]
y_scale: (float) scalar tensor
x_scale: (float) scalar tensor
scope: name scope.
Returns:
new_keypoints: a t... | def keypoint_scale(keypoints, y_scale, x_scale, scope=None):
| """Scales keypoint coordinates in x and y dimensions.
Args:
keypoints: a tensor of shape [num_instances, num_keypoints, 2]
y_scale: (float) scalar tensor
x_scale: (float) scalar tensor
scope: name scope.
Returns:
new_keypoints: a tensor of shape [num_instances, num_keypoints, 2]
"""
with... | _scale * x_max
scaled_boxlist = box_list.BoxList(
tf.concat([y_min, x_min, y_max, x_max], 1))
return _copy_extra_fields(scaled_boxlist, boxlist)
def keypoint_scale(keypoints, y_scale, x_scale, scope=None):
| 64 | 64 | 160 | 16 | 48 | aman2930/tpu | models/official/retinanet/object_detection/preprocessor.py | Python | keypoint_scale | keypoint_scale | 395 | 411 | 395 | 395 | 90660a09d6d2f825deb26ffc6a3aa354e1495ded | bigcode/the-stack | train |
7f1cbc9abd33a3a9f6cd4b41 | train | class | class ExistsByID(DBFormatter):
"""
_WorkUnit.ExistsByID_
MySQL implementation of WorkUnit.ExistsByID
"""
sql = 'SELECT id FROM wmbs_workunit WHERE id = :id'
def format(self, result):
result = DBFormatter.format(self, result)
if result:
return result[0][0]
e... | class ExistsByID(DBFormatter):
| """
_WorkUnit.ExistsByID_
MySQL implementation of WorkUnit.ExistsByID
"""
sql = 'SELECT id FROM wmbs_workunit WHERE id = :id'
def format(self, result):
result = DBFormatter.format(self, result)
if result:
return result[0][0]
else:
return False
... | #!/usr/bin/env python
"""
_WorkUnit.ExistsByID_
MySQL implementation of WorkUnit.ExistsByID
"""
from __future__ import absolute_import, division, print_function
from WMCore.Database.DBFormatter import DBFormatter
class ExistsByID(DBFormatter):
| 54 | 64 | 160 | 7 | 46 | khurtado/WMCore | src/python/WMCore/WMBS/MySQL/WorkUnit/ExistsByID.py | Python | ExistsByID | ExistsByID | 13 | 34 | 13 | 13 | f9d56eea778fc3bab9e4c373760406d6d9d73dae | bigcode/the-stack | train |
58b20626f62f7eb5e1524253 | train | function | def write_to_global_array():
myarray[0] = 1
| def write_to_global_array():
| myarray[0] = 1
| getitem3(i):
return a3[i]
def getitem4(i):
return a4[i]
def getitem5(i):
return a5[i]
def getitem6(i):
return a6[i]
def use_arrayscalar_const():
return s1
def write_to_global_array():
| 64 | 64 | 16 | 6 | 57 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | write_to_global_array | write_to_global_array | 60 | 61 | 60 | 60 | 44253f70cd143557f523727fcf5d9e13f513a22c | bigcode/the-stack | train |
b1b1cac3a0591db3fbbbc11f | train | function | def getitem0(i):
return a0[()]
| def getitem0(i):
| return a0[()]
| ), ('y', 'S3')])
a4 = np.arange(32, dtype=np.int8).view(dt)
a5 = a4[::-2]
# A recognizable data string
a6 = np.frombuffer(b"XXXX_array_contents_XXXX", dtype=np.float32)
def getitem0(i):
| 64 | 64 | 12 | 6 | 58 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | getitem0 | getitem0 | 28 | 29 | 28 | 28 | 7c441ec90e8e38f7dd06c6a0d58c6df73f541839 | bigcode/the-stack | train |
64e1f1ac3673c65c40c492eb | train | function | def getitem1(i):
return a1[i]
| def getitem1(i):
| return a1[i]
| .arange(32, dtype=np.int8).view(dt)
a5 = a4[::-2]
# A recognizable data string
a6 = np.frombuffer(b"XXXX_array_contents_XXXX", dtype=np.float32)
def getitem0(i):
return a0[()]
def getitem1(i):
| 63 | 64 | 12 | 6 | 57 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | getitem1 | getitem1 | 32 | 33 | 32 | 32 | 99e83656c817af3ffbad754706f08e967c7829a6 | bigcode/the-stack | train |
cdb5e3ab060a09e963f785ab | train | function | def use_arrayscalar_const():
return s1
| def use_arrayscalar_const():
| return s1
| item2(i):
return a2[i]
def getitem3(i):
return a3[i]
def getitem4(i):
return a4[i]
def getitem5(i):
return a5[i]
def getitem6(i):
return a6[i]
def use_arrayscalar_const():
| 64 | 64 | 11 | 6 | 58 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | use_arrayscalar_const | use_arrayscalar_const | 56 | 57 | 56 | 56 | a99350c68bc306f09170b98a9225d7099213c7d0 | bigcode/the-stack | train |
95964f58d538502f09245a31 | train | function | def getitem5(i):
return a5[i]
| def getitem5(i):
| return a5[i]
| 0(i):
return a0[()]
def getitem1(i):
return a1[i]
def getitem2(i):
return a2[i]
def getitem3(i):
return a3[i]
def getitem4(i):
return a4[i]
def getitem5(i):
| 64 | 64 | 12 | 6 | 58 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | getitem5 | getitem5 | 48 | 49 | 48 | 48 | 16dc487fb15ece58339c1b32b489929b413dca16 | bigcode/the-stack | train |
eaedec775a9489c296777de1 | train | class | class TestConstantArray(unittest.TestCase):
"""
Test array constants.
"""
def check_array_const(self, pyfunc):
cres = compile_isolated(pyfunc, (types.int32,))
cfunc = cres.entry_point
for i in [0, 1, 2]:
np.testing.assert_array_equal(pyfunc(i), cfunc(i))
def tes... | class TestConstantArray(unittest.TestCase):
| """
Test array constants.
"""
def check_array_const(self, pyfunc):
cres = compile_isolated(pyfunc, (types.int32,))
cfunc = cres.entry_point
for i in [0, 1, 2]:
np.testing.assert_array_equal(pyfunc(i), cfunc(i))
def test_array_const_0d(self):
self.check_a... | numba.errors import TypingError
from numba import jit, types, typeof
a0 = np.array(42)
s1 = np.int32(64)
a1 = np.arange(12)
a2 = a1[::2]
a3 = a1.reshape((3, 4)).T
dt = np.dtype([('x', np.int8), ('y', 'S3')])
a4 = np.arange(32, dtype=np.int8).view(dt)
a5 = a4[::-2]
# A recognizable data string
a6 = np.frombuffer... | 255 | 255 | 850 | 8 | 246 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | TestConstantArray | TestConstantArray | 64 | 174 | 64 | 64 | a6deddd6178445b168344579d83a444b17046e50 | bigcode/the-stack | train |
b5176cf40bbba038382cdc57 | train | function | def getitem4(i):
return a4[i]
| def getitem4(i):
| return a4[i]
| _contents_XXXX", dtype=np.float32)
def getitem0(i):
return a0[()]
def getitem1(i):
return a1[i]
def getitem2(i):
return a2[i]
def getitem3(i):
return a3[i]
def getitem4(i):
| 64 | 64 | 12 | 6 | 58 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | getitem4 | getitem4 | 44 | 45 | 44 | 44 | e3023794b3dd918c816c53e1c3818a59f3e8341b | bigcode/the-stack | train |
57b7c179503846e6c48f79b3 | train | function | def getitem2(i):
return a2[i]
| def getitem2(i):
| return a2[i]
| a5 = a4[::-2]
# A recognizable data string
a6 = np.frombuffer(b"XXXX_array_contents_XXXX", dtype=np.float32)
def getitem0(i):
return a0[()]
def getitem1(i):
return a1[i]
def getitem2(i):
| 64 | 64 | 12 | 6 | 58 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | getitem2 | getitem2 | 36 | 37 | 36 | 36 | 6515d2e97206291b0b4211ca57d901c927924c27 | bigcode/the-stack | train |
b144e5cbdb5fcfbf4496dbea | train | function | def getitem3(i):
return a3[i]
| def getitem3(i):
| return a3[i]
| string
a6 = np.frombuffer(b"XXXX_array_contents_XXXX", dtype=np.float32)
def getitem0(i):
return a0[()]
def getitem1(i):
return a1[i]
def getitem2(i):
return a2[i]
def getitem3(i):
| 64 | 64 | 12 | 6 | 58 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | getitem3 | getitem3 | 40 | 41 | 40 | 40 | e6ff54afe90d358e92c77d940f21d779a3297111 | bigcode/the-stack | train |
505edcb6cc236ac924a175c8 | train | function | def getitem6(i):
return a6[i]
| def getitem6(i):
| return a6[i]
| item1(i):
return a1[i]
def getitem2(i):
return a2[i]
def getitem3(i):
return a3[i]
def getitem4(i):
return a4[i]
def getitem5(i):
return a5[i]
def getitem6(i):
| 64 | 64 | 12 | 6 | 58 | jeikabu/lumberyard | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_array_constants.py | Python | getitem6 | getitem6 | 52 | 53 | 52 | 52 | a294d5d7e2a1dc86ebadbaed7515c4f9f0d84853 | bigcode/the-stack | train |
575dcf74f19ebafefe9ebe4b | train | function | def extr_lon(nc_fid, var_nc_fid):
"""Extract lat coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previously cr... | def extr_lon(nc_fid, var_nc_fid):
| """Extract lat coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previously created;
"""
lons = nc_fid.v... | in nc_fid.variables['lat'].ncattrs():
var_nc_dim.setncattr(ncattr, nc_fid.variables['lat'].getncattr(ncattr))
var_nc_fid.variables[latn][:] = lats
def extr_lon(nc_fid, var_nc_fid):
| 64 | 64 | 191 | 13 | 50 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | extr_lon | extr_lon | 207 | 223 | 207 | 207 | 14de7eb5a28718654d0d7cf67a8fd693ebac201d | bigcode/the-stack | train |
8abe325cf8ef791a72cbae19 | train | function | def varatts(w_nc_var, varname):
"""Add attibutes to the variables, depending on their name.
Arguments:
---------
w_nc_var: a variable object;
varname: the name of the variable, among ta, ua, va and wap.
"""
if varname == 'ta':
w_nc_var.setncatts({
'long_name': "Air tempe... | def varatts(w_nc_var, varname):
| """Add attibutes to the variables, depending on their name.
Arguments:
---------
w_nc_var: a variable object;
varname: the name of the variable, among ta, ua, va and wap.
"""
if varname == 'ta':
w_nc_var.setncatts({
'long_name': "Air temperature",
'units': "K... | .variables['time'].dtype,
('time', ))
for ncattr in nc_fid.variables['time'].ncattrs():
var_nc_dim.setncattr(ncattr,
nc_fid.variables['time'].getncattr(ncattr))
var_nc_fid.variables['time'][:] = time
def varatts(w_nc_var, varname):
| 75 | 75 | 253 | 10 | 64 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | varatts | varatts | 266 | 297 | 266 | 266 | 119f0ec07e06a523a9082b06a27eaf96e8acac4d | bigcode/the-stack | train |
469d659e907e86c211318138 | train | function | def extr_time(nc_fid, var_nc_fid):
"""Extract time coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previously ... | def extr_time(nc_fid, var_nc_fid):
| """Extract time coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previously created;
"""
time = nc_fid.... | id.variables['plev'].ncattrs():
var_nc_dim.setncattr(ncattr,
nc_fid.variables['plev'].getncattr(ncattr))
var_nc_fid.variables['plev'][:] = plev
def extr_time(nc_fid, var_nc_fid):
| 64 | 64 | 189 | 13 | 50 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | extr_time | extr_time | 246 | 263 | 246 | 246 | 0224e242602fd24a7cc3f6983c412a940cfb6467 | bigcode/the-stack | train |
08d8783437bd048e341e42c7 | train | function | def extr_lat(nc_fid, var_nc_fid, latn):
"""Extract lat coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previou... | def extr_lat(nc_fid, var_nc_fid, latn):
| """Extract lat coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previously created;
latn: the name of the l... | 1, 'f8',
('time', 'plev', 'lat', 'lon'))
varatts(var1_nc_var, name1)
var_nc_fid.variables[name1][:, :, :, :] = var1
def extr_lat(nc_fid, var_nc_fid, latn):
| 64 | 64 | 206 | 16 | 47 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | extr_lat | extr_lat | 188 | 204 | 188 | 188 | 5a6d5fa9a2f28241b89b904d61cb6a82e6e25542 | bigcode/the-stack | train |
0fc3a66ce9222c7f2b845566 | train | function | def fourier_coeff(tadiagfile, outfile, ta_input, tas_input):
"""Compute Fourier coefficients in lon direction.
Arguments:
---------
tadiagfile: the name of a file to store modified t fields;
outfile: the name of a file to store the Fourier coefficients;
ta_input: the name of a file containing t... | def fourier_coeff(tadiagfile, outfile, ta_input, tas_input):
| """Compute Fourier coefficients in lon direction.
Arguments:
---------
tadiagfile: the name of a file to store modified t fields;
outfile: the name of a file to store the Fourier coefficients;
ta_input: the name of a file containing t,u,v,w fields;
tas_input: the name of a file containing t... | by the number of longitudinal
gridsteps. The outputs are given as (time,level,wave,lat) where wave stands
for the zonal wavenumber. In the context of the thermodynamic diagnostic tool,
this is used for the computation of the Lorenz Energy Cycle.
@author: valerio.lembo@uni-hamburg.de, Valerio Lembo, Hamburg University... | 256 | 256 | 1,458 | 17 | 238 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | fourier_coeff | fourier_coeff | 25 | 113 | 25 | 25 | f62fb2f075ab0216a4bcdb48a1dbf663a3af4e32 | bigcode/the-stack | train |
15c359decee781cf2ec1f021 | train | function | def pr_output(dict_v, nc_f, fileo, file_desc, wave2):
"""Print outputs to NetCDF.
Save fields to NetCDF, retrieving information from an existing
NetCDF file. Metadata are transferred from the existing file to the
new one.
Arguments:
---------
var1, var2, var3, var4: the fields to be stored... | def pr_output(dict_v, nc_f, fileo, file_desc, wave2):
| """Print outputs to NetCDF.
Save fields to NetCDF, retrieving information from an existing
NetCDF file. Metadata are transferred from the existing file to the
new one.
Arguments:
---------
var1, var2, var3, var4: the fields to be stored, with shape
(time,level,w... | afft_p)
vafft[:, :, :, 1::2] = np.imag(vafft_p)
wapfft[:, :, :, 0::2] = np.real(wapfft_p)
wapfft[:, :, :, 1::2] = np.imag(wapfft_p)
dict_v = {'ta': tafft, 'ua': uafft, 'va': vafft, 'wap': wapfft}
file_desc = 'Fourier coefficients'
pr_output(dict_v, ta_input, outfile, file_desc, wave2)
def pr_out... | 131 | 131 | 438 | 18 | 113 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | pr_output | pr_output | 116 | 153 | 116 | 116 | 5293a03776f98998f6bb4bd39db4ac188a018461 | bigcode/the-stack | train |
df6380cfc5191d7942b31539 | train | function | def extr_plev(nc_fid, var_nc_fid):
"""Extract plev coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previously ... | def extr_plev(nc_fid, var_nc_fid):
| """Extract plev coord. from NC files and save them to a new NC file.
Arguments:
---------
nc_f: the existing dataset, from where the metadata are
retrieved. Time,level and lon dimensions are retrieved;
var_nc_fid: the id of the new NC dataset previously created;
"""
plev = nc_fid.... | nc_fid.variables['lon'].ncattrs():
var_nc_dim.setncattr(ncattr, nc_fid.variables['lon'].getncattr(ncattr))
var_nc_fid.variables['lon'][:] = lons
def extr_plev(nc_fid, var_nc_fid):
| 64 | 64 | 204 | 15 | 48 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | extr_plev | extr_plev | 226 | 243 | 226 | 226 | 5eb01f78d8931f53a70ff6044920464b1e1c2340 | bigcode/the-stack | train |
16e18705ac3248c0892d0ef4 | train | function | def pr_output_diag(var1, nc_f, fileo, name1):
"""Print processed ta field to NetCDF file.
Save fields to NetCDF, retrieving information from an existing
NetCDF file. Metadata are transferred from the existing file to the
new one.
Arguments:
---------
var1: the field to be stored, with shap... | def pr_output_diag(var1, nc_f, fileo, name1):
| """Print processed ta field to NetCDF file.
Save fields to NetCDF, retrieving information from an existing
NetCDF file. Metadata are transferred from the existing file to the
new one.
Arguments:
---------
var1: the field to be stored, with shape (time,level,lat,lon);
nc_f: the existing... | ('wave', ))
var_nc_fid.variables['wave'][:] = wave2
for key in dict_v:
value = dict_v[key]
var1_nc_var = var_nc_fid.createVariable(
key, 'f8', ('time', 'plev', 'lat', 'wave'))
varatts(var1_nc_var, key)
... | 107 | 107 | 359 | 16 | 90 | cffbots/ESMValTool | esmvaltool/diag_scripts/thermodyn_diagtool/fourier_coefficients.py | Python | pr_output_diag | pr_output_diag | 156 | 185 | 156 | 156 | 0216d0386c251a9fee78e5916ff0553a3c323d50 | bigcode/the-stack | train |
a2c1fcc8f3d3a2fd5856839d | train | class | class SSMix:
def __init__(self, args):
self.args = args
def __call__(self, input1, input2, target1, target2, length1, length2, max_len):
batch_size = len(length1)
if self.args.ss_no_saliency:
if self.args.ss_no_span:
inputs_aug, ratio = self.ssmix_nosal_nosp... | class SSMix:
| def __init__(self, args):
self.args = args
def __call__(self, input1, input2, target1, target2, length1, length2, max_len):
batch_size = len(length1)
if self.args.ss_no_saliency:
if self.args.ss_no_span:
inputs_aug, ratio = self.ssmix_nosal_nospan(input1, in... | '''
SSMix
Copyright (c) 2021-present NAVER Corp.
Apache License v2.0
'''
import copy
import random
import torch
import torch.nn.functional as F
from .saliency import get_saliency
class SSMix:
| 54 | 256 | 1,420 | 5 | 48 | sounritesh/SSMix-Custom | augmentation/ssmix.py | Python | SSMix | SSMix | 14 | 133 | 14 | 14 | d750efc401c7916c5950892f416425adfc1a5b8e | bigcode/the-stack | train |
656766ed0f132f00a1bb972a | train | function | @curry
def log_lr(optimizer, engine):
logger = logging.getLogger(__name__)
lr = [param_group["lr"] for param_group in optimizer.param_groups]
logger.info(f"lr - {lr}")
| @curry
def log_lr(optimizer, engine):
| logger = logging.getLogger(__name__)
lr = [param_group["lr"] for param_group in optimizer.param_groups]
logger.info(f"lr - {lr}")
| logger = logging.getLogger(__name__)
if engine.state.iteration % log_interval == 0:
logger.info(f"Epoch: {engine.state.epoch} Iter: {engine.state.iteration} loss {engine.state.output['loss']}")
@curry
def log_lr(optimizer, engine):
| 63 | 64 | 48 | 12 | 51 | elmajdma/seismic-deeplearning | cv_lib/cv_lib/event_handlers/logging_handlers.py | Python | log_lr | log_lr | 21 | 25 | 21 | 22 | fce25106f7b22388004083070395cf789cc3da18 | bigcode/the-stack | train |
f94ad58ac900ee74ec5890a2 | train | class | class Evaluator:
def __init__(self, evaluation_engine, data_loader):
self._evaluation_engine = evaluation_engine
self._data_loader = data_loader
def __call__(self, engine):
self._evaluation_engine.run(self._data_loader)
| class Evaluator:
| def __init__(self, evaluation_engine, data_loader):
self._evaluation_engine = evaluation_engine
self._data_loader = data_loader
def __call__(self, engine):
self._evaluation_engine.run(self._data_loader)
| metrics_dict[k]} {metrics[k].numpy()}" for k in metrics_dict)
logger.info(f"{log_msg} - Epoch {engine.state.epoch} [{engine.state.max_epochs}]\n" + metrics_msg)
# TODO: remove Evaluator once other train.py scripts are updated
class Evaluator:
| 64 | 64 | 55 | 4 | 59 | elmajdma/seismic-deeplearning | cv_lib/cv_lib/event_handlers/logging_handlers.py | Python | Evaluator | Evaluator | 55 | 61 | 55 | 55 | dabc4f14656547eba1ef418508c7728361d5add9 | bigcode/the-stack | train |
b8baf5d7e840dce0d487e5ba | train | function | @curry
def log_metrics(
engine,
evaluator,
metrics_dict={
"nll": "Avg loss :",
"pixacc": "Pixelwise Accuracy :",
"mca": "Avg Class Accuracy :",
"mIoU": "Avg Class IoU :",
},
stage="undefined",
):
logger = logging.getLogger(__name__)
metrics = evaluator.state.m... | @curry
def log_metrics(
engine,
evaluator,
metrics_dict={
"nll": "Avg loss :",
"pixacc": "Pixelwise Accuracy :",
"mca": "Avg Class Accuracy :",
"mIoU": "Avg Class IoU :",
},
stage="undefined",
):
| logger = logging.getLogger(__name__)
metrics = evaluator.state.metrics
metrics_msg = " ".join([f"{metrics_dict[k]} {metrics[k]:.4f}" for k in metrics_dict])
logger.info(f"{stage} - Epoch {engine.state.epoch} [{engine.state.max_epochs}] " + metrics_msg)
| @curry
def log_metrics(
engine,
evaluator,
metrics_dict={
"nll": "Avg loss :",
"pixacc": "Pixelwise Accuracy :",
"mca": "Avg Class Accuracy :",
"mIoU": "Avg Class IoU :",
},
stage="undefined",
):
| 71 | 64 | 141 | 71 | 0 | elmajdma/seismic-deeplearning | cv_lib/cv_lib/event_handlers/logging_handlers.py | Python | log_metrics | log_metrics | 28 | 43 | 28 | 39 | 6ba06b7d171abae1cd6572bd8bd081b11f527a66 | bigcode/the-stack | train |
275704e81322a0e06b0d6e51 | train | function | @curry
def log_training_output(engine, log_interval=100):
logger = logging.getLogger(__name__)
if engine.state.iteration % log_interval == 0:
logger.info(f"Epoch: {engine.state.epoch} Iter: {engine.state.iteration} loss {engine.state.output['loss']}")
| @curry
def log_training_output(engine, log_interval=100):
| logger = logging.getLogger(__name__)
if engine.state.iteration % log_interval == 0:
logger.info(f"Epoch: {engine.state.epoch} Iter: {engine.state.iteration} loss {engine.state.output['loss']}")
| # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
import logging
import logging.config
from toolz import curry
import numpy as np
np.set_printoptions(precision=3)
@curry
def log_training_output(engine, log_interval=100):
| 60 | 64 | 67 | 15 | 45 | elmajdma/seismic-deeplearning | cv_lib/cv_lib/event_handlers/logging_handlers.py | Python | log_training_output | log_training_output | 13 | 18 | 13 | 14 | 2f14a69d45d77aade32284419450d7b26a5f5e12 | bigcode/the-stack | train |
c02472852d82f237470dca91 | train | function | @curry
def log_class_metrics(log_msg, engine, metrics_dict):
logger = logging.getLogger(__name__)
metrics = engine.state.metrics
metrics_msg = "\n".join(f"{metrics_dict[k]} {metrics[k].numpy()}" for k in metrics_dict)
logger.info(f"{log_msg} - Epoch {engine.state.epoch} [{engine.state.max_epochs}]\n" + ... | @curry
def log_class_metrics(log_msg, engine, metrics_dict):
| logger = logging.getLogger(__name__)
metrics = engine.state.metrics
metrics_msg = "\n".join(f"{metrics_dict[k]} {metrics[k].numpy()}" for k in metrics_dict)
logger.info(f"{log_msg} - Epoch {engine.state.epoch} [{engine.state.max_epochs}]\n" + metrics_msg)
| join([f"{metrics_dict[k]} {metrics[k]:.4f}" for k in metrics_dict])
logger.info(f"{stage} - Epoch {engine.state.epoch} [{engine.state.max_epochs}] " + metrics_msg)
@curry
def log_class_metrics(log_msg, engine, metrics_dict):
| 64 | 64 | 88 | 16 | 48 | elmajdma/seismic-deeplearning | cv_lib/cv_lib/event_handlers/logging_handlers.py | Python | log_class_metrics | log_class_metrics | 46 | 51 | 46 | 47 | c8ddbc5d395cb6ca05c61bc45eff980c2507093b | bigcode/the-stack | train |
cfc8e2e9cf0031a119c4f093 | train | function | def patch_copy_tpu_client_py(dst_dir):
with open(r.Rlocation("org_tensorflow/tensorflow/compiler/xla/python/tpu_driver/client/tpu_client.py")) as f:
src = f.read()
src = src.replace("from tensorflow.compiler.xla.python import xla_extension as _xla",
"from . import xla_extension as _xla")... | def patch_copy_tpu_client_py(dst_dir):
| with open(r.Rlocation("org_tensorflow/tensorflow/compiler/xla/python/tpu_driver/client/tpu_client.py")) as f:
src = f.read()
src = src.replace("from tensorflow.compiler.xla.python import xla_extension as _xla",
"from . import xla_extension as _xla")
src = src.replace("from tensorflow... | from tensorflow.compiler.xla.python import xla_extension as _xla",
"from . import xla_extension as _xla")
with open(os.path.join(dst_dir, "xla_client.py"), "w") as f:
f.write(src)
def patch_copy_tpu_client_py(dst_dir):
| 64 | 64 | 175 | 10 | 54 | inailuig/jax | build/build_wheel.py | Python | patch_copy_tpu_client_py | patch_copy_tpu_client_py | 90 | 101 | 90 | 90 | eb1cbb142738dc90a673b01b86fc9a0cf5419cc0 | bigcode/the-stack | train |
061d1b48d2615e9165b38c9d | train | function | def patch_copy_xla_client_py(dst_dir):
with open(r.Rlocation("org_tensorflow/tensorflow/compiler/xla/python/xla_client.py")) as f:
src = f.read()
src = src.replace("from tensorflow.compiler.xla.python import xla_extension as _xla",
"from . import xla_extension as _xla")
with open(os.... | def patch_copy_xla_client_py(dst_dir):
| with open(r.Rlocation("org_tensorflow/tensorflow/compiler/xla/python/xla_client.py")) as f:
src = f.read()
src = src.replace("from tensorflow.compiler.xla.python import xla_extension as _xla",
"from . import xla_extension as _xla")
with open(os.path.join(dst_dir, "xla_client.py"), "w... | _file(src_file, dst_dir, dst_filename=None):
if src_file.endswith(".so"):
_copy_so(src_file, dst_dir, dst_filename=dst_filename)
else:
_copy_normal(src_file, dst_dir, dst_filename=dst_filename)
def patch_copy_xla_client_py(dst_dir):
| 64 | 64 | 101 | 10 | 54 | inailuig/jax | build/build_wheel.py | Python | patch_copy_xla_client_py | patch_copy_xla_client_py | 81 | 87 | 81 | 81 | 5e1e71cd1ecbe97edab34615e70ec24540080bfe | bigcode/the-stack | train |
cf2f4bcae527a0e59fde8e0a | train | function | def _is_windows():
return sys.platform.startswith("win32")
| def _is_windows():
| return sys.platform.startswith("win32")
| . If "
"omitted, a temporary directory will be used.")
parser.add_argument(
"--output_path",
default=None,
required=True,
help="Path to which the output wheel should be written. Required.")
args = parser.parse_args()
r = runfiles.Create()
def _is_windows():
| 64 | 64 | 14 | 5 | 59 | inailuig/jax | build/build_wheel.py | Python | _is_windows | _is_windows | 48 | 49 | 48 | 48 | 3be979ee72f0464c91ba7caa22863075a2d235de | bigcode/the-stack | train |
88edd7b8fbb2f59def51facc | train | function | def verify_mac_libraries_dont_reference_chkstack():
"""Verifies that xla_extension.so doesn't depend on ____chkstk_darwin.
We don't entirely know why this happens, but in some build environments
we seem to target the wrong Mac OS version.
https://github.com/google/jax/issues/3867
This check makes sure we do... | def verify_mac_libraries_dont_reference_chkstack():
| """Verifies that xla_extension.so doesn't depend on ____chkstk_darwin.
We don't entirely know why this happens, but in some build environments
we seem to target the wrong Mac OS version.
https://github.com/google/jax/issues/3867
This check makes sure we don't release wheels that have this dependency.
"""
... | .client import tpu_client_extension as _tpu_client",
"from . import tpu_client_extension as _tpu_client")
with open(os.path.join(dst_dir, "tpu_client.py"), "w") as f:
f.write(src)
def verify_mac_libraries_dont_reference_chkstack():
| 64 | 64 | 216 | 11 | 53 | inailuig/jax | build/build_wheel.py | Python | verify_mac_libraries_dont_reference_chkstack | verify_mac_libraries_dont_reference_chkstack | 103 | 123 | 103 | 103 | dd5c5c6353701617ae559702ac11a42c43cd5d5b | bigcode/the-stack | train |
f74c9fd5932c88566bbcc1fd | train | function | def _copy_so(src_file, dst_dir, dst_filename=None):
src_filename = os.path.basename(src_file)
if not dst_filename:
if _is_windows() and src_filename.endswith(".so"):
dst_filename = src_filename[:-3] + ".pyd"
else:
dst_filename = src_filename
dst_file = os.path.join(dst_dir, dst_filename)
if ... | def _copy_so(src_file, dst_dir, dst_filename=None):
| src_filename = os.path.basename(src_file)
if not dst_filename:
if _is_windows() and src_filename.endswith(".so"):
dst_filename = src_filename[:-3] + ".pyd"
else:
dst_filename = src_filename
dst_file = os.path.join(dst_dir, dst_filename)
if _is_windows():
shutil.copyfile(src_file, dst_fil... | ",
default=None,
required=True,
help="Path to which the output wheel should be written. Required.")
args = parser.parse_args()
r = runfiles.Create()
def _is_windows():
return sys.platform.startswith("win32")
def _copy_so(src_file, dst_dir, dst_filename=None):
| 64 | 64 | 108 | 14 | 50 | inailuig/jax | build/build_wheel.py | Python | _copy_so | _copy_so | 52 | 63 | 52 | 52 | 5f66c688506333f2fe12bbbff2be2582adbcf7c7 | bigcode/the-stack | train |
1469b566cc3a0127003b9653 | train | function | def prepare_wheel(sources_path):
"""Assembles a source tree for the wheel in `sources_path`."""
jaxlib_dir = os.path.join(sources_path, "jaxlib")
os.makedirs(jaxlib_dir)
copy_to_jaxlib = functools.partial(copy_file, dst_dir=jaxlib_dir)
verify_mac_libraries_dont_reference_chkstack()
copy_file(r.Rlocation("_... | def prepare_wheel(sources_path):
| """Assembles a source tree for the wheel in `sources_path`."""
jaxlib_dir = os.path.join(sources_path, "jaxlib")
os.makedirs(jaxlib_dir)
copy_to_jaxlib = functools.partial(copy_file, dst_dir=jaxlib_dir)
verify_mac_libraries_dont_reference_chkstack()
copy_file(r.Rlocation("__main__/jaxlib/setup.py"), dst_di... | know why this happens, but in some build environments
we seem to target the wrong Mac OS version.
https://github.com/google/jax/issues/3867
This check makes sure we don't release wheels that have this dependency.
"""
if platform.system() != "Darwin":
return
nm = subprocess.run(
["nm", "-g",
r... | 190 | 191 | 637 | 8 | 182 | inailuig/jax | build/build_wheel.py | Python | prepare_wheel | prepare_wheel | 126 | 163 | 126 | 126 | 5c0c3ff8a12b1af383806d75250a9d06e71e73c3 | bigcode/the-stack | train |
221c5a108d7e3b67f5143240 | train | function | def _copy_normal(src_file, dst_dir, dst_filename=None):
src_filename = os.path.basename(src_file)
dst_file = os.path.join(dst_dir, dst_filename or src_filename)
if _is_windows():
shutil.copyfile(src_file, dst_file)
else:
shutil.copy(src_file, dst_file)
| def _copy_normal(src_file, dst_dir, dst_filename=None):
| src_filename = os.path.basename(src_file)
dst_file = os.path.join(dst_dir, dst_filename or src_filename)
if _is_windows():
shutil.copyfile(src_file, dst_file)
else:
shutil.copy(src_file, dst_file)
| else:
dst_filename = src_filename
dst_file = os.path.join(dst_dir, dst_filename)
if _is_windows():
shutil.copyfile(src_file, dst_file)
else:
shutil.copy(src_file, dst_file)
def _copy_normal(src_file, dst_dir, dst_filename=None):
| 64 | 64 | 68 | 14 | 50 | inailuig/jax | build/build_wheel.py | Python | _copy_normal | _copy_normal | 66 | 72 | 66 | 66 | b4f208b17509d646b4fc17313283b84d16e04b26 | bigcode/the-stack | train |
ce1dd34ac078a409979043c5 | train | function | def build_wheel(sources_path, output_path):
"""Builds a wheel in `output_path` using the source tree in `sources_path`."""
platform_name = {
"Linux": "manylinux2010",
"Darwin": "macosx_10_9",
"Windows": "win",
}[platform.system()]
cpu_name = "amd64" if platform.system() == "Windows" else "x86_64"
... | def build_wheel(sources_path, output_path):
| """Builds a wheel in `output_path` using the source tree in `sources_path`."""
platform_name = {
"Linux": "manylinux2010",
"Darwin": "macosx_10_9",
"Windows": "win",
}[platform.system()]
cpu_name = "amd64" if platform.system() == "Windows" else "x86_64"
python_tag_arg = (f"--python-tag=cp{sys.vers... | flow/tensorflow/compiler/xla/python/xla_extension.so"))
patch_copy_xla_client_py(jaxlib_dir)
if not _is_windows():
copy_to_jaxlib(r.Rlocation("org_tensorflow/tensorflow/compiler/xla/python/tpu_driver/client/tpu_client_extension.so"))
patch_copy_tpu_client_py(jaxlib_dir)
def build_wheel(sources_path, output... | 85 | 85 | 284 | 11 | 74 | inailuig/jax | build/build_wheel.py | Python | build_wheel | build_wheel | 166 | 187 | 166 | 166 | 6ae72eb31e2a60542d7edc18897e01fc28b41c28 | bigcode/the-stack | train |
8071c8213a6d24e6130c6875 | train | function | def copy_file(src_file, dst_dir, dst_filename=None):
if src_file.endswith(".so"):
_copy_so(src_file, dst_dir, dst_filename=dst_filename)
else:
_copy_normal(src_file, dst_dir, dst_filename=dst_filename)
| def copy_file(src_file, dst_dir, dst_filename=None):
| if src_file.endswith(".so"):
_copy_so(src_file, dst_dir, dst_filename=dst_filename)
else:
_copy_normal(src_file, dst_dir, dst_filename=dst_filename)
| = os.path.basename(src_file)
dst_file = os.path.join(dst_dir, dst_filename or src_filename)
if _is_windows():
shutil.copyfile(src_file, dst_file)
else:
shutil.copy(src_file, dst_file)
def copy_file(src_file, dst_dir, dst_filename=None):
| 64 | 64 | 56 | 13 | 51 | inailuig/jax | build/build_wheel.py | Python | copy_file | copy_file | 75 | 79 | 75 | 75 | f415d5c408524e514dfc85ddd2d5b061bd3eeca5 | bigcode/the-stack | train |
259666c4d5e7b409c38d1611 | train | class | class QPolicyTest(test_utils.TestCase):
def setUp(self):
super(QPolicyTest, self).setUp()
self._obs_spec = tensor_spec.TensorSpec([2], tf.float32)
self._time_step_spec = ts.time_step_spec(self._obs_spec)
self._action_spec = tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1)
@test_util.run_in_graph... | class QPolicyTest(test_utils.TestCase):
| def setUp(self):
super(QPolicyTest, self).setUp()
self._obs_spec = tensor_spec.TensorSpec([2], tf.float32)
self._time_step_spec = ts.time_step_spec(self._obs_spec)
self._action_spec = tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1)
@test_util.run_in_graph_and_eager_modes()
def testBuild(self):... | Test for tf_agents.policies.q_policy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tf_agents.networks import network
from tf_agents.policies import q_policy
from tf_agents.specs import tensor_spec
from tf... | 256 | 256 | 1,418 | 9 | 246 | landuber/agents | tf_agents/policies/q_policy_test.py | Python | QPolicyTest | QPolicyTest | 49 | 179 | 49 | 50 | 8aecd1eddd50edda4a17a93d64037078a7c46860 | bigcode/the-stack | train |
1adcad138bfcb094c865acd2 | train | class | class DummyNet(network.Network):
def __init__(self, name=None, num_actions=2):
super(DummyNet, self).__init__(name, (), 'DummyNet')
self._layers.append(
tf.keras.layers.Dense(
num_actions,
kernel_initializer=tf.compat.v1.initializers.constant([[1, 1.5],
... | class DummyNet(network.Network):
| def __init__(self, name=None, num_actions=2):
super(DummyNet, self).__init__(name, (), 'DummyNet')
self._layers.append(
tf.keras.layers.Dense(
num_actions,
kernel_initializer=tf.compat.v1.initializers.constant([[1, 1.5],
... | tf_agents.networks import network
from tf_agents.policies import q_policy
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import time_step as ts
from tf_agents.utils import test_utils
from tensorflow.python.framework import test_util # TF internal
class DummyNet(network.Network):
| 64 | 64 | 146 | 6 | 57 | landuber/agents | tf_agents/policies/q_policy_test.py | Python | DummyNet | DummyNet | 31 | 46 | 31 | 32 | 618283102f7dc4e1bda27b0e9da33fabaa5e71e7 | bigcode/the-stack | train |
38e031cd2da0e1b7ddcf908a | train | function | def test_execute_user_script_error():
error = _errors.ExecuteUserScriptError(['python', '-m', '42'], return_code=42, output=b'42')
assert str(error) == """ExecuteUserScriptError:
Command "['python', '-m', '42']"
42"""
| def test_execute_user_script_error():
| error = _errors.ExecuteUserScriptError(['python', '-m', '42'], return_code=42, output=b'42')
assert str(error) == """ExecuteUserScriptError:
Command "['python', '-m', '42']"
42"""
| test_install_module_error():
error = _errors.InstallModuleError(['python', '-m', '42'], return_code=42, output=b'42')
assert str(error) == """InstallModuleError:
Command "['python', '-m', '42']"
42"""
def test_execute_user_script_error():
| 64 | 64 | 61 | 7 | 57 | mvsusp/sagemaker-containers | test/unit/test_errors.py | Python | test_execute_user_script_error | test_execute_user_script_error | 26 | 31 | 26 | 26 | 72ebaf546bc48823e9ce493b41b1b34819f4dfce | bigcode/the-stack | train |
e218b33b938bb7e989189152 | train | function | def test_install_module_error():
error = _errors.InstallModuleError(['python', '-m', '42'], return_code=42, output=b'42')
assert str(error) == """InstallModuleError:
Command "['python', '-m', '42']"
42"""
| def test_install_module_error():
| error = _errors.InstallModuleError(['python', '-m', '42'], return_code=42, output=b'42')
assert str(error) == """InstallModuleError:
Command "['python', '-m', '42']"
42"""
| on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from __future__ import absolute_import
from sagemaker_containers import _errors
def test_install_module_error():
| 64 | 64 | 58 | 6 | 57 | mvsusp/sagemaker-containers | test/unit/test_errors.py | Python | test_install_module_error | test_install_module_error | 18 | 23 | 18 | 18 | 4761b1b358caa46d3718ac4b25ffa0e0b32b5d52 | bigcode/the-stack | train |
e9f23e1d38a3774934b04615 | train | class | class LinearSVRAlgorithmWithPrecomputedKernel(RegressionAlgorithm):
'''
SVR with precomputed linear kernel.
'''
def __init__(self, kernel, y, grid_search_folds=10, c_range=np.logspace(-6, 2, 17), n_threads=15,
verbose=False):
self._kernel = kernel
self._y = y
sel... | class LinearSVRAlgorithmWithPrecomputedKernel(RegressionAlgorithm):
| '''
SVR with precomputed linear kernel.
'''
def __init__(self, kernel, y, grid_search_folds=10, c_range=np.logspace(-6, 2, 17), n_threads=15,
verbose=False):
self._kernel = kernel
self._y = y
self._grid_search_folds = grid_search_folds
self._c_range = c_r... | .get_kernel()
else:
kernel = self._kernel
x = self._input.get_x()
y = self._input.get_y_raw()
self._algorithm = LinearSVRAlgorithmWithPrecomputedKernel(kernel,
y,
grid_s... | 256 | 256 | 1,238 | 13 | 243 | anbai106/pyhydra | mlni/regression.py | Python | LinearSVRAlgorithmWithPrecomputedKernel | LinearSVRAlgorithmWithPrecomputedKernel | 116 | 252 | 116 | 116 | e7773a7e32d059d3c14be2ecd15a81986f5d644a | bigcode/the-stack | train |
f006baab19eecb7e32dd963a | train | class | class KFoldCV(RegressionValidation):
"""
KFold CV.
"""
def __init__(self, ml_algorithm):
self._ml_algorithm = ml_algorithm
self._fold_results = []
self._classifier = None
self._best_params = None
self._cv = None
def validate(self, y, n_folds=10, n_threads=15,... | class KFoldCV(RegressionValidation):
| """
KFold CV.
"""
def __init__(self, ml_algorithm):
self._ml_algorithm = ml_algorithm
self._fold_results = []
self._classifier = None
self._best_params = None
self._cv = None
def validate(self, y, n_folds=10, n_threads=15, splits_indices=None, verbose=False):... | y = self._input.get_y_raw()
self._algorithm = LinearSVRAlgorithmWithPrecomputedKernel(kernel, y,
grid_search_folds=self._grid_search_folds, c_range=self._c_range,
n_threads=self._n_threads, verbose=self._... | 221 | 221 | 737 | 8 | 213 | anbai106/pyhydra | mlni/regression.py | Python | KFoldCV | KFoldCV | 446 | 521 | 446 | 446 | 96807afb986cf1d72f1b898f84466e9e31724e98 | bigcode/the-stack | train |
a795485113e7dbfdb1349d47 | train | class | class VB_RepeatedHoldOut_DualSVM_Regression(WorkFlow):
"""
The main class to run MLNI with repeated holdout CV for regression.
"""
def __init__(self, input, split_index, output_dir, n_threads=8, n_iterations=100, test_size=0.2,
grid_search_folds=10, c_range=np.logspace(-6, 2, 17), kern... | class VB_RepeatedHoldOut_DualSVM_Regression(WorkFlow):
| """
The main class to run MLNI with repeated holdout CV for regression.
"""
def __init__(self, input, split_index, output_dir, n_threads=8, n_iterations=100, test_size=0.2,
grid_search_folds=10, c_range=np.logspace(-6, 2, 17), kernel=None, verbose=False):
self._input = input
... | _size=self._test_size)
classifier, best_params, results = self._validation.validate(y, n_threads=self._n_threads,
splits_indices=self._split_index, verbose=self._verbose)
classifier_dir = os.path.join(self._output_dir, 'regressor')
... | 138 | 138 | 460 | 16 | 122 | anbai106/pyhydra | mlni/regression.py | Python | VB_RepeatedHoldOut_DualSVM_Regression | VB_RepeatedHoldOut_DualSVM_Regression | 68 | 114 | 68 | 68 | 47c985094ab8f274b999e011b88f959f3ecf82b8 | bigcode/the-stack | train |
8be10c158fe0118abd4e3d0e | train | class | class RB_RepeatedHoldOut_DualSVM_Regression(WorkFlow):
"""
The main class to run MLNI with repeated holdout CV for regression.
"""
def __init__(self, input, split_index, output_dir, n_threads=8, n_iterations=100, test_size=0.2,
grid_search_folds=10, c_range=np.logspace(-6, 2, 17), kern... | class RB_RepeatedHoldOut_DualSVM_Regression(WorkFlow):
| """
The main class to run MLNI with repeated holdout CV for regression.
"""
def __init__(self, input, split_index, output_dir, n_threads=8, n_iterations=100, test_size=0.2,
grid_search_folds=10, c_range=np.logspace(-6, 2, 17), kernel=None, verbose=False):
self._input = input
... | from multiprocessing.pool import ThreadPool
from mlni.utils import time_bar
from joblib import dump
__author__ = "Junhao Wen"
__copyright__ = "Copyright 2019-2020 The CBICA & SBIA Lab"
__credits__ = ["Junhao Wen, Jorge Samper-González"]
__license__ = "See LICENSE file"
__version__ = "0.1.0"
__maintainer__ = "Junhao We... | 132 | 132 | 443 | 16 | 116 | anbai106/pyhydra | mlni/regression.py | Python | RB_RepeatedHoldOut_DualSVM_Regression | RB_RepeatedHoldOut_DualSVM_Regression | 21 | 66 | 21 | 21 | e339d7e6306cc92985c07bb57098382bc10432f4 | bigcode/the-stack | train |
78aa327ab884715556c42765 | train | class | class VB_KFold_DualSVM_Regression(WorkFlow):
"""
The main class to run MLNI with stritified KFold CV for regression with voxel-wise images.
"""
def __init__(self, input, split_index, output_dir, n_folds, n_threads=8, grid_search_folds=10,
c_range=np.logspace(-6, 2, 17), kernel=None, ve... | class VB_KFold_DualSVM_Regression(WorkFlow):
| """
The main class to run MLNI with stritified KFold CV for regression with voxel-wise images.
"""
def __init__(self, input, split_index, output_dir, n_folds, n_threads=8, grid_search_folds=10,
c_range=np.logspace(-6, 2, 17), kernel=None, verbose=False):
self._input = input
... | self._validation.validate(y, n_threads=self._n_threads,
splits_indices=self._split_index,
n_folds=self._n_folds, verbose=self._verbose)
classifier_dir = os.path.join(self._o... | 132 | 132 | 442 | 14 | 118 | anbai106/pyhydra | mlni/regression.py | Python | VB_KFold_DualSVM_Regression | VB_KFold_DualSVM_Regression | 400 | 444 | 400 | 400 | fb9c667707972538e453b5d0b8bb5d46c226616c | bigcode/the-stack | train |
1845519c89e7cb86bd50cc4d | train | class | class RepeatedHoldOut(RegressionValidation):
"""
Repeated holdout splits CV.
"""
def __init__(self, ml_algorithm, n_iterations=100, test_size=0.3):
self._ml_algorithm = ml_algorithm
self._split_results = []
self._classifier = None
self._best_params = None
self._c... | class RepeatedHoldOut(RegressionValidation):
| """
Repeated holdout splits CV.
"""
def __init__(self, ml_algorithm, n_iterations=100, test_size=0.3):
self._ml_algorithm = ml_algorithm
self._split_results = []
self._classifier = None
self._best_params = None
self._cv = None
self._n_iterations = n_itera... | .fit(self._kernel, self._y)
return svr, {'c': best_c, 'mae': mean_mae}
def save_classifier(self, classifier, output_dir):
np.savetxt(os.path.join(output_dir, 'dual_coefficients.txt'), classifier.dual_coef_)
np.savetxt(os.path.join(output_dir, 'support_vectors_indices.txt'), classifier.sup... | 256 | 256 | 988 | 9 | 247 | anbai106/pyhydra | mlni/regression.py | Python | RepeatedHoldOut | RepeatedHoldOut | 254 | 353 | 254 | 254 | 5e47c24388091fc9a10363ea42de024456904fa9 | bigcode/the-stack | train |
4c9bb2f7dc110d479c2c13d6 | train | class | class RB_KFold_DualSVM_Regression(WorkFlow):
"""
The main class to run MLNI with stritified KFold CV for regression with ROI features.
"""
def __init__(self, input, split_index, output_dir, n_folds, n_threads=8, grid_search_folds=10,
c_range=np.logspace(-6, 2, 17), kernel=None, verbose... | class RB_KFold_DualSVM_Regression(WorkFlow):
| """
The main class to run MLNI with stritified KFold CV for regression with ROI features.
"""
def __init__(self, input, split_index, output_dir, n_folds, n_threads=8, grid_search_folds=10,
c_range=np.logspace(-6, 2, 17), kernel=None, verbose=False):
self._input = input
... | results.tsv'),
index=False, sep='\t', encoding='utf-8')
mean_results_df = pd.DataFrame(all_results_df.apply(np.nanmean).to_dict(),
columns=all_results_df.columns, index=[0, ])
mean_results_df.to_csv(os.path.join(output_dir, 'mean_resu... | 127 | 127 | 424 | 14 | 113 | anbai106/pyhydra | mlni/regression.py | Python | RB_KFold_DualSVM_Regression | RB_KFold_DualSVM_Regression | 355 | 398 | 355 | 355 | eb9895dbb9cba7b3265c1ad43d0a39dfe4399611 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.