query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
provide functionality to associate an account with the market segment Raises ValueError if the market segment already knows about the account | def add_account(self, account, add_ms_to_account=True):
# check if name already exists and throw ValueError if it does
# it doesn't make sense to add an account twice -- this could be
# refactored to use a set instead
# check for accounts by name per Q2 bonus below
if accoun... | [
"def put_account(self, account):\n \n pass",
"def add(self, account):\r\n key = self.makeKey(account.getName(),\r\n account.getPin())\r\n self.accounts[key] = account",
"def create_account(self):\n pass",
"def set_account(publisher_id, account_id):",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the accounts associated with this MarketSegment | def get_accounts(self):
return self._accounts | [
"def accounts(self):\n return self._accounts.values()",
"def get_accounts(self) -> list:\n response = self.TradeAPI.makeRequest(\"GET\", \"account/list\")\n response = response.json()\n response = response[\"results\"]\n return response",
"def getAccounts(self):\n query... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the sales rep assocated to this Account | def get_sales_rep(self):
return self._sales_rep | [
"def sales_rep_code(self):\n return self._sales_rep_code",
"def get_sales(self, date):\n\n return self.sales[date]",
"def get_sales_data():\n print(\"Retrieving all the sales information...\")\n data = SHEET.worksheet('sales')\n print(\"Compilation complete!\\n\")\n return data",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the sales rep for this Account | def set_sales_rep(self, sales_rep):
self._sales_rep = sales_rep | [
"def sales(self, sales):\n\n self._sales = sales",
"def update_sales_data(self):\n purprods = self.purchasedproduct_set.all()\n \n self.n_rows = purprods.count()\n row_discounts = purprods.aggregate(Sum('total_discount')).values()[0] or Decimal(0)\n self.total_discount = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
replaces the list of market segments for this Account | def set_market_segments(self, segments):
"""
Q1-2. Implement this method, which takes an iterable of MarketSegments
to which this Account will be attached. This method REPLACES all
MarketSegment associations, so be sure to update each
MarketSegment's intern... | [
"def remove_from_market_segment(self, market_segment):\r\n if market_segment in self._market_segments:\r\n self._market_segments.remove(market_segment)\r\n market_segment.remove_account(self)\r\n else:\r\n # nothing to do, the market segment was already\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add a market segment to this account | def add_to_market_segment(self, market_segment, add_account_to_ms=True):
if market_segment in self._market_segments:
raise ValueError("{name} already part of {ms_name}"
.format(name=self.name,
ms_name=market_segment.name))
... | [
"def set_market_segments(self, segments):\r\n \"\"\"\r\n Q1-2. Implement this method, which takes an iterable of MarketSegments\r\n to which this Account will be attached. This method REPLACES all\r\n MarketSegment associations, so be sure to update each\r\n Mark... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove the market segment from this account | def remove_from_market_segment(self, market_segment):
if market_segment in self._market_segments:
self._market_segments.remove(market_segment)
market_segment.remove_account(self)
else:
# nothing to do, the market segment was already
# not in the acco... | [
"def remove(self, wallet: 'Wallet') -> None:\n self._wallets.pop((wallet.exchange.id, wallet.instrument.symbol), None)",
"def do_erase(self, line):\n if self.bootstrap() != 0:\n return self.return_code(1, True)\n\n # Warning\n print('')\n print(self.t.underline_red('!... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper function that returns market segments in a list | def get_market_segments(self):
return self._market_segments | [
"def getSegments(self) -> List[int]:\n ...",
"def _split_into_segments(input_list):\n max_n = 100 # as of 23.02.2021\n\n # n cuts divide a list into n+1 segments (math.floor(len(song_uris) / max_n) =: number_of_cuts)\n n_of_segments = math.floor(len(input_list) / max_n) + 1\n list_of_lists = [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
associates an instance of ChildAccount to this Account | def add_child(self, child_account):
self._children.append(child_account) | [
"def add(self, account):\r\n key = self.makeKey(account.getName(),\r\n account.getPin())\r\n self.accounts[key] = account",
"def save_this_account(self):\n Account.list_of_accounts.append(self)",
"def add(self, account):\n if isinstance(account, Account) and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print a hierarchical structure representing an account and all child accounts associated to it to the console | def print_tree(account, level=0):
""" In the example output below, "GE" is the root account, "Jet Engines"
and "Appliances" are first-degree ChildAccounts, and "DoD Contracts"
and "Washing Machines" are second-degree ChildAccounts.
> print_tree(general_electric)
GE (Manufacturing, R&D... | [
"def DisplayAccountTree(account, link, accounts, links, depth=0):\n prefix = '-' * depth * 2\n print '%s%s, %s, %s' % (prefix, account.get('login', ''), account['customerId'],\n account['name'])\n if account['customerId'] in links:\n for child_link in links[account['customer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
utility function that checks the global scope for an object that matches the one passed in, if it doesn't exist create the reference in the global scope, this allows for "anonymous" object creation and to still get the object back later Note, the new object name will be the name property with special characters removed... | def check_for_existing_market_segment(segment):
for var in list(globals().keys()):
if isinstance(eval("{var}".format(var=var)), MarketSegment):
if eval("{var}.name".format(var=var)) == segment.name:
return
# no matching segment found in globals, create it!
var_nam... | [
"def default_object_scoper(object_name):\n return \"tag=\\\"{}\\\"\".format(object_name)",
"def replace(name, newobject):",
"def _valid_object_with_name(ui_object):\n return ui_object.obj_name",
"def create_simplenamespace():\n obj1 = _(foo=1)\n obj1.random = \"Whoa\"\n print(obj1)\n obj2 = _(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basically any speaker id is valid. | def clean(self, value):
speakers = speaker_models.Speaker.objects.filter(pk__in=value)
if len(speakers) != len(value):
raise ValidationError(self.error_messages['invalid_choice'] % value)
return speakers | [
"def _validate_id(self, id: str):\n raise NotImplementedError",
"def id_valid(self):\n if self.problems_with_id() == 'NONE':\n return True\n else:\n return False",
"def test_add_speech_with_unknown_speaker(self):\n self.assertEqual(Speaker.objects.filter(name='N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract names of categorical column This function accepts a dataframe and returns categorical list, containing the names of categorical columns(categorical_var). | def categorical(df):
categorical_var=df.select_dtypes(include ='object').columns.tolist()
return categorical_var | [
"def get_categorical_columns(X):\n return X.select_dtypes(include=['object', 'category'])",
"def find_cats(column):\r\n return pd.Categorical(column).categories",
"def _get_categorical_feature(self, data):\r\n categorical_column = [ ]\r\n for col in data:\r\n if data [ col ].dtype... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract names of numerical column This function accepts a dataframe and returns numerical list, containing the names of numerical columns(numerical_var). | def numerical(df):
numerical_var=df.select_dtypes(include =['float64','int64']).columns.tolist()
return numerical_var | [
"def get_numeric_columns(X):\n return X.select_dtypes(include=[np.number])",
"def get_non_num_cols(df):\n numerics = ['number']\n newdf = df.select_dtypes(exclude=numerics).columns\n return newdf",
"def getcolnames(self):\n return np.array([str(x) for x in self.colnames])",
"def get_non_flo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instances based on the condition This function accepts a dataframe, 2 columns(feature) and 2 values which returns the dataframe based on the condition. | def instances_based_condition(df,col1,val1,col2,val2):
instance=df[(df[col1]>val1) & (df[col2]==val2)]
return instance | [
"def filtering(self, df_condition):\n try:\n # Notice that this indexing return a copy of the original df, so the\n # original instance remains unchanged\n new_df = self.df.loc[df_condition]\n return Fermi_Dataset(new_df)\n except Exception as e:\n print('Oops! Give me a valid conditi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Aggregate values according to month This function accepts a dataframe, 2 columns(feature) and aggregated funcion(agg) which returns the Pivot table with different aggregated value of the feature with an index of the month. | def agg_values_ina_month(df,date_col,agg_col, agg):
df[date_col] = pd.to_datetime(df[date_col])
aggregate = {'mean':np.mean,'max':np.max,'min':np.min,'sum':np.sum,'len':len}
aggregated_value = df.pivot_table(values=[agg_col], index=df[date_col].dt.month,aggfunc={agg_col:aggregate[agg]})
... | [
"def monthly_aggregator(shape, agg_axis) :\r\n monthdays = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] \r\n cutpoints = np.concatenate( ((0,), np.cumsum(monthdays)-1))\r\n return CutpointReduceVar(shape, agg_axis, cutpoints)",
"def expand_feature_vectors(feature_df, minutes_agg, periods):\n df ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Agrregate values by grouping This function accepts a dataframe, 1 column(feature) and aggregated function(agg1) which groupby the datframe based on the column. | def group_values(df,col1,agg1):
grouping=df.groupby(col1).agg(agg1)
return grouping | [
"def group_aggregation(df, group_var, agg_var):\n\n # Grouping the data and taking mean\n grouped_df = df.groupby([group_var])[agg_var].mean()\n return grouped_df",
"def groupby(self, df, groupby_col, value_col, func_name, custom_func = None):\n func = {\"mean\": np.mean,\n \"min\":... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert temperatures from celsius to fahrenhheit This function accepts a dataframe, 1 column(feature) which returns the dataframe with converted values from celsius to fahrenhheit. | def convert(df,celsius):
converted_temp=(df[celsius]*(9/5))+32
return converted_temp | [
"def fahr_to_celsius(temp_fahrenheit):\n\n converted_temp=(temp_fahrenheit-32)/1.8\n return converted_temp",
"def celsius_to_fahrenheit(tempc):\n return (tempc*(9/5))+32",
"def celsius_to_fahrenheit():\n celsius = entry_temp2.get()\n # If entry field is empty, convert temp\n if celsius != \"\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns true if strA divides strB | def divs(strA,strB):
for i in range(0,1001):
if strB == strA*i:
return(True)
return(False) | [
"def check_divisibility(a, b):\n \n float_version = float(a)/b\n int_version = a/b\n if float_version == int_version:\n answer = \"divisible\"\n else:\n answer = \"not divisible\"\n return answer",
"def is_div(first, second):\n\n if first % second == 0:\n return True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Followup, group isomorphic strings | def group_isomorphic(strs):
def encode(s):
r, d = [], {}
for c in s:
if c not in d:
d[c] = len(d)
r.append(d[c])
return str(r)
m = defaultdict(list)
for s in strs:
m[encode(s)].append(s)
return list(m.values()) | [
"def group_anagrams(strs):\n anagram_grouping = {}\n \n for anagram in strs:\n curr_ana = str(sorted(anagram))\n anagram_grouping.setdefault(curr_ana, [])\n \n anagram_grouping[curr_ana].append(anagram)\n \n return [ anagram_grouping[gro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return processed audio data. Returns mel curve, x/y data. This method is called every time there is a microphone update. | def update(self, audio_samples):
min_frequency = self._config["general_settings"]["min_frequency"]
max_frequency = self._config["general_settings"]["max_frequency"]
audio_data = {}
# Normalize samples between 0 and 1.
y = audio_samples / 2.0**15
# Construct a rolling win... | [
"def getRawData(self):\n try:\n self.data = np.fromstring(\n self.stream.read(\n self.frames_per_buffer,\n exception_on_overflow = False\n ),\n dtype = np.int16\n )\n self.data = self.data.asty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns centerfrequencies and band edges for a mel filter bank | def melfrequencies_mel_filterbank(self, num_bands, freq_min, freq_max, num_fft_bands):
mel_max = self.hertz_to_mel(freq_max)
mel_min = self.hertz_to_mel(freq_min)
delta_mel = abs(mel_max - mel_min) / (num_bands + 1.0)
frequencies_mel = mel_min + delta_mel * arange(0, num_bands + 2)
... | [
"def get_filterbanks(nfilt=26,nfft=512,samplerate=16000,lowfreq=0,highfreq=None):\n highfreq= highfreq or samplerate/2\n assert highfreq <= samplerate/2, \"highfreq is greater than samplerate/2\"\n\n # compute points evenly spaced in mels\n lowmel = hz2mel(lowfreq)\n highmel = hz2mel(highfreq)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function renames columns of a pandas dataframe It converts column names to snake case if rename_dict is not passed. | def cleanup_column_names(df, rename_dict={}, do_inplace=True):
if not rename_dict:
return df.rename(columns={col: col.lower().replace(' ', '_')
for col in df.columns.values.tolist()},
inplace=do_inplace)
else:
return df.rename(columns=re... | [
"def rename_columns(self, df, old_to_new_cols_dict):\n return df.rename(columns=old_to_new_cols_dict)",
"def converted_multi_columns_to_camel_case(df):\n _columns = [col[0] + col[1].capitalize() for col in df.columns.values]\n df.columns = _columns\n \n return df",
"def rename_columns(df, col... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function should be overriden in the derived classes and return moreorless successfull guess about calling convention | def guess_calling_convention(self):
return calldef_types.CALLING_CONVENTION_TYPES.UNKNOWN | [
"def calling_conventions(self):\n\t\tcount = ctypes.c_ulonglong()\n\t\tcc = core.BNGetPlatformCallingConventions(self.handle, count)\n\t\tresult = []\n\t\tfor i in xrange(0, count.value):\n\t\t\tresult.append(callingconvention.CallingConvention(None, core.BNNewCallingConventionReference(cc[i])))\n\t\tcore.BNFreeCal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
list of class/class declaration types, extracted from the operator arguments | def class_types(self):
if None is self.__class_types:
self.__class_types = []
for type_ in self.argument_types:
decl = None
type_ = type_traits.remove_reference(type_)
if type_traits_classes.is_class(type_):
decl = type... | [
"def get_operator_metatypes() -> List[Type[OperatorMetatype]]:\n return list(PT_OPERATOR_METATYPES.registry_dict.values())",
"def get_types(*args, **kwargs) -> list:\n arg_types = []\n for arg in args:\n arg_types.append(type(arg))\n for values in kwargs.values():\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate through the condensed FAQ entries to expand all of the keywords and answers | def parse_faq_entries(entries):
parsed_entries = {}
for entry in entries:
for keyword in entry["keywords"]:
if keyword not in parsed_entries:
parsed_entries[keyword] = entry["answer"]
else:
print("Error: Found duplicate keyword '{}' in pre-configur... | [
"def compile_faqs(self):\n def doc_to_dict(faq):\n return dict(answer=faq.answer,\n question=faq.question,\n queries=faq.queries)\n self.faqs = [doc_to_dict(faq) for faq in FAQ.objects.find(channel=self.channel)]\n answer_df, query_df, st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the FAQ from disk into memory | def read_faq_from_disk():
return json.load(open("./faq.json")) | [
"def load_knowledge(self):\n MemoryManager.load_memory(self.knowledge_file)",
"def load_questions():\n\n\tprint \"Questions\"\n\n\twith open(\"seed_data/questions.txt\") as questions: \n\t\tfor q in questions: \n\t\t\tq = q.rstrip()\n\t\t\tquestion_id, question = q.split(\"|\")\n\n\t\t\tquestion = Question... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether or not a message that was sent belongs to an active conversation that the bot is in | def is_active_conv(timestamp):
debug_print("Checking to see if {} is an active conversation.".format(timestamp))
debug_print(ACTIVE_CONVS)
return timestamp in ACTIVE_CONVS | [
"def filter(self, message):\n conversations = Conversations()\n return conversations.get_conversation(message.from_user.id) is not None",
"def filter(self, message):\n conversations = Conversations()\n conversation = conversations.get_conversation(message.from_user.id)\n if conv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PrettyPrint to stdout if in debug mode | def debug_print(debug_data):
if DEBUG_MODE == "true":
pp.pprint(debug_data) | [
"def debug_print(text):\n if settings.debug:\n print(text)",
"def debug_print(text):\r\n if settings.debug:\r\n print (text)",
"def debug():",
"def debug():\n\n return",
"def stampadebug(messaggio):\n if settings.DEBUG_PRINT:\n print(messaggio)",
"def debug(string)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove polygons from this cell. The function or callable `test` is called for each polygon in the cell. If its return value evaluates to True, the corresponding polygon is removed from the cell. | def remove_polygons(self, test):
filtered_polys = []
for element in self.polygons:
pld = [(poly, l, dt) for poly, l, dt in zip(element.polygons, element.layers, element.datatypes)
if not test(poly, l, dt)]
if len(pld) == 0:
pass # we don't need... | [
"def remove_polygons(self, test):\n empty = []\n for element in self.elements:\n if isinstance(element, PolygonSet):\n ii = 0\n while ii < len(element.polygons):\n if test(element.polygons[ii], element.layers[ii],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove paths from this cell. The function or callable `test` is called for each `FlexPath` or `RobustPath` in the cell. If its return value evaluates to True, the corresponding label is removed from the cell. | def remove_paths(self, test):
ii = 0
while ii < len(self.paths):
if test(self.paths[ii]):
self.paths.pop(ii)
else:
ii += 1
return self | [
"def remove_labels(self, test):\n ii = 0\n while ii < len(self.labels):\n if test(self.labels[ii]):\n self.labels.pop(ii)\n else:\n ii += 1\n return self",
"def remove(self, path):",
"def clean_up(self, path):\n for path_cell in pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove labels from this cell. The function or callable `test` is called for each label in the cell. If its return value evaluates to True, the corresponding label is removed from the cell. | def remove_labels(self, test):
ii = 0
while ii < len(self.labels):
if test(self.labels[ii]):
self.labels.pop(ii)
else:
ii += 1
return self | [
"def pop_labels(self):\n\t\tself.labels.pop()",
"def remove_label(self):\n\t\tfor l in self.labels:\n\t\t\tl.destroy()",
"def RemoveLabel(self, label):\n if self.labels is None:\n self.labels = set()\n else:\n try:\n self.labels.remove(label)\n excep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the set of datatypes in this cell. Returns | def get_datatypes(self):
datatypes = set()
for element in itertools.chain(self.polygons, self.paths):
datatypes.update(element.datatypes)
for reference in self.references:
datatypes.update(reference.ref_cell.get_datatypes())
return datatypes | [
"def get_datatypes(self):\n datatypes = set()\n for element in self.elements:\n if isinstance(element, PolygonSet):\n datatypes.update(element.datatypes)\n elif isinstance(element, CellReference) or isinstance(\n element, CellArray):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the set of texttypes in this cell. Returns | def get_texttypes(self):
texttypes = set()
for reference in self.references:
texttypes.update(reference.ref_cell.get_textypes())
for label in self.labels:
texttypes.add(label.texttype)
return texttypes | [
"def types(self):\n return [term for term in self._terms\n if isinstance(term, (TypeIdentifier, String, Regex))]",
"def GetCellTypes(self):\n if not self.VTKObject.GetCellTypesArray():\n return None\n return vtkDataArrayToVTKArray(\n self.VTKObject.GetCell... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the set of classes for the SVG representation of this cell. Returns | def get_svg_classes(self):
ld = set()
lt = set()
for element in itertools.chain(self.polygons, self.paths):
ld.update(zip(element.layers, element.datatypes))
for label in self.labels:
lt.add((label.layer, label.texttype))
for reference in self.references:
... | [
"def get_classes(self):\n if self.include_unseen_class and self.fill_unseen_labels:\n return np.append(self.classes_, [self.fill_label_value])\n\n return self.classes_",
"def classes(self):\n return self._classes",
"def getClasses(self):\n self._process()\n return s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write an SVG fragment representation of this object. | def to_svg(self, outfile, scaling, precision, attributes):
outfile.write('<g id="')
outfile.write(self.name.replace("#", "_"))
outfile.write('" ')
outfile.write(attributes)
outfile.write(">\n")
for polygon in self.polygons:
polygon.to_svg(outfile, scaling, pre... | [
"def write_doc(self):\n svg_doc = ET.Element(\n \"svg\",\n width=\"{}mm\".format(10 * self.xdim),\n height=\"{}mm\".format(10 * self.ydim),\n viewBox=\"0 0 {} {}\".format(10 * self.xdim, 10 * self.ydim),\n )\n g = ET.SubElement(svg_doc, \"g\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform a set of polygons. This reference transformation is used to transform the given polygons in place. | def _transform_polygons(self, polygons):
if self.rotation is not None:
ct = numpy.cos(self.rotation * numpy.pi / 180.0)
st = numpy.sin(self.rotation * numpy.pi / 180.0) * _mpone
if self.x_reflection:
xrefl = numpy.array((1, -1))
if self.magnification is not No... | [
"def _transform_polygons(self, polygons):\n if self.rotation is not None:\n ct = numpy.cos(self.rotation * numpy.pi / 180.0)\n st = numpy.sin(self.rotation * numpy.pi / 180.0) * _mpone\n if self.magnification is not None:\n mag = numpy.array((self.magnification, self.m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform a set of polygons. This reference transformation is used to transform the given polygons. | def _transform_polygons(self, polygons):
if self.rotation is not None:
ct = numpy.cos(self.rotation * numpy.pi / 180.0)
st = numpy.sin(self.rotation * numpy.pi / 180.0) * _mpone
if self.magnification is not None:
mag = numpy.array((self.magnification, self.magnificati... | [
"def _transform_polygons(self, polygons):\n if self.rotation is not None:\n ct = numpy.cos(self.rotation * numpy.pi / 180.0)\n st = numpy.sin(self.rotation * numpy.pi / 180.0) * _mpone\n if self.x_reflection:\n xrefl = numpy.array((1, -1))\n if self.magnificatio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rename an existing cell in the library. | def rename_cell(self, cell, name, update_references=True):
if isinstance(cell, Cell):
old_name = cell.name
if old_name not in self.cells:
raise ValueError(
"[GDSPY] Cell named {0} not present in library.".format(old_name)
)
... | [
"def rename(row, new_name):\n # Get the old name\n old_name = Presets.get_name(row)\n\n # If the new name is the same as the old, silently return\n if old_name == new_name:\n return False\n\n # Check so we got a unique name, else return with an error message.\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace cells in all references in the library. All `CellReference` and `CellArray` using the `old_cell` are updated to reference `new_cell`. Matching with `old_cell` is by name only. | def replace_references(self, old_cell, new_cell):
if isinstance(old_cell, Cell):
old_name = old_cell.name
else:
old_name = old_cell
if not isinstance(new_cell, Cell) and new_cell in self.cells:
new_cell = self.cells[new_cell]
replacements = 0
f... | [
"def rename_cell(self, cell, name, update_references=True):\n if isinstance(cell, Cell):\n old_name = cell.name\n if old_name not in self.cells:\n raise ValueError(\n \"[GDSPY] Cell named {0} not present in library.\".format(old_name)\n )... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract a cell from the this GDSII file and include it in the current global library, including referenced dependencies. | def extract(self, cell, overwrite_duplicate=False):
warnings.warn(
"[GDSPY] extract and the use of the global library is deprecated.",
category=DeprecationWarning,
stacklevel=2,
)
import gdspy
cell = self.cells.get(cell, cell)
gdspy.current_li... | [
"def extract(self, cell):\n cell = self.cell_dict.get(cell, cell)\n current_library.add(cell)\n current_library.add(cell.get_dependencies(True))\n return cell",
"def import_cell(self, cell):\n # If the cell is already in the library, skip loading\n if self.cell(cell.name)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the specified cell to the file. | def write_cell(self, cell, timestamp=None):
cell.to_gds(self._outfile, self._res, timestamp)
return self | [
"def write_cell(self, cell):\n self._outfile.write(cell.to_gds(self._res))\n return self",
"def __writeValue(self, row_number, col_name, value):\n self.worksheet.update_cell(row_number, COL_INDEXES[col_name], value)",
"def writefile(self, filename):\n with open(filename, \"wb\") as gridf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the specified binary cells to the file. | def write_binary_cells(self, binary_cells):
for bc in binary_cells:
self._outfile.write(bc)
return self | [
"def write_df_to_binary(file_name_mask, df):\n write_matrix_to_binary(file_name_mask + '-value.bin', df.values)\n with open(file_name_mask + '-name.txt', 'w') as f:\n f.write(\"\\t\".join(df.index))\n f.write(\"\\n\")\n f.write(\"\\t\".join(df.columns))\n f.write(\"\\n\")",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the unit and precision used in the GDS stream file. | def get_gds_units(infile):
close = True
if hasattr(infile, "__fspath__"):
infile = open(infile.__fspath__(), "rb")
elif isinstance(infile, (basestring, Path)):
infile = open(infile, "rb")
else:
close = False
unit = precision = None
for rec_type, data in _raw_record_reader... | [
"def get_precision():\n return K.precision",
"def unit_of_measurement(self):\n\t\treturn self._unit_of_measurement",
"def GetDataPrecision():\n return _gmat_py.GmatBase_GetDataPrecision()",
"def get_observed_precision(self):\n return self.get_precision()",
"def getvalue(self,param,unit):\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load all cells from a GDSII stream file in binary format. | def get_binary_cells(infile):
close = True
if hasattr(infile, "__fspath__"):
infile = open(infile.__fspath__(), "rb")
elif isinstance(infile, (basestring, Path)):
infile = open(infile, "rb")
else:
close = False
cells = {}
name = None
cell_data = None
for rec_type,... | [
"def load(datastream):",
"def _read_binary(self, dtype):\n # NOTE: binary files store binned data using Fortran-like ordering.\n # Dimensions are iterated like z, y, x (so x changes fastest)\n\n header_path = self.path + 'header'\n with open(header_path) as f_header:\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the product of this SubscriptionProductRetirement. | def product(self, product):
self._product = product | [
"def product(self, product):\n self._product = product",
"def setProduct(self, product):\n # First we delete an old reference. (This is used for changing \n # properties/variants within cart)\n self.deleteReferences(\"cartitem_product\")\n self.addReference(product, \"cartitem_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the respect_terminiation_periods_enabled of this SubscriptionProductRetirement. | def respect_terminiation_periods_enabled(self):
return self._respect_terminiation_periods_enabled | [
"def respect_terminiation_periods_enabled(self, respect_terminiation_periods_enabled):\n\n self._respect_terminiation_periods_enabled = respect_terminiation_periods_enabled",
"def evaluation_periods(self) -> Optional[int]:\n return pulumi.get(self, \"evaluation_periods\")",
"def periods(self):\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the respect_terminiation_periods_enabled of this SubscriptionProductRetirement. | def respect_terminiation_periods_enabled(self, respect_terminiation_periods_enabled):
self._respect_terminiation_periods_enabled = respect_terminiation_periods_enabled | [
"def respect_terminiation_periods_enabled(self):\n return self._respect_terminiation_periods_enabled",
"def return_periods(self, return_periods):\n\n self._return_periods = return_periods",
"def evaluation_periods(self) -> Optional[int]:\n return pulumi.get(self, \"evaluation_periods\")",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the target_product of this SubscriptionProductRetirement. | def target_product(self):
return self._target_product | [
"def target_for_product(self, product):\n for target, products in self._products_by_target.items():\n if product in products:\n return target\n return None",
"def target_resource(self):\n return self._target_resource",
"def product(self):\n return self._product",
"def getProduc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the target_product of this SubscriptionProductRetirement. | def target_product(self, target_product):
self._target_product = target_product | [
"def target_resource(self, target_resource):\n\n self._target_resource = target_resource",
"def target_resource(self, target_resource):\n self._target_resource = target_resource",
"def product(self, product):\n\n self._product = product",
"def target_product(self):\n return self._t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a module for converting to two theta | def pixels_two_theta_module(id=None, datatype=None, action=None,
version='0.0', fields=[], xtype=None, **kwargs):
icon = {
'URI': config.IMAGES + config.ANDR_FOLDER + "twotheta.png",
'image': config.IMAGES + config.ANDR_FOLDER + "twotheta_image.png",
'terminals': {
... | [
"def make_theta_gen():\n #Will allow angle between 0 and 180 degrees (in radians)\n return stats.uniform(loc=0, scale=3.14159)",
"def create_rbt(omega, theta, trans):\n #YOUR CODE HERE\n\n R = rotation_3d(omega,theta)\n p = np.matrix(trans).T\n g1 = np.append(R,p,1)\n b = np.matrix([0,0,0,1])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds and compiles an LSTM model with the provided hyperparameters | def build_lstm_model(num_features,
embedding_size=None,
kernel_size=None,
filters=None,
pool_size=None,
lstm_output_size=None):
# Embedding
if embedding_size is None:
embedding_size = 64
# Convo... | [
"def LSTM_train(X_train, Y_train, X_dev, Y_dev, R_train, R_dev, hyperparams):",
"def train_lstm_model():\n\ttexts, _ = data.data_util.load_text_with_specific_label(\n\t\tDEFAULT_FILE_NAME,\n\t\tdata.data_util.FbReaction.LIKE_INDEX\n\t)\n\tsequences, num_words, index_to_word, word_to_index = text_tokenizer.get_tex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds and compiles an GRU model with the provided hyperparameters | def build_gru_model(num_features,
embedding_size=None,
kernel_size=None,
filters=None,
pool_size=None,
gru_output_size=None):
# Embedding
if embedding_size is None:
embedding_size = 64
# Convolu... | [
"def compile_gru_model(input_dim=101, output_dim=4563, recur_layers=3, nodes=1000,\n conv_context=11, conv_border_mode='valid', conv_stride=2,\n initialization='glorot_uniform', batch_norm=True, num_gpu=1):\n logger.info(\"Building gru model\")\n # Main acoustic input... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create bitmap from given unicode character, return image file object. | def create_unicode_image(unicode_character):
# Check the cache
if unicode_character in unicode_cache.keys():
return unicode_cache[unicode_character]
# Initialize canvas and font parameters
# Credit: JackNova (until URL)
width = 10
height = 20
background_color=(0,0,0)
font_size=2... | [
"def get_font_image(self, char):\n im = Image.new(\"RGB\", (self.size, self.size), (255, 255, 255))\n dr = ImageDraw.Draw(im)\n font = ImageFont.truetype(self.input_path, self.size)\n dr.text((0, self.y_offset), char, font=font, fill=\"#000000\")\n im = im.convert('1')\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ingest a file and slice it into 10x20 bitmaps which are compared with bitmaps of unicode charcters. The most similar character is printed with x256 color which is most like the average color for the 10x20 bitmap slice. | def print_image_as_unicode(image_file, **kwargs):
char_set = kwargs['char_set']
x256_mode = kwargs['x256']
height = 20 # height of unicode character
width = 10 # width of the unicode characters we are using
# Credit ElTero and ABM (https://stackoverflow.com/a/7051075)
if image_file == '-':
... | [
"def imagesplit(self, pixmap_index=0, width=8, height=8, count_x=1, count_y=1, margin=0, chars=[], ignore_empty=True):\r\n if(len(self.pixmap) == 0):\r\n return False\r\n if(len(chars) == 0):\r\n chars = [\r\n \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter a `items` list according to a list of `queries`. Values from `items` are kept if they match at least one query. The original `items` list is untouched but the result list uses the same data (not a deep copy). If `attribute` is None, it is assumed that `items` is a list of strings to be filtered directly. If `att... | def stringfilter(items, queries, attribute=None):
result = []
if attribute is not None:
key_path = attribute.split('.')
else:
key_path = None
for item in items:
if key_path is not None:
string = _get_nested_value(item, key_path)
if not isinstance(string, ... | [
"def itemFilterAttr(*args, **kwargs):\n\n pass",
"def _filter_by_attribute(self, context, refs, attr):\n if attr in context['query_string']:\n value = context['query_string'][attr]\n return [r for r in refs if r[attr] == value]\n return refs",
"def itemFilterAttr(*args, by... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get value under `key_path` key in `dct` dictionary. `key_path` is a list of keys to be traversed into a potentially nested `dct` dictionary. | def _get_nested_value(dct, key_path):
key = key_path[0]
if not isinstance(dct, dict):
raise errors.AnsibleFilterError(
f"stringfilter: looking for key '{key}' "
f"but list item is not dict: {pformat(dct)}"
)
if key not in dct:
raise errors.AnsibleFilterError(
... | [
"def get_from_dict(dct: Dict, path: str, *default: Any) -> Any:\n curr = dct\n for part in path.split('.'):\n if part in curr:\n curr = curr[part]\n elif default:\n return default[0]\n else:\n raise KeyError(f\"'{path}' not found in dict: {pformat(dct)}\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests whether the trace for step methods is exactly the same as on master. Code changes that effect how random numbers are drawn may change this, and require `master_samples` to be updated, but such changes should be noted and justified in the commit. This method may also be used to benchmark step methods across commit... | def check_trace(self, step_method):
n_steps = 100
with Model():
x = Normal('x', mu=0, sd=1)
if step_method.__name__ == 'SMC':
Deterministic('like', - 0.5 * tt.log(2 * np.pi) - 0.5 * x.T.dot(x))
trace = smc.ATMIP_sample(n_steps=n_steps, step=step_me... | [
"def test_run_repeatability(self):\n self.assertEqual(TestTrain.hash_100_steps_1, TestTrain.hash_100_steps_2)",
"def check_trace(self, step_method):\n n_steps = 100\n with Model() as model:\n x = Normal('x', mu=0, sd=1)\n if step_method.__name__ == 'SMC':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that samplers correctly create nonblocked compound steps. | def test_non_blocked(self):
_, model = simple_2model()
with model:
for sampler in self.samplers:
assert isinstance(sampler(blocked=False), CompoundStep) | [
"def test_non_blocked(self):\n _, model = simple_2model_continuous()\n with model:\n for sampler in self.samplers:\n assert isinstance(sampler(blocked=False), CompoundStep)",
"def test_block_bad_batch(self):\n pass",
"def test_block_missing_batch(self):\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test bernoulli distribution is assigned binary gibbs metropolis method | def test_bernoulli(self):
with Model() as model:
Bernoulli('x', 0.5)
steps = assign_step_methods(model, [])
assert isinstance(steps, BinaryGibbsMetropolis) | [
"def bernoulli(p):\r\n if np.random.random() < p:\r\n return 0\r\n else:\r\n return 1",
"def bernoulli_num(n):\n return mp.bernoulli(n)",
"def bernoulli(n):\n\n x, res, s, c = Rat(0), Rat(0), Rat(0), Rat(-1)\n for k in range(1, n+2):\n c *= 1 - Rat(n + 2)/k\n s += x**n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test binomial distribution is assigned metropolis method. | def test_binomial(self):
with Model() as model:
Binomial('x', 10, 0.5)
steps = assign_step_methods(model, [])
assert isinstance(steps, Metropolis) | [
"def test_against_binomial_processes(self):\n\n compare_against_binomial(1.0, (32, ))\n compare_against_binomial(2.9, (47, ))\n compare_against_binomial(4.5, (6, ))",
"def test_bernoulli(self):\n with Model() as model:\n Bernoulli('x', 0.5)\n steps = assign_step_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that, for the given service, the video_id is valid. | def clean_video_id(self):
failed = False
d = self.cleaned_data
service = d.get('service')
# Get the video id and clear whitespace on either side.
video_id = d.get('video_id', '').strip()
# Validate using YouTube's API:
if service == 'youtube':
url = (... | [
"def validate_video(form, video):\n if \"youtube.com\" in video.data or \"youtu.be\" in video.data or \"vimeo.com\" in video.data:\n try:\n video_test = requests.get(video.data)\n if video_test.status_code != 200:\n raise ValidationError('Invalid video URL, please try ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes coverage rate for `y_pred`. | def coverage(y_true, y_pred):
m = tf.shape(y_pred)[1] - tf.constant(1, dtype=tf.int32)
n_samples = tf.cast(tf.shape(y_pred)[0], tf.float32)
n_abstain = tf.reduce_sum(
tf.where(tf.argmax(y_pred, axis=1, output_type=tf.int32) == m, 1.0, 0.0)
)
return tf.constant(1.0) - n_abstain / n_samples | [
"def score(self, y_true, y_pred):\n print(\"y_true\", y_true)\n print(\"y_pred\", y_pred)\n\n return roc_auc_score(y_true, y_pred)",
"def scorer(y_true, y_pred, **kwargs) -> float:\n return sklearn_accuracy_score(y_true, y_pred, **kwargs)",
"def scorer(y_true, y_pred, **kwargs) -> fl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View products in Cart. | def index(self, user):
cart_products = CartProduct.index(user)
CartProductsView.index(cart_products) | [
"def products(request):\n\n if not request.user.is_superuser:\n messages.error(request, 'Sorry, only store owners can do that.')\n return redirect(reverse('home'))\n\n products = Product.objects.all()\n template = \"auctionsmng/products.html\"\n\n context = {\n 'products': products\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yield the classes in module ``mod`` that inherit from ``cls`` | def get_subclasses(mod, cls):
for name, obj in inspect.getmembers(mod):
if hasattr(obj, "__bases__") and cls in obj.__bases__:
yield obj | [
"def classes(self):\n m = self.module\n for m in self.modules():\n for klass_name, klass in inspect.getmembers(m, inspect.isclass):\n yield klass",
"def _classesToCheck(self, cls):\r\n yield cls\r\n yield from inspect.getmro(cls)",
"def get_classes(*cls_or_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A main function to run the simulation | def Main():
numberOfPopulation = 350
numberOfDays = 60
simulation = Simulation(Covid19(), numberOfPopulation, numberOfDays, "Covid 19 Simulation")
simulation.run()
simulation = Simulation(Ebola(), numberOfPopulation, numberOfDays, "Ebola Simulation")
simulation.run() | [
"def run(self, simulation):",
"def run():\n\n e = Environment() # create environment (also adds some dummy traffic)\n a = e.create_agent(QLearningAgent) # create agent\n e.set_primary_agent(a, enforce_deadline=True) # set agent to track\n # Now simulate it\n sim = Simulator(e, update_delay=0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses the readings from all nodes to report the mean and standard deviation of all nodes | def get_network_reading(self):
# update the readings for all nodes
self.update_all_readings()
# get the current readings from all nodes
node_readings = []
for node_name in self.nodes:
node_readings.append(self.nodes[node_name].stable_reading)
node_readings... | [
"def compute_training_stats():\n means, stds = [], []\n data = SUNRGBDTrainDataset(True)\n for i in range(len(data)):\n print(i)\n img, _ = data[i]\n std, mean = t.std_mean(input=img, dim=(1, 2))\n means.append(mean)\n stds.append(std)\n means = t.sum(t.vstack(means), ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator that returns the names of all nodes in the network | def node_names(self):
for node_name in self.nodes.keys():
yield node_name | [
"def get_nodes(self):\n return [self._nodes[j].get_name() for j in range(self._n_nodes)]",
"def nodeNames(self):\n return self.nodes.keys()",
"def get_node_names(self) -> List[str]:\n\t\t# Variables\n\t\tnames: List[str] = []\n\n\t\t# Iterate over nodes\n\t\tfor node in self.nodes:\n\t\t\tnames.ap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets average position of all nodes in the network | def get_network_average_position(self):
# the total number of nodes in the network
num_nodes = self.total_nodes()
# get the location of all nodes
all_nodes = np.empty((num_nodes, R_space))
for index, item in enumerate(self.nodes.values()):
all_nodes[index] = item.ge... | [
"def mean_nodes_point(ns):\n\n xs = [n.P[0] for n in ns]\n ys = [n.P[1] for n in ns]\n zs = [n.P[2] for n in ns]\n\n return sum(xs) / len(xs), sum(ys) / len(ys), sum(zs) / len(zs)",
"def mean_average_position():\n pass",
"def streets_per_node_avg(G):\n spn_vals = streets_per_node(G).values()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the nodes with the lowest and highest number of neighbors | def get_interest_nodes(self):
# go through each node in the network to find the min and max degrees
max_value = 0
min_value = len(self.nodes)
for name in self.nodes:
# check for new max
if self.nodes[name].get_degree() >= max_value:
max_value = s... | [
"def neighbors(self, n):\n return self.graph[n]",
"def neighbours(self):\n return [x.node for x in self.edges]",
"def get_neighbours(self):\n return self.neighbours",
"def calculate_neighbours(self):\n mm_atoms = to_molmod(self)\n neighbours = mm_atoms.graph.neighbors\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Esta función es recursivo. Recibe un valor de X Y evalua el valor de su gama Regresa el valor de gama | def gama(self,x):
if x==1:
return 1
elif x == 0.5:
return math.sqrt(math.pi)
else:
return (x-1)*self.gama(x-1) | [
"def compute_Graam(self, X):\n pass",
"def grau(self, v):\n # O loop percorre cada linha e cada coluna da matriz até a posição do vértice do parâmetro.\n # Então, soma o valor/quantidade das arestas conectadas aquele vértice, e adiciona-o a variável grau para depois\n # retorná-la.\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recibe el numero de segmentos y el valor de W Esta es la funcion de sumatoria para los numeros Impares Regresa el total de la sumatoria | def sumaImpar(self,numSeg,w):
total=0
for i in range(1,numSeg,2):
total+=4*self.F(i*w)
return total | [
"def sumaPar(self,numSeg,w):\n total=0\n for i in range(2,numSeg-1,2):\n total+=2*self.F(i*w)\n return total",
"def patrimony_total(self):\n pass",
"def sumidouro(c_infil, n_contri, contri_despejos, contri_lodo, p_retencao, t_acumulacao):\r\n area_infil = (tanque_septic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recibe el numero de segmentos y el valor de W Esta es la funcion de sumatoria para los numeros Pares Regresa el total de la sumatoria | def sumaPar(self,numSeg,w):
total=0
for i in range(2,numSeg-1,2):
total+=2*self.F(i*w)
return total | [
"def patrimony_total(self):\n pass",
"def sumaImpar(self,numSeg,w):\n total=0\n for i in range(1,numSeg,2):\n total+=4*self.F(i*w)\n return total",
"def calcular_precio_total(self):\n\t\tsuma=0\n\t\tfor linea in detalle_pedido:\n\t\t\tsuma+= linea.subtotal\n\t\tself.total=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a decorator which will parse a gerber file before running the test. | def use_file(filename):
def decorator(test_method):
""" Add params to decorator function. """
@wraps(test_method)
def wrapper(self):
""" Parse file then run test. """
parser = Gerber(ignore_unknown=False)
self.design = parser.parse(path.join(DIR, filenam... | [
"def test_gen_parser(self):\n pass",
"def test_basic_parsers():",
"def test_create_new_gerber_parser(self):\n parser = Gerber()\n assert parser != None",
"def test_config(config_file):\n\n def test_decorator(fn):\n \"\"\"Decorate function.\"\"\"\n fn.config_file = config_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an empty gerber parser. | def test_create_new_gerber_parser(self):
parser = Gerber()
assert parser != None | [
"def _make_parser(self):\n return DefusedExpatParser()",
"def _create_parser() -> Parser:\n parser = Parser(replace_cosmetic=False)\n\n _add_code_formatter(parser)\n _add_image_formatter(parser)\n _add_quote_formatter(parser)\n\n return parser",
"def __init__(self, parser: Any = None):",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The Modifier can evaluate expressions correctly. | def test_modifier(self):
modif = Modifier('1.2')
self.assertEqual(modif.evaluate({}), 1.2)
modif = Modifier('$1')
self.assertEqual(modif.evaluate({1:3.2}), 3.2)
modif = Modifier('1+1')
self.assertEqual(modif.evaluate({}), 2)
modif = Modifier('3-1.5')
self.... | [
"def evaluate(compiled_expression):",
"def test_expression_sanitizer(self):\n\n self.assertFalse(_is_math_expr_safe('INSERT INTO students VALUES (?,?)'))\n self.assertFalse(_is_math_expr_safe('import math'))\n self.assertFalse(_is_math_expr_safe('complex'))\n self.assertFalse(_is_math_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Trap coord preceding gerber format spec. | def test_coord_preceding_fs(self): | [
"def _FormatBarrierLocation(self):\r\n return '%s:%d' % (self._filename, self._lineno)",
"def format_coord(self, th, r):\n return 'time=' + angle_to_time(th) + ', val=%1.0f'%(r) # TODO: units on val?",
"def get_local_xy(self, chip):",
"def _tra(self, coord, amount):\n return coord + amount",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unsubscribe events for a callback. | def unsubscribe(callback):
if callback in _subscribers:
del _subscribers[callback] | [
"def unsubscribe(self, callback):\n raise NotImplementedError",
"def unsubscribe(self, callback):\n\n if callback in self._subscribers:\n self._subscribers.remove(callback)",
"def unsubscribe(self, event_type: typing.Type[typing.Any], callback: CallbackT[typing.Any]) -> None:",
"def u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate mean of role/token embeddings for a node. | def _mean_vec(self, node) -> Tuple[np.array, int]:
tokens = [t for t in chain(node.token, ("RoleId_%d" % role for role in node.roles))
if t in self.emb]
if not tokens:
return None, 0
return np.mean([self.emb[t] for t in tokens], axis=0), len(tokens) | [
"def compute_mean(self):\n # load_in_all_parameters(self.save_directory, self.auto_encoder)\n for i, data_row in enumerate(self.X_train_naive):\n input_nn = data_row\n if torch.cuda.is_available():\n input_nn = Variable(torch.Tensor(np.asarray(input_nn).reshape(1, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert UAST into feature and label arrays. Had to be defined outside of RolesMLP so that we don't suppply `self` twice. | def _process_uast(self, filename: str) -> Tuple[np.array, np.array]:
X, y = [], []
uast_model = UASTModel().load(filename)
for uast in uast_model.uasts:
child_vecs, parent_vecs = self._mean_vecs(uast)
for node, node_idx in node_iterator(uast):
child_vec = child_vecs[node_idx]
... | [
"def _convert_to_features(self, img: np.ndarray) -> np.ndarray:",
"def gen_features(self, X):",
"def _seqs_to_train(self, seqs):\n X = []\n Y = []\n for seq in seqs:\n for token in seq:\n features = token.strip().split()\n X.append({i:xi for (i, xi) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
on_load is called when a objects is instantiated from database | def on_load(self):
self.__init__() | [
"def on_loaded(self):\n pass",
"def _post_load(self):\n pass",
"def on_class_loaded(cls):\n\n on_class_loaded.cls = cls",
"def on_loaded(self, func):\n self._on_loaded_funcs.append(func)",
"def post_init(self):\n pass",
"def on_load(self, bot):\n self.bot = bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return column number of first zombie in row. | def first_zombie_col(self, row_num):
row = self.board[row_num]
for col_num, square in enumerate(row):
if any(self.is_zombie([row_num, col_num])):
return col_num | [
"def __find_prime_in_row(self, row):\r\n col = -1\r\n for j in range(self.n):\r\n if self.marked[row][j] == 2:\r\n col = j\r\n break\r\n\r\n return col",
"def get_colnumber(self, header):\n for i in range(0, len(self.data)):\n if self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes an item from it's 2D location on the board. | def del_item(self, item):
index = self.board[item.pos[0]][item.pos[1]].index(item)
del self.board[item.pos[0]][item.pos[1]][index] | [
"def delItem(self,row,column):\n data = self.data\n if row in data and column in data[row]:\n del data[row][column]\n self.hasChanged = True",
"def remove_cell(self, x, y):\n pass",
"def remove(self, item):\n entry = self.entry_finder.pop(item)\n entry[-1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly add new Zombie to board | def spawn(self):
new_zombie_lvl = random.randint(0, min(self.level, 3))
_ = Zombie(new_zombie_lvl, [random.randint(0, 4), 99], self.board)
self.zombie_spawn_delay = random.randint(*self.zombie_spawn_delay_range) | [
"def spawn(cls):\n new_zombies = random.randint(1, Zombie.plague_level)\n count = 0\n\n while count < new_zombies:\n speed = random.randint(1, Zombie.max_speed)\n strength = random.randint(1, Zombie.max_strength)\n Zombie.horde.append(Zombie(speed, strength))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If there is a Sun at a position, convert it to player gold. | def try_collecting(self, event):
sun_list = [i for i in self.board[event.pos] if isinstance(i, Sun)]
if sun_list:
sun_list[0].collected = True
self.player.gold += Sun.gold
self.ev_manager.post(events.SunCollected(self.player.gold)) | [
"def SUN_POS():\n LIST=[]\n loc = coord.EarthLocation(lon=28.7134 * u.deg,\n lat=17.9058 * u.deg)\n\n start = Time(datetime.utcnow(), format='datetime', scale='utc') - TimeDelta(1, format='jd')\n\n for i in range(0,384):\n T = start+TimeDelta(i*225, format='sec')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the Salesforce location strategies 'text' and 'title' plus any strategies registered by other keyword libraries | def initialize_location_strategies(self):
locator_manager.register_locators("sf", lex_locators)
locator_manager.register_locators("text", "Salesforce.Locate Element by Text")
locator_manager.register_locators("title", "Salesforce.Locate Element by Title")
# This does the work of actuall... | [
"def __initialization(self):\n print(\"Initialize default 'lime', 'cle', 'anchor' explainers. \" + \n \"Please explicitly initialize 'shap' explainer before use it.\")\n self.explainers['lime'] = XDeepLimeTextExplainer(self.predict_proba, self.class_names)\n self.explainers['cle'] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the locale for fake data This sets the locale for all calls to the ``Faker`` keyword and ``${faker}`` variable. The default is en_US For a list of supported locales see | def set_faker_locale(self, locale):
try:
self._faker = faker.Faker(locale)
except AttributeError:
raise Exception(f"Unknown locale for fake data: '{locale}'") | [
"def with_locale_en_us():\n orig = locale.getlocale()\n yield load_locale(\"en_US\")\n locale.setlocale(locale.LC_ALL, orig)",
"def setupLocale():",
"def setLocale(self, loc):\r\n locale.setlocale(locale.LC_ALL, loc)",
"def setLocale(self, value):\n return self._set(locale=value)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call the Create Webdriver keyword. Retry on connection resets which can happen if custom domain propagation is slow. | def create_webdriver_with_retry(self, *args, **kwargs):
# Get selenium without referencing selenium.driver which doesn't exist yet
selenium = self.builtin.get_library_instance("SeleniumLibrary")
for _ in range(12):
try:
return selenium.create_webdriver(*args, **kwargs... | [
"def create_driver(self, error = None):\n # Send mail and take screenshot if an error was found\n if error is True:\n if self.fail_counter >= self.MIN_FAIL_TO_SEND_EMAIL:\n self.send_mail(ScraperEmail.ERROR_MESSAGE, self.fail_counter)\n self.screenshot()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scrolls down until the specified related list loads. | def load_related_list(self, heading):
locator = lex_locators["record"]["related"]["card"].format(heading)
el = None
i = 0
while el is None:
i += 1
if i > 50:
raise AssertionError(
"Timed out waiting for {} related list to load."... | [
"def scroll_to_end_by_class_name(driver, class_name, number_requested):\r\n eles = driver.find_elements_by_class_name(class_name)\r\n count = 0\r\n new_count = len(eles)\r\n\r\n while new_count != count:\r\n try:\r\n utils.update_progress(new_count / number_requested, f' - Scrolling... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clicks a button in the heading of a related list. Waits for a modal to open after clicking the button. | def click_related_list_button(self, heading, button_title):
self.load_related_list(heading)
locator = lex_locators["record"]["related"]["button"].format(
heading, button_title
)
self._jsclick(locator)
self.wait_until_modal_is_open() | [
"def click_modal_button(self, button_label):\n # stolen from Salesforce.py:click_modal_button\n locator = f\"sf:modal.button:{button_label}\"\n self.selenium.wait_until_page_contains_element(locator)\n self.selenium.wait_until_element_is_enabled(locator)\n self.salesforce._jsclick... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clicks a link in the related list with the specified heading. This keyword will automatically call Wait until loading is complete. | def click_related_item_link(self, heading, title):
self.load_related_list(heading)
locator = lex_locators["record"]["related"]["link"].format(heading, title)
try:
self._jsclick(locator)
except Exception as e:
self.builtin.log(f"Exception: {e}", "DEBUG")
... | [
"def click_related_item_popup_link(self, heading, title, link):\n self.load_related_list(heading)\n locator = lex_locators[\"record\"][\"related\"][\"popup_trigger\"].format(\n heading, title\n )\n\n self.selenium.wait_until_page_contains_element(locator)\n self._jsclic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clicks a link in the popup menu for a related list item. heading specifies the name of the list, title specifies the name of the item, and link specifies the name of the link | def click_related_item_popup_link(self, heading, title, link):
self.load_related_list(heading)
locator = lex_locators["record"]["related"]["popup_trigger"].format(
heading, title
)
self.selenium.wait_until_page_contains_element(locator)
self._jsclick(locator)
... | [
"def click_related_item_link(self, heading, title):\n self.load_related_list(heading)\n locator = lex_locators[\"record\"][\"related\"][\"link\"].format(heading, title)\n try:\n self._jsclick(locator)\n except Exception as e:\n self.builtin.log(f\"Exception: {e}\", ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the open modal | def close_modal(self):
locator = lex_locators["modal"]["close"]
self._jsclick(locator) | [
"def close_the_modal(self):\n\n locator = \"css: button.slds-modal__close\"\n self.selenium.wait_until_element_is_enabled(locator)\n self.selenium.click_element(locator)\n self.wait_until_modal_is_closed()\n self._remove_from_library_search_order()",
"def onBtnCloseClicked(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes records that were created while running this test case. (Only records specifically recorded using the Store Session Record keyword are deleted.) | def delete_session_records(self):
self._session_records.reverse()
self.builtin.log("Deleting {} records".format(len(self._session_records)))
for record in self._session_records[:]:
self.builtin.log(" Deleting {type} {id}".format(**record))
try:
self.sales... | [
"def test_delete_records(self):\n pass",
"def delete_record(records):\n delete_record()",
"def delete_test_data(session_maker):\n\n orm_session = session_maker()\n orm_session.query(USERS).filter(USERS.username.like('%test%')).delete(synchronize_session=False)\n orm_session.query(USER_POSTS).... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the id of all open browser ids | def get_active_browser_ids(self):
# This relies on some private data structures, but presently
# there is no other way. There's been a discussion in the
# robot slack channels about adding a new keyword that does
# what this keyword does. When that happens, we can remove
# this ... | [
"def getAllWindowHandles(self):\n cmdId = self.executeCommand(Command.GET_WINDOW_HANDLES)\n return cmdId",
"def get_opened_windows_list():\n\n global opened_windows_names\n EnumWindows(EnumWindowsProc(foreach_window), 0)\n return opened_windows_names",
"def window_handles(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the current url to get the object id of the current record. | def get_current_record_id(self):
url = self.selenium.get_location()
for part in url.split("/"):
oid_match = re.match(OID_REGEX, part)
if oid_match is not None:
return oid_match.group(2)
raise AssertionError("Could not parse record id from url: {}".format(u... | [
"def get_id(url):\n\n return re.search(GET_ID_REGEX_URL, url)[0]",
"def get_record_id(uri):\n return urlparse(uri).path.split(\"/\")[-1]",
"def get_id(self, resource):\n try:\n return resource.href.split('/')[-1]\n except AttributeError:\n return resource['href'].sp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the current value of a form field based on the field label | def get_field_value(self, label):
input_element_id = self.selenium.get_element_attribute(
"xpath://label[contains(., '{}')]".format(label), "for"
)
value = self.selenium.get_value(input_element_id)
return value | [
"def get_label_field(self):\n\n return self.label_field",
"def form_value(self):\n if self.form and self.layout: # There must be rendered form widgets.\n if self.form == Inputs.TEXTBOX:\n return self.textbox.text\n elif self.form == Inputs.TEXTAREA:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a rendered locator string from the Salesforce lex_locators dictionary. This can be useful if you want to use an element in a different way than the built in keywords allow. | def get_locator(self, path, *args, **kwargs):
locator = lex_locators
for key in path.split("."):
locator = locator[key]
return locator.format(*args, **kwargs) | [
"def _locator_string(self, locator):\n return '(\"{0}\", \"{1}\")'.format(*locator)",
"def locator(self):\n return (self.by, self.locator_str)",
"def deprecated_locator_ids():\n return strategies.text(\n alphabet=unicode_letters_and_digits() | strategies.sampled_from(\"-~.:%\"),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the Record Type Id for a record type name | def get_record_type_id(self, obj_type, developer_name):
soql = "SELECT Id FROM RecordType WHERE SObjectType='{}' and DeveloperName='{}'".format(
obj_type, developer_name
)
res = self.cumulusci.sf.query_all(soql)
return res["records"][0]["Id"] | [
"def __get_type_id(record: TNSRecord) -> int:\n return ObjectType.get_or_create(record.type or 'Unknown').id",
"def get_type_id(self, name: '_types.QualifiedNameType') -> str:\n\t\t_name = _types.QualifiedName(name)._to_core_struct()\n\t\treturn core.BNGetAnalysisTypeId(self.handle, _name)",
"def record_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of items indicated for a related list. | def get_related_list_count(self, heading):
locator = lex_locators["record"]["related"]["count"].format(heading)
count = self.selenium.get_webelement(locator).text
count = count.replace("(", "").replace(")", "")
return int(count) | [
"def count_items(self):\n count = 0\n for o in self.order_lst:\n count += o.count()\n \n return count",
"def number_of_items(self):",
"def _items_count(self, queryset: QuerySet) -> int:\n try:\n # forcing to find queryset.count instead of list.count:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |