query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Categorical/softmax crossentropy loss with masking | def masked_categorical_crossentropy(y_true, y_pred):
mask = y_true[:, -1]
# y_true = y_true[:, :-1]
loss = K.categorical_crossentropy(target=y_true,
output=y_pred,
from_logits=True)
mask = K.cast(mask, dtype=np.float32)
loss... | [
"def masked_softmax_cross_entropy(preds, labels, mask):\r\n loss = -tf.reduce_sum(labels*tf.log(tf.nn.softmax(preds)+1e-7), axis=1)\r\n mask = tf.cast(mask, dtype=tf.float32)\r\n mask /= tf.reduce_mean(mask)\r\n loss *= mask\r\n return tf.reduce_mean(loss)",
"def _cross_entropy_loss(self, y_true_cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the packet `size`. | def test_size():
assert Packet2.size == 6 | [
"def test_size():\n assert Packet12.size == 1",
"def check_size(msg):\n\n if len(msg) > TWEET_SIZE:\n return False\n return True",
"def __check_size__(self, size):\n # size must be an integer, otherwise raise a TypeError exception\n if type(size) != int:\n raise TypeErro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a `PythonLogLevel` field. | def __init__(self, description=None): # type: (Optional[six.text_type]) -> None
super(PythonLogLevel, self).__init__(
logging.getLevelName(logging.DEBUG),
logging.getLevelName(logging.INFO),
logging.getLevelName(logging.WARNING),
logging.getLevelName(logging.ERRO... | [
"def as_python_level(self) -> int:\n to_python_level = {\n LogLevel.CRITICAL: logging.CRITICAL,\n LogLevel.ERROR: logging.ERROR,\n LogLevel.WARNING: logging.WARNING,\n LogLevel.INFO: logging.INFO,\n LogLevel.DEBUG: logging.DEBUG}\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Follows the same initialization design as the PlotSessions class, but just returns the raw info for the API | def __init__(self,
session_objs: SessionsFromInterval=None,
session: SessionData=None):
self.sessions = None
self.session_objs = session_objs
if session_objs:
self.sessions = session_objs
elif session:
self.sessions = [session]
... | [
"def info(self):\n sess_info = {}\n\n sess_info['ID'] = self.get('ID')\n sess_info['label'] = self.get('label')\n sess_info['note'] = self.get('xnat:note')\n sess_info['session_type'] = self.get('session_type')\n sess_info['project_id'] = self.project\n sess_info['or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test whether users exist on changelist page | def test_users_on_changelist(self):
url = reverse('admin:core_user_changelist')
response = self.client.get(url)
self.assertContains(response, self.user.email)
self.assertContains(response, self.admin_user.email) | [
"def test_users_listed(self) -> None:\n url = reverse(\"admin:core_user_changelist\")\n response_ = self.client.get(url)\n\n self.assertContains(response_, self.user.name)\n self.assertContains(response_, self.user.email)",
"def test_users_listed(self):\n url = reverse('admin:co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a set of wayback URLs | def getUrls(domain):
wayback_urls = set()
history = requests.get(API_URL + domain).text.splitlines()
for line in history:
record = parse_wayback_record(line)
if record.mimetype == "text/html":
url = domain + record.path
wayback_url = BASE_URL + record.timestamp + "/" ... | [
"def _get_all_url(cls) -> str:",
"def urls(self):\n return [\n url('', include(self.get_list_urls()), {'flow_class': self.flow_class}),\n self.flow_class.instance.urls\n ]",
"def get_urls(self):\n return [\n url(\"^$\", self.browser_index, name=\"api_playgro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a new proposal from a trajectory state. The trajectory state records information about the position in the state space and corresponding potential energy. A proposal also carries a weight that is equal to the difference between the current energy and the previous one. It thus carries information about the prev... | def update(
previous_proposal: Proposal, state: IntegratorState
) -> Tuple[Proposal, bool]:
energy = previous_proposal.energy
new_energy = state.potential_energy + kinetic_energy(
state.position, state.momentum
)
delta_energy = energy - new_energy
delta_e... | [
"def create_proposal(sequence) -> Proposal:\n return Proposal(sequence)",
"def transition_from(self, state):\n a, b, c = state\n tomorrow_state = [(0, 0, 0)]\n if a == 0:\n proba_state = [1.0] # exogenous state is absorbing. Done.\n else:\n proba_state = [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Baised proposal sampling. Unlike uniform sampling, biased sampling favors new proposals. It thus biases the transition away from the trajectory's initial state. | def progressive_biased_sampling(rng_key, proposal, new_proposal):
p_accept = jnp.exp(new_proposal.weight - proposal.weight)
p_accept = jnp.clip(p_accept, a_max=1.0)
do_accept = jax.random.bernoulli(rng_key, p_accept)
updated_proposal = Proposal(
new_proposal.state,
new_proposal.energy,
... | [
"def sample(self, state):\n # get probabilities for next state over all states observed so far, plus oracle proba in final index:\n base_probas = self.base_probas(state)\n # sample one of the states (or oracle query):\n next_state = np.random.choice(range(len(base_probas)), p=base_probas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides parse results over an iterable of input lines which are parsed according to the format of the implementation. | def parse_lines(self, lines):
raise NotImplementedError(self.__class__) | [
"def build_from(lines:[str]) -> [object]:\n lines = iter(lines)\n current_line = None\n while True:\n try:\n line = next(lines).strip()\n except StopIteration:\n break\n if not line: break\n if REG_CHARACTER.match(line): ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for printing progress and time elapsed. | def progress(i, num_total, t):
dt = time.time() - t
print '\r', i, '/',num_total, 'Elapsed Time:', dt , 'Time Remaining:',
print 1.0 * dt / (i+1) * (num_total-i-1), | [
"def show_elapsed_time(start, end):\n PRINT('Elapsed: %s' % (end - start))",
"def module_progress(strInfo):\n\n sys.stdout.write(_colors('PROGRESS') + '\\n > ' + _colors('ENDC'))\n sys.stdout.write(strInfo + '...')\n sys.stdout.flush()\n\n # Start the timer\n tStart = time.time()\n\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to sample an op for each edge. | def add_sampled_op_index(edge):
op_index = np.random.randint(len(edge.data.op))
edge.data.set('op_index', op_index, shared=True) | [
"def make_samples(self):\n for generated_pixel in self.generate_edge_pixels():\n yield self.pixel_to_sample(generated_pixel[0], generated_pixel[1])",
"def sample_edge_uniform(_, __, n_triplets, sample_size):\n all_edges = np.arange(n_triplets)\n return np.random.choice(all_edges, sample_si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to replace the primitive ops at the edges with the sampled one | def update_ops(edge):
if isinstance(edge.data.op, list):
primitives = edge.data.op
else:
primitives = edge.data.primitives
edge.data.set('op', primitives[edge.data.op_index])
edge.data.set('primitives', primitives) # store for later use | [
"def add_sampled_op_index(edge):\n op_index = np.random.randint(len(edge.data.op))\n edge.data.set('op_index', op_index, shared=True)",
"def replace(self, subset):\n for e in subset:\n v = e[0]\n self.remove_edge(e)\n choices = list(set(self.vertices()) - set([v]))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the basename of a path, lowercased. | def get_lower_basename(path):
return os.path.basename(os.path.normpath(os.path.abspath(path))).lower() | [
"def basename(input_file):\n\n input_file = value_checkup(input_file)\n return os.path.basename(os.path.splitext(input_file)[0])",
"def sort_by_basename_icase(path):\n\treturn path.basename_lower",
"def crds_basename(name):\n if name == \"N/A\":\n return \"N/A\"\n else:\n return os.pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create or replace path. | def create_path_or_replace(path_to_create):
if os.path.exists(path_to_create):
shutil.rmtree(path_to_create)
create_path_tree(path_to_create) | [
"def createPath(self, path):\n if os.path.abspath('.') != os.path.abspath(path):\n try:\n os.makedirs(path)\n except OSError:\n print \"Error: Path already exists.\"\n self._handleCollision(path)",
"def create_path(path: str) -> None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a path tree if folders does not exist. | def create_path_tree(path_to_create):
current = ""
for path in path_to_create.split("/"):
current = os.path.join(current, path)
# Root
if current == "":
current = "/"
continue
if not os.path.exists(current):
os.makedirs(current) | [
"def create_dirs(path_to_dir):\n path_to_dir = Path(path_to_dir)\n if not path_to_dir.exists():\n path_to_dir.mkdir(parents=True)\n LOG.debug(f\"Created directory structure: '{path_to_dir}'\")",
"def create_folder(path):\n Path(path).mkdir(parents=True, exist_ok=True)",
"def create_folder... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns first found reader | def get_reader():
rarr=readers()
if len(rarr) == 0:
return None
return rarr[0] | [
"def get_first_row(self):\n if not self.csv_reader:\n return None\n\n if not self.first_row:\n the_list = list(self.csv_reader)\n if the_list:\n self.first_row = the_list[0]\n self.reset_csv()\n else:\n return Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select an applet with appletID appletID can be either a hexencoded string or byte sequence | def select_applet(connection, appletID):
data = maybe_fromhex(appletID)
# Select:
# CLA = 0x00
# INS = 0xA4
# P1 = 0x04
# P2 = 0x00
# Data = the instance AID
cmd = [0x00, # CLA
0xA4, # INS
0x04, # P1
0x00, # P2
len(data), # Lc (content length)
... | [
"def ExtractText(self):\n return \"[applet]\"",
"def applet_new(input_params={}, always_retry=False, **kwargs):\n return DXHTTPRequest('/applet/new', input_params, always_retry=always_retry, **kwargs)",
"def applet_run(object_id, input_params={}, always_retry=False, **kwargs):\n return DXHTTPReques... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in a filename, and for each gene (in name column), collapse regions such that each gene has nonoverlapping intervals. This might be functionally the same as merge() but it's really slow. | def merge2(fn):
df = pd.read_table(fn, names=['chrom','start','end','name','score','strand'])
df.sort_values(['chrom','start','end'], inplace=True)
df = df.groupby('name').apply(collapse)
df.reset_index(inplace=True)
return df[['chrom','start','end','name','score','strand']] | [
"def clean_overlap ( self ):\n regions = self.regions\n new_regions = {}\n chrs = regions.keys()\n chrs.sort()\n for chrom in chrs:\n new_regions[chrom]=[]\n n_append = new_regions[chrom].append\n prev_region = None\n regions_chr = regio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a pandas dataframe, return a list of strings that represent a bedfile (tabbed) | def make_linelist_from_dataframe(df):
lst = []
for values in df.head().values:
lst.append('\t'.join([str(v) for v in values]))
return lst | [
"def bed_to_df(bed_file):\n header_lines = 0\n #Handle likely header by checking colums 2 and 3 as numbers\n with open(bed_file, 'r') as f:\n next_line = f.readline().strip()\n line_split = next_line.split(None) #This split by any blank character\n start = line_split[1]\n end = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renames the BedTools.Interval.name() into something that can be used as an index (removes the tabs and replaces with a more friendly delimiter | def rename_index(interval_name):
chrom, start, end, name, score, strand = str(
interval_name
).strip().split('\t')
return "{}:{}-{}:{}:{}".format(chrom, start, end, name, strand) | [
"def new_index_from_name(base_name):\n return base_name + \".\" + str(int(time.time()))",
"def set_interval_name(sinsData):\n tempData = []\n df_depth = sinsData.df_depth\n for name,df_well in zip (sinsData.wellnames,sinsData.dfs_well):\n for index, row in df_depth[df_depth[\"Well\"] == name].i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits list (lst) into n equal parts. | def split(lst, n):
newlist = []
division = len(lst) / float(n)
for i in xrange(n):
newlist.append(
lst[int(round(division * i)):int(round(division * (i + 1)))])
return newlist | [
"def do_chunkify(lst,n):\n return [lst[i::n] for i in range(n)]",
"def divide_list_in_n_equal_chunks(_list, n):\n for i in range(0, len(_list), n):\n yield _list[i : i + n]",
"def chunks(l, n):\n \n if n<1:\n n=1\n return [l[i:i+n] for i in range(0, len(l), n)]",
"def partition_li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given two boundaries (upper and lower genomic boundaries), returns the area defined by anchor lower_offset and anchor + upper_offset. If the region bleeds over the boundaries, this function will return the genomic left pad and genomic right pad. | def _get_absolute_coords_and_pad(
anchor,
upper_boundary, upper_offset,
lower_boundary, lower_offset):
left_pad = _too_far(anchor, lower_offset, lower_boundary, -1)
right_pad = _too_far(anchor, upper_offset, upper_boundary, 1)
absolute_start = anchor - lower_offset + left_pad
ab... | [
"def range_overlap(a, b, ratio=False):\n a_chr, a_min, a_max = a\n b_chr, b_min, b_max = b\n a_min, a_max = sorted((a_min, a_max))\n b_min, b_max = sorted((b_min, b_max))\n shorter = min((a_max - a_min), (b_max - b_min)) + 1\n # must be on the same chromosome\n if a_chr != b_chr:\n ov = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines what the genomic lower boundary is. For intron regions, if a neighboring (next) interval exists, set the boundary with respect to that. Otherwise, set the lower boundary to 0. For exon regions, if 'stop_at_midpoint' flag is on, set the boundary to the middle of the exon. Otherwise, set the lower boundary to ... | def _get_lower_boundary(current_interval, next_interval, strand_or_5p,
stop_at_midpoint=False):
if strand_or_5p == '+':
if stop_at_midpoint:
return (current_interval.end + current_interval.start) / 2
else:
return current_interval.start
else:
... | [
"def _lower_bound(self, query: str, offset_l: int, offset_h: int) -> int:\n logging.debug('lower bound 2 %s %s %s', query, offset_l, offset_h)\n if offset_l >= offset_h:\n return self._seek_back_to_line_start(offset_l)\n\n mid = (offset_l + offset_h) // 2\n\n line_start = self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines what the genomic upper boundary is. For intron regions, if a neighboring (next) interval exists, set the boundary with respect to that. Otherwise, set the upper boundary to MAX. For exon regions, if 'stop_at_midpoint' flag is on, set the boundary to the middle of the exon. Otherwise, set the upper boundary t... | def _get_upper_boundary(current_interval, next_interval, strand_or_5p,
stop_at_midpoint=False):
if strand_or_5p == '+':
return next_interval.start if next_interval is not None else MAX
else:
if stop_at_midpoint:
return (current_interval.end + current_interval.... | [
"def boundary():\r\n return 250",
"def getOptBoundUpper(self):\n return _core.CGPopt_getOptBoundUpper(self)",
"def upper_limit(self, val):\n self.gf_condition(upperLimit=val)",
"def setOptBoundUpper(self, optBoundUpper):\n return _core.CGPopt_setOptBoundUpper(self, optBoundUpper)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes nans from a list (replaces with 0), and appends padding to ensure that the list will always be of length len(wiggle) + left_pad + right_pad. | def _clean_and_add_padding(wiggle, left_pad=0, right_pad=0, fill_pads_with=-1):
wiggle = pd.Series(wiggle)
wiggle = abs(wiggle)
wiggle = np.pad(
wiggle,
(left_pad, right_pad),
'constant',
constant_values=fill_pads_with
)
wiggle = np.nan_to_num(wiggle)
return wiggl... | [
"def padding(x, L, padding_list=None):\n len_x = len(x)\n assert len_x <= L, \"Length of vector x is larger than the padding length\"\n zero_n = L - len_x\n if padding_list is None:\n x.extend([0] * zero_n)\n elif len(padding_list) < zero_n:\n x.extend(padding_list + [0] * (zero_n - len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the score of a region with peak overlaps as a series. | def get_overlap(peak, region, score_type='simple'):
series = pd.Series(data=0, index=range(len(region)))
overlap_type, overlap = determine_overlap(peak, region)
if overlap_type == 'no_overlap':
return series
elif overlap_type == 'equal':
series[:] = [score(score_type, peak, region) fo... | [
"def max_min_score (self):\n peaks = self.peaks\n chrs = peaks.keys()\n chrs.sort()\n x = 0\n y = 100000\n for chrom in chrs:\n if peaks[chrom]:\n m = max([i[4] for i in peaks[chrom]])\n if m>x:\n x=m\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes two intervals (peak, region) and determines whether or not the peak overlaps the left, right, entire region, or not at all. | def determine_overlap(peak, region):
assert(peak.strand == region.strand)
# print('peak:', peak.start, peak.end)
# print('region:', region.start, region.end)
if peak.start >= region.end or region.start >= peak.end:
# newPeak and region don't overlap
return 'no_overlap', 0
elif peak.s... | [
"def regions_overlap(r1,r2):\n x = False\n for loc in r1.locs:\n if loc in r2.locs:\n return True\n return False",
"def _do_intervals_overlap(intervals_a, intervals_b):\n\n def contained(points, intervals):\n return np.logical_and(\n np.less_equal(intervals[:, 0], points),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
masks the intervals in df based on where peaks are. If a peak does not directly overlap the region at a given position, mask that position with nan. If a peak does overlap, preserve the score. | def mask(df, peak, stream):
progress = trange(len(df.index))
for i in df.index:
region = bedtool_from_renamed_twobed_index(i, stream)
masked_interval = peak.values(region.chrom, region.start, region.end, region.strand)
if sum(masked_interval) != 0:
for pos in masked_interval.... | [
"def _remove_overlaps(segmentation_mask, fronts):\n fidxs, sidxs = np.where((segmentation_mask != fronts) & (segmentation_mask != 0) & (fronts != 0))\n fronts[fidxs, sidxs] = 0",
"def detect_peaks_1d(timeseries, delta_peak, threshold, peak_width=5):\n\n # Sort time series by magnitude.\n max_idx = np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the target sum of two numbers in collection. Naive method, iterate through string. | def find_sum_naive(collection, target):
for i in collection:
for j in collection[1:]:
if i + j == target:
return True
return False | [
"def sum_integers(string):",
"def twoSum(self, nums, target):\n for i in nums:\n for j in nums:\n my_target = i + j\n if my_target == target:\n return i, j",
"def sum(str1: str, str2: str) -> str:\n\n print(\"str1=\" + str(str1) + \", str2=\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move to the cookie's location, and begin clicking. | def click_cookie(self):
# Locate the cookie, and move the mouse over it
cookie_location = pyautogui.locateOnScreen(self.cookie_image)
pyautogui.moveTo(cookie_location)
# main logic
if cookie_location is not None:
while True:
for i in range(0, 105):
... | [
"def set_clicked_cookie(headers, code):\n cookieUtil = Cookie.SimpleCookie()\n cookieUtil[code] = True\n cookieUtil.name = code\n cookieUtil[code]['expires'] = 31556928\n \n headers.add_header('Set-Cookie', cookieUtil.output())",
"def _dismiss_cookies(self):\n print(\"W dismis_cookies z B... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates an JSON schema based on the class structure in SQL.py | def generate_schema():
_result = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "The JSON Schema for QAL transformations",
"title": "QAL Transformation",
"type": "object",
"version": __version__,
"properties": {},
"namespace": "qal",
... | [
"def _schema_to_json(schema):\n features = []\n sparse_features = []\n for name, column_schema in sorted(six.iteritems(schema.column_schemas)):\n if isinstance(column_schema.representation,\n sch.SparseColumnRepresentation):\n sparse_features.append(_sparse_column_schema_to_json(name, co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log any invalid run states found. | def _LogInvalidRunLevels(states, valid):
invalid = set()
for state in states:
if state not in valid:
invalid.add(state)
if invalid:
logging.warning("Invalid init runlevel(s) encountered: %s",
", ".join(invalid)) | [
"def test_invalid_run(self):\n probe_run = 123321\n self.assertTrue(probe_run not in RUNS)\n self.assertFalse(utils.valid_run(probe_run))",
"def error(self):\n \n print('---error state report ---')\n print(' state', self.state)\n print(' scenario', self.scenario)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accepts a string and returns a list of strings of numeric LSB runlevels. | def GetRunlevelsLSB(states):
if not states:
return set()
valid = set(["0", "1", "2", "3", "4", "5", "6"])
_LogInvalidRunLevels(states, valid)
return valid.intersection(set(states.split())) | [
"def GetRunlevelsNonLSB(states):\n if not states:\n return set()\n convert_table = {\n \"0\": \"0\",\n \"1\": \"1\",\n \"2\": \"2\",\n \"3\": \"3\",\n \"4\": \"4\",\n \"5\": \"5\",\n \"6\": \"6\",\n # SysV, Gentoo, Solaris, HP-UX all allow an alpha variant\n # for s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accepts a string and returns a list of strings of numeric LSB runlevels. | def GetRunlevelsNonLSB(states):
if not states:
return set()
convert_table = {
"0": "0",
"1": "1",
"2": "2",
"3": "3",
"4": "4",
"5": "5",
"6": "6",
# SysV, Gentoo, Solaris, HP-UX all allow an alpha variant
# for single user. https://en.wikipedia.org/wiki/Run... | [
"def GetRunlevelsLSB(states):\n if not states:\n return set()\n valid = set([\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\"])\n _LogInvalidRunLevels(states, valid)\n return valid.intersection(set(states.split()))",
"def __get_bin_list(string):\n return [1 if str(c).isupper() else 0 for c in string]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dump the classifier 'cls' to a pickle named 'fn'. | def _dump_cls(self, cls, fn):
w = gzip.open(fn, 'wb')
cPickle.dump(cls, w, 1)
w.close() | [
"def saveClassifier(filename, clf):\n with open(filename, 'wb') as fid:\n cPickle.dump(clf, fid)",
"def save_classifier(self,filename=\"classifier.pickle\"):\n with open(filename,\"w\") as f:\n pickle.dump(self.classifier,f)",
"def classifier_save(self, classifier, path=\"../../../da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if pan is in the current limits | def _is_in_pan_bounds(self, pan):
return self.neck_pan_bounds[0] <= pan and self.neck_pan_bounds[1] >= pan | [
"def inside_bounds(self, point):\n return all(mn <= p <= mx for p, (mn, mx) in zip(point, self.bounds))",
"def CanEast(self):\n return (not self.HWLimit) or (self.LimOverride and self.WestLim)",
"def within_limits(self):\n within_limit = True\n\n for lux_sensor, limit in self.lightlevel.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if tilt is in the current limits | def _is_in_tilt_bounds(self, tilt):
return self.neck_tilt_bounds[0] <= tilt and self.neck_tilt_bounds[1] >= tilt | [
"def within_limits(self):\n within_limit = True\n\n for lux_sensor, limit in self.lightlevel.items():\n current_lightlevel = float(self.get_state(lux_sensor))\n if current_lightlevel > limit:\n within_limit = False\n self.log('Light level beyond limi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the joints are is in the current limits | def _is_in_bounds(self, joints):
return self._is_in_pan_bounds(joints[0]) and self._is_in_tilt_bounds(joints[1]) | [
"def check_joint_limit(self, curve, info):\n low_mask = (curve < self.joint_lower_limit - 5e-3).any()\n high_mask = curve > self.joint_upper_limit + 5e-3\n over_joint_limit = (low_mask * high_mask).any() #\n info[\"violate_limit\"] = over_joint_limit\n info[\"terminate\"] = info[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change direction of the pan movement | def change_pan_direction(self):
self.neck_pan_delta *= -1 | [
"def change_tilt_direction(self):\n self.neck_tilt_delta *= -1",
"def set_direction(self, direction):",
"def pan(self, angle):\n self.__send_servo_command(self.__CMD_PAN, angle)",
"def move(self, direction):\n if direction == Direction.north:\n self.y -= 1\n elif directi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change direction of the tilt movement | def change_tilt_direction(self):
self.neck_tilt_delta *= -1 | [
"def levelTilt(self):\n self.tiltAngle = 0",
"def tilt(self, angle):\n self.__send_servo_command(self.__CMD_TILT, angle)",
"def set_direction(self, direction):",
"def tilt(self, angle):\n self.tiltAngle += angle\n tiltBound = 90 # Tilt restriction (degrees)\n if self.tiltAng... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for upserting samples using API data data of response | def upsert(self, data):
url = '/samples/upsert'
return post(url, data) | [
"def upsert_bulk(self, data):\n url = '/samples/upsert/bulk'\n return post(url, data)",
"def bulk_upsert(self, docs):\n\n for doc in docs:\n index = doc[\"ns\"] \n doc[\"_time\"] = doc[\"_id\"].generation_time\n \n service = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for bulk upserting samples using API data data of response | def upsert_bulk(self, data):
url = '/samples/upsert/bulk'
return post(url, data) | [
"def bulk_upsert(self, docs):\n\n for doc in docs:\n index = doc[\"ns\"] \n doc[\"_time\"] = doc[\"_id\"].generation_time\n \n service = self.getConnection()\n\n source = index.split(\".\")\n index_name = index.replace(\"_\",\"-\").repl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays notifications. Optionally pass in your own attributes, to override defaults in class. | def display(
self,
notifications: List[Notification],
attributes: Optional[List[List[str]]] = None,
):
if len(notifications) < 1:
self._write_stdout(self._no_notifications_msg)
return
if attributes is None:
attributes = self._default_attrib... | [
"def render(self, notification):\n raise NotImplementedError()",
"def notify(self, title, message, icon_data=None):\n \n print \"[\" + title + \"]\"\n print message\n print",
"def notify(self, **kwargs):\n self.notifiers.notify(**kwargs)",
"def showEvent(self, event):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a data structure for storing batched calls to Datastore Lookup. The batch data structure is stored in the current context. If there is not already a batch started, a new structure is created and an idle callback is added to the current event loop which will eventually perform the batch look up. | def get_batch(batch_cls, options=None):
# prevent circular import in Python 2.7
from google.cloud.ndb import context as context_module
context = context_module.get_context()
batches = context.batches.get(batch_cls)
if batches is None:
context.batches[batch_cls] = batches = {}
if option... | [
"def _get_lookup_batch():\n state = _runstate.current()\n batch = state.batches.get(_BATCH_LOOKUP)\n if batch is not None:\n return batch\n\n state.batches[_BATCH_LOOKUP] = batch = {}\n _eventloop.add_idle(_perform_batch_lookup)\n return batch",
"def _perform_batch_lookup():\n state = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute rules and handler | async def execute_handler(self, *args):
# args - (event, data)
if self.rules:
_execute = False
for rule in self.rules:
if not asyncio.iscoroutinefunction(rule) and not isinstance(
rule, BaseRule
):
result = r... | [
"def process(self, x):\n match_not_found = True\n if self.before_processing:\n self.before_processing(x)\n for rule in self._rules:\n if rule.matches(x):\n rule.action(x)\n match_not_found = False\n if rule.last:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns FocusGame Player One object | def get_player_one(self):
return self._player_one | [
"def player():\n\n name_id = 1\n return card_game.Player(name_id)",
"def _get_ac_player(self):\n\t\treturn self.players[self.active_player]",
"def get_player(self, name):\r\n return User(name)",
"def getPlayer(self, p):\n log(\"MState getPlayer\",5)\n if type(p) == Player:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns FocusGame Player Two object | def get_player_two(self):
return self._player_two | [
"def player_2(self):\n return self.player_2_init or self.previous_match_2.winner()",
"def initialize_second_player(self, option):\n if option is BOT:\n self.players[\"1\"] = BotPlayer(self.player_marks[\"1\"])\n self.players[\"1\"].set_player_info(\"Bot Player\")\n else:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a parameter of a player name, sets the FocusGame turn to that player | def set_turn(self, player_name):
self._turn = player_name | [
"def set_player_name(name):\n\n player[\"player_name\"] = name",
"def change_player():\n\n global current_player\n if current_player == 'X':\n current_player = 'O'\n elif current_player == 'O':\n current_player = 'X'\n return",
"def change_name(self, name):\n self._player_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a parameter of a player_name and sets the winner data field of FocusGame to the inputted player | def set_winner(self, player_name):
self._winner = player_name | [
"def set_player_name(name):\n\n player[\"player_name\"] = name",
"def test_set_player_name(self):\n self.game.set_player(1, \"Wille\")\n p_1 = self.game.player1\n exp = \"Lucas\"\n self.game.set_player_name(\"Lucas\", p_1)\n self.assertEqual(exp, p_1.name)",
"def set_player... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for the movement of pieces. Takes a player_name, start location, destination location, and the number of pieces desired to move as parameters. move_piece will check the validity of the move and then make the appropriate move depending on whether it is a single move or multiple move. Will update the board, and ca... | def move_piece(self, player_name, start, destination, num_of_pieces):
if self.get_winner() is not None:
return self.get_winner() + ' has already won!'
turn = self.get_turn()
player = self.get_active_player(player_name)
move_size = self.move_size(start, destination)
va... | [
"def move_piece(self, player_name, from_position, to_position, pieces_moved):\n if self._whose_turn is None:\n self._whose_turn = player_name\n\n # general validation\n validation_result = self.general_move_validation(player_name, to_position)\n if validation_result is not Tru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the stack post player move and processes it. Captures enemy pieces and gets reserve pieces if the size of the stack is more than five pieces. Updates the current board and returns it to the calling function. | def process_stack(self, board, destination, player):
stack = board[destination[0]][destination[1]]
while len(stack) > 5:
piece = stack[0]
if piece == player.get_player_color():
player.add_reserve_piece()
else:
player.capture_piece()
... | [
"def overflow(self, player, move):\r\n player_profile = self.which_player(player)\r\n piece_move = self._board[move[0]][move[1]]\r\n while len(self._board[move[0]][move[1]]) > 5:\r\n bottom_piece = piece_move[0]\r\n self._board[move[0]][move[1]].pop(0)\r\n if bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the starting location tuple, destination tuple, and pieces to move tuple. Updates the initial location with the first item in the pieces to move tuple (the part of the stack not desired to move) appends the second part of the pieces to move tuple to the destination list. Returns the updated instance of the board. | def update_board_location(self, start, destination, pieces_to_move):
board = self.get_board()
board[start[0]][start[1]] = pieces_to_move[0]
list_of_pieces_to_add = pieces_to_move[1]
for piece in list_of_pieces_to_add:
board[destination[0]][destination[1]].append(piece)
... | [
"def move(self, start, end):\n piece = self.get_piece_at(*start)\n opposing_piece = self.get_piece_at(*end)\n \n if opposing_piece != None:\n opposing_piece.is_alive = False\n opposing_piece.x = None\n opposing_piece.y = None\n \n if str(piece) == 'Pawn':\n self.promote(piece, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the coordinates of teh stack, and the number of pieces desired to move form that stack, as parameters. Splits the stack and returns it in a tuple. | def get_pieces_to_move(self, coord, num_of_pieces):
stack = self.get_stack(coord)
pieces_to_move = []
counter = 0
while counter != num_of_pieces:
pieces_to_move.insert(0, stack.pop())
counter += 1
return stack, pieces_to_move | [
"def move_stack(n, start, end):\n assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, \"Bad start/end\"\n def do_move(source, end):\n print_move(source, end)\n\n def play_game(disks, source, end, spare):\n if (disks == 1):\n do_move(source, end)\n else:\n p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a player_name as a parameter and returns the active player based on the player name | def get_active_player(self, player_name):
player_one = self.get_player_one()
player_two = self.get_player_two()
if player_one.get_player_name() == player_name:
return player_one
if player_two.get_player_name() == player_name:
return player_two
else:
... | [
"def findPlayerByName(self, name): \r\n\t\treturn self.__players_by_name.get(name.lower(), None)",
"def get_player(self, name):\n\n try:\n name = name.name\n except AttributeError: pass\n\n for i in self.players:\n if i.name == name:\n return i",
"def pl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a player name as a parameter and returns how many pieces they have in reserve | def show_reserve(self, player_name):
player = self.get_active_player(player_name)
return player.get_reserve_pieces() | [
"def check_occupancy(shelter_name):\n\tresult = session.query(Shelter.name,func.count(Puppy.id).label('puppy_count'),Shelter.max_occ)\\\n\t.outerjoin(Shelter.name).group_by(Shelter.name).filter(Shelter.name==shelter_name).one()\n\tnum_left = result.max_occ-result.puppy_count\n\tprint \"Cur Occupancy - {sname}: {pco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a players name, and the destination coordinates and determines if they can make a reserve piece move, and executes if so. Updates the turn order. Returns a message if failed. | def reserved_move(self, player_name, coord):
player = self.get_active_player(player_name)
board = self.get_board()
if player.get_reserve_pieces() < 1:
return 'no pieces in reserve'
board[coord[0]][coord[1]].append(player.get_player_color())
player.remove_reserve_piece... | [
"def move_piece(self, player_name, start, destination, num_of_pieces):\n if self.get_winner() is not None:\n return self.get_winner() + ' has already won!'\n turn = self.get_turn()\n player = self.get_active_player(player_name)\n move_size = self.move_size(start, destination)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes with empty captured pieces, reserved pieces, their assigned color, and name. | def __init__(self, player_name, player_color):
self._player_name = player_name
self._player_color = player_color
self._reserve_pieces = 0
self._captured_pieces = 0 | [
"def __init__(self, name, color):\n self._name = name\n self._color = color\n self._is_turn = None\n self._red_captured = 0\n self._marbles_left = 8",
"def __init__(self):\n \n # White always starts the game\n self.current_turn = 'white'\n self.num_wh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a piece to the player's reserve pile | def add_reserve_piece(self):
self._reserve_pieces += 1 | [
"def add_to_reserve(self, pawn):\n self._reserve.append(pawn)",
"def place_piece(board, x, y, player):\n can_place = isfree(board, x, y)\n if can_place:\n board[(x,y)] = player\n return can_place",
"def add_piece(self, piece):\n self.piece = piece\n self.set_piece_rect(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if there are enough reserve pieces for a move, then removes one if so, if not returns an error message | def remove_reserve_piece(self):
self._reserve_pieces -= 1 | [
"def reserved_move(self, player_name, coord):\n player = self.get_active_player(player_name)\n board = self.get_board()\n if player.get_reserve_pieces() < 1:\n return 'no pieces in reserve'\n board[coord[0]][coord[1]].append(player.get_player_color())\n player.remove_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Captures a piece for the player | def capture_piece(self):
self._captured_pieces += 1 | [
"def take_effect(self, player):\n\t\tpass",
"def add_piece(self, piece):\n self.piece = piece\n self.set_piece_rect(self.square_rect)",
"def captured_piece(self):\n self._num_captured += 1",
"def play(self, player, game):\n pass #normal card dont play cause only a special card act... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reflect point a across vector b | def reflect(a, b):
return 2 * proj(a,b) - a | [
"def get_vector(a, b):\n return Vector(b.x - a.x, b.y - a.y, b.z - a.z)",
"def tangent(self, pos):",
"def proj(a,b):\n return np.dot(a,b) * b / (np.linalg.norm(b)**2)",
"def get_relative_transformation(a_to_base, b_to_base):\n\n base_to_a = np.linalg.inv(a_to_base)\n return base_to_a @ b_to_base",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Projects vector a onto vector b returns the projected vector | def proj(a,b):
return np.dot(a,b) * b / (np.linalg.norm(b)**2) | [
"def projection(b, a, norm=False):\n if norm:\n proj = np.dot(np.dot(a, a.T), b)\n else:\n c = np.dot(a.T, b) / np.dot(a.T, a)\n proj = c * a\n\n return proj",
"def proj(A,B):\n return A - (A*B).sum()*B/(B**2).sum()",
"def project(self, vector):\n return vector.multiply(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute and prints errors between two images. | def print_errors(ref, img):
print('RMSE : %.5f' % rmse(ref, img))
print('rRMSE: %.5f' % rrmse(ref, img)) | [
"def error(x1, x2):\n return x2/x1 - 1",
"def error_images(self):\n return flatten_out(\n [f.error_images for f in self.algorithm_results])",
"def PostRegistration(image1, image2, model = False, **kwargs):\n silent = False\n if kwargs.get(silent) == True: silent = kwargs.get(silent)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Produce a symbol generator | def symbol_factory(packager,prefix):
i=1
while True:
yield packager(prefix+str(i))
i +=1 | [
"def gen_symbol(length):\r\n\r\n def c():\r\n return chr(random.randint(ord('A'), ord('Z')))\r\n\r\n s = ''\r\n for i in range(length):\r\n s += c()\r\n return s",
"def retr_symmetry_generators(struct,ini):\n #hall = struct.spacegroup_hall()\n ini[\"symgen\"] = struct.get_symmetry_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Convert a maxima MRAT expression to Sage SR Maxima has an optimised representation for multivariate rational expressions. The easiest way to translate those to SR is by first asking maxima to give the generic representation of the object. That is what RATDISREP does in maxima. | def mrat_to_sage(expr):
return max_to_sage(meval(EclObject([[ratdisrep],expr]))) | [
"def frame_rms ( frame , expression , cuts = '' ) : \n return frame_central_moment ( frame , order = 2 , expression = expression , cuts = cuts )",
"def _2MASS_query(ra_deg, dec_deg, rad_deg, maxmag=20,\n maxsources=-1):\n vquery = Vizier(columns=['+_r', '2MASS', 'RAJ2000', 'DEJ2000',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Translate a python object into a maxima object Mainly just a wrapper around EclObject, but needs to be in place because some objects might be translated better into maxima than just into lisp (think vectors and matrices). | def pyobject_to_max(obj):
return EclObject(obj) | [
"def computeFrameToObject(*args):\n return _almathinternal.computeFrameToObject(*args)",
"def convert(cls, obj: typ.Any, target_type: ScriptTypes):\n\n # TODO: Catch and report other parsing or conversion exceptions.\n\n source_type: ScriptTypes = cls.get_type_of(obj)\n\n if source_type is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Convert a maxima expression to sage symbolic ring | def max_to_sage(expr):
global op_sage_to_max, op_max_to_sage
global sym_sage_to_max, sym_max_to_sage
if expr.consp():
op_max=caar(expr)
if op_max in special_max_to_sage:
return special_max_to_sage[op_max](expr)
if not(op_max in op_max_to_sage):
op=sageop.next(... | [
"def mrat_to_sage(expr):\n return max_to_sage(meval(EclObject([[ratdisrep],expr])))",
"def frame_rms ( frame , expression , cuts = '' ) : \n return frame_central_moment ( frame , order = 2 , expression = expression , cuts = cuts )",
"def stanley_reisner_ring(self, base_ring=ZZ):\n R = self._stan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the velocity search space ranges (Vs from DWA paper) | def calculate_Vs(self):
return [self.robot.min_vel, self.robot.max_vel, self.robot.min_omega, self.robot.max_omega] | [
"def calculate_Vr(self, robot_state):\n ### Calculate Velocity spaces\n Vs = self.calculate_Vs()\n Vd = self.calculate_Vd(robot_state)\n\n ### Resulting search space range\n Vr_v_min = max(Vs[0], Vd[0]) # Resulting Minimum Linear velocity Vr_v_min\n Vr_v_max = min(Vs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the resulting velocity search space Implements EQN 16, INTERSECT(Vs, Vd). Note the admissable velocity Va is checked after iterating through the (v,omega) pairs of the search space (Vr_v, Vr_omega). | def calculate_Vr(self, robot_state):
### Calculate Velocity spaces
Vs = self.calculate_Vs()
Vd = self.calculate_Vd(robot_state)
### Resulting search space range
Vr_v_min = max(Vs[0], Vd[0]) # Resulting Minimum Linear velocity Vr_v_min
Vr_v_max = min(Vs[1], Vd[1]) ... | [
"def veq(self):\n return self._veq / self._velocity_factor",
"def get_Hv():\n \n vn = np.zeros((nx,ny+1)) \n vs = np.zeros((nx,ny+1))\n ve = np.zeros((nx,ny+1))\n vw = np.zeros((nx,ny+1))\n ue = np.zeros((nx,ny+1))\n uw = np.zeros((nx,ny+1))\n τyyn = np.zeros((nx,ny+1)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the dynamic window approach control inputs required for path planning. Returns the best control inputsm best trajectory and the resulting trajectory found from evaluating the velocity search space. | def calc_dwa_control(self, robot_state, robot_goal, obstacles):
# Best Metrics Initializer
minimum_cost = np.inf # Initialize minimum cost to extremely large initially
best_control_input = np.zeros(2)
best_trajectory = deepcopy(robot_state)
# Compute the resultin... | [
"def calculate_optimal_control(inputs):\n phi_init = 0\n numsteps, step_norm, ig_max, ig_min = inputs\n phi_osc_pos = phi_init\n phi_osc_neg = phi_init\n\n # define a function that integrates for step size\n def step_integrate(phi0, u_val, step):\n \"\"\" function that integrates one step f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the nearest obstacles w.r.t to the robot current state and obstacle position | def calculate_nearest_obstacles(self, state, obstacles):
robot_pos = state[0:2]
nearest_obstacles_ind = np.where(
np.linalg.norm(robot_pos - obstacles, axis=1) < self.obstacle_dist_tol)
nearest_obstacles = obstacles[nearest_obstacles_ind]
return nearest_obstacles | [
"def closest_obstacles(queen, obstacles):\n closest = [(0,0)]*8\n for obstacle in obstacles:\n t = obstacle_type(queen, obstacle)\n if t > -1 and closest[t] == (0,0):\n closest[t] = obstacle\n elif t > -1 and dist(queen,obstacle) < dist(queen,closest[t]):\n closest[t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the Obstacle Heuristic cost function (dist(v,omega) from DWA paper) | def calc_obs_dist_heuristic(self, trajectory, nearest_obstacles):
trajectory_positions = trajectory[:, 0:2]
obs_x = nearest_obstacles[:,0]
obs_y = nearest_obstacles[:,1]
dx = trajectory_positions[:, 0] - obs_x[:, None]
dy = trajectory_positions[:, 1] - obs_y[:, None]
euc... | [
"def heuristic_cost_estimate(self, node):\n # TODO: Return the heuristic cost estimate of a node\n \n d=self.distance(node,self.goal)\n \n return d",
"def heuristic(current, goal):\n\n return ((goal[0][0] - current[0])**2 + (goal[0][1] - current[1])**2) ** (0.5) # Your code here",
"def heurist... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that region of gcp util object could be specified via constructor. | def test_gcputil_init_region():
gcp_util = gcp.GoogleCloudUtil(region_name="europe-west1")
assert gcp_util._region_name == "europe-west1" | [
"def test_gcputil_init_region_config():\n test_region = \"europe-west3\"\n TEST_ENV_DATA = copy.deepcopy(config.ENV_DATA)\n TEST_ENV_DATA[\"region\"] = test_region\n with patch(\"ocs_ci.framework.config.ENV_DATA\", TEST_ENV_DATA):\n gcp_util = gcp.GoogleCloudUtil()\n assert gcp_util._regio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that region of gcp util object is loaded from via ocsci config when not specified. Moreover if the region is specified directly, the config value should not be used. | def test_gcputil_init_region_config():
test_region = "europe-west3"
TEST_ENV_DATA = copy.deepcopy(config.ENV_DATA)
TEST_ENV_DATA["region"] = test_region
with patch("ocs_ci.framework.config.ENV_DATA", TEST_ENV_DATA):
gcp_util = gcp.GoogleCloudUtil()
assert gcp_util._region_name == test_re... | [
"def test_gcputil_init_region():\n gcp_util = gcp.GoogleCloudUtil(region_name=\"europe-west1\")\n assert gcp_util._region_name == \"europe-west1\"",
"def parse_region():\r\n\r\n if ARGS.get('os_rax_auth'):\r\n region = ARGS.get('os_rax_auth')\r\n auth_url = 'identity.api.rackspacecloud.com/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Just some array that can accept one of Customer or Int32 | def someArray(self) -> Array[Customer, Int32]: | [
"def _validate(x):\n if not isinstance(x, int):\n raise TypeError(\"Only Integer Arrays are allowed\")",
"def validate_integers(*nums):\n for num in nums:\n if not isinstance(num, int):\n raise TypeError(\"Sorry. The function only works with integers.\")",
"def list_multip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An array that accepts anything | def anyArray(self) -> Array[...]: | [
"def array(self):\n raise NotImplementedError",
"def arrayify(value):\n return value if _is_array(value) else [value]",
"def IsArray(self) -> bool:",
"def inputArrayValue(*args, **kwargs):\n \n pass",
"def _arraytest(*args):\r\n\r\n rargs = []\r\n for a in args:\r\n if i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read pin values from board. Return a dict. | def read(self, board, sensors=None, timestamp=False):
keys = []
values = []
for sensor in sensors:
keys.append(sensor)
values.append(board.read(sensor))
return dict(zip(keys, values)) | [
"def getAllBoardCoord(driver):\n board_list = ['hi', 'mid', 'lo']\n board_dict = {}\n for b in board_list: \n tmp = getTemplate(b)\n game_image = getGameImage(driver, 'layer2')\n board_coord = detectTemplate(game_image, tmp, False, -1)\n board_dict[b] = board_coord\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Common setup for Vera devices. | def setup(hass, base_config):
global VERA_CONTROLLER
import pyvera as veraApi
config = base_config.get(DOMAIN)
base_url = config.get('vera_controller_url')
if not base_url:
_LOGGER.error(
"The required parameter 'vera_controller_url'"
" was not found in config"
... | [
"def SetupCommon(self):\n self.network_name = self._GetResourceName()\n self.subnetwork_name = self._GetResourceName()\n\n self.Run('compute networks create {} --subnet-mode=custom'.format(\n self.network_name))\n self.Run('compute networks subnets create {0} --network {1} '\n '--regi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shutdown Vera subscriptions and subscription thread on exit. | def stop_subscription(event):
_LOGGER.info("Shutting down subscriptions.")
VERA_CONTROLLER.stop() | [
"async def cleanup(self) -> None:\n for pf in self._scheduled_functions.values():\n pf.stop()\n for t in self._in_stream.values():\n t.cancel()\n if self._cb_app_heartbeat:\n self._cb_app_heartbeat.stop()\n if self.name and self._red is not None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IFieldWidget factory for SelectWidget. | def CollectionChoiceSelectFieldWidget(field, value_type, request):
return SelectFieldWidget(field, None, request) | [
"def _createWidget(context, field, viewType, request):\n field = field.bind(context)\n return component.getMultiAdapter((field, request), viewType)",
"def new_default_widget(self):\n if self.choices is not None:\n widget = QtWidgets.QComboBox()\n elif self.dtype in [int, float]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test parsing and streaming session response KNX/IP packet. | def test_session_response(self):
public_key = bytes.fromhex(
"bd f0 99 90 99 23 14 3e" # Diffie-Hellman Server Public Value Y
"f0 a5 de 0b 3b e3 68 7b"
"c5 bd 3c f5 f9 e6 f9 01"
"69 9c d8 70 ec 1f f8 24"
)
message_authentication_code = bytes.fromh... | [
"def test_connect_response(self):\n raw = (\n 0x06,\n 0x10,\n 0x02,\n 0x06,\n 0x00,\n 0x14,\n 0x01,\n 0x00,\n 0x08,\n 0x01,\n 0xC0,\n 0xA8,\n 0x2A,\n 0x0A,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets a random node from nodes list if fixed is set then the node at the nodes[fixed] will be returned, this may be useful in stress tests | def random_node(self):
rnd = random.randint(0, len(self.clients_lst)-1) if not self.fixed_node else self.fixed_node
pod_ip, pod_name = self.clients_lst[rnd]['pod_ip'], self.clients_lst[rnd]['name']
if not self.fixed_node:
print("randomly ", end="")
print(f"selected pod: ip ... | [
"def getRandomNode(self, node_type=0):\n\n lists = (self.nodes_list, self.nodes_leaf, self.nodes_branch)\n cho = lists[node_type]\n if len(cho) <= 0:\n return None\n\n return prng.choice(cho)",
"def pickNode(self,xrand):\n #setup nearest neighbor filters\n filters = [lamb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs commands on remote linux instances | def execute_commands_on_linux_instances(client, commands, instance_ids):
resp = client.send_command(
DocumentName="AWS-RunShellScript", # One of AWS' preconfigured documents
Parameters={'commands': commands},
InstanceIds=instance_ids,
)
return resp | [
"def execute_commands_on_linux_instances(config: dict, commands: List[str], instance_ips: List[str]):\n for instance_ip in instance_ips:\n client = paramiko.SSHClient()\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n try:\n logging.info(f\"Connecting to {instance_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the event enters category X, given the tuple computed by eventCategory. | def isInCategory(category, categoryData):
if category == 0:
return categoryData[0]
if category == 1:
return categoryData[1]
if category == 2:
return categoryData[0] or categoryData[1]
else:
return False | [
"def event_in(event, widget):\n x, y = event.x_root, event.y_root\n x1, y1, x2, y2 = (\n widget.winfo_rootx(),\n widget.winfo_rooty(),\n widget.winfo_rootx() + widget.winfo_width(),\n widget.winfo_rooty() + widget.winfo_height(),\n )\n return x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adjust an item to store it the way we want to based on the format and other restrictions. | def adjustItemForStorage(item, format=None, ingestSource=None, service=None,
region=None):
if (item['url'].startswith('http://instagram.com/p/') or
item['url'].startswith('https://instagram.com/p/')):
item['url'] = (
'i/' + item['url'].split('://instagram.com... | [
"def format_item(item):\n\n for key, value in item.items():\n if not value:\n continue\n if key in [\n 'cislo_lv', 'cislo_ku', 'cislo_obce', 'cislo_casti_obce',\n 'vymera', 'cislo_stavebniho_objektu', 'ext_id_parcely',\n 'pocet_bytu', 'zastavena_plocha', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an instagram JSON object to our item format. | def convertInstagramJSONToItem(inst, partial):
if (not inst.get('location', None) or
'latitude' not in inst['location'] or
'longitude' not in inst['location']):
return None
item = {
'user_name': inst['user']['username'],
'user_fullname': inst['user']['full_nam... | [
"def convertTwitterJSONToItem(tw, decoder, line, partial):\n if 'created_at' not in tw or tw.get('coordinates', None) is None:\n return None\n if tw['created_at'] in DateLookup:\n date = DateLookup[tw['created_at']]\n else:\n try:\n date = int(calendar.timegm(time.strptime(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a twitter JSON object to our item format. | def convertTwitterJSONToItem(tw, decoder, line, partial):
if 'created_at' not in tw or tw.get('coordinates', None) is None:
return None
if tw['created_at'] in DateLookup:
date = DateLookup[tw['created_at']]
else:
try:
date = int(calendar.timegm(time.strptime(
... | [
"def convertInstagramJSONToItem(inst, partial):\n if (not inst.get('location', None) or\n 'latitude' not in inst['location'] or\n 'longitude' not in inst['location']):\n return None\n item = {\n 'user_name': inst['user']['username'],\n 'user_fullname': inst['user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the list of files, either determining the latest entry we have for each instagram message or storing the latest entries for final conversion. | def processFiles(files, items, fileData, format='instagram'):
processed = 0
itemsStored = 0
files_processed = 0
keylist = (KeyList if format == 'instagram' else
(JSONKeyList if format == 'json' else MessageKeyList))
for filerecord in files:
region = filerecord.get('region', No... | [
"def process_files(self):\n while self.search_set:\n current_file = self.add_file(self.search_set.pop())\n self.save_file(current_file)",
"def process_files(self):\n while self.running:\n current_time = time.time()\n # sort by created time descending\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If we are tracking mentions and likes, parse likes and comments and add those users to the user mention dictionaries. | def trackLikes(mentions, item, likes=False):
if (mentions is None or not likes or (not item.get('likes', None) and
not item.get('comments', None))):
return
users = []
likes = item.get('likes', None)
if likes:
users.extend([like.split(';', 1)[0] f... | [
"def trackMentions(mentions, item, service):\n if (mentions is None or not item.get('caption', None) or\n '@' not in item['caption']):\n return\n if service == 'i':\n users = InstagramMentionPattern.findall(item['caption'])\n else:\n users = TwitterMentionPattern.findall(ite... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If we are tracking mentions, parse a message string for mentions and build user mention dictionaries. | def trackMentions(mentions, item, service):
if (mentions is None or not item.get('caption', None) or
'@' not in item['caption']):
return
if service == 'i':
users = InstagramMentionPattern.findall(item['caption'])
else:
users = TwitterMentionPattern.findall(item['caption']... | [
"def test_tweet_user_mentions(self):\n user_mention = {\n 'id_str': '123',\n 'screen_name': 'fakeuser',\n 'name': 'Fake User',\n }\n msg = {\n 'entities': {'user_mentions': [user_mention]},\n 'id_str': '12345',\n 'text': 'This is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read yspec.in from the directory | def read_yspec_in(path1):
yspec_in_fio = open(os.path.join(path1, 'yspec.in'))
yspec_in_fi = yspec_in_fio.readlines()
yspec_in_fi = yspec_in_fi[86:]
for i in range(len(yspec_in_fi)):
yspec_in_fi[i] = yspec_in_fi[i].split()
for i in range(len(yspec_in_fi)):
for j in range(len(yspec_in... | [
"def read_specs(folder):\n specfiles = [f for f in listdir(folder) if isfile(join(folder, f))]\n specs = []\n for file in specfiles:\n if file.startswith(\".\"):\n continue\n print(f\"Parsing spec file: {file}\")\n # Only use the first part of the filename as spec name\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cut time window around theoretical arrival time It is meant to be run in parallel | def cut_time_window(i, all_files_i, req_phase, forward_code, path1):
tr = read(os.path.join(all_files_i))[0]
(phase_flag, O, A, B, E, GCARC, tr_sliced) = epi_dist(tr, req_phase=req_phase, tb=20, ta=100,
forward_code=forward_code)
if phase_flag == 'Y'... | [
"def cutting_time_prediction(self, job):\r\n # print('job :', job)\r\n cutting_time = 10\r\n return cutting_time",
"def syncronize_movie(movie,times,t_window=1e-3,N_interval=3,t_start=1e-4,bgsub=0): \n \n frames = movie[:]\n times = movie.timestamps\n \n frames_sub = np.zeros(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Schema resulting from merging the subschemas. NOT equivalent to the schema defined for the item type itself (use the TypeInfo contained in registry[TYPES].by_abstract_type[item_type] for that) | def schema(self):
subschemas = (self.types[name].schema for name in self.subtypes)
return reduce(combine_schemas, subschemas) | [
"def merge_schemas(subschema, types):\n if not subschema:\n return None\n # handle arrays by simply jumping into them\n # we don't care that they're flattened during mapping\n ref_types = None\n subschema = subschema.get('items', subschema)\n if 'linkFrom' in subschema:\n _ref_type, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if item is in array and returns its index, if not found returns 1 | def index_of(array, item):
try:
return array.index(item)
except ValueError:
return -1 | [
"def find_index(array, value):\n for index, val in enumerate(array):\n if val == value:\n return index\n return -1",
"def linear_search(arr, value):\r\n\r\n for i in range(len(arr)): # O(n)\r\n if arr[i] == value:\r\n return i\r\n return -1",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fix given path according to os path sep | def fix_path(path):
not_sep = "/" if os.path.sep == "\\" else "\\"
return path.replace(not_sep, os.path.sep) | [
"def convert_directory_separator(path):\n if os.path.sep != '/':\n path = path.replace(os.path.sep, '/')\n\n return '/' + path",
"def fix_path(path):\n correct_path = '/' + path if not path.startswith('/') else path\n correct_path = correct_path + '/' if not correct_path.endswith('/') else corr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Single target Djikstra's will terminate once a path is found from the source s to target t It is the same worstcase complexity but can be faster than normal Djikstra's | def single_target_dijkstra(adjacency_list, weights, s, t):
unfinished = {}
for u in adjacency_list:
unfinished[u] = float('inf')
unfinished[s] = 0
predecessors = {s: None}
path_costs = {}
while unfinished:
u = min(unfinished, key=unfinished.get)
path_costs[u] = unfinished[u]
del unfinished[u... | [
"def shortest_path(source, target):\n ##for testing\n # source=person_id_for_name(\"Lupita Nyong'o\")\n # target=person_id_for_name(\"Joan Cusack\")\n ## \n explored=[]\n frontier=QueueFrontier()\n init_state=Node(state=source,parent=None,action=None)\n frontier.add(init_state)\n success=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that a plot update is requested (scheduled for the next cycle of the timer) and that the timer is active, which means the updates are going to happen. Once that is assured, do the updates immediately instead of waiting one cycle (that would slow down the test) | def check_update_is_requested_and_apply(self):
# check
self.assertTrue(self.plot.update_required)
self.assertTrue(self.plot.plot_updater.active)
# update
self.plot._check_scheduled_updates() | [
"def update_plotting_chart(self, extraInfo = None):\n \n self.plot_lock.acquire()\n desired_value = self.Monitor.desired_value # The desired value of the sensor\n range_warning = self.Monitor.range_warning # The range which if crosses we send email\n range_stop = self.Monitor.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test register intent files using register_intent. | def test_register_intent_intent_file(self):
self._test_intent_file(SimpleSkill6()) | [
"async def test_send_intent(self):\n with patchers.patch_connect(True)[self.PATCH_KEY], patchers.patch_shell('output\\r\\nretcode')[self.PATCH_KEY]:\n result = await self.ftv._send_intent(\"TEST\", constants.INTENT_LAUNCH)\n self.assertEqual(getattr(self.ftv._adb, self.ADB_ATTR).shell_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that the a translatable list can be loaded from dialog and locale. | def test_translate_locations(self):
# Check that translatables can be loaded from the dialog directory
s = SimpleSkill1()
s.root_dir = abspath(join(dirname(__file__),
'translate', 'in-dialog/'))
lst = s.translate_list('good_things')
self.assertTr... | [
"def test_language_chooser_available_language_with_translated_page(self):\n content = {\"en\": \"Language menu test\", \"fr\": \"Test du menu de langues\"}\n page = create_i18n_page(\n content, published=True, template=\"richie/single_column.html\"\n )\n url = page.get_absolut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Planification du parcours point par point en mode "avion". En fait le drone se tourne toujours vers son point cible avant d'avancer vers celui ci. | def goToPoint(self,point, pas):
point1 = [self.positionX[-1], self.positionY[-1], self.positionZ[-1]] #position actuelle du drone
if distanceXY(point, point1) >= pas and denivellation(point,point1)**2 >= pas:
print("going to point")
theta = math.atan2(point[1],point[0]) #angle du... | [
"def velocidad_promedio(self): \n u_x = 0\n u_y = 0\n u_z = 0\n for i in range(self.N):\n u_x += self.particulas[i].v[0]\n u_y += self.particulas[i].v[1]\n u_z += self.particulas[i].v[2]\n self.p_vx = u_x /self.N\n self.p_vy = u_y /self.N\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |