repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
xoolive/traffic | traffic/core/aero.py | vcas2mach | def vcas2mach(cas, h):
""" CAS to Mach conversion """
tas = vcas2tas(cas, h)
M = vtas2mach(tas, h)
return M | python | def vcas2mach(cas, h):
""" CAS to Mach conversion """
tas = vcas2tas(cas, h)
M = vtas2mach(tas, h)
return M | [
"def",
"vcas2mach",
"(",
"cas",
",",
"h",
")",
":",
"tas",
"=",
"vcas2tas",
"(",
"cas",
",",
"h",
")",
"M",
"=",
"vtas2mach",
"(",
"tas",
",",
"h",
")",
"return",
"M"
] | CAS to Mach conversion | [
"CAS",
"to",
"Mach",
"conversion"
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/aero.py#L145-L149 | train | 199,800 |
xoolive/traffic | traffic/core/aero.py | cas2mach | def cas2mach(cas, h):
""" CAS Mach conversion """
tas = cas2tas(cas, h)
M = tas2mach(tas, h)
return M | python | def cas2mach(cas, h):
""" CAS Mach conversion """
tas = cas2tas(cas, h)
M = tas2mach(tas, h)
return M | [
"def",
"cas2mach",
"(",
"cas",
",",
"h",
")",
":",
"tas",
"=",
"cas2tas",
"(",
"cas",
",",
"h",
")",
"M",
"=",
"tas2mach",
"(",
"tas",
",",
"h",
")",
"return",
"M"
] | CAS Mach conversion | [
"CAS",
"Mach",
"conversion"
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/core/aero.py#L352-L356 | train | 199,801 |
xoolive/traffic | traffic/plugins/bluesky.py | to_bluesky | def to_bluesky(
traffic: Traffic,
filename: Union[str, Path],
minimum_time: Optional[timelike] = None,
) -> None:
"""Generates a Bluesky scenario file."""
if minimum_time is not None:
minimum_time = to_datetime(minimum_time)
traffic = traffic.query(f"timestamp >= '{minimum_time}'")
if isinstance(filename, str):
filename = Path(filename)
if not filename.parent.exists():
filename.parent.mkdir(parents=True)
altitude = (
"baro_altitude"
if "baro_altitude" in traffic.data.columns
else "altitude"
)
if "mdl" not in traffic.data.columns:
traffic = aircraft.merge(traffic)
if "cas" not in traffic.data.columns:
traffic = Traffic(
traffic.data.assign(
cas=vtas2cas(traffic.data.ground_speed, traffic.data[altitude])
)
)
with filename.open("w") as fh:
t_delta = traffic.data.timestamp - traffic.start_time
data = (
traffic.assign_id()
.data.groupby("flight_id")
.filter(lambda x: x.shape[0] > 3)
.assign(timedelta=t_delta.apply(fmt_timedelta))
.sort_values(by="timestamp")
)
for column in data.columns:
data[column] = data[column].astype(np.str)
is_created: List[str] = []
is_deleted: List[str] = []
start_time = cast(pd.Timestamp, traffic.start_time).time()
fh.write(f"00:00:00> TIME {start_time}\n")
# Add some bluesky command for the visualisation
# fh.write("00:00:00>trail on\n")
# fh.write("00:00:00>ssd conflicts\n")
# We remove an object when it's its last data point
buff = data.groupby("flight_id").timestamp.max()
dd = pd.DataFrame(
columns=["timestamp"], data=buff.values, index=buff.index.values
)
map_icao24_last_point = {}
for i, v in dd.iterrows():
map_icao24_last_point[i] = v[0]
# Main loop to write lines in the scenario file
for _, v in data.iterrows():
if v.flight_id not in is_created:
# If the object is not created then create it
is_created.append(v.flight_id)
fh.write(
f"{v.timedelta}> CRE {v.callsign} {v.mdl} "
f"{v.latitude} {v.longitude} {v.track} "
f"{v[altitude]} {v.cas}\n"
)
elif v.timestamp == map_icao24_last_point[v.flight_id]:
# Remove an aircraft when no data are available
if v.flight_id not in is_deleted:
is_deleted.append(v.flight_id)
fh.write(f"{v.timedelta}> DEL {v.callsign}\n")
elif v.flight_id not in is_deleted:
# Otherwise update the object position
fh.write(
f"{v.timedelta}> MOVE {v.callsign} "
f"{v.latitude} {v.longitude} {v[altitude]} "
f"{v.track} {v.cas} {v.vertical_rate}\n"
)
logging.info(f"Scenario file {filename} written") | python | def to_bluesky(
traffic: Traffic,
filename: Union[str, Path],
minimum_time: Optional[timelike] = None,
) -> None:
"""Generates a Bluesky scenario file."""
if minimum_time is not None:
minimum_time = to_datetime(minimum_time)
traffic = traffic.query(f"timestamp >= '{minimum_time}'")
if isinstance(filename, str):
filename = Path(filename)
if not filename.parent.exists():
filename.parent.mkdir(parents=True)
altitude = (
"baro_altitude"
if "baro_altitude" in traffic.data.columns
else "altitude"
)
if "mdl" not in traffic.data.columns:
traffic = aircraft.merge(traffic)
if "cas" not in traffic.data.columns:
traffic = Traffic(
traffic.data.assign(
cas=vtas2cas(traffic.data.ground_speed, traffic.data[altitude])
)
)
with filename.open("w") as fh:
t_delta = traffic.data.timestamp - traffic.start_time
data = (
traffic.assign_id()
.data.groupby("flight_id")
.filter(lambda x: x.shape[0] > 3)
.assign(timedelta=t_delta.apply(fmt_timedelta))
.sort_values(by="timestamp")
)
for column in data.columns:
data[column] = data[column].astype(np.str)
is_created: List[str] = []
is_deleted: List[str] = []
start_time = cast(pd.Timestamp, traffic.start_time).time()
fh.write(f"00:00:00> TIME {start_time}\n")
# Add some bluesky command for the visualisation
# fh.write("00:00:00>trail on\n")
# fh.write("00:00:00>ssd conflicts\n")
# We remove an object when it's its last data point
buff = data.groupby("flight_id").timestamp.max()
dd = pd.DataFrame(
columns=["timestamp"], data=buff.values, index=buff.index.values
)
map_icao24_last_point = {}
for i, v in dd.iterrows():
map_icao24_last_point[i] = v[0]
# Main loop to write lines in the scenario file
for _, v in data.iterrows():
if v.flight_id not in is_created:
# If the object is not created then create it
is_created.append(v.flight_id)
fh.write(
f"{v.timedelta}> CRE {v.callsign} {v.mdl} "
f"{v.latitude} {v.longitude} {v.track} "
f"{v[altitude]} {v.cas}\n"
)
elif v.timestamp == map_icao24_last_point[v.flight_id]:
# Remove an aircraft when no data are available
if v.flight_id not in is_deleted:
is_deleted.append(v.flight_id)
fh.write(f"{v.timedelta}> DEL {v.callsign}\n")
elif v.flight_id not in is_deleted:
# Otherwise update the object position
fh.write(
f"{v.timedelta}> MOVE {v.callsign} "
f"{v.latitude} {v.longitude} {v[altitude]} "
f"{v.track} {v.cas} {v.vertical_rate}\n"
)
logging.info(f"Scenario file {filename} written") | [
"def",
"to_bluesky",
"(",
"traffic",
":",
"Traffic",
",",
"filename",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"minimum_time",
":",
"Optional",
"[",
"timelike",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"if",
"minimum_time",
"is",
"not",
... | Generates a Bluesky scenario file. | [
"Generates",
"a",
"Bluesky",
"scenario",
"file",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/plugins/bluesky.py#L22-L112 | train | 199,802 |
xoolive/traffic | traffic/console/__init__.py | import_submodules | def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
full_name = package.__name__ + "." + name
results[name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results | python | def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
full_name = package.__name__ + "." + name
results[name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results | [
"def",
"import_submodules",
"(",
"package",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"package",
",",
"str",
")",
":",
"package",
"=",
"importlib",
".",
"import_module",
"(",
"package",
")",
"results",
"=",
"{",
"}",
"for",
"loade... | Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType] | [
"Import",
"all",
"submodules",
"of",
"a",
"module",
"recursively",
"including",
"subpackages"
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/console/__init__.py#L19-L34 | train | 199,803 |
xoolive/traffic | traffic/data/so6/so6.py | Flight.interpolate | def interpolate(self, times, proj=PlateCarree()) -> np.ndarray:
"""Interpolates a trajectory in time. """
if proj not in self.interpolator:
self.interpolator[proj] = interp1d(
np.stack(t.to_pydatetime().timestamp() for t in self.timestamp),
proj.transform_points(
PlateCarree(), *np.stack(self.coords).T
).T,
)
return PlateCarree().transform_points(
proj, *self.interpolator[proj](times)
) | python | def interpolate(self, times, proj=PlateCarree()) -> np.ndarray:
"""Interpolates a trajectory in time. """
if proj not in self.interpolator:
self.interpolator[proj] = interp1d(
np.stack(t.to_pydatetime().timestamp() for t in self.timestamp),
proj.transform_points(
PlateCarree(), *np.stack(self.coords).T
).T,
)
return PlateCarree().transform_points(
proj, *self.interpolator[proj](times)
) | [
"def",
"interpolate",
"(",
"self",
",",
"times",
",",
"proj",
"=",
"PlateCarree",
"(",
")",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"proj",
"not",
"in",
"self",
".",
"interpolator",
":",
"self",
".",
"interpolator",
"[",
"proj",
"]",
"=",
"interp... | Interpolates a trajectory in time. | [
"Interpolates",
"a",
"trajectory",
"in",
"time",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/so6/so6.py#L116-L127 | train | 199,804 |
xoolive/traffic | traffic/drawing/cartopy.py | _set_default_extent | def _set_default_extent(self):
"""Helper for a default extent limited to the projection boundaries."""
west, south, east, north = self.projection.boundary.bounds
self.set_extent((west, east, south, north), crs=self.projection) | python | def _set_default_extent(self):
"""Helper for a default extent limited to the projection boundaries."""
west, south, east, north = self.projection.boundary.bounds
self.set_extent((west, east, south, north), crs=self.projection) | [
"def",
"_set_default_extent",
"(",
"self",
")",
":",
"west",
",",
"south",
",",
"east",
",",
"north",
"=",
"self",
".",
"projection",
".",
"boundary",
".",
"bounds",
"self",
".",
"set_extent",
"(",
"(",
"west",
",",
"east",
",",
"south",
",",
"north",
... | Helper for a default extent limited to the projection boundaries. | [
"Helper",
"for",
"a",
"default",
"extent",
"limited",
"to",
"the",
"projection",
"boundaries",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/drawing/cartopy.py#L62-L65 | train | 199,805 |
xoolive/traffic | traffic/data/adsb/opensky_impala.py | Impala._format_dataframe | def _format_dataframe(
df: pd.DataFrame, nautical_units=True
) -> pd.DataFrame:
"""
This function converts types, strips spaces after callsigns and sorts
the DataFrame by timestamp.
For some reason, all data arriving from OpenSky are converted to
units in metric system. Optionally, you may convert the units back to
nautical miles, feet and feet/min.
"""
if "callsign" in df.columns and df.callsign.dtype == object:
df.callsign = df.callsign.str.strip()
if nautical_units:
df.altitude = df.altitude / 0.3048
if "geoaltitude" in df.columns:
df.geoaltitude = df.geoaltitude / 0.3048
if "groundspeed" in df.columns:
df.groundspeed = df.groundspeed / 1852 * 3600
if "vertical_rate" in df.columns:
df.vertical_rate = df.vertical_rate / 0.3048 * 60
df.timestamp = pd.to_datetime(df.timestamp * 1e9).dt.tz_localize("utc")
if "last_position" in df.columns:
df = df.query("last_position == last_position").assign(
last_position=pd.to_datetime(
df.last_position * 1e9
).dt.tz_localize("utc")
)
return df.sort_values("timestamp") | python | def _format_dataframe(
df: pd.DataFrame, nautical_units=True
) -> pd.DataFrame:
"""
This function converts types, strips spaces after callsigns and sorts
the DataFrame by timestamp.
For some reason, all data arriving from OpenSky are converted to
units in metric system. Optionally, you may convert the units back to
nautical miles, feet and feet/min.
"""
if "callsign" in df.columns and df.callsign.dtype == object:
df.callsign = df.callsign.str.strip()
if nautical_units:
df.altitude = df.altitude / 0.3048
if "geoaltitude" in df.columns:
df.geoaltitude = df.geoaltitude / 0.3048
if "groundspeed" in df.columns:
df.groundspeed = df.groundspeed / 1852 * 3600
if "vertical_rate" in df.columns:
df.vertical_rate = df.vertical_rate / 0.3048 * 60
df.timestamp = pd.to_datetime(df.timestamp * 1e9).dt.tz_localize("utc")
if "last_position" in df.columns:
df = df.query("last_position == last_position").assign(
last_position=pd.to_datetime(
df.last_position * 1e9
).dt.tz_localize("utc")
)
return df.sort_values("timestamp") | [
"def",
"_format_dataframe",
"(",
"df",
":",
"pd",
".",
"DataFrame",
",",
"nautical_units",
"=",
"True",
")",
"->",
"pd",
".",
"DataFrame",
":",
"if",
"\"callsign\"",
"in",
"df",
".",
"columns",
"and",
"df",
".",
"callsign",
".",
"dtype",
"==",
"object",
... | This function converts types, strips spaces after callsigns and sorts
the DataFrame by timestamp.
For some reason, all data arriving from OpenSky are converted to
units in metric system. Optionally, you may convert the units back to
nautical miles, feet and feet/min. | [
"This",
"function",
"converts",
"types",
"strips",
"spaces",
"after",
"callsigns",
"and",
"sorts",
"the",
"DataFrame",
"by",
"timestamp",
"."
] | d1a8878098f16759f6b6e0e8d8b8f32e34a680a8 | https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky_impala.py#L125-L159 | train | 199,806 |
pypa/bandersnatch | src/bandersnatch_filter_plugins/filename_name.py | ExcludePlatformFilter.filter | def filter(self, info, releases):
"""
Remove files from `releases` that match any pattern.
"""
# Make a copy of releases keys
# as we may delete packages during iteration
removed = 0
versions = list(releases.keys())
for version in versions:
new_files = []
for file_desc in releases[version]:
if self._check_match(file_desc):
removed += 1
else:
new_files.append(file_desc)
if len(new_files) == 0:
del releases[version]
else:
releases[version] = new_files
logger.debug(f"{self.name}: filenames removed: {removed}") | python | def filter(self, info, releases):
"""
Remove files from `releases` that match any pattern.
"""
# Make a copy of releases keys
# as we may delete packages during iteration
removed = 0
versions = list(releases.keys())
for version in versions:
new_files = []
for file_desc in releases[version]:
if self._check_match(file_desc):
removed += 1
else:
new_files.append(file_desc)
if len(new_files) == 0:
del releases[version]
else:
releases[version] = new_files
logger.debug(f"{self.name}: filenames removed: {removed}") | [
"def",
"filter",
"(",
"self",
",",
"info",
",",
"releases",
")",
":",
"# Make a copy of releases keys",
"# as we may delete packages during iteration",
"removed",
"=",
"0",
"versions",
"=",
"list",
"(",
"releases",
".",
"keys",
"(",
")",
")",
"for",
"version",
"... | Remove files from `releases` that match any pattern. | [
"Remove",
"files",
"from",
"releases",
"that",
"match",
"any",
"pattern",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch_filter_plugins/filename_name.py#L69-L89 | train | 199,807 |
pypa/bandersnatch | src/bandersnatch/filter.py | load_filter_plugins | def load_filter_plugins(entrypoint_group: str) -> Iterable[Filter]:
"""
Load all blacklist plugins that are registered with pkg_resources
Parameters
==========
entrypoint_group: str
The entrypoint group name to load plugins from
Returns
=======
List of Blacklist:
A list of objects derived from the Blacklist class
"""
global loaded_filter_plugins
enabled_plugins: List[str] = []
config = BandersnatchConfig().config
try:
config_blacklist_plugins = config["blacklist"]["plugins"]
split_plugins = config_blacklist_plugins.split("\n")
if "all" in split_plugins:
enabled_plugins = ["all"]
else:
for plugin in split_plugins:
if not plugin:
continue
enabled_plugins.append(plugin)
except KeyError:
pass
# If the plugins for the entrypoint_group have been loaded return them
cached_plugins = loaded_filter_plugins.get(entrypoint_group)
if cached_plugins:
return cached_plugins
plugins = set()
for entry_point in pkg_resources.iter_entry_points(group=entrypoint_group):
plugin_class = entry_point.load()
plugin_instance = plugin_class()
if "all" in enabled_plugins or plugin_instance.name in enabled_plugins:
plugins.add(plugin_instance)
loaded_filter_plugins[entrypoint_group] = list(plugins)
return plugins | python | def load_filter_plugins(entrypoint_group: str) -> Iterable[Filter]:
"""
Load all blacklist plugins that are registered with pkg_resources
Parameters
==========
entrypoint_group: str
The entrypoint group name to load plugins from
Returns
=======
List of Blacklist:
A list of objects derived from the Blacklist class
"""
global loaded_filter_plugins
enabled_plugins: List[str] = []
config = BandersnatchConfig().config
try:
config_blacklist_plugins = config["blacklist"]["plugins"]
split_plugins = config_blacklist_plugins.split("\n")
if "all" in split_plugins:
enabled_plugins = ["all"]
else:
for plugin in split_plugins:
if not plugin:
continue
enabled_plugins.append(plugin)
except KeyError:
pass
# If the plugins for the entrypoint_group have been loaded return them
cached_plugins = loaded_filter_plugins.get(entrypoint_group)
if cached_plugins:
return cached_plugins
plugins = set()
for entry_point in pkg_resources.iter_entry_points(group=entrypoint_group):
plugin_class = entry_point.load()
plugin_instance = plugin_class()
if "all" in enabled_plugins or plugin_instance.name in enabled_plugins:
plugins.add(plugin_instance)
loaded_filter_plugins[entrypoint_group] = list(plugins)
return plugins | [
"def",
"load_filter_plugins",
"(",
"entrypoint_group",
":",
"str",
")",
"->",
"Iterable",
"[",
"Filter",
"]",
":",
"global",
"loaded_filter_plugins",
"enabled_plugins",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"config",
"=",
"BandersnatchConfig",
"(",
")",... | Load all blacklist plugins that are registered with pkg_resources
Parameters
==========
entrypoint_group: str
The entrypoint group name to load plugins from
Returns
=======
List of Blacklist:
A list of objects derived from the Blacklist class | [
"Load",
"all",
"blacklist",
"plugins",
"that",
"are",
"registered",
"with",
"pkg_resources"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/filter.py#L82-L126 | train | 199,808 |
pypa/bandersnatch | src/bandersnatch_filter_plugins/prerelease_name.py | PreReleaseFilter.filter | def filter(self, info, releases):
"""
Remove all release versions that match any of the specificed patterns.
"""
for version in list(releases.keys()):
if any(pattern.match(version) for pattern in self.patterns):
del releases[version] | python | def filter(self, info, releases):
"""
Remove all release versions that match any of the specificed patterns.
"""
for version in list(releases.keys()):
if any(pattern.match(version) for pattern in self.patterns):
del releases[version] | [
"def",
"filter",
"(",
"self",
",",
"info",
",",
"releases",
")",
":",
"for",
"version",
"in",
"list",
"(",
"releases",
".",
"keys",
"(",
")",
")",
":",
"if",
"any",
"(",
"pattern",
".",
"match",
"(",
"version",
")",
"for",
"pattern",
"in",
"self",
... | Remove all release versions that match any of the specificed patterns. | [
"Remove",
"all",
"release",
"versions",
"that",
"match",
"any",
"of",
"the",
"specificed",
"patterns",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch_filter_plugins/prerelease_name.py#L29-L35 | train | 199,809 |
pypa/bandersnatch | src/bandersnatch_filter_plugins/blacklist_name.py | BlacklistRelease._check_match | def _check_match(self, name, version_string) -> bool:
"""
Check if the package name and version matches against a blacklisted
package version specifier.
Parameters
==========
name: str
Package name
version: str
Package version
Returns
=======
bool:
True if it matches, False otherwise.
"""
if not name or not version_string:
return False
try:
version = Version(version_string)
except InvalidVersion:
logger.debug(f"Package {name}=={version_string} has an invalid version")
return False
for requirement in self.blacklist_release_requirements:
if name != requirement.name:
continue
if version in requirement.specifier:
logger.debug(
f"MATCH: Release {name}=={version} matches specifier "
f"{requirement.specifier}"
)
return True
return False | python | def _check_match(self, name, version_string) -> bool:
"""
Check if the package name and version matches against a blacklisted
package version specifier.
Parameters
==========
name: str
Package name
version: str
Package version
Returns
=======
bool:
True if it matches, False otherwise.
"""
if not name or not version_string:
return False
try:
version = Version(version_string)
except InvalidVersion:
logger.debug(f"Package {name}=={version_string} has an invalid version")
return False
for requirement in self.blacklist_release_requirements:
if name != requirement.name:
continue
if version in requirement.specifier:
logger.debug(
f"MATCH: Release {name}=={version} matches specifier "
f"{requirement.specifier}"
)
return True
return False | [
"def",
"_check_match",
"(",
"self",
",",
"name",
",",
"version_string",
")",
"->",
"bool",
":",
"if",
"not",
"name",
"or",
"not",
"version_string",
":",
"return",
"False",
"try",
":",
"version",
"=",
"Version",
"(",
"version_string",
")",
"except",
"Invali... | Check if the package name and version matches against a blacklisted
package version specifier.
Parameters
==========
name: str
Package name
version: str
Package version
Returns
=======
bool:
True if it matches, False otherwise. | [
"Check",
"if",
"the",
"package",
"name",
"and",
"version",
"matches",
"against",
"a",
"blacklisted",
"package",
"version",
"specifier",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch_filter_plugins/blacklist_name.py#L139-L174 | train | 199,810 |
pypa/bandersnatch | src/bandersnatch/utils.py | find | def find(root: Union[Path, str], dirs: bool = True) -> str:
"""A test helper simulating 'find'.
Iterates over directories and filenames, given as relative paths to the
root.
"""
if isinstance(root, str):
root = Path(root)
results: List[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
names = filenames
if dirs:
names += dirnames
for name in names:
results.append(Path(dirpath) / name)
results.sort()
return "\n".join(str(result.relative_to(root)) for result in results) | python | def find(root: Union[Path, str], dirs: bool = True) -> str:
"""A test helper simulating 'find'.
Iterates over directories and filenames, given as relative paths to the
root.
"""
if isinstance(root, str):
root = Path(root)
results: List[Path] = []
for dirpath, dirnames, filenames in os.walk(root):
names = filenames
if dirs:
names += dirnames
for name in names:
results.append(Path(dirpath) / name)
results.sort()
return "\n".join(str(result.relative_to(root)) for result in results) | [
"def",
"find",
"(",
"root",
":",
"Union",
"[",
"Path",
",",
"str",
"]",
",",
"dirs",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"root",
",",
"str",
")",
":",
"root",
"=",
"Path",
"(",
"root",
")",
"results",
":",
... | A test helper simulating 'find'.
Iterates over directories and filenames, given as relative paths to the
root. | [
"A",
"test",
"helper",
"simulating",
"find",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/utils.py#L49-L67 | train | 199,811 |
pypa/bandersnatch | src/bandersnatch/utils.py | rewrite | def rewrite(
filepath: Union[str, Path], mode: str = "w", **kw: Any
) -> Generator[IO, None, None]:
"""Rewrite an existing file atomically to avoid programs running in
parallel to have race conditions while reading."""
if isinstance(filepath, str):
base_dir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
else:
base_dir = str(filepath.parent)
filename = filepath.name
# Change naming format to be more friendly with distributed POSIX
# filesystems like GlusterFS that hash based on filename
# GlusterFS ignore '.' at the start of filenames and this avoid rehashing
with tempfile.NamedTemporaryFile(
mode=mode, prefix=f".{filename}.", delete=False, dir=base_dir, **kw
) as f:
filepath_tmp = f.name
yield f
if not os.path.exists(filepath_tmp):
# Allow our clients to remove the file in case it doesn't want it to be
# put in place actually but also doesn't want to error out.
return
os.chmod(filepath_tmp, 0o100644)
os.rename(filepath_tmp, filepath) | python | def rewrite(
filepath: Union[str, Path], mode: str = "w", **kw: Any
) -> Generator[IO, None, None]:
"""Rewrite an existing file atomically to avoid programs running in
parallel to have race conditions while reading."""
if isinstance(filepath, str):
base_dir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
else:
base_dir = str(filepath.parent)
filename = filepath.name
# Change naming format to be more friendly with distributed POSIX
# filesystems like GlusterFS that hash based on filename
# GlusterFS ignore '.' at the start of filenames and this avoid rehashing
with tempfile.NamedTemporaryFile(
mode=mode, prefix=f".{filename}.", delete=False, dir=base_dir, **kw
) as f:
filepath_tmp = f.name
yield f
if not os.path.exists(filepath_tmp):
# Allow our clients to remove the file in case it doesn't want it to be
# put in place actually but also doesn't want to error out.
return
os.chmod(filepath_tmp, 0o100644)
os.rename(filepath_tmp, filepath) | [
"def",
"rewrite",
"(",
"filepath",
":",
"Union",
"[",
"str",
",",
"Path",
"]",
",",
"mode",
":",
"str",
"=",
"\"w\"",
",",
"*",
"*",
"kw",
":",
"Any",
")",
"->",
"Generator",
"[",
"IO",
",",
"None",
",",
"None",
"]",
":",
"if",
"isinstance",
"(... | Rewrite an existing file atomically to avoid programs running in
parallel to have race conditions while reading. | [
"Rewrite",
"an",
"existing",
"file",
"atomically",
"to",
"avoid",
"programs",
"running",
"in",
"parallel",
"to",
"have",
"race",
"conditions",
"while",
"reading",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/utils.py#L71-L97 | train | 199,812 |
pypa/bandersnatch | src/bandersnatch/utils.py | unlink_parent_dir | def unlink_parent_dir(path: Path) -> None:
""" Remove a file and if the dir is empty remove it """
logger.info(f"unlink {str(path)}")
path.unlink()
parent_path = path.parent
try:
parent_path.rmdir()
logger.info(f"rmdir {str(parent_path)}")
except OSError as oe:
logger.debug(f"Did not remove {str(parent_path)}: {str(oe)}") | python | def unlink_parent_dir(path: Path) -> None:
""" Remove a file and if the dir is empty remove it """
logger.info(f"unlink {str(path)}")
path.unlink()
parent_path = path.parent
try:
parent_path.rmdir()
logger.info(f"rmdir {str(parent_path)}")
except OSError as oe:
logger.debug(f"Did not remove {str(parent_path)}: {str(oe)}") | [
"def",
"unlink_parent_dir",
"(",
"path",
":",
"Path",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"f\"unlink {str(path)}\"",
")",
"path",
".",
"unlink",
"(",
")",
"parent_path",
"=",
"path",
".",
"parent",
"try",
":",
"parent_path",
".",
"rmdir",
... | Remove a file and if the dir is empty remove it | [
"Remove",
"a",
"file",
"and",
"if",
"the",
"dir",
"is",
"empty",
"remove",
"it"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/utils.py#L107-L117 | train | 199,813 |
pypa/bandersnatch | src/bandersnatch/utils.py | update_safe | def update_safe(filename: str, **kw: Any) -> Generator[IO, None, None]:
"""Rewrite a file atomically.
Clients are allowed to delete the tmpfile to signal that they don't
want to have it updated.
"""
with tempfile.NamedTemporaryFile(
dir=os.path.dirname(filename),
delete=False,
prefix=f"{os.path.basename(filename)}.",
**kw,
) as tf:
if os.path.exists(filename):
os.chmod(tf.name, os.stat(filename).st_mode & 0o7777)
tf.has_changed = False # type: ignore
yield tf
if not os.path.exists(tf.name):
return
filename_tmp = tf.name
if os.path.exists(filename) and filecmp.cmp(filename, filename_tmp, shallow=False):
os.unlink(filename_tmp)
else:
os.rename(filename_tmp, filename)
tf.has_changed = True | python | def update_safe(filename: str, **kw: Any) -> Generator[IO, None, None]:
"""Rewrite a file atomically.
Clients are allowed to delete the tmpfile to signal that they don't
want to have it updated.
"""
with tempfile.NamedTemporaryFile(
dir=os.path.dirname(filename),
delete=False,
prefix=f"{os.path.basename(filename)}.",
**kw,
) as tf:
if os.path.exists(filename):
os.chmod(tf.name, os.stat(filename).st_mode & 0o7777)
tf.has_changed = False # type: ignore
yield tf
if not os.path.exists(tf.name):
return
filename_tmp = tf.name
if os.path.exists(filename) and filecmp.cmp(filename, filename_tmp, shallow=False):
os.unlink(filename_tmp)
else:
os.rename(filename_tmp, filename)
tf.has_changed = True | [
"def",
"update_safe",
"(",
"filename",
":",
"str",
",",
"*",
"*",
"kw",
":",
"Any",
")",
"->",
"Generator",
"[",
"IO",
",",
"None",
",",
"None",
"]",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"os",
".",
"path",
".",
"dirn... | Rewrite a file atomically.
Clients are allowed to delete the tmpfile to signal that they don't
want to have it updated. | [
"Rewrite",
"a",
"file",
"atomically",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/utils.py#L121-L145 | train | 199,814 |
pypa/bandersnatch | src/bandersnatch/package.py | Package.save_json_metadata | def save_json_metadata(self, package_info: Dict) -> bool:
"""
Take the JSON metadata we just fetched and save to disk
"""
try:
with utils.rewrite(self.json_file) as jf:
dump(package_info, jf, indent=4, sort_keys=True)
except Exception as e:
logger.error(
"Unable to write json to {}: {}".format(self.json_file, str(e))
)
return False
symlink_dir = self.json_pypi_symlink.parent
if not symlink_dir.exists():
symlink_dir.mkdir()
try:
# If symlink already exists throw a FileExistsError
self.json_pypi_symlink.symlink_to(self.json_file)
except FileExistsError:
pass
return True | python | def save_json_metadata(self, package_info: Dict) -> bool:
"""
Take the JSON metadata we just fetched and save to disk
"""
try:
with utils.rewrite(self.json_file) as jf:
dump(package_info, jf, indent=4, sort_keys=True)
except Exception as e:
logger.error(
"Unable to write json to {}: {}".format(self.json_file, str(e))
)
return False
symlink_dir = self.json_pypi_symlink.parent
if not symlink_dir.exists():
symlink_dir.mkdir()
try:
# If symlink already exists throw a FileExistsError
self.json_pypi_symlink.symlink_to(self.json_file)
except FileExistsError:
pass
return True | [
"def",
"save_json_metadata",
"(",
"self",
",",
"package_info",
":",
"Dict",
")",
"->",
"bool",
":",
"try",
":",
"with",
"utils",
".",
"rewrite",
"(",
"self",
".",
"json_file",
")",
"as",
"jf",
":",
"dump",
"(",
"package_info",
",",
"jf",
",",
"indent",... | Take the JSON metadata we just fetched and save to disk | [
"Take",
"the",
"JSON",
"metadata",
"we",
"just",
"fetched",
"and",
"save",
"to",
"disk"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/package.py#L75-L98 | train | 199,815 |
pypa/bandersnatch | src/bandersnatch/package.py | Package._filter_releases | def _filter_releases(self):
"""
Run the release filtering plugins
"""
global display_filter_log
filter_plugins = filter_release_plugins()
if not filter_plugins:
if display_filter_log:
logger.info("No release filters are enabled. Skipping filtering")
display_filter_log = False
else:
for plugin in filter_plugins:
plugin.filter(self.info, self.releases) | python | def _filter_releases(self):
"""
Run the release filtering plugins
"""
global display_filter_log
filter_plugins = filter_release_plugins()
if not filter_plugins:
if display_filter_log:
logger.info("No release filters are enabled. Skipping filtering")
display_filter_log = False
else:
for plugin in filter_plugins:
plugin.filter(self.info, self.releases) | [
"def",
"_filter_releases",
"(",
"self",
")",
":",
"global",
"display_filter_log",
"filter_plugins",
"=",
"filter_release_plugins",
"(",
")",
"if",
"not",
"filter_plugins",
":",
"if",
"display_filter_log",
":",
"logger",
".",
"info",
"(",
"\"No release filters are enab... | Run the release filtering plugins | [
"Run",
"the",
"release",
"filtering",
"plugins"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/package.py#L158-L170 | train | 199,816 |
pypa/bandersnatch | src/bandersnatch/package.py | Package.sync_release_files | def sync_release_files(self):
""" Purge + download files returning files removed + added """
release_files = []
for release in self.releases.values():
release_files.extend(release)
downloaded_files = set()
deferred_exception = None
for release_file in release_files:
try:
downloaded_file = self.download_file(
release_file["url"], release_file["digests"]["sha256"]
)
if downloaded_file:
downloaded_files.add(
str(downloaded_file.relative_to(self.mirror.homedir))
)
except Exception as e:
logger.exception(
f"Continuing to next file after error downloading: "
f"{release_file['url']}"
)
if not deferred_exception: # keep first exception
deferred_exception = e
if deferred_exception:
raise deferred_exception # raise the exception after trying all files
self.mirror.altered_packages[self.name] = downloaded_files | python | def sync_release_files(self):
""" Purge + download files returning files removed + added """
release_files = []
for release in self.releases.values():
release_files.extend(release)
downloaded_files = set()
deferred_exception = None
for release_file in release_files:
try:
downloaded_file = self.download_file(
release_file["url"], release_file["digests"]["sha256"]
)
if downloaded_file:
downloaded_files.add(
str(downloaded_file.relative_to(self.mirror.homedir))
)
except Exception as e:
logger.exception(
f"Continuing to next file after error downloading: "
f"{release_file['url']}"
)
if not deferred_exception: # keep first exception
deferred_exception = e
if deferred_exception:
raise deferred_exception # raise the exception after trying all files
self.mirror.altered_packages[self.name] = downloaded_files | [
"def",
"sync_release_files",
"(",
"self",
")",
":",
"release_files",
"=",
"[",
"]",
"for",
"release",
"in",
"self",
".",
"releases",
".",
"values",
"(",
")",
":",
"release_files",
".",
"extend",
"(",
"release",
")",
"downloaded_files",
"=",
"set",
"(",
"... | Purge + download files returning files removed + added | [
"Purge",
"+",
"download",
"files",
"returning",
"files",
"removed",
"+",
"added"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/package.py#L174-L202 | train | 199,817 |
pypa/bandersnatch | src/bandersnatch/mirror.py | Mirror._cleanup | def _cleanup(self):
"""Does a couple of cleanup tasks to ensure consistent data for later
processing."""
if self.todolist.exists():
try:
saved_todo = iter(open(self.todolist, encoding="utf-8"))
int(next(saved_todo).strip())
for line in saved_todo:
_, serial = line.strip().split()
int(serial)
except (StopIteration, ValueError):
# The todo list was inconsistent. This may happen if we get
# killed e.g. by the timeout wrapper. Just remove it - we'll
# just have to do whatever happened since the last successful
# sync.
logger.info("Removing inconsistent todo list.")
self.todolist.unlink() | python | def _cleanup(self):
"""Does a couple of cleanup tasks to ensure consistent data for later
processing."""
if self.todolist.exists():
try:
saved_todo = iter(open(self.todolist, encoding="utf-8"))
int(next(saved_todo).strip())
for line in saved_todo:
_, serial = line.strip().split()
int(serial)
except (StopIteration, ValueError):
# The todo list was inconsistent. This may happen if we get
# killed e.g. by the timeout wrapper. Just remove it - we'll
# just have to do whatever happened since the last successful
# sync.
logger.info("Removing inconsistent todo list.")
self.todolist.unlink() | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"todolist",
".",
"exists",
"(",
")",
":",
"try",
":",
"saved_todo",
"=",
"iter",
"(",
"open",
"(",
"self",
".",
"todolist",
",",
"encoding",
"=",
"\"utf-8\"",
")",
")",
"int",
"(",
"next"... | Does a couple of cleanup tasks to ensure consistent data for later
processing. | [
"Does",
"a",
"couple",
"of",
"cleanup",
"tasks",
"to",
"ensure",
"consistent",
"data",
"for",
"later",
"processing",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/mirror.py#L117-L133 | train | 199,818 |
pypa/bandersnatch | src/bandersnatch/mirror.py | Mirror._filter_packages | def _filter_packages(self):
"""
Run the package filtering plugins and remove any packages from the
packages_to_sync that match any filters.
- Logging of action will be done within the check_match methods
"""
global LOG_PLUGINS
filter_plugins = filter_project_plugins()
if not filter_plugins:
if LOG_PLUGINS:
logger.info("No project filters are enabled. Skipping filtering")
LOG_PLUGINS = False
return
# Make a copy of self.packages_to_sync keys
# as we may delete packages during iteration
packages = list(self.packages_to_sync.keys())
for package_name in packages:
for plugin in filter_plugins:
if plugin.check_match(name=package_name):
if package_name not in self.packages_to_sync:
logger.debug(
f"{package_name} not found in packages to sync - "
+ f"{plugin.name} has no effect here ..."
)
else:
del self.packages_to_sync[package_name] | python | def _filter_packages(self):
"""
Run the package filtering plugins and remove any packages from the
packages_to_sync that match any filters.
- Logging of action will be done within the check_match methods
"""
global LOG_PLUGINS
filter_plugins = filter_project_plugins()
if not filter_plugins:
if LOG_PLUGINS:
logger.info("No project filters are enabled. Skipping filtering")
LOG_PLUGINS = False
return
# Make a copy of self.packages_to_sync keys
# as we may delete packages during iteration
packages = list(self.packages_to_sync.keys())
for package_name in packages:
for plugin in filter_plugins:
if plugin.check_match(name=package_name):
if package_name not in self.packages_to_sync:
logger.debug(
f"{package_name} not found in packages to sync - "
+ f"{plugin.name} has no effect here ..."
)
else:
del self.packages_to_sync[package_name] | [
"def",
"_filter_packages",
"(",
"self",
")",
":",
"global",
"LOG_PLUGINS",
"filter_plugins",
"=",
"filter_project_plugins",
"(",
")",
"if",
"not",
"filter_plugins",
":",
"if",
"LOG_PLUGINS",
":",
"logger",
".",
"info",
"(",
"\"No project filters are enabled. Skipping ... | Run the package filtering plugins and remove any packages from the
packages_to_sync that match any filters.
- Logging of action will be done within the check_match methods | [
"Run",
"the",
"package",
"filtering",
"plugins",
"and",
"remove",
"any",
"packages",
"from",
"the",
"packages_to_sync",
"that",
"match",
"any",
"filters",
".",
"-",
"Logging",
"of",
"action",
"will",
"be",
"done",
"within",
"the",
"check_match",
"methods"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/mirror.py#L135-L162 | train | 199,819 |
pypa/bandersnatch | src/bandersnatch/mirror.py | Mirror.determine_packages_to_sync | def determine_packages_to_sync(self):
"""
Update the self.packages_to_sync to contain packages that need to be
synced.
"""
# In case we don't find any changes we will stay on the currently
# synced serial.
self.target_serial = self.synced_serial
self.packages_to_sync = {}
logger.info(f"Current mirror serial: {self.synced_serial}")
if self.todolist.exists():
# We started a sync previously and left a todo list as well as the
# targetted serial. We'll try to keep going through the todo list
# and then mark the targetted serial as done.
logger.info("Resuming interrupted sync from local todo list.")
saved_todo = iter(open(self.todolist, encoding="utf-8"))
self.target_serial = int(next(saved_todo).strip())
for line in saved_todo:
package, serial = line.strip().split()
self.packages_to_sync[package] = int(serial)
elif not self.synced_serial:
logger.info("Syncing all packages.")
# First get the current serial, then start to sync. This makes us
# more defensive in case something changes on the server between
# those two calls.
self.packages_to_sync.update(self.master.all_packages())
self.target_serial = max(
[self.synced_serial] + list(self.packages_to_sync.values())
)
else:
logger.info("Syncing based on changelog.")
self.packages_to_sync.update(
self.master.changed_packages(self.synced_serial)
)
self.target_serial = max(
[self.synced_serial] + list(self.packages_to_sync.values())
)
# We can avoid downloading the main index page if we don't have
# anything todo at all during a changelog-based sync.
self.need_index_sync = bool(self.packages_to_sync)
self._filter_packages()
logger.info(f"Trying to reach serial: {self.target_serial}")
pkg_count = len(self.packages_to_sync)
logger.info(f"{pkg_count} packages to sync.") | python | def determine_packages_to_sync(self):
"""
Update the self.packages_to_sync to contain packages that need to be
synced.
"""
# In case we don't find any changes we will stay on the currently
# synced serial.
self.target_serial = self.synced_serial
self.packages_to_sync = {}
logger.info(f"Current mirror serial: {self.synced_serial}")
if self.todolist.exists():
# We started a sync previously and left a todo list as well as the
# targetted serial. We'll try to keep going through the todo list
# and then mark the targetted serial as done.
logger.info("Resuming interrupted sync from local todo list.")
saved_todo = iter(open(self.todolist, encoding="utf-8"))
self.target_serial = int(next(saved_todo).strip())
for line in saved_todo:
package, serial = line.strip().split()
self.packages_to_sync[package] = int(serial)
elif not self.synced_serial:
logger.info("Syncing all packages.")
# First get the current serial, then start to sync. This makes us
# more defensive in case something changes on the server between
# those two calls.
self.packages_to_sync.update(self.master.all_packages())
self.target_serial = max(
[self.synced_serial] + list(self.packages_to_sync.values())
)
else:
logger.info("Syncing based on changelog.")
self.packages_to_sync.update(
self.master.changed_packages(self.synced_serial)
)
self.target_serial = max(
[self.synced_serial] + list(self.packages_to_sync.values())
)
# We can avoid downloading the main index page if we don't have
# anything todo at all during a changelog-based sync.
self.need_index_sync = bool(self.packages_to_sync)
self._filter_packages()
logger.info(f"Trying to reach serial: {self.target_serial}")
pkg_count = len(self.packages_to_sync)
logger.info(f"{pkg_count} packages to sync.") | [
"def",
"determine_packages_to_sync",
"(",
"self",
")",
":",
"# In case we don't find any changes we will stay on the currently",
"# synced serial.",
"self",
".",
"target_serial",
"=",
"self",
".",
"synced_serial",
"self",
".",
"packages_to_sync",
"=",
"{",
"}",
"logger",
... | Update the self.packages_to_sync to contain packages that need to be
synced. | [
"Update",
"the",
"self",
".",
"packages_to_sync",
"to",
"contain",
"packages",
"that",
"need",
"to",
"be",
"synced",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/mirror.py#L164-L209 | train | 199,820 |
pypa/bandersnatch | src/bandersnatch/mirror.py | Mirror.get_simple_dirs | def get_simple_dirs(self, simple_dir: Path) -> List[Path]:
"""Return a list of simple index directories that should be searched
for package indexes when compiling the main index page."""
if self.hash_index:
# We are using index page directory hashing, so the directory
# format is /simple/f/foo/. We want to return a list of dirs
# like "simple/f".
subdirs = [simple_dir / x for x in simple_dir.iterdir() if x.is_dir()]
else:
# This is the traditional layout of /simple/foo/. We should
# return a single directory, "simple".
subdirs = [simple_dir]
return subdirs | python | def get_simple_dirs(self, simple_dir: Path) -> List[Path]:
"""Return a list of simple index directories that should be searched
for package indexes when compiling the main index page."""
if self.hash_index:
# We are using index page directory hashing, so the directory
# format is /simple/f/foo/. We want to return a list of dirs
# like "simple/f".
subdirs = [simple_dir / x for x in simple_dir.iterdir() if x.is_dir()]
else:
# This is the traditional layout of /simple/foo/. We should
# return a single directory, "simple".
subdirs = [simple_dir]
return subdirs | [
"def",
"get_simple_dirs",
"(",
"self",
",",
"simple_dir",
":",
"Path",
")",
"->",
"List",
"[",
"Path",
"]",
":",
"if",
"self",
".",
"hash_index",
":",
"# We are using index page directory hashing, so the directory",
"# format is /simple/f/foo/. We want to return a list of ... | Return a list of simple index directories that should be searched
for package indexes when compiling the main index page. | [
"Return",
"a",
"list",
"of",
"simple",
"index",
"directories",
"that",
"should",
"be",
"searched",
"for",
"package",
"indexes",
"when",
"compiling",
"the",
"main",
"index",
"page",
"."
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/mirror.py#L252-L264 | train | 199,821 |
pypa/bandersnatch | src/bandersnatch/mirror.py | Mirror.find_package_indexes_in_dir | def find_package_indexes_in_dir(self, simple_dir):
"""Given a directory that contains simple packages indexes, return
a sorted list of normalized package names. This presumes every
directory within is a simple package index directory."""
packages = sorted(
{
# Filter out all of the "non" normalized names here
canonicalize_name(x)
for x in os.listdir(simple_dir)
}
)
# Package indexes must be in directories, so ignore anything else.
packages = [x for x in packages if os.path.isdir(os.path.join(simple_dir, x))]
return packages | python | def find_package_indexes_in_dir(self, simple_dir):
"""Given a directory that contains simple packages indexes, return
a sorted list of normalized package names. This presumes every
directory within is a simple package index directory."""
packages = sorted(
{
# Filter out all of the "non" normalized names here
canonicalize_name(x)
for x in os.listdir(simple_dir)
}
)
# Package indexes must be in directories, so ignore anything else.
packages = [x for x in packages if os.path.isdir(os.path.join(simple_dir, x))]
return packages | [
"def",
"find_package_indexes_in_dir",
"(",
"self",
",",
"simple_dir",
")",
":",
"packages",
"=",
"sorted",
"(",
"{",
"# Filter out all of the \"non\" normalized names here",
"canonicalize_name",
"(",
"x",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"simple_dir... | Given a directory that contains simple packages indexes, return
a sorted list of normalized package names. This presumes every
directory within is a simple package index directory. | [
"Given",
"a",
"directory",
"that",
"contains",
"simple",
"packages",
"indexes",
"return",
"a",
"sorted",
"list",
"of",
"normalized",
"package",
"names",
".",
"This",
"presumes",
"every",
"directory",
"within",
"is",
"a",
"simple",
"package",
"index",
"directory"... | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/mirror.py#L266-L279 | train | 199,822 |
pypa/bandersnatch | src/bandersnatch/configuration.py | BandersnatchConfig.load_configuration | def load_configuration(self) -> None:
"""
Read the configuration from a configuration file
"""
config_file = self.default_config_file
if self.config_file:
config_file = self.config_file
self.config = ConfigParser()
self.config.read(config_file) | python | def load_configuration(self) -> None:
"""
Read the configuration from a configuration file
"""
config_file = self.default_config_file
if self.config_file:
config_file = self.config_file
self.config = ConfigParser()
self.config.read(config_file) | [
"def",
"load_configuration",
"(",
"self",
")",
"->",
"None",
":",
"config_file",
"=",
"self",
".",
"default_config_file",
"if",
"self",
".",
"config_file",
":",
"config_file",
"=",
"self",
".",
"config_file",
"self",
".",
"config",
"=",
"ConfigParser",
"(",
... | Read the configuration from a configuration file | [
"Read",
"the",
"configuration",
"from",
"a",
"configuration",
"file"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/configuration.py#L38-L46 | train | 199,823 |
pypa/bandersnatch | src/bandersnatch/verify.py | metadata_verify | async def metadata_verify(config, args) -> int:
""" Crawl all saved JSON metadata or online to check we have all packages
if delete - generate a diff of unowned files """
all_package_files = [] # type: List[Path]
loop = asyncio.get_event_loop()
mirror_base = config.get("mirror", "directory")
json_base = Path(mirror_base) / "web" / "json"
workers = args.workers or config.getint("mirror", "workers")
executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)
logger.info(f"Starting verify for {mirror_base} with {workers} workers")
try:
json_files = await loop.run_in_executor(executor, os.listdir, json_base)
except FileExistsError as fee:
logger.error(f"Metadata base dir {json_base} does not exist: {fee}")
return 2
if not json_files:
logger.error("No JSON metadata files found. Can not verify")
return 3
logger.debug(f"Found {len(json_files)} objects in {json_base}")
logger.debug(f"Using a {workers} thread ThreadPoolExecutor")
await async_verify(
config, all_package_files, mirror_base, json_files, args, executor
)
if not args.delete:
return 0
return await delete_files(mirror_base, executor, all_package_files, args.dry_run) | python | async def metadata_verify(config, args) -> int:
""" Crawl all saved JSON metadata or online to check we have all packages
if delete - generate a diff of unowned files """
all_package_files = [] # type: List[Path]
loop = asyncio.get_event_loop()
mirror_base = config.get("mirror", "directory")
json_base = Path(mirror_base) / "web" / "json"
workers = args.workers or config.getint("mirror", "workers")
executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers)
logger.info(f"Starting verify for {mirror_base} with {workers} workers")
try:
json_files = await loop.run_in_executor(executor, os.listdir, json_base)
except FileExistsError as fee:
logger.error(f"Metadata base dir {json_base} does not exist: {fee}")
return 2
if not json_files:
logger.error("No JSON metadata files found. Can not verify")
return 3
logger.debug(f"Found {len(json_files)} objects in {json_base}")
logger.debug(f"Using a {workers} thread ThreadPoolExecutor")
await async_verify(
config, all_package_files, mirror_base, json_files, args, executor
)
if not args.delete:
return 0
return await delete_files(mirror_base, executor, all_package_files, args.dry_run) | [
"async",
"def",
"metadata_verify",
"(",
"config",
",",
"args",
")",
"->",
"int",
":",
"all_package_files",
"=",
"[",
"]",
"# type: List[Path]",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"mirror_base",
"=",
"config",
".",
"get",
"(",
"\"mirror\... | Crawl all saved JSON metadata or online to check we have all packages
if delete - generate a diff of unowned files | [
"Crawl",
"all",
"saved",
"JSON",
"metadata",
"or",
"online",
"to",
"check",
"we",
"have",
"all",
"packages",
"if",
"delete",
"-",
"generate",
"a",
"diff",
"of",
"unowned",
"files"
] | 8b702c3bc128c5a1cbdd18890adede2f7f17fad4 | https://github.com/pypa/bandersnatch/blob/8b702c3bc128c5a1cbdd18890adede2f7f17fad4/src/bandersnatch/verify.py#L197-L226 | train | 199,824 |
mpdavis/python-jose | jose/backends/pycrypto_backend.py | _der_to_pem | def _der_to_pem(der_key, marker):
"""
Perform a simple DER to PEM conversion.
"""
pem_key_chunks = [('-----BEGIN %s-----' % marker).encode('utf-8')]
# Limit base64 output lines to 64 characters by limiting input lines to 48 characters.
for chunk_start in range(0, len(der_key), 48):
pem_key_chunks.append(b64encode(der_key[chunk_start:chunk_start + 48]))
pem_key_chunks.append(('-----END %s-----' % marker).encode('utf-8'))
return b'\n'.join(pem_key_chunks) | python | def _der_to_pem(der_key, marker):
"""
Perform a simple DER to PEM conversion.
"""
pem_key_chunks = [('-----BEGIN %s-----' % marker).encode('utf-8')]
# Limit base64 output lines to 64 characters by limiting input lines to 48 characters.
for chunk_start in range(0, len(der_key), 48):
pem_key_chunks.append(b64encode(der_key[chunk_start:chunk_start + 48]))
pem_key_chunks.append(('-----END %s-----' % marker).encode('utf-8'))
return b'\n'.join(pem_key_chunks) | [
"def",
"_der_to_pem",
"(",
"der_key",
",",
"marker",
")",
":",
"pem_key_chunks",
"=",
"[",
"(",
"'-----BEGIN %s-----'",
"%",
"marker",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"]",
"# Limit base64 output lines to 64 characters by limiting input lines to 48 characters.",
... | Perform a simple DER to PEM conversion. | [
"Perform",
"a",
"simple",
"DER",
"to",
"PEM",
"conversion",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/pycrypto_backend.py#L30-L42 | train | 199,825 |
mpdavis/python-jose | jose/backends/cryptography_backend.py | CryptographyECKey._der_to_raw | def _der_to_raw(self, der_signature):
"""Convert signature from DER encoding to RAW encoding."""
r, s = decode_dss_signature(der_signature)
component_length = self._sig_component_length()
return int_to_bytes(r, component_length) + int_to_bytes(s, component_length) | python | def _der_to_raw(self, der_signature):
"""Convert signature from DER encoding to RAW encoding."""
r, s = decode_dss_signature(der_signature)
component_length = self._sig_component_length()
return int_to_bytes(r, component_length) + int_to_bytes(s, component_length) | [
"def",
"_der_to_raw",
"(",
"self",
",",
"der_signature",
")",
":",
"r",
",",
"s",
"=",
"decode_dss_signature",
"(",
"der_signature",
")",
"component_length",
"=",
"self",
".",
"_sig_component_length",
"(",
")",
"return",
"int_to_bytes",
"(",
"r",
",",
"compone... | Convert signature from DER encoding to RAW encoding. | [
"Convert",
"signature",
"from",
"DER",
"encoding",
"to",
"RAW",
"encoding",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/cryptography_backend.py#L109-L113 | train | 199,826 |
mpdavis/python-jose | jose/backends/cryptography_backend.py | CryptographyECKey._raw_to_der | def _raw_to_der(self, raw_signature):
"""Convert signature from RAW encoding to DER encoding."""
component_length = self._sig_component_length()
if len(raw_signature) != int(2 * component_length):
raise ValueError("Invalid signature")
r_bytes = raw_signature[:component_length]
s_bytes = raw_signature[component_length:]
r = int_from_bytes(r_bytes, "big")
s = int_from_bytes(s_bytes, "big")
return encode_dss_signature(r, s) | python | def _raw_to_der(self, raw_signature):
"""Convert signature from RAW encoding to DER encoding."""
component_length = self._sig_component_length()
if len(raw_signature) != int(2 * component_length):
raise ValueError("Invalid signature")
r_bytes = raw_signature[:component_length]
s_bytes = raw_signature[component_length:]
r = int_from_bytes(r_bytes, "big")
s = int_from_bytes(s_bytes, "big")
return encode_dss_signature(r, s) | [
"def",
"_raw_to_der",
"(",
"self",
",",
"raw_signature",
")",
":",
"component_length",
"=",
"self",
".",
"_sig_component_length",
"(",
")",
"if",
"len",
"(",
"raw_signature",
")",
"!=",
"int",
"(",
"2",
"*",
"component_length",
")",
":",
"raise",
"ValueError... | Convert signature from RAW encoding to DER encoding. | [
"Convert",
"signature",
"from",
"RAW",
"encoding",
"to",
"DER",
"encoding",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/cryptography_backend.py#L115-L125 | train | 199,827 |
mpdavis/python-jose | jose/jwt.py | encode | def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm) | python | def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=None):
"""Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
for time_claim in ['exp', 'iat', 'nbf']:
# Convert datetime to a intDate value in known time-format claims
if isinstance(claims.get(time_claim), datetime):
claims[time_claim] = timegm(claims[time_claim].utctimetuple())
if access_token:
claims['at_hash'] = calculate_at_hash(access_token,
ALGORITHMS.HASHES[algorithm])
return jws.sign(claims, key, headers=headers, algorithm=algorithm) | [
"def",
"encode",
"(",
"claims",
",",
"key",
",",
"algorithm",
"=",
"ALGORITHMS",
".",
"HS256",
",",
"headers",
"=",
"None",
",",
"access_token",
"=",
"None",
")",
":",
"for",
"time_claim",
"in",
"[",
"'exp'",
",",
"'iat'",
",",
"'nbf'",
"]",
":",
"# ... | Encodes a claims set and returns a JWT string.
JWTs are JWS signed objects with a few reserved claims.
Args:
claims (dict): A claims set to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
access_token (str, optional): If present, the 'at_hash' claim will
be calculated and added to the claims present in the 'claims'
parameter.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWTError: If there is an error encoding the claims.
Examples:
>>> jwt.encode({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' | [
"Encodes",
"a",
"claims",
"set",
"and",
"returns",
"a",
"JWT",
"string",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L23-L64 | train | 199,828 |
mpdavis/python-jose | jose/jwt.py | decode | def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims | python | def decode(token, key, algorithms=None, options=None, audience=None,
issuer=None, subject=None, access_token=None):
"""Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256')
"""
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
if options:
defaults.update(options)
verify_signature = defaults.get('verify_signature', True)
try:
payload = jws.verify(token, key, algorithms, verify=verify_signature)
except JWSError as e:
raise JWTError(e)
# Needed for at_hash verification
algorithm = jws.get_unverified_header(token)['alg']
try:
claims = json.loads(payload.decode('utf-8'))
except ValueError as e:
raise JWTError('Invalid payload string: %s' % e)
if not isinstance(claims, Mapping):
raise JWTError('Invalid payload string: must be a json object')
_validate_claims(claims, audience=audience, issuer=issuer,
subject=subject, algorithm=algorithm,
access_token=access_token,
options=defaults)
return claims | [
"def",
"decode",
"(",
"token",
",",
"key",
",",
"algorithms",
"=",
"None",
",",
"options",
"=",
"None",
",",
"audience",
"=",
"None",
",",
"issuer",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"access_token",
"=",
"None",
")",
":",
"defaults",
"="... | Verifies a JWT string's signature and validates reserved claims.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
audience (str): The intended audience of the token. If the "aud" claim is
included in the claim set, then the audience must be included and must equal
the provided claim.
issuer (str or iterable): Acceptable value(s) for the issuer of the token.
If the "iss" claim is included in the claim set, then the issuer must be
given and the claim in the token must be among the acceptable values.
subject (str): The subject of the token. If the "sub" claim is
included in the claim set, then the subject must be included and must equal
the provided claim.
access_token (str): An access token string. If the "at_hash" claim is included in the
claim set, then the access_token must be included, and it must match
the "at_hash" claim.
options (dict): A dictionary of options for skipping validation steps.
defaults = {
'verify_signature': True,
'verify_aud': True,
'verify_iat': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iss': True,
'verify_sub': True,
'verify_jti': True,
'verify_at_hash': True,
'require_aud': False,
'require_iat': False,
'require_exp': False,
'require_nbf': False,
'require_iss': False,
'require_sub': False,
'require_jti': False,
'require_at_hash': False,
'leeway': 0,
}
Returns:
dict: The dict representation of the claims set, assuming the signature is valid
and all requested data validation passes.
Raises:
JWTError: If the signature is invalid in any way.
ExpiredSignatureError: If the signature has expired.
JWTClaimsError: If any claim is invalid in any way.
Examples:
>>> payload = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jwt.decode(payload, 'secret', algorithms='HS256') | [
"Verifies",
"a",
"JWT",
"string",
"s",
"signature",
"and",
"validates",
"reserved",
"claims",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L67-L174 | train | 199,829 |
mpdavis/python-jose | jose/jwt.py | _validate_nbf | def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)') | python | def _validate_nbf(claims, leeway=0):
"""Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'nbf' not in claims:
return
try:
nbf = int(claims['nbf'])
except ValueError:
raise JWTClaimsError('Not Before claim (nbf) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if nbf > (now + leeway):
raise JWTClaimsError('The token is not yet valid (nbf)') | [
"def",
"_validate_nbf",
"(",
"claims",
",",
"leeway",
"=",
"0",
")",
":",
"if",
"'nbf'",
"not",
"in",
"claims",
":",
"return",
"try",
":",
"nbf",
"=",
"int",
"(",
"claims",
"[",
"'nbf'",
"]",
")",
"except",
"ValueError",
":",
"raise",
"JWTClaimsError",... | Validates that the 'nbf' claim is valid.
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed. | [
"Validates",
"that",
"the",
"nbf",
"claim",
"is",
"valid",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L264-L291 | train | 199,830 |
mpdavis/python-jose | jose/jwt.py | _validate_exp | def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.') | python | def _validate_exp(claims, leeway=0):
"""Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed.
"""
if 'exp' not in claims:
return
try:
exp = int(claims['exp'])
except ValueError:
raise JWTClaimsError('Expiration Time claim (exp) must be an integer.')
now = timegm(datetime.utcnow().utctimetuple())
if exp < (now - leeway):
raise ExpiredSignatureError('Signature has expired.') | [
"def",
"_validate_exp",
"(",
"claims",
",",
"leeway",
"=",
"0",
")",
":",
"if",
"'exp'",
"not",
"in",
"claims",
":",
"return",
"try",
":",
"exp",
"=",
"int",
"(",
"claims",
"[",
"'exp'",
"]",
")",
"except",
"ValueError",
":",
"raise",
"JWTClaimsError",... | Validates that the 'exp' claim is valid.
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
leeway (int): The number of seconds of skew that is allowed. | [
"Validates",
"that",
"the",
"exp",
"claim",
"is",
"valid",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L294-L321 | train | 199,831 |
mpdavis/python-jose | jose/jwt.py | _validate_aud | def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience') | python | def _validate_aud(claims, audience=None):
"""Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token.
"""
if 'aud' not in claims:
# if audience:
# raise JWTError('Audience claim expected, but not in claims')
return
audience_claims = claims['aud']
if isinstance(audience_claims, string_types):
audience_claims = [audience_claims]
if not isinstance(audience_claims, list):
raise JWTClaimsError('Invalid claim format in token')
if any(not isinstance(c, string_types) for c in audience_claims):
raise JWTClaimsError('Invalid claim format in token')
if audience not in audience_claims:
raise JWTClaimsError('Invalid audience') | [
"def",
"_validate_aud",
"(",
"claims",
",",
"audience",
"=",
"None",
")",
":",
"if",
"'aud'",
"not",
"in",
"claims",
":",
"# if audience:",
"# raise JWTError('Audience claim expected, but not in claims')",
"return",
"audience_claims",
"=",
"claims",
"[",
"'aud'",
... | Validates that the 'aud' claim is valid.
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
audience (str): The audience that is verifying the token. | [
"Validates",
"that",
"the",
"aud",
"claim",
"is",
"valid",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L324-L357 | train | 199,832 |
mpdavis/python-jose | jose/jwt.py | _validate_iss | def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer') | python | def _validate_iss(claims, issuer=None):
"""Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token.
"""
if issuer is not None:
if isinstance(issuer, string_types):
issuer = (issuer,)
if claims.get('iss') not in issuer:
raise JWTClaimsError('Invalid issuer') | [
"def",
"_validate_iss",
"(",
"claims",
",",
"issuer",
"=",
"None",
")",
":",
"if",
"issuer",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"issuer",
",",
"string_types",
")",
":",
"issuer",
"=",
"(",
"issuer",
",",
")",
"if",
"claims",
".",
"get... | Validates that the 'iss' claim is valid.
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
issuer (str or iterable): Acceptable value(s) for the issuer that
signed the token. | [
"Validates",
"that",
"the",
"iss",
"claim",
"is",
"valid",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L360-L378 | train | 199,833 |
mpdavis/python-jose | jose/jwt.py | _validate_sub | def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject') | python | def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token.
"""
if 'sub' not in claims:
return
if not isinstance(claims['sub'], string_types):
raise JWTClaimsError('Subject must be a string.')
if subject is not None:
if claims.get('sub') != subject:
raise JWTClaimsError('Invalid subject') | [
"def",
"_validate_sub",
"(",
"claims",
",",
"subject",
"=",
"None",
")",
":",
"if",
"'sub'",
"not",
"in",
"claims",
":",
"return",
"if",
"not",
"isinstance",
"(",
"claims",
"[",
"'sub'",
"]",
",",
"string_types",
")",
":",
"raise",
"JWTClaimsError",
"(",... | Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.
Args:
claims (dict): The claims dictionary to validate.
subject (str): The subject of the token. | [
"Validates",
"that",
"the",
"sub",
"claim",
"is",
"valid",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwt.py#L381-L405 | train | 199,834 |
mpdavis/python-jose | jose/backends/rsa_backend.py | _gcd | def _gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, (a % b)
return a | python | def _gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, (a % b)
return a | [
"def",
"_gcd",
"(",
"a",
",",
"b",
")",
":",
"while",
"b",
":",
"a",
",",
"b",
"=",
"b",
",",
"(",
"a",
"%",
"b",
")",
"return",
"a"
] | Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive). | [
"Calculate",
"the",
"Greatest",
"Common",
"Divisor",
"of",
"a",
"and",
"b",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/rsa_backend.py#L37-L45 | train | 199,835 |
mpdavis/python-jose | jose/backends/rsa_backend.py | _rsa_recover_prime_factors | def _rsa_recover_prime_factors(n, e, d):
"""
Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto.
"""
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a multiple of phi(n), even,
# and can be represented as t*2^s.
t = ktot
while t % 2 == 0:
t = t // 2
# Cycle through all multiplicative inverses in Zn.
# The algorithm is non-deterministic, but there is a 50% chance
# any candidate a leads to successful factoring.
# See "Digitalized Signatures and Public Key Functions as Intractable
# as Factorization", M. Rabin, 1979
spotted = False
a = 2
while not spotted and a < _MAX_RECOVERY_ATTEMPTS:
k = t
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = _gcd(cand + 1, n)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
q, r = divmod(n, p)
assert r == 0
p, q = sorted((p, q), reverse=True)
return (p, q) | python | def _rsa_recover_prime_factors(n, e, d):
"""
Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto.
"""
# See 8.2.2(i) in Handbook of Applied Cryptography.
ktot = d * e - 1
# The quantity d*e-1 is a multiple of phi(n), even,
# and can be represented as t*2^s.
t = ktot
while t % 2 == 0:
t = t // 2
# Cycle through all multiplicative inverses in Zn.
# The algorithm is non-deterministic, but there is a 50% chance
# any candidate a leads to successful factoring.
# See "Digitalized Signatures and Public Key Functions as Intractable
# as Factorization", M. Rabin, 1979
spotted = False
a = 2
while not spotted and a < _MAX_RECOVERY_ATTEMPTS:
k = t
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = _gcd(cand + 1, n)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
q, r = divmod(n, p)
assert r == 0
p, q = sorted((p, q), reverse=True)
return (p, q) | [
"def",
"_rsa_recover_prime_factors",
"(",
"n",
",",
"e",
",",
"d",
")",
":",
"# See 8.2.2(i) in Handbook of Applied Cryptography.",
"ktot",
"=",
"d",
"*",
"e",
"-",
"1",
"# The quantity d*e-1 is a multiple of phi(n), even,",
"# and can be represented as t*2^s.",
"t",
"=",
... | Compute factors p and q from the private exponent d. We assume that n has
no more than two factors. This function is adapted from code in PyCrypto. | [
"Compute",
"factors",
"p",
"and",
"q",
"from",
"the",
"private",
"exponent",
"d",
".",
"We",
"assume",
"that",
"n",
"has",
"no",
"more",
"than",
"two",
"factors",
".",
"This",
"function",
"is",
"adapted",
"from",
"code",
"in",
"PyCrypto",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/rsa_backend.py#L54-L94 | train | 199,836 |
mpdavis/python-jose | jose/backends/rsa_backend.py | _legacy_private_key_pkcs8_to_pkcs1 | def _legacy_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Legacy RSA private key PKCS8-to-PKCS1 conversion.
.. warning::
This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8
encoding was also incorrect.
"""
# Only allow this processing if the prefix matches
# AND the following byte indicates an ASN1 sequence,
# as we would expect with the legacy encoding.
if not pkcs8_key.startswith(LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID):
raise ValueError("Invalid private key encoding")
return pkcs8_key[len(LEGACY_INVALID_PKCS8_RSA_HEADER):] | python | def _legacy_private_key_pkcs8_to_pkcs1(pkcs8_key):
"""Legacy RSA private key PKCS8-to-PKCS1 conversion.
.. warning::
This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8
encoding was also incorrect.
"""
# Only allow this processing if the prefix matches
# AND the following byte indicates an ASN1 sequence,
# as we would expect with the legacy encoding.
if not pkcs8_key.startswith(LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID):
raise ValueError("Invalid private key encoding")
return pkcs8_key[len(LEGACY_INVALID_PKCS8_RSA_HEADER):] | [
"def",
"_legacy_private_key_pkcs8_to_pkcs1",
"(",
"pkcs8_key",
")",
":",
"# Only allow this processing if the prefix matches",
"# AND the following byte indicates an ASN1 sequence,",
"# as we would expect with the legacy encoding.",
"if",
"not",
"pkcs8_key",
".",
"startswith",
"(",
"LE... | Legacy RSA private key PKCS8-to-PKCS1 conversion.
.. warning::
This is incorrect parsing and only works because the legacy PKCS1-to-PKCS8
encoding was also incorrect. | [
"Legacy",
"RSA",
"private",
"key",
"PKCS8",
"-",
"to",
"-",
"PKCS1",
"conversion",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/backends/rsa_backend.py#L102-L116 | train | 199,837 |
mpdavis/python-jose | jose/utils.py | base64url_decode | def base64url_decode(input):
"""Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode.
"""
rem = len(input) % 4
if rem > 0:
input += b'=' * (4 - rem)
return base64.urlsafe_b64decode(input) | python | def base64url_decode(input):
"""Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode.
"""
rem = len(input) % 4
if rem > 0:
input += b'=' * (4 - rem)
return base64.urlsafe_b64decode(input) | [
"def",
"base64url_decode",
"(",
"input",
")",
":",
"rem",
"=",
"len",
"(",
"input",
")",
"%",
"4",
"if",
"rem",
">",
"0",
":",
"input",
"+=",
"b'='",
"*",
"(",
"4",
"-",
"rem",
")",
"return",
"base64",
".",
"urlsafe_b64decode",
"(",
"input",
")"
] | Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode. | [
"Helper",
"method",
"to",
"base64url_decode",
"a",
"string",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/utils.py#L78-L90 | train | 199,838 |
mpdavis/python-jose | jose/utils.py | constant_time_string_compare | def constant_time_string_compare(a, b):
"""Helper for comparing string in constant time, independent
of the python version being used.
Args:
a (str): A string to compare
b (str): A string to compare
"""
try:
return hmac.compare_digest(a, b)
except AttributeError:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 | python | def constant_time_string_compare(a, b):
"""Helper for comparing string in constant time, independent
of the python version being used.
Args:
a (str): A string to compare
b (str): A string to compare
"""
try:
return hmac.compare_digest(a, b)
except AttributeError:
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0 | [
"def",
"constant_time_string_compare",
"(",
"a",
",",
"b",
")",
":",
"try",
":",
"return",
"hmac",
".",
"compare_digest",
"(",
"a",
",",
"b",
")",
"except",
"AttributeError",
":",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
":",
"return",... | Helper for comparing string in constant time, independent
of the python version being used.
Args:
a (str): A string to compare
b (str): A string to compare | [
"Helper",
"for",
"comparing",
"string",
"in",
"constant",
"time",
"independent",
"of",
"the",
"python",
"version",
"being",
"used",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/utils.py#L113-L134 | train | 199,839 |
mpdavis/python-jose | jose/jws.py | sign | def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256):
"""Signs a claims set and returns a JWS string.
Args:
payload (str): A string to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWSError: If there is an error signing the token.
Examples:
>>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
if algorithm not in ALGORITHMS.SUPPORTED:
raise JWSError('Algorithm %s not supported.' % algorithm)
encoded_header = _encode_header(algorithm, additional_headers=headers)
encoded_payload = _encode_payload(payload)
signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key)
return signed_output | python | def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256):
"""Signs a claims set and returns a JWS string.
Args:
payload (str): A string to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWSError: If there is an error signing the token.
Examples:
>>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
"""
if algorithm not in ALGORITHMS.SUPPORTED:
raise JWSError('Algorithm %s not supported.' % algorithm)
encoded_header = _encode_header(algorithm, additional_headers=headers)
encoded_payload = _encode_payload(payload)
signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key)
return signed_output | [
"def",
"sign",
"(",
"payload",
",",
"key",
",",
"headers",
"=",
"None",
",",
"algorithm",
"=",
"ALGORITHMS",
".",
"HS256",
")",
":",
"if",
"algorithm",
"not",
"in",
"ALGORITHMS",
".",
"SUPPORTED",
":",
"raise",
"JWSError",
"(",
"'Algorithm %s not supported.'... | Signs a claims set and returns a JWS string.
Args:
payload (str): A string to sign
key (str or dict): The key to use for signing the claim set. Can be
individual JWK or JWK set.
headers (dict, optional): A set of headers that will be added to
the default headers. Any headers that are added as additional
headers will override the default headers.
algorithm (str, optional): The algorithm to use for signing the
the claims. Defaults to HS256.
Returns:
str: The string representation of the header, claims, and signature.
Raises:
JWSError: If there is an error signing the token.
Examples:
>>> jws.sign({'a': 'b'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8' | [
"Signs",
"a",
"claims",
"set",
"and",
"returns",
"a",
"JWS",
"string",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jws.py#L19-L52 | train | 199,840 |
mpdavis/python-jose | jose/jws.py | verify | def verify(token, key, algorithms, verify=True):
"""Verifies a JWS string's signature.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
Returns:
str: The str representation of the payload, assuming the signature is valid.
Raises:
JWSError: If there is an exception verifying a token.
Examples:
>>> token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jws.verify(token, 'secret', algorithms='HS256')
"""
header, payload, signing_input, signature = _load(token)
if verify:
_verify_signature(signing_input, header, signature, key, algorithms)
return payload | python | def verify(token, key, algorithms, verify=True):
"""Verifies a JWS string's signature.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
Returns:
str: The str representation of the payload, assuming the signature is valid.
Raises:
JWSError: If there is an exception verifying a token.
Examples:
>>> token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jws.verify(token, 'secret', algorithms='HS256')
"""
header, payload, signing_input, signature = _load(token)
if verify:
_verify_signature(signing_input, header, signature, key, algorithms)
return payload | [
"def",
"verify",
"(",
"token",
",",
"key",
",",
"algorithms",
",",
"verify",
"=",
"True",
")",
":",
"header",
",",
"payload",
",",
"signing_input",
",",
"signature",
"=",
"_load",
"(",
"token",
")",
"if",
"verify",
":",
"_verify_signature",
"(",
"signing... | Verifies a JWS string's signature.
Args:
token (str): A signed JWS to be verified.
key (str or dict): A key to attempt to verify the payload with. Can be
individual JWK or JWK set.
algorithms (str or list): Valid algorithms that should be used to verify the JWS.
Returns:
str: The str representation of the payload, assuming the signature is valid.
Raises:
JWSError: If there is an exception verifying a token.
Examples:
>>> token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.jiMyrsmD8AoHWeQgmxZ5yq8z0lXS67_QGs52AzC8Ru8'
>>> jws.verify(token, 'secret', algorithms='HS256') | [
"Verifies",
"a",
"JWS",
"string",
"s",
"signature",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jws.py#L55-L82 | train | 199,841 |
mpdavis/python-jose | jose/jwk.py | construct | def construct(key_data, algorithm=None):
"""
Construct a Key object for the given algorithm with the given
key_data.
"""
# Allow for pulling the algorithm off of the passed in jwk.
if not algorithm and isinstance(key_data, dict):
algorithm = key_data.get('alg', None)
if not algorithm:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
key_class = get_key(algorithm)
if not key_class:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
return key_class(key_data, algorithm) | python | def construct(key_data, algorithm=None):
"""
Construct a Key object for the given algorithm with the given
key_data.
"""
# Allow for pulling the algorithm off of the passed in jwk.
if not algorithm and isinstance(key_data, dict):
algorithm = key_data.get('alg', None)
if not algorithm:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
key_class = get_key(algorithm)
if not key_class:
raise JWKError('Unable to find a algorithm for key: %s' % key_data)
return key_class(key_data, algorithm) | [
"def",
"construct",
"(",
"key_data",
",",
"algorithm",
"=",
"None",
")",
":",
"# Allow for pulling the algorithm off of the passed in jwk.",
"if",
"not",
"algorithm",
"and",
"isinstance",
"(",
"key_data",
",",
"dict",
")",
":",
"algorithm",
"=",
"key_data",
".",
"... | Construct a Key object for the given algorithm with the given
key_data. | [
"Construct",
"a",
"Key",
"object",
"for",
"the",
"given",
"algorithm",
"with",
"the",
"given",
"key_data",
"."
] | deea7600eeea47aeb1bf5053a96de51cf2b9c639 | https://github.com/mpdavis/python-jose/blob/deea7600eeea47aeb1bf5053a96de51cf2b9c639/jose/jwk.py#L45-L61 | train | 199,842 |
ntucllab/libact | libact/models/multilabel/binary_relevance.py | BinaryRelevance.train | def train(self, dataset):
r"""Train model with given feature.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Train feature vector.
Y : array-like, shape=(n_samples, n_labels)
Target labels.
Attributes
----------
clfs\_ : list of :py:mod:`libact.models` object instances
Classifier instances.
Returns
-------
self : object
Retuen self.
"""
X, Y = dataset.format_sklearn()
X = np.array(X)
Y = np.array(Y)
self.n_labels_ = np.shape(Y)[1]
self.n_features_ = np.shape(X)[1]
self.clfs_ = []
for i in range(self.n_labels_):
# TODO should we handle it here or we should handle it before calling
if len(np.unique(Y[:, i])) == 1:
clf = DummyClf()
else:
clf = copy.deepcopy(self.base_clf)
self.clfs_.append(clf)
Parallel(n_jobs=self.n_jobs, backend='threading')(
delayed(_fit_model)(self.clfs_[i], X, Y[:, i])
for i in range(self.n_labels_))
#clf.train(Dataset(X, Y[:, i]))
return self | python | def train(self, dataset):
r"""Train model with given feature.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Train feature vector.
Y : array-like, shape=(n_samples, n_labels)
Target labels.
Attributes
----------
clfs\_ : list of :py:mod:`libact.models` object instances
Classifier instances.
Returns
-------
self : object
Retuen self.
"""
X, Y = dataset.format_sklearn()
X = np.array(X)
Y = np.array(Y)
self.n_labels_ = np.shape(Y)[1]
self.n_features_ = np.shape(X)[1]
self.clfs_ = []
for i in range(self.n_labels_):
# TODO should we handle it here or we should handle it before calling
if len(np.unique(Y[:, i])) == 1:
clf = DummyClf()
else:
clf = copy.deepcopy(self.base_clf)
self.clfs_.append(clf)
Parallel(n_jobs=self.n_jobs, backend='threading')(
delayed(_fit_model)(self.clfs_[i], X, Y[:, i])
for i in range(self.n_labels_))
#clf.train(Dataset(X, Y[:, i]))
return self | [
"def",
"train",
"(",
"self",
",",
"dataset",
")",
":",
"X",
",",
"Y",
"=",
"dataset",
".",
"format_sklearn",
"(",
")",
"X",
"=",
"np",
".",
"array",
"(",
"X",
")",
"Y",
"=",
"np",
".",
"array",
"(",
"Y",
")",
"self",
".",
"n_labels_",
"=",
"n... | r"""Train model with given feature.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Train feature vector.
Y : array-like, shape=(n_samples, n_labels)
Target labels.
Attributes
----------
clfs\_ : list of :py:mod:`libact.models` object instances
Classifier instances.
Returns
-------
self : object
Retuen self. | [
"r",
"Train",
"model",
"with",
"given",
"feature",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/models/multilabel/binary_relevance.py#L40-L82 | train | 199,843 |
ntucllab/libact | libact/models/multilabel/binary_relevance.py | BinaryRelevance.predict | def predict(self, X):
r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted labels of given feature vector.
"""
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('Given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict(X)
return pred.astype(int) | python | def predict(self, X):
r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted labels of given feature vector.
"""
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('Given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict(X)
return pred.astype(int) | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"asarray",
"(",
"X",
")",
"if",
"self",
".",
"clfs_",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Train before prediction\"",
")",
"if",
"X",
".",
"shape",
"[",
"1",
"]",... | r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted labels of given feature vector. | [
"r",
"Predict",
"labels",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/models/multilabel/binary_relevance.py#L84-L106 | train | 199,844 |
ntucllab/libact | libact/models/multilabel/binary_relevance.py | BinaryRelevance.predict_real | def predict_real(self, X):
r"""Predict the probability of being 1 for each label.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted probability of each label.
"""
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict_real(X)[:, 1]
return pred | python | def predict_real(self, X):
r"""Predict the probability of being 1 for each label.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted probability of each label.
"""
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict_real(X)[:, 1]
return pred | [
"def",
"predict_real",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"np",
".",
"asarray",
"(",
"X",
")",
"if",
"self",
".",
"clfs_",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Train before prediction\"",
")",
"if",
"X",
".",
"shape",
"[",
"1",
... | r"""Predict the probability of being 1 for each label.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted probability of each label. | [
"r",
"Predict",
"the",
"probability",
"of",
"being",
"1",
"for",
"each",
"label",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/models/multilabel/binary_relevance.py#L108-L130 | train | 199,845 |
ntucllab/libact | libact/models/multilabel/binary_relevance.py | BinaryRelevance.score | def score(self, testing_dataset, criterion='hamming'):
"""Return the mean accuracy on the test dataset
Parameters
----------
testing_dataset : Dataset object
The testing dataset used to measure the perforance of the trained
model.
criterion : ['hamming', 'f1']
instance-wise criterion.
Returns
-------
score : float
Mean accuracy of self.predict(X) wrt. y.
"""
# TODO check if data in dataset are all correct
X, Y = testing_dataset.format_sklearn()
if criterion == 'hamming':
return np.mean(np.abs(self.predict(X) - Y).mean(axis=1))
elif criterion == 'f1':
Z = self.predict(X)
Z = Z.astype(int)
Y = Y.astype(int)
up = 2*np.sum(Z & Y, axis=1).astype(float)
down1 = np.sum(Z, axis=1)
down2 = np.sum(Y, axis=1)
down = (down1 + down2)
down[down==0] = 1.
up[down==0] = 1.
return np.mean(up / down)
else:
raise NotImplementedError(
"criterion '%s' not implemented" % criterion) | python | def score(self, testing_dataset, criterion='hamming'):
"""Return the mean accuracy on the test dataset
Parameters
----------
testing_dataset : Dataset object
The testing dataset used to measure the perforance of the trained
model.
criterion : ['hamming', 'f1']
instance-wise criterion.
Returns
-------
score : float
Mean accuracy of self.predict(X) wrt. y.
"""
# TODO check if data in dataset are all correct
X, Y = testing_dataset.format_sklearn()
if criterion == 'hamming':
return np.mean(np.abs(self.predict(X) - Y).mean(axis=1))
elif criterion == 'f1':
Z = self.predict(X)
Z = Z.astype(int)
Y = Y.astype(int)
up = 2*np.sum(Z & Y, axis=1).astype(float)
down1 = np.sum(Z, axis=1)
down2 = np.sum(Y, axis=1)
down = (down1 + down2)
down[down==0] = 1.
up[down==0] = 1.
return np.mean(up / down)
else:
raise NotImplementedError(
"criterion '%s' not implemented" % criterion) | [
"def",
"score",
"(",
"self",
",",
"testing_dataset",
",",
"criterion",
"=",
"'hamming'",
")",
":",
"# TODO check if data in dataset are all correct",
"X",
",",
"Y",
"=",
"testing_dataset",
".",
"format_sklearn",
"(",
")",
"if",
"criterion",
"==",
"'hamming'",
":",... | Return the mean accuracy on the test dataset
Parameters
----------
testing_dataset : Dataset object
The testing dataset used to measure the perforance of the trained
model.
criterion : ['hamming', 'f1']
instance-wise criterion.
Returns
-------
score : float
Mean accuracy of self.predict(X) wrt. y. | [
"Return",
"the",
"mean",
"accuracy",
"on",
"the",
"test",
"dataset"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/models/multilabel/binary_relevance.py#L156-L190 | train | 199,846 |
ntucllab/libact | libact/utils/__init__.py | seed_random_state | def seed_random_state(seed):
"""Turn seed into np.random.RandomState instance
"""
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r can not be used to generate numpy.random.RandomState"
" instance" % seed) | python | def seed_random_state(seed):
"""Turn seed into np.random.RandomState instance
"""
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r can not be used to generate numpy.random.RandomState"
" instance" % seed) | [
"def",
"seed_random_state",
"(",
"seed",
")",
":",
"if",
"(",
"seed",
"is",
"None",
")",
"or",
"(",
"isinstance",
"(",
"seed",
",",
"int",
")",
")",
":",
"return",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")",
"elif",
"isinstance",
"(",
... | Turn seed into np.random.RandomState instance | [
"Turn",
"seed",
"into",
"np",
".",
"random",
".",
"RandomState",
"instance"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/utils/__init__.py#L31-L39 | train | 199,847 |
ntucllab/libact | libact/utils/__init__.py | calc_cost | def calc_cost(y, yhat, cost_matrix):
"""Calculate the cost with given cost matrix
y : ground truth
yhat : estimation
cost_matrix : array-like, shape=(n_classes, n_classes)
The ith row, jth column represents the cost of the ground truth being
ith class and prediction as jth class.
"""
return np.mean(cost_matrix[list(y), list(yhat)]) | python | def calc_cost(y, yhat, cost_matrix):
"""Calculate the cost with given cost matrix
y : ground truth
yhat : estimation
cost_matrix : array-like, shape=(n_classes, n_classes)
The ith row, jth column represents the cost of the ground truth being
ith class and prediction as jth class.
"""
return np.mean(cost_matrix[list(y), list(yhat)]) | [
"def",
"calc_cost",
"(",
"y",
",",
"yhat",
",",
"cost_matrix",
")",
":",
"return",
"np",
".",
"mean",
"(",
"cost_matrix",
"[",
"list",
"(",
"y",
")",
",",
"list",
"(",
"yhat",
")",
"]",
")"
] | Calculate the cost with given cost matrix
y : ground truth
yhat : estimation
cost_matrix : array-like, shape=(n_classes, n_classes)
The ith row, jth column represents the cost of the ground truth being
ith class and prediction as jth class. | [
"Calculate",
"the",
"cost",
"with",
"given",
"cost",
"matrix"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/utils/__init__.py#L41-L52 | train | 199,848 |
ntucllab/libact | libact/query_strategies/uncertainty_sampling.py | UncertaintySampling.make_query | def make_query(self, return_score=False):
"""Return the index of the sample to be queried and labeled and
selection score of each sample. Read-only.
No modification to the internal states.
Returns
-------
ask_id : int
The index of the next unlabeled sample to be queried and labeled.
score : list of (index, score) tuple
Selection score of unlabled entries, the larger the better.
"""
dataset = self.dataset
self.model.train(dataset)
unlabeled_entry_ids, X_pool = zip(*dataset.get_unlabeled_entries())
if isinstance(self.model, ProbabilisticModel):
dvalue = self.model.predict_proba(X_pool)
elif isinstance(self.model, ContinuousModel):
dvalue = self.model.predict_real(X_pool)
if self.method == 'lc': # least confident
score = -np.max(dvalue, axis=1)
elif self.method == 'sm': # smallest margin
if np.shape(dvalue)[1] > 2:
# Find 2 largest decision values
dvalue = -(np.partition(-dvalue, 2, axis=1)[:, :2])
score = -np.abs(dvalue[:, 0] - dvalue[:, 1])
elif self.method == 'entropy':
score = np.sum(-dvalue * np.log(dvalue), axis=1)
ask_id = np.argmax(score)
if return_score:
return unlabeled_entry_ids[ask_id], \
list(zip(unlabeled_entry_ids, score))
else:
return unlabeled_entry_ids[ask_id] | python | def make_query(self, return_score=False):
"""Return the index of the sample to be queried and labeled and
selection score of each sample. Read-only.
No modification to the internal states.
Returns
-------
ask_id : int
The index of the next unlabeled sample to be queried and labeled.
score : list of (index, score) tuple
Selection score of unlabled entries, the larger the better.
"""
dataset = self.dataset
self.model.train(dataset)
unlabeled_entry_ids, X_pool = zip(*dataset.get_unlabeled_entries())
if isinstance(self.model, ProbabilisticModel):
dvalue = self.model.predict_proba(X_pool)
elif isinstance(self.model, ContinuousModel):
dvalue = self.model.predict_real(X_pool)
if self.method == 'lc': # least confident
score = -np.max(dvalue, axis=1)
elif self.method == 'sm': # smallest margin
if np.shape(dvalue)[1] > 2:
# Find 2 largest decision values
dvalue = -(np.partition(-dvalue, 2, axis=1)[:, :2])
score = -np.abs(dvalue[:, 0] - dvalue[:, 1])
elif self.method == 'entropy':
score = np.sum(-dvalue * np.log(dvalue), axis=1)
ask_id = np.argmax(score)
if return_score:
return unlabeled_entry_ids[ask_id], \
list(zip(unlabeled_entry_ids, score))
else:
return unlabeled_entry_ids[ask_id] | [
"def",
"make_query",
"(",
"self",
",",
"return_score",
"=",
"False",
")",
":",
"dataset",
"=",
"self",
".",
"dataset",
"self",
".",
"model",
".",
"train",
"(",
"dataset",
")",
"unlabeled_entry_ids",
",",
"X_pool",
"=",
"zip",
"(",
"*",
"dataset",
".",
... | Return the index of the sample to be queried and labeled and
selection score of each sample. Read-only.
No modification to the internal states.
Returns
-------
ask_id : int
The index of the next unlabeled sample to be queried and labeled.
score : list of (index, score) tuple
Selection score of unlabled entries, the larger the better. | [
"Return",
"the",
"index",
"of",
"the",
"sample",
"to",
"be",
"queried",
"and",
"labeled",
"and",
"selection",
"score",
"of",
"each",
"sample",
".",
"Read",
"-",
"only",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/query_strategies/uncertainty_sampling.py#L98-L141 | train | 199,849 |
ntucllab/libact | libact/query_strategies/query_by_committee.py | QueryByCommittee._vote_disagreement | def _vote_disagreement(self, votes):
"""
Return the disagreement measurement of the given number of votes.
It uses the vote vote to measure the disagreement.
Parameters
----------
votes : list of int, shape==(n_samples, n_students)
The predictions that each student gives to each sample.
Returns
-------
disagreement : list of float, shape=(n_samples)
The vote entropy of the given votes.
"""
ret = []
for candidate in votes:
ret.append(0.0)
lab_count = {}
for lab in candidate:
lab_count[lab] = lab_count.setdefault(lab, 0) + 1
# Using vote entropy to measure disagreement
for lab in lab_count.keys():
ret[-1] -= lab_count[lab] / self.n_students * \
math.log(float(lab_count[lab]) / self.n_students)
return ret | python | def _vote_disagreement(self, votes):
"""
Return the disagreement measurement of the given number of votes.
It uses the vote vote to measure the disagreement.
Parameters
----------
votes : list of int, shape==(n_samples, n_students)
The predictions that each student gives to each sample.
Returns
-------
disagreement : list of float, shape=(n_samples)
The vote entropy of the given votes.
"""
ret = []
for candidate in votes:
ret.append(0.0)
lab_count = {}
for lab in candidate:
lab_count[lab] = lab_count.setdefault(lab, 0) + 1
# Using vote entropy to measure disagreement
for lab in lab_count.keys():
ret[-1] -= lab_count[lab] / self.n_students * \
math.log(float(lab_count[lab]) / self.n_students)
return ret | [
"def",
"_vote_disagreement",
"(",
"self",
",",
"votes",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"candidate",
"in",
"votes",
":",
"ret",
".",
"append",
"(",
"0.0",
")",
"lab_count",
"=",
"{",
"}",
"for",
"lab",
"in",
"candidate",
":",
"lab_count",
"[",... | Return the disagreement measurement of the given number of votes.
It uses the vote vote to measure the disagreement.
Parameters
----------
votes : list of int, shape==(n_samples, n_students)
The predictions that each student gives to each sample.
Returns
-------
disagreement : list of float, shape=(n_samples)
The vote entropy of the given votes. | [
"Return",
"the",
"disagreement",
"measurement",
"of",
"the",
"given",
"number",
"of",
"votes",
".",
"It",
"uses",
"the",
"vote",
"vote",
"to",
"measure",
"the",
"disagreement",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/query_strategies/query_by_committee.py#L110-L137 | train | 199,850 |
ntucllab/libact | libact/query_strategies/query_by_committee.py | QueryByCommittee._labeled_uniform_sample | def _labeled_uniform_sample(self, sample_size):
"""sample labeled entries uniformly"""
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zip(*samples)) | python | def _labeled_uniform_sample(self, sample_size):
"""sample labeled entries uniformly"""
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zip(*samples)) | [
"def",
"_labeled_uniform_sample",
"(",
"self",
",",
"sample_size",
")",
":",
"labeled_entries",
"=",
"self",
".",
"dataset",
".",
"get_labeled_entries",
"(",
")",
"samples",
"=",
"[",
"labeled_entries",
"[",
"self",
".",
"random_state_",
".",
"randint",
"(",
"... | sample labeled entries uniformly | [
"sample",
"labeled",
"entries",
"uniformly"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/query_strategies/query_by_committee.py#L159-L165 | train | 199,851 |
ntucllab/libact | libact/query_strategies/active_learning_by_learning.py | ActiveLearningByLearning.calc_reward_fn | def calc_reward_fn(self):
"""Calculate the reward value"""
model = copy.copy(self.model)
model.train(self.dataset)
# reward function: Importance-Weighted-Accuracy (IW-ACC) (tau, f)
reward = 0.
for i in range(len(self.queried_hist_)):
reward += self.W[i] * (
model.predict(
self.dataset.data[
self.queried_hist_[i]][0].reshape(1, -1)
)[0] ==
self.dataset.data[self.queried_hist_[i]][1]
)
reward /= (self.dataset.len_labeled() + self.dataset.len_unlabeled())
reward /= self.T
return reward | python | def calc_reward_fn(self):
"""Calculate the reward value"""
model = copy.copy(self.model)
model.train(self.dataset)
# reward function: Importance-Weighted-Accuracy (IW-ACC) (tau, f)
reward = 0.
for i in range(len(self.queried_hist_)):
reward += self.W[i] * (
model.predict(
self.dataset.data[
self.queried_hist_[i]][0].reshape(1, -1)
)[0] ==
self.dataset.data[self.queried_hist_[i]][1]
)
reward /= (self.dataset.len_labeled() + self.dataset.len_unlabeled())
reward /= self.T
return reward | [
"def",
"calc_reward_fn",
"(",
"self",
")",
":",
"model",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"model",
")",
"model",
".",
"train",
"(",
"self",
".",
"dataset",
")",
"# reward function: Importance-Weighted-Accuracy (IW-ACC) (tau, f)",
"reward",
"=",
"0.",
... | Calculate the reward value | [
"Calculate",
"the",
"reward",
"value"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/query_strategies/active_learning_by_learning.py#L178-L195 | train | 199,852 |
ntucllab/libact | libact/query_strategies/active_learning_by_learning.py | ActiveLearningByLearning.calc_query | def calc_query(self):
"""Calculate the sampling query distribution"""
# initial query
if self.query_dist is None:
self.query_dist = self.exp4p_.next(-1, None, None)
else:
self.query_dist = self.exp4p_.next(
self.calc_reward_fn(),
self.queried_hist_[-1],
self.dataset.data[self.queried_hist_[-1]][1]
)
return | python | def calc_query(self):
"""Calculate the sampling query distribution"""
# initial query
if self.query_dist is None:
self.query_dist = self.exp4p_.next(-1, None, None)
else:
self.query_dist = self.exp4p_.next(
self.calc_reward_fn(),
self.queried_hist_[-1],
self.dataset.data[self.queried_hist_[-1]][1]
)
return | [
"def",
"calc_query",
"(",
"self",
")",
":",
"# initial query",
"if",
"self",
".",
"query_dist",
"is",
"None",
":",
"self",
".",
"query_dist",
"=",
"self",
".",
"exp4p_",
".",
"next",
"(",
"-",
"1",
",",
"None",
",",
"None",
")",
"else",
":",
"self",
... | Calculate the sampling query distribution | [
"Calculate",
"the",
"sampling",
"query",
"distribution"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/query_strategies/active_learning_by_learning.py#L197-L208 | train | 199,853 |
ntucllab/libact | libact/query_strategies/active_learning_by_learning.py | Exp4P.next | def next(self, reward, ask_id, lbl):
"""Taking the label and the reward value of last question and returns
the next question to ask."""
# first run don't have reward, TODO exception on reward == -1 only once
if reward == -1:
return next(self.exp4p_gen)
else:
# TODO exception on reward in [0, 1]
return self.exp4p_gen.send((reward, ask_id, lbl)) | python | def next(self, reward, ask_id, lbl):
"""Taking the label and the reward value of last question and returns
the next question to ask."""
# first run don't have reward, TODO exception on reward == -1 only once
if reward == -1:
return next(self.exp4p_gen)
else:
# TODO exception on reward in [0, 1]
return self.exp4p_gen.send((reward, ask_id, lbl)) | [
"def",
"next",
"(",
"self",
",",
"reward",
",",
"ask_id",
",",
"lbl",
")",
":",
"# first run don't have reward, TODO exception on reward == -1 only once",
"if",
"reward",
"==",
"-",
"1",
":",
"return",
"next",
"(",
"self",
".",
"exp4p_gen",
")",
"else",
":",
"... | Taking the label and the reward value of last question and returns
the next question to ask. | [
"Taking",
"the",
"label",
"and",
"the",
"reward",
"value",
"of",
"last",
"question",
"and",
"returns",
"the",
"next",
"question",
"to",
"ask",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/query_strategies/active_learning_by_learning.py#L353-L361 | train | 199,854 |
ntucllab/libact | libact/query_strategies/active_learning_by_learning.py | Exp4P.exp4p | def exp4p(self):
"""The generator which implements the main part of Exp4.P.
Parameters
----------
reward: float
The reward value calculated from ALBL.
ask_id: integer
The entry_id of the sample point ALBL asked.
lbl: integer
The answer received from asking the entry_id ask_id.
Yields
------
q: array-like, shape = [K]
The query vector which tells ALBL what kind of distribution if
should sample from the unlabeled pool.
"""
while True:
# TODO probabilistic active learning algorithm
# len(self.unlabeled_invert_id_idx) is the number of unlabeled data
query = np.zeros((self.N, len(self.unlabeled_invert_id_idx)))
if self.uniform_sampler:
query[-1, :] = 1. / len(self.unlabeled_invert_id_idx)
for i, model in enumerate(self.query_strategies_):
query[i][self.unlabeled_invert_id_idx[model.make_query()]] = 1
# choice vector, shape = (self.K, )
W = np.sum(self.w)
p = (1 - self.K * self.pmin) * self.w / W + self.pmin
# query vector, shape= = (self.n_unlabeled, )
query_vector = np.dot(p, query)
reward, ask_id, _ = yield query_vector
ask_idx = self.unlabeled_invert_id_idx[ask_id]
rhat = reward * query[:, ask_idx] / query_vector[ask_idx]
# The original advice vector in Exp4.P in ALBL is a identity matrix
yhat = rhat
vhat = 1 / p
self.w = self.w * np.exp(
self.pmin / 2 * (
yhat + vhat * np.sqrt(
np.log(self.N / self.delta) / self.K / self.T
)
)
)
raise StopIteration | python | def exp4p(self):
"""The generator which implements the main part of Exp4.P.
Parameters
----------
reward: float
The reward value calculated from ALBL.
ask_id: integer
The entry_id of the sample point ALBL asked.
lbl: integer
The answer received from asking the entry_id ask_id.
Yields
------
q: array-like, shape = [K]
The query vector which tells ALBL what kind of distribution if
should sample from the unlabeled pool.
"""
while True:
# TODO probabilistic active learning algorithm
# len(self.unlabeled_invert_id_idx) is the number of unlabeled data
query = np.zeros((self.N, len(self.unlabeled_invert_id_idx)))
if self.uniform_sampler:
query[-1, :] = 1. / len(self.unlabeled_invert_id_idx)
for i, model in enumerate(self.query_strategies_):
query[i][self.unlabeled_invert_id_idx[model.make_query()]] = 1
# choice vector, shape = (self.K, )
W = np.sum(self.w)
p = (1 - self.K * self.pmin) * self.w / W + self.pmin
# query vector, shape= = (self.n_unlabeled, )
query_vector = np.dot(p, query)
reward, ask_id, _ = yield query_vector
ask_idx = self.unlabeled_invert_id_idx[ask_id]
rhat = reward * query[:, ask_idx] / query_vector[ask_idx]
# The original advice vector in Exp4.P in ALBL is a identity matrix
yhat = rhat
vhat = 1 / p
self.w = self.w * np.exp(
self.pmin / 2 * (
yhat + vhat * np.sqrt(
np.log(self.N / self.delta) / self.K / self.T
)
)
)
raise StopIteration | [
"def",
"exp4p",
"(",
"self",
")",
":",
"while",
"True",
":",
"# TODO probabilistic active learning algorithm",
"# len(self.unlabeled_invert_id_idx) is the number of unlabeled data",
"query",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"N",
",",
"len",
"(",
"self",... | The generator which implements the main part of Exp4.P.
Parameters
----------
reward: float
The reward value calculated from ALBL.
ask_id: integer
The entry_id of the sample point ALBL asked.
lbl: integer
The answer received from asking the entry_id ask_id.
Yields
------
q: array-like, shape = [K]
The query vector which tells ALBL what kind of distribution if
should sample from the unlabeled pool. | [
"The",
"generator",
"which",
"implements",
"the",
"main",
"part",
"of",
"Exp4",
".",
"P",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/query_strategies/active_learning_by_learning.py#L363-L416 | train | 199,855 |
ntucllab/libact | libact/base/dataset.py | import_libsvm_sparse | def import_libsvm_sparse(filename):
"""Imports dataset file in libsvm sparse format"""
from sklearn.datasets import load_svmlight_file
X, y = load_svmlight_file(filename)
return Dataset(X.toarray().tolist(), y.tolist()) | python | def import_libsvm_sparse(filename):
"""Imports dataset file in libsvm sparse format"""
from sklearn.datasets import load_svmlight_file
X, y = load_svmlight_file(filename)
return Dataset(X.toarray().tolist(), y.tolist()) | [
"def",
"import_libsvm_sparse",
"(",
"filename",
")",
":",
"from",
"sklearn",
".",
"datasets",
"import",
"load_svmlight_file",
"X",
",",
"y",
"=",
"load_svmlight_file",
"(",
"filename",
")",
"return",
"Dataset",
"(",
"X",
".",
"toarray",
"(",
")",
".",
"tolis... | Imports dataset file in libsvm sparse format | [
"Imports",
"dataset",
"file",
"in",
"libsvm",
"sparse",
"format"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/base/dataset.py#L203-L207 | train | 199,856 |
ntucllab/libact | libact/base/dataset.py | Dataset.update | def update(self, entry_id, new_label):
"""
Updates an entry with entry_id with the given label
Parameters
----------
entry_id : int
entry id of the sample to update.
label : {int, None}
Label of the sample to be update.
"""
self.data[entry_id] = (self.data[entry_id][0], new_label)
self.modified = True
for callback in self._update_callback:
callback(entry_id, new_label) | python | def update(self, entry_id, new_label):
"""
Updates an entry with entry_id with the given label
Parameters
----------
entry_id : int
entry id of the sample to update.
label : {int, None}
Label of the sample to be update.
"""
self.data[entry_id] = (self.data[entry_id][0], new_label)
self.modified = True
for callback in self._update_callback:
callback(entry_id, new_label) | [
"def",
"update",
"(",
"self",
",",
"entry_id",
",",
"new_label",
")",
":",
"self",
".",
"data",
"[",
"entry_id",
"]",
"=",
"(",
"self",
".",
"data",
"[",
"entry_id",
"]",
"[",
"0",
"]",
",",
"new_label",
")",
"self",
".",
"modified",
"=",
"True",
... | Updates an entry with entry_id with the given label
Parameters
----------
entry_id : int
entry id of the sample to update.
label : {int, None}
Label of the sample to be update. | [
"Updates",
"an",
"entry",
"with",
"entry_id",
"with",
"the",
"given",
"label"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/base/dataset.py#L104-L119 | train | 199,857 |
ntucllab/libact | libact/base/dataset.py | Dataset.get_unlabeled_entries | def get_unlabeled_entries(self):
"""
Returns list of unlabeled features, along with their entry_ids
Returns
-------
unlabeled_entries : list of (entry_id, feature) tuple
Labeled entries
"""
return [
(idx, entry[0]) for idx, entry in enumerate(self.data)
if entry[1] is None
] | python | def get_unlabeled_entries(self):
"""
Returns list of unlabeled features, along with their entry_ids
Returns
-------
unlabeled_entries : list of (entry_id, feature) tuple
Labeled entries
"""
return [
(idx, entry[0]) for idx, entry in enumerate(self.data)
if entry[1] is None
] | [
"def",
"get_unlabeled_entries",
"(",
"self",
")",
":",
"return",
"[",
"(",
"idx",
",",
"entry",
"[",
"0",
"]",
")",
"for",
"idx",
",",
"entry",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
"if",
"entry",
"[",
"1",
"]",
"is",
"None",
"]"
] | Returns list of unlabeled features, along with their entry_ids
Returns
-------
unlabeled_entries : list of (entry_id, feature) tuple
Labeled entries | [
"Returns",
"list",
"of",
"unlabeled",
"features",
"along",
"with",
"their",
"entry_ids"
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/base/dataset.py#L170-L182 | train | 199,858 |
ntucllab/libact | libact/base/dataset.py | Dataset.labeled_uniform_sample | def labeled_uniform_sample(self, sample_size, replace=True):
"""Returns a Dataset object with labeled data only, which is
resampled uniformly with given sample size.
Parameter `replace` decides whether sampling with replacement or not.
Parameters
----------
sample_size
"""
if replace:
samples = [
random.choice(self.get_labeled_entries())
for _ in range(sample_size)
]
else:
samples = random.sample(self.get_labeled_entries(), sample_size)
return Dataset(*zip(*samples)) | python | def labeled_uniform_sample(self, sample_size, replace=True):
"""Returns a Dataset object with labeled data only, which is
resampled uniformly with given sample size.
Parameter `replace` decides whether sampling with replacement or not.
Parameters
----------
sample_size
"""
if replace:
samples = [
random.choice(self.get_labeled_entries())
for _ in range(sample_size)
]
else:
samples = random.sample(self.get_labeled_entries(), sample_size)
return Dataset(*zip(*samples)) | [
"def",
"labeled_uniform_sample",
"(",
"self",
",",
"sample_size",
",",
"replace",
"=",
"True",
")",
":",
"if",
"replace",
":",
"samples",
"=",
"[",
"random",
".",
"choice",
"(",
"self",
".",
"get_labeled_entries",
"(",
")",
")",
"for",
"_",
"in",
"range"... | Returns a Dataset object with labeled data only, which is
resampled uniformly with given sample size.
Parameter `replace` decides whether sampling with replacement or not.
Parameters
----------
sample_size | [
"Returns",
"a",
"Dataset",
"object",
"with",
"labeled",
"data",
"only",
"which",
"is",
"resampled",
"uniformly",
"with",
"given",
"sample",
"size",
".",
"Parameter",
"replace",
"decides",
"whether",
"sampling",
"with",
"replacement",
"or",
"not",
"."
] | e37e9ed6c36febe701d84b2d495c958ab02f0bc8 | https://github.com/ntucllab/libact/blob/e37e9ed6c36febe701d84b2d495c958ab02f0bc8/libact/base/dataset.py#L184-L200 | train | 199,859 |
kislyuk/argcomplete | argcomplete/my_shlex.py | shlex.push_token | def push_token(self, tok):
"Push a token onto the stack popped by the get_token method"
if self.debug >= 1:
print("shlex: pushing token " + repr(tok))
self.pushback.appendleft(tok) | python | def push_token(self, tok):
"Push a token onto the stack popped by the get_token method"
if self.debug >= 1:
print("shlex: pushing token " + repr(tok))
self.pushback.appendleft(tok) | [
"def",
"push_token",
"(",
"self",
",",
"tok",
")",
":",
"if",
"self",
".",
"debug",
">=",
"1",
":",
"print",
"(",
"\"shlex: pushing token \"",
"+",
"repr",
"(",
"tok",
")",
")",
"self",
".",
"pushback",
".",
"appendleft",
"(",
"tok",
")"
] | Push a token onto the stack popped by the get_token method | [
"Push",
"a",
"token",
"onto",
"the",
"stack",
"popped",
"by",
"the",
"get_token",
"method"
] | f9eb0a2354d9e6153f687c463df98c16251d97ed | https://github.com/kislyuk/argcomplete/blob/f9eb0a2354d9e6153f687c463df98c16251d97ed/argcomplete/my_shlex.py#L87-L91 | train | 199,860 |
kislyuk/argcomplete | argcomplete/__init__.py | CompletionFinder._get_next_positional | def _get_next_positional(self):
"""
Get the next positional action if it exists.
"""
active_parser = self.active_parsers[-1]
last_positional = self.visited_positionals[-1]
all_positionals = active_parser._get_positional_actions()
if not all_positionals:
return None
if active_parser == last_positional:
return all_positionals[0]
i = 0
for i in range(len(all_positionals)):
if all_positionals[i] == last_positional:
break
if i + 1 < len(all_positionals):
return all_positionals[i + 1]
return None | python | def _get_next_positional(self):
"""
Get the next positional action if it exists.
"""
active_parser = self.active_parsers[-1]
last_positional = self.visited_positionals[-1]
all_positionals = active_parser._get_positional_actions()
if not all_positionals:
return None
if active_parser == last_positional:
return all_positionals[0]
i = 0
for i in range(len(all_positionals)):
if all_positionals[i] == last_positional:
break
if i + 1 < len(all_positionals):
return all_positionals[i + 1]
return None | [
"def",
"_get_next_positional",
"(",
"self",
")",
":",
"active_parser",
"=",
"self",
".",
"active_parsers",
"[",
"-",
"1",
"]",
"last_positional",
"=",
"self",
".",
"visited_positionals",
"[",
"-",
"1",
"]",
"all_positionals",
"=",
"active_parser",
".",
"_get_p... | Get the next positional action if it exists. | [
"Get",
"the",
"next",
"positional",
"action",
"if",
"it",
"exists",
"."
] | f9eb0a2354d9e6153f687c463df98c16251d97ed | https://github.com/kislyuk/argcomplete/blob/f9eb0a2354d9e6153f687c463df98c16251d97ed/argcomplete/__init__.py#L473-L495 | train | 199,861 |
kislyuk/argcomplete | argcomplete/shellintegration.py | shellcode | def shellcode(executables, use_defaults=True, shell='bash', complete_arguments=None):
'''
Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param str shell: Name of the shell to output code for (bash or tcsh)
:param complete_arguments: Arguments to call complete with
:type complete_arguments: list(str) or None
'''
if complete_arguments is None:
complete_options = '-o nospace -o default' if use_defaults else '-o nospace'
else:
complete_options = " ".join(complete_arguments)
if shell == 'bash':
quoted_executables = [quote(i) for i in executables]
executables_list = " ".join(quoted_executables)
code = bashcode % dict(complete_opts=complete_options, executables=executables_list)
else:
code = ""
for executable in executables:
code += tcshcode % dict(executable=executable)
return code | python | def shellcode(executables, use_defaults=True, shell='bash', complete_arguments=None):
'''
Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param str shell: Name of the shell to output code for (bash or tcsh)
:param complete_arguments: Arguments to call complete with
:type complete_arguments: list(str) or None
'''
if complete_arguments is None:
complete_options = '-o nospace -o default' if use_defaults else '-o nospace'
else:
complete_options = " ".join(complete_arguments)
if shell == 'bash':
quoted_executables = [quote(i) for i in executables]
executables_list = " ".join(quoted_executables)
code = bashcode % dict(complete_opts=complete_options, executables=executables_list)
else:
code = ""
for executable in executables:
code += tcshcode % dict(executable=executable)
return code | [
"def",
"shellcode",
"(",
"executables",
",",
"use_defaults",
"=",
"True",
",",
"shell",
"=",
"'bash'",
",",
"complete_arguments",
"=",
"None",
")",
":",
"if",
"complete_arguments",
"is",
"None",
":",
"complete_options",
"=",
"'-o nospace -o default'",
"if",
"use... | Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param str shell: Name of the shell to output code for (bash or tcsh)
:param complete_arguments: Arguments to call complete with
:type complete_arguments: list(str) or None | [
"Provide",
"the",
"shell",
"code",
"required",
"to",
"register",
"a",
"python",
"executable",
"for",
"use",
"with",
"the",
"argcomplete",
"module",
"."
] | f9eb0a2354d9e6153f687c463df98c16251d97ed | https://github.com/kislyuk/argcomplete/blob/f9eb0a2354d9e6153f687c463df98c16251d97ed/argcomplete/shellintegration.py#L46-L71 | train | 199,862 |
stefanfoulis/django-sendsms | sendsms/backends/smspubli.py | SmsBackend._send | def _send(self, message):
"""
Private method for send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sended else False
:rtype: bool
"""
params = {
'V': SMSPUBLI_API_VERSION,
'UN': SMSPUBLI_USERNAME,
'PWD': SMSPUBLI_PASSWORD,
'R': SMSPUBLI_ROUTE,
'SA': message.from_phone,
'DA': ','.join(message.to),
'M': message.body.encode('latin-1'),
'DC': SMSPUBLI_DC,
'DR': SMSPUBLI_DR,
'UR': message.from_phone
}
if SMSPUBLI_ALLOW_LONG_SMS:
params['LM'] = '1'
response = requests.post(SMSPUBLI_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise
else:
return False
response_msg, response_code = response.content.split(':')
if response_msg == 'OK':
try:
if "," in response_code:
codes = map(int, response_code.split(","))
else:
codes = [int(response_code)]
for code in codes:
if code == -5:
#: TODO send error signal (no $$)
pass
elif code == -3:
#: TODO send error signal (incorrect num)
pass
return True
except (ValueError, TypeError):
if not self.fail_silently:
raise
return False
return False | python | def _send(self, message):
"""
Private method for send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sended else False
:rtype: bool
"""
params = {
'V': SMSPUBLI_API_VERSION,
'UN': SMSPUBLI_USERNAME,
'PWD': SMSPUBLI_PASSWORD,
'R': SMSPUBLI_ROUTE,
'SA': message.from_phone,
'DA': ','.join(message.to),
'M': message.body.encode('latin-1'),
'DC': SMSPUBLI_DC,
'DR': SMSPUBLI_DR,
'UR': message.from_phone
}
if SMSPUBLI_ALLOW_LONG_SMS:
params['LM'] = '1'
response = requests.post(SMSPUBLI_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise
else:
return False
response_msg, response_code = response.content.split(':')
if response_msg == 'OK':
try:
if "," in response_code:
codes = map(int, response_code.split(","))
else:
codes = [int(response_code)]
for code in codes:
if code == -5:
#: TODO send error signal (no $$)
pass
elif code == -3:
#: TODO send error signal (incorrect num)
pass
return True
except (ValueError, TypeError):
if not self.fail_silently:
raise
return False
return False | [
"def",
"_send",
"(",
"self",
",",
"message",
")",
":",
"params",
"=",
"{",
"'V'",
":",
"SMSPUBLI_API_VERSION",
",",
"'UN'",
":",
"SMSPUBLI_USERNAME",
",",
"'PWD'",
":",
"SMSPUBLI_PASSWORD",
",",
"'R'",
":",
"SMSPUBLI_ROUTE",
",",
"'SA'",
":",
"message",
".... | Private method for send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sended else False
:rtype: bool | [
"Private",
"method",
"for",
"send",
"one",
"message",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smspubli.py#L59-L113 | train | 199,863 |
stefanfoulis/django-sendsms | sendsms/backends/filebased.py | SmsBackend._get_filename | def _get_filename(self):
"""Return a unique file name."""
if self._fname is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
fname = "%s-%s.log" % (timestamp, abs(id(self)))
self._fname = os.path.join(self.file_path, fname)
return self._fname | python | def _get_filename(self):
"""Return a unique file name."""
if self._fname is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
fname = "%s-%s.log" % (timestamp, abs(id(self)))
self._fname = os.path.join(self.file_path, fname)
return self._fname | [
"def",
"_get_filename",
"(",
"self",
")",
":",
"if",
"self",
".",
"_fname",
"is",
"None",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d-%H%M%S\"",
")",
"fname",
"=",
"\"%s-%s.log\"",
"%",
"(",
... | Return a unique file name. | [
"Return",
"a",
"unique",
"file",
"name",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/filebased.py#L43-L49 | train | 199,864 |
stefanfoulis/django-sendsms | sendsms/backends/smsglobal.py | SmsBackend.get_balance | def get_balance(self):
"""
Get balance with provider.
"""
if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:
raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.')
params = {
'user' : self.get_username(),
'password' : self.get_password(),
'country' : SMSGLOBAL_CHECK_BALANCE_COUNTRY,
}
req = urllib2.Request(SMSGLOBAL_API_URL_CHECKBALANCE, urllib.urlencode(params))
response = urllib2.urlopen(req).read()
# CREDITS:8658.44;COUNTRY:AU;SMS:3764.54;
if response.startswith('ERROR'):
raise Exception('Error retrieving balance: %s' % response.replace('ERROR:', ''))
return dict([(p.split(':')[0].lower(), p.split(':')[1]) for p in response.split(';') if len(p) > 0]) | python | def get_balance(self):
"""
Get balance with provider.
"""
if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:
raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.')
params = {
'user' : self.get_username(),
'password' : self.get_password(),
'country' : SMSGLOBAL_CHECK_BALANCE_COUNTRY,
}
req = urllib2.Request(SMSGLOBAL_API_URL_CHECKBALANCE, urllib.urlencode(params))
response = urllib2.urlopen(req).read()
# CREDITS:8658.44;COUNTRY:AU;SMS:3764.54;
if response.startswith('ERROR'):
raise Exception('Error retrieving balance: %s' % response.replace('ERROR:', ''))
return dict([(p.split(':')[0].lower(), p.split(':')[1]) for p in response.split(';') if len(p) > 0]) | [
"def",
"get_balance",
"(",
"self",
")",
":",
"if",
"not",
"SMSGLOBAL_CHECK_BALANCE_COUNTRY",
":",
"raise",
"Exception",
"(",
"'SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.'",
")",
"params",
"=",
"{",
"'user'",
":",
"self",
".",
"get_username",
"... | Get balance with provider. | [
"Get",
"balance",
"with",
"provider",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smsglobal.py#L32-L52 | train | 199,865 |
stefanfoulis/django-sendsms | sendsms/backends/smsglobal.py | SmsBackend.send_messages | def send_messages(self, sms_messages):
"""
Sends one or more SmsMessage objects and returns the number of sms
messages sent.
"""
if not sms_messages:
return
num_sent = 0
for message in sms_messages:
if self._send(message):
num_sent += 1
return num_sent | python | def send_messages(self, sms_messages):
"""
Sends one or more SmsMessage objects and returns the number of sms
messages sent.
"""
if not sms_messages:
return
num_sent = 0
for message in sms_messages:
if self._send(message):
num_sent += 1
return num_sent | [
"def",
"send_messages",
"(",
"self",
",",
"sms_messages",
")",
":",
"if",
"not",
"sms_messages",
":",
"return",
"num_sent",
"=",
"0",
"for",
"message",
"in",
"sms_messages",
":",
"if",
"self",
".",
"_send",
"(",
"message",
")",
":",
"num_sent",
"+=",
"1"... | Sends one or more SmsMessage objects and returns the number of sms
messages sent. | [
"Sends",
"one",
"or",
"more",
"SmsMessage",
"objects",
"and",
"returns",
"the",
"number",
"of",
"sms",
"messages",
"sent",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smsglobal.py#L54-L66 | train | 199,866 |
stefanfoulis/django-sendsms | sendsms/api.py | send_sms | def send_sms(body, from_phone, to, flash=False, fail_silently=False,
auth_user=None, auth_password=None, connection=None):
"""
Easy wrapper for send a single SMS to a recipient list.
:returns: the number of SMSs sent.
"""
from sendsms.message import SmsMessage
connection = connection or get_connection(
username = auth_user,
password = auth_password,
fail_silently = fail_silently
)
return SmsMessage(body=body, from_phone=from_phone, to=to, \
flash=flash, connection=connection).send() | python | def send_sms(body, from_phone, to, flash=False, fail_silently=False,
auth_user=None, auth_password=None, connection=None):
"""
Easy wrapper for send a single SMS to a recipient list.
:returns: the number of SMSs sent.
"""
from sendsms.message import SmsMessage
connection = connection or get_connection(
username = auth_user,
password = auth_password,
fail_silently = fail_silently
)
return SmsMessage(body=body, from_phone=from_phone, to=to, \
flash=flash, connection=connection).send() | [
"def",
"send_sms",
"(",
"body",
",",
"from_phone",
",",
"to",
",",
"flash",
"=",
"False",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"from",
"sendsms",
... | Easy wrapper for send a single SMS to a recipient list.
:returns: the number of SMSs sent. | [
"Easy",
"wrapper",
"for",
"send",
"a",
"single",
"SMS",
"to",
"a",
"recipient",
"list",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/api.py#L14-L28 | train | 199,867 |
stefanfoulis/django-sendsms | sendsms/backends/smssluzbacz.py | SmsBackend.open | def open(self):
"""Initializes sms.sluzba.cz API library."""
self.client = SmsGateApi(getattr(settings, 'SMS_SLUZBA_API_LOGIN', ''),
getattr(settings, 'SMS_SLUZBA_API_PASSWORD', ''),
getattr(settings, 'SMS_SLUZBA_API_TIMEOUT', 2),
getattr(settings, 'SMS_SLUZBA_API_USE_SSL', True)) | python | def open(self):
"""Initializes sms.sluzba.cz API library."""
self.client = SmsGateApi(getattr(settings, 'SMS_SLUZBA_API_LOGIN', ''),
getattr(settings, 'SMS_SLUZBA_API_PASSWORD', ''),
getattr(settings, 'SMS_SLUZBA_API_TIMEOUT', 2),
getattr(settings, 'SMS_SLUZBA_API_USE_SSL', True)) | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"client",
"=",
"SmsGateApi",
"(",
"getattr",
"(",
"settings",
",",
"'SMS_SLUZBA_API_LOGIN'",
",",
"''",
")",
",",
"getattr",
"(",
"settings",
",",
"'SMS_SLUZBA_API_PASSWORD'",
",",
"''",
")",
",",
"getattr... | Initializes sms.sluzba.cz API library. | [
"Initializes",
"sms",
".",
"sluzba",
".",
"cz",
"API",
"library",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smssluzbacz.py#L59-L64 | train | 199,868 |
stefanfoulis/django-sendsms | sendsms/backends/smssluzbacz.py | SmsBackend.send_messages | def send_messages(self, messages):
"""Sending SMS messages via sms.sluzba.cz API.
Note:
This method returns number of actually sent sms messages
not number of SmsMessage instances processed.
:param messages: list of sms messages
:type messages: list of sendsms.message.SmsMessage instances
:returns: number of sent sms messages
:rtype: int
"""
count = 0
for message in messages:
message_body = unicodedata.normalize('NFKD', unicode(message.body)).encode('ascii', 'ignore')
for tel_number in message.to:
try:
self.client.send(tel_number, message_body, getattr(settings, 'SMS_SLUZBA_API_USE_POST', True))
except Exception:
if self.fail_silently:
log.exception('Error while sending sms via sms.sluzba.cz backend API.')
else:
raise
else:
count += 1
return count | python | def send_messages(self, messages):
"""Sending SMS messages via sms.sluzba.cz API.
Note:
This method returns number of actually sent sms messages
not number of SmsMessage instances processed.
:param messages: list of sms messages
:type messages: list of sendsms.message.SmsMessage instances
:returns: number of sent sms messages
:rtype: int
"""
count = 0
for message in messages:
message_body = unicodedata.normalize('NFKD', unicode(message.body)).encode('ascii', 'ignore')
for tel_number in message.to:
try:
self.client.send(tel_number, message_body, getattr(settings, 'SMS_SLUZBA_API_USE_POST', True))
except Exception:
if self.fail_silently:
log.exception('Error while sending sms via sms.sluzba.cz backend API.')
else:
raise
else:
count += 1
return count | [
"def",
"send_messages",
"(",
"self",
",",
"messages",
")",
":",
"count",
"=",
"0",
"for",
"message",
"in",
"messages",
":",
"message_body",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"unicode",
"(",
"message",
".",
"body",
")",
")",
".",
... | Sending SMS messages via sms.sluzba.cz API.
Note:
This method returns number of actually sent sms messages
not number of SmsMessage instances processed.
:param messages: list of sms messages
:type messages: list of sendsms.message.SmsMessage instances
:returns: number of sent sms messages
:rtype: int | [
"Sending",
"SMS",
"messages",
"via",
"sms",
".",
"sluzba",
".",
"cz",
"API",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/smssluzbacz.py#L70-L97 | train | 199,869 |
stefanfoulis/django-sendsms | sendsms/backends/esendex.py | SmsBackend._send | def _send(self, message):
"""
Private method to send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool
"""
params = {
'EsendexUsername': self.get_username(),
'EsendexPassword': self.get_password(),
'EsendexAccount': self.get_account(),
'EsendexOriginator': message.from_phone,
'EsendexRecipient': ",".join(message.to),
'EsendexBody': message.body,
'EsendexPlainText':'1'
}
if ESENDEX_SANDBOX:
params['EsendexTest'] = '1'
response = requests.post(ESENDEX_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise Exception('Bad status code')
else:
return False
if not response.content.startswith(b'Result'):
if not self.fail_silently:
raise Exception('Bad result')
else:
return False
response = self._parse_response(response.content.decode('utf8'))
if ESENDEX_SANDBOX and response['Result'] == 'Test':
return True
else:
if response['Result'].startswith('OK'):
return True
else:
if not self.fail_silently:
raise Exception('Bad result')
return False | python | def _send(self, message):
"""
Private method to send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool
"""
params = {
'EsendexUsername': self.get_username(),
'EsendexPassword': self.get_password(),
'EsendexAccount': self.get_account(),
'EsendexOriginator': message.from_phone,
'EsendexRecipient': ",".join(message.to),
'EsendexBody': message.body,
'EsendexPlainText':'1'
}
if ESENDEX_SANDBOX:
params['EsendexTest'] = '1'
response = requests.post(ESENDEX_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise Exception('Bad status code')
else:
return False
if not response.content.startswith(b'Result'):
if not self.fail_silently:
raise Exception('Bad result')
else:
return False
response = self._parse_response(response.content.decode('utf8'))
if ESENDEX_SANDBOX and response['Result'] == 'Test':
return True
else:
if response['Result'].startswith('OK'):
return True
else:
if not self.fail_silently:
raise Exception('Bad result')
return False | [
"def",
"_send",
"(",
"self",
",",
"message",
")",
":",
"params",
"=",
"{",
"'EsendexUsername'",
":",
"self",
".",
"get_username",
"(",
")",
",",
"'EsendexPassword'",
":",
"self",
".",
"get_password",
"(",
")",
",",
"'EsendexAccount'",
":",
"self",
".",
"... | Private method to send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool | [
"Private",
"method",
"to",
"send",
"one",
"message",
"."
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/esendex.py#L74-L119 | train | 199,870 |
stefanfoulis/django-sendsms | sendsms/message.py | SmsMessage.send | def send(self, fail_silently=False):
"""
Sends the sms message
"""
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender=self, to=self.to, from_phone=self.from_phone, body=self.body)
return res | python | def send(self, fail_silently=False):
"""
Sends the sms message
"""
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender=self, to=self.to, from_phone=self.from_phone, body=self.body)
return res | [
"def",
"send",
"(",
"self",
",",
"fail_silently",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"to",
":",
"# Don't bother creating the connection if there's nobody to send to",
"return",
"0",
"res",
"=",
"self",
".",
"get_connection",
"(",
"fail_silently",
")... | Sends the sms message | [
"Sends",
"the",
"sms",
"message"
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/message.py#L30-L39 | train | 199,871 |
stefanfoulis/django-sendsms | sendsms/backends/nexmo.py | SmsBackend._send | def _send(self, message):
"""
A helper method that does the actual sending
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool
"""
params = {
'from': message.from_phone,
'to': ",".join(message.to),
'text': message.body,
'api_key': self.get_api_key(),
'api_secret': self.get_api_secret(),
}
print(params)
logger.debug("POST to %r with body: %r", NEXMO_API_URL, params)
return self.parse(NEXMO_API_URL, requests.post(NEXMO_API_URL, data=params)) | python | def _send(self, message):
"""
A helper method that does the actual sending
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool
"""
params = {
'from': message.from_phone,
'to': ",".join(message.to),
'text': message.body,
'api_key': self.get_api_key(),
'api_secret': self.get_api_secret(),
}
print(params)
logger.debug("POST to %r with body: %r", NEXMO_API_URL, params)
return self.parse(NEXMO_API_URL, requests.post(NEXMO_API_URL, data=params)) | [
"def",
"_send",
"(",
"self",
",",
"message",
")",
":",
"params",
"=",
"{",
"'from'",
":",
"message",
".",
"from_phone",
",",
"'to'",
":",
"\",\"",
".",
"join",
"(",
"message",
".",
"to",
")",
",",
"'text'",
":",
"message",
".",
"body",
",",
"'api_k... | A helper method that does the actual sending
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool | [
"A",
"helper",
"method",
"that",
"does",
"the",
"actual",
"sending"
] | 375f469789866853253eceba936ebcff98e83c07 | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/backends/nexmo.py#L120-L142 | train | 199,872 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_market_summary | def get_market_summary(self, market):
"""
Used to get the last 24 hour summary of all active
exchanges in specific coin
Endpoint:
1.1 /public/getmarketsummary
2.0 /pub/Market/GetMarketSummary
:param market: String literal for the market(ex: BTC-XRP)
:type market: str
:return: Summaries of active exchanges of a coin in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/public/getmarketsummary',
API_V2_0: '/pub/Market/GetMarketSummary'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) | python | def get_market_summary(self, market):
"""
Used to get the last 24 hour summary of all active
exchanges in specific coin
Endpoint:
1.1 /public/getmarketsummary
2.0 /pub/Market/GetMarketSummary
:param market: String literal for the market(ex: BTC-XRP)
:type market: str
:return: Summaries of active exchanges of a coin in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/public/getmarketsummary',
API_V2_0: '/pub/Market/GetMarketSummary'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) | [
"def",
"get_market_summary",
"(",
"self",
",",
"market",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/public/getmarketsummary'",
",",
"API_V2_0",
":",
"'/pub/Market/GetMarketSummary'",
"}",
",",
"options",
"=",
"... | Used to get the last 24 hour summary of all active
exchanges in specific coin
Endpoint:
1.1 /public/getmarketsummary
2.0 /pub/Market/GetMarketSummary
:param market: String literal for the market(ex: BTC-XRP)
:type market: str
:return: Summaries of active exchanges of a coin in JSON
:rtype : dict | [
"Used",
"to",
"get",
"the",
"last",
"24",
"hour",
"summary",
"of",
"all",
"active",
"exchanges",
"in",
"specific",
"coin"
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L256-L273 | train | 199,873 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_orderbook | def get_orderbook(self, market, depth_type=BOTH_ORDERBOOK):
"""
Used to get retrieve the orderbook for a given market.
The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned
Endpoint:
1.1 /public/getorderbook
2.0 /pub/Market/GetMarketOrderBook
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param depth_type: buy, sell or both to identify the type of
orderbook to return.
Use constants BUY_ORDERBOOK, SELL_ORDERBOOK, BOTH_ORDERBOOK
:type depth_type: str
:return: Orderbook of market in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/public/getorderbook',
API_V2_0: '/pub/Market/GetMarketOrderBook'
}, options={'market': market, 'marketname': market, 'type': depth_type}, protection=PROTECTION_PUB) | python | def get_orderbook(self, market, depth_type=BOTH_ORDERBOOK):
"""
Used to get retrieve the orderbook for a given market.
The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned
Endpoint:
1.1 /public/getorderbook
2.0 /pub/Market/GetMarketOrderBook
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param depth_type: buy, sell or both to identify the type of
orderbook to return.
Use constants BUY_ORDERBOOK, SELL_ORDERBOOK, BOTH_ORDERBOOK
:type depth_type: str
:return: Orderbook of market in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/public/getorderbook',
API_V2_0: '/pub/Market/GetMarketOrderBook'
}, options={'market': market, 'marketname': market, 'type': depth_type}, protection=PROTECTION_PUB) | [
"def",
"get_orderbook",
"(",
"self",
",",
"market",
",",
"depth_type",
"=",
"BOTH_ORDERBOOK",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/public/getorderbook'",
",",
"API_V2_0",
":",
"'/pub/Market/GetMarketOrderBo... | Used to get retrieve the orderbook for a given market.
The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned
Endpoint:
1.1 /public/getorderbook
2.0 /pub/Market/GetMarketOrderBook
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param depth_type: buy, sell or both to identify the type of
orderbook to return.
Use constants BUY_ORDERBOOK, SELL_ORDERBOOK, BOTH_ORDERBOOK
:type depth_type: str
:return: Orderbook of market in JSON
:rtype : dict | [
"Used",
"to",
"get",
"retrieve",
"the",
"orderbook",
"for",
"a",
"given",
"market",
"."
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L275-L297 | train | 199,874 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_market_history | def get_market_history(self, market):
"""
Used to retrieve the latest trades that have occurred for a
specific market.
Endpoint:
1.1 /market/getmarkethistory
2.0 NO Equivalent
Example ::
{'success': True,
'message': '',
'result': [ {'Id': 5625015,
'TimeStamp': '2017-08-31T01:29:50.427',
'Quantity': 7.31008193,
'Price': 0.00177639,
'Total': 0.01298555,
'FillType': 'FILL',
'OrderType': 'BUY'},
...
]
}
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:return: Market history in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/public/getmarkethistory',
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) | python | def get_market_history(self, market):
"""
Used to retrieve the latest trades that have occurred for a
specific market.
Endpoint:
1.1 /market/getmarkethistory
2.0 NO Equivalent
Example ::
{'success': True,
'message': '',
'result': [ {'Id': 5625015,
'TimeStamp': '2017-08-31T01:29:50.427',
'Quantity': 7.31008193,
'Price': 0.00177639,
'Total': 0.01298555,
'FillType': 'FILL',
'OrderType': 'BUY'},
...
]
}
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:return: Market history in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/public/getmarkethistory',
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB) | [
"def",
"get_market_history",
"(",
"self",
",",
"market",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/public/getmarkethistory'",
",",
"}",
",",
"options",
"=",
"{",
"'market'",
":",
"market",
",",
"'marketnam... | Used to retrieve the latest trades that have occurred for a
specific market.
Endpoint:
1.1 /market/getmarkethistory
2.0 NO Equivalent
Example ::
{'success': True,
'message': '',
'result': [ {'Id': 5625015,
'TimeStamp': '2017-08-31T01:29:50.427',
'Quantity': 7.31008193,
'Price': 0.00177639,
'Total': 0.01298555,
'FillType': 'FILL',
'OrderType': 'BUY'},
...
]
}
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:return: Market history in JSON
:rtype : dict | [
"Used",
"to",
"retrieve",
"the",
"latest",
"trades",
"that",
"have",
"occurred",
"for",
"a",
"specific",
"market",
"."
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L299-L329 | train | 199,875 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.buy_limit | def buy_limit(self, market, quantity, rate):
"""
Used to place a buy order in a specific market. Use buylimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
Endpoint:
1.1 /market/buylimit
2.0 NO Direct equivalent. Use trade_buy for LIMIT and MARKET buys
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/market/buylimit',
}, options={'market': market,
'quantity': quantity,
'rate': rate}, protection=PROTECTION_PRV) | python | def buy_limit(self, market, quantity, rate):
"""
Used to place a buy order in a specific market. Use buylimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
Endpoint:
1.1 /market/buylimit
2.0 NO Direct equivalent. Use trade_buy for LIMIT and MARKET buys
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/market/buylimit',
}, options={'market': market,
'quantity': quantity,
'rate': rate}, protection=PROTECTION_PRV) | [
"def",
"buy_limit",
"(",
"self",
",",
"market",
",",
"quantity",
",",
"rate",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/market/buylimit'",
",",
"}",
",",
"options",
"=",
"{",
"'market'",
":",
"market",... | Used to place a buy order in a specific market. Use buylimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
Endpoint:
1.1 /market/buylimit
2.0 NO Direct equivalent. Use trade_buy for LIMIT and MARKET buys
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict | [
"Used",
"to",
"place",
"a",
"buy",
"order",
"in",
"a",
"specific",
"market",
".",
"Use",
"buylimit",
"to",
"place",
"limit",
"orders",
"Make",
"sure",
"you",
"have",
"the",
"proper",
"permissions",
"set",
"on",
"your",
"API",
"keys",
"for",
"this",
"call... | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L331-L355 | train | 199,876 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_open_orders | def get_open_orders(self, market=None):
"""
Get all orders that you currently have opened.
A specific market can be requested.
Endpoint:
1.1 /market/getopenorders
2.0 /key/market/getopenorders
:param market: String literal for the market (ie. BTC-LTC)
:type market: str
:return: Open orders info in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/market/getopenorders',
API_V2_0: '/key/market/getopenorders'
}, options={'market': market, 'marketname': market} if market else None, protection=PROTECTION_PRV) | python | def get_open_orders(self, market=None):
"""
Get all orders that you currently have opened.
A specific market can be requested.
Endpoint:
1.1 /market/getopenorders
2.0 /key/market/getopenorders
:param market: String literal for the market (ie. BTC-LTC)
:type market: str
:return: Open orders info in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/market/getopenorders',
API_V2_0: '/key/market/getopenorders'
}, options={'market': market, 'marketname': market} if market else None, protection=PROTECTION_PRV) | [
"def",
"get_open_orders",
"(",
"self",
",",
"market",
"=",
"None",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/market/getopenorders'",
",",
"API_V2_0",
":",
"'/key/market/getopenorders'",
"}",
",",
"options",
... | Get all orders that you currently have opened.
A specific market can be requested.
Endpoint:
1.1 /market/getopenorders
2.0 /key/market/getopenorders
:param market: String literal for the market (ie. BTC-LTC)
:type market: str
:return: Open orders info in JSON
:rtype : dict | [
"Get",
"all",
"orders",
"that",
"you",
"currently",
"have",
"opened",
".",
"A",
"specific",
"market",
"can",
"be",
"requested",
"."
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L401-L418 | train | 199,877 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_deposit_address | def get_deposit_address(self, currency):
"""
Used to generate or retrieve an address for a specific currency
Endpoint:
1.1 /account/getdepositaddress
2.0 /key/balance/getdepositaddress
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: Address info in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/account/getdepositaddress',
API_V2_0: '/key/balance/getdepositaddress'
}, options={'currency': currency, 'currencyname': currency}, protection=PROTECTION_PRV) | python | def get_deposit_address(self, currency):
"""
Used to generate or retrieve an address for a specific currency
Endpoint:
1.1 /account/getdepositaddress
2.0 /key/balance/getdepositaddress
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: Address info in JSON
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/account/getdepositaddress',
API_V2_0: '/key/balance/getdepositaddress'
}, options={'currency': currency, 'currencyname': currency}, protection=PROTECTION_PRV) | [
"def",
"get_deposit_address",
"(",
"self",
",",
"currency",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/account/getdepositaddress'",
",",
"API_V2_0",
":",
"'/key/balance/getdepositaddress'",
"}",
",",
"options",
"... | Used to generate or retrieve an address for a specific currency
Endpoint:
1.1 /account/getdepositaddress
2.0 /key/balance/getdepositaddress
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: Address info in JSON
:rtype : dict | [
"Used",
"to",
"generate",
"or",
"retrieve",
"an",
"address",
"for",
"a",
"specific",
"currency"
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L478-L494 | train | 199,878 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.withdraw | def withdraw(self, currency, quantity, address, paymentid=None):
"""
Used to withdraw funds from your account
Endpoint:
1.1 /account/withdraw
2.0 /key/balance/withdrawcurrency
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:param quantity: The quantity of coins to withdraw
:type quantity: float
:param address: The address where to send the funds.
:type address: str
:param paymentid: Optional argument for memos, tags, or other supplemental information for cryptos such as XRP.
:type paymentid: str
:return:
:rtype : dict
"""
options = {
'currency': currency,
'quantity': quantity,
'address': address
}
if paymentid:
options['paymentid'] = paymentid
return self._api_query(path_dict={
API_V1_1: '/account/withdraw',
API_V2_0: '/key/balance/withdrawcurrency'
}, options=options, protection=PROTECTION_PRV) | python | def withdraw(self, currency, quantity, address, paymentid=None):
"""
Used to withdraw funds from your account
Endpoint:
1.1 /account/withdraw
2.0 /key/balance/withdrawcurrency
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:param quantity: The quantity of coins to withdraw
:type quantity: float
:param address: The address where to send the funds.
:type address: str
:param paymentid: Optional argument for memos, tags, or other supplemental information for cryptos such as XRP.
:type paymentid: str
:return:
:rtype : dict
"""
options = {
'currency': currency,
'quantity': quantity,
'address': address
}
if paymentid:
options['paymentid'] = paymentid
return self._api_query(path_dict={
API_V1_1: '/account/withdraw',
API_V2_0: '/key/balance/withdrawcurrency'
}, options=options, protection=PROTECTION_PRV) | [
"def",
"withdraw",
"(",
"self",
",",
"currency",
",",
"quantity",
",",
"address",
",",
"paymentid",
"=",
"None",
")",
":",
"options",
"=",
"{",
"'currency'",
":",
"currency",
",",
"'quantity'",
":",
"quantity",
",",
"'address'",
":",
"address",
"}",
"if"... | Used to withdraw funds from your account
Endpoint:
1.1 /account/withdraw
2.0 /key/balance/withdrawcurrency
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:param quantity: The quantity of coins to withdraw
:type quantity: float
:param address: The address where to send the funds.
:type address: str
:param paymentid: Optional argument for memos, tags, or other supplemental information for cryptos such as XRP.
:type paymentid: str
:return:
:rtype : dict | [
"Used",
"to",
"withdraw",
"funds",
"from",
"your",
"account"
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L496-L525 | train | 199,879 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_order_history | def get_order_history(self, market=None):
"""
Used to retrieve order trade history of account
Endpoint:
1.1 /account/getorderhistory
2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory
:param market: optional a string literal for the market (ie. BTC-LTC).
If omitted, will return for all markets
:type market: str
:return: order history in JSON
:rtype : dict
"""
if market:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/market/GetOrderHistory'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PRV)
else:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/orders/getorderhistory'
}, protection=PROTECTION_PRV) | python | def get_order_history(self, market=None):
"""
Used to retrieve order trade history of account
Endpoint:
1.1 /account/getorderhistory
2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory
:param market: optional a string literal for the market (ie. BTC-LTC).
If omitted, will return for all markets
:type market: str
:return: order history in JSON
:rtype : dict
"""
if market:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/market/GetOrderHistory'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PRV)
else:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/orders/getorderhistory'
}, protection=PROTECTION_PRV) | [
"def",
"get_order_history",
"(",
"self",
",",
"market",
"=",
"None",
")",
":",
"if",
"market",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/account/getorderhistory'",
",",
"API_V2_0",
":",
"'/key/market/GetOrderHistor... | Used to retrieve order trade history of account
Endpoint:
1.1 /account/getorderhistory
2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory
:param market: optional a string literal for the market (ie. BTC-LTC).
If omitted, will return for all markets
:type market: str
:return: order history in JSON
:rtype : dict | [
"Used",
"to",
"retrieve",
"order",
"trade",
"history",
"of",
"account"
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L527-L550 | train | 199,880 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_order | def get_order(self, uuid):
"""
Used to get details of buy or sell order
Endpoint:
1.1 /account/getorder
2.0 /key/orders/getorder
:param uuid: uuid of buy or sell order
:type uuid: str
:return:
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/account/getorder',
API_V2_0: '/key/orders/getorder'
}, options={'uuid': uuid, 'orderid': uuid}, protection=PROTECTION_PRV) | python | def get_order(self, uuid):
"""
Used to get details of buy or sell order
Endpoint:
1.1 /account/getorder
2.0 /key/orders/getorder
:param uuid: uuid of buy or sell order
:type uuid: str
:return:
:rtype : dict
"""
return self._api_query(path_dict={
API_V1_1: '/account/getorder',
API_V2_0: '/key/orders/getorder'
}, options={'uuid': uuid, 'orderid': uuid}, protection=PROTECTION_PRV) | [
"def",
"get_order",
"(",
"self",
",",
"uuid",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/account/getorder'",
",",
"API_V2_0",
":",
"'/key/orders/getorder'",
"}",
",",
"options",
"=",
"{",
"'uuid'",
":",
"... | Used to get details of buy or sell order
Endpoint:
1.1 /account/getorder
2.0 /key/orders/getorder
:param uuid: uuid of buy or sell order
:type uuid: str
:return:
:rtype : dict | [
"Used",
"to",
"get",
"details",
"of",
"buy",
"or",
"sell",
"order"
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L552-L568 | train | 199,881 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.list_markets_by_currency | def list_markets_by_currency(self, currency):
"""
Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param currency: String literal for the currency (ex: LTC)
:type currency: str
:return: List of markets that the currency appears in
:rtype: list
"""
return [market['MarketName'] for market in self.get_markets()['result']
if market['MarketName'].lower().endswith(currency.lower())] | python | def list_markets_by_currency(self, currency):
"""
Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param currency: String literal for the currency (ex: LTC)
:type currency: str
:return: List of markets that the currency appears in
:rtype: list
"""
return [market['MarketName'] for market in self.get_markets()['result']
if market['MarketName'].lower().endswith(currency.lower())] | [
"def",
"list_markets_by_currency",
"(",
"self",
",",
"currency",
")",
":",
"return",
"[",
"market",
"[",
"'MarketName'",
"]",
"for",
"market",
"in",
"self",
".",
"get_markets",
"(",
")",
"[",
"'result'",
"]",
"if",
"market",
"[",
"'MarketName'",
"]",
".",
... | Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param currency: String literal for the currency (ex: LTC)
:type currency: str
:return: List of markets that the currency appears in
:rtype: list | [
"Helper",
"function",
"to",
"see",
"which",
"markets",
"exist",
"for",
"a",
"currency",
"."
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L609-L625 | train | 199,882 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_pending_withdrawals | def get_pending_withdrawals(self, currency=None):
"""
Used to view your pending withdrawals
Endpoint:
1.1 NO EQUIVALENT
2.0 /key/balance/getpendingwithdrawals
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: pending withdrawals in JSON
:rtype : list
"""
return self._api_query(path_dict={
API_V2_0: '/key/balance/getpendingwithdrawals'
}, options={'currencyname': currency} if currency else None,
protection=PROTECTION_PRV) | python | def get_pending_withdrawals(self, currency=None):
"""
Used to view your pending withdrawals
Endpoint:
1.1 NO EQUIVALENT
2.0 /key/balance/getpendingwithdrawals
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: pending withdrawals in JSON
:rtype : list
"""
return self._api_query(path_dict={
API_V2_0: '/key/balance/getpendingwithdrawals'
}, options={'currencyname': currency} if currency else None,
protection=PROTECTION_PRV) | [
"def",
"get_pending_withdrawals",
"(",
"self",
",",
"currency",
"=",
"None",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V2_0",
":",
"'/key/balance/getpendingwithdrawals'",
"}",
",",
"options",
"=",
"{",
"'currencyname'",
":",... | Used to view your pending withdrawals
Endpoint:
1.1 NO EQUIVALENT
2.0 /key/balance/getpendingwithdrawals
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: pending withdrawals in JSON
:rtype : list | [
"Used",
"to",
"view",
"your",
"pending",
"withdrawals"
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L655-L671 | train | 199,883 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | Bittrex.get_candles | def get_candles(self, market, tick_interval):
"""
Used to get all tick candles for a market.
Endpoint:
1.1 NO EQUIVALENT
2.0 /pub/market/GetTicks
Example ::
{ success: true,
message: '',
result:
[ { O: 421.20630125,
H: 424.03951276,
L: 421.20630125,
C: 421.20630125,
V: 0.05187504,
T: '2016-04-08T00:00:00',
BV: 21.87921187 },
{ O: 420.206,
H: 420.206,
L: 416.78743422,
C: 416.78743422,
V: 2.42281573,
T: '2016-04-09T00:00:00',
BV: 1012.63286332 }]
}
:return: Available tick candles in JSON
:rtype: dict
"""
return self._api_query(path_dict={
API_V2_0: '/pub/market/GetTicks'
}, options={
'marketName': market, 'tickInterval': tick_interval
}, protection=PROTECTION_PUB) | python | def get_candles(self, market, tick_interval):
"""
Used to get all tick candles for a market.
Endpoint:
1.1 NO EQUIVALENT
2.0 /pub/market/GetTicks
Example ::
{ success: true,
message: '',
result:
[ { O: 421.20630125,
H: 424.03951276,
L: 421.20630125,
C: 421.20630125,
V: 0.05187504,
T: '2016-04-08T00:00:00',
BV: 21.87921187 },
{ O: 420.206,
H: 420.206,
L: 416.78743422,
C: 416.78743422,
V: 2.42281573,
T: '2016-04-09T00:00:00',
BV: 1012.63286332 }]
}
:return: Available tick candles in JSON
:rtype: dict
"""
return self._api_query(path_dict={
API_V2_0: '/pub/market/GetTicks'
}, options={
'marketName': market, 'tickInterval': tick_interval
}, protection=PROTECTION_PUB) | [
"def",
"get_candles",
"(",
"self",
",",
"market",
",",
"tick_interval",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V2_0",
":",
"'/pub/market/GetTicks'",
"}",
",",
"options",
"=",
"{",
"'marketName'",
":",
"market",
",",
... | Used to get all tick candles for a market.
Endpoint:
1.1 NO EQUIVALENT
2.0 /pub/market/GetTicks
Example ::
{ success: true,
message: '',
result:
[ { O: 421.20630125,
H: 424.03951276,
L: 421.20630125,
C: 421.20630125,
V: 0.05187504,
T: '2016-04-08T00:00:00',
BV: 21.87921187 },
{ O: 420.206,
H: 420.206,
L: 416.78743422,
C: 416.78743422,
V: 2.42281573,
T: '2016-04-09T00:00:00',
BV: 1012.63286332 }]
}
:return: Available tick candles in JSON
:rtype: dict | [
"Used",
"to",
"get",
"all",
"tick",
"candles",
"for",
"a",
"market",
"."
] | 2dbc08e3221e07a9e618eaa025d98ed197d28e31 | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L788-L824 | train | 199,884 |
modlinltd/django-advanced-filters | advanced_filters/admin.py | AdminAdvancedFiltersMixin.changelist_view | def changelist_view(self, request, extra_context=None):
"""Add advanced_filters form to changelist context"""
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return super(AdminAdvancedFiltersMixin, self
).changelist_view(request, extra_context=extra_context) | python | def changelist_view(self, request, extra_context=None):
"""Add advanced_filters form to changelist context"""
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return super(AdminAdvancedFiltersMixin, self
).changelist_view(request, extra_context=extra_context) | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"if",
"extra_context",
"is",
"None",
":",
"extra_context",
"=",
"{",
"}",
"response",
"=",
"self",
".",
"adv_filters_handle",
"(",
"request",
",",
"extra_cont... | Add advanced_filters form to changelist context | [
"Add",
"advanced_filters",
"form",
"to",
"changelist",
"context"
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/admin.py#L93-L102 | train | 199,885 |
modlinltd/django-advanced-filters | advanced_filters/models.py | AdvancedFilter.query | def query(self):
"""
De-serialize, decode and return an ORM query stored in b64_query.
"""
if not self.b64_query:
return None
s = QSerializer(base64=True)
return s.loads(self.b64_query) | python | def query(self):
"""
De-serialize, decode and return an ORM query stored in b64_query.
"""
if not self.b64_query:
return None
s = QSerializer(base64=True)
return s.loads(self.b64_query) | [
"def",
"query",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"b64_query",
":",
"return",
"None",
"s",
"=",
"QSerializer",
"(",
"base64",
"=",
"True",
")",
"return",
"s",
".",
"loads",
"(",
"self",
".",
"b64_query",
")"
] | De-serialize, decode and return an ORM query stored in b64_query. | [
"De",
"-",
"serialize",
"decode",
"and",
"return",
"an",
"ORM",
"query",
"stored",
"in",
"b64_query",
"."
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/models.py#L39-L46 | train | 199,886 |
modlinltd/django-advanced-filters | advanced_filters/models.py | AdvancedFilter.query | def query(self, value):
"""
Serialize an ORM query, Base-64 encode it and set it to
the b64_query field
"""
if not isinstance(value, Q):
raise Exception('Must only be passed a Django (Q)uery object')
s = QSerializer(base64=True)
self.b64_query = s.dumps(value) | python | def query(self, value):
"""
Serialize an ORM query, Base-64 encode it and set it to
the b64_query field
"""
if not isinstance(value, Q):
raise Exception('Must only be passed a Django (Q)uery object')
s = QSerializer(base64=True)
self.b64_query = s.dumps(value) | [
"def",
"query",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Q",
")",
":",
"raise",
"Exception",
"(",
"'Must only be passed a Django (Q)uery object'",
")",
"s",
"=",
"QSerializer",
"(",
"base64",
"=",
"True",
")",
"se... | Serialize an ORM query, Base-64 encode it and set it to
the b64_query field | [
"Serialize",
"an",
"ORM",
"query",
"Base",
"-",
"64",
"encode",
"it",
"and",
"set",
"it",
"to",
"the",
"b64_query",
"field"
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/models.py#L49-L57 | train | 199,887 |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm._build_field_choices | def _build_field_choices(self, fields):
"""
Iterate over passed model fields tuple and update initial choices.
"""
return tuple(sorted(
[(fquery, capfirst(fname)) for fquery, fname in fields.items()],
key=lambda f: f[1].lower())
) + self.FIELD_CHOICES | python | def _build_field_choices(self, fields):
"""
Iterate over passed model fields tuple and update initial choices.
"""
return tuple(sorted(
[(fquery, capfirst(fname)) for fquery, fname in fields.items()],
key=lambda f: f[1].lower())
) + self.FIELD_CHOICES | [
"def",
"_build_field_choices",
"(",
"self",
",",
"fields",
")",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"[",
"(",
"fquery",
",",
"capfirst",
"(",
"fname",
")",
")",
"for",
"fquery",
",",
"fname",
"in",
"fields",
".",
"items",
"(",
")",
"]",
",",
... | Iterate over passed model fields tuple and update initial choices. | [
"Iterate",
"over",
"passed",
"model",
"fields",
"tuple",
"and",
"update",
"initial",
"choices",
"."
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L77-L84 | train | 199,888 |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm._parse_query_dict | def _parse_query_dict(query_data, model):
"""
Take a list of query field dict and return data for form initialization
"""
operator = 'iexact'
if query_data['field'] == '_OR':
query_data['operator'] = operator
return query_data
parts = query_data['field'].split('__')
if len(parts) < 2:
field = parts[0]
else:
if parts[-1] in dict(AdvancedFilterQueryForm.OPERATORS).keys():
field = '__'.join(parts[:-1])
operator = parts[-1]
else:
field = query_data['field']
query_data['field'] = field
mfield = get_fields_from_path(model, query_data['field'])
if not mfield:
raise Exception('Field path "%s" could not be followed to a field'
' in model %s', query_data['field'], model)
else:
mfield = mfield[-1] # get the field object
if query_data['value'] is None:
query_data['operator'] = "isnull"
elif query_data['value'] is True:
query_data['operator'] = "istrue"
elif query_data['value'] is False:
query_data['operator'] = "isfalse"
else:
if isinstance(mfield, DateField):
# this is a date/datetime field
query_data['operator'] = "range" # default
else:
query_data['operator'] = operator # default
if isinstance(query_data.get('value'),
list) and query_data['operator'] == 'range':
date_from = date_to_string(query_data.get('value_from'))
date_to = date_to_string(query_data.get('value_to'))
query_data['value'] = ','.join([date_from, date_to])
return query_data | python | def _parse_query_dict(query_data, model):
"""
Take a list of query field dict and return data for form initialization
"""
operator = 'iexact'
if query_data['field'] == '_OR':
query_data['operator'] = operator
return query_data
parts = query_data['field'].split('__')
if len(parts) < 2:
field = parts[0]
else:
if parts[-1] in dict(AdvancedFilterQueryForm.OPERATORS).keys():
field = '__'.join(parts[:-1])
operator = parts[-1]
else:
field = query_data['field']
query_data['field'] = field
mfield = get_fields_from_path(model, query_data['field'])
if not mfield:
raise Exception('Field path "%s" could not be followed to a field'
' in model %s', query_data['field'], model)
else:
mfield = mfield[-1] # get the field object
if query_data['value'] is None:
query_data['operator'] = "isnull"
elif query_data['value'] is True:
query_data['operator'] = "istrue"
elif query_data['value'] is False:
query_data['operator'] = "isfalse"
else:
if isinstance(mfield, DateField):
# this is a date/datetime field
query_data['operator'] = "range" # default
else:
query_data['operator'] = operator # default
if isinstance(query_data.get('value'),
list) and query_data['operator'] == 'range':
date_from = date_to_string(query_data.get('value_from'))
date_to = date_to_string(query_data.get('value_to'))
query_data['value'] = ','.join([date_from, date_to])
return query_data | [
"def",
"_parse_query_dict",
"(",
"query_data",
",",
"model",
")",
":",
"operator",
"=",
"'iexact'",
"if",
"query_data",
"[",
"'field'",
"]",
"==",
"'_OR'",
":",
"query_data",
"[",
"'operator'",
"]",
"=",
"operator",
"return",
"query_data",
"parts",
"=",
"que... | Take a list of query field dict and return data for form initialization | [
"Take",
"a",
"list",
"of",
"query",
"field",
"dict",
"and",
"return",
"data",
"for",
"form",
"initialization"
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L103-L149 | train | 199,889 |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm.set_range_value | def set_range_value(self, data):
"""
Validates date range by parsing into 2 datetime objects and
validating them both.
"""
dtfrom = data.pop('value_from')
dtto = data.pop('value_to')
if dtfrom is dtto is None:
self.errors['value'] = ['Date range requires values']
raise forms.ValidationError([])
data['value'] = (dtfrom, dtto) | python | def set_range_value(self, data):
"""
Validates date range by parsing into 2 datetime objects and
validating them both.
"""
dtfrom = data.pop('value_from')
dtto = data.pop('value_to')
if dtfrom is dtto is None:
self.errors['value'] = ['Date range requires values']
raise forms.ValidationError([])
data['value'] = (dtfrom, dtto) | [
"def",
"set_range_value",
"(",
"self",
",",
"data",
")",
":",
"dtfrom",
"=",
"data",
".",
"pop",
"(",
"'value_from'",
")",
"dtto",
"=",
"data",
".",
"pop",
"(",
"'value_to'",
")",
"if",
"dtfrom",
"is",
"dtto",
"is",
"None",
":",
"self",
".",
"errors"... | Validates date range by parsing into 2 datetime objects and
validating them both. | [
"Validates",
"date",
"range",
"by",
"parsing",
"into",
"2",
"datetime",
"objects",
"and",
"validating",
"them",
"both",
"."
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L151-L161 | train | 199,890 |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm.make_query | def make_query(self, *args, **kwargs):
""" Returns a Q object from the submitted form """
query = Q() # initial is an empty query
query_dict = self._build_query_dict(self.cleaned_data)
if 'negate' in self.cleaned_data and self.cleaned_data['negate']:
query = query & ~Q(**query_dict)
else:
query = query & Q(**query_dict)
return query | python | def make_query(self, *args, **kwargs):
""" Returns a Q object from the submitted form """
query = Q() # initial is an empty query
query_dict = self._build_query_dict(self.cleaned_data)
if 'negate' in self.cleaned_data and self.cleaned_data['negate']:
query = query & ~Q(**query_dict)
else:
query = query & Q(**query_dict)
return query | [
"def",
"make_query",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"Q",
"(",
")",
"# initial is an empty query",
"query_dict",
"=",
"self",
".",
"_build_query_dict",
"(",
"self",
".",
"cleaned_data",
")",
"if",
"'negate'",... | Returns a Q object from the submitted form | [
"Returns",
"a",
"Q",
"object",
"from",
"the",
"submitted",
"form"
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L171-L179 | train | 199,891 |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterForm.generate_query | def generate_query(self):
""" Reduces multiple queries into a single usable query """
query = Q()
ORed = []
for form in self._non_deleted_forms:
if not hasattr(form, 'cleaned_data'):
continue
if form.cleaned_data['field'] == "_OR":
ORed.append(query)
query = Q()
else:
query = query & form.make_query()
if ORed:
if query: # add last query for OR if any
ORed.append(query)
query = reduce(operator.or_, ORed)
return query | python | def generate_query(self):
""" Reduces multiple queries into a single usable query """
query = Q()
ORed = []
for form in self._non_deleted_forms:
if not hasattr(form, 'cleaned_data'):
continue
if form.cleaned_data['field'] == "_OR":
ORed.append(query)
query = Q()
else:
query = query & form.make_query()
if ORed:
if query: # add last query for OR if any
ORed.append(query)
query = reduce(operator.or_, ORed)
return query | [
"def",
"generate_query",
"(",
"self",
")",
":",
"query",
"=",
"Q",
"(",
")",
"ORed",
"=",
"[",
"]",
"for",
"form",
"in",
"self",
".",
"_non_deleted_forms",
":",
"if",
"not",
"hasattr",
"(",
"form",
",",
"'cleaned_data'",
")",
":",
"continue",
"if",
"... | Reduces multiple queries into a single usable query | [
"Reduces",
"multiple",
"queries",
"into",
"a",
"single",
"usable",
"query"
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L322-L338 | train | 199,892 |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterForm.initialize_form | def initialize_form(self, instance, model, data=None, extra=None):
""" Takes a "finalized" query and generate it's form data """
model_fields = self.get_fields_from_model(model, self._filter_fields)
forms = []
if instance:
for field_data in instance.list_fields():
forms.append(
AdvancedFilterQueryForm._parse_query_dict(
field_data, model))
formset = AFQFormSetNoExtra if not extra else AFQFormSet
self.fields_formset = formset(
data=data,
initial=forms or None,
model_fields=model_fields
) | python | def initialize_form(self, instance, model, data=None, extra=None):
""" Takes a "finalized" query and generate it's form data """
model_fields = self.get_fields_from_model(model, self._filter_fields)
forms = []
if instance:
for field_data in instance.list_fields():
forms.append(
AdvancedFilterQueryForm._parse_query_dict(
field_data, model))
formset = AFQFormSetNoExtra if not extra else AFQFormSet
self.fields_formset = formset(
data=data,
initial=forms or None,
model_fields=model_fields
) | [
"def",
"initialize_form",
"(",
"self",
",",
"instance",
",",
"model",
",",
"data",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"model_fields",
"=",
"self",
".",
"get_fields_from_model",
"(",
"model",
",",
"self",
".",
"_filter_fields",
")",
"forms",
... | Takes a "finalized" query and generate it's form data | [
"Takes",
"a",
"finalized",
"query",
"and",
"generate",
"it",
"s",
"form",
"data"
] | ba51e6946d1652796a82b2b95cceffbe1190a227 | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L340-L356 | train | 199,893 |
cameronbwhite/Flask-CAS | flask_cas/routing.py | login | def login():
"""
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS will respond to this
route with the ticket in the url. The ticket is then validated.
If validation was successful the logged in username is saved in
the user's session under the key `CAS_USERNAME_SESSION_KEY` and
the user's attributes are saved under the key
'CAS_USERNAME_ATTRIBUTE_KEY'
"""
cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']
redirect_url = create_cas_login_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGIN_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True))
if 'ticket' in flask.request.args:
flask.session[cas_token_session_key] = flask.request.args['ticket']
if cas_token_session_key in flask.session:
if validate(flask.session[cas_token_session_key]):
if 'CAS_AFTER_LOGIN_SESSION_URL' in flask.session:
redirect_url = flask.session.pop('CAS_AFTER_LOGIN_SESSION_URL')
elif flask.request.args.get('origin'):
redirect_url = flask.request.args['origin']
else:
redirect_url = flask.url_for(
current_app.config['CAS_AFTER_LOGIN'])
else:
del flask.session[cas_token_session_key]
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url) | python | def login():
"""
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS will respond to this
route with the ticket in the url. The ticket is then validated.
If validation was successful the logged in username is saved in
the user's session under the key `CAS_USERNAME_SESSION_KEY` and
the user's attributes are saved under the key
'CAS_USERNAME_ATTRIBUTE_KEY'
"""
cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']
redirect_url = create_cas_login_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGIN_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True))
if 'ticket' in flask.request.args:
flask.session[cas_token_session_key] = flask.request.args['ticket']
if cas_token_session_key in flask.session:
if validate(flask.session[cas_token_session_key]):
if 'CAS_AFTER_LOGIN_SESSION_URL' in flask.session:
redirect_url = flask.session.pop('CAS_AFTER_LOGIN_SESSION_URL')
elif flask.request.args.get('origin'):
redirect_url = flask.request.args['origin']
else:
redirect_url = flask.url_for(
current_app.config['CAS_AFTER_LOGIN'])
else:
del flask.session[cas_token_session_key]
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url) | [
"def",
"login",
"(",
")",
":",
"cas_token_session_key",
"=",
"current_app",
".",
"config",
"[",
"'CAS_TOKEN_SESSION_KEY'",
"]",
"redirect_url",
"=",
"create_cas_login_url",
"(",
"current_app",
".",
"config",
"[",
"'CAS_SERVER'",
"]",
",",
"current_app",
".",
"conf... | This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS will respond to this
route with the ticket in the url. The ticket is then validated.
If validation was successful the logged in username is saved in
the user's session under the key `CAS_USERNAME_SESSION_KEY` and
the user's attributes are saved under the key
'CAS_USERNAME_ATTRIBUTE_KEY' | [
"This",
"route",
"has",
"two",
"purposes",
".",
"First",
"it",
"is",
"used",
"by",
"the",
"user",
"to",
"login",
".",
"Second",
"it",
"is",
"used",
"by",
"the",
"CAS",
"to",
"respond",
"with",
"the",
"ticket",
"after",
"the",
"user",
"logs",
"in",
"s... | f85173938654cb9b9316a5c869000b74b008422e | https://github.com/cameronbwhite/Flask-CAS/blob/f85173938654cb9b9316a5c869000b74b008422e/flask_cas/routing.py#L18-L58 | train | 199,894 |
cameronbwhite/Flask-CAS | flask_cas/routing.py | logout | def logout():
"""
When the user accesses this route they are logged out.
"""
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
if cas_username_session_key in flask.session:
del flask.session[cas_username_session_key]
if cas_attributes_session_key in flask.session:
del flask.session[cas_attributes_session_key]
if(current_app.config['CAS_AFTER_LOGOUT'] is not None):
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'],
current_app.config['CAS_AFTER_LOGOUT'])
else:
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'])
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url) | python | def logout():
"""
When the user accesses this route they are logged out.
"""
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
if cas_username_session_key in flask.session:
del flask.session[cas_username_session_key]
if cas_attributes_session_key in flask.session:
del flask.session[cas_attributes_session_key]
if(current_app.config['CAS_AFTER_LOGOUT'] is not None):
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'],
current_app.config['CAS_AFTER_LOGOUT'])
else:
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'])
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url) | [
"def",
"logout",
"(",
")",
":",
"cas_username_session_key",
"=",
"current_app",
".",
"config",
"[",
"'CAS_USERNAME_SESSION_KEY'",
"]",
"cas_attributes_session_key",
"=",
"current_app",
".",
"config",
"[",
"'CAS_ATTRIBUTES_SESSION_KEY'",
"]",
"if",
"cas_username_session_ke... | When the user accesses this route they are logged out. | [
"When",
"the",
"user",
"accesses",
"this",
"route",
"they",
"are",
"logged",
"out",
"."
] | f85173938654cb9b9316a5c869000b74b008422e | https://github.com/cameronbwhite/Flask-CAS/blob/f85173938654cb9b9316a5c869000b74b008422e/flask_cas/routing.py#L62-L87 | train | 199,895 |
cameronbwhite/Flask-CAS | flask_cas/routing.py | validate | def validate(ticket):
"""
Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is saved under the key 'CAS_ATTRIBUTES_SESSION_KEY'.
"""
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
current_app.logger.debug("validating token {0}".format(ticket))
cas_validate_url = create_cas_validate_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_VALIDATE_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True),
ticket)
current_app.logger.debug("Making GET request to {0}".format(
cas_validate_url))
xml_from_dict = {}
isValid = False
try:
xmldump = urlopen(cas_validate_url).read().strip().decode('utf8', 'ignore')
xml_from_dict = parse(xmldump)
isValid = True if "cas:authenticationSuccess" in xml_from_dict["cas:serviceResponse"] else False
except ValueError:
current_app.logger.error("CAS returned unexpected result")
if isValid:
current_app.logger.debug("valid")
xml_from_dict = xml_from_dict["cas:serviceResponse"]["cas:authenticationSuccess"]
username = xml_from_dict["cas:user"]
flask.session[cas_username_session_key] = username
if "cas:attributes" in xml_from_dict:
attributes = xml_from_dict["cas:attributes"]
if "cas:memberOf" in attributes:
attributes["cas:memberOf"] = attributes["cas:memberOf"].lstrip('[').rstrip(']').split(',')
for group_number in range(0, len(attributes['cas:memberOf'])):
attributes['cas:memberOf'][group_number] = attributes['cas:memberOf'][group_number].lstrip(' ').rstrip(' ')
flask.session[cas_attributes_session_key] = attributes
else:
current_app.logger.debug("invalid")
return isValid | python | def validate(ticket):
"""
Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is saved under the key 'CAS_ATTRIBUTES_SESSION_KEY'.
"""
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
current_app.logger.debug("validating token {0}".format(ticket))
cas_validate_url = create_cas_validate_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_VALIDATE_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True),
ticket)
current_app.logger.debug("Making GET request to {0}".format(
cas_validate_url))
xml_from_dict = {}
isValid = False
try:
xmldump = urlopen(cas_validate_url).read().strip().decode('utf8', 'ignore')
xml_from_dict = parse(xmldump)
isValid = True if "cas:authenticationSuccess" in xml_from_dict["cas:serviceResponse"] else False
except ValueError:
current_app.logger.error("CAS returned unexpected result")
if isValid:
current_app.logger.debug("valid")
xml_from_dict = xml_from_dict["cas:serviceResponse"]["cas:authenticationSuccess"]
username = xml_from_dict["cas:user"]
flask.session[cas_username_session_key] = username
if "cas:attributes" in xml_from_dict:
attributes = xml_from_dict["cas:attributes"]
if "cas:memberOf" in attributes:
attributes["cas:memberOf"] = attributes["cas:memberOf"].lstrip('[').rstrip(']').split(',')
for group_number in range(0, len(attributes['cas:memberOf'])):
attributes['cas:memberOf'][group_number] = attributes['cas:memberOf'][group_number].lstrip(' ').rstrip(' ')
flask.session[cas_attributes_session_key] = attributes
else:
current_app.logger.debug("invalid")
return isValid | [
"def",
"validate",
"(",
"ticket",
")",
":",
"cas_username_session_key",
"=",
"current_app",
".",
"config",
"[",
"'CAS_USERNAME_SESSION_KEY'",
"]",
"cas_attributes_session_key",
"=",
"current_app",
".",
"config",
"[",
"'CAS_ATTRIBUTES_SESSION_KEY'",
"]",
"current_app",
"... | Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is saved under the key 'CAS_ATTRIBUTES_SESSION_KEY'. | [
"Will",
"attempt",
"to",
"validate",
"the",
"ticket",
".",
"If",
"validation",
"fails",
"then",
"False",
"is",
"returned",
".",
"If",
"validation",
"is",
"successful",
"then",
"True",
"is",
"returned",
"and",
"the",
"validated",
"username",
"is",
"saved",
"i... | f85173938654cb9b9316a5c869000b74b008422e | https://github.com/cameronbwhite/Flask-CAS/blob/f85173938654cb9b9316a5c869000b74b008422e/flask_cas/routing.py#L90-L141 | train | 199,896 |
cameronbwhite/Flask-CAS | flask_cas/cas_urls.py | create_url | def create_url(base, path=None, *query):
""" Create a url.
Creates a url by combining base, path, and the query's list of
key/value pairs. Escaping is handled automatically. Any
key/value pair with a value that is None is ignored.
Keyword arguments:
base -- The left most part of the url (ex. http://localhost:5000).
path -- The path after the base (ex. /foo/bar).
query -- A list of key value pairs (ex. [('key', 'value')]).
Example usage:
>>> create_url(
... 'http://localhost:5000',
... 'foo/bar',
... ('key1', 'value'),
... ('key2', None), # Will not include None
... ('url', 'http://example.com'),
... )
'http://localhost:5000/foo/bar?key1=value&url=http%3A%2F%2Fexample.com'
"""
url = base
# Add the path to the url if it's not None.
if path is not None:
url = urljoin(url, quote(path))
# Remove key/value pairs with None values.
query = filter(lambda pair: pair[1] is not None, query)
# Add the query string to the url
url = urljoin(url, '?{0}'.format(urlencode(list(query))))
return url | python | def create_url(base, path=None, *query):
""" Create a url.
Creates a url by combining base, path, and the query's list of
key/value pairs. Escaping is handled automatically. Any
key/value pair with a value that is None is ignored.
Keyword arguments:
base -- The left most part of the url (ex. http://localhost:5000).
path -- The path after the base (ex. /foo/bar).
query -- A list of key value pairs (ex. [('key', 'value')]).
Example usage:
>>> create_url(
... 'http://localhost:5000',
... 'foo/bar',
... ('key1', 'value'),
... ('key2', None), # Will not include None
... ('url', 'http://example.com'),
... )
'http://localhost:5000/foo/bar?key1=value&url=http%3A%2F%2Fexample.com'
"""
url = base
# Add the path to the url if it's not None.
if path is not None:
url = urljoin(url, quote(path))
# Remove key/value pairs with None values.
query = filter(lambda pair: pair[1] is not None, query)
# Add the query string to the url
url = urljoin(url, '?{0}'.format(urlencode(list(query))))
return url | [
"def",
"create_url",
"(",
"base",
",",
"path",
"=",
"None",
",",
"*",
"query",
")",
":",
"url",
"=",
"base",
"# Add the path to the url if it's not None.",
"if",
"path",
"is",
"not",
"None",
":",
"url",
"=",
"urljoin",
"(",
"url",
",",
"quote",
"(",
"pat... | Create a url.
Creates a url by combining base, path, and the query's list of
key/value pairs. Escaping is handled automatically. Any
key/value pair with a value that is None is ignored.
Keyword arguments:
base -- The left most part of the url (ex. http://localhost:5000).
path -- The path after the base (ex. /foo/bar).
query -- A list of key value pairs (ex. [('key', 'value')]).
Example usage:
>>> create_url(
... 'http://localhost:5000',
... 'foo/bar',
... ('key1', 'value'),
... ('key2', None), # Will not include None
... ('url', 'http://example.com'),
... )
'http://localhost:5000/foo/bar?key1=value&url=http%3A%2F%2Fexample.com' | [
"Create",
"a",
"url",
"."
] | f85173938654cb9b9316a5c869000b74b008422e | https://github.com/cameronbwhite/Flask-CAS/blob/f85173938654cb9b9316a5c869000b74b008422e/flask_cas/cas_urls.py#L17-L47 | train | 199,897 |
cameronbwhite/Flask-CAS | flask_cas/cas_urls.py | create_cas_login_url | def create_cas_login_url(cas_url, cas_route, service, renew=None, gateway=None):
""" Create a CAS login URL .
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas)
service -- (ex. http://localhost:5000/login)
renew -- "true" or "false"
gateway -- "true" or "false"
Example usage:
>>> create_cas_login_url(
... 'http://sso.pdx.edu',
... '/cas',
... 'http://localhost:5000',
... )
'http://sso.pdx.edu/cas?service=http%3A%2F%2Flocalhost%3A5000'
"""
return create_url(
cas_url,
cas_route,
('service', service),
('renew', renew),
('gateway', gateway),
) | python | def create_cas_login_url(cas_url, cas_route, service, renew=None, gateway=None):
""" Create a CAS login URL .
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas)
service -- (ex. http://localhost:5000/login)
renew -- "true" or "false"
gateway -- "true" or "false"
Example usage:
>>> create_cas_login_url(
... 'http://sso.pdx.edu',
... '/cas',
... 'http://localhost:5000',
... )
'http://sso.pdx.edu/cas?service=http%3A%2F%2Flocalhost%3A5000'
"""
return create_url(
cas_url,
cas_route,
('service', service),
('renew', renew),
('gateway', gateway),
) | [
"def",
"create_cas_login_url",
"(",
"cas_url",
",",
"cas_route",
",",
"service",
",",
"renew",
"=",
"None",
",",
"gateway",
"=",
"None",
")",
":",
"return",
"create_url",
"(",
"cas_url",
",",
"cas_route",
",",
"(",
"'service'",
",",
"service",
")",
",",
... | Create a CAS login URL .
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas)
service -- (ex. http://localhost:5000/login)
renew -- "true" or "false"
gateway -- "true" or "false"
Example usage:
>>> create_cas_login_url(
... 'http://sso.pdx.edu',
... '/cas',
... 'http://localhost:5000',
... )
'http://sso.pdx.edu/cas?service=http%3A%2F%2Flocalhost%3A5000' | [
"Create",
"a",
"CAS",
"login",
"URL",
"."
] | f85173938654cb9b9316a5c869000b74b008422e | https://github.com/cameronbwhite/Flask-CAS/blob/f85173938654cb9b9316a5c869000b74b008422e/flask_cas/cas_urls.py#L50-L74 | train | 199,898 |
cameronbwhite/Flask-CAS | flask_cas/cas_urls.py | create_cas_validate_url | def create_cas_validate_url(cas_url, cas_route, service, ticket,
renew=None):
""" Create a CAS validate URL.
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas/serviceValidate)
service -- (ex. http://localhost:5000/login)
ticket -- (ex. 'ST-58274-x839euFek492ou832Eena7ee-cas')
renew -- "true" or "false"
Example usage:
>>> create_cas_validate_url(
... 'http://sso.pdx.edu',
... '/cas/serviceValidate',
... 'http://localhost:5000/login',
... 'ST-58274-x839euFek492ou832Eena7ee-cas'
... )
'http://sso.pdx.edu/cas/serviceValidate?service=http%3A%2F%2Flocalhost%3A5000%2Flogin&ticket=ST-58274-x839euFek492ou832Eena7ee-cas'
"""
return create_url(
cas_url,
cas_route,
('service', service),
('ticket', ticket),
('renew', renew),
) | python | def create_cas_validate_url(cas_url, cas_route, service, ticket,
renew=None):
""" Create a CAS validate URL.
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas/serviceValidate)
service -- (ex. http://localhost:5000/login)
ticket -- (ex. 'ST-58274-x839euFek492ou832Eena7ee-cas')
renew -- "true" or "false"
Example usage:
>>> create_cas_validate_url(
... 'http://sso.pdx.edu',
... '/cas/serviceValidate',
... 'http://localhost:5000/login',
... 'ST-58274-x839euFek492ou832Eena7ee-cas'
... )
'http://sso.pdx.edu/cas/serviceValidate?service=http%3A%2F%2Flocalhost%3A5000%2Flogin&ticket=ST-58274-x839euFek492ou832Eena7ee-cas'
"""
return create_url(
cas_url,
cas_route,
('service', service),
('ticket', ticket),
('renew', renew),
) | [
"def",
"create_cas_validate_url",
"(",
"cas_url",
",",
"cas_route",
",",
"service",
",",
"ticket",
",",
"renew",
"=",
"None",
")",
":",
"return",
"create_url",
"(",
"cas_url",
",",
"cas_route",
",",
"(",
"'service'",
",",
"service",
")",
",",
"(",
"'ticket... | Create a CAS validate URL.
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas/serviceValidate)
service -- (ex. http://localhost:5000/login)
ticket -- (ex. 'ST-58274-x839euFek492ou832Eena7ee-cas')
renew -- "true" or "false"
Example usage:
>>> create_cas_validate_url(
... 'http://sso.pdx.edu',
... '/cas/serviceValidate',
... 'http://localhost:5000/login',
... 'ST-58274-x839euFek492ou832Eena7ee-cas'
... )
'http://sso.pdx.edu/cas/serviceValidate?service=http%3A%2F%2Flocalhost%3A5000%2Flogin&ticket=ST-58274-x839euFek492ou832Eena7ee-cas' | [
"Create",
"a",
"CAS",
"validate",
"URL",
"."
] | f85173938654cb9b9316a5c869000b74b008422e | https://github.com/cameronbwhite/Flask-CAS/blob/f85173938654cb9b9316a5c869000b74b008422e/flask_cas/cas_urls.py#L100-L126 | train | 199,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.