query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
GRE IPv4 tunnel Tests | def test_gre(self):
#
# Create an L3 GRE tunnel.
# - set it admin up
# - assign an IP Addres
# - Add a route via the tunnel
#
gre_if = VppGreInterface(self, self.pg0.local_ip4, "1.1.1.2")
gre_if.add_vpp_config()
#
# The double create (... | [
"def test_gre_vrf(self):\n\n e = VppEnum.vl_api_tunnel_encap_decap_flags_t\n\n #\n # Create an L3 GRE tunnel whose destination is in the non-default\n # table. The underlay is thus non-default - the overlay is still\n # the default.\n # - set it admin up\n # - assi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GRE IPv6 tunnel Tests | def test_gre6(self):
self.pg1.config_ip6()
self.pg1.resolve_ndp()
#
# Create an L3 GRE tunnel.
# - set it admin up
# - assign an IP Address
# - Add a route via the tunnel
#
gre_if = VppGreInterface(self, self.pg2.local_ip6, "1002::1")
... | [
"def test_mgre6(self):\n\n self.pg0.config_ip6()\n self.pg0.resolve_ndp()\n\n e = VppEnum.vl_api_tunnel_encap_decap_flags_t\n\n for itf in self.pg_interfaces[3:]:\n #\n # one underlay nh for each overlay/tunnel peer\n #\n itf.config_ip6()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GRE tunnel VRF Tests | def test_gre_vrf(self):
e = VppEnum.vl_api_tunnel_encap_decap_flags_t
#
# Create an L3 GRE tunnel whose destination is in the non-default
# table. The underlay is thus non-default - the overlay is still
# the default.
# - set it admin up
# - assign an IP Addre... | [
"def test_gre(self):\n\n #\n # Create an L3 GRE tunnel.\n # - set it admin up\n # - assign an IP Addres\n # - Add a route via the tunnel\n #\n gre_if = VppGreInterface(self, self.pg0.local_ip4, \"1.1.1.2\")\n gre_if.add_vpp_config()\n\n #\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GRE tunnel L2 Tests | def test_gre_l2(self):
#
# Add routes to resolve the tunnel destinations
#
route_tun1_dst = VppIpRoute(
self,
"2.2.2.2",
32,
[VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)],
)
route_tun2_dst = VppIpRoute(
... | [
"def test_gre(self):\n\n #\n # Create an L3 GRE tunnel.\n # - set it admin up\n # - assign an IP Addres\n # - Add a route via the tunnel\n #\n gre_if = VppGreInterface(self, self.pg0.local_ip4, \"1.1.1.2\")\n gre_if.add_vpp_config()\n\n #\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GRE tunnel loop Tests | def test_gre_loop(self):
#
# Create an L3 GRE tunnel.
# - set it admin up
# - assign an IP Addres
#
gre_if = VppGreInterface(self, self.pg0.local_ip4, "1.1.1.2")
gre_if.add_vpp_config()
gre_if.admin_up()
gre_if.config_ip4()
#
# ... | [
"def test_gre(self):\n\n #\n # Create an L3 GRE tunnel.\n # - set it admin up\n # - assign an IP Addres\n # - Add a route via the tunnel\n #\n gre_if = VppGreInterface(self, self.pg0.local_ip4, \"1.1.1.2\")\n gre_if.add_vpp_config()\n\n #\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mGRE IPv4 tunnel Tests | def test_mgre(self):
for itf in self.pg_interfaces[3:]:
#
# one underlay nh for each overlay/tunnel peer
#
itf.generate_remote_hosts(4)
itf.configure_ipv4_neighbors()
#
# Create an L3 GRE tunnel.
# - set it admin ... | [
"def test_gre(self):\n\n #\n # Create an L3 GRE tunnel.\n # - set it admin up\n # - assign an IP Addres\n # - Add a route via the tunnel\n #\n gre_if = VppGreInterface(self, self.pg0.local_ip4, \"1.1.1.2\")\n gre_if.add_vpp_config()\n\n #\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mGRE IPv6 tunnel Tests | def test_mgre6(self):
self.pg0.config_ip6()
self.pg0.resolve_ndp()
e = VppEnum.vl_api_tunnel_encap_decap_flags_t
for itf in self.pg_interfaces[3:]:
#
# one underlay nh for each overlay/tunnel peer
#
itf.config_ip6()
itf.gener... | [
"def test_gre6(self):\n\n self.pg1.config_ip6()\n self.pg1.resolve_ndp()\n\n #\n # Create an L3 GRE tunnel.\n # - set it admin up\n # - assign an IP Address\n # - Add a route via the tunnel\n #\n gre_if = VppGreInterface(self, self.pg2.local_ip6, \"1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compress a FASTQ file using fastore | def convert_fastq_to_fastore(fwd_reads, rev_reads, output_prefix, num_threads=multiprocessing.cpu_count()):
if output_prefix is None:
output_prefix = os.path.basename(fwd_reads)
output_prefix = re.sub(FASTQ_PATTERN, '', output_prefix)
cmd = [
'fastore_compress.sh', '--lossless',
... | [
"def compress(infile):\r\n cmd = ' '.join([\"gzip\", \"-f\", infile])\r\n pipe = subprocess.run(cmd, shell=True,\r\n stdout=subprocess.PIPE,\r\n stderr=subprocess.PIPE)",
"def scarf_to_fastq(infile=sys.stdin, outfile=sys.stdout):\n infile = open_gzipped(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compress a FASTQ file using fqzcomp | def convert_fastq_to_fqzcomp(reads, output_prefix):
if output_prefix is None:
output_prefix = os.path.basename(reads)
output_prefix = re.sub(FASTQ_PATTERN, '', output_prefix)
# Recommended parameters for Illumina data as provided by:
# https://github.com/jkbonfield/fqzcomp
output_filenam... | [
"def vcf_compress(fn):\n ret = cmd_exe(f\"vcf-sort {fn} | bgzip > {fn}.gz && tabix {fn}.gz\")",
"def compress(infile):\r\n cmd = ' '.join([\"gzip\", \"-f\", infile])\r\n pipe = subprocess.run(cmd, shell=True,\r\n stdout=subprocess.PIPE,\r\n stderr=subproc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the callback that will handle updated audio samples. Unlike core.EmulatedSNES.set_audio_sample_cb, the callback passed to this | def set_audio_sample_cb(core, callback=pygame.mixer.Sound.play):
maxlog = 512*2*2 # 512 stereo samples of 16-bits each
sndstruct = struct.Struct('<hh')
def wrapper(left, right):
global sndlog
sndlog += sndstruct.pack(left, right)
if len(sndlog) >= maxlog:
sndarr = numpy.fromstring(sndlog[:maxlog], dtype=... | [
"def set_audio_sample_cb(core, callback=pygame.mixer.Sound.play):\n\n\t# init pygame sound. snes freq is 32000, 16bit unsigned stereo.\n\tpygame.mixer.init(\n\t\tfrequency=SNES_OUTPUT_FREQUENCY,\n\t\tsize=16, channels=2, buffer=512\n\t)\n\n\tsnd = pygame.sndarray.make_sound(\n\t\t\tnumpy.zeros( (512, 2), dtype='in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a dict of link, headers, and proxies | def get_dict(self):
self.headers = self.hm.getRequestHeaders()
self.proxies = self.hm.getRandomProxyDict(self.num)
return {'link':self.link,
'headers':headers,
'proxies':proxies,
't0':datetime.now(),
't1':None,
'resp... | [
"def get_headers(referer):\n headers = deepcopy(base_headers)\n headers['referer'] = referer\n return headers",
"def headers(url):\n if url.startswith(\"http://i.meizitu.net/\"):\n return {\n \"User-Agent\": CONFIG.USER_AGENT,\n \"Referer\": \"http://www.mz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets processes the contents of req_dict | def set_dict(self, req_dict):
self.delta = (req_dict['t1'] - req_dict['t0']).total_seconds()
resp = req_dict['response']
if resp == None or resp.status==400:
self.status = 400
else:
self.status = resp.status
self.raw_html = resp.raw_html
s... | [
"def __update_request(self, request_dict, namespace, apikey):\n request_dict['namespace'] = namespace if namespace else self.namespace\n request_dict['apikey'] = apikey if apikey else self.apikey",
"def process_request(self, req, resp):\n pass",
"def process_request(self, req, resp):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A helper method to return True if the given argument appears to be iterable (like a list) but not able to be converted to a Range. In particular, checks for whether python would consider the argument to be iterable (it has either __iter__() or __getattr__() defined), and then checks that it isn't a string (in which cas... | def _is_iterable_non_string(arg):
return (hasattr(arg, "__iter__") or hasattr(arg, "__getattr__")) and not isinstance(arg, str) | [
"def is_iterable(arg):\n return (\n isinstance(arg, collections.Iterable)\n and not isinstance(arg, str)\n )",
"def isiterable(val):\n return isinstance(val, Iterable) and not isinstance(val, str)",
"def is_iterable(obj):\n return not isinstance(obj, str) and isinstance(obj, co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function which calculates and returns the collective thrust and the moment about the X axis | def get_thrust_and_moment(self):
f1 = self.k_f * self.omega_1 ** 2
f2 = self.k_f * self.omega_2 ** 2
# c is often used to indicate "collective" thrust
c = f1 + f2
M_x = (f1 - f2) * self.l
return c, M_x | [
"def get_thrust_and_moment(self):\n\n f1 = self.k_f * self.omega_1 ** 2\n f2 = self.k_f * self.omega_2 ** 2\n\n # c is often used to indicate \"collective\" thrust\n c = f1 + f2\n\n M_x = (f1 - f2) * self.l\n return c, M_x",
"def __get_time_grid__(self, x):\n if se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates vertical (z) acceleration of drone. | def z_dot_dot(self):
# TODO 1
# Calculate the vertical component of the acceleration
# You might find get_thrust_and_moment helpful
c, M_x = self.get_thrust_and_moment()
phi = self.X[2]
zdd = (self.g - c * np.cos(phi)) / self.m
print (zdd)
retu... | [
"def accel_z(self):\n return float(self.__angles[2]) - ZEROZ",
"def z(self) -> float:\n return self.read_accel(0x06, 4)",
"def getZ(self):\n return self.getAcceleration(self.Axes.kZ)",
"def accel_z(self):\n return self._accel_z",
"def getAngVelZ(self):\n return self.angvel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new RateLimitExceededResponse with either a body or json_body. | def __init__(self, status='429 Too Many Requests', status_code=429, headerlist=None,
body=None, json_body=None, environ=None):
super(RateLimitExceededResponse, self).__init__(headerlist=headerlist, charset="UTF-8")
self.status_code = status_code
self.status = status
sel... | [
"def __init__(self, message, details, retry_time):\n hdrs = RateLimitFault._retry_after(retry_time)\n self.wrapped_exc = webob.exc.HTTPTooManyRequests(headers=hdrs)\n self.content = {\n \"overLimit\": {\n \"code\": self.wrapped_exc.status_int,\n \"messag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the environ of the request triggering this response. | def set_environ(self, environ):
self.environ = environ | [
"def set_environ(self, name, value):\n self._envpatcher.setenv(name, value)",
"def load_environ(self, environ):\n self.environ = environ\n self.url = environ['PATH_INFO']\n\n if self.is_not_get_request():\n self.environ['QUERY_STRING'] = self.set_post_params()\n\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new BlacklistResponse with either a body or json_body. | def __init__(self, status='497 Blacklisted', status_code=497, headerlist=None,
body=None, json_body=None, environ=None):
super(BlacklistResponse, self).__init__(headerlist=headerlist, charset="UTF-8")
self.status_code = status_code
self.status = status
self.environ = en... | [
"def create_with_http_info(self, filter_entry, **kwargs):\n\n all_params = ['filter_entry']\n all_params.append('callback')\n all_params.append('_return_http_data_only')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the environ of the request triggering this response. | def set_environ(self, environ):
self.environ = environ | [
"def set_environ(self, name, value):\n self._envpatcher.setenv(name, value)",
"def load_environ(self, environ):\n self.environ = environ\n self.url = environ['PATH_INFO']\n\n if self.is_not_get_request():\n self.environ['QUERY_STRING'] = self.set_post_params()\n\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
computes mean squared displacement and saves corresponding plots. DT is the tim1e between two spiral tip observations in milliseconds. file is a string locating in a folder with files ending in _unwrap.csv n_tips is the number of tips | def gen_msd_figs(file,n_tips=1,**kwargs):#,V_thresh):
return generate_msd_figures_routine(file,n_tips,**kwargs)#, V_thresh=None) | [
"def msidLimitPlot(file, out_path):\n\n#\n#--- read data\n#\n f = open(file, 'r')\n data = [line.strip() for line in f.readlines()]\n f.close()\n\n#\n#--- find msid names (column names)\n#\n colEnt = re.split('\\s+|\\t+', data[0])\n colLen = len(colEnt)\n colName = []\n#\n#--- header is in the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable globally progress bars used in `huggingface_hub` except if `HF_HUB_DISABLE_PROGRESS_BARS` environment variable has been set. Use [`~utils.enable_progress_bars`] to reenable them. | def disable_progress_bars() -> None:
if HF_HUB_DISABLE_PROGRESS_BARS is False:
warnings.warn(
"Cannot disable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=0` is set and has"
" priority."
)
return
global _hf_hub_progress_bars_disabled
_hf_h... | [
"def enable_progress_bars() -> None:\n if HF_HUB_DISABLE_PROGRESS_BARS is True:\n warnings.warn(\n \"Cannot enable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=1` is set and has\"\n \" priority.\"\n )\n return\n global _hf_hub_progress_bars_disab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable globally progress bars used in `huggingface_hub` except if `HF_HUB_DISABLE_PROGRESS_BARS` environment variable has been set. Use [`~utils.disable_progress_bars`] to disable them. | def enable_progress_bars() -> None:
if HF_HUB_DISABLE_PROGRESS_BARS is True:
warnings.warn(
"Cannot enable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=1` is set and has"
" priority."
)
return
global _hf_hub_progress_bars_disabled
_hf_hub_... | [
"def disable_progress_bars() -> None:\n if HF_HUB_DISABLE_PROGRESS_BARS is False:\n warnings.warn(\n \"Cannot disable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=0` is set and has\"\n \" priority.\"\n )\n return\n global _hf_hub_progress_bars_di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether progress bars are globally disabled or not. Progress bars used in `huggingface_hub` can be enable or disabled globally using [`~utils.enable_progress_bars`] and [`~utils.disable_progress_bars`] or by setting `HF_HUB_DISABLE_PROGRESS_BARS` as environment variable. | def are_progress_bars_disabled() -> bool:
global _hf_hub_progress_bars_disabled
return _hf_hub_progress_bars_disabled | [
"def disable_progress_bars() -> None:\n if HF_HUB_DISABLE_PROGRESS_BARS is False:\n warnings.warn(\n \"Cannot disable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=0` is set and has\"\n \" priority.\"\n )\n return\n global _hf_hub_progress_bars_di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open a file as binary and wrap the `read` method to display a progress bar when it's streamed. First implemented in `transformers` in 2019 but removed when switched to gitlfs. Used in `huggingface_hub` to show progress bar when uploading an LFS file to the Hub. See github.com/huggingface/transformers/pull/2078discussio... | def tqdm_stream_file(path: Union[Path, str]) -> Iterator[io.BufferedReader]:
if isinstance(path, str):
path = Path(path)
with path.open("rb") as f:
total_size = path.stat().st_size
pbar = tqdm(
unit="B",
unit_scale=True,
total=total_size,
... | [
"def read_binary(self):\n todo = self.length\n if todo >= 0:\n while todo > 0:\n data = self.fp.read(min(todo, self.bufsize))\n if not isinstance(data, bytes):\n raise ValueError(\"%s should return bytes, got %s\"\n % (self.fp, type(d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Surcharge de l'init pour accepter le label_singulier et les formats | def __init__(self, instance=None, data=empty, label_singulier=None, formats=None, **kwargs):
self.label_singulier = label_singulier
self.formats = formats or {}
super().__init__(instance, data, **kwargs) | [
"def initFormat(self):\n pass",
"def __init__(self, label):\n self.label = label",
"def __init__(self, Label=\"\", Sequence=\"\"):\n self.Label = Label\n self.Sequence = Sequence",
"def __init__(self,sequence,label=\"\"):\n\n self.sequence = sequence\n self.label = la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update numeric display next to the steps slider | def update_steps_display(self):
self.steps_display["text"] = str(self.steps.get()) | [
"def _slider_change(self, slider, value):\n self.slider_label.text = str(float(value))",
"def update(self, step=1):\n self.current += step\n percent = self.current / float(self.total)\n size = int(self.width * percent)\n remaining = self.total - self.current\n bar = '[' +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recompute output text from given input, steps, reverse flag | def recompute_output_text(self):
s = self.input_string.get()
senc = rotcode.rotate(s,steps=self.steps.get())
if self.reverse_flag.get():
# Reverse the encoded text
senc = senc[::-1]
self.output_string.set(senc) | [
"def slowly_reverse_string(self, string_to_reverse):\n logger = logging.getLogger(self.request.id)\n logger.info(f\"Reversing {string_to_reverse}.\")\n counter = 10\n for i in range(0, counter):\n self.update_state(state=\"PROGRESS\", meta={\"done\": i, \"total\": counter})\n logger.info(f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test automol.pot.points test automol.pot.coords | def test__build_potential():
ref_1dgrid_pts = ((0,), (1,), (2,), (3,))
ref_1dgrid_coords = ((1.0,), (2.0,), (3.0,), (4.0,))
ref_2dgrid_pts = ((0, 0), (0, 1),
(1, 0), (1, 1),
(2, 0), (2, 1),
(3, 0), (3, 1))
ref_2dgrid_coords = ((1.0, 0.1... | [
"def testPointSystem():\n deleteMatches()\n deletePlayers()\n registerPlayer(\"Pikachu\")\n registerPlayer(\"Charmander\")\n registerPlayer(\"Bulbasaur\")\n registerPlayer(\"Squirtle\")\n registerPlayer(\"MewTwo\")\n standings = playerStandings()\n [id1, id2, id3, id4, id5] = [row[0] for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test automol.pot.scale test automol.pot.truncate | def test__transform_potential():
# Test scaling
ref_pot_scaled = {(0.0,): 0.0,
(0.52359878,): 0.9625,
(1.04719755,): 2.0250,
(1.57079633,): 1.1250,
(2.0943951,): 0.0125,
(2.61799388,): 0.7625,
... | [
"def test_fltruncate(doctest):",
"def test__trunc__(parameter):\n par, _ = parameter\n par.set(value=10.5)\n assert isinstance(trunc(par), int)\n assert_allclose(trunc(par), 10)",
"def test_size_too_small(self):\n min_size = min(settings.MISAGO_AVATARS_SIZES)\n too_small = min_size / 2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test automol.pot.is_nonempty test automol.pot.remove_empty_terms | def test__empty_terms_in_potential():
assert automol.pot.is_nonempty(POT1)
assert not automol.pot.is_nonempty(POT4)
ref_filt_pot = {
(0.00000000,): 0.00, (1.04719755,): 3.58,
(2.09439510,): 0.01, (2.61799388,): 1.75,
(3.14159265,): 3.59, (3.66519143,): 1.69,
(4.18879020,): ... | [
"def empty(field):\n return OR(missing(field), term(field, ''))",
"def test_complete_sentences_empty(self):\n\n cleaner = Cleaner(complete_sentences=True)\n\n text = ''\n self.assertEqual(text, cleaner.clean(text))",
"def test_drop_empty_tokens():\n assert TextCleaner().transform([[[\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test pot.low_repulsion_struct test pot.intramol_interaction_potential_sum | def test__intmol():
assert automol.pot.low_repulsion_struct(
PROP_GEO1, PROP_GEO2, thresh=40.0, potential='exp6')
assert automol.pot.low_repulsion_struct(
PROP_GEO1, PROP_GEO2, thresh=40.0, potential='lj_12_6') | [
"def test_positive_electrode_potential_profile(self):\n\n # TODO: add these when have averages",
"def test_get_damage(self):\n self.veh.health = 2.2\n for op in self.veh.operators:\n op.health = 0.5\n self.veh.get_damage(0.5)\n self.assertEqual(self.veh.health, 1.9)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all registered webhooks | def list_webhooks(self):
response = requests.get(
'%spreferences/notifications' % self._url,
**self._auth
)
if response.status_code == 401:
raise MoipAuthorizationException(response.json())
else:
pretty_print(response.json())
r... | [
"def listWebhooks():\n\n api = WebexTeamsAPI(access_token=teams_token)\n webhooks = api.webhooks.list()\n\n # no need to iterate through all the webhooks if the list is empty\n if len(list(webhooks)) == 0:\n print('no webhooks registered')\n return\n\n print('listing webhooks...')\n\n # iterate through ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is the specified flag value set in the named field | def scapy_packet_Packet_hasflag(self, field_name, value):
field, val = self.getfield_and_val(field_name)
if isinstance(field, EnumField):
if val not in field.i2s:
return False
return field.i2s[val] == value
else:
return (1 << field.names.index([value])) & self.__getattr__(field_name) != 0 | [
"def flag_is_set(FLAG):\r\n return ((F & FLAG) != 0x00)",
"def a_flag(self, nom_flag):\n valeur = FLAGS[nom_flag]\n return self.flags & valeur != 0",
"def hasValue (self, field):\n\t\treturn self[field].strip() != \"\"",
"def has_value(self, name: Text) -> bool:\n return any(k.identifier =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ignore any unparsed conditionally present fields If all fields have been parsed, the payload length should have decreased RadioTap_len bytes If it has not, there are unparsed fields which should be treated as padding | def scapy_layers_dot11_RadioTap_extract_padding(self, s):
padding = len(s) - (self.pre_dissect_len - self.RadioTap_len)
if padding:
return s[padding:], s[:padding]
else:
return s, None | [
"def _trimRecords(self):\n self.highpassrecords.resize(self.nhighpassrecords, refcheck=False)\n self.lowpassrecords.resize(self.nlowpassrecords, refcheck=False)\n self.digitalsvalrecords.resize(self.ndigitalsvalrecords, refcheck=False)\n # cleanup by deleting any struct arrays of len 0\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An iterator of Dot11Elt | def scapy_layers_dot11_Dot11_elts(self):
dot11elt = self.getlayer(Dot11Elt)
while dot11elt and dot11elt.haslayer(Dot11Elt):
yield dot11elt
dot11elt = dot11elt.payload | [
"def __iter__(self):\n return self.elements.__iter__()",
"def __iter__(self):\n\n return iter(self.attr_lst)",
"def __iter__(self):\r\n return self.iterNodes()",
"def __iter__(self) -> Iterator[Vector]:\n return iter(self.__elements)",
"def __iter__(self):\n for each in se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over elt and return the first with a specific ID | def scapy_layers_dot11_Dot11_find_elt_by_id(self, id):
for elt in self.elts():
if elt.ID == id:
return elt
return None | [
"def get_by_id( elements, id ):\n for e in elements:\n if e.get('id',None) == id:\n return e\n ret = get_by_id(e,id)\n if ret is not None:\n return ret\n return None",
"def get_element_by_element_id(self, element_id):\n for element in self.iterate():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the payload of the SSID Dot11Elt if it exists | def scapy_layers_dot11_Dot11_essid(self):
elt = self.find_elt_by_id(0)
return elt.info if elt else None | [
"def get_ssid():\n command = \"\".join([\n \"System/Library/PrivateFrameworks/Apple80211.framework/Versions/\",\n \"Current/Resources/airport -I\",\n ])\n airport = shell_out(command)\n for i in airport:\n if re.match(r'^SSID:', i.strip()):\n return i.strip().strip(\"SSID... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the payload of the rates Dot11Elt if it exists | def scapy_layers_dot11_Dot11_rates(self, id=1):
elt = self.find_elt_by_id(id)
if elt:
try:
return Dot11EltRates(str(elt)).rates
except Exception, e:
Printer.error('Bad Dot11EltRates got[{0:s}]'.format(elt.info))
Printer.exception(e)
return [] | [
"def scapy_layers_dot11_Dot11_extended_rates(self):\n\treturn scapy.layers.dot11.Dot11.rates(self, 50)",
"def scapy_layers_dot11_Dot11_rsn(self):\n\telt = self.find_elt_by_id(48)\n\tif elt:\n\t\ttry:\n\t\t\treturn Dot11EltRSN(str(elt))\n\t\texcept Exception, e:\n\t\t\tPrinter.error('Bad Dot11EltRSN got[{0:s}]'.fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the payload of the extended rates Dot11Elt if it exists | def scapy_layers_dot11_Dot11_extended_rates(self):
return scapy.layers.dot11.Dot11.rates(self, 50) | [
"def scapy_layers_dot11_Dot11_rsn(self):\n\telt = self.find_elt_by_id(48)\n\tif elt:\n\t\ttry:\n\t\t\treturn Dot11EltRSN(str(elt))\n\t\texcept Exception, e:\n\t\t\tPrinter.error('Bad Dot11EltRSN got[{0:s}]'.format(elt.info))\n\t\t\tPrinter.exception(e)\n\treturn None",
"def scapy_layers_dot11_Dot11_rates(self, id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the bssid for a station associated with the packet | def scapy_layers_dot11_Dot11_sta_bssid(self):
if self.haslayer(Dot11ProbeReq) or self.hasflag('FCfield', 'to-DS'):
return self.addr2
else:
return self.addr1 | [
"def scapy_layers_dot11_Dot11_ap_bssid(self):\n\tif self.haslayer(Dot11ProbeReq) or self.hasflag('FCfield', 'to-DS'):\n\t\treturn self.addr1\n\telse:\n\t\treturn self.addr2",
"def get_ssid():\n command = \"\".join([\n \"System/Library/PrivateFrameworks/Apple80211.framework/Versions/\",\n \"Curren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the bssid for a access point associated with the packet | def scapy_layers_dot11_Dot11_ap_bssid(self):
if self.haslayer(Dot11ProbeReq) or self.hasflag('FCfield', 'to-DS'):
return self.addr1
else:
return self.addr2 | [
"def scapy_layers_dot11_Dot11_sta_bssid(self):\n\tif self.haslayer(Dot11ProbeReq) or self.hasflag('FCfield', 'to-DS'):\n\t\treturn self.addr2\n\telse:\n\t\treturn self.addr1",
"def wifi_ap(self):\n return self.api.get(\"wifi/ap\")",
"def _ParseScanAccessPoint(self, bssid, active, output):\n logging.de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the payload of the channel Dot11Elt if it exists | def scapy_layers_dot11_Dot11_channel(self):
elt = self.find_elt_by_id(3)
if elt:
try:
return int(ord(elt.info))
except Exception, e:
Printer.error('Bad Dot11Elt channel got[{0:s}]'.format(elt.info))
Printer.exception(e)
return None | [
"def get_payload(pkt: Packet) -> Optional[str]:\n return f\"{pkt.payload!r}\"",
"def get_payload(raw_msg):\n\n return raw_msg[14:-6], raw_msg[-5]",
"def scapy_layers_dot11_Dot11_essid(self):\n\telt = self.find_elt_by_id(0)\n\treturn elt.info if elt else None",
"def get_payload(original):\n # TODO: Se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the payload of the RSN Dot11Elt as a Dot11EltRSN | def scapy_layers_dot11_Dot11_rsn(self):
elt = self.find_elt_by_id(48)
if elt:
try:
return Dot11EltRSN(str(elt))
except Exception, e:
Printer.error('Bad Dot11EltRSN got[{0:s}]'.format(elt.info))
Printer.exception(e)
return None | [
"def scapy_layers_dot11_Dot11_essid(self):\n\telt = self.find_elt_by_id(0)\n\treturn elt.info if elt else None",
"def radrad(rxn_class):\n return rxn_class[2]",
"def scapy_layers_dot11_Dot11_channel(self):\n\telt = self.find_elt_by_id(3)\n\tif elt:\n\t\ttry:\n\t\t\treturn int(ord(elt.info))\n\t\texcept Excep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The script and recent_reviews div should not be in pages other than / | def test_scripts_inside_content_block(self):
c = Client()
resp = c.get('/books/')
self.assertNotIn(b'<div id="recent_reviews"></div>', resp.content)
self.assertNotIn(b'<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>',
resp.... | [
"def is_review_page(self):\n if self.soup.xpath(\"//div[@id='cm_cr-review_list']\"):\n return True\n return False",
"def _scrape_current_page(self):\n self._get_reviews()\n for review in self.current_reviews:\n try:\n content = self._extract_content... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate multiples and submultiples for SI mass units ``kg_unit`` must be defined, with name ``kilogram`` and symbol ``kg`` | def si_mass_units(kg_unit):
if (
kg_unit.scale.name != 'kilogram' and
kg_unit.scale.symbol != 'kg'
):
raise RuntimeError(
"conventional name required, got {0.name} and{0.symbol}".format(
kg_unit.scale
)
)
register =... | [
"def ug(micrograms):\n return Unit(micrograms,\"microgram\")",
"def unit(self, units='kgs'):\n if units == 'kgs':\n return self.__factory(self.data)\n elif units == 'kgh':\n return self.__factory(self.data / hour)\n elif units == 'lbs':\n return self.__fact... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a table with n points for L <= x <= R. | def table(self, L, R, n=10):
s = ""
for x in np.linspace(L, R, n):
y = self(x)
s += f"({x:.2f}, {y:.2f})\n"
return s | [
"def table(self, L, R, n):\n\n self.L, self.R, self.n = L, R, n\n\n # Create array of x values from a to b in n steps:\n x_values = linspace(L, R, n)\n\n # Indices to traverse x\n index_set = range(len(x_values))\n\n # Create array of zeros for y values:\n y_values ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets family and nodename for a loopback address. | def _localhost():
s = socket
infos = s.getaddrinfo(
None, 0, s.AF_UNSPEC, s.SOCK_STREAM, 0, s.AI_ADDRCONFIG
)
(family, _, _, _, address) = infos[0]
nodename = address[0]
return (family, nodename) | [
"def get_ip_or_name():\n # Access to the local computer name.\n name = socket.getfqdn(socket.gethostname())\n # Access to the local computer address.\n addr = socket.gethostbyname(name)\n\n return addr, name",
"def lan_address(self):\n _, port = self._socket.getsockname()\n return (\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a `WSGIServer` subclass that works on IPv6only machines. | def _make_ipv6_compatible_wsgi_server():
address_family = _localhost()[0]
attrs = {"address_family": address_family}
bases = (simple_server.WSGIServer, object) # `object` needed for py2
return type("_Ipv6CompatibleWsgiServer", bases, attrs) | [
"def make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler):\n server = server_class((host, port), handler_class)\n server.set_app(app)\n return server",
"def listen_v6(self):\n self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) # creaz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tabulate neff for the set of nsigma maglim, integrating n(m)completeness(m) | def tabulate_neff(nofm,
maglims,
min_int_mag=None,
max_int_mag=None,
ninterp=_DEFAULT_NINTERP,
nint=_DEFAULT_NINT):
from .completeness import Completeness
maglims=numpy.array(maglims, ndmin=1, dtype='f8')
if min_int_... | [
"def main(n = 150000, quiet = False):\n t0 = time() #timing possibility\n\n if quiet:\n output_stream = StringIO()\n else:\n output_stream = sys.stdout\n\n\n print(t0,file=output_stream)\n \n\n sfr = .01\n # star mass function\n kroupa = np.vectorize(functions.kroupa)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests extract features function | def test__extract_features(self):
text_sample = "I really really love this movie"
feature_sample = ['really','love','good']
feature_score_type = "presence"
model_sample = Model(feature_sample,feature_score_type)
result_features = model_sample.extract_features(text_sample)
... | [
"def feature_extractor():\n pass",
"def extract_features(self):\n self.extract_features_static()\n self.extract_features_dynamic()",
"def extract_features(batches):\n pass",
"def extractFeatures(self, datum):\n abstract",
"def run_feature_extraction_tests():\n test_feature_extr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the function build feature base | def test_build_feature_base(self):
data = pd.DataFrame(pd.read_csv("tests/in_data/pro1_sub.csv"))
X = data.ix[:,1]
Y = data.ix[:,0]
model_sample = Model([],"presence")
feature_base = model_sample.build_feature_base(X,Y)
feature_evaluation =
assert_equal(len(feat... | [
"def test_quick_build(self):\n pass",
"def test_quick_build1(self):\n pass",
"def testing_featurizer_build():\n f = ImageFeaturizer()\n compare_featurizer_class(f, (0, 0), np.zeros((1)), 0, '', False, '', {}, 1)",
"def testing(self):",
"def init_features():\n TEST_FEATURES.append(feat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merges QC Data at resolutions other than HH (DD, WW, MM, YY) | def merge_qcdata_res(qcdata, output, res):
ts_label = TIMESTAMP_DTYPE_BY_RESOLUTION[res][-1][0]
if not numpy.all(qcdata[ts_label] == output[ts_label]):
raise ONEFluxError("Timestamps differ for QAData merging ({r})".format(r=res))
var_add = [i for i in list(qcdata.dtype.descr) if (('TIMESTAMP' not... | [
"def aggregate_qcdata(qcdata):\n\n # DD\n log.debug('Aggregating daily DD QC Data')\n curr_ts, last_ts = datetime.strptime(qcdata['TIMESTAMP_START'][0], '%Y%m%d%H%M'), datetime.strptime(qcdata['TIMESTAMP_START'][-1], '%Y%m%d%H%M')\n curr_y, first_y, last_y = curr_ts.year, curr_ts.year, last_ts.year\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create DD, WW, MM, and YY aggregations for QC Data from HH | def aggregate_qcdata(qcdata):
# DD
log.debug('Aggregating daily DD QC Data')
curr_ts, last_ts = datetime.strptime(qcdata['TIMESTAMP_START'][0], '%Y%m%d%H%M'), datetime.strptime(qcdata['TIMESTAMP_START'][-1], '%Y%m%d%H%M')
curr_y, first_y, last_y = curr_ts.year, curr_ts.year, last_ts.year
entries_dd... | [
"def build_time_metric(df_joined,dictionary):\n # Extract the hour\n df_joined[\"Time\"] = df_joined[\"TimeSt\"].str[11:13]\n # Map the score\n df_joined[\"Time_Metric\"] = df_joined[\"Time\"].map(dictionary)\n return df_joined",
"def MQI_Statistics(j):\n fields = [\"startDate\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate stats and zip file for file list | def gen_stats_zip(filename_list, zipfilename, tier='tier2', csv_processor='ICOS-ETC', zip_processor='LBL_AMP', ts_format="%Y-%m-%d %H:%M:%S"):
log.info("Generating ZIP and stats for: {z}".format(z=zipfilename))
if not filename_list:
return [], []
today = datetime.now().strftime(ts_format)
outp... | [
"def zip(self):\n self.report()\n cwd = os.getcwd()\n os.chdir(self.dirn)\n # Top-level directory to create in the zip file\n zip_top_dir = self.report_name\n # Relative path to qc results directory\n qc_dir = os.path.basename(self.qc_dir)\n # Create the zip f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a consecutive date list starting at start_day for period days. | def create_date_list(
periods: int, start_date: str = "2020-09-01", freq: str = "d"
) -> list:
return [str(d)[:10] for d in pd.date_range(start_date, periods=periods, freq=freq)] | [
"def create_date_range(start_date: datetime.date, number_of_days: int) -> List[datetime.date]:\n return [start_date + datetime.timedelta(days=day) for day in range(number_of_days)]",
"def create_date_list(start_date = start_date, end_date = end_date):",
"def build_date_ranges(begin_date, end_date, days_per_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a spline basis functions. | def create_spline_basis(
x, knot_list=None, num_knots=None, degree: int = 3, add_intercept=True
):
assert ((knot_list is None) and (num_knots is not None)) or (
(knot_list is not None) and (num_knots is None)
), "Define knot_list OR num_knot"
if knot_list is None:
knot_list = np.quantile... | [
"def calc_spline_coefs(self):\n\n if(not self.import_all):\n self.importAll() # we need to import the quantities\n\n self.rSpline = SPLINE.SPLINE({'x':self.es, \n 'y':self.rmnc, \n 'kindspec':self.compute_spline_typ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a SKAST expression from a given bound method of a fitted SKLearn model. A shorthand notation for SKompiledModel(method, inputs) | def skompile(*args, inputs=None):
if len(args) > 3:
raise ValueError("Too many arguments")
elif not args:
raise ValueError("Invalid arguments")
elif len(args) == 3:
if inputs is not None:
raise ValueError("Too many arguments")
model, method, inputs = args
eli... | [
"def relaxation_as_linear_operator(method, A, b):\n\n def unpack_arg(v):\n if isinstance(v, tuple):\n return v[0], v[1]\n return v, {}\n\n # setup variables\n accepted_methods = ['gauss_seidel', 'block_gauss_seidel', 'sor',\n 'gauss_seidel_ne', 'gauss_seidel_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all wildcards that occur in a grammar | def get_wildcards_forest(trees):
wildcards = set()
for tree in trees:
extracted = tree.scan_values(lambda x: isinstance(x, WildCard))
for item in extracted:
wildcards.add(item)
return wildcards | [
"def get_wildcards(self, mat, raw_text):\n\n regexpr = r\"((?:[A-Z][a-z]?\\d*[A-Za-z0-9\" + \\\n self.GREEK_LETTERS + \"\\(\\)\\+\\-]*){2,})\"\n formula = re.findall(regexpr, mat)\n if not formula:\n return\n try:\n struct = self.mp.get_chemical_structure... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a resnet model from torchvision.models, it changes its norm according to norm_type | def change_norm(model, norm_type="BN", norm_power=0.2):
# select norm to be used
normlayer = select_norm(norm_type, norm_power=norm_power)
# find total number of childern
model_len = 0
for n, child in enumerate(model.children()):
model_len = n
# for layer 0 which is outside
conv_sh... | [
"def _update_normalizer(self, rollout, env_type):\n if self._config.ob_norm:\n self._agent.update_normalizer(rollout[\"ob\"], env_type)",
"def _select_norm(norm):\n if norm == 'batchnorm':\n norm = nn.BatchNorm2d\n elif norm == 'instancenorm':\n norm = nn.InstanceNorm2d\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mueller matrix operator for an optical attenuator. | def op_attenuator(t):
att = np.array([[t, 0, 0, 0],
[0, t, 0, 0],
[0, 0, t, 0],
[0, 0, 0, t]])
return att | [
"def multiplica_matriu(self,m):\n\t\tr_org = self.rows\n\t\tc_org = self.cols\n\t\t\n\t\tr_add = m.rows\n\t\tc_add = m.cols\n\t\t\n\t\t\n\t\t#matriu auxiliar per a resultat, omplint en 0.\n\t\tl_aux = []\n\t\tfor r in range(0,self.rows):\n\t\t\tr_aux = []\n\t\t\tfor c in range(m.cols):\n\t\t\t\tr_aux.append(0)\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mueller matrix operator for a perfect mirror. | def op_mirror():
mir = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, -1]])
return mir | [
"def reverse_matrix(self):\n return SWAP.matrix @ self.matrix @ SWAP.matrix",
"def _mirror_(o, a, b):\n A = a-o\n B = b-o\n C = (dot(B,A)/dot(A,A))*A\n mB = 2*C-B\n return mB+o",
"def commute_matrix(A):\n R = resistance_matrix(A)\n E = A.sum() / 2 # number of edg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mueller matrix operator for an quarterwave plate. | def op_quarter_wave_plate(theta):
C2 = np.cos(2 * theta)
S2 = np.sin(2 * theta)
qwp = np.array([[1, 0, 0, 0],
[0, C2**2, C2 * S2, -S2],
[0, C2 * S2, S2 * S2, C2],
[0, S2, -C2, 0]])
return qwp | [
"def Q_mat(self, angle):\n\n # U_i values for the block multiplication\n U_1 = (1 / 8) * (3 * self.Qxx + 3 * self.Qyy + 2 * self.Qxy + 4 * self.Qss)\n U_2 = (1 / 2) * (self.Qxx - self.Qyy)\n U_3 = (1 / 8) * (self.Qxx + self.Qyy - 2 * self.Qxy - 4 * self.Qss)\n U_4 = (1 / 8) * (sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mueller matrix operator for Fresnel reflection at angle theta. These are based on Collett, MuellerStokes Matrix Formulation of Fresnel equation, Am. J Phys., 39, 1971. The changes in direction and detector orientation are included in the Mueller matrix. See Clark, Stellar Polarimetry, Appendix A. Still needs sign testi... | def op_fresnel_reflection(m, theta):
rho_p = pypolar.fresnel.r_par_amplitude(m, theta)
rho_s = pypolar.fresnel.r_per_amplitude(m, theta)
a = abs(rho_s)**2 + abs(rho_p)**2
b = abs(rho_s)**2 - abs(rho_p)**2
c = 2 * rho_s * rho_p
mat = np.array([[a, b, 0, 0],
[b, a, 0, 0],
... | [
"def op_fresnel_transmission(m, theta):\n tau_p = pypolar.fresnel.T_par(m, theta)\n tau_s = pypolar.fresnel.T_per(m, theta)\n a = tau_s + tau_p\n b = tau_s - tau_p\n c = 2 * np.sqrt(tau_s * tau_p)\n mat = np.array([[a, b, 0, 0],\n [b, a, 0, 0],\n [0, 0, c, 0],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mueller matrix operator for Fresnel transmission at angle theta. These are based on Collett, MuellerStokes Matrix Formulation of Fresnel equation, Am. J Phys., 39, 1971. Still needs sign testing for angles above Brewster's angle. | def op_fresnel_transmission(m, theta):
tau_p = pypolar.fresnel.T_par(m, theta)
tau_s = pypolar.fresnel.T_per(m, theta)
a = tau_s + tau_p
b = tau_s - tau_p
c = 2 * np.sqrt(tau_s * tau_p)
mat = np.array([[a, b, 0, 0],
[b, a, 0, 0],
[0, 0, c, 0],
... | [
"def applyRotMatrix(station,rm,mode='LBA'):\n loc=station.antField.location[mode]\n return n.dot(rm,loc)",
"def forward_matrix(joints, goal_frame='right_wrist'):\n zaxis = np.array([0,0,1])\n M = np.identity(4)\n \n if goal_frame.startswith('right_'):\n #torso to right_arm_mount\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stokes vector for right circular polarized light. | def stokes_right_circular():
return np.array([1, 0, 0, 1]) | [
"def Stokes_from_circular(self):\n (El,Er) = self.circular\n self.logger.debug(\"Stokes_from_circular: (El, Er) = %s\", (El,Er))\n (Elc,Erc) = self.circular.conj()\n self.logger.debug(\"Stokes_from_circular: (El*,Er*) = %s\", (Elc,Erc))\n (Sll,Srr) = abs(self.circular*self.circular.conj())\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stokes vector for left circular polarized light. | def stokes_left_circular():
return np.array([1, 0, 0, -1]) | [
"def stokes_right_circular():\n return np.array([1, 0, 0, 1])",
"def Stokes_from_circular(self):\n (El,Er) = self.circular\n self.logger.debug(\"Stokes_from_circular: (El, Er) = %s\", (El,Er))\n (Elc,Erc) = self.circular.conj()\n self.logger.debug(\"Stokes_from_circular: (El*,Er*) = %s\", (Elc,Erc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stokes vector for horizontal polarized light. | def stokes_horizontal():
return np.array([1, 1, 0, 0]) | [
"def getStokesVector(self):\n Ex, Ey = np.sum(self.Ex*self.Mask), np.sum(self.Ey*self.Mask)\n I = np.real(Ex*np.conjugate(Ex) + Ey*np.conjugate(Ey))\n Q = np.real(Ex*np.conjugate(Ex) - Ey*np.conjugate(Ey))\n U = np.real(Ex*np.conjugate(Ey) + Ey*np.conjugate(Ex))\n V = np.real(1j*(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stokes vector for vertical polarized light. | def stokes_vertical():
return np.array([1, -1, 0, 0]) | [
"def getStokesVector(self):\n Ex, Ey = np.sum(self.Ex*self.Mask), np.sum(self.Ey*self.Mask)\n I = np.real(Ex*np.conjugate(Ex) + Ey*np.conjugate(Ey))\n Q = np.real(Ex*np.conjugate(Ex) - Ey*np.conjugate(Ey))\n U = np.real(Ex*np.conjugate(Ey) + Ey*np.conjugate(Ex))\n V = np.real(1j*(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stokes vector using ellipsometer parameters. This creates a Stokes vector for the specific set of ellipsometry parameters tanpsi and Delta. See Fujiwara table 3.1 for example. | def stokes_ellipsometry(tanpsi, Delta):
psi = np.arctan(tanpsi)
cp = np.cos(2*psi)
sp = np.sin(2*psi)
cd = np.cos(2*Delta)
sd = np.sin(2*Delta)
if np.isscalar(tanpsi) and np.isscalar(Delta):
return np.array([1, -cp, sp*cd, -sp*sd])
return np.array([np.ones_like(tanpsi), -cp, sp*cd, ... | [
"def Stokes_from_linear(self):\n (Ex,Ey) = self.linear\n self.logger.debug(\"Stokes_from_linear: (Ex, Ey) = %s\", (Ex,Ey))\n (Exc,Eyc) = self.linear.conj()\n self.logger.debug(\"Stokes_from_linear: (Ex*,Ey*) = %s\", (Exc,Eyc))\n (Sxx,Syy) = abs(self.linear*self.linear.conj())\n self.logger.debug(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the ellipticity of the polarization ellipse. This parameter is often represented by Chi. | def ellipse_ellipticity(S):
return 1/2 * np.arcsin(S[..., 3]/S[..., 0]) | [
"def elliptic_curve(self):\n return self.__E",
"def is_elliptic(self):\n if self.is_irreducible():\n return self._info['elliptic']\n else:\n return False",
"def eccentricity(self):\n return sqrt(self.f * 2 - self.f ** 2)",
"def eccentricity(self):\n\n l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the semimajor and semiminor axes of the polarization ellipse. | def ellipse_axes(S):
absL = np.sqrt(S[..., 1]**2 + S[..., 2]**2)
A = np.sqrt((S[..., 0] + absL)/2)
B = np.sqrt((S[..., 0] - absL)/2)
return A, B | [
"def semiminor_axis(self):\n return self.semimajor_axis * (1 - self.flattening)",
"def _get_semimajor_axis(self):\n t0 = jd.t_zero(self._julianDay)\n switcher = {\n 1: 0.387099270 + t0 * 0.00000037, # Mercury\n 2: 0.723335660 + t0 * 0.00000390, # Venus\n 3... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a Stokes vector to a Jones vector. The Jones vector can only represent the part of the Stokes vector that is polarized. This fraction is calculated and represented as a Jones vector with its horizontal component represented as a real number. The sign convention for the Jones vector can be set by calling `pypola... | def _stokes_to_jones(S):
if S[0] == 0:
return np.array([0, 0])
# Fraction of intensity that is polarized
Ip = np.sqrt(S[1]**2 + S[2]**2 + S[3]**2)
# Normalize the remaining Stokes parameters to this fraction
Q = S[1] / Ip
U = S[2] / Ip
V = S[3] / Ip
# Amplitude of the polarize... | [
"def stokes_vector_to_jones(vec: (np.ndarray, list, tuple), is_need_check=True):\n if is_need_check:\n is_stokes_vector(vec)\n from_stokes_to_jones_transform = np.array([[0.5, 0.5, 0., 0.],\n [0., 0., 0.5, - 0.5j],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a (list of) Stokes vector(s) to a (list of) Jones vector(s). The sign convention for the Jones vector can be set by calling `pypolar.jones.use_alternate_convention(True)`. The default is to assume that the field is represented by exp(jomegatkz). | def stokes_to_jones(S):
if S.ndim == 1:
return _stokes_to_jones(S)
n, m = S.shape
if m != 4:
print("Wrong shape ... should be %dx4 not %dx%d" % (m, n, m))
return None
J = np.empty(shape=(n, 2), dtype=np.ndarray)
for i, SS in enumerate(S):
J[i] = _stokes_to_jones(SS)... | [
"def _stokes_to_jones(S):\n if S[0] == 0:\n return np.array([0, 0])\n\n # Fraction of intensity that is polarized\n Ip = np.sqrt(S[1]**2 + S[2]**2 + S[3]**2)\n\n # Normalize the remaining Stokes parameters to this fraction\n Q = S[1] / Ip\n U = S[2] / Ip\n V = S[3] / Ip\n\n # Amplitud... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a Mueller matrix to a Jones matrix. Theocaris, Matrix Theory of Photoelasticity, eqns 4.704.76, 1979 | def mueller_to_jones(M):
A = np.empty((2, 2))
A[0, 0] = np.sqrt((M[0, 0]+M[0, 1]+M[1, 0]+M[1, 1])/2)
A[0, 1] = np.sqrt((M[0, 0]+M[0, 1]-M[1, 0]-M[1, 1])/2)
A[1, 0] = np.sqrt((M[0, 0]-M[0, 1]+M[1, 0]-M[1, 1])/2)
A[1, 1] = np.sqrt((M[0, 0]-M[0, 1]-M[1, 0]+M[1, 1])/2)
theta = np.empty((2, 2))
... | [
"def Jones2Mueller(J):\n A=np.matrix([[1,0,0,1],[1,0,0,-1],[0,1,1,0],[0,1j,-1j,0]])\n M=invStokes*np.kron(J,J.conj())*Stokes\n return np.real(M)",
"def rigidBodyMassMatrix(Mass,J,rho): # TODO change interface\n S=Mass*skew(rho)\n MM=np.zeros((6,6))\n MM[0:3,0:3] = Mass*np.eye(3);\n MM[0:3,3:6... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interpret a Stokes vector. | def interpret(S):
try:
S0, S1, S2, S3 = S
except:
print("Stokes vector must have four real elements")
return 0
# eps = 1e-12
print("I = %.3f" % S0)
print("Q = %.3f" % S1)
print("U = %.3f" % S2)
print("V = %.3f" % S3)
s = "not implemented yet"
return s | [
"def getStokesVector(self):\n Ex, Ey = np.sum(self.Ex*self.Mask), np.sum(self.Ey*self.Mask)\n I = np.real(Ex*np.conjugate(Ex) + Ey*np.conjugate(Ey))\n Q = np.real(Ex*np.conjugate(Ex) - Ey*np.conjugate(Ey))\n U = np.real(Ex*np.conjugate(Ey) + Ey*np.conjugate(Ex))\n V = np.real(1j*(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Smooth observations producing position, speed, acceleration | def smooth(self, observations):
pos = []
vel = []
acc = []
for i in range(observations.shape[1]):
y, covariances = self.kf.smooth(observations[:, i])
pos.append(y[:, 0].reshape(-1, 1))
vel.append(y[:, 1].reshape(-1, 1))
acc.append(y[:, 2].... | [
"def ApplySmooth(self) -> None:\n ...",
"def smooth(self, data_points):\n movements = self.interpolate_data_points(data_points)\n joint_names = list()\n for motion in movements[0]:\n joint_names.append(motion[0])\n\n positions_list, durations = self.get_positions_dura... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Datasets class for TUD datasets | def __init__(self, name_dataset, reduce=False):
dataset = TUDataset(root='data/TUDataset', name=name_dataset)
if reduce:
new_dataset = []
for i in tqdm(range(len(dataset))):
aux_graph = copy.deepcopy(dataset[i])
aux_graph.edge_index = TUDData.reduc... | [
"def datasets(self):\n pass",
"def datasets(self) -> AbstractDatasetResource:",
"def task_dataset(representations, features):\n return FakeTaskDataset(representations, features)",
"def __init__(self):\n print(\"Generando el Dataset de Entrenamiento...\")\n self._X_train, self._Y_train = crearD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Morphologically removes small (less than size) connected regions of 0s or 1s. | def remove_small_regions(img, size):
img = morphology.remove_small_objects(img, size)
img = morphology.remove_small_holes(img, size)
return img | [
"def clean(img):\n\n label_img = label(img, connectivity=2)\n props = sorted(regionprops(label_img), key=lambda x: x.area)\n clean = morphology.binary_closing(img)\n\n clean = morphology.remove_small_holes(clean)\n return morphology.remove_small_objects(clean,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Annotate a corpus for numerical values | def annotate(self,corpus):
assert corpus.parsed == True, "Corpus must already be parsed before entity recognition"
for doc in corpus.documents:
entityCount = len(doc.entities)
for sentence in doc.sentences:
words = [ t.word for t in sentence.tokens ]
for i,t in enumerate(sentence.tokens):
... | [
"def numericalize_corpus(corpus, word_to_index, pad_examples=True, input_length=100):\n return [numericalize_text(document, word_to_index, pad_examples, input_length) for document in corpus]",
"def encode_annotations(self, documents:List[Document]):\n\n # Loop over documents\n labels = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the tile at position row, col to have the given value. | def set_tile(self, row, col, value):
self.grid[row][col] = value | [
"def set_tile(self, row, col, value):\n self.grid[row][col] = value\n pass",
"def set_tile(self, row, col, value):\r\n \r\n self._grid[row][col] = value",
"def set_value( self, row, col, value ):\n self.theMaze[row][col]=value",
"def set_our_tile(self, x, y, value):\n\t\tif ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Erases the cache of instrument parameters. | def _erase_device_parameters_cache(self):
self._device_parameters = {} | [
"def clear_cache(self):",
"def memo_clear(self, *args, **kwargs):\n memo_key = self._key(args, kwargs)\n self._get_memo_dict().pop(memo_key, None)",
"def clear_params(self):\n self._last_population = None",
"def clear_cache(self):\n pass",
"def clear_cache(self):\n # pylint: disab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configures the instrument with the settings of the runcard. A connection to the instrument needs to be established beforehand. | def setup(self):
settings: ClusterQRM_RF_Settings = self.settings
if self.is_connected:
# Load settings
port_settings: ClusterRF_OutputPort_Settings = settings.ports["o1"]
self.ports["o1"].channel = port_settings.channel
self._port_channel_map["o1"] = self... | [
"def configure_instrumented_models(self):\n # Expose Pyramid configuration to classes\n from websauna.system.model.meta import Base\n Base.metadata.pyramid_config = self.config",
"def config(self) -> InstrumentConfig:\n ...",
"def configure(self, config):\n pass",
"def confi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves and configures the next avaliable sequencer. The parameters of the new sequencer are copied from those of the default sequencer, except for the intermediate frequency and classification parameters. | def _get_next_sequencer(self, port: str, frequency: int, qubits: dict, qubit: None):
# select a new sequencer and configure it as required
next_sequencer_number = self._free_sequencers_numbers.pop(0)
if next_sequencer_number != self.DEFAULT_SEQUENCERS[port]:
for parameter in self.de... | [
"def update_sequencers(self):\n if self.sequencer_updated:\n params = self.get_sequence_params()\n if params[\"sequence_type\"] != \"None\":\n self.controller.awg.set_sequence_params(**params)",
"def get_sequence_params(self):\n base_name = f\"Sequencer - \"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the intermediate frequency needed to synthesise a pulse based on the port lo frequency. | def get_if(self, pulse: Pulse):
_rf = pulse.frequency
_lo = self.ports[self._channel_port_map[pulse.channel]].lo_frequency
_if = _rf - _lo
if abs(_if) > self.FREQUENCY_LIMIT:
raise Exception(
f"""
Pulse frequency {_rf:_} cannot be synthesised with... | [
"def get_pulse_frequency(self, k):\n return self.omega[k]",
"def tone_to_freq(tone):\n return math.pow(2, (tone - 69.0) / 12.0) * 440.0",
"def _frequency_to_wavelength(freq):\n return ifc.SPEED_OF_LIGHT_METRES_PER_SECOND / freq",
"def frequency(self) -> float:\r\n return self.gpio.get_PWM_fr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes a sequence of pulses and sweepers, generating the waveforms and program required by the instrument to synthesise them. The output of the process is a list of sequencers used for each port, configured with the information required to play the sequence. | def process_pulse_sequence(
self,
qubits: dict,
instrument_pulses: PulseSequence,
navgs: int,
nshots: int,
repetition_duration: int,
sweepers=None,
):
if sweepers is None:
sweepers = []
sequencer: Sequencer
sweeper: Sweeper
... | [
"def preparePulseSequence(self):\n # get carrier frequency\n if self._MWSource is not None:\n carrierFrequency = self.carrierFrequency()\n else:\n carrierFrequency = 0\n\n # Decide to apply or not corrections\n applyCorrectionsArray = [\n pulse.app... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads waveforms and programs of all sequencers and arms them in preparation for execution. This method should be called after `process_pulse_sequence()`. It configures certain parameters of the instrument based on the needs of resources determined while processing the pulse sequence. | def upload(self):
# Setup
for sequencer_number in self._used_sequencers_numbers:
target = self.device.sequencers[sequencer_number]
self._set_device_parameter(target, "sync_en", value=True)
self._set_device_parameter(target, "marker_ovr_en", value=True) # Default afte... | [
"def _push_waveforms(self) -> None:\n if not self._seqc_features.codewords:\n return\n for codeword in self._codeword_manager.active_codewords:\n try:\n waveform = self.get(_waveform_name(codeword))\n ch, slot = self._generator_slot(codeword)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plays the sequence of pulses. Starts the sequencers needed to play the sequence of pulses. | def play_sequence(self):
# Start used sequencers
for sequencer_number in self._used_sequencers_numbers:
self.device.start_sequencer(sequencer_number) | [
"def play_seq(self):\n \n self.deactivate_buts()\n \n # Add one random button number to sequence\n self.sequence.append(randint(0, 3))\n\n # Speed up playback by set amounts at set points in the game\n if len(self.sequence) == 6:\n self.duration = 0.36\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes the results of the acquisition. If hardware demodulation is disabled, it demodulates and integrates the acquired pulse. If enabled, if processes the results as required by qblox (calculating the average by dividing the integrated results by the number of smaples acquired). | def _process_acquisition_results(self, acquisition_results, readout_pulse: Pulse, demodulate=True):
if demodulate:
acquisition_frequency = self.get_if(readout_pulse)
# DOWN Conversion
n0 = 0
n1 = self.ports["i1"].acquisition_duration
input_vec_I = np.... | [
"def start_accumulation(self):\n\n # get Keithley picoAmmeters ready by resetting and clearing buffer\n# sub.pd.synchCommand(60, \"reset\")\n# bbsub.synchCommand(60, \"resetPD\")\n# bbsub.synchCommand(60, \"clearPDbuff\")\n# bbsub.sendSynchCommand(\"resetPD\")\n bbsub.Photo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse one page of a restaurant and get all his parameters | def parse_one_restaurant():
# Used for determining on which page error occurs
global on_tags, on_details
try:
on_details = True
on_tags = False
# Get all of useful params of this page
name = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'h1.section-hero-header-title-title'))).text
type =... | [
"def crawl_page(latitude,longitude, page_num, verbose=True):\r\n try:\r\n if(page_num==0):\r\n page_url = get_city_restaurants_page_0(latitude, longitude)\r\n else:\r\n page_url= get_city_restaurants_pages(latitude,longitude,page_num)\r\n soup = BeautifulSoup(urllib2.ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a shallow copy of this matrix. Creates a new instance of Matrix but with data referencing the data of the original matrix. | def __copy__(self):
return self.__class__(self.m, self.n, self.data) | [
"def copy(self):\n return Matrix(self.__data.copy(),\n self.__rowlabels.copy(),\n self.__columnlabels.copy())",
"def copy(self):\n c = matrix()\n c.tt = self.tt.copy()\n c.n = self.n.copy()\n c.m = self.m.copy()\n return c",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if and only if this matrix is symmetric. | def is_symmetric(self):
return self.all_equal(self.transpose()) | [
"def is_symmetric(self):\n return self.matrix_copy().is_symmetric",
"def is_symmetric(self):\n if self.is_square():\n return self == self.transpose()\n else:\n return False",
"def is_symmetric(self):\n return self.args[0].is_symmetric()",
"def is_symmetric(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if and only if this matrix is skewsymmetric. | def is_skew_symmetric(self):
return self.all_equal(-self.transpose()) | [
"def is_skew_symmetric(self):\n if self.is_square():\n return self == self.transpose() * -1\n else:\n return False",
"def is_skew_symmetric(self):\n return self._info['skew_symmetric']",
"def is_symmetric(self):\n return self.matrix_copy().is_symmetric",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the Toeplitz decomposition to this matrix. Decompose this matrix into the sum of a symmetric and skewsymmetric matrix, returning the result as a tuple. | def toeplitz_decomposition(self):
if self.m != self.n:
raise exc.DecompositionError("non-square matrices do not have a " +
"a Toeplitz decomposition")
# TODO: test for decomposition directly using the parity of elements
try:
diviso... | [
"def berkowitz(self):\n if not self.is_square:\n raise NonSquareMatrixError()\n\n A, N = self, self.rows\n transforms = [0] * (N-1)\n\n for n in xrange(N, 1, -1):\n T, k = zeros(n+1, n), n - 1\n\n R, C = -A[k,:k], A[:k,k]\n A, a = A[:k,:k], -A[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the QR decomposition to this matrix. Decompose this matrix into the product of an orthogonal and upper triangular matrix, returning the result as a tuple. | def qr_decomposition(self):
if self.m != self.n:
raise NotImplementedError('QR decomposition not yet available ' +
'for non-square matrices')
orig_basis = [vec.Vector.fromMatrixColumn(self, j)
for j in range(self.m)]
orthog_... | [
"def qr_factorization_householder(A: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n assert norm(A) > 0, \"QR factorization of zero-matrix not possible\"\n m, n = A.shape\n\n I = np.identity(m)\n Q = I.copy()\n\n for k in range(min(m - 1, n)):\n A_small = A[k:, k:]\n x = A_small[:, 0] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create random matrix. Make a random matrix of dimension m by n with elements chosen independently and uniformly from the interval (min, max). | def makeRandom(cls, m, n, min=0, max=1):
Matrix.validate_dimensions(m, n)
data = [[randrange(min, max) for j in range(n)] for i in range(m)]
return RealMatrix(m, n, data) | [
"def randmatrix(m, n, lower=-0.5, upper=0.5):\n return np.array([random.uniform(lower, upper) for i in range(m*n)]).reshape(m, n)",
"def generate_matrix(rand_range,n_value):\n matrix = np.empty([n_value,n_value])\n for x in range(rand_range):\n for y in range(rand_range):\n matrix[x][y]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make matrix from list. Make a matrix from a list of elements, filling along data, when given at least one dimension of the matrix. | def fromList(cls, elems, **kwargs):
if not ('m' in kwargs or 'n' in kwargs):
raise ValueError("at least one of m and n must be specified")
m = kwargs.get('m')
n = kwargs.get('n')
num_elems = len(elems)
if m is None:
m = num_elems // n
elif n is Non... | [
"def matrixlist(inputlist, converter=proper, fake=False):\n if converter is None:\n converter = type(inputlist[0][0])\n xlen = len(inputlist[0])\n for x in xrange(1,len(inputlist)):\n if len(inputlist[x]) != xlen:\n raise IndexError(\"Unequal matrix row lengths for matrixlist of \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make matrix from a list of vectors. | def fromVectors(cls, vectors):
data = [[v[i] for i in range(v.m)] for v in vectors]
return Matrix.fromCols(data) | [
"def getVector(lstOfValues):\n return MatrixExtended([[v] for v in lstOfValues])",
"def vector_as_matrix(v):\r\n return [[v_i] for v_i in v]",
"def vector_as_matrix(v):\n return [[v_i] for v_i in v]",
"def get_list_as_mvector(input_list):\n out_vec = oMa.MVector(input_list[0], input_list[1], input... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set/reset the decimal precision used for the __str__() magic. | def set_str_precision(cls, dp=3):
cls.str_decimal_places = dp | [
"def set_precision(prec = None):\n context = decimal.getcontext()\n oldprec = context.prec\n if prec is not None:\n context.prec = prec\n return oldprec",
"def _set_precision(self, precision) :\n self.__precision = self.parent().monoid().filter(precision)",
"def _se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a given object is of a numeric type. Note that since bool inherits from int, that this will accept Boolean values | def is_numeric(obj):
return isinstance(obj, (int, float, complex)) | [
"def isNumeric(obj):\n return isinstance(obj, (int, float, bool))",
"def _is_numeric(obj) -> bool:\n\n if type(obj) is float:\n obj: float = float(obj)\n return not isnan(obj)\n\n if type(obj) is int:\n return True\n\n assert type(obj) is str\n obj: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute Boolean AND of this matrix and another valid object. | def __and__(self, obj):
return self._boolean_operation(obj, operator.__and__) | [
"def __and__(self, other):\n return arithmetics.bitwise_and(self, other)",
"def logical_and(self, a, b):\n a = _convert_other(a, raiseit=True)\n return a.logical_and(b, context=self)",
"def __and__(self, other):\n a, b = Trits.match_length(self, other)\n return Trits([x & y fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |