query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Returns whether or not SWO is enabled. | def swo_enabled(self):
return self._swo_enabled | [
"def isSledIOEnabled(self):\n mode = self.getSledIOMode()\n if mode.lower() == 'off':\n return False\n else:\n return True",
"def enabled(self) -> bool:\n return self._controller[\"enabled\"]",
"def _is_sriov_enabled(self):\n return (self._get_bios_settin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables SWO output on the target device. Configures the output protocol, the SWO output speed, and enables any ITM & stimulus ports. This is equivalent to calling ``.swo_start()``. | def swo_enable(self, cpu_speed, swo_speed=9600, port_mask=0x01):
if self.swo_enabled():
self.swo_stop()
res = self._dll.JLINKARM_SWO_EnableTarget(cpu_speed,
swo_speed,
enums.JLinkSWOInterface... | [
"def enableSledIO(self):\n resp = self.sledIOCmdProxy('set mode', 'motor_cmd')",
"def enable_output(self):\n\n self.__rtcconfig = self.__helper.updatebyte(self.__rtcconfig, 7, 1)\n self.__rtcconfig = self.__helper.updatebyte(self.__rtcconfig, 4, 1)\n self.__bus.write_byte_data(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disables ITM & Stimulus ports. | def swo_disable(self, port_mask):
res = self._dll.JLINKARM_SWO_DisableTarget(port_mask)
if res != 0:
raise errors.JLinkException(res)
return None | [
"def disable_switch_port(self, mgr, interface):\n confstr = snipp.CMD_NO_SWITCHPORT % (interface)\n confstr = self.create_xml_snippet(confstr)\n LOG.debug(\"NexusDriver: %s\" % confstr)\n mgr.edit_config(target='running', config=confstr)",
"def port_disable(self, port_num: int) -> None... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flushes data from the SWO buffer. After this method is called, the flushed part of the SWO buffer is empty. If ``num_bytes`` is not present, flushes all data currently in the SWO buffer. | def swo_flush(self, num_bytes=None):
if num_bytes is None:
num_bytes = self.swo_num_bytes()
buf = ctypes.c_uint32(num_bytes)
res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.FLUSH,
ctypes.byref(buf))
if res < 0:
... | [
"def flush(self):\n if self._writable:\n with self._seek_lock:\n self._flush_raw_or_buffered()\n self._write_buffer = bytearray(self._buffer_size)\n self._buffer_seek = 0",
"def flush(self, data):",
"def flush(self):\n self.buffer = self.buffer[-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves information about the supported SWO speeds. | def swo_speed_info(self):
info = structs.JLinkSWOSpeedInfo()
res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_SPEED_INFO,
ctypes.byref(info))
if res < 0:
raise errors.JLinkException(res)
return info | [
"def speed_list(self) -> Optional[List[str]]:\n if not self._static_info.supports_speed:\n return None\n return [SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH]",
"def swo_supported_speeds(self, cpu_speed, num_speeds=3):\n buf_size = num_speeds\n buf = (ctypes.c_uint32 * buf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrives the number of bytes in the SWO buffer. | def swo_num_bytes(self):
res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_NUM_BYTES,
0)
if res < 0:
raise errors.JLinkException(res)
return res | [
"def getBufferLen(self):\n return(len(self.buffer))",
"def size(self):\n return len(self.buffer)",
"def len (self):\n return len (self._buf)",
"def get_size(self):\n return self.buffer_size",
"def __len__(self):\n return len(self.buffer)",
"def buffer_count(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the size of the buffer used by the host to collect SWO data. | def swo_set_host_buffer_size(self, buf_size):
buf = ctypes.c_uint32(buf_size)
res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST,
ctypes.byref(buf))
if res < 0:
raise errors.JLinkException(res)
return ... | [
"def set_buffer_size(self,buffer_size: int):\n self.buffer_size = buffer_size\n return self",
"def strace_set_buffer_size(self, size):\n size = ctypes.c_uint32(size)\n res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.SET_BUFFER_SIZE, size)\n if res < 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrives a list of SWO speeds supported by both the target and the connected JLink. The supported speeds are returned in order from highest to lowest. | def swo_supported_speeds(self, cpu_speed, num_speeds=3):
buf_size = num_speeds
buf = (ctypes.c_uint32 * buf_size)()
res = self._dll.JLINKARM_SWO_GetCompatibleSpeeds(cpu_speed, 0, buf, buf_size)
if res < 0:
raise errors.JLinkException(res)
return list(buf)[:res] | [
"def speed_list(self) -> list:\n wink_supported_speeds = self.wink.fan_speeds()\n supported_speeds = []\n if SPEED_AUTO in wink_supported_speeds:\n supported_speeds.append(SPEED_AUTO)\n if SPEED_LOWEST in wink_supported_speeds:\n supported_speeds.append(SPEED_LOWEST... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads data from the SWO buffer. The data read is not automatically removed from the SWO buffer after reading unless ``remove`` is ``True``. Otherwise the callee must explicitly remove the data by calling ``.swo_flush()``. | def swo_read(self, offset, num_bytes, remove=False):
buf_size = ctypes.c_uint32(num_bytes)
buf = (ctypes.c_uint8 * num_bytes)(0)
self._dll.JLINKARM_SWO_Read(buf, offset, ctypes.byref(buf_size))
# After the call, ``buf_size`` has been modified to be the actual
# number of bytes ... | [
"def read(self, nsamp=None, remove=True): ###\n available = self.to_read()\n if nsamp == None:\n nsamp = available\n if nsamp > available:\n raise RuntimeError(\"ring buffer underflow\")\n x = numpy.zeros((self.channels(), nsamp), dtype=self.buf.dtype)\n n =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the printable data via SWO. This method reads SWO for one stimulus port, which is all printable data. | def swo_read_stimulus(self, port, num_bytes):
if port < 0 or port > 31:
raise ValueError('Invalid port number: %s' % port)
buf_size = num_bytes
buf = (ctypes.c_uint8 * buf_size)()
bytes_read = self._dll.JLINKARM_SWO_ReadStimulus(port, buf, buf_size)
return list(buf)... | [
"def read_data(self):\n\t\t\n\t\tself.wii_init()\n\t\tsleep(0.01)\n\t\t# Para leer del Nunchuck primero se debe enviar un comando 0x00\n\t\t# y después leer 6 bytes de información\n\t\t#\n\t\t# La información recibida debe ser decodificada realizando\n\t\t# XOR con 0x17 y después sumando 0x17\n\t\ttry:\t\n\t\t\tsel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops RTT on the JLink and host side. | def rtt_stop(self):
self.rtt_control(enums.JLinkRTTCommand.STOP, None) | [
"async def stop_rtsp_livestream(self):\n await self.api.stop_rtsp_livestream(self.product_type, self.serial_no)",
"def stop():\n server = current_server()\n server.stop()",
"def stop(self):\n self._netal.stop()",
"def stopAndDisconnectWalabot():\n wlbt.Stop()\n wlbt.Disconnect()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
After starting RTT, get the descriptor for an RTT control block. | def rtt_get_buf_descriptor(self, buffer_index, up):
desc = structs.JLinkRTTerminalBufDesc()
desc.BufferIndex = buffer_index
desc.Direction = 0 if up else 1
self.rtt_control(enums.JLinkRTTCommand.GETDESC, desc)
return desc | [
"def open_CtlDataset(desfile, returnctl=False, encoding='GBK'):\r\n if isinstance(desfile, str):\r\n if not desfile.endswith('.ctl'):\r\n raise Exception('unsupported file, suffix should be .ctl')\r\n\r\n ctl = CtlDescriptor(encoding=encoding, file=desfile)\r\n elif isinstance(desfile... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
After starting RTT, get the current number of up buffers. | def rtt_get_num_up_buffers(self):
cmd = enums.JLinkRTTCommand.GETNUMBUF
dir = ctypes.c_int(enums.JLinkRTTDirection.UP)
return self.rtt_control(cmd, dir) | [
"def rtt_get_num_down_buffers(self):\n cmd = enums.JLinkRTTCommand.GETNUMBUF\n dir = ctypes.c_int(enums.JLinkRTTDirection.DOWN)\n return self.rtt_control(cmd, dir)",
"def buffer_count(self):\n self.send_command(\"GET_BUFFER_COUNT\")\n return int(self.latest_response)",
"def ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
After starting RTT, get the current number of down buffers. | def rtt_get_num_down_buffers(self):
cmd = enums.JLinkRTTCommand.GETNUMBUF
dir = ctypes.c_int(enums.JLinkRTTDirection.DOWN)
return self.rtt_control(cmd, dir) | [
"def rtt_get_num_up_buffers(self):\n cmd = enums.JLinkRTTCommand.GETNUMBUF\n dir = ctypes.c_int(enums.JLinkRTTDirection.UP)\n return self.rtt_control(cmd, dir)",
"def buffer_count(self):\n self.send_command(\"GET_BUFFER_COUNT\")\n return int(self.latest_response)",
"def _get_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
After starting RTT, get the status. | def rtt_get_status(self):
status = structs.JLinkRTTerminalStatus()
res = self.rtt_control(enums.JLinkRTTCommand.GETSTAT, status)
return status | [
"def _read_status(self):",
"def get_status(self):\n\n resp = self.sendcmd('TS', '?', expect_response=True, retry=10)\n errors = int(resp[0:4], 16)\n state = resp[4:]\n\n assert len(state) == 2\n\n return errors, state",
"def status(self):\n stat = self.run_status.get()\n return stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads data from the RTT buffer. This method will read at most num_bytes bytes from the specified RTT buffer. The data is automatically removed from the RTT buffer. If there are not num_bytes bytes waiting in the RTT buffer, the entire contents of the RTT buffer will be read. | def rtt_read(self, buffer_index, num_bytes):
buf = (ctypes.c_ubyte * num_bytes)()
bytes_read = self._dll.JLINK_RTTERMINAL_Read(buffer_index, buf, num_bytes)
if bytes_read < 0:
raise errors.JLinkRTTException(bytes_read)
return list(buf[:bytes_read]) | [
"def read_bytes(self, number_of_bytes):\n\n self.index = -1\n data = self.buf[self.offset:self.offset + number_of_bytes]\n self.offset += number_of_bytes\n\n return data",
"def read(self, numbytes):\n # a file in non-blocking mode may return less bytes, so we loop\n buf =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Issues an RTT Control command. All RTT control is done through a single API call which expects specifically laidout configuration structures. | def rtt_control(self, command, config):
config_byref = ctypes.byref(config) if config is not None else None
res = self._dll.JLINK_RTTERMINAL_Control(command, config_byref)
if res < 0:
raise errors.JLinkRTTException(res)
return res | [
"def set_control_commands(self, ref_state, ref_ind):\n super(DummyVehicle, self).set_control_commands(ref_state, ref_ind)\n safety_distance = 20.\n full_stop_distance = 15.\n\n\n self.check_if_overtake_is_finished()\n\n # Only continue from this point if there are some radar sensi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether target has CP15 coprocessor. | def cp15_present(self):
result = False
if self._dll.JLINKARM_CP15_IsPresent() != 0:
result = True
return result | [
"def is_fcc_on(self):\n raise NotImplementedError",
"def has_fcc(self):\n if not self.simulation_mode:\n return \"yes\" in self.sem_api.Get('DP_CAPCC_FITTED', 0)[1].lower()\n return False",
"def is_fcc_on(self):\n return \"yes\" in self.sem_api.Get('DP_CAPCC_INUSE', 0)[1].... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create namespace for amq | def _create_namespace(self):
self.ocp.new_project(self.namespace) | [
"def createNamespace(self):\r\n raise NotImplementedError('Endpoint can not be used directly.')",
"def test_create_net_namespace(self):\n pass",
"def xmlrpc_namespace():",
"def create_namespace(self, request):\n return self._create(request, u\"namespaces\")",
"def createNamespace(pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clone the amq repo | def _clone_amq(self):
self.dir = tempfile.mkdtemp(prefix='amq_')
try:
log.info(f'cloning amq in {self.dir}')
git_clone_cmd = f'git clone -b {self.branch} {self.repo} '
run(
git_clone_cmd,
shell=True,
cwd=self.dir,
... | [
"def git_clone_target_repo(self):\r\n self.repo = git.Repo.clone_from(self.target_repo_url, self.local_gitlab_runner_repo)\r\n print(\"Cloning Repo - completed ....\")",
"def clone_repo():\r\n run('git clone %(repository_url)s %(repo_path)s' % env)",
"def checkout_qmk():\n if exists('qmk_fir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to setup amqcluster_operator, the file file is pulling from github it will make sure clusteroperator pod is running | def setup_amq_cluster_operator(self):
# self.amq_dir = constants.TEMPLATE_DEPLOYMENT_AMQ_CP
run(f'oc apply -f {self.amq_dir} -n {self.namespace}', shell=True, check=True, cwd=self.dir)
time.sleep(5)
# Wait for strimzi-cluster-operator pod to be created
if self.is_amq_pod_running... | [
"def setup_amq(self):\n self.setup_amq_cluster_operator()\n self.setup_amq_kafka_persistent()\n self.setup_amq_kafka_connect()\n self.setup_amq_kafka_bridge()\n self.amq_is_setup = True\n return self",
"def setup(args):\n gke = discovery.build(\"container\", \"v1\")\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function checks if provided pod_pattern finds a pod and if the status is running or not | def is_amq_pod_running(self, pod_pattern="cluster-operator"):
for pod in TimeoutSampler(
300, 10, get_pod_name_by_pattern, pod_pattern, self.namespace
):
try:
if pod[0] is not None:
amq_pod = pod[0]
break
except ... | [
"def _is_pod_scheduled(pod):\n try:\n return (pod['spec']['nodeName'] and\n pod['status']['phase'] == constants.K8S_POD_STATUS_PENDING)\n except KeyError:\n return False",
"def check_pod_status(k8s_client, name, namespace=\"default\", state=\"Running\"):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function is to setup amqkafkaconnect, the yaml file is pulling from github | def setup_amq_kafka_connect(self):
try:
kafka_connect = templating.load_yaml(os.path.join(self.dir, self.amq_kafka_connect_yaml))
self.kafka_connect = OCS(**kafka_connect)
self.kafka_connect.create()
except(CommandFailed, CalledProcessError) as cf:
log.err... | [
"def install(self):\n #Check nodes are accessible:\n for n in (self.allnodes):\n if not setup.check_nodes(n):\n sys.exit(\"Can't reach node:{}, exiting install, check that the IPs in your config file are correct.\")\n log.info(\"All nodes are accessible\")\n # Dow... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup AMQ from local folder, function will call all necessary sub functions to make sure amq installation is complete | def setup_amq(self):
self.setup_amq_cluster_operator()
self.setup_amq_kafka_persistent()
self.setup_amq_kafka_connect()
self.setup_amq_kafka_bridge()
self.amq_is_setup = True
return self | [
"def qa_init():\r\n _, qatools_config_paths = find_qatools_configs(Path('.'))\r\n if qatools_config_paths:\r\n click.secho(f'You already have a qatools.yaml configuration:', fg='green', bold=True, err=True)\r\n for p in qatools_config_paths:\r\n click.secho(str(p), fg='green')\r\n exit(0)\r\n\r\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean up function, will start to delete from amq cluster operator then amqconnector, persistent, bridge, at the end it will delete the created namespace | def cleanup(self):
if self.amq_is_setup:
self.kafka_persistent.delete()
self.kafka_connect.delete()
self.kafka_bridge.delete()
run_cmd(f'oc delete -f {self.amq_dir}', shell=True, check=True, cwd=self.dir)
run_cmd(f'oc delete -f {self.amq_dir_examples}'... | [
"def cleanup(self):\n switch_to_project(constants.COUCHBASE_OPERATOR)\n if self.cb_create_cb_secret:\n self.cb_secrets._is_deleted = False\n self.cb_secrets.delete()\n if self.cb_create_cb_cluster:\n self.cb_example._is_deleted = False\n self.cb_examp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return dividends (array) mod divisor (double) | def mod(dividends, divisor):
output = np.zeros(len(dividends))
for i in tqdm(range(len(dividends))):
output[i] = dividends[i]
done=False
while (not done):
if output[i] >= divisor:
output[i] -= divisor
elif output[i] < 0.:
output[... | [
"def divisible_by(array, divisor):\n return_list = list()\n for i in array:\n if i % divisor == 0:\n return_list.append(i)\n return return_list",
"def getDivisors(n):",
"def divisors(number):\n alld = []\n for i in range(1, number // 2 +1): #round(math.sqrt(number))+2\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asserts the correct number of keys have been loaded in the dictionary | def test_load_from_file_to_dict_key_length(self):
self.assertEqual(len(self.loaded_json_dict), 3) | [
"def test_txt_loader_dict_key_length(self):\n self.assertEqual(1, len(self.citation_dict.keys()))",
"def test_txt_loader_dict_values_length(self):\n self.assertEqual(\n 1553, len(self.citation_dict[self.expected_dict_keys[0]]))",
"def test_has_correct_number_of_keys_and_values(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves an access token from the specified URL | def get_access_token(self, token_url):
# type: (str) -> str
payload = {
"grant_type" : "client_credentials",
"client_id" : self.client_id,
"client_secret" : self.client_secret,
"scope" : self.client_scope,
}
headers = {
"accept... | [
"def _oauth2_request(self, url, token, token_param='access_token'):\n target_url = url.format(urlencode({token_param:token}))\n return urlfetch.fetch(target_url).content",
"def fetch_oauth_access_token(consumer_token, request_token):\n url = get_oauth_access_token_url(consumer_token, request_token)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recieves raven_automove msgs, calls talker to update raven sim joint positions | def raven_automove_listener(Raven):
th = np.pi / 2
Raven.T = RotX4_N(-3*th) * RotY4_N(-th)
Raven.T[0,3] = 0.2
Raven.T[1,3] = 0.0
Raven.T[2,3] = -2.2
rospy.init_node('msg_converter', anonymous=True)
rospy.Subscriber("/automove_test", raven_automove, callback, Raven)
rospy.spin() | [
"def raven_automove_listener(Raven):\n # (-0.12, 0.04, 0.0) works with world rpy=\"0 ${PI/2} ${-PI/2}\"/>, theta2joint\n # gazebo (x left, y out, z up)\n # raven (x out, y down, z right)\n # enter gazebo coords -> raven coords => (x, y, z) -> (y, -z, -x)\n x = -0.0\n y = 0.09\n z = -0.04\n R... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the network, this means create new hidden state. Batch_size has to be different for inference (1) and training (self.batch_size). | def reset(self, batch_size: Optional[int] = 1):
self.hidden = self.get_hidden(batch_size) | [
"def reset(self):\n\t\ttf.reset_default_graph()\n\t\tdel self.train_x_state, self.train_y_state\n\t\tdel self.test_x_state, self.test_y_state",
"def reset(self):\n\n # Reset everything\n self._layers = OrderedDict()\n self._connections = defaultdict(list)\n self._learning_rules = dict(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the network, this means create new hidden state. Batch_size has to be different for inference (1) and training (self.batch_size). | def reset(self, batch_size: Optional[int] = 1):
self.hidden = self.get_hidden(batch_size) | [
"def reset(self):\n\t\ttf.reset_default_graph()\n\t\tdel self.train_x_state, self.train_y_state\n\t\tdel self.test_x_state, self.test_y_state",
"def reset(self):\n\n # Reset everything\n self._layers = OrderedDict()\n self._connections = defaultdict(list)\n self._learning_rules = dict(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in a one dimensional array of weights and repeats them to match shape Shape is expected to have the channels as the final dimension. | def repeat_weights(weights, shape):
weights_extra = weights.unsqueeze(-1)
return weights_extra.expand(
weights.shape[0], shape[-1]).reshape(shape) | [
"def cycle_rgb_weights(weights, n):\n slices = [(c % 3, c % 3 + 1) for c in range(n)] # slice a:a+1 to keep dims\n new_weights = torch.cat([\n weights[:, a:b, :, :] for a, b in slices\n ], dim=1)\n return new_weights",
"def _prepare_weights(orig_array,weights):\n weights_broadcast = np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples a large torch array using indexes, which are x, y arrays Reshapes output to desired_shape | def torch_big_sample(array, indexes, desired_shape):
torch_arr = torch.tensor(array, dtype=torch.float32)
indexed = torch_arr[[indexes[0], indexes[1]]]
return indexed.reshape(desired_shape)
#chunked = torch.chunk(indexed, desired_shape[0])
#chunked = [chunk.reshape(desired_shape[1:]) for chunk in ch... | [
"def _get_batch_of_transformed_samples(self, index_array: np.array):",
"def sample(num_dims, num_samples):\n samples = np.random.rand(num_samples, num_dims)\n ### TODO: Update with a uniform sampling plan to fill space\n return samples",
"def batchwise_sample(gen, num_samples, batch_size):\n\n sampl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a forward warped novel from an input image and disparity_map For each pixel position in the reference view, shift it by the disparity, and assign the value in the reference at that new pixel position to the novel view. | def fw_warp_image(
ref_view, disparity_map, ref_pos, novel_pos,
dtype=np.uint8, blank=0):
size_x, size_y = ref_view.shape[0:2]
distance = ref_pos - novel_pos
#Initialise an array of blanks
novel_view = np.full(ref_view.shape, blank, dtype=dtype)
#Create an array of pixel positions
grid... | [
"def slow_fw_warp_image(ref_view, disparity_map, ref_pos, novel_pos):\n size_x, size_y = ref_view.shape[0:2]\n distance = ref_pos - novel_pos\n\n novel_view = np.zeros(ref_view.shape, dtype=np.uint8)\n for x in range(size_x):\n for y in range(size_y):\n res = np.repeat(disparity_map[x,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a forward warped novel from an input image and disparity_map For each pixel position in the reference view, shift it by the disparity, and assign the value in the reference at that new pixel position to the novel view. Has a very large for loop, performance is much slower than fw_warp_image | def slow_fw_warp_image(ref_view, disparity_map, ref_pos, novel_pos):
size_x, size_y = ref_view.shape[0:2]
distance = ref_pos - novel_pos
novel_view = np.zeros(ref_view.shape, dtype=np.uint8)
for x in range(size_x):
for y in range(size_y):
res = np.repeat(disparity_map[x, y], 2, -1) ... | [
"def fw_warp_image(\n ref_view, disparity_map, ref_pos, novel_pos,\n dtype=np.uint8, blank=0):\n size_x, size_y = ref_view.shape[0:2]\n distance = ref_pos - novel_pos\n\n #Initialise an array of blanks\n novel_view = np.full(ref_view.shape, blank, dtype=dtype)\n\n #Create an array of pixel posi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves an array as an image at the save_location using pillow | def save_array_as_image(array, save_location):
image = Image.fromarray(array)
image.save(save_location)
image.close() | [
"def save_image(arr, path):\n im = Image.fromarray(arr)\n im.save(path)",
"def array_image_save(array, image_path):\n image = Image.fromarray(array)\n if image.mode != 'RGB':\n image = image.convert('RGB')\n image.save(image_path)\n print(\"Saved image: {}\".format(image_path))",
"def save_image(im... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new database session. | def create_new_session():
database_engine = create_engine(SQLITE_FILE)
DeclarativeBase.metadata.create_all(database_engine)
DeclarativeBase.bind = database_engine
session = sessionmaker()
session.configure(bind=database_engine)
return session() | [
"def create_session():\n DB_session = sessionmaker(bind=engine)\n session = DB_session()\n return session",
"def create(self):\r\n sessId = Session.generateId()\r\n return Session(sessId)",
"def create_db_session(self):\n mysql_conn_str = f\"mysql+pymysql://{self.DB_USER}:{self.DB_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encrypts a string with the included public Key. AString String to Encrypt PK Pycrypto PublicKey to encrypt with. sEncrypted = EncryptAString("This will be encrypted", myPK) | def EncryptAString(AString):
key = RSA.importKey(self.public)
return key.encrypt(AString, 101) | [
"def encrypt(string,pub):\r\n string = livingDead.utfE(string)\r\n crypto = rsa.encrypt(string, pub)\r\n return crypto",
"def testEncryptString(self):\n g=gpg.GPG(gpg.findGPG())\n encrypted, warnings=g.encryptString(['primary'], 'hello')\n self.assertEncrypted... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert epoch to given format | def epoch_to_format(epoch, format='%Y-%m-%dT%H:%M:%SZ'):
return datetime.fromtimestamp(int(epoch[:10]), tz=timezone.utc).strftime(format) | [
"def epoch_to_format(format, epoch):\n\n return datetime.fromtimestamp(int(epoch[:10]), tz=timezone.utc).strftime(format)",
"def epoch_to_date(epoch):\n date_string = datetime.datetime.fromtimestamp(epoch/10**6).strftime('%m-%d-%Y %H:%M:%S')\n return date_string",
"def epoch_to_str(epoch: int) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests for showing ride urls | def test_show_ride_resolves(self):
url = reverse('showridepage', args=['078508ce-2efc-4316-8987-12b9551be5b4'])
self.assertEquals(resolve(url).func, show_ride) # pylint: disable=deprecated-method | [
"def test_view_url_accessible_by_name(self):\n response = self.client.get(reverse('apparel'))\n self.assertEqual(response.status_code, 200)",
"def test_view_url_exists_at_desired_location(self):\n response = self.client.get('')\n self.assertEqual(response.status_code, 200)",
"def tes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test optimization of selected terms in CCD equations. This purpose of this test is mostly on the treatment of term in the present of symmetries. | def test_ccd_doubles_terms(parthole_drudge):
dr = parthole_drudge
p = dr.names
a, b, c, d = p.V_dumms[:4]
i, j, k, l = p.O_dumms[:4]
u = dr.two_body
t = IndexedBase('t')
dr.set_dbbar_base(t, 2)
r = IndexedBase('r')
tensor = dr.define_einst(
r[a, b, i, j],
+ t[a, b,... | [
"def test_ccsd_singles_terms(parthole_drudge):\n\n dr = parthole_drudge\n p = dr.names\n\n a, b, c = p.V_dumms[:3]\n i, j, k = p.O_dumms[:3]\n u = dr.two_body\n f = dr.fock\n t = IndexedBase('t')\n dr.set_dbbar_base(t, 2)\n\n r = IndexedBase('r')\n tensor = dr.define_einst(\n r[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test selected terms in CCSD singles equation. The purpose of this test is the capability of recognition of repeated appearance of the same summation intermediates. | def test_ccsd_singles_terms(parthole_drudge):
dr = parthole_drudge
p = dr.names
a, b, c = p.V_dumms[:3]
i, j, k = p.O_dumms[:3]
u = dr.two_body
f = dr.fock
t = IndexedBase('t')
dr.set_dbbar_base(t, 2)
r = IndexedBase('r')
tensor = dr.define_einst(
r[a, i],
t[a,... | [
"def test_ccd_doubles_terms(parthole_drudge):\n\n dr = parthole_drudge\n p = dr.names\n\n a, b, c, d = p.V_dumms[:4]\n i, j, k, l = p.O_dumms[:4]\n u = dr.two_body\n t = IndexedBase('t')\n dr.set_dbbar_base(t, 2)\n\n r = IndexedBase('r')\n tensor = dr.define_einst(\n r[a, b, i, j],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test discovery of effective T in CCSD energy equation. The purpose of this test is the capability of using locally nonoptimal contractions in the final summation optimization. The equation is not CCSD energy equation exactly. | def test_ccsd_energy(parthole_drudge):
dr = parthole_drudge
p = dr.names
a, b = p.V_dumms[:2]
i, j = p.O_dumms[:2]
u = dr.two_body
t = IndexedBase('t')
energy = dr.define_einst(
Symbol('e'),
u[i, j, a, b] * t[a, b, i, j] * Rational(1, 2)
+ u[i, j, a, b] * t[a, i] *... | [
"def solve_TDSE(params, wavefunction_initial):\n\n # Initilise density\n density = np.zeros((params.Ntime,params.Nspace))\n density[0,:] = calculate_density_exact(params, wavefunction_initial)\n wavefunction = np.copy(wavefunction_initial)\n\n # Time stepping defined by numpy's expm function\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push base_repo code to this repo | def push(self, base_repo, branch="master"):
base_repo.push_to(self, branch) | [
"def push(self, base_repo, branch: str = \"master\") -> None:\n raise NotImplementedError",
"def repo_push(self):\n\n if self.clowder_repo is None:\n exit_clowder_not_found()\n\n if is_offline():\n print(fmt.offline_error())\n sys.exit(1)\n\n self.clowd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a junitxml filename or path to said file. From this file it extracts the testsuite node and adds it to the junit_docker.xml file, in the process it adds a name to the testsuite (the suite param) and changes the classname from tests. to {suite}. Finaly, it removes the original file. This is because jenkins was not... | def merge_to_junit_xml(filename: str, suite: str) -> None:
junit_docker = Path("junit_docker.xml")
if junit_docker.exists():
tree = ElementTree.parse(junit_docker)
root = tree.getroot()
for testsuite in root:
if testsuite.get("name", None) == suite:
root.remov... | [
"def _write_test_file(self):\n with open('nlt-junit.xml', 'w') as file:\n junit_xml.TestSuite.to_file(file, [self.test_suite], prettyprint=True)",
"def resmoke2junit(skip_long_lines=1):\n\n cwd = os.getcwd()\n error_log = deque(\"\",200)\n\n with open('junit.xml', 'w') as junitfile:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter the queryset based on the provided report ID values. As each 'report' instance may optionally define its own filters, the resulting queryset is the 'union' of the two | def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
items = self.get_items()
if len(items) > 0:
"""At this point, we are basically forced to be inefficient:
We need to compare the 'filters' string of each report template,
and ... | [
"def _report_filters(self):\n filter_type_map = {\n 'Choice': 'dynamic_choice_list',\n 'Date': 'date',\n 'Numeric': 'numeric'\n }\n\n def _make_report_filter(conf):\n col_id = self.data_source_properties[conf[\"property\"]]['column_id']\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Default implementation of GET for a print endpoint. Note that it expects the class has defined a get_items() method | def get(self, request, *args, **kwargs):
items = self.get_items()
return self.print(request, items) | [
"def list(self, *args, **kwargs):\n kwargs['methods'] = ['GET']\n return self.flexible_route('/', *args, **kwargs)",
"def _get(self, *args, **kwargs):\n return self._request('get', *args, **kwargs)",
"def _get(self, *args, **kwargs):\n return self._request(requests.get, *args, **kwar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.ComputeStructuredCoordinates(vtkAMRBox, (float, float, float), ( float, float, float), (float, float, float), [int, int, int], [float, float, float]) > int | def ComputeStructuredCoordinates(self, vtkAMRBox, , , , p_int=..., p_int=..., p_int=..., *args, **kwargs):
... | [
"def GetBoxOrigin(self, vtkAMRBox, , , p_float=..., p_float=..., p_float=...):\n ...",
"def ComputeStructuredCoordinates(self, , p_int=..., p_int=..., p_int=..., *args, **kwargs):\n ...",
"def DoesBoxIntersectAlongDimension(self, vtkAMRBox, p_int):\n ...",
"def GetBounds(self, vtkAMRBox, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.DoesBoxIntersectAlongDimension(vtkAMRBox, int) > bool | def DoesBoxIntersectAlongDimension(self, vtkAMRBox, p_int):
... | [
"def inside(point, box):\n return (np.all(np.greater_equal(point, box[1, :])) and np.all(np.less_equal(point, box[0, :])))",
"def box_in_image(box, image):\r\n rows = image.shape[0]\r\n cols = image.shape[1]\r\n return box[0] >= 0 and box[1] >= 0 and box[2] <= cols and box[3] <= rows",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.GetBounds(vtkAMRBox, (float, float, float), (float, float, float), [float, float, float, float, float, float]) | def GetBounds(self, vtkAMRBox, , , p_float=..., p_float=..., p_float=..., p_float=..., p_float=..., p_float=...):
... | [
"def bounds(self):\n return self._bboxes[0][0] #TODO: merge all coverages",
"def GetBounds(self):\n ...",
"def GetBoxOrigin(self, vtkAMRBox, , , p_float=..., p_float=..., p_float=...):\n ...",
"def mesh_bounding_box(mesh):\n xyz = mesh.vertices_attributes(\"xyz\", keys=list(mesh.vertices())... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.GetBoxOrigin(vtkAMRBox, (float, float, float), (float, float, float), [float, float, float]) | def GetBoxOrigin(self, vtkAMRBox, , , p_float=..., p_float=..., p_float=...):
... | [
"def ComputeStructuredCoordinates(self, vtkAMRBox, , , , p_int=..., p_int=..., p_int=..., *args, **kwargs):\n ...",
"def GetBounds(self, vtkAMRBox, , , p_float=..., p_float=..., p_float=..., p_float=..., p_float=..., p_float=...):\n ...",
"def __init__(self, boxCoord):\n self.boxCoord =boxCoord... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.GetCellLinearIndex(vtkAMRBox, int, int, int, [int, int, int]) > int | def GetCellLinearIndex(self, vtkAMRBox, p_int, p_int_1, p_int_2, p_int=..., p_int=..., p_int=...):
... | [
"def DoesBoxIntersectAlongDimension(self, vtkAMRBox, p_int):\n ...",
"def index(self, cell):\n for i,c in enumerate(self.buckets):\n if c is cell:\n return i",
"def CellBoundary(self, p_int, , vtkIdList):\n ...",
"def cell_containing (a):\n k_x = int (a[0] * L... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.GetGhostVector(int, [int, int, int, int, int, int]) | def GetGhostVector(self, p_int, p_int=..., p_int=..., p_int=..., p_int=..., p_int=..., p_int=...):
... | [
"def get_vector(self, source, destination):",
"def Vector():",
"def function(self, vector):\n pass",
"def fun(self,v_vec):\n fx=-self.gamma*v_vec[0]\n fy=-self.g-self.gamma*v_vec[1]\n return np.array([fx,fy])",
"def __getitem__(self, *args):\n return _almathswig.vectorPosi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.GetHiCorner() > (int, ...) | def GetHiCorner(self):
... | [
"def GetLoCorner(self):\n ...",
"def footprint_corner_indices():",
"def GetCorners(self):\n ...",
"def upper_covers(self, x):",
"def _cal_meaningful_corners(self):\n corners = np.where(self._free_of_clash)\n corners = np.array(corners, dtype=int)\n corners = corners.transp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.GetLoCorner() > (int, ...) | def GetLoCorner(self):
... | [
"def GetHiCorner(self):\n ...",
"def GetCorners(self):\n ...",
"def footprint_corner_indices():",
"def right_of(self,v):\n x,y = v[0:2]\n if y < self.ylo: return False\n if y >= self.yhi: return False\n if x > self.xhi: return False\n if x > ((y * self.m) + self.b): return False... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.HasPoint(vtkAMRBox, (float, float, float), (float, float, float) , float, float, float) > bool | def HasPoint(self, vtkAMRBox, , , p_float_6, p_float_7, p_float_8):
... | [
"def DoesBoxIntersectAlongDimension(self, vtkAMRBox, p_int):\n ...",
"def inside(point, box):\n return (np.all(np.greater_equal(point, box[1, :])) and np.all(np.less_equal(point, box[0, :])))",
"def is_point_in_box(x, y, bbox):\n if x < 200 and y < 200:\n return True\n return False",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
V.SetDimensions(int, int, int, int, int, int, int) | def SetDimensions(self, p_int, p_int_1, p_int_2, p_int_3, p_int_4, p_int_5, p_int_6):
... | [
"def setdim(cls, name, values):\n\t\t#FIXME - check values\n\t\tcls.__dim_array__[cls.__getDimKey__(name)] = values",
"def setDimensions(self, *args):\n return _libsbml.Layout_setDimensions(self, *args)",
"def setVoxelSize(self, vxs):\n\t\tself.voxelsize = vxs\n\t\ta, b, c = vxs\n\t\tself.spacing = [1, b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper for the server_default 'userid' above so it is not called through SERVER_DEFAULTS in our code | def get_userid():
return _userid() | [
"def get_default_user_id():\n return get_or_create_user().id",
"def get_default_user():\n engine=Engine(\"defaults\")\n user=engine.get_attrib(\"user\")\n if user==None or user.strip()=='':\n user=engine.prompt_user(\"Enter a default username for sent profile\", str)\n engine.set_attrib(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unknown actions aren't a traceback. | def test_unknown_action(self):
exit_string = actions.main(["foo"])
self.assertEqual("Action foo undefined", exit_string) | [
"def test_unknown_action(self):\n exit_string = actions.main(['foo'])\n self.assertEqual('Action \"foo\" undefined', exit_string)",
"def test_unknown_action(self):\n self.assertFalse(self.animal.do_something(action=\"play\"))\n self.assertFalse(self.animal.do_something(action=\"jump\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Actions which traceback trigger action_fail() calls. | def test_failing_action(self):
dummy_calls = []
self.action_fail.side_effect = dummy_calls.append
def dummy_action(args):
raise ValueError("uh oh")
with mock.patch.dict(actions.ACTIONS, {"foo": dummy_action}):
actions.main(["foo"])
self.assertEqual(dumm... | [
"def test_failing_action(self):\n dummy_calls = []\n\n self.ch_core.hookenv.action_fail.side_effect = dummy_calls.append\n\n def dummy_action(args):\n raise ValueError('uh oh')\n\n with mock.patch.dict(actions.ACTIONS, {'foo': dummy_action}):\n actions.main(['foo'])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add config for VoVNet. | def add_vovnet_config(cfg):
_C = cfg
_C.MODEL.VOVNET = CN()
_C.MODEL.VOVNET.CONV_BODY = "V-39-eSE"
_C.MODEL.VOVNET.OUT_FEATURES = ["stage2", "stage3", "stage4", "stage5"]
# Options: FrozenBN, GN, "SyncBN", "BN"
_C.MODEL.VOVNET.NORM = "FrozenBN"
_C.MODEL.VOVNET.OUT_CHANNELS = 256
_C.... | [
"def add_config(self, type, *config):\n if len(config) == 1:\n config = config[0]\n elif len(config) == 0:\n raise RuntimeError(\"config has no definition\")\n else:\n config = f'{config[0]} ' + ', '.join(config[1:])\n\n self.debug('Adding into Vagrantfil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate and create a list of twitter authentication elements | def twitter_auth(consumer_key=None, consumer_secret=None, access_key=None, access_secret=None):
if not consumer_key:
consumer_key = os.environ.get('T_CONSUMER_KEY', consumer_key)
if not consumer_secret:
consumer_secret = os.environ.get('T_CONSUMER_SECRET', consumer_secret)
if not access_key... | [
"def get_multiple_auth():\n try:\n # edit the config_follow_hashtag to set your twitter credentials\n auths = []\n for consumer_key, consumer_secret in config_follow_hashtag.oauth_keys:\n auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)\n auths.append(auth)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate and create reddit access credentials | def reddit_auth(client_id=None, client_secret=None):
if not client_id:
client_id = os.environ.get('R_CLIENT_ID', client_id)
if not client_secret:
client_secret = os.environ.get('R_CLIENT_SECRET', client_secret)
user_agent = 'smtk:d4d'
# auth = [client_id, client_secret, user_agent]
... | [
"def credentials(self):\n path = Path.cwd().joinpath(\"secrets.json\")\n with open(path) as file:\n secrets = json.load(file)\n\n self.reddit = praw.Reddit(client_id = secrets[\"api_id\"], client_secret = secrets[\"secret\"], \n user_agent = secrets[\"user_agent\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch extended information for the specified users. Users may be specified either as lists of either user_ids, screen_names, or twitter.User objects. The list of users that are queried is the union of all specified parameters. | def UsersLookup_modified(self,
user_id=None,
screen_name=None,
users=None,
include_entities=True,
return_JSON = False):
if not user_id and not screen_name and not users:
raise twitter.TwitterError({'message':... | [
"def user_lookup(\n self,\n users,\n usernames=False,\n expansions=None,\n tweet_fields=None,\n user_fields=None,\n ):\n\n if isinstance(users, str):\n raise TypeError(\"users must be an iterable other than a string\")\n\n if usernames:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split a logfile line into a dict of specific attributes of interest. Initially we just want size and requested file name, so we'll split on spaces and pull the data out. | def split(self, line):
parts = line.split()
return {
'size': 0 if parts[9] == '-' else int(parts[9]),
'file_requested': parts[6]
} | [
"def _parse_line(self, line):\n fields = line.split('|', 4) # stop splitting after fourth | found\n line_info = {'raw_message': line}\n if len(fields) == 5:\n line_info.update(dict(zip(self._fieldnames, fields)))\n return line_info",
"def parse_line(line: str):\n\n log_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is called to generate a random set of data The function gets the values put in by the user scales/sliders | def generate():
global data
data = []
# Generate a random data set
for _ in range(usr_size.get()):
data.append(random.randrange(usr_min.get(), usr_max.get()+1))
display_data(data, ['red' for x in range(len(data))]) | [
"def gen_data(min_coord, max_coord, size):\r\n data = np.random.randint(min_coord, max_coord, size)\r\n return data",
"def data_feeder_2():\n return random.sample(range(100), 10)",
"def randomize(self):\n self.g_value = np.random.rand()",
"def randomize(self):\n for key in self.sliders.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a coordinates string into a dictionary of lats and lons. | def _package_coordinates(self, coords_string):
values = [float(x) for x in coords_string.strip().replace(",", " ").split()]
if len(values) % 2 != 0:
raise Exception("Number of values for coordinates is not even.")
return {"lat": values[0::2], "lon": values[1::2], "type": "polygon"... | [
"def _package_coordinates(self, coords_string):\n values = [float(x)\n for x in coords_string.strip().replace(\",\", \" \").split()]\n if len(values) % 2 != 0:\n raise Exception(\"Number of values for coordinates is not even.\")\n\n return {\"lat\": values[0::2], \"l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds extra metadata extracted from the filename. Dictionary `extra_metadata` is changed in place. Returns nothing. | def _add_filename_metadata(self, extra_metadata):
# Make sure product_info section exists
extra_metadata.setdefault('product_info', {})
file_name = os.path.basename(self.fname)
fn_comps = file_name.split("_")
if self.__class__ == SAFESentinel1:
... | [
"def _update_extra_metadata(self, extra_metadata):\n self._add_filename_metadata(extra_metadata)\n self._derive_extra_metadata(extra_metadata)",
"def _add_filename_metadata(self, extra_metadata):\n\n # Make sure product_info section exists\n extra_metadata.setdefault('product_info', {}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Derives extra fields from the existing fields. Dictionary `extra_metadata` is changed in place. Returns nothing. | def _derive_extra_metadata(self, extra_metadata):
extra_metadata['platform']['Family'] = extra_metadata['platform']['Platform Family Name']
# Add platform number if derivable from file
if self.__class__ is not SAFESentinel1:
extra_metadata['platform']['Family'] += "-%s" % extra_meta... | [
"def extra_fields(self):\n return {}",
"def _update_extra_metadata(self, extra_metadata):\n self._add_filename_metadata(extra_metadata)\n self._derive_extra_metadata(extra_metadata)",
"def copy_fields(self, model):\n fields = super(HistoricalRecords, self).copy_fields(model)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set extra metadata extracted from the zip file. Dictionary `extra_metadata` is changed in place. Returns nothing. | def _extract_metadata_from_zipfile(self, extra_metadata):
try:
if type(self) == SAFESentinel2:
zip_metadata = sentinel2.Sentinel2Scan(self.fname).sentinel_metadata
elif type(self) == SAFESentinel3:
zip_metadata = sentinel3.Sentinel3Scan(self.fname).senti... | [
"def _update_extra_metadata(self, extra_metadata):\n self._add_filename_metadata(extra_metadata)\n self._derive_extra_metadata(extra_metadata)\n \n if type(self) == SAFESentinel3:\n self._extract_metadata_from_zipfile(extra_metadata)",
"def _update_extra_metadata(self, extra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set extra content from existing content and filename. Dictionary `extra_metadata` is changed in place. Returns nothing. | def _update_extra_metadata(self, extra_metadata):
self._add_filename_metadata(extra_metadata)
self._derive_extra_metadata(extra_metadata)
if type(self) == SAFESentinel3:
self._extract_metadata_from_zipfile(extra_metadata) | [
"def _update_extra_metadata(self, extra_metadata):\n self._add_filename_metadata(extra_metadata)\n self._derive_extra_metadata(extra_metadata)",
"def _add_filename_metadata(self, extra_metadata):\n\n # Make sure product_info section exists\n extra_metadata.setdefault('product_info', {}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the dictionary file info `metadata` and does some ESA SAFE specific searching for the '.zip' and '.png' files to report on their existence in the output dictionary by adding to `metadata`. | def _update_filesystem_metadata(self, metadata):
directory, fname = os.path.split(self.fname)
fbase = os.path.splitext(fname)[0]
# Test for presence and size of zip file
zip_file = fbase + '.zip'
zip_path = os.path.join(directory, zip_file)
if os.path.is... | [
"def _update_filesystem_metadata(self, metadata):\n directory, fname = os.path.split(self.fname)\n fbase = fname.split('_')[0]\n\n # Test for presence and size of tif file\n os.listdir(directory)\n tiff_files = glob(os.path.join(directory, '{}*.TIF'.format(fbase)))\n\n if l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The hDQN learning algorithm. All schedules are w.r.t. total number of steps taken in the environment. | def hdqn_learning(
env,
agent,
num_episodes,
exploration_schedule,
gamma=1.0,
):
###############
# RUN ENV #
###############
# Keep track of useful statistics
stats = plotting.EpisodeStats(
episode_lengths=np.zeros(num_episodes),
episode_rewards=np.zeros(n... | [
"def test_n_step_dqn(self):\n model = NStepDQNLightning(self.hparams)\n result = self.trainer.fit(model)\n\n self.assertEqual(result, 1)",
"def learn_Q_QLearning(env, num_episodes=5000, gamma=0.95, lr=0.1, e=0.8, decay_rate=0.99):\n # https://github.com/openai/gym/blob/master/gym/envs/toy_te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to apply the Harmonic analysis of time series applied to arrays sample_count = nr. of images (total number of actual samples of the time series) base_period_len = length of the base period, measured in virtual samples (days, dekads, months, etc.) frequencies_considered_count = number of frequencies to be consi... | def HANTS(sample_count, inputs,
frequencies_considered_count=3,
outliers_to_reject='Hi',
low=0., high=255,
fit_error_tolerance=5,
delta=0.1):
# define some parameters
base_period_len = sample_count*2 #
# check which setting to set for outlier filtering
... | [
"def HANTS(sample_count, inputs,\n frequencies_considered_count=3,\n outliers_to_reject='Hi',\n low=0., high=255,\n fit_error_tolerance=5,\n delta=0.1, \n base=2):\n\n # define some parameters\n if base == 1:\n base_period_len = sample_count #\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean an IPv6 address string. Raise ValidationError if the address is invalid. | def clean_ipv6_address(
ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")
):
try:
addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
except ValueError:
raise ValidationError(error_message, code="invalid")
if unpack_ipv4 and addr.ipv4_mapped:
... | [
"def _canonicalize_ipv6_addr(addr):\n try:\n return str(ipaddress.IPv6Address(addr).compressed)\n except AddressValueError:\n return addr",
"def validate_ipv6_addr(addr):\n return IPV6_REGEX.match(addr)",
"def validate_ipv6_address(ipv6_address):\n\n if ipv6_address.cou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether or not the `ip_str` string is a valid IPv6 address. | def is_valid_ipv6_address(ip_str):
try:
ipaddress.IPv6Address(ip_str)
except ValueError:
return False
return True | [
"def isIPv6(ip):\n return _isIPv(6, ip)",
"def validate_ipv6_addr(addr):\n return IPV6_REGEX.match(addr)",
"def is_valid_ipv6_address(address):\n try:\n socket.inet_pton(socket.AF_INET6, address)\n except (socket.error, TypeError):\n return False\n return True",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rewrite `get_bboxes` of `GFLHead` for default backend. Rewrite this function to deploy model, transform network output for a batch into bbox predictions. | def gfl_head__get_bbox(ctx,
self,
cls_scores,
bbox_preds,
score_factors=None,
img_metas=None,
cfg=None,
rescale=False,
with_nms=True,
... | [
"def get_bboxes(self, cls_scores, bbox_preds, img_metas, cfg, **kwargs):\n if cls_scores[0].shape[0] == 1:\n cls_scores = torch.cat(cls_scores, dim=1).squeeze(0)\n bbox_preds = torch.cat(bbox_preds, dim=1).squeeze(0)\n# \n# cls_scores = cls_scores[0] # (-1,2)\n# ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Analyze, debug and validate your training and development data, get useful stats, and find problems like invalid entity annotations, cyclic dependencies, low data labels and more. | def debug_data(
# fmt: off
lang: ("Model language", "positional", None, str),
train_path: ("Location of JSON-formatted training data", "positional", None, Path),
dev_path: ("Location of JSON-formatted development data", "positional", None, Path),
tag_map_path: ("Location of JSON-formatted tag map", ... | [
"def validate(self):\n # type: () -> None\n\n examples = self.sorted_intent_examples()\n for intent, group in groupby(examples, lambda e: e[\"intent\"]):\n size = len(list(group))\n if size < self.MIN_EXAMPLES_PER_INTENT:\n template = u\"Intent '{0}' has onl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure certificates are valid v1.2 schema | def validate_schema(self):
for _, certificate in self.certificates_to_issue.items():
with open(certificate.signed_cert_file_name) as cert:
cert_json = json.load(cert)
validate_unsigned_v1_2(cert_json) | [
"def _validate_certificates(self):\n try:\n client_security = self.get_security()\n client_security.gen_rabbitmq_self_signed_ca()\n except Exception as ex:\n if const.CERTIFICATE_VALID in str(ex):\n utils.print_log_message('Info', 'The certificate does n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hash the JSONLD normalized certificate | def do_hash_certificate(self, certificate):
options = {'algorithm': 'URDNA2015', 'format': 'application/nquads', 'documentLoader': cached_document_loader}
cert_utf8 = certificate.decode('utf-8')
cert_json = json.loads(cert_utf8)
normalized = jsonld.normalize(cert_json, options=options)
... | [
"def extract_hash(self, cert):\n cert_obj = crypto.load_certificate(crypto.FILETYPE_PEM, cert)\n pubkey_obj = cert_obj.get_pubkey()\n pubkey = crypto.dump_publickey(crypto.FILETYPE_ASN1, pubkey_obj)\n\n spki_hash = hashlib.sha256(pubkey).digest()\n cert_hash = base64.b64encode(spk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Per certificate, we pay 2min_per_output (which is based on dust) + fee. Note assumes 1 input per tx. | def calculate_cost_for_certificate_batch(self):
num_inputs = 1
# output per recipient
num_outputs = len(self.certificates_to_issue)
# plus revocation outputs
num_outputs += sum(1 for c in self.certificates_to_issue.values() if c.revocation_key)
# plus global revocation, c... | [
"def quadratic_cost(output_out, target_out):\r\n total = 0\r\n for target_node in range(len(target_out)): # For each target data set\r\n for output_node in range(len(output_out)): # For each output node\r\n total += (0.5 * (target_out[target_node][output_node] - output_out[output_node])) *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Should not have threads that are marked invisible. | def test_invisible_thread(self):
thread = self.create_thread(visible=False)
result = Thread.public.by_user(thread.recipients.first())
self.assertNotIn(thread, result) | [
"def test_invisible_thread(self):\n thread = self.create_thread(visible=False)\n result = Thread.public.by_group(thread.group)\n self.assertNotIn(thread, result)",
"def test_non_active_userthread(self):\n user = self.create_user()\n thread = self.create_thread(recipient=user)\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Userthreads that are not active should not be in the by_user | def test_non_active_userthread(self):
user = self.create_user()
thread = self.create_thread(recipient=user)
UserThread.objects.filter(
thread=thread, user=user).update(status='deleted')
result = Thread.public.by_user(user)
self.assertNotIn(thread, result) | [
"def test_invisible_thread(self):\n thread = self.create_thread(visible=False)\n result = Thread.public.by_user(thread.recipients.first())\n self.assertNotIn(thread, result)",
"def test_userthread_status(self):\n thread = self.create_thread()\n thread = Thread.public.by_user(thr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The current userthread_status should be selected. | def test_userthread_status(self):
thread = self.create_thread()
thread = Thread.public.by_user(thread.test_shortcuts['recipient'])
self.assertEqual(thread[0].userthread_status, 'active') | [
"def _get_user_active_status(self, user):\n return user.is_active or is_account_activation_requirement_disabled()",
"def is_active(self):\n return self.status == ACTIVE_USER",
"def status(self):\n return UserStatuses.Pending.value",
"def get_is_current_user(self):\n return self.is_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Should not have threads posted to another group. | def test_by_group_no_messages_for_another_group(self):
thread = self.create_thread()
other_group = mommy.make('groups.Group')
result = Thread.public.by_group(thread.group)
self.assertNotIn(other_group, result) | [
"def test_invisible_thread(self):\n thread = self.create_thread(visible=False)\n result = Thread.public.by_group(thread.group)\n self.assertNotIn(thread, result)",
"def test_group_is_private(self):\n group = mommy.make('groups.Group', private=True)\n thread = self.create_thread(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Should not have threads that are marked invisible. | def test_invisible_thread(self):
thread = self.create_thread(visible=False)
result = Thread.public.by_group(thread.group)
self.assertNotIn(thread, result) | [
"def test_invisible_thread(self):\n thread = self.create_thread(visible=False)\n result = Thread.public.by_user(thread.recipients.first())\n self.assertNotIn(thread, result)",
"def test_non_active_userthread(self):\n user = self.create_user()\n thread = self.create_thread(recipi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Private groups should not have their threads exposed. | def test_group_is_private(self):
group = mommy.make('groups.Group', private=True)
thread = self.create_thread(group=group)
result = Thread.public.by_group(group)
self.assertNotIn(thread, result) | [
"def test_group_is_private_user_is_not_member(self):\n thread = self.create_thread()\n thread.group.private = True\n thread.save()\n message = thread.first_message\n user = self.create_user()\n self.assertFalse(message.visible_to_user(user))",
"def test_invisible_thread(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unicode conversion should be Thread and the id of the thread. | def test_unicode(self):
thread = mommy.prepare('connectmessages.Thread')
self.assertEqual(str(thread), "Thread %s" % thread.subject) | [
"def _message(message):\n str_thread = \"Thread-%d\" % threading.current_thread().ident\n return \"%s\\t%s\" % (str_thread, message)",
"def name_thread( cls, id, ):\n if cls.main_thread_id is None:\n y= 1/0 # cheap exception when main_thread not set up\n\n if id == cls.ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that add_user_to_thread adds the user to the thread. | def test_add_user_to_thread(self):
thread = self.create_thread()
user = self.create_user()
thread.add_user_to_thread(user)
self.assertTrue(
UserThread.objects.filter(thread=thread, user=user).exists()) | [
"def test_add_user(self):\n pass",
"def test_add_user_to_g(self):\r\n\r\n with app.test_request_context():\r\n u1 = User.query.filter_by(username='testuser').one()\r\n\r\n add_user_to_g()\r\n self.assertIsNone(g.user)\r\n do_login(u1)\r\n add_us... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the get_unsubscribe_url method on the Thread model | def test_get_unsubscribe_url(self):
thread = self.create_thread()
self.assertEqual(
thread.get_unsubscribe_url(),
reverse('thread_unsubscribe', args=[thread.pk])
) | [
"def test_unsubscribe_url(self):\r\n w = watch()\r\n url = w.unsubscribe_url()\r\n assert url.startswith('http')\r\n assert url.endswith('?s=%s' % w.secret)",
"def test_unsubscribe_offer(self):\n pass",
"def test_unsubscribe_instructions(self):\r\n w = watch(save=True)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the thread serialization method for a group message | def test_group_serializable(self):
sender = self.create_user()
thread = self.create_thread(sender=sender)
message = thread.first_message
chicago = pytz.timezone('US/Central')
self.assertDictEqual(
thread.serializable(),
{
'id': thread.pk,
... | [
"def test_message_group_by_member(self):\n code, data = self.message_group(self.imsi1, self.groupname,\n 'Hello there!')\n self.assertEqual(200, code)\n self.assertEqual('OK SEND', data)",
"def test_by_group_no_messages_for_another_group(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the thread serialization method for a direct message | def test_direct_serializable(self):
sender = self.create_user()
recipient = self.create_user()
thread = self.create_thread(
direct=True, sender=sender, recipient=recipient)
message = thread.first_message
chicago = pytz.timezone('US/Central')
self.assertDictIt... | [
"def test_group_serializable(self):\n sender = self.create_user()\n thread = self.create_thread(sender=sender)\n\n message = thread.first_message\n chicago = pytz.timezone('US/Central')\n self.assertDictEqual(\n thread.serializable(),\n {\n 'id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the thread serialization method for a system message | def test_systemthread(self):
# The sqlite test runner doesn't run south migrations, so create the
# user here if it doesn't exist
USER_MODEL.objects.get_or_create(
email='systemuser-email@connect.local', defaults={
'username': 'systemuser-email@connect.local',
... | [
"def test_serizable_pending(self):\n thread = self.create_thread()\n message = thread.first_message\n\n # Confirm that an 'approved' message is not marked as pending\n self.assertEqual(message.status, 'approved')\n self.assertEqual(message.serializable()['pending'], False)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
last_read_at should be correctly set. | def test_last_read_at(self):
recipient = self.create_user()
thread = self.create_thread(recipient=recipient)
last_read_at = datetime.datetime(
2014, 3, 17, 19, 42, 37, tzinfo=pytz.timezone('UTC'))
UserThread.objects.filter(
thread=thread, user=recipient).update(la... | [
"def last_read(self, last_read):\n\n self._last_read = last_read",
"def last_read_thread(self, last_read_thread):\n\n self._last_read_thread = last_read_thread",
"def most_recent_read(self):\n self.read_pos = (self.write_pos - 1) % self.log_len\n return",
"def lastRead(self):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If thread has never been opened, count should equal all messages. | def test_unread_message_count_thread_never_opened(self):
recipient = self.create_user()
thread = self.create_thread(recipient=recipient)
mommy.make(Message, thread=thread, sender=self.create_superuser())
result = Thread.public.by_user(
user=recipient,
queryset=Thr... | [
"def test_updates_count(self):\n user = self.create_user()\n thread = self.create_thread(sender=user)\n\n original_count = thread.message_set.count()\n\n for _ in range(0, 5):\n msg = mommy.make(Message, thread=thread, sender=user)\n\n send_message(msg.pk)\n\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get_absolute_url should resolve to threads. | def test_get_absolute_url_resolves_to_threads(self):
thread = self.create_thread()
self.assertEqual(
thread.first_message.get_absolute_url(),
'/messages/id/{pk}/'.format(
pk=thread.pk)
) | [
"def get_absolute_url(self):\n\n\treturn self.composition.get_absolute_url()",
"def resolve_url(self, info, absolute):\n request = info.context\n return resolve_absolute_url(self.url, request, absolute=absolute)",
"def test_absolute_url(self):\n response = self.client.get(self.htsv.get_abso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the 'pending' logic in message.serlizable | def test_serizable_pending(self):
thread = self.create_thread()
message = thread.first_message
# Confirm that an 'approved' message is not marked as pending
self.assertEqual(message.status, 'approved')
self.assertEqual(message.serializable()['pending'], False)
message.s... | [
"def is_pending(self):\n return self.type_id == STATE_PENDING",
"def test__put_pending_into():\n for input_value, defaults, expected_output in (\n (False, False, {}),\n (False, True, {'pending': False}),\n (True, False, {'pending': True}),\n ):\n data = put_pending_into(in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that save calls _text_cleaner(). | def test_save_calls_text_cleaner(self):
thread = self.create_thread()
with patch.object(Message, '_text_cleaner') as mock:
mock.return_value = ''
self.assertEqual(mock.call_count, 0)
thread.first_message.save()
self.assertEqual(mock.call_count, 1) | [
"def test_text_in_model(self):\n current_post = Post.objects.get(id=1)\n expected_text = \"Test text for my model\"\n self.assertEqual(current_post.text, expected_text)",
"def test_prep_textarea(self):\n pass",
"def test_text(self):\n conn = self.database.connection()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Long Snippet should return first 140 characters of clean_text. | def test_long_snippet(self):
message = Message(clean_text=''.join('x' for _ in range(0, 200)))
self.assertEqual(
message.long_snippet,
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... | [
"def remove_longer_words(text):\n return \" \".join([word for word in str(text).split() if len(word) <= 12])",
"def shortened_text(self, max_chars=50):\n if len(self.text) > max_chars:\n return self.text[:max_chars] + \"...\"\n else:\n return self.text",
"def cut_text(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a long snippet that starts and ends with a nonletter | def test_snippet_beginning_nonletter(self):
message = Message(clean_text=u"!I already know what this will be!!!!!")
self.assertEqual(
message.snippet,
'I already know what...'
) | [
"def customwordcheck(word):\r\n result = True\r\n if len(word) >= 3 and len(word) <= 15:\r\n result = True\r\n else:\r\n return False\r\n word = word.lower()\r\n for letter in word:\r\n if letter not in \"abcdefghijklmnopqrstuvwxyz\":\r\n return False\r\n else:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |