query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Testing init method for TechCrunchScraper. Testing that the filename for the csv file and the header were created properly. | def test_init(self):
header = ['company name', 'company website']
test_csv = 'test.csv'
tcs = TechCrunchScraper(test_csv, header)
self.assertEqual(tcs.out_filename, test_csv)
self.assertEqual(tcs.csv_header, header) | [
"def setUp(self):\n self.convert = Convert()\n self.create_csv_test_file(self.TESTS_DATA)",
"def setUp(self):\n call_command('importcategories', self.channel, self.csv_file)",
"def test_get_soup(self):\n url = 'http://techcrunch.com/'\n header = ['company name', 'company websi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing get soup method. Testing that the soup returned is not None. | def test_get_soup(self):
url = 'http://techcrunch.com/'
header = ['company name', 'company website']
test_csv = 'test.csv'
tcs = TechCrunchScraper(test_csv, header)
soup = tcs.get_soup(url)
self.assertIsNotNone(soup) | [
"def test_beautiful_soup_can_parse_html_from_returned_content(self):\n soup = self.soupify(self.response)\n self.assertIsNotNone(soup)",
"def test_good_page_url():\n page_html = site_parser._get_page_html(\n \"https://www.smashingmagazine.com/category/wallpapers/\",\n )\n assert type... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the get article links method. Testing that the number of links returned is greater than 0. | def test_get_article_links(self):
url = 'http://techcrunch.com/'
header = ['company name', 'company website']
test_csv = 'test.csv'
tcs = TechCrunchScraper(test_csv, header)
soup = tcs.get_soup(url)
links = tcs.get_article_links(soup)
self.assertGreater(len(links... | [
"def tags_links_testing(self):\n totalLinks = 0\n externalLinks = 0\n\n m = []\n\n meta = self.soup.find_all(\"meta\")\n links = self.soup.find_all(\"link\")\n scripts = self.soup.find_all(\"script\")\n\n for tag in meta:\n for link in re.findall(re.compil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the scrape article method. Testing specifically that the header data is valid in the data returned. | def test_scrape_article(self):
url = 'http://techcrunch.com/'
header = ['company name', 'company website']
test_csv = 'test.csv'
tcs = TechCrunchScraper(test_csv, header)
soup = tcs.get_soup(url)
links = tcs.get_article_links(soup)
link_soup = tcs.get_soup(links[0... | [
"def test_get_header_data(session):\n # setup\n title = 'Test Title'\n # test\n data = report_utils.get_header_data(title)\n # verify\n assert data\n assert data.find(title) != -1",
"def test_get_article_links(self):\n url = 'http://techcrunch.com/'\n header = ['company name', '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the component at zi, return the component and the remaining length find the component after zi, if zi is at the end of the line, return the last component | def find_component(self, zi) -> (Components, float):
g = None
for g in self.components:
zi = round(zi - g.length, LENGTH_PRECISION)
if zi < 0:
break
return g, -zi | [
"def lastposary(self, chtr, istart):\n if istart < 1:\n return 0 # -1 #ejf\n if istart > self.linmax:\n return 0 # -1 #ejf\n\n I = istart\n while 1 <= I:\n if self.Linary[I] == chtr:\n return I\n I -= 1\n return 0",
"def getEndPosition(self, i: int) -> int:\n ...",
"def _get_closing_index... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate transfer matrix ( ) from z0 (default 0) to z1 | def generate_matrix(self, z1: float, z0: float = 0) -> UdfTransMatrix:
assert 0 <= z0 <= z1 <= self.length, "0 <= z0 < z1 <= line length"
new_length = z1 - z0
comp_iter = iter(self.components)
while True:
component = next(comp_iter)
z0 = round(z0 - component... | [
"def Z_1(z):\n return -2*(1+z*Z(z))",
"def flows_Pack2Z(pack,z1,zones):\n nlay = zones.shape[0]\n nrow = zones.shape[1]\n ncol = zones.shape[2]\n zones = zones.reshape(nlay*nrow*ncol)\n flow_pos=0\n flow_neg=0\n \n if z1 in np.unique(zones[pack.node-1]):\n for q1 in pack:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adjust the parameter of component and return a new Line adjust length of Drift or length of Dipole or k1 of Quadrupole relatively (1e6) | def adjust(self, component, precision):
adjust_relatively = 1 + precision
temp_list = []
for comp in self.components:
if component is comp:
new_comp = comp.rela_adjust(adjust_relatively)
else:
new_comp = copy.deepcopy(comp)
... | [
"def calculate_change_mesh(self):",
"def get_sweep_line_properties(self):\n # if self.pt3 is not None:\n # try:\n # self.d = find_circle(\n # x1=0,\n # y1=0,\n # x2=self.pt2.x,\n # y2=self.pt2.z,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return sub_matrix of x or y direction | def sub_matrix(self, direction):
if direction == 'x':
return np.array([[self.matrix[0, 0], self.matrix[0, 1]],
[self.matrix[1, 0], self.matrix[1, 1]]])
elif direction == 'y':
return np.array([[self.matrix[2, 2], self.matrix[2, 3]],
... | [
"def sub2ind(matrixSize, rowSub, colSub):\n m, n = matrixSize\n # return rowSub * (n-1) + colSub - 1 ### 09122020: this is wrong?\n return rowSub * n + colSub",
"def test_get_submatrix(self):\n\n # First up a 3x3 example\n M = matrices.Matrix(3, 3)\n M.set_row(0, [1, 5, 0])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set virtual rf cavity, length and location will not be considered | def set_virtual_rf_cavity(self, voltage, harmonic_number):
self.rf_cavity = VirtualRFCavity(voltage, harmonic_number)
self.rf_cavity.omega_rf = harmonic_number * 2 * pi / self.Tperiod
phase = np.arcsin(self.U0 / self.rf_cavity.voltage) # this result is in [0, pi / 2]
if self.etap < ... | [
"def __init__(self, virtuality_flags):\r\n FilterBase.__init__(self)\r\n self.virtuality_flags = virtuality_flags",
"def setCRFparams(self, crfParams):\n #weight vector for node features\n self.unaryWeights = crfParams['unaryWeights']\n \n #weight vector for edg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate list of elements along the ring Watch Out! Theoretically, the code doesn't consider the situation that the beginning or ending component is DIPOLE, but usually this won't happen, the beginning and ending should be drift | def ring_element(self):
elements = []
ele = Element()
ele.z_axis = 0
magnet, drop_data = self.line.find_component(0)
ele.symbol = magnet.symbol
ele.theta_e = 0
[beta_x, alpha_x, gamma_x] = self.initial_twiss('x')
[beta_y, alpha_y, gamma_y] = self.i... | [
"def rings(self):\n if self._rings is None:\n if self.status == \"in\" or self.status == \"out\":\n self._rings = []\n else:\n self._rings = []\n extract_result = extract_segments_from_cell_with_arcs([self.min_x, self.min_y], self.length_x, s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
relatively smooth tuning of the lattice within a small range gathers quadrupoles in two groups depending on the sign of the kvalue, and establishes a sensitivity matrix for a relative change of strength (dk/k = 1e6). | def tune_adjust(self, tune_x, tune_y):
def tune_sensitivity_matrix():
rela_matrix = np.zeros([2, 2])
test_k = 1e-6
temp_comps = []
for comp in self.line.components:
if 320 <= comp.symbol < 330:
temp_comp = Quadrupole(co... | [
"def switchToSelectiveSearchQuality(self, base_k=..., inc_k=..., sigma=...) -> None:\n ...",
"def test_raise_error_if_k_gt_N():\n N = 4\n param_file = \"SALib/tests/test_params.txt\"\n problem = read_param_file(param_file)\n num_levels = 4\n grid_jump = num_levels / 2\n k_choices = 6\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
according to the component_name_list generate the list of component objects | def __get_component(self, components_name_list):
components_list = []
for comp in self.line.components:
if comp.name in components_name_list:
components_list.append(comp)
return components_list | [
"def component_list(self) -> List[str]:\n match = re.findall(\"name='([-A-Za-z0-9_ ]+)'\", self['components'])\n # Check for unicode as well\n matchu = re.findall(\"name=u'([-A-Za-z0-9_ ]+)'\", self['components'])\n\n return match + matchu",
"def get_component_packages_list(self) -> Li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
to set marks along the ring, and data at mark will be output | def set_marks(self, s):
if s != 0:
print('\n目前只支持记录入口处数据,标记将被改到0.0处')
print('\nset marks at s=0.0 successfully!')
self.marks = [0.0] | [
"def setMarkFromList(self,list):\n self.mark = \"/\".join(list)",
"def set_mark(self, i, symbol):\n self.marks[i] = symbol\n if symbol == 'N':\n if i not in self.nuclei:\n self.nuclei.append(i)\n self.nuclei.sort()",
"def mark(self, x,y,z):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
plot phase space and do fft analysis | def fft_phase(self):
x = []
px = []
y = []
py = []
for particle in self.record:
x.append(particle[0])
px.append(particle[1])
y.append(particle[2])
py.append(particle[3])
fft_tune = fftpack.fft(y)
k1 = [i *... | [
"def plotFFT(func,t_range=(0,2*pi),points=128,tol=1e-5,\n func_name=None,unwrap_=True,wlim=(-10,10),scatter_size=40,\n iff=False, plot=True, window=False):\n \n # default name for function\n if func_name == None:\n func_name = func.__name__\n \n # time points to sample\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> verify_age(34) Get ready to play! | def verify_age(user_age):
# doctest used to test if it works
# If the users age is less than 18, it will stop running
if user_age < 18:
print("You are underage, please come back when you are 18 or above.\n")
exit()
# A message will pop up if the user is older than 18
else:
print... | [
"def age_check():\n\n return render_template(\"ageverify.html\")",
"def check150(birth, death):\n try:\n if birth is None:\n return False\n birth = parser.parse(birth)\n\n if death is None:\n death = parser.parse(time.strftime(\"%d %b %Y\"))\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reduces the number of articles to the threshold provided. Therefore the number of events will also be reduced. | def max_articles(n_articles):
global articles, features, events, n_arms, n_events
assert n_articles < n_arms
n_arms = n_articles
articles = articles[:n_articles]
features = features[:n_articles]
for i in reversed(range(len(events))):
displayed_pool_idx = events[i][0] # index relative... | [
"def prune(self, threshold=1e-3):\n\n pass",
"def truncate(self, limit=10):\r\n scores = self.get_scores()\r\n too_much = scores[limit:]\r\n self._scores = scores[:limit]\r\n return too_much",
"def number_of_articles():",
"def InitialThreshold(self) -> int:",
"def threshol... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator that will convert a boolean pandas object into an integer, bitmasked object when `_return_mask=True`. This decorator adds the `_return_mask` kwarg to the decorated function. Using this decorator to mask values ensures the description and decorated function are clearly linked. | def mask_flags(flag_description, invert=True):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
return_mask = kwargs.pop('_return_mask', False)
flags = f(*args, **kwargs)
if return_mask:
if isinstance(flags, tuple):
ret... | [
"def replaceBoolWithInt(df):\n return df.apply(colBoolToInt, axis=0)",
"def getMaskFunction(self):\n return self.mask",
"def boolean_decorator(boolean_operator: str):\n\n def boolean_function(function: FunctionType):\n def wrapper(self, expressions: list):\n plan = self.create_exe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True (or a boolean series) if flags has been validated | def has_data_been_validated(flags):
return flags > 1 | [
"def check_flags(cls, flags):\n return cls.FLAGS | cls.FLAGS_MASK == flags | cls.FLAGS_MASK",
"def valid_flag_bit(self, bitpos):\n return True",
"def enablable(flag):\n return not any(\n c.required for c in flag.conditions if c.condition == \"boolean\"\n ) and not bool_enabled(flag)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the version from flag | def get_version(flag):
# will be more complicated if another version identifier must be added
return np.right_shift(flag & VERSION_MASK, 1) | [
"def _parse_version_input(self, release_number):\n parts = release_number.split('.')\n if len(parts) < 3:\n logging.error('FLAGS.version_number must be x.x.x or x.x.x.y')\n elif len(parts) == 3:\n return parts[0], parts[1], parts[2], ''\n else:\n return parts[0], parts[1], parts[2], parts... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies input DataFrame and then adds new masks derived from input masks | def _add_derived_masks(masks):
unvalidated = masks['NOT VALIDATED']
if unvalidated.all():
return masks
out = masks.copy()[~unvalidated]
for flag, operations in DERIVED_MASKS.items():
func = operations[0]
cols = operations[1:]
args = [out[col] for col in cols]
out[... | [
"def mask_dataset(self, ref_df, gpi_info):\n\n matched_masking = self.temporal_match_masking_data(ref_df, gpi_info)\n # this will only be one element since n is the same as the\n # number of masking datasets\n result_names = get_result_names(self.masking_dm.ds_dict,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert `flag_series` into a boolean DataFrame indicating which checks the flags represent. | def convert_mask_into_dataframe(flag_series):
vers = get_version(flag_series)
fundamental_masks = flag_series.groupby(vers, sort=False).apply(
_convert_version_mask).fillna(False)
out = _add_derived_masks(fundamental_masks)
return out | [
"def get_flags_as_df(self):\n flags = [s.flag for s in self]\n data = [\n (this, [flag & this for flag in flags]) for this in (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048)\n ]\n df = pd.DataFrame(dict(data))\n\n # special case of flag 0 has to be handled separe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if `flag_series` has been flagged for the checks given by flag_description | def check_if_series_flagged(flag_series, flag_description):
if not has_data_been_validated(flag_series).all():
raise ValueError('Data has not been validated')
_flag_description_checks(flag_description)
return flag_series.apply(check_if_single_value_flagged,
flag_descript... | [
"def _flag(self, series, meta=dict()):\n meta = self._parse_meta(series, meta)\n self.flags[series['series_id']] = meta",
"def isFlagSet(*args, **kwargs):\n \n pass",
"def check_flags(self, ds):\n ret_val = []\n\n for k, v in ds.dataset.variables.iteritems():\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
u"""makes random pairs from num elements. | def make_pairs(num):
arr= range(num)
pairs=[]
while len(arr) >= 2:
i= int(random()*len(arr))
ival= arr.pop(i)
j= int(random()*len(arr))
jval= arr.pop(j)
pairs.append((ival,jval))
return pairs | [
"def random_pair(n):\n return tuple(random.choice(list(range(n)), 2, replace=False))",
"def num_pairs(num_elements):\n return (num_elements * (num_elements - 1)) // 2",
"def _gen_pair(min_digits, max_digits):\n n_digits = randrange(min_digits, max_digits + 1)\n a = randrange(10 ** (n_digits - 1), 10... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
u""" calculates the value of given function. | def calc_func_value(self,num,q):
vars= np.zeros(len(self.genes))
for i in range(len(self.genes)):
vars[i]= self.genes[i].get_var()
#.....change args[0] which is the name of the directory
#.....wehre the function is evaluated.
val= self.func(vars,
... | [
"def calculate_setFUNC(self,val):\n self.open.write('CALCULATE:FUNCTION ' + str(val))\n self.open.write('CALCULATE:FUNCTION?')\n reply = self.open.read()\n return('Function selected: ' + str(reply))",
"def compute_value(self, functions=None):\n return compute_function(self.funct... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
u"""Constructor of GA class. func function to be evaluated with arguments vars and args. fitfunc function for fitness evaluation with using function value obtained above. | def __init__(self,nindv,nbitlen,murate,func,vars,vranges,fitfunc,args=()):
self.nindv= nindv
self.ngene= len(vars)
self.nbitlen= nbitlen
self.murate= murate
self.func= func
self.vars= vars
self.vranges= vranges
self.fitfunc= fitfunc
self.args= args... | [
"def __init__(self, fitness_function, solution_size, lower_bounds, upper_bounds, \n population_size=20, max_iterations=100, \n G_initial=1.0, G_reduction_rate=0.5,\n **kwargs):\n optimize.Optimizer.__init__(self, fitness_function, population_size, \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
u"""creates nindv individuals around the initial guess. | def create_population(self):
global maxid
self.population= []
#.....0th individual is the initial guess if there is
ind= Individual(0,self.ngene,self.murate,self.func,self.args)
genes=[]
for ig in range(self.ngene):
g= Gene(self.nbitlen,self.vars[ig]
... | [
"def init_vertex_ids(self):\n for i, ndd in enumerate(self.altruists):\n ndd.index = i\n for i, v in enumerate(self.graph.vs):\n v.index = i + len(self.altruists)",
"def build_xn_vn_array(xn):\n\n num_policies = len(xn)\n num_itr = len(xn[0])\n num_factors = len(xn[0][... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
u"""selects nindv individuals according to their fitnesses by means of roulette. | def roulette_selection(self):
#.....calc all the probabilities
prob= []
for ind in self.population:
prob.append(self.fitfunc(ind.value))
istore=[]
for i in range(len(self.population)):
istore.append(0)
for i in range(self.nindv):
ptot... | [
"def __roulette_wheel_ind_selection(roulette_wheel: Dict[Individual, Union[float, int]], sum_of_fitness) -> Individual:\n chosen_point = randrange(0, maxsize * 2 + 1) % sum_of_fitness\n for ind in roulette_wheel:\n if roulette_wheel.get(ind) < chosen_point:\n chosen_point -= ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the HeikinAshi candlesticks from OHLC data set. | def ha_candlesticks(ohlc):
if "open" not in ohlc or not hasattr(ohlc["open"], "__iter__"):
raise Exception("Expect 'open' array")
elif "high" not in ohlc or not hasattr(ohlc["high"], "__iter__"):
raise Exception("Expect 'high' array")
elif "low" not in ohlc or not hasattr(ohlc["low"], "__it... | [
"def get_candlesticks_intervals(self):\n\n pass",
"def HA(df, ohlc=['Open', 'High', 'Low', 'Close']):\n\n ha_open = 'HA_' + ohlc[0]\n ha_high = 'HA_' + ohlc[1]\n ha_low = 'HA_' + ohlc[2]\n ha_close = 'HA_' + ohlc[3]\n \n df[ha_close] = (df[ohlc[0]] + df[ohlc[1]] + df[ohlc[2]] + df[ohlc[3]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add application commandline arguments | def addArgs(self):
self.createArgument('--fork', self.fork, 1, 'Fork to background', action='store_true')
self.createArgument('--run', self.run, 1, 'Execute run on remote server (to be used with --client argument)', action='store_true')
self.createArgument('--stop', self.stop, 1, 'Stop prev... | [
"def add_argument_cmd(self, *args, **kwargs):\n pass",
"def add_cli_arguments(self, parser):\n super(Application, self).add_cli_arguments(parser)\n\n add_kafka_manager_api_cli_arguments(parser)",
"def main():\n # set up the program to take in arguments from the command line",
"def add_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test execute freshness indicator. | def test_execute_freshness(self):
test_case_name = test_utils.get_test_case_name(self.test_case_list)
self.test_case_list.append({'class': 'ModelIndicator', 'test_case': test_case_name})
self.test_case_list.append({'class': 'ModelDataSource', 'test_case': test_case_name})
self.test_case_... | [
"def test_restart_run(self):\n pass",
"def test_notify_run_status(self):\n pass",
"def test_create_run_status(self):\n pass",
"def test_prepare_vac(self):\n self.circuit.prepare_vacuum_state(0)\n self.assertAllTrue(self.circuit.is_vacuum(self.tol))",
"def test_restore_run(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test execute latency indicator. | def test_execute_latency(self):
test_case_name = test_utils.get_test_case_name(self.test_case_list)
self.test_case_list.append({'class': 'ModelIndicator', 'test_case': test_case_name})
self.test_case_list.append({'class': 'ModelDataSource', 'test_case': test_case_name})
self.test_case_li... | [
"async def test_latency(self) -> None:\n # Initially less than 0\n latency = self.client.latency\n self.assertLess(latency, 0)\n # After a call, it should be greater than 0\n await self.client.get(Character)\n latency = self.client.latency\n self.assertGreater(latenc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test execute validity indicator. | def test_execute_validity(self):
test_case_name = test_utils.get_test_case_name(self.test_case_list)
self.test_case_list.append({'class': 'ModelIndicator', 'test_case': test_case_name})
self.test_case_list.append({'class': 'ModelDataSource', 'test_case': test_case_name})
self.test_case_l... | [
"def perform_checks(self) -> None:",
"def testExecute(self):\n l = TestLayer(\"test2\")\n self.assertFalse(l.executeSet)\n l.execute(1)\n self.assertTrue(l.executeSet)",
"def _verify_vector_execution(self):\r\n \r\n # If self._result is set. False is probably a good ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a copy of user_config with local_paths set. | def _configure_local_paths(local_paths):
answer = copy(local_paths)
# Ask the user for a repository root.
while not answer.get('reporoot'):
logger.info('First, we need to know where you store most code on your '
'local machine.')
logger.info('Other paths (example: toolki... | [
"def _load_user_config(self):\n config = RawConfigParser()\n config.add_section('copr-user')\n config.set('copr-user', 'ssh_key', '~/.ssh/id_rsa')\n\n copr_conf = os.path.expanduser(\"~/.config/copr\")\n if os.path.exists(copr_conf):\n config.read(copr_conf)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a function that compares two `Id` objects with the passed relational operator. Discards the function being decorated. | def _Id_make_comparison_function(op):
def decorate(fn):
def cmp_fn(self, other):
try:
return op((str(self._prefix), self._seqno),
(str(other._prefix), other._seqno))
except AttributeError:
# fall back to safe comparison as `st... | [
"def __gt__(self, other):\n if self.function == other.function:\n return self.id_node > other.id_node\n else:\n return self.function > other.function",
"def _apply_operator(self, other, op):\n symbols = {operator.add: \"+\", operator.sub: \"-\", operator.mul: \"*\", oper... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preallocate `n` IDs. Successive invocations of the `Id` constructor will return one of the preallocated, with a potential speed gain if many `Id` objects are constructed in a loop. | def reserve(self, n):
assert n > 0, "Argument `n` must be a positive integer"
IdFactory._seqno_pool.extend(self._next_id_fn(n)) | [
"def __init__(self,n:int) -> None:\r\n self.vertices = [None]*n\r\n for i in range(n):\r\n self.vertices[i] = Vertex(i)",
"def build_ids(size, id_start=0, prefix=\"id_\", max_length=10):\n return [prefix + str(x).zfill(max_length)\n for x in np.arange(id_start, id_start + si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a preexisting game from 'game.txt' to be played Returns | def loadGame():
d = {
'player1' : None,
'player2' : None,
'who' : None,
'board' : None
}
with open("game.txt", mode="rt", encoding="utf8") as f:
f = f.read().splitlines()
d['player1'] = f.pop(0)
d['player2'] = f.pop(0)
... | [
"def loadGame():\r\n with open(\"game.txt\",mode=\"rt\",encoding=\"utf8\") as gamesave:\r\n #checking if the game.txt contains 9 lines \r\n if sum(1 for _ in gamesave) != 9:\r\n raise ValueError(\"Cannot load a valid game.\")\r\n with open(\"game.txt\",mode=\"rt\",encoding=\"ut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds a line in the chosen direction and returns the positions of the opponents counters if there | def getLine(board, who, pos, dir):
result = []
p = pos
q = (p[0]+dir[0], p[1]+dir[1]) #q is the next space in direction of dir
if who == 1: #Condenses the code as no need to write out the same thing twice
a = 1
b = 2
elif who == 2:
a = 2
b = 1
... | [
"def find_possible_position(length, board):\n directions = [0, 1, 2] # three directions: 0 for horizontal, 1 for vertical, 2 for inclined\n board_coordinates = []\n for hex in board:\n board_coordinates.append((hex.x,hex.y))\n\n for direction in directions:\n\n if direction == 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterates over every element in every list in board to create a list of tuples of the format (r, c), where r and c are integers from 0 to 7 corresponding to the indices of the board rows/columns for every place in board that is not occupied by another players counters | def getTile(board):
position = []
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col] == 0: #only adds empty spaces
position.append((row, col))
return position | [
"def generate_legal_moves(self) -> list:\n board = self.board_list\n index = 0\n return_list = []\n for row in board:\n for column in row:\n if column is None:\n return_list.append(index)\n index += 1\n return return_list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes as argument a list 'board' representing the Othello board and returns an integer corresponding to the difference of the number of player1's and player2's counters. Positive scores indicate an advantage of player1, while negative scores indicate an advantage of player2 | def scoreBoard(board):
x = 0
y = 0
for i in board:
for j in i:
if j == 1: # if the space is occupied by player1's counter
x += 1
elif j == 2: # if the space is occupied by player2's counter
y -= 1
return x + y | [
"def score(player, board):\n mine, theirs = 0, 0\n opp = othello.opponent(player)\n for sq in othello.squares():\n piece = board[sq]\n if piece == player: mine += 1\n elif piece == opp: theirs += 1\n return mine - theirs",
"def count_board(board):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Supervised Learning dataset as spark DataFrame, The Dataset DataFrame is consisting of both features and labels. | def get_supervised_learning_df(df, label_variable, feature_variables,
label_name=None,
features_name=None):
from pyspark.ml.linalg import Vectors
from pyspark.sql import Row
df = df\
.rdd\
.map(lambda x: Row(
... | [
"def to_spark_df(self):\n return self.df",
"def load_sklearn_dataset(name):\n\n if name in [\"iris\"]:\n data = datasets[name]() \n df = (\n pd.DataFrame(\n np.hstack([data.data, [[x] for x in data.target]]), \n columns=(list(data.feature_names) + [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new reminder for a specific day | def add_reminder_for_day(request, year, month, day):
try:
date = datetime(int(year), int(month), int(day)).date()
except ValueError:
raise Http404
form = NewReminderForm(request.POST or None, user=request.user, date=date)
if request.method == 'POST' and form.is_valid():
form.sa... | [
"def add_specific_date(self, recurring_event_id, date, location_description):\n pass",
"def handle_create_reminder(self, message):\n if self.neon_in_request(message):\n content = self._extract_alert_params(message, AlertType.REMINDER)\n content[\"kind\"] = int(AlertType.REMINDE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a torch function based on ``arrays`` and ``expr``. | def build_expression(_, expr): # pragma: no cover
def torch_contract(*arrays):
torch_arrays = [to_torch(x) for x in arrays]
torch_out = expr._contract(torch_arrays, backend="torch")
if torch_out.device.type == "cpu":
return torch_out.numpy()
return torch_out.cpu().num... | [
"def evaluate_constants(const_arrays, expr):\n const_arrays = [to_torch(x) for x in const_arrays]\n return expr(*const_arrays, backend=\"torch\", evaluate_constants=True)",
"def create_expression_function(self, expression):\n expr_func = CompiledFunction(self, len(self.functions) + 1, [])\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert constant arguments to torch, and perform any possible constant contractions. | def evaluate_constants(const_arrays, expr):
const_arrays = [to_torch(x) for x in const_arrays]
return expr(*const_arrays, backend="torch", evaluate_constants=True) | [
"def validate_arguments(self):\r\n if not self.args[0].is_vector() or not self.args[1].is_vector():\r\n raise TypeError(\"The arguments to conv must resolve to vectors.\" )\r\n if not self.args[0].is_constant():\r\n raise TypeError(\"The first argument to conv must be constant.\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if pfile or spfile is existing for ORACLE_SID and ORACLE_HOME returncode 'True', 'False' ASM is a special situation. GridInfrastructure has no pfile or spfile for AsM => ORACLE_SID = +ASM => True | def check_oraclesid(ORACLE_SID, ORACLE_HOME):
# We don't have an init.ora or spfile.ora for ASM in CRS_HOME
# We don't need to check for a valid home
# => return True
if ORACLE_SID[0:4] == '+ASM':
return 'True'
orapfile=ORACLE_HOME + '/dbs/' + 'init' + ORACLE_SID + '.ora'
oraspfile=... | [
"def check_psspy_already_in_path():\n syspath = find_file_on_path(\"psspy.pyc\", sys.path)\n\n if syspath:\n # file in one of the files on the sys.path (python's path) list.\n envpaths = os.environ[\"PATH\"].split(\";\")\n envpath = find_file_on_path(\"psspy.pyc\", envpaths)\n if e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return 'true' when clusterware is found return 'false' when no clusterware is found | def check4clusterware():
ocrcfg = '/etc/oracle/ocr.loc'
if os.path.exists(ocrcfg) == True:
# read the file
ocrcfg = open(ocrcfg, 'r')
for line in ocrcfg:
if line.rstrip() == 'local_only=FALSE':
# we have a real clusterware!
return 'True'
re... | [
"def can_connect_to_cluster():\n url = 'https://travelimperial.azurehdinsight.net/templeton/v1/status'\n resp = requests.get(url, auth=(CLUSTER_USER, CLUSTER_PASS))\n print(resp.status_code)\n return (resp.status_code == 200)",
"def host_is_vmware():\n [rv, stdout, stderr] = run_command([constants.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill the dictionary from oratab ORACLE_SID_list | def readoratab():
oratabfile='/etc/oratab'
if os.path.exists(oratabfile) == False:
print "no oratab found. Exiting script!"
sys.exit(99)
oratab = open(oratabfile, 'r')
for line in oratab:
linestr = line.rstrip()
# filter all lines starting with '#'
if linestr != ... | [
"def sid_to_user(registry, sid_list):\n mapping_list = []\n for sid in sid_list:\n with OpenKey(registry, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\%s\" % s) as key:\n v,t = QueryValueEx(key, \"ProfileImagePath\")\n mapping_list.append(\"{0:20} : {1}\".forma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate that x is a valid ID for a new experiment plate. | def validate_new_experiment_plate_id(x):
if x <= 0:
raise forms.ValidationError('ExperimentPlate ID must be positive')
if ExperimentPlate.objects.filter(pk=x).count():
raise forms.ValidationError('ExperimentPlate ID {} already exists'
.format(x)) | [
"def test_validate_id_too_short():\n assetpack = get_test_assetpack()\n with raises(PyInquirer.ValidationError):\n assert validate_component_id('z', assetpack) is False",
"def test_validate_component_id():\n assetpack = get_test_assetpack()\n assert validate_component_id('brand_new', assetpack)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to apply the ChangeExperimentPlateForm changes to a specific plate. data should be the cleaned_data from a ChangeExperimentPlatesForm. | def process_ChangeExperimentPlatesForm_data(experiment_plate, data):
# First update straightforward plate fields
for key in ('screen_stage', 'date', 'temperature', 'comment',):
value = data.get(key)
if value:
setattr(experiment_plate, key, value)
experiment_plate.save()
... | [
"def alter(self, date, data, component='main'):\n if date < 0 or date > self.n - 1:\n raise NameError('The date should be between 0 and ' +\n str(self.n - 1))\n\n # initialize the model to ease the modification\n if not self.initialized:\n self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiate a cleaning rule with basic attributes. Inheriting classes must set issue numbers, description and affected datasets. As other tickets may affect the SQL of a cleaning rule, append them to the list of Jira Issues. DO NOT REMOVE ORIGINAL JIRA ISSUE NUMBERS! | def __init__(self,
issue_numbers: string_list = None,
issue_urls: string_list = None,
description: str = None,
affected_datasets: string_list = None,
project_id: str = None,
dataset_id: str = None,
san... | [
"def __init__(self, rules={}):\n\n # Copy default rules and overwite with constructor argument.\n self.rules = self.DEFAULT_RULES.copy()\n self.rules.update(rules)",
"def __init__(self, ticket_id=None,\n summary=None,\n description=None,\n reporter=No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate the given argument is a list of strings. | def __validate_list_of_strings(self, arg, arg_name):
if arg is None:
raise NotImplementedError(
'{} cleaning rule must set {} variable'.format(
self.__class__.__name__, arg_name))
if not isinstance(arg, list):
raise TypeError(
... | [
"def ValidateStringList(arg_internal_name, arg_value):\n if isinstance(arg_value, basestring): # convert single str to a str list\n return [arg_value]\n if isinstance(arg_value, int): # convert single int to a str list\n return [str(arg_value)]\n if isinstance(arg_value, list):\n return [_ValidateStri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the names of classes the rule depends on. | def depends_on_classes(self):
return self._depends_on_classes | [
"def needs(self):\n result = []\n for dep in self.dependencies:\n module = dep.split(\".\")[0].lower()\n if module not in result:\n result.append(module)\n\n return result",
"def all_dependencies():\n return Dependency.all_instances().keys()",
"def de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the issue_urls instance variable. | def issue_urls(self):
return self._issue_urls | [
"def return_urls(self):\n return self._return_urls",
"def issue_numbers(self):\n return self._issue_numbers",
"def get_worker_urls( self ):\n return self.worker_urls",
"def urls(self):\n return [\n url('', include(self.get_list_urls()), {'flow_class': self.flow_class... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the issue_numbers instance variable. | def issue_numbers(self):
return self._issue_numbers | [
"def issues(self):\n return self._issueBox",
"def issue_number(self):\n return self._get('issueNumber')",
"def issue_urls(self):\n return self._issue_urls",
"def get_unique_issues(self) -> collections.Counter[str]:\n return collections.Counter(\n str(record[\"setup\"][\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the list of datasets a rule affects. | def affected_datasets(self):
return self._affected_datasets | [
"def dt_query_affected_datasets_list():",
"def list_datasets():\n # TODO: Query datasets in database\n return []",
"def get(self):\n args = parser.parse(datasets_args, request)\n ds = get_datasets(**args)\n datasets = [ str(d.id) for d in ds ]\n return datasets",
"def filter(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the dataset id for this class instance. | def dataset_id(self):
return self._dataset_id | [
"def get_dataset_id(self, dataset):\n raise NotImplementedError",
"def get_id(self):\n return self[\"ds_id\"]",
"def data_id(self) -> str:\n return self.entity_description.data_id",
"def _get_id(self) -> \"std::string\" :\n return _core.DataFile__get_id(self)",
"def data_id(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the sandbox dataset id for this class instance. | def sandbox_dataset_id(self):
return self._sandbox_dataset_id | [
"def get_dataset_id(self, dataset):\n raise NotImplementedError",
"def get_id(self):\n return self[\"ds_id\"]",
"def _get_id(self) -> \"std::string\" :\n return _core.DataFile__get_id(self)",
"def data_id(self) -> str:\n return self.entity_description.data_id",
"def data_id(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to get tables that will be modified by the cleaning rule. If getting the tables_affected dynamically logic needs to be implemented in this method. | def affected_tables(self):
return self._affected_tables | [
"def getAllTables (self):\n\n return self.tables",
"def affected_tables(self, affected_tables):\n if affected_tables:\n if not isinstance(affected_tables, list):\n raise TypeError('affected_tables must be of type List')\n else:\n self._affected_table... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the table tag of the sandbox for this class instance. | def table_tag(self):
return self._table_tag | [
"def get_ethnicity_sandbox_table(self):\n return self.sandbox_table_for(self.ETHNICITY)",
"def get_race_sandbox_table(self):\n return self.sandbox_table_for(self.RACE)",
"def table_name(self) -> str:\n return jsii.get(self, \"tableName\")",
"def get_birth_info_sandbox_table(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the affected_tables for this class instance, raises error if affected_tables is not a list | def affected_tables(self, affected_tables):
if affected_tables:
if not isinstance(affected_tables, list):
raise TypeError('affected_tables must be of type List')
else:
self._affected_tables = affected_tables
else:
self._affected_tables ... | [
"def affected_tables(self):\n return self._affected_tables",
"def reflecttable(self, connection, table):\n raise NotImplementedError()",
"def setTable( self, table ):\n self._table = table\n self.setEnabled(table is not None)\n self.clear()",
"def refreshTables(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the table_namer for this class instance. If no value is provided, it is set to a default value. | def table_namer(self, table_namer, **kwargs):
if not table_namer:
for key, value in kwargs.items():
self._table_namer = kwargs.get(value)
else:
self._table_namer = table_namer | [
"def setTable(self, tableName):\n # TODO: Need to check if tableName really exists in the selected database before setting it.\n # if does not exist throw exception.\n # right now any string is selected as database - need to FIX this.\n self.table = tableName",
"def set_ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A helper function to retrieve the sandbox table name for the affected_table | def sandbox_table_for(self, affected_table):
base_name = f'{"_".join(self.issue_numbers).lower()}_{affected_table}'
return get_sandbox_table_name(self.table_namer, base_name) | [
"def table_name(self) -> str:\n return jsii.get(self, \"tableName\")",
"def dynamo_table_name():\n if is_local_env():\n return LOCAL_TABLE_NAME\n\n # get data from parameter store with correct key\n # table_name = get_params_from_ssm()[\"CORRECT_KEY\"]\n return \"table_name\"",
"def ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to retrieve the sandbox options which includes the description and labels | def get_sandbox_options_string(self, shared=False):
return get_sandbox_options(self.dataset_id,
self.__class__.__name__,
self.table_tag,
self.description,
shared_lookup=sha... | [
"def test_get_options_expirations(self):\n pass",
"def test_get_options(self):\n pass",
"def getOptionDescriptions(self) -> List[unicode]:\n ...",
"def options(self):\n return self.data['options']",
"def options(self, section: str) -> List[str]:",
"def getOptions(self):\n #r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifica si esta registrado remotamente | def checkRegistradoRemotamente(self):
id, nombre, email, version, password = self.obtenerDatosRegistrados()
if id > 0:
registrado = self.peticionRemota.usuarioRegistrado(id, email)
return (registrado != 'False')
else:
return False | [
"def registrarRemotamente(self):\n id, nombre, email, version, password = self.obtenerDatosRegistrados()\n id_obtenido, server_id = self.peticionRemota.registrarUsuario(nombre,\n email, password, version)\n modulo_logger.log(logging.INFO, 'ID OBTENIDO: %s, server_id: %s' %\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registra remotamente los datos solicitados al momento de la instalacion | def registrarRemotamente(self):
id, nombre, email, version, password = self.obtenerDatosRegistrados()
id_obtenido, server_id = self.peticionRemota.registrarUsuario(nombre,
email, password, version)
modulo_logger.log(logging.INFO, 'ID OBTENIDO: %s, server_id: %s' %
(id_obt... | [
"def register(minion):\n host_id = string.join([_host_prefix(), minion], '/')\n fname = '%s.json'% re.sub(\"/\", \"_\", host_id)\n\n host = _provision_host(host_id, _client_layer_id())\n api_key = None\n try:\n api_key = host.api_key\n except AttributeError:\n None\n # pass\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Devuelve id, nombre, email y version | def obtenerDatosRegistrados(self):
try:
userid, nombre, email, version, password = self.cursor.execute(
'select id, nombretitular, email, version, password from '
'instalacion'
).fetchone()
except sqlite3.OperationalError, msg:
modu... | [
"def modificar(self, nombre, nombreNew, descripcionNew):\n from models import LineaBase \n lineaBase = LineaBase.query.filter(LineaBase.nombre == nombre).first_or_404()\n lineaBase.nombre = nombreNew\n lineaBase.descripcion = descripcionNew\n db.session.commit()",
"def get_info(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ask authy token prompt. | def prompt_authy_token(self):
return six.moves.input('Authy token: ') | [
"def otp_token_prompt(self, uri, token_method, *args, **kwargs):\n if getattr(self.options, 'diff_filename', None) == '-':\n raise CommandError('A two-factor authentication token is '\n 'required, but cannot be used with '\n '--diff-filen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for the SqlBackupJobParams class | def __init__(self,
aag_backup_preference_type=None,
advanced_settings=None,
backup_database_volumes_only=None,
backup_system_dbs=None,
continue_after_error=None,
enable_checksum=None,
enable_incrementa... | [
"def __init__(__self__,\n resource_name: str,\n args: RdsBackupArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n ...",
"def __init__(self,\n *,\n job_id: str = None,\n job_name: str = None,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for finding product's links in given content. | def products_links(self, content):
raise NotImplementedError | [
"def _scrape_product_links(self, response):\n lis = response.xpath(\n \"//div[@id='resultsCol']/./ul/li |\"\n \"//div[@id='mainResults']/.//ul/li [contains(@id, 'result')] |\"\n \"//div[@id='atfResults']/.//ul/li[contains(@id, 'result')] |\"\n \"//div[@id='mainResu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read csv file with store urls | def _read_csv(self, source_file):
stores = set()
with open(source_file, 'rb') as f:
reader = csv.reader(f)
# skip header
next(reader, None)
for store in reader:
#url = store["url"]
url = store[0]
if not url.... | [
"def parse_urls() -> List[str]:\n urls = []\n with open(CSV_FILEPATH, newline=\"\") as f:\n reader = csv.reader(f)\n for line in reader:\n urls.append(line[0])\n\n return urls",
"def get_urls_from_csv(filename):\n try:\n with open(filename, 'r') as infile:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find emails addresses in given content | def find_emails(self, content):
# Simple regex from stackoverflow
email_regex = r'[\w\.-]+@[\w\.-]+'
return {e for e in self._find_pattern(content, email_regex) if e} | [
"def extract_emails(text):\n result = re.findall(EMAIL_REGEX, text)\n return result",
"def get_emails(document=None):\n print(\"get_emails()\")\n _r = r\"'<\\S+?>'\"\n # this caught false-positives like 'rd@context'\n # _r = r\"[\\w\\.-]+@[\\w\\.-]+\"\n emails = list(\n set(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the link of this FormField. | def link(self, link):
self._link = link | [
"def setHref(self, href):",
"def set_link(self, link):\r\n arg_str = p2e._base._util._convert_args_to_string(\"set.node.link\", self._node._eco_id, link._eco_id)\r\n p2e._app.Exec(arg_str)",
"def setLinked(self, linked):\n pass",
"def self_link(self, self_link):\n\n self._self_link = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the node_id of this FormField. | def node_id(self, node_id):
self._node_id = node_id | [
"def set_parent(self, node_id: int):\r\n self.parent = node_id",
"def set_node(self, node, _id) -> None:\n\n if self.node1._id == _id:\n self.node1 = node\n elif self.node2._id == _id:\n self.node2 = node\n else:\n self.node1.set_node(node, _id)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the status_text of this FormField. | def status_text(self, status_text):
self._status_text = status_text | [
"def text_confirmation_status(self, text_confirmation_status):\n\n self._text_confirmation_status = text_confirmation_status",
"def _set_status_message(self, value, fg=\"Black\"):\n self.__log.call(value, fg=fg)\n self._status_label.config(text=value)\n _styled(self._status_label, fore... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the own_status of this FormField. | def own_status(self, own_status):
self._own_status = own_status | [
"def set_Status(self, value):\n super(UpdateTicketInputSet, self)._set_input('Status', value)",
"def status_pick_up_code(self, status_pick_up_code):\n\n self._status_pick_up_code = status_pick_up_code",
"def status_pick_up(self, status_pick_up):\n allowed_values = [\"Unknown\", \"Ready\", \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the help_text of this FormField. | def help_text(self, help_text):
self._help_text = help_text | [
"def custom_help_label(self, custom_help_label):\n\n self._custom_help_label = custom_help_label",
"def setHelpWidget(self):\n self.help = HelpPopUp()\n self.help.showHelp(str(Path(__file__).parents[1]) + '/images/help/helpEditing.png')",
"def _help(self, name, text):\n self._arg_tre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the own_help of this FormField. | def own_help(self, own_help):
self._own_help = own_help | [
"def custom_help_label(self, custom_help_label):\n\n self._custom_help_label = custom_help_label",
"def custom_help_url(self, custom_help_url):\n\n self._custom_help_url = custom_help_url",
"def setHelpWidget(self):\n self.help = HelpPopUp()\n self.help.showHelp(str(Path(__file__).pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the calculate_on_exit of this FormField. | def calculate_on_exit(self, calculate_on_exit):
self._calculate_on_exit = calculate_on_exit | [
"def setOnExit(self, onexit: 'ScXMLOnExitElt') -> \"void\":\n return _coin.ScXMLFinalElt_setOnExit(self, onexit)",
"def setOnExit(self, onexit: 'ScXMLOnExitElt') -> \"void\":\n return _coin.ScXMLStateElt_setOnExit(self, onexit)",
"def setOnExit(self, onexit: 'ScXMLOnExitElt') -> \"void\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the entry_macro of this FormField. | def entry_macro(self, entry_macro):
self._entry_macro = entry_macro | [
"def setOnEntry(self, onentry: 'ScXMLOnEntryElt') -> \"void\":\n return _coin.ScXMLFinalElt_setOnEntry(self, onentry)",
"def setOnEntry(self, onentry: 'ScXMLOnEntryElt') -> \"void\":\n return _coin.ScXMLParallelElt_setOnEntry(self, onentry)",
"def setOnEntry(self, onentry: 'ScXMLOnEntryElt') -> \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the exit_macro of this FormField. | def exit_macro(self, exit_macro):
self._exit_macro = exit_macro | [
"def exit_condition(self, exit_condition):\n\n self._exit_condition = exit_condition",
"def setOnExit(self, onexit: 'ScXMLOnExitElt') -> \"void\":\n return _coin.ScXMLFinalElt_setOnExit(self, onexit)",
"def entry_macro(self, entry_macro):\n self._entry_macro = entry_macro",
"def setOnExit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the datasets from the response. | def parse_datasets(self , selector, response):
datasets = []
for row in selector.xpath('//table[@class="Tabular"]//tr[td]'):
base_title = row.xpath("td[1]//text()").extract()[0].strip()
for link in row.xpath("td[2]//a"):
dataset = DatasetItem()
dat... | [
"def parse_datasets(self, selector, response):\n datasets = []\n for dataset_info in selector.xpath('//div[@class=\"Timeline\"]//dl'):\n dataset = self.parse_dataset(dataset_info)\n dataset['documentation_title'] = selector.xpath('//title//text()').extract()[0].strip()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the datasets from the response. | def parse_datasets(self, selector, response):
datasets = []
for dataset_info in selector.xpath('//div[@class="Timeline"]//dl'):
dataset = self.parse_dataset(dataset_info)
dataset['documentation_title'] = selector.xpath('//title//text()').extract()[0].strip()
dataset['... | [
"def parse_datasets(self , selector, response):\n datasets = []\n for row in selector.xpath('//table[@class=\"Tabular\"]//tr[td]'):\n base_title = row.xpath(\"td[1]//text()\").extract()[0].strip()\n for link in row.xpath(\"td[2]//a\"):\n dataset = DatasetItem()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select the most competent classifier for the classification of the query sample given the competence level estimates. Four selection schemes are available. | def select(self, competences):
if competences.ndim < 2:
competences = competences.reshape(1, -1)
selected_classifiers = []
best_index = np.argmax(competences, axis=1)
if self.selection_method == 'best':
# Select the classifier with highest competence level
... | [
"def select(self, competences):\n if competences.ndim < 2:\n competences = competences.reshape(1, -1)\n\n # Select classifier if it correctly classified at least one sample\n selected_classifiers = (competences > 0)\n\n # For the rows that are all False (i.e., no base classifi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predicts the class label of the corresponding query sample. If self.selection_method == "all", the majority voting scheme is used to aggregate the predictions of all classifiers with the max competence level estimates for each test examples. | def classify_with_ds(self, query, predictions, probabilities=None, neighbors=None, distances=None, DFP_mask=None):
if query.ndim < 2:
query = query.reshape(1, -1)
if predictions.ndim < 2:
predictions = predictions.reshape(1, -1)
if query.shape[0] != predictions.shape[0]... | [
"def predict(self, test_example):\r\n\r\n probs = self.features[0].get_probs(test_example[0])\r\n for i, feature in enumerate(test_example):\r\n probs *= self.features[i].get_probs(feature)\r\n total_examples = sum(self.total)\r\n probs *= self.total\r\n return CLASS_LABELS[np.argmax(probs)]",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predicts the posterior probabilities of the corresponding query sample. If self.selection_method == "all", get the probability estimates of the selected ensemble. Otherwise, the technique gets the probability estimates from the selected base classifier | def predict_proba_with_ds(self, query, predictions, probabilities, neighbors=None, distances=None, DFP_mask=None):
if query.shape[0] != probabilities.shape[0]:
raise ValueError('The arrays query and predictions must have the same number of samples. query.shape is {}'
'an... | [
"def sample_prediction(self):\n\t\tnn_param_set = np.random.choice(self.nn_param_sets, p = self.posterior_weights)\n\t\tself.set_k_weights(nn_param_set)\n\t\treturn self.model.predict(self.x)",
"def ensemble(dict_model_acc, test_design, method='vote'):\n pred_models_dict = {}\n pred_models_lst = []\n pro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calibrate camera using images from calid_images_folder | def calibrate_and_draw(self, calib_images_folder, nx, ny):
# +-----------------+
# | FINDING CORNERS |
# +-----------------+
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((nx*ny,3), np.float32)
objp[:,:2] = np.mgrid[0:nx, 0:... | [
"def calibrate(self, calib_images_folder, nx, ny):\n\n # +-----------------+\n # | FINDING CORNERS |\n # +-----------------+\n # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((nx*ny,3), np.float32)\n objp[:,:2] = np.mgrid[0:nx, 0:ny].T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calibrate camera using images from calid_images_folder | def calibrate(self, calib_images_folder, nx, ny):
# +-----------------+
# | FINDING CORNERS |
# +-----------------+
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((nx*ny,3), np.float32)
objp[:,:2] = np.mgrid[0:nx, 0:ny].T.reshape(-1,... | [
"def calibrate_and_draw(self, calib_images_folder, nx, ny):\n \n # +-----------------+\n # | FINDING CORNERS |\n # +-----------------+\n # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((nx*ny,3), np.float32)\n objp[:,:2] = np.mg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Harvest elegiable donor sites from this CodingBlockGraph into a DonorSiteCollectionGraph | def harvest_elegiable_donor_sites(self,projected_donors={},forced_codingblock_ends={},next=None,
store_all_projected_sites=False,
allow_phase_shift=False,
enlarge_5p_boundary_by=None, # in AA coordinates
enlarge_3p_boundary_by=None, # in AA coordinates
ALIGNED_DONOR_MAX_TRIPLET_DISTANCE=None,
MI... | [
"def college_transfer_scrape(schools):\n \n #links =\n\n #for i, link in enumerate(links):\n # soup = make_soup(link)\n \n # for item in soup.findAll():\n # stuff = ''\n \n # schools[i]['item'] = stuff\n \n return schools",
"def scrape_page(driver, connecto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Harvest elegiable acceptor sites from this CodingBlockGraph into a AcceptorSiteCollectionGraph | def harvest_elegiable_acceptor_sites(self,projected_acceptors={},forced_codingblock_ends={},prev=None,
store_all_projected_sites=False,
allow_phase_shift=False,
enlarge_5p_boundary_by=None, # in AA coordinates
enlarge_3p_boundary_by=None, # in AA coordinates
ALIGNED_ACCEPTOR_MAX_TRIPLET_DISTANCE=Non... | [
"def sites(self):\n return self.data.sites.values",
"async def _output_fact_edges(\n self, ability: Ability, graph: nx.DiGraph, agent: Agent\n ) -> nx.DiGraph:\n executor = await agent.get_preferred_executor(ability)\n if self._is_invalid_executor(executor):\n return grap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Align the stopcodons from the aligned orfs in the pacbporfs in a graph object. Perfectly alignable stopcodons result in a graph with total_weight() == 1.0, all below 1.0 means offsets in the alignment. Nonperfect aligned stopcodons are common, but (very) poor alignable stopcodons are very rare. | def align_stop_codons(codingblockgraph,alignedstopcodongraph):
for ( (a,b,c,d),(g1,o1),(g2,o2) ), pacbporf in codingblockgraph.pacbps.iteritems():
stopQpos = pacbporf.orfQ.protein_endPY+1
stopSpos = pacbporf.orfS.protein_endPY+1
stopQdnapos = pacbporf.orfQ.proteinpos2dnapos(stopQpos)
... | [
"def _align_orns(self,\n target_orn,\n ref_orn=None,\n axes=[0, 1, 2],\n exclude_vertical_axis=False):\n if ref_orn is None:\n ref_orn = self._get_default_gripper_orn()\n\n for axis in axes:\n if (axis == self.vertical_axis_idx and excl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the position on the Orf of this organism in the CBG from where to take TSS positions into account | def minimal_eligable_tss_position(cbg,organism):
# take the first (and only) orf of this organism
orf_of_org = cbg.get_orfs_of_graph(organism=organism)[0]
omsr = cbg.overall_minimal_spanning_range(organism=organism)
# calculate absolute aa and nt positions from where to take acceptors into account
i... | [
"def maximal_eligable_tss_position(cbg,organism):\n # take the first (and only) orf of this organism\n orf_of_org = cbg.get_orfs_of_graph(organism=organism)[0]\n omsr = cbg.overall_minimal_spanning_range(organism=organism)\n # calculate absolute aa and nt positions from where to take acceptors into acco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the position on the Orf of this organism in the CBG untill where to take TSS positions into account | def maximal_eligable_tss_position(cbg,organism):
# take the first (and only) orf of this organism
orf_of_org = cbg.get_orfs_of_graph(organism=organism)[0]
omsr = cbg.overall_minimal_spanning_range(organism=organism)
# calculate absolute aa and nt positions from where to take acceptors into account
i... | [
"def minimal_eligable_tss_position(cbg,organism):\n # take the first (and only) orf of this organism\n orf_of_org = cbg.get_orfs_of_graph(organism=organism)[0]\n omsr = cbg.overall_minimal_spanning_range(organism=organism)\n # calculate absolute aa and nt positions from where to take acceptors into acco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the ohlc data in the database | def save_ohlc(self, pair, interval, ohlcs):
# We modify the first element with the correct volume
self.web_db.sql_commit("UPDATE ohlcs SET volume = %s WHERE pair_id = %s AND interval = %s AND date_ohlc = %s", [Decimal(ohlcs[0][5]), pair['id'], interval, int(ohlcs[0][0])]);
# We skip the first element to add only ... | [
"def save_data( self, ):\n\n log_msg = \"in save_data() \" #print( log_msg )\n self.logger.debug( log_msg )\n\n if not ( self.need_update() ):\n #self.logger.info( \"no update needed\" )\n return\n\n\n\n # bad ideas we shoul have some standards even if we hav... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the last ohlc in the db and call API to complete with the most recent datas | def get_ohlc(self, api, pair, interval, broker):
# Get the last ohlc date we have for the concerned broker, pair & inteval
success = False
last_ohlc = self.web_db.sql_fetchall("SELECT date_ohlc FROM OHLCS WHERE pair_id = %s AND interval = %s ORDER BY date_ohlc DESC LIMIT 2", [pair['id'], interval])
# We do not ... | [
"def download_latest_data():\n try:\n response = requests.get(FOOD_TRUCK_DATA_URL)\n response.raise_for_status()\n\n with open(FOOD_TRUCK_DATA_CSV, 'w') as file:\n file.write(response.text)\n\n except requests.RequestException:\n logging.error(\"There was a problem retri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a rather long but very useful utility method which enables complete testing of ```ks_util.AsyncAction.async_req_to_key_store```. | def _test_good(self,
request_method,
request_body_as_dict,
response_body_as_dict):
request_path = str(uuid.uuid4()).replace("-", "")
response_body = json.dumps(response_body_as_dict) if response_body_as_dict else None
def async_http_clie... | [
"def on_async_req_to_key_store_done(is_ok, http_status_code=None, body=None):\n self.assertTrue(is_ok)\n\n self.assertIsNotNone(http_status_code)\n self.assertEqual(http_status_code, httplib.OK)\n\n if response_body_as_dict:\n self.assertIsNotNone(body)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is used to patch ```tornado.httpclient.AsyncHTTPClient.fetch``` so that when ```ks_util.AsyncAction.async_req_to_key_store``` calls ```tornado.httpclient.AsyncHTTPClient.fetch``` this test (or this function specifically) can get into the call stream. | def async_http_client_fetch_patch(http_client, request, callback):
self.assertIsNotNone(request)
self.assertIsNotNone(request.url)
expected_url = "http://%s/%s" % (type(self)._key_store, request_path)
self.assertEqual(request.url, expected_url)
self.assertI... | [
"def _test_good(self,\n request_method,\n request_body_as_dict,\n response_body_as_dict):\n\n request_path = str(uuid.uuid4()).replace(\"-\", \"\")\n response_body = json.dumps(response_body_as_dict) if response_body_as_dict else None\n\n de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when ```ks_util.AsyncAction.async_req_to_key_store``` completes. | def on_async_req_to_key_store_done(is_ok, http_status_code=None, body=None):
self.assertTrue(is_ok)
self.assertIsNotNone(http_status_code)
self.assertEqual(http_status_code, httplib.OK)
if response_body_as_dict:
self.assertIsNotNone(body)
... | [
"def on_async_req_to_key_store_done(is_ok, http_status_code=None, body=None):\n self.assertFalse(is_ok)\n\n self.assertIsNone(http_status_code)\n self.assertIsNone(body)",
"def _on_fetch_done(self, response):\n _logger.info(\n \"Key Service (%s - %s) responded in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This test verifies the behavior of ```ks_util.AsyncAction.async_req_to_key_store``` when an error is returned by the HTTP request to the key store. | def test_error_in_response(self):
def async_http_client_fetch_patch(http_client, request, callback):
"""This function is used to patch
```tornado.httpclient.AsyncHTTPClient.fetch``` so that when
```ks_util.AsyncAction.async_req_to_key_store``` calls
```tornado.ht... | [
"def on_async_req_to_key_store_done(is_ok, http_status_code=None, body=None):\n self.assertFalse(is_ok)\n\n self.assertIsNone(http_status_code)\n self.assertIsNone(body)",
"def on_async_req_to_key_store_done(is_ok, http_status_code=None, body=None):\n self.assertTrue(is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when ```ks_util.AsyncAction.async_req_to_key_store``` completes. | def on_async_req_to_key_store_done(is_ok, http_status_code=None, body=None):
self.assertFalse(is_ok)
self.assertIsNone(http_status_code)
self.assertIsNone(body) | [
"def on_async_req_to_key_store_done(is_ok, http_status_code=None, body=None):\n self.assertTrue(is_ok)\n\n self.assertIsNotNone(http_status_code)\n self.assertEqual(http_status_code, httplib.OK)\n\n if response_body_as_dict:\n self.assertIsNotNone(body)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate microgrid profile based on peractor ones | def calculate_microgrid_profile(per_actor_load_prof: dict) -> np.ndarray:
return np.sum([per_actor_load_prof[elt] for elt in per_actor_load_prof], axis=0) | [
"def _subprofiles(self):\n\n self.subcounts = self._get_subcounts()\n hasval = [np.nonzero(arr.astype(bool))[0] for arr in self.subcounts]\n\n # calculating jackknife subprofiles\n for i, lab in enumerate(self.sub_labels):\n # print i, lab\n ind = self.indexes[i]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate pmax cost (power component in the elec. tariff) | def calculate_pmax_cost(daily_microgrid_prof: np.ndarray,
contracted_p_tariffs: dict) -> float:
# get all thresholds values and sort them
power_thresholds = list(contracted_p_tariffs.keys())
power_thresholds.sort()
# if microgrid max. load (power) bigger than pmax v... | [
"def calPMax(p1,p2,p3):\n a=((p1[1]-p2[1])*(p2[0]-p3[0])-(p2[1]-p3[1])*(p1[0]\n -p2[0]))/((p1[0]*p1[0]-p2[0]*p2[0])*(p2[0]-p3[0])\n -(p2[0]*p2[0]-p3[0]*p3[0])*(p1[0]-p2[0]))\n b=(p1[1]-p2[1]-a*(p1[0]*p1[0]-p2[0]*p2[0]))/(p1[0]-p2[0])\n return -1.0*b/(2.0*a)",
"def compute_optimum(self):\n assert s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |