query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
The source of the dataset. | def source(self) -> DatasetSource:
return self._source | [
"def data_source(self):\n return self.__data_source",
"def data_source(self):\n for ds in self._data_sources.values():\n return ds\n return None",
"def source_datasets(self):\n return self._source_datasets",
"def source_dataset_id(self):\n return self._source_data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MLflow TensorSpec schema representing the dataset features and targets (optional). | def schema(self) -> Optional[TensorDatasetSchema]:
try:
features_schema = _infer_schema(self._features)
targets_schema = None
if self._targets is not None:
targets_schema = _infer_schema(self._targets)
return TensorDatasetSchema(features=features_s... | [
"def _to_tf_example_spec(tensor_info: feature_lib.TensorInfo):\n # Convert the dtype\n\n # TODO(b/119937875): TF Examples proto only support int64, float32 and string\n # This create limitation like float64 downsampled to float32, bool converted\n # to int64 which is space ineficient, no support for complexes o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the dataset to a collection of pyfunc inputs and outputs for model evaluation. Required for use with mlflow.evaluate(). | def to_pyfunc(self) -> PyFuncInputsOutputs:
return PyFuncInputsOutputs(self._features, self._targets) | [
"def input_fn():\n dataset = tf.contrib.data.make_batched_features_dataset(\n file_pattern=transformed_examples,\n batch_size=batch,\n features=tf_transform_output.transformed_feature_spec(),\n reader=tf.data.TFRecordDataset,\n shuffle=True,\n )\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the dataset to an EvaluationDataset for model evaluation. Required for use with mlflow.sklearn.evalute(). | def to_evaluation_dataset(self, path=None, feature_names=None) -> EvaluationDataset:
return EvaluationDataset(
data=self._features,
targets=self._targets,
path=path,
feature_names=feature_names,
) | [
"def get_eval_data() -> GraphDataset:\n _load_data_if_needed()\n return eval_data",
"def evaluate(self, dataset):\n\t\tpass",
"def evaluate(self, dataset):\n return self.model.evaluate(dataset.X_val, dataset.y_val)",
"def load_eval_datasets(cfg):\n # Temporarily change dataset type to be f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the first task instance that is a module node. | def get_module_task_instance_id(task_instances):
for id in task_instances:
if task_instances[id] == 'module_node':
return id
return None | [
"def _get_module_instance(node: torch._C.Node,\n node_name_to_module: Dict[str, torch.nn.Module]) -> torch.nn.Module:\n input_name: str = node.input().debugName()\n attributes = _get_attribute_name(node)\n model = node_name_to_module[input_name]\n sub_model = getattr(model, attri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map the mode parameter to the server parameter | def get_mode_parameter(mode):
if mode == 'job':
return 'cli'
elif mode == 'serve':
return 'serving'
else:
return mode | [
"def setMode(self, mode='04'):\r\n reply = self.sendMessage('MDS,%s' %mode)\r\n return self.checkOK(reply)",
"def _convert_mode(self, mode):\r\n if mode in self.map_atstr_id:\r\n at = self.get_agent_type(mode)\r\n return at.get_name(), mode\r\n\r\n if mode in self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new payment profile for the customer. | def create_payment_profile(self, cr, uid, ids, context=None):
parent_model = context.get('active_model')
parent_id = context.get('active_id')
partner_obj = self.pool.get('res.partner')
if parent_model == 'res.partner':
partner = self.pool.get(parent_model).browse(cr, uid, par... | [
"def test_create_payment_profile(self):\n self.cim.create_payment_profile(\n customer_profile_id=u'300',\n customer_type=u'individual',\n card_number=u'42222222222',\n expiration_date=u'2009-10'\n )",
"def create_payment_profile(self):\n Invoice = P... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
to initialise appium session | def appium_init(self):
desired_cups = {}
desired_cups['platformName'] = 'Android'
desired_cups['platformVersion'] = android_version
desired_cups['deviceName'] = device_name
desired_cups['appPackage'] = pkg_name
desired_cups['appActivity'] = activity
desired_cups['... | [
"def setup(self):\n\n caps = {}\n caps[\"platformName\"] = \"Android\"\n caps[\"automationName\"] = \"uiautomator2\"\n caps[\"deviceName\"] = \"xiaomi-mi_5s-238c8e2f\"\n# \"\"\"hogwarts\"\n\n caps[\"appPackage\"] = \"com.xueqiu.android\"\n caps[\"appActivity\"] = \".view.We... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialise Sequence with a string. The string must only contain letters in the set a,A,c,C,g,G,t,T. | def __init__(self, sequence=""):
assert Sequence.is_valid(sequence), \
"Sequence should only contain A, C, G and T"
self._nucleotides = sequence.upper() # 处理对象.方法 | [
"def __init__(self, length, alphabet=IUPAC.unambiguous_dna):\n seq_str = self.SampleLetters(alphabet.letters, length)\n \n Seq.__init__(self, seq_str.upper(), alphabet)",
"def _initSeqString(self, s):\r\n if s is None:\r\n s = \"\"\r\n \r\n s = str(s)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get nucleotides of this sequence, in uppercase. | def nucleotides(self):
return self._nucleotides # 将字符串变作一个列表 | [
"def get_nuclei(self):\n sim_layer = self._wrap_ns(self.setup_config[\"sim_layer\"])\n return cmds.listRelatives(sim_layer, ad=True, type=\"nucleus\") or []",
"def _GetNucleicAcidResidueNames():\n \n ResidueNames = [\"A\", \"G\", \"T\", \"U\", \"C\", \"DA\", \"DG\", \"DT\", \"DU\", \"DC\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate molecular weight of a DNA sequence. | def calculate_weight(sequence):
weight = 0
for c in sequence.nucleotides: # 处理对象.方法;代表一个序列中元素的变量用一个字母代表即可
weight += Sequence.WEIGHTS[c] # 叠加nucleotide在WEIGHT dict中对应的重量
return weight | [
"def calc_weight(sequence):\r\n return len(sequence) * AVG_WEIGHT",
"def molecularWeight (self):\r\n protMass = 0\r\n for aa in ProteinParam.aa2mw.keys():\r\n protMass += (ProteinParam.aa2mw[aa] * self.protString.count(aa))\r\n protMass -= ProteinParam.mwH2O * (myParamMaker.aaCo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that splits the serialized string of icon image file names into a list of individual file names. Multiple icons are used in the construction of the card header. As such they are stored as a single CharField in the database in serialized fashion | def serialized_icon_names(self):
return self.card_icons.split(':') | [
"def map_csv_images(images: str):\n api_images = []\n images = [x.strip() for x in images.split(\",\")]\n for image in images:\n api_images.append({\n \"src\": image,\n \"name\": os.path.basename(image)\n })\n return api_images",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a job. phases must be one of PHASES.keys(). centers must be a list of one or more RegistrationCenter instances input_arguments must be a dict in the form of INPUT_ARGUMENTS_TEMPLATE user is a string identifying the user running this job output_path is a directory name defining where output will be written The of... | def __init__(self, phase, centers, input_arguments, user, output_path):
# Phase, centers, output_path, input_arguments, and user are set here in __init__() and
# don't change hereafter.
self.phase = phase
self.centers = centers
self.output_path = output_path
self.input_ar... | [
"def _create_job(self):\n LOGGER.debug(\"Creating Solve Engine job...\")\n pb_data = self.model.build_str_model().encode('ascii')\n\n pb_data = b64.b64encode(pb_data).decode('utf-8')\n\n dict_data = dict(problems=[dict(name=self.model.file_name, data=pb_data)])\n resp = self._send... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a PDF filename and the number of pages in that PDF, add it to the tracker dict. | def add(self, filename, n_pages):
with open(filename, 'rb') as f:
content = f.read()
size = len(content)
# Before storing the filename I strip first part of output path which is the parent
# directory of all of these files. We don't want that info in here because it will bec... | [
"def registerPDF(self, filename):\n now = datetime.now()\n pdfs = self.getPDFList()\n pdfs[filename] = now\n\n if (now - self.get_last_clean()).seconds > 1000:\n self.cleanPDFs()",
"def __count_pdf_pages(filename):\n data = file(filename, 'rb').read()\n return len(__RE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the phaseappropriate fully qualified filename. The filename is populated with the passed params. type_ is only appropriate when the phase is polling, and should be one of 'list', 'book', or 'sign'. | def get_filename(self, path, params, type_=None):
phase = self.phase
if type_:
phase += ('_' + type_)
filename = self.FILENAME_TEMPLATES[phase].format(**params)
return os.path.join(path, filename) | [
"def hap_filename(self, filetype):\n if filetype == 'events':\n return self.folder('events') / 'run_{:07d}_{}_eventlist.fits'.format(self.obs_id, self.hap_config)\n # return self.folder('events') / 'events_{:06d}.fits.gz'.format(self.obs_id)\n elif filetype == 'aeff':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator for ProtoRPC methods. It wraps the target method with typechecking assertions as well as attaching additional a spec information placeholder. | def ProtoRPCServiceMethod(method):
def wrapper(self, request):
assert isinstance(request, wrapper.rpc_method_spec.request_type)
logging.info("Request:\n%s", request)
response = method(self, request)
assert isinstance(response, wrapper.rpc_method_spec.response_type)
logging.info("Response:\n%s", r... | [
"def decorator(fn):\n\n def wrapper(self, *args, **kw):\n \"\"\" Type-checking method wrapper. \"\"\"\n\n actual_args = _validate_args(self, fn, trait_types, args)\n actual_kw = _validate_kw(self, fn, trait_types, kw)\n\n return_value = fn(self, *actual_args, **a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register the given ProtoRPC service to the given flask app. | def RegisterProtoRPCServiceToFlaskApp(app_inst, path, service_inst,
service_name=None):
service_name = service_name or service_inst.SERVICE_DESCRIPTOR.name
endpoint_name = '__protorpc_service_view_func_' + str(uuid.uuid1())
view_func = _ProtoRPCServiceFlaskAppViewFunc(service... | [
"def register(app):\n logger.info(\"register: app=%r\" % app)\n\n app.register_blueprint(\n blueprint,\n url_prefix=service_base_url + \"/example\")\n\n return app",
"def register_service(application):\n consul_host = application.config['CONSUL_ADDR']\n consul_port = int(application.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the number of days that the person has had a twitter, as well as some other useful information including the average number of statuses per day, followers gained per day, and the average number of status's per day. | def calculate_days(self):
tweet_time = self.data['created_at']
birthday = self.data['user']['created_at']
my_dates = {"Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10,
"Nov": 11, "Dec": 12}
# This could have easily be... | [
"async def twitter_status(self, ctx):\n server_channels = set(c.id for c in ctx.message.server.channels)\n\n followed_count = 0\n displayed_count = 0\n for chan_conf in self.conf.follows:\n # Check if this channel is displayed in the server\n if set(c.id for c in ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function cleans the user description, removing all but alphabetical characters, and casting everything to lowercase. | def clean_user_desc(self):
desc = self.data['user']['description']
if desc is not None:
desc = ' '.join(re.sub("(RT : )|(@[\S]+)|(&\S+)|(http\S+)", " ", desc).split())
desc = " ".join(re.sub("(#\S+)", ' ', desc).split())
desc = ''.join(list(filter(lambda x: x.isalpha(... | [
"def title_cleanup(data):\n keys = data.keys()\n for key in keys:\n regex = re.compile('[^a-zA-Z ]')\n data[key][0] = regex.sub('',data[key][0]).lower()\n return",
"def clean_username(self, username):\n return username.lower()",
"def clean_up_text(text):\n text = text.lower() #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The following function stores the data into the specified database. This function is the heart of the program the_main_dict is an example of the power of dictionary unpacking, it also makes it very easy to modify the scraper. If new information is wanted to be gleaned, a new function can be created above, since the ent... | def store_data(self, data):
self.data = data
# HERE
the_main_dict = {**self.user_data(), **self.entities_data(), **self.extract_relevant(), **self.locate(),
**self.calculate_days(), **self.clean_user_desc()}
# The below is the reason that the table creation must ... | [
"def save_data(scrapper_data):\n print(f'Persisting {len(scrapper_data)} results')\n\n restaurant_persistor, city_persistor = RestaurantHelper(), CityHelper()\n\n city_persistor.insert(scrapper_data[0].city)\n city_persistor.commit()\n\n for restaurant in scrapper_data:\n restaurant_persistor.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the class folders in a dataset. | def _find_classes(self, dir):
if sys.version_info >= (3, 5):
# Faster and available in Python 3.5 and above
classes = [d.name for d in os.scandir(dir) if d.is_dir()]
else:
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
# accordin... | [
"def get_classes_from_subdirs(data_dir, expected_num_classes: int):\n all_classes = os.listdir(data_dir)\n all_classes = [x for x in all_classes if os.path.isdir(os.path.join(data_dir, x))]\n if len(all_classes) != expected_num_classes:\n print(\"length of found classes does not equal number of expe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a pool of threads each associated with a host machine | def __init__(self, hostFileName, cwd=os.getcwd(), daemons=True):
# Queues for each IO to threads:
self.Q = {'in': Queue.Queue(),
'out': Queue.Queue(),
'err': Queue.Queue()}
self.pool = []
self.hostList = []
if hostFileName:
if not os.path.exists(h... | [
"def ping_pool(hosts, num_threads):\n p = dummy.Pool(int(num_threads))\n results = p.map(ping_worker, hosts)\n p.close()\n return results",
"def make_pool(self):\r\n self.logger.info(\"...using pool\")\r\n return mp.Pool(processes=self.number_of_cores)",
"def parallel_ping(host_list):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the host is fine | def _hostOK(self, host):
if os.system("ping -c 1 $node &> /dev/null"):
# No access to host
return False
elif os.system("ssh -n -a -x $node 'ls' &> /dev/null"):
# No route to host
return False
else:
return True | [
"def host_is_valid (host) :\n\n # FIXME: cache results so that further lookups are quick\n\n if host_is_local (host) :\n return True\n \n try :\n ip = socket.gethostbyname (host)\n return True\n except :\n return False",
"def __verify_connection(host):\n \n # spli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Work requests are posted as (data, flag) pairs to self.Q['in'] | def enqueue(self, data, flag='process'):
self.Q['in'].put((data, flag)) | [
"def _request_in(self, request, requests_seen):\n _req_seen = lambda r: self._requests_equal(r, request)\n for seen in ifilter(_req_seen, requests_seen):\n return True\n # request not seen\n return False",
"def check_in(self):\n etree = self._encapsulate_request(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We report errors by adding error information fo self.Q['err'] | def reportError(self):
self.Q['err'].put(sys.exc_info()[:2]) | [
"def error(self, msg, *args, **kwargs):\n self.add_report_entry(ERROR, msg, args, **kwargs)",
"def _record_errors(self):\n if len(self._source_volume_too_small) > 0:\n msg = 'Some source containers do not contain enough volume to ' \\\n 'provide liquid for all target cont... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
routine that generates the python files for a network given with its id | def generate_files_from_network(id):
folder_prefix = "results/"+id+"/"
network_prefix = "results/"+id+"_"
g = open(network_prefix+'network.json', 'r')
data = json.load(g)
names = []
for node in data:
my_name = data[node]['my_name']
names.append(my_name)
targets = data[node]['target']
n_receive = data[node... | [
"def generate_topology(self, filename):\n\n self.settings['topology'].generate(self, filename)",
"def create_filtered_network_file(network_file_prefix, filtered_network_file, ueids):\n network_file_method_attribute = network_file_prefix + \"_method_id.eda\"\n network_file_source_attribute = network_file_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs n_runs runs. Calculates the mean run time and its standard deviation. | def measure(self):
# --- perform repeated runs
for i_run in range(self.n_runs):
if self.verbosity > 0:
print("Run {0} / {1} ...".format(i_run, self.n_runs), end = '')
tdelta = self._timed_execute()
self._run_times[i_run] = tdelta
if sel... | [
"def std_run_time(self) -> float:\n return float(self.result_array.sum(axis=0).std())",
"def run_timing():\n\n num_of_runs = 0\n total_time = 0\n\n while True:\n one_run = input('Enter 10 Km run time: ')\n\n if not one_run:\n break\n\n num_of_runs += 1\n tota... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the array to store the run times. | def _set_runtimes(self):
self._run_times =np.zeros(self.n_runs, dtype = np.float) | [
"def rt_arr_time(self, rt_arr_time):\n\n self._rt_arr_time = rt_arr_time",
"def arr_time(self, arr_time):\n\n self._arr_time = arr_time",
"def set_times(self, times):\n self.times = times",
"def set_time(self, time_array):\n if len(time_array) < 2:\n raise ModelParameter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct the JSONRPC payload for NXAPI. | def _build_payload(self, commands, method, rpc_version="2.0", api_version=1.0):
payload_list = []
id_num = 1
for command in commands:
payload = {
"jsonrpc": rpc_version,
"method": method,
"params": {"cmd": command, "version": api_versio... | [
"def _build_payload(self, body: Dict) -> Dict[str, Any]:\n return {'jsonrpc': '2.0',\n 'id': self._id_count,\n **body}",
"def _make_payload(self, **kwargs):\n pass",
"def _build_payload(self, commands, method, rpc_version='2.0', version=1):\n payload_list = []\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize the API response including handling errors; adding the sent command into the returned data strucutre; make response structure consistent for raw_text and structured data. | def _process_api_response(self, response, commands, raw_text=False):
response_list = json.loads(response)
if isinstance(response_list, dict):
response_list = [response_list]
# Add the 'command' that was executed to the response dictionary
for i, response_dict in enumerate(r... | [
"def _convert_response(\n self, api_method, target, verb, response, raw_response, byte_output\n ):\n if raw_response:\n return response\n\n # Trying to see if the response content can be loaded as a json\n bad_status_codes = list(range(400, 600))\n if response.status... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show a scan result. | def show_result():
return scan_result(request.args.get('filename')) | [
"def print_scan_results(self):\n print(\"Name: %s\\nTime: %s\\nCoortinates: %d, %d\\nMAC addresses %s\",\\\n self.name,\\\n self.time,\\\n self.coordinates[0],\\\n self.coordinates[1],\\\n \", \".join(self.ap_list))",
"def help_scan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the constant/polyMesh/points file in polymesh directory and stores the points coordinates into region.mesh.nodeCentroids | def cfdReadPointsFile(self):
with open(self.pointsFile,"r") as fpid:
print('Reading points file ...')
points_x=[]
points_y=[]
points_z=[]
for linecount, tline in enumerate(fpid):
if... | [
"def parse(self, filename):\n self._check_filename_type(filename)\n self._check_extension(filename)\n\n self.infile = filename\n\n i = 0\n n_points = 0\n with open(self.infile, 'r') as input_file:\n for line in input_file:\n n_points += 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the constant/polyMesh/faces file and stores the nodes pertaining to each face in region.mesh.faceNodes Starts with interior faces and then goes through the boundary faces. | def cfdReadFacesFile(self):
with open(self.facesFile,"r") as fpid:
print('Reading faces file ...')
self.faceNodes=[]
for linecount, tline in enumerate(fpid):
if not io.cfdSkipEmptyLines(tline):
conti... | [
"def read_faces(zone_id, Nmin, Nmax, bc_type, face, ifile):\n \n line = ifile.readline()\n readline = False\n if re.search(re_parant, line): # check for initial paranthesis\n readline = True\n\n ls = []\n for i in range(Nmin, Nmax + 1):\n if readline:\n line = ifile.readli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the polyMesh/constant/owner file and returns a list where the indexes are the faces and the corresponding element value is the owner cell | def cfdReadOwnerFile(self):
with open(self.ownerFile,"r") as fpid:
print('Reading owner file ...')
## (list) 1D, indices refer to faces, list value is the face's owner cell
self.owners=[]
start=False
for linecount, tline in enu... | [
"def cfdReadNeighbourFile(self): \r\n with open(self.neighbourFile,\"r\") as fpid:\r\n print('Reading neighbour file ...')\r\n\r\n ## (list) 1D, indices refer to faces, list value is the face's neighbour cell\r\n self.neighbours=[]\r\n start=False\r\n \r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the polyMesh/constant/neighbour file and returns a list where the indexes are the faces and the corresponding element value is the neighbour cell | def cfdReadNeighbourFile(self):
with open(self.neighbourFile,"r") as fpid:
print('Reading neighbour file ...')
## (list) 1D, indices refer to faces, list value is the face's neighbour cell
self.neighbours=[]
start=False
for linec... | [
"def read_faces(zone_id, Nmin, Nmax, bc_type, face, ifile):\n \n line = ifile.readline()\n readline = False\n if re.search(re_parant, line): # check for initial paranthesis\n readline = True\n\n ls = []\n for i in range(Nmin, Nmax + 1):\n if readline:\n line = ifile.readli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the polyMesh/boundary file and reads its contents in a dictionary (self.cfdBoundary) | def cfdReadBoundaryFile(self):
with open(self.boundaryFile,"r") as fpid:
print('Reading boundary file ...')
## (dict) key for each boundary patch
self.cfdBoundaryPatchesArray={}
for linecount, tline in enumerate(fpid):
... | [
"def readSurfaceGeo(b18path):\n if not os.path.isfile(b18path):\n print(\"b18 building file not found! Please check!\")\n pass\n else:\n b18file = open(b18path,\"r\")\n b18data = b18file.readlines()\n srfGeoBlock = getDataParagraph(\"_EXTENSION_BuildingGeometry_START_\", \"_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if there are any inlets or outlets in the domain, based on the boundary types found in system/boundary if any of the boundaries is an inlet or outlet returns self.foundPatch = True | def cfdCheckIfCavity(self):
self.foundPatch=False
for patch, value in self.cfdBoundaryPatchesArray.items():
if value['type'] == 'inlet' or 'outlet':
self.foundPatch =True
break | [
"def _hitBoundry(self):\n collision = False\n for block in self._boundry:\n if self._whetherCollides(block,self._head):\n collision = True\n return collision",
"def _detect_collision(self):\n if len(p.getContactPoints(self.robot)) > 0:\n return True... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populates self.elementNeighbours and self.elementFaces also populates self.upperAnbCoeffIndex self.lowerAnbCoeffIndex | def cfdProcessElementTopology(self):
## (list of lists) List where each index represents an element in the domain. Each index has an associated list which contains the elements for which is shares a face (i.e. the neighouring elements). Do not confuse a faces 'neighbour cell', which refers to a face's neighbou... | [
"def _store_neighbour_information(self):\n\n import time\n\n # walltime = time.clock()\n\n neighbour_list = []\n num_neighbours = np.zeros(len(self.tri.points), dtype=int)\n\n\n for node in range(0,len(self.tri.points)):\n neighbours = self.neighbours(node)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invokes the cfdInvertConnectivity method on self.elementNodes and self.faceNodes | def cfdProcessNodeTopology(self):
self.nodeElements = self.cfdInvertConnectivity(self.elementNodes)
self.nodeFaces = self.cfdInvertConnectivity(self.faceNodes) | [
"def SetApplyConnectivity(self, _arg: 'bool const') -> \"void\":\n return _itkCollidingFrontsImageFilterPython.itkCollidingFrontsImageFilterIF2IF2_SetApplyConnectivity(self, _arg)",
"def cfdProcessElementTopology(self):\r\n ## (list of lists) List where each index represents an element in the domain... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array with the inverted connectivty of an input array. For example self.cfdInvertConnectivty(self.elementNodes) takes the elementNodes connectivity array and returns an inverted array with the elements belonging to each node. | def cfdInvertConnectivity(self,theConnectivityArray):
theInvertedSize=0
for i in range(len(theConnectivityArray)):
for j in range(len(theConnectivityArray[i])):
theInvertedSize=max(theInvertedSize, int(theConnectivityArray[i][... | [
"def _inverse_edges(edges: np.array) -> np.array:\n inversed_edges = edges.copy()\n inversed_edges[:, [0, 1]] = inversed_edges[:, [1, 0]]\n return inversed_edges",
"def invert(array):\n\n f = [1, 1, 1]\n\n result = np.array(array)\n\n for row in range(result.shape[0]):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list of the boundary elements pertaining to a patch in self.cfdBoundaryPatchesArray | def cfdGetBoundaryElementsSubArrayForBoundaryPatch(self):
for iBPatch, theBCInfo in self.cfdBoundaryPatchesArray.items():
startBElement=self.numberOfElements+self.cfdBoundaryPatchesArray[iBPatch]['startFaceIndex']-self.numberOfInteriorFaces
endBElement=startBElement+se... | [
"def cfdGetFaceSfSubArrayForBoundaryPatch(self):\r\n\r\n for iBPatch, theBCInfo in self.cfdBoundaryPatchesArray.items():\r\n \r\n startBFace=self.cfdBoundaryPatchesArray[iBPatch]['startFaceIndex']\r\n \r\n endBFace=startBFace+self.cfdBoundaryPatchesArray[iBPatch]['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list with the centroids for each face of the patch in self.cfdBoundaryPatchesArray[patch]['faceCentroids'] | def cfdGetFaceCentroidsSubArrayForBoundaryPatch(self):
for iBPatch, theBCInfo in self.cfdBoundaryPatchesArray.items():
startBFace=self.cfdBoundaryPatchesArray[iBPatch]['startFaceIndex']
endBFace=startBFace+self.cfdBoundaryPatchesArray[iBPatch]['numberOfBFaces']... | [
"def _calc_face_centers(self):\n\n points = self.nodes[self.face_nodes]\n self.face_centers = np.mean(points, axis=1)",
"def _face_center(mesh, face):\n center = [0, 0, 0]\n for vert in face.vertices:\n center = _list_plus(vert, center)\n new_list = [x / len(face.vertices) for x in c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list with the element owners of each boundary patch face in self.cfdBoundaryPatchesArray[patch]['owners_b'] | def cfdGetOwnersSubArrayForBoundaryPatch(self):
for iBPatch, theBCInfo in self.cfdBoundaryPatchesArray.items():
startBFace=self.cfdBoundaryPatchesArray[iBPatch]['startFaceIndex']
endBFace=startBFace+self.cfdBoundaryPatchesArray[iBPatch]['numberOfB... | [
"def cfdGetFaceCentroidsSubArrayForBoundaryPatch(self):\r\n \r\n for iBPatch, theBCInfo in self.cfdBoundaryPatchesArray.items():\r\n \r\n startBFace=self.cfdBoundaryPatchesArray[iBPatch]['startFaceIndex']\r\n endBFace=startBFace+self.cfdBoundaryPatchesArray[iBPatch]['n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list with the surface vectors (Sf) of each face belonging to each boundary patch in self.cfdBoundaryPatchesArray[patch]['facesSf'] | def cfdGetFaceSfSubArrayForBoundaryPatch(self):
for iBPatch, theBCInfo in self.cfdBoundaryPatchesArray.items():
startBFace=self.cfdBoundaryPatchesArray[iBPatch]['startFaceIndex']
endBFace=startBFace+self.cfdBoundaryPatchesArray[iBPatch]['numberOfBFaces']
... | [
"def getFaces(self):\n\t\tfaces = []\n\t\tfor solid in self.getSolids():\n\t\t\ttry:\n\t\t\t\tfor face in solid.Faces:\n\t\t\t\t\tfaces.append(face)\n\t\t\texcept:\n\t\t\t\tpass\n\t\treturn faces",
"def faces(self):\r\n \r\n faceset = set()\r\n for faset in self.SCFaset:\r\n for fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Convert a Luv image to RGB. | def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
if not isinstance(image, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, ... | [
"def luv2rgb(luv):\n return xyz2rgb(luv2xyz(luv))",
"def yuv_to_rgb(img_yuv):\n\n y = img_yuv[..., 0]\n u = img_yuv[..., 1]\n v = img_yuv[..., 2]\n\n r = y + 1.14 * v\n g = y - 0.396 * u - 0.581 * v\n b = y + 2.029 * u\n\n img_rgb = np.stack((r, g, b), axis=2)\n img_rgb = np.clip(img_rg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The expectation this result refers to. | def expectation(self):
return self._expectation | [
"def expectation_results(self):\n return self._expectation_results",
"def expectation(self):\n\n return self.a / (self.a + self.b)",
"def test_result(self):\n return self._test_result",
"def actual(self):\n return self._actual",
"def GetExpectationExpression(self):\n callR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method adds a HeapNode instance to the heap If value == None the new node's value should be set to key | def add(self, key, value=None):
if value is None:
value = key
node = HeapNode(key, value)
self.store.append(node)
self.heap_up(len(self.store)-1)
return None | [
"def push(self, key, value):\r\n if len(self.heap)<self.depth:\r\n heapq.heappush(self.heap, key)\r\n self.elements[key] = value\r\n else:\r\n oldkey = heapq.heappushpop(self.heap, key)\r\n self.elements[key] = value\r\n del self.elements[oldkey]"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This helper method takes an index and moves the corresponding element down the heap if it's larger than either of its children and continues until the heap property is reestablished. | def heap_down(self, index):
left_child = (2*index) + 1
right_child = (2*index) + 2
if left_child < len(self.store):
if right_child >= len(self.store):
min_child = left_child
elif self.store[left_child].key < self.store[right_child].key:
m... | [
"def sift_down(self, i):\n while 2 * i <= self.size: # while there're some children below\n max_index = self.max_child_index(i)\n if self.heaplist[i] < self.heaplist[max_index]:\n self.heaplist[i], self.heaplist[max_index] = \\\n self.heaplist[max_inde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Swaps two elements in self.store at index_1 and index_2 used for heap_up & heap_down | def swap(self, index_1, index_2):
temp = self.store[index_1]
self.store[index_1] = self.store[index_2]
self.store[index_2] = temp | [
"def __swap(self, index1, index2):\n self.heap[index1], self.heap[index2] = self.heap[index2], self.heap[index1]",
"def _swap_items(self, index1, index2):\n temp = self._min_heap[index1]\n self._min_heap[index1] = self._min_heap[index2]\n self._min_heap[index2] = temp",
"def __swap__... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a hypothesis space of concepts defined by 1D lines | def create_line_hyp_space(n_features):
hyp_space = []
for i in range(1, n_features + 1):
for j in range(n_features - i + 1):
hyp = [0 for _ in range(n_features)]
hyp[j:j + i] = [1 for _ in range(i)]
hyp_space.append(hyp)
hyp_space = np.array(hyp_space)
return ... | [
"def mk(prop_lines, eq_lines, ops):\n props = flatten([Eq.parse_prop(pl) for pl in prop_lines])\n eqs = [Eq.parse_eq(el, ops) for el in eq_lines]\n return Theory(props, eqs, ops)",
"def test_make_model_horizontal(self) -> None:\n test_model = line2d.Line2D()\n test_data = [line2d.Point2D(x=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a hypothesis space of concepts defined by a linear boundary | def create_boundary_hyp_space(n_features):
hyp_space = []
for i in range(n_features + 1):
hyp = [1 for _ in range(n_features)]
hyp[n_features-i:n_features] = [0 for _ in range(i)]
hyp_space.append(hyp)
hyp_space = np.array(hyp_space)
return hyp_space | [
"def create_boundary_hyp_space(self):\n hyp_space = []\n for i in range(self.n_features + 1):\n hyp = [1 for _ in range(self.n_features)]\n hyp[:i] = [0 for _ in range(i)]\n hyp_space.append(hyp)\n hyp_space = np.array(hyp_space)\n return hyp_space",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
copy directory from a location in bcdbfs file system to another | def dir_copy_from_bcdbfs(self, path, dest, recursive=True):
if path == j.sal.fs.getParent(dest):
raise j.exceptions.Base("{} can not copy directory into itself".format(path))
dir_source = self._dir_model.get_by_name(name=path)[0]
source_files = dir_source.files
for file_id in... | [
"def file_copy_form_bcdbfs(self, path, dest):\n source_file = self._file_model.get_by_name(name=path)[0]\n if self.is_dir(dest):\n dest = j.sal.fs.joinPaths(dest, j.sal.fs.getBaseName(path))\n dest_file = self.file_create_empty(dest)\n if source_file.blocks:\n dest_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
copies a dir from either local file system or from bcdbfs | def dir_copy(self, path, dest, recursive=True):
if j.sal.fs.exists(path):
self.dir_copy_from_local(path, dest, recursive=recursive)
else:
self.dir_copy_from_bcdbfs(path, dest, recursive=recursive) | [
"def _staf_dir_copy(self, local_path, remote_path):\n\n staf_request = ('COPY DIRECTORY \"{0}\" TODIRECTORY \"{1}\" TOMACHINE \"{2}\" RECURSE '\n 'KEEPEMPTYDIRECTORIES'.format(unix_style_path(local_path),\n unix_style_path(remote_pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
copies file to another location in bcdbfs | def file_copy_form_bcdbfs(self, path, dest):
source_file = self._file_model.get_by_name(name=path)[0]
if self.is_dir(dest):
dest = j.sal.fs.joinPaths(dest, j.sal.fs.getBaseName(path))
dest_file = self.file_create_empty(dest)
if source_file.blocks:
dest_file.blocks... | [
"def copy(self, source_host, dest_host, filename):",
"def copy(self, src_path: str, tgt_path: str) -> None:",
"def copyFile(self, f1, f2):\n\t\tif not self.fileInDB(f2):\n\t\t\tf3 = self.getFile(f1)\n\t\t\tf3.setFileName(f2.getFileName())\n\t\t\tf3.setPath(f2.getPath())\n\t\t\tself.addFile(f3)",
"def _copy_fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
list dirs in path | def list_dirs(self, path="/"):
path = j.sal.fs.pathClean(path)
dir_obj = self._dir_model.get_by_name(path)
if not dir_obj:
raise j.exceptions.Base("path {} does not exist".format(path))
res = [self._dir_model.get(item).name for item in dir_obj[0].dirs]
return res | [
"def list_dir(self, path):",
"def get_directory_list(path):\n if not os.path.isdir(path):\n print(\"Path does not exist \" + path)\n sys.exit(1)\n dirs = next(os.walk(path))[1]\n return dirs",
"def listdir(path):\r\n return os.listdir(path)",
"def dirs(path = None) -> List[str]:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
list files and dirs in path | def list_files_and_dirs(self, path="/"):
dirs = self.list_dirs(path)
files = self.list_files(path)
return dirs + files | [
"def list_dir(self, path):",
"def listdir(path):\r\n return os.listdir(path)",
"def get_files(self, path):\n lst1 = get_content(path)\n for item in lst1:\n if item.is_file():\n self.lst.append(item.absolute())\n elif item.is_dir() and self.recursion: # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Genere le message en bytes. Override dans sousclasse pour ajouter le contenu apres le prefixe. | def encoder(self):
prefixe = pack('=BHB', VERSION_PROTOCOLE, self.type_message, self.node_id)
return prefixe | [
"def _generate_message(self, cmd, addr, port, version = None):\r\n\r\n # Set default version of needed. Sometime need version 0 so check None.\r\n if version is None:\r\n version = self.version\r\n\r\n # Create message.\r\n msg = pack(\"!BBH\", version, cmd, port)\r\n m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds the boson destruction operator acting on the `site`th of the Hilbert space `hilbert`. If `hilbert` is a nonBosonic space of local dimension M, it is considered as a bosonic space of local dimension M. | def destroy(hilbert, site):
N = hilbert.local_size
D = _np.array([_np.sqrt(m) for m in _np.arange(1, N)])
mat = _np.diag(D, 1)
return _LocalOperator(hilbert, mat, [site]) | [
"def create(hilbert, site):\n N = hilbert.local_size\n\n D = _np.array([_np.sqrt(m) for m in _np.arange(1, N)])\n mat = _np.diag(D, -1)\n return _LocalOperator(hilbert, mat, [site])",
"def number(hilbert, site):\n N = hilbert.local_size\n\n D = _np.array([m for m in _np.arange(0, N)])\n mat =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds the boson creation operator acting on the `site`th of the Hilbert space `hilbert`. If `hilbert` is a nonBosonic space of local dimension M, it is considered as a bosonic space of local dimension M. | def create(hilbert, site):
N = hilbert.local_size
D = _np.array([_np.sqrt(m) for m in _np.arange(1, N)])
mat = _np.diag(D, -1)
return _LocalOperator(hilbert, mat, [site]) | [
"def destroy(hilbert, site):\n N = hilbert.local_size\n\n D = _np.array([_np.sqrt(m) for m in _np.arange(1, N)])\n mat = _np.diag(D, 1)\n return _LocalOperator(hilbert, mat, [site])",
"def number(hilbert, site):\n N = hilbert.local_size\n\n D = _np.array([m for m in _np.arange(0, N)])\n mat =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds the number operator acting on the `site`th of the Hilbert space `hilbert`. If `hilbert` is a nonBosonic space of local dimension M, it is considered as a bosonic space of local dimension M. | def number(hilbert, site):
N = hilbert.local_size
D = _np.array([m for m in _np.arange(0, N)])
mat = _np.diag(D, 0)
return _LocalOperator(hilbert, mat, [site]) | [
"def create(hilbert, site):\n N = hilbert.local_size\n\n D = _np.array([_np.sqrt(m) for m in _np.arange(1, N)])\n mat = _np.diag(D, -1)\n return _LocalOperator(hilbert, mat, [site])",
"def destroy(hilbert, site):\n N = hilbert.local_size\n\n D = _np.array([_np.sqrt(m) for m in _np.arange(1, N)])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expects two string values. It will split the string by whitespace and compare each value. It will return True if both lists are the same, contain the same elements and the same order. | def _values_is_equal(self, a, b):
if a is None or b is None:
return False
a = a.split()
b = b.split()
if len(a) != len(b):
return False
return len([i for i, j in zip(a, b) if i == j]) == len(a) | [
"def eq_tokens(token_sequence1: str, token_sequence2: str) -> bool:\n return set(token_sequence1.split(' ')) - {''} == set(token_sequence2.split(' ')) - {''}",
"def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n first_word = \"\".join(word1)\n sec_word = \"\".join(word2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses command line agurments into inps variable. | def command_line_parse(iargs=None):
parser = create_parser()
inps = parser.parse_args(args=iargs)
return inps | [
"def parseCommandLine_(self):\n\n self.ensureNotCreated()\n\n import sys\n\n parseCommandLine = False\n for argv in sys.argv:\n if 'globalTag' in argv or 'era' in argv or 'process' in argv:\n parseCommandLine = True\n break\n\n if parseComm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a CSV to a list of JSON | def convert_to_json(self, csvname):
csvfile = open(csvname, 'r')
self.__obtain_csv_delimiter__(csvfile)
self.__obtain_csv_fieldnames__(csvfile)
data = self.__obtain_data_from_csv__(csvfile)
jsons = self.__convert_data_to_list_of_dict__(data)
list_of_jsons = self.__transfo... | [
"def convert_csv_to_json():\n result = {}\n try:\n with open(FILE_NAME, 'r', newline='') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n for entry_id in range(len(row)):\n row[entry_id] = row[entry_id].replace(\"'\", \"\\\"\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain the field names of the CSV file | def __obtain_csv_fieldnames__(self, csvfile):
self.__fieldnames__ = csvfile.readline()
self.__obtain_csv_delimiter__(self.__fieldnames__)
self.__fieldnames__ = self.__remove_break_line__(self.__fieldnames__)
self.__fieldnames__ = self.__split_for_delimiter__(self.__fieldnames__) | [
"def fieldnames(self):\n try:\n fieldnames = self._csv_reader.fieldnames\n except AttributeError:\n fieldnames = None\n return fieldnames",
"def read_sample_csv(self):\n f = open('sample.csv')\n lines = f.readline()\n fields = lines.split(',')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove the break line character | def __remove_break_line__(self, string):
return string.rstrip() | [
"def strip_line_breaks(self, text):\n text = re.sub(r'(\\r*)', r'', text)\n text = re.sub(r'(\\n*)', r'', text)\n return text",
"def __stripEol(self, txt):\n return txt.replace(\"\\r\", \"\").replace(\"\\n\", \"\")",
"def removeEmptyLine (self, text):\n newtext = filter(str.st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split a string based in the delimiter | def __split_for_delimiter__(self, string):
if not self.__delimiter__ == '':
return string.split(self.__delimiter__)
return string.split() | [
"def _split(string, delimiter):\n segment = \"\"\n segments = []\n\n for i, c in enumerate(string):\n if c == delimiter and not _isCharEnclosed(i, string):\n segments.append(segment)\n segment = \"\"\n else:\n segment += c\n\n if segment:\n segments.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test get_bytes_summary_stats_counter(counter_name, runtime_profile) using a dummy runtime profile. | def test_get_bytes_summary_stats_counter():
runtime_profile = "- ExampleCounter: (Avg: 8.00 KB (8192) ; " \
"Min: 6.00 KB (6144) ; " \
"Max: 10.00 KB (10240) ; " \
"Number of samples: 4)"
summary_stats = get_bytes_summary_stats_counter("ExampleCounter",
... | [
"def get_bytes_summary_stats_counter(counter_name, runtime_profile):\n # This requires the Thrift definitions to be generated. We limit the scope of the import\n # to allow tools like the stress test to import this file without building Impala.\n from RuntimeProfile.ttypes import TSummaryStatsCounter\n\n regex_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test get_time_summary_stats_counter(counter_name, runtime_profile) using a dummy runtime profile. | def test_get_time_summary_stats_counter():
# This is constructed to test the parsing logic for timestamps, so the number don't
# add up.
runtime_profile = "- ExampleTimeStats: (Avg: 161.554ms ; " \
"Min: 101.411us ; " \
"Max: 1h2m3s4ms5us6ns ; " \
"Numbe... | [
"def get_time_summary_stats_counter(counter_name, runtime_profile):\n # This requires the Thrift definitions to be generated. We limit the scope of the import\n # to allow tools like the stress test to import this file without building Impala.\n from RuntimeProfile.ttypes import TSummaryStatsCounter\n\n regex_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an array of colors of shape (n, 3) where 3 represents r, g, and b, send the colors to the renderer. This will change the colors of the current set of particles without affecting the values of the particles themself. The first dimension of `colors` must be equivalent to the number of particles in the most recent c... | def send_colors(colors: np.ndarray):
send("colors", json.dumps(np.ravel(colors).tolist())) | [
"def update_colors(self, connectivity_colors):\n assert( len(self.colors) == len(connectivity_colors) )\n\n if connectivity_colors.shape[1] == 4:\n # replace color values, keep alpha\n self.colors = connectivity_colors\n # duplicate array\n self.colors_draw ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For every group of three vertices, drawing lines from 1>2, 2>3, and 3>1 will create one of the faces of the convex hull. `simplices` as returned by `scipy.spatial.ConvexHull()` is an array of shape (n, 3, 3) where each index along axis=0 is an array of three vertices. Returns an array of vertices such that drawing a li... | def simplices_to_lines(simplices: np.ndarray):
i = 0
formatted = np.zeros((simplices.shape[0] * 3 * 2, 3))
for vertex_group in simplices:
v1 = vertex_group[0]
v2 = vertex_group[1]
v3 = vertex_group[2]
formatted[i:i + 6] = np.array([v1, v2, v2, v3, v3, v1])
i += 6
... | [
"def visualHull(sils, length):\n result = sils.pop(0).cone(length)\n assert result.pnFacesInPoly()\n i = 0\n for s in sils:\n # print(i)\n assert result.pnFacesInPoly()\n result = result.intersection(s.cone(length), True)\n # result.plot()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an image, encodes it in base64 and sends it to the javascript server. | def send_image(image: PIL.Image.Image):
import base64
import io
image = image.convert("RGB")
buffer = io.BytesIO()
image.save(buffer, format="PNG")
image_b64 = base64.b64encode(buffer.getvalue())
send("image", image_b64.decode("utf-8")) | [
"def encode_image(image):\n base64_img = base64.b64encode(image).decode('ascii')\n return base64_img",
"def encode_image(self, image):\n\t\t# Encode in Base64 and print encoded string for copying\n\t\twith open(image, 'rb') as image:\n\t\t\tprint(\"[+] Image has been encoded. Copy this string:\\n\")\n\t\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts uWSGI package and returns path containing uwsgiconfig.py along with path to extraction root. | def extract_release(self, download_path):
uwsgi_path = None
extract_path = tempfile.mkdtemp("-uwsgi")
setuptools.archive_util.unpack_archive(download_path, extract_path)
for root, dirs, files in os.walk(extract_path):
if 'uwsgiconfig.py' in files:
uwsgi_path =... | [
"def extract_release(self, download_path):\n uwsgi_path = None\n extract_path = tempfile.mkdtemp(\"-uwsgi\")\n setuptools.archive_util.unpack_archive(download_path, extract_path)\n for root, dirs, files in os.walk(extract_path):\n if \"uwsgiconfig.py\" in files:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build uWSGI and returns path to executable. | def build_release(self, uwsgi_path):
# Change dir to uwsgi_path for compile.
sys_path_changed = False
current_path = os.getcwd()
os.chdir(uwsgi_path)
try:
# Add uwsgi_path to the Python path so we can import uwsgiconfig.
if uwsgi_path not in sys.path:
... | [
"def build_uwsgi(self, uwsgi_path):\n current_path = os.getcwd()\n profile = self.options.get(\"profile\", MARKER)\n\n if profile is MARKER:\n profile = '%s/buildconf/default.ini' % uwsgi_path\n elif not os.path.isabs(profile):\n # if the specified profile is not an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns extra paths to include for uWSGI. | def get_extra_paths(self):
# Add libraries found by a site .pth files to our extra-paths.
if 'pth-files' in self.options:
import site
for pth_file in self.options['pth-files'].splitlines():
pth_libs = site.addsitedir(pth_file, set())
if not pth_lib... | [
"def get_extra_paths(self):\n parts_path = self.buildout['buildout']['parts-directory']\n parts_paths = [os.path.join(parts_path, part) for part in os.listdir(parts_path)]\n extra_paths = [self.buildout['buildout']['directory'],] + parts_paths\n\n # Add libraries found by a site .pth fil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create xml file file with which to run uwsgi. | def create_conf_xml(self):
path = os.path.join(
self.buildout['buildout']['parts-directory'],
self.name)
if not os.path.isdir(path):
os.makedirs(path)
xml_path = os.path.join(path, 'uwsgi.xml')
conf = ""
for key, value in self.conf.items():
... | [
"def create_conf_xml(self):\n path = os.path.join(self.buildout['buildout']['directory'], 'uwsgi')\n try:\n os.mkdir(path)\n except OSError:\n pass\n \n xml_path = os.path.join(path, '%s.xml' % self.name)\n \n conf = \"\"\n for key, value ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gaborfiltering based on the median frequency estimation | def medgabor(image: np.array,
orient: np.array,
freq: np.array):
medfreq = np.round(np.median(freq[freq > 0]), 2)
sigma_x = 0.66 / medfreq
sigma_y = 0.66 / medfreq
# Original gabor filter
krnsize = int(np.round(3 * np.max([sigma_x, sigma_y])))
x, y = np.meshgrid(np.lin... | [
"def _compute_median_features(window):\r\n return np.median(window, axis=0)",
"def gaborFilter(img, ksize=31):\n filters = []\n #ksize = 31\n for theta in np.arange(0, np.pi, np.pi / 16):\n kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
image_filenames is a list of filename strings Returns a list of dicts formatted as the Vision API needs them to be | def make_image_data_list(image_filenames):
img_requests = []
for imgname in image_filenames:
try:
with open(imgname, 'rb') as f:
ctxt = b64encode(f.read()).decode()
img_requests.append({
'image': {'content': ctxt},
... | [
"def make_image_data_list(image_filenames):\n img_requests = []\n for imgname in image_filenames:\n with open(imgname, 'rb') as f:\n ctxt = b64encode(f.read()).decode()\n img_requests.append({\n 'image': {'content': ctxt},\n 'features': [{\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize this OWSProviderCheck object with a service URL and layer. | def __init__(self, *args, **kwargs):
super(OWS, self).__init__(*args, **kwargs)
self.query = {"VERSION": "1.0.0", "REQUEST": "GetCapabilities"}
# Amended with "SERVICE" parameter by subclasses
# If service or version parameters are left in query string, it can lead to a protocol ... | [
"def __init__(self,url=False,useCertificates=False):\n try:\n if not url:\n self.url = PathFinder.getServiceURL('DataManagement/DataLogging')\n else:\n self.url = url\n except Exception, x:\n errStr = \"DataLoggingClient.__init__: Exception while obtaining service URL.\"\n gL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Postprune your DecisionTreeClassifier given some optional validation dataset. You can ignore x_val and y_val if you do not need a validation dataset for pruning. | def prune(self, x_val, y_val):
# make sure that the classifier has been trained before predicting
if not self.is_trained:
raise Exception("DecisionTreeClassifier has not yet been trained.")
# get the maximum depth
deepest_depth = get_max_depth(self.root)
# explore ... | [
"def prune(self, x_val, y_val):\n\n # make sure that the classifier has been trained before predicting\n if not self.is_trained:\n raise Exception(\"DecisionTreeClassifier has not yet been trained.\")\n\n #######################################################################\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a tuple list of keypoint edges from the eval config. | def get_keypoint_tuples(eval_config):
tuple_list = []
kp_list = eval_config.keypoint_edge
for edge in kp_list:
tuple_list.append((edge.start, edge.end))
return tuple_list | [
"def get_keypoint_tuples(eval_config):\n tuple_list = []\n kp_list = eval_config.keypoint_edge\n for edge in kp_list:\n tuple_list.append((edge.start, edge.end))\n return tuple_list\n\n # @title Choose the model to use, then evaluate the cell.",
"def get_edge_list(self):\n return [edge for edge in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The standard set function for momentum. | def setMomentum(self,p):
if p is None:
self.p = Cartesian3DVector()
else:
if isinstance(p,Cartesian3DVector):
self.p = Cartesian3DVector(p.x,p.y,p.z)
else:
raise CoordinateVector("Initializing a particle with the incorrect momentum vector type.") | [
"def momentum(E,m):\n\treturn math.sqrt(E*E - m*m)",
"def momentum(self, k):\n self._momentum = k\n self._energy = self.dispersion(k)",
"def moments(self):",
"def getMomentum(self):\n return self.p",
"def momentum (self):\n\n for planet in self.planets: #this loop takes a 'planet' fr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The standard get function for momentum. | def getMomentum(self):
return self.p | [
"def momentum(E,m):\n\treturn math.sqrt(E*E - m*m)",
"def momentum(self):\n return self.mass * self.velocity",
"def get_velocity(self):\n return self.momentum/self.mass",
"def linear_momentum(self):\r\n return self.mass * self.vel",
"def get_massfunc(self):\n return self.p['mcmc'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The standard set function for mass. | def setMass(self,mass):
self.mass = mass | [
"def def_mass(self,mass):\n\n self.mass=float(mass)",
"def mass(self, mass):\n\n self._mass = mass",
"def SetMassMatrix(self, M):\n return _hypre.HypreAME_SetMassMatrix(self, M)",
"def set_mass(self, mass):\n _pal.lib.geometry_set_mass(self._geometry, c.c_float(mass))",
"def set_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The standard get function for mass. | def getMass(self):
return self.mass | [
"def get_mass(self):\n return self.m",
"def atomic_mass(a):\n\n return a.GetMass()",
"def _get_mass(self, geom: MjcfElement, volume: float) -> float:\n if geom.mass:\n return geom.mass\n density = geom.density if geom.density else self._default_density\n return volume * density",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The standard get fucntion for velocity. | def getVelocity(self):
return self.v | [
"def get_velocity(self):\r\n return self._v",
"def get_velocity(self):\n return self.velocity",
"def get_velocity(self):\n self.velocity = 0.5*(self.f2[:-1]/self.f1[:-1]+self.f2[1:]/self.f1[1:])",
"def base_velocity(self):\n raise NotImplementedError('Not yet implemented!')",
"def ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the cartesian 3d vector of velocity from the momentum and mass of the particle. | def calcVelocityFromMomentum(self):
if self.mass is None:
raise CoordinateVector("The particle mass needs to be specified to calculate the particle velocity from momentum.")
values = {}
for direction in self.p.order:
gamma = self.calcLorentzGammaFromMomentum(direction)
values[direction] = ... | [
"def calcMomentumFromVelocity(self):\n if self.mass is None:\n raise CoordinateVector(\"The particle mass needs to be specified to calculate the particle momentum from velocity.\")\n values = {}\n for direction in self.v.order:\n gamma = self.calcLorentzGammaFromVelocity(direction)\n values[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the cartesian 3d vector of momentum from the velocity and mass of the particle. | def calcMomentumFromVelocity(self):
if self.mass is None:
raise CoordinateVector("The particle mass needs to be specified to calculate the particle momentum from velocity.")
values = {}
for direction in self.v.order:
gamma = self.calcLorentzGammaFromVelocity(direction)
values[direction] = ... | [
"def calcVelocityFromMomentum(self):\n if self.mass is None:\n raise CoordinateVector(\"The particle mass needs to be specified to calculate the particle velocity from momentum.\")\n values = {}\n for direction in self.p.order:\n gamma = self.calcLorentzGammaFromMomentum(direction)\n values[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the lorenzt gamma in the provided direction from the momentum and mass of the particle. | def calcLorentzGammaFromMomentum(self,direction):
if self.mass is None:
raise CoordinateVector("The particle mass needs to be specified to calculate the lorentz gamma.")
if direction not in self.x.order:
raise CoordinateVector("The direction, "+str(direction)+ " needs to be one of " +",".join(sel... | [
"def calcLorentzGammaFromVelocity(self,direction):\n if direction not in self.v.order: \n raise CoordinateVector(\"The direction, \"+str(direction)+ \" needs to be one of \" +\",\".join(self.x.order) + \" to calculated the lorentz gamma.\")\n speed_light = constants.physical_constants[\"speed of light ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the lorenzt gamma in the provided direction from the velocity of the particle expressed as a fraction of c. | def calcLorentzGammaFromVelocity(self,direction):
if direction not in self.v.order:
raise CoordinateVector("The direction, "+str(direction)+ " needs to be one of " +",".join(self.x.order) + " to calculated the lorentz gamma.")
speed_light = constants.physical_constants["speed of light in vacuum"][0]#m/... | [
"def gamma(v):\n vmag = numpy.linalg.norm(v)\n if vmag >= c_lgt:\n raise ValueError('Velocity was {}, which exceeds c.'.format(vmag))\n return 1/sqrt(1-vmag**2/c_lgt**2)",
"def calcLorentzGammaFromMomentum(self,direction):\n if self.mass is None:\n raise CoordinateVector(\"The particle mas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assuming no forces, advances the particle's position over the provided time. | def advancePosition(self,time):
velocity = self.getVelocity()
return self.x + time*velocity | [
"def particle_pos(particle, time):\n return particle.pos + particle.dir * particle.speed * (time - particle.time)",
"def advanceVelocity(self,time,acceleration):\n if not isinstance(acceleration,Cartesian3DVector):\n raise CoordinateException(\"Advancing particle momentum with the incorrect acceleratio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Advances the particle's momentum over the provided time. | def advanceVelocity(self,time,acceleration):
if not isinstance(acceleration,Cartesian3DVector):
raise CoordinateException("Advancing particle momentum with the incorrect acceleration type.")
return self.v + time*acceleration | [
"def advancePosition(self,time):\n velocity = self.getVelocity()\n return self.x + time*velocity",
"def update_time(self, time):\n\n # The current time of the graph\n time_updated_until = self.time\n\n # Reset the graph time to be the new value\n self.time = time\n\n # Upd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new particle with the translated position. | def translate(self,translation_vector):
if not isinstance(translation_vector,Cartesian3DVector):
raise CoordinateException("Translating a particle with the incorrect translation vector type.")
new_particle = self.__class__(self.mass,self.x-translation_vector,self.p)
return new_particle | [
"def translate(self,translation_vector):\n if isinstance(translation_vector,Cartesian3DVector):\n new_particle = self.__class__(self.mass,self.time,x=self.x-translation_vector,p=self.p)\n return new_particle\n raise CoordinateException(\"Translating a particle with the incorrect translation vector t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wraps the calc energy method skipping it if the energy is already stored. | def getEnergy(self):
if not hasattr(self,"energy"):
self.energy = self.calcEnergy()
return self.energy | [
"def _update_energies(self) -> NoReturn:\n self._currentTotPot = self.calculate_total_potential_energy()\n self._currentTotKin = self.calculate_total_kinetic_energy()\n self._currentTotE = self._currentTotPot if (np.isnan(self._currentTotKin)) else np.add(self._currentTotKin,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the time to the object and then passes control back to ParticlePhaseCoordinates() | def __init__(self,mass,time,**kwargs):
self.setTime(time)
ParticlePhaseCoordinates.__init__(self,mass,**kwargs) | [
"def _add_time(self):\n\n self.params[self.EventParams.TIME] = int(round(time.time() * 1000))",
"def add(self, time):\n\n self.elapsed_time = self.elapsed_time + time",
"def _add_time(self):\n\n self.params[self.EventParams.TIME] = int(time.time())",
"def add_time(self,time):\n self.time +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The standard set function for time. | def setTime(self,time):
self.time = time | [
"def set_time(self, time):\n pass",
"def set_time(self, set_time):\n\n self._set_time = set_time",
"def set_time(self, time):\n self._time = time",
"def __setitem__(self, time, value):\n return self.set(time, value)",
"def set_time(self, time):\n self.hours = time[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new particle with the translated position. | def translate(self,translation_vector):
if isinstance(translation_vector,Cartesian3DVector):
new_particle = self.__class__(self.mass,self.time,x=self.x-translation_vector,p=self.p)
return new_particle
raise CoordinateException("Translating a particle with the incorrect translation vector type.") | [
"def translate(self,translation_vector):\n if not isinstance(translation_vector,Cartesian3DVector):\n raise CoordinateException(\"Translating a particle with the incorrect translation vector type.\")\n new_particle = self.__class__(self.mass,self.x-translation_vector,self.p)\n return new_particle",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the time to the string argument from ParticlePhaseCoordinates. | def __str__(self):
return str(self.time)+" " + " ".join(ParticlePhaseCoordinates.__str__(self)) | [
"def _add_time(self):\n\n self.params[self.EventParams.TIME] = int(round(time.time() * 1000))",
"def _add_time(self):\n\n self.params[self.EventParams.TIME] = int(time.time())",
"def VMD_string(self, time):\n # First add preamble:\n # N_data\n # Point = time\n # ...\n VM... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
P0, P1, P2, and P3 should be (x,y) point pairs that define the CatmullRom spline. nPoints is the number of points to include in this curve segment. | def CatmullRomSpline(P0, P1, P2, P3, nPoints=100):
# Convert the points to numpy so that we can do array multiplication
P0, P1, P2, P3 = map(np.array, [P0, P1, P2, P3])
# Calculate t0 to t4
alpha = 0.5
def tj(ti, Pi, Pj):
xi, yi = Pi
xj, yj = Pj
return ( ( (xj-xi)**2 + (yj-yi)**2 )**0.5 )**alpha ... | [
"def CatmullRomSpline(P0, P1, P2, P3, nPoints=100):\n # Convert the points to numpy so that we can do array multiplication\n P0, P1, P2, P3 = map(np.array, [P0, P1, P2, P3])\n\n # Calculate t0 to t4\n alpha = 0.5\n def tj(ti, Pi, Pj):\n xi, yi = Pi\n xj, yj = Pj\n return ( ( (xj-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate Catmull Rom for a chain of points and return the combined curve. | def CatmullRomChain(P, n_points=100):
sz = len(P)
# The curve C will contain an array of (x,y) points.
C = []
for i in range(sz-3):
c = CatmullRomSpline(P[i], P[i+1], P[i+2], P[i+3], nPoints=n_points)
C.extend(c)
return C | [
"def CatmullRomChain(P, n_points=100):\n sz = len(P)\n\n # The curve C will contain an array of (x,y) points.\n C = []\n for i in range(sz - 3):\n c = CatmullRomSpline(P[i], P[i + 1], P[i + 2], P[i + 3], nPoints=n_points)\n C.extend(c)\n\n return C",
"def CatmullRomSpline(P0, P1, P2, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialization method attempts to open the database and create the connection and cursor objects. Raises an exception if the database does not exist at the path. | def __init__(self, in_db_path, in_db_name):
if not os.path.isfile(in_db_path + in_db_name):
self._connection, self._cursor = None, None
raise Exception('PASSED IN DATABASE PATH IS NOT VALID.')
else:
self._connection = sqlite3.connect(in_db_path + in_db_name)
... | [
"def _init_db(self):\n should_init = not os.path.exists(self._db_file)\n self._conn = sqlite3.connect(self._db_file)\n self._cur = self._conn.cursor()\n if should_init:\n logging.info('Creating new database file '+self._db_file)\n sql = \"CREATE table posts (id INTE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |