id int32 0 252k | 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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
31,600 | sdispater/poetry | poetry/packages/dependency.py | Dependency.accepts | def accepts(self, package): # type: (poetry.packages.Package) -> bool
"""
Determines if the given package matches this dependency.
"""
return (
self._name == package.name
and self._constraint.allows(package.version)
and (not package.is_prerelease() or self.allows_prereleases())
) | python | def accepts(self, package): # type: (poetry.packages.Package) -> bool
"""
Determines if the given package matches this dependency.
"""
return (
self._name == package.name
and self._constraint.allows(package.version)
and (not package.is_prerelease() or self.allows_prereleases())
) | [
"def",
"accepts",
"(",
"self",
",",
"package",
")",
":",
"# type: (poetry.packages.Package) -> bool",
"return",
"(",
"self",
".",
"_name",
"==",
"package",
".",
"name",
"and",
"self",
".",
"_constraint",
".",
"allows",
"(",
"package",
".",
"version",
")",
"a... | Determines if the given package matches this dependency. | [
"Determines",
"if",
"the",
"given",
"package",
"matches",
"this",
"dependency",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/dependency.py#L166-L174 |
31,601 | sdispater/poetry | poetry/packages/dependency.py | Dependency.deactivate | def deactivate(self):
"""
Set the dependency as optional.
"""
if not self._optional:
self._optional = True
self._activated = False | python | def deactivate(self):
"""
Set the dependency as optional.
"""
if not self._optional:
self._optional = True
self._activated = False | [
"def",
"deactivate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_optional",
":",
"self",
".",
"_optional",
"=",
"True",
"self",
".",
"_activated",
"=",
"False"
] | Set the dependency as optional. | [
"Set",
"the",
"dependency",
"as",
"optional",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/dependency.py#L282-L289 |
31,602 | sdispater/poetry | poetry/mixology/term.py | Term.satisfies | def satisfies(self, other): # type: (Term) -> bool
"""
Returns whether this term satisfies another.
"""
return (
self.dependency.name == other.dependency.name
and self.relation(other) == SetRelation.SUBSET
) | python | def satisfies(self, other): # type: (Term) -> bool
"""
Returns whether this term satisfies another.
"""
return (
self.dependency.name == other.dependency.name
and self.relation(other) == SetRelation.SUBSET
) | [
"def",
"satisfies",
"(",
"self",
",",
"other",
")",
":",
"# type: (Term) -> bool",
"return",
"(",
"self",
".",
"dependency",
".",
"name",
"==",
"other",
".",
"dependency",
".",
"name",
"and",
"self",
".",
"relation",
"(",
"other",
")",
"==",
"SetRelation",... | Returns whether this term satisfies another. | [
"Returns",
"whether",
"this",
"term",
"satisfies",
"another",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/term.py#L36-L43 |
31,603 | sdispater/poetry | poetry/mixology/term.py | Term.relation | def relation(self, other): # type: (Term) -> int
"""
Returns the relationship between the package versions
allowed by this term and another.
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
other_constraint = other.constraint
if other.is_positive():
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.DISJOINT
# foo ^1.5.0 is a subset of foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.SUBSET
# foo ^2.0.0 is disjoint with foo ^1.0.0
if not self.constraint.allows_any(other_constraint):
return SetRelation.DISJOINT
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is disjoint with foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.DISJOINT
# not foo ^1.5.0 overlaps foo ^1.0.0
# not foo ^2.0.0 is a superset of foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.SUBSET
# foo ^2.0.0 is a subset of not foo ^1.0.0
if not other_constraint.allows_any(self.constraint):
return SetRelation.SUBSET
# foo ^1.5.0 is disjoint with not foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.DISJOINT
# foo ^1.0.0 overlaps not foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is a subset of not foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.SUBSET
# not foo ^2.0.0 overlaps not foo ^1.0.0
# not foo ^1.5.0 is a superset of not foo ^1.0.0
return SetRelation.OVERLAPPING | python | def relation(self, other): # type: (Term) -> int
"""
Returns the relationship between the package versions
allowed by this term and another.
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
other_constraint = other.constraint
if other.is_positive():
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.DISJOINT
# foo ^1.5.0 is a subset of foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.SUBSET
# foo ^2.0.0 is disjoint with foo ^1.0.0
if not self.constraint.allows_any(other_constraint):
return SetRelation.DISJOINT
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is disjoint with foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.DISJOINT
# not foo ^1.5.0 overlaps foo ^1.0.0
# not foo ^2.0.0 is a superset of foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if self.is_positive():
if not self._compatible_dependency(other.dependency):
return SetRelation.SUBSET
# foo ^2.0.0 is a subset of not foo ^1.0.0
if not other_constraint.allows_any(self.constraint):
return SetRelation.SUBSET
# foo ^1.5.0 is disjoint with not foo ^1.0.0
if other_constraint.allows_all(self.constraint):
return SetRelation.DISJOINT
# foo ^1.0.0 overlaps not foo ^1.5.0
return SetRelation.OVERLAPPING
else:
if not self._compatible_dependency(other.dependency):
return SetRelation.OVERLAPPING
# not foo ^1.0.0 is a subset of not foo ^1.5.0
if self.constraint.allows_all(other_constraint):
return SetRelation.SUBSET
# not foo ^2.0.0 overlaps not foo ^1.0.0
# not foo ^1.5.0 is a superset of not foo ^1.0.0
return SetRelation.OVERLAPPING | [
"def",
"relation",
"(",
"self",
",",
"other",
")",
":",
"# type: (Term) -> int",
"if",
"self",
".",
"dependency",
".",
"name",
"!=",
"other",
".",
"dependency",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"{} should refer to {}\"",
".",
"format",
"(",
"o... | Returns the relationship between the package versions
allowed by this term and another. | [
"Returns",
"the",
"relationship",
"between",
"the",
"package",
"versions",
"allowed",
"by",
"this",
"term",
"and",
"another",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/term.py#L45-L107 |
31,604 | sdispater/poetry | poetry/mixology/term.py | Term.intersect | def intersect(self, other): # type: (Term) -> Union[Term, None]
"""
Returns a Term that represents the packages
allowed by both this term and another
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
if self._compatible_dependency(other.dependency):
if self.is_positive() != other.is_positive():
# foo ^1.0.0 β© not foo ^1.5.0 β foo >=1.0.0 <1.5.0
positive = self if self.is_positive() else other
negative = other if self.is_positive() else self
return self._non_empty_term(
positive.constraint.difference(negative.constraint), True
)
elif self.is_positive():
# foo ^1.0.0 β© foo >=1.5.0 <3.0.0 β foo ^1.5.0
return self._non_empty_term(
self.constraint.intersect(other.constraint), True
)
else:
# not foo ^1.0.0 β© not foo >=1.5.0 <3.0.0 β not foo >=1.0.0 <3.0.0
return self._non_empty_term(
self.constraint.union(other.constraint), False
)
elif self.is_positive() != other.is_positive():
return self if self.is_positive() else other
else:
return | python | def intersect(self, other): # type: (Term) -> Union[Term, None]
"""
Returns a Term that represents the packages
allowed by both this term and another
"""
if self.dependency.name != other.dependency.name:
raise ValueError(
"{} should refer to {}".format(other, self.dependency.name)
)
if self._compatible_dependency(other.dependency):
if self.is_positive() != other.is_positive():
# foo ^1.0.0 β© not foo ^1.5.0 β foo >=1.0.0 <1.5.0
positive = self if self.is_positive() else other
negative = other if self.is_positive() else self
return self._non_empty_term(
positive.constraint.difference(negative.constraint), True
)
elif self.is_positive():
# foo ^1.0.0 β© foo >=1.5.0 <3.0.0 β foo ^1.5.0
return self._non_empty_term(
self.constraint.intersect(other.constraint), True
)
else:
# not foo ^1.0.0 β© not foo >=1.5.0 <3.0.0 β not foo >=1.0.0 <3.0.0
return self._non_empty_term(
self.constraint.union(other.constraint), False
)
elif self.is_positive() != other.is_positive():
return self if self.is_positive() else other
else:
return | [
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"# type: (Term) -> Union[Term, None]",
"if",
"self",
".",
"dependency",
".",
"name",
"!=",
"other",
".",
"dependency",
".",
"name",
":",
"raise",
"ValueError",
"(",
"\"{} should refer to {}\"",
".",
"forma... | Returns a Term that represents the packages
allowed by both this term and another | [
"Returns",
"a",
"Term",
"that",
"represents",
"the",
"packages",
"allowed",
"by",
"both",
"this",
"term",
"and",
"another"
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/mixology/term.py#L109-L141 |
31,605 | sdispater/poetry | poetry/masonry/builders/builder.py | Builder.find_files_to_add | def find_files_to_add(self, exclude_build=True): # type: (bool) -> list
"""
Finds all files to add to the tarball
"""
to_add = []
for include in self._module.includes:
for file in include.elements:
if "__pycache__" in str(file):
continue
if file.is_dir():
continue
file = file.relative_to(self._path)
if self.is_excluded(file) and isinstance(include, PackageInclude):
continue
if file.suffix == ".pyc":
continue
if file in to_add:
# Skip duplicates
continue
self._io.writeln(
" - Adding: <comment>{}</comment>".format(str(file)),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(file)
# Include project files
self._io.writeln(
" - Adding: <comment>pyproject.toml</comment>",
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(Path("pyproject.toml"))
# If a license file exists, add it
for license_file in self._path.glob("LICENSE*"):
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
license_file.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(license_file.relative_to(self._path))
# If a README is specificed we need to include it
# to avoid errors
if "readme" in self._poetry.local_config:
readme = self._path / self._poetry.local_config["readme"]
if readme.exists():
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
readme.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(readme.relative_to(self._path))
# If a build script is specified and explicitely required
# we add it to the list of files
if self._package.build and not exclude_build:
to_add.append(Path(self._package.build))
return sorted(to_add) | python | def find_files_to_add(self, exclude_build=True): # type: (bool) -> list
"""
Finds all files to add to the tarball
"""
to_add = []
for include in self._module.includes:
for file in include.elements:
if "__pycache__" in str(file):
continue
if file.is_dir():
continue
file = file.relative_to(self._path)
if self.is_excluded(file) and isinstance(include, PackageInclude):
continue
if file.suffix == ".pyc":
continue
if file in to_add:
# Skip duplicates
continue
self._io.writeln(
" - Adding: <comment>{}</comment>".format(str(file)),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(file)
# Include project files
self._io.writeln(
" - Adding: <comment>pyproject.toml</comment>",
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(Path("pyproject.toml"))
# If a license file exists, add it
for license_file in self._path.glob("LICENSE*"):
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
license_file.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(license_file.relative_to(self._path))
# If a README is specificed we need to include it
# to avoid errors
if "readme" in self._poetry.local_config:
readme = self._path / self._poetry.local_config["readme"]
if readme.exists():
self._io.writeln(
" - Adding: <comment>{}</comment>".format(
readme.relative_to(self._path)
),
verbosity=self._io.VERBOSITY_VERY_VERBOSE,
)
to_add.append(readme.relative_to(self._path))
# If a build script is specified and explicitely required
# we add it to the list of files
if self._package.build and not exclude_build:
to_add.append(Path(self._package.build))
return sorted(to_add) | [
"def",
"find_files_to_add",
"(",
"self",
",",
"exclude_build",
"=",
"True",
")",
":",
"# type: (bool) -> list",
"to_add",
"=",
"[",
"]",
"for",
"include",
"in",
"self",
".",
"_module",
".",
"includes",
":",
"for",
"file",
"in",
"include",
".",
"elements",
... | Finds all files to add to the tarball | [
"Finds",
"all",
"files",
"to",
"add",
"to",
"the",
"tarball"
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/builders/builder.py#L89-L156 |
31,606 | sdispater/poetry | poetry/packages/locker.py | Locker.is_fresh | def is_fresh(self): # type: () -> bool
"""
Checks whether the lock file is still up to date with the current hash.
"""
lock = self._lock.read()
metadata = lock.get("metadata", {})
if "content-hash" in metadata:
return self._content_hash == lock["metadata"]["content-hash"]
return False | python | def is_fresh(self): # type: () -> bool
"""
Checks whether the lock file is still up to date with the current hash.
"""
lock = self._lock.read()
metadata = lock.get("metadata", {})
if "content-hash" in metadata:
return self._content_hash == lock["metadata"]["content-hash"]
return False | [
"def",
"is_fresh",
"(",
"self",
")",
":",
"# type: () -> bool",
"lock",
"=",
"self",
".",
"_lock",
".",
"read",
"(",
")",
"metadata",
"=",
"lock",
".",
"get",
"(",
"\"metadata\"",
",",
"{",
"}",
")",
"if",
"\"content-hash\"",
"in",
"metadata",
":",
"re... | Checks whether the lock file is still up to date with the current hash. | [
"Checks",
"whether",
"the",
"lock",
"file",
"is",
"still",
"up",
"to",
"date",
"with",
"the",
"current",
"hash",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/locker.py#L45-L55 |
31,607 | sdispater/poetry | poetry/packages/locker.py | Locker.locked_repository | def locked_repository(
self, with_dev_reqs=False
): # type: (bool) -> poetry.repositories.Repository
"""
Searches and returns a repository of locked packages.
"""
if not self.is_locked():
return poetry.repositories.Repository()
lock_data = self.lock_data
packages = poetry.repositories.Repository()
if with_dev_reqs:
locked_packages = lock_data["package"]
else:
locked_packages = [
p for p in lock_data["package"] if p["category"] == "main"
]
if not locked_packages:
return packages
for info in locked_packages:
package = poetry.packages.Package(
info["name"], info["version"], info["version"]
)
package.description = info.get("description", "")
package.category = info["category"]
package.optional = info["optional"]
package.hashes = lock_data["metadata"]["hashes"][info["name"]]
package.python_versions = info["python-versions"]
if "marker" in info:
package.marker = parse_marker(info["marker"])
else:
# Compatibility for old locks
if "requirements" in info:
dep = poetry.packages.Dependency("foo", "0.0.0")
for name, value in info["requirements"].items():
if name == "python":
dep.python_versions = value
elif name == "platform":
dep.platform = value
split_dep = dep.to_pep_508(False).split(";")
if len(split_dep) > 1:
package.marker = parse_marker(split_dep[1].strip())
for dep_name, constraint in info.get("dependencies", {}).items():
if isinstance(constraint, list):
for c in constraint:
package.add_dependency(dep_name, c)
continue
package.add_dependency(dep_name, constraint)
if "source" in info:
package.source_type = info["source"]["type"]
package.source_url = info["source"]["url"]
package.source_reference = info["source"]["reference"]
packages.add_package(package)
return packages | python | def locked_repository(
self, with_dev_reqs=False
): # type: (bool) -> poetry.repositories.Repository
"""
Searches and returns a repository of locked packages.
"""
if not self.is_locked():
return poetry.repositories.Repository()
lock_data = self.lock_data
packages = poetry.repositories.Repository()
if with_dev_reqs:
locked_packages = lock_data["package"]
else:
locked_packages = [
p for p in lock_data["package"] if p["category"] == "main"
]
if not locked_packages:
return packages
for info in locked_packages:
package = poetry.packages.Package(
info["name"], info["version"], info["version"]
)
package.description = info.get("description", "")
package.category = info["category"]
package.optional = info["optional"]
package.hashes = lock_data["metadata"]["hashes"][info["name"]]
package.python_versions = info["python-versions"]
if "marker" in info:
package.marker = parse_marker(info["marker"])
else:
# Compatibility for old locks
if "requirements" in info:
dep = poetry.packages.Dependency("foo", "0.0.0")
for name, value in info["requirements"].items():
if name == "python":
dep.python_versions = value
elif name == "platform":
dep.platform = value
split_dep = dep.to_pep_508(False).split(";")
if len(split_dep) > 1:
package.marker = parse_marker(split_dep[1].strip())
for dep_name, constraint in info.get("dependencies", {}).items():
if isinstance(constraint, list):
for c in constraint:
package.add_dependency(dep_name, c)
continue
package.add_dependency(dep_name, constraint)
if "source" in info:
package.source_type = info["source"]["type"]
package.source_url = info["source"]["url"]
package.source_reference = info["source"]["reference"]
packages.add_package(package)
return packages | [
"def",
"locked_repository",
"(",
"self",
",",
"with_dev_reqs",
"=",
"False",
")",
":",
"# type: (bool) -> poetry.repositories.Repository",
"if",
"not",
"self",
".",
"is_locked",
"(",
")",
":",
"return",
"poetry",
".",
"repositories",
".",
"Repository",
"(",
")",
... | Searches and returns a repository of locked packages. | [
"Searches",
"and",
"returns",
"a",
"repository",
"of",
"locked",
"packages",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/locker.py#L57-L121 |
31,608 | sdispater/poetry | poetry/packages/locker.py | Locker._get_content_hash | def _get_content_hash(self): # type: () -> str
"""
Returns the sha256 hash of the sorted content of the pyproject file.
"""
content = self._local_config
relevant_content = {}
for key in self._relevant_keys:
relevant_content[key] = content.get(key)
content_hash = sha256(
json.dumps(relevant_content, sort_keys=True).encode()
).hexdigest()
return content_hash | python | def _get_content_hash(self): # type: () -> str
"""
Returns the sha256 hash of the sorted content of the pyproject file.
"""
content = self._local_config
relevant_content = {}
for key in self._relevant_keys:
relevant_content[key] = content.get(key)
content_hash = sha256(
json.dumps(relevant_content, sort_keys=True).encode()
).hexdigest()
return content_hash | [
"def",
"_get_content_hash",
"(",
"self",
")",
":",
"# type: () -> str",
"content",
"=",
"self",
".",
"_local_config",
"relevant_content",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"_relevant_keys",
":",
"relevant_content",
"[",
"key",
"]",
"=",
"content"... | Returns the sha256 hash of the sorted content of the pyproject file. | [
"Returns",
"the",
"sha256",
"hash",
"of",
"the",
"sorted",
"content",
"of",
"the",
"pyproject",
"file",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/packages/locker.py#L165-L179 |
31,609 | sdispater/poetry | poetry/repositories/installed_repository.py | InstalledRepository.load | def load(cls, env): # type: (Env) -> InstalledRepository
"""
Load installed packages.
For now, it uses the pip "freeze" command.
"""
repo = cls()
freeze_output = env.run("pip", "freeze")
for line in freeze_output.split("\n"):
if "==" in line:
name, version = re.split("={2,3}", line)
repo.add_package(Package(name, version, version))
elif line.startswith("-e "):
line = line[3:].strip()
if line.startswith("git+"):
url = line.lstrip("git+")
if "@" in url:
url, rev = url.rsplit("@", 1)
else:
rev = "master"
name = url.split("/")[-1].rstrip(".git")
if "#egg=" in rev:
rev, name = rev.split("#egg=")
package = Package(name, "0.0.0")
package.source_type = "git"
package.source_url = url
package.source_reference = rev
repo.add_package(package)
return repo | python | def load(cls, env): # type: (Env) -> InstalledRepository
"""
Load installed packages.
For now, it uses the pip "freeze" command.
"""
repo = cls()
freeze_output = env.run("pip", "freeze")
for line in freeze_output.split("\n"):
if "==" in line:
name, version = re.split("={2,3}", line)
repo.add_package(Package(name, version, version))
elif line.startswith("-e "):
line = line[3:].strip()
if line.startswith("git+"):
url = line.lstrip("git+")
if "@" in url:
url, rev = url.rsplit("@", 1)
else:
rev = "master"
name = url.split("/")[-1].rstrip(".git")
if "#egg=" in rev:
rev, name = rev.split("#egg=")
package = Package(name, "0.0.0")
package.source_type = "git"
package.source_url = url
package.source_reference = rev
repo.add_package(package)
return repo | [
"def",
"load",
"(",
"cls",
",",
"env",
")",
":",
"# type: (Env) -> InstalledRepository",
"repo",
"=",
"cls",
"(",
")",
"freeze_output",
"=",
"env",
".",
"run",
"(",
"\"pip\"",
",",
"\"freeze\"",
")",
"for",
"line",
"in",
"freeze_output",
".",
"split",
"(",... | Load installed packages.
For now, it uses the pip "freeze" command. | [
"Load",
"installed",
"packages",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/installed_repository.py#L11-L44 |
31,610 | sdispater/poetry | poetry/version/version_selector.py | VersionSelector.find_best_candidate | def find_best_candidate(
self,
package_name, # type: str
target_package_version=None, # type: Union[str, None]
allow_prereleases=False, # type: bool
): # type: (...) -> Union[Package, bool]
"""
Given a package name and optional version,
returns the latest Package that matches
"""
if target_package_version:
constraint = parse_constraint(target_package_version)
else:
constraint = parse_constraint("*")
candidates = self._pool.find_packages(
package_name, constraint, allow_prereleases=allow_prereleases
)
if not candidates:
return False
dependency = Dependency(package_name, constraint)
# Select highest version if we have many
package = candidates[0]
for candidate in candidates:
if candidate.is_prerelease() and not dependency.allows_prereleases():
continue
# Select highest version of the two
if package.version < candidate.version:
package = candidate
return package | python | def find_best_candidate(
self,
package_name, # type: str
target_package_version=None, # type: Union[str, None]
allow_prereleases=False, # type: bool
): # type: (...) -> Union[Package, bool]
"""
Given a package name and optional version,
returns the latest Package that matches
"""
if target_package_version:
constraint = parse_constraint(target_package_version)
else:
constraint = parse_constraint("*")
candidates = self._pool.find_packages(
package_name, constraint, allow_prereleases=allow_prereleases
)
if not candidates:
return False
dependency = Dependency(package_name, constraint)
# Select highest version if we have many
package = candidates[0]
for candidate in candidates:
if candidate.is_prerelease() and not dependency.allows_prereleases():
continue
# Select highest version of the two
if package.version < candidate.version:
package = candidate
return package | [
"def",
"find_best_candidate",
"(",
"self",
",",
"package_name",
",",
"# type: str",
"target_package_version",
"=",
"None",
",",
"# type: Union[str, None]",
"allow_prereleases",
"=",
"False",
",",
"# type: bool",
")",
":",
"# type: (...) -> Union[Package, bool]",
"if",
"t... | Given a package name and optional version,
returns the latest Package that matches | [
"Given",
"a",
"package",
"name",
"and",
"optional",
"version",
"returns",
"the",
"latest",
"Package",
"that",
"matches"
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/version/version_selector.py#L13-L47 |
31,611 | sdispater/poetry | poetry/repositories/legacy_repository.py | LegacyRepository.package | def package(
self, name, version, extras=None
): # type: (...) -> poetry.packages.Package
"""
Retrieve the release information.
This is a heavy task which takes time.
We have to download a package to get the dependencies.
We also need to download every file matching this release
to get the various hashes.
Note that, this will be cached so the subsequent operations
should be much faster.
"""
try:
index = self._packages.index(
poetry.packages.Package(name, version, version)
)
return self._packages[index]
except ValueError:
if extras is None:
extras = []
release_info = self.get_release_info(name, version)
package = poetry.packages.Package(name, version, version)
if release_info["requires_python"]:
package.python_versions = release_info["requires_python"]
package.source_type = "legacy"
package.source_url = self._url
package.source_reference = self.name
requires_dist = release_info["requires_dist"] or []
for req in requires_dist:
try:
dependency = dependency_from_pep_508(req)
except InvalidMarker:
# Invalid marker
# We strip the markers hoping for the best
req = req.split(";")[0]
dependency = dependency_from_pep_508(req)
except ValueError:
# Likely unable to parse constraint so we skip it
self._log(
"Invalid constraint ({}) found in {}-{} dependencies, "
"skipping".format(req, package.name, package.version),
level="debug",
)
continue
if dependency.in_extras:
for extra in dependency.in_extras:
if extra not in package.extras:
package.extras[extra] = []
package.extras[extra].append(dependency)
if not dependency.is_optional():
package.requires.append(dependency)
# Adding description
package.description = release_info.get("summary", "")
# Adding hashes information
package.hashes = release_info["digests"]
# Activate extra dependencies
for extra in extras:
if extra in package.extras:
for dep in package.extras[extra]:
dep.activate()
package.requires += package.extras[extra]
self._packages.append(package)
return package | python | def package(
self, name, version, extras=None
): # type: (...) -> poetry.packages.Package
"""
Retrieve the release information.
This is a heavy task which takes time.
We have to download a package to get the dependencies.
We also need to download every file matching this release
to get the various hashes.
Note that, this will be cached so the subsequent operations
should be much faster.
"""
try:
index = self._packages.index(
poetry.packages.Package(name, version, version)
)
return self._packages[index]
except ValueError:
if extras is None:
extras = []
release_info = self.get_release_info(name, version)
package = poetry.packages.Package(name, version, version)
if release_info["requires_python"]:
package.python_versions = release_info["requires_python"]
package.source_type = "legacy"
package.source_url = self._url
package.source_reference = self.name
requires_dist = release_info["requires_dist"] or []
for req in requires_dist:
try:
dependency = dependency_from_pep_508(req)
except InvalidMarker:
# Invalid marker
# We strip the markers hoping for the best
req = req.split(";")[0]
dependency = dependency_from_pep_508(req)
except ValueError:
# Likely unable to parse constraint so we skip it
self._log(
"Invalid constraint ({}) found in {}-{} dependencies, "
"skipping".format(req, package.name, package.version),
level="debug",
)
continue
if dependency.in_extras:
for extra in dependency.in_extras:
if extra not in package.extras:
package.extras[extra] = []
package.extras[extra].append(dependency)
if not dependency.is_optional():
package.requires.append(dependency)
# Adding description
package.description = release_info.get("summary", "")
# Adding hashes information
package.hashes = release_info["digests"]
# Activate extra dependencies
for extra in extras:
if extra in package.extras:
for dep in package.extras[extra]:
dep.activate()
package.requires += package.extras[extra]
self._packages.append(package)
return package | [
"def",
"package",
"(",
"self",
",",
"name",
",",
"version",
",",
"extras",
"=",
"None",
")",
":",
"# type: (...) -> poetry.packages.Package",
"try",
":",
"index",
"=",
"self",
".",
"_packages",
".",
"index",
"(",
"poetry",
".",
"packages",
".",
"Package",
... | Retrieve the release information.
This is a heavy task which takes time.
We have to download a package to get the dependencies.
We also need to download every file matching this release
to get the various hashes.
Note that, this will be cached so the subsequent operations
should be much faster. | [
"Retrieve",
"the",
"release",
"information",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/legacy_repository.py#L246-L325 |
31,612 | sdispater/poetry | poetry/console/commands/command.py | Command.run | def run(self, i, o): # type: () -> int
"""
Initialize command.
"""
self.input = i
self.output = PoetryStyle(i, o)
for logger in self._loggers:
self.register_logger(logging.getLogger(logger))
return super(BaseCommand, self).run(i, o) | python | def run(self, i, o): # type: () -> int
"""
Initialize command.
"""
self.input = i
self.output = PoetryStyle(i, o)
for logger in self._loggers:
self.register_logger(logging.getLogger(logger))
return super(BaseCommand, self).run(i, o) | [
"def",
"run",
"(",
"self",
",",
"i",
",",
"o",
")",
":",
"# type: () -> int",
"self",
".",
"input",
"=",
"i",
"self",
".",
"output",
"=",
"PoetryStyle",
"(",
"i",
",",
"o",
")",
"for",
"logger",
"in",
"self",
".",
"_loggers",
":",
"self",
".",
"r... | Initialize command. | [
"Initialize",
"command",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/console/commands/command.py#L67-L77 |
31,613 | sdispater/poetry | poetry/console/commands/command.py | Command.register_logger | def register_logger(self, logger):
"""
Register a new logger.
"""
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if output.is_debug():
level = logging.DEBUG
elif output.is_very_verbose() or output.is_verbose():
level = logging.INFO
logger.setLevel(level) | python | def register_logger(self, logger):
"""
Register a new logger.
"""
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if output.is_debug():
level = logging.DEBUG
elif output.is_very_verbose() or output.is_verbose():
level = logging.INFO
logger.setLevel(level) | [
"def",
"register_logger",
"(",
"self",
",",
"logger",
")",
":",
"handler",
"=",
"CommandHandler",
"(",
"self",
")",
"handler",
".",
"setFormatter",
"(",
"CommandFormatter",
"(",
")",
")",
"logger",
".",
"handlers",
"=",
"[",
"handler",
"]",
"logger",
".",
... | Register a new logger. | [
"Register",
"a",
"new",
"logger",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/console/commands/command.py#L79-L95 |
31,614 | sdispater/poetry | poetry/masonry/publishing/uploader.py | Uploader._register | def _register(self, session, url):
"""
Register a package to a repository.
"""
dist = self._poetry.file.parent / "dist"
file = dist / "{}-{}.tar.gz".format(
self._package.name, normalize_version(self._package.version.text)
)
if not file.exists():
raise RuntimeError('"{0}" does not exist.'.format(file.name))
data = self.post_data(file)
data.update({":action": "submit", "protocol_version": "1"})
data_to_send = self._prepare_data(data)
encoder = MultipartEncoder(data_to_send)
resp = session.post(
url,
data=encoder,
allow_redirects=False,
headers={"Content-Type": encoder.content_type},
)
resp.raise_for_status()
return resp | python | def _register(self, session, url):
"""
Register a package to a repository.
"""
dist = self._poetry.file.parent / "dist"
file = dist / "{}-{}.tar.gz".format(
self._package.name, normalize_version(self._package.version.text)
)
if not file.exists():
raise RuntimeError('"{0}" does not exist.'.format(file.name))
data = self.post_data(file)
data.update({":action": "submit", "protocol_version": "1"})
data_to_send = self._prepare_data(data)
encoder = MultipartEncoder(data_to_send)
resp = session.post(
url,
data=encoder,
allow_redirects=False,
headers={"Content-Type": encoder.content_type},
)
resp.raise_for_status()
return resp | [
"def",
"_register",
"(",
"self",
",",
"session",
",",
"url",
")",
":",
"dist",
"=",
"self",
".",
"_poetry",
".",
"file",
".",
"parent",
"/",
"\"dist\"",
"file",
"=",
"dist",
"/",
"\"{}-{}.tar.gz\"",
".",
"format",
"(",
"self",
".",
"_package",
".",
"... | Register a package to a repository. | [
"Register",
"a",
"package",
"to",
"a",
"repository",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/publishing/uploader.py#L256-L282 |
31,615 | sdispater/poetry | poetry/repositories/pypi_repository.py | PyPiRepository.find_packages | def find_packages(
self,
name, # type: str
constraint=None, # type: Union[VersionConstraint, str, None]
extras=None, # type: Union[list, None]
allow_prereleases=False, # type: bool
): # type: (...) -> List[Package]
"""
Find packages on the remote server.
"""
if constraint is None:
constraint = "*"
if not isinstance(constraint, VersionConstraint):
constraint = parse_constraint(constraint)
if isinstance(constraint, VersionRange):
if (
constraint.max is not None
and constraint.max.is_prerelease()
or constraint.min is not None
and constraint.min.is_prerelease()
):
allow_prereleases = True
info = self.get_package_info(name)
packages = []
for version, release in info["releases"].items():
if not release:
# Bad release
self._log(
"No release information found for {}-{}, skipping".format(
name, version
),
level="debug",
)
continue
try:
package = Package(name, version)
except ParseVersionError:
self._log(
'Unable to parse version "{}" for the {} package, skipping'.format(
version, name
),
level="debug",
)
continue
if package.is_prerelease() and not allow_prereleases:
continue
if not constraint or (constraint and constraint.allows(package.version)):
if extras is not None:
package.requires_extras = extras
packages.append(package)
self._log(
"{} packages found for {} {}".format(len(packages), name, str(constraint)),
level="debug",
)
return packages | python | def find_packages(
self,
name, # type: str
constraint=None, # type: Union[VersionConstraint, str, None]
extras=None, # type: Union[list, None]
allow_prereleases=False, # type: bool
): # type: (...) -> List[Package]
"""
Find packages on the remote server.
"""
if constraint is None:
constraint = "*"
if not isinstance(constraint, VersionConstraint):
constraint = parse_constraint(constraint)
if isinstance(constraint, VersionRange):
if (
constraint.max is not None
and constraint.max.is_prerelease()
or constraint.min is not None
and constraint.min.is_prerelease()
):
allow_prereleases = True
info = self.get_package_info(name)
packages = []
for version, release in info["releases"].items():
if not release:
# Bad release
self._log(
"No release information found for {}-{}, skipping".format(
name, version
),
level="debug",
)
continue
try:
package = Package(name, version)
except ParseVersionError:
self._log(
'Unable to parse version "{}" for the {} package, skipping'.format(
version, name
),
level="debug",
)
continue
if package.is_prerelease() and not allow_prereleases:
continue
if not constraint or (constraint and constraint.allows(package.version)):
if extras is not None:
package.requires_extras = extras
packages.append(package)
self._log(
"{} packages found for {} {}".format(len(packages), name, str(constraint)),
level="debug",
)
return packages | [
"def",
"find_packages",
"(",
"self",
",",
"name",
",",
"# type: str",
"constraint",
"=",
"None",
",",
"# type: Union[VersionConstraint, str, None]",
"extras",
"=",
"None",
",",
"# type: Union[list, None]",
"allow_prereleases",
"=",
"False",
",",
"# type: bool",
")",
"... | Find packages on the remote server. | [
"Find",
"packages",
"on",
"the",
"remote",
"server",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/pypi_repository.py#L83-L148 |
31,616 | sdispater/poetry | poetry/repositories/pypi_repository.py | PyPiRepository.get_package_info | def get_package_info(self, name): # type: (str) -> dict
"""
Return the package information given its name.
The information is returned from the cache if it exists
or retrieved from the remote server.
"""
if self._disable_cache:
return self._get_package_info(name)
return self._cache.store("packages").remember_forever(
name, lambda: self._get_package_info(name)
) | python | def get_package_info(self, name): # type: (str) -> dict
"""
Return the package information given its name.
The information is returned from the cache if it exists
or retrieved from the remote server.
"""
if self._disable_cache:
return self._get_package_info(name)
return self._cache.store("packages").remember_forever(
name, lambda: self._get_package_info(name)
) | [
"def",
"get_package_info",
"(",
"self",
",",
"name",
")",
":",
"# type: (str) -> dict",
"if",
"self",
".",
"_disable_cache",
":",
"return",
"self",
".",
"_get_package_info",
"(",
"name",
")",
"return",
"self",
".",
"_cache",
".",
"store",
"(",
"\"packages\"",
... | Return the package information given its name.
The information is returned from the cache if it exists
or retrieved from the remote server. | [
"Return",
"the",
"package",
"information",
"given",
"its",
"name",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/pypi_repository.py#L230-L242 |
31,617 | sdispater/poetry | poetry/repositories/pypi_repository.py | PyPiRepository.get_release_info | def get_release_info(self, name, version): # type: (str, str) -> dict
"""
Return the release information given a package name and a version.
The information is returned from the cache if it exists
or retrieved from the remote server.
"""
if self._disable_cache:
return self._get_release_info(name, version)
cached = self._cache.remember_forever(
"{}:{}".format(name, version), lambda: self._get_release_info(name, version)
)
cache_version = cached.get("_cache_version", "0.0.0")
if parse_constraint(cache_version) != self.CACHE_VERSION:
# The cache must be updated
self._log(
"The cache for {} {} is outdated. Refreshing.".format(name, version),
level="debug",
)
cached = self._get_release_info(name, version)
self._cache.forever("{}:{}".format(name, version), cached)
return cached | python | def get_release_info(self, name, version): # type: (str, str) -> dict
"""
Return the release information given a package name and a version.
The information is returned from the cache if it exists
or retrieved from the remote server.
"""
if self._disable_cache:
return self._get_release_info(name, version)
cached = self._cache.remember_forever(
"{}:{}".format(name, version), lambda: self._get_release_info(name, version)
)
cache_version = cached.get("_cache_version", "0.0.0")
if parse_constraint(cache_version) != self.CACHE_VERSION:
# The cache must be updated
self._log(
"The cache for {} {} is outdated. Refreshing.".format(name, version),
level="debug",
)
cached = self._get_release_info(name, version)
self._cache.forever("{}:{}".format(name, version), cached)
return cached | [
"def",
"get_release_info",
"(",
"self",
",",
"name",
",",
"version",
")",
":",
"# type: (str, str) -> dict",
"if",
"self",
".",
"_disable_cache",
":",
"return",
"self",
".",
"_get_release_info",
"(",
"name",
",",
"version",
")",
"cached",
"=",
"self",
".",
"... | Return the release information given a package name and a version.
The information is returned from the cache if it exists
or retrieved from the remote server. | [
"Return",
"the",
"release",
"information",
"given",
"a",
"package",
"name",
"and",
"a",
"version",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/repositories/pypi_repository.py#L251-L276 |
31,618 | sdispater/poetry | poetry/masonry/builders/wheel.py | WheelBuilder._write_entry_points | def _write_entry_points(self, fp):
"""
Write entry_points.txt.
"""
entry_points = self.convert_entry_points()
for group_name in sorted(entry_points):
fp.write("[{}]\n".format(group_name))
for ep in sorted(entry_points[group_name]):
fp.write(ep.replace(" ", "") + "\n")
fp.write("\n") | python | def _write_entry_points(self, fp):
"""
Write entry_points.txt.
"""
entry_points = self.convert_entry_points()
for group_name in sorted(entry_points):
fp.write("[{}]\n".format(group_name))
for ep in sorted(entry_points[group_name]):
fp.write(ep.replace(" ", "") + "\n")
fp.write("\n") | [
"def",
"_write_entry_points",
"(",
"self",
",",
"fp",
")",
":",
"entry_points",
"=",
"self",
".",
"convert_entry_points",
"(",
")",
"for",
"group_name",
"in",
"sorted",
"(",
"entry_points",
")",
":",
"fp",
".",
"write",
"(",
"\"[{}]\\n\"",
".",
"format",
"... | Write entry_points.txt. | [
"Write",
"entry_points",
".",
"txt",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/masonry/builders/wheel.py#L288-L299 |
31,619 | sdispater/poetry | poetry/installation/installer.py | Installer.lock | def lock(self): # type: () -> Installer
"""
Prepare the installer for locking only.
"""
self.update()
self.execute_operations(False)
self._lock = True
return self | python | def lock(self): # type: () -> Installer
"""
Prepare the installer for locking only.
"""
self.update()
self.execute_operations(False)
self._lock = True
return self | [
"def",
"lock",
"(",
"self",
")",
":",
"# type: () -> Installer",
"self",
".",
"update",
"(",
")",
"self",
".",
"execute_operations",
"(",
"False",
")",
"self",
".",
"_lock",
"=",
"True",
"return",
"self"
] | Prepare the installer for locking only. | [
"Prepare",
"the",
"installer",
"for",
"locking",
"only",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/installation/installer.py#L111-L119 |
31,620 | sdispater/poetry | poetry/installation/installer.py | Installer._execute | def _execute(self, operation): # type: (Operation) -> None
"""
Execute a given operation.
"""
method = operation.job_type
getattr(self, "_execute_{}".format(method))(operation) | python | def _execute(self, operation): # type: (Operation) -> None
"""
Execute a given operation.
"""
method = operation.job_type
getattr(self, "_execute_{}".format(method))(operation) | [
"def",
"_execute",
"(",
"self",
",",
"operation",
")",
":",
"# type: (Operation) -> None",
"method",
"=",
"operation",
".",
"job_type",
"getattr",
"(",
"self",
",",
"\"_execute_{}\"",
".",
"format",
"(",
"method",
")",
")",
"(",
"operation",
")"
] | Execute a given operation. | [
"Execute",
"a",
"given",
"operation",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/installation/installer.py#L300-L306 |
31,621 | sdispater/poetry | poetry/installation/installer.py | Installer._get_extra_packages | def _get_extra_packages(self, repo):
"""
Returns all packages required by extras.
Maybe we just let the solver handle it?
"""
if self._update:
extras = {k: [d.name for d in v] for k, v in self._package.extras.items()}
else:
extras = self._locker.lock_data.get("extras", {})
extra_packages = []
for extra_name, packages in extras.items():
if extra_name not in self._extras:
continue
extra_packages += [Dependency(p, "*") for p in packages]
def _extra_packages(packages):
pkgs = []
for package in packages:
for pkg in repo.packages:
if pkg.name == package.name:
pkgs.append(package)
pkgs += _extra_packages(pkg.requires)
break
return pkgs
return _extra_packages(extra_packages) | python | def _get_extra_packages(self, repo):
"""
Returns all packages required by extras.
Maybe we just let the solver handle it?
"""
if self._update:
extras = {k: [d.name for d in v] for k, v in self._package.extras.items()}
else:
extras = self._locker.lock_data.get("extras", {})
extra_packages = []
for extra_name, packages in extras.items():
if extra_name not in self._extras:
continue
extra_packages += [Dependency(p, "*") for p in packages]
def _extra_packages(packages):
pkgs = []
for package in packages:
for pkg in repo.packages:
if pkg.name == package.name:
pkgs.append(package)
pkgs += _extra_packages(pkg.requires)
break
return pkgs
return _extra_packages(extra_packages) | [
"def",
"_get_extra_packages",
"(",
"self",
",",
"repo",
")",
":",
"if",
"self",
".",
"_update",
":",
"extras",
"=",
"{",
"k",
":",
"[",
"d",
".",
"name",
"for",
"d",
"in",
"v",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_package",
".",
"ext... | Returns all packages required by extras.
Maybe we just let the solver handle it? | [
"Returns",
"all",
"packages",
"required",
"by",
"extras",
"."
] | 2d27acd76c165dd49f11934520a7973de7a3762a | https://github.com/sdispater/poetry/blob/2d27acd76c165dd49f11934520a7973de7a3762a/poetry/installation/installer.py#L480-L510 |
31,622 | spotify/luigi | luigi/tools/luigi_grep.py | LuigiGrep._fetch_json | def _fetch_json(self):
"""Returns the json representation of the dep graph"""
print("Fetching from url: " + self.graph_url)
resp = urlopen(self.graph_url).read()
return json.loads(resp.decode('utf-8')) | python | def _fetch_json(self):
"""Returns the json representation of the dep graph"""
print("Fetching from url: " + self.graph_url)
resp = urlopen(self.graph_url).read()
return json.loads(resp.decode('utf-8')) | [
"def",
"_fetch_json",
"(",
"self",
")",
":",
"print",
"(",
"\"Fetching from url: \"",
"+",
"self",
".",
"graph_url",
")",
"resp",
"=",
"urlopen",
"(",
"self",
".",
"graph_url",
")",
".",
"read",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"resp",
".... | Returns the json representation of the dep graph | [
"Returns",
"the",
"json",
"representation",
"of",
"the",
"dep",
"graph"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/luigi_grep.py#L21-L25 |
31,623 | spotify/luigi | luigi/tools/luigi_grep.py | LuigiGrep.prefix_search | def prefix_search(self, job_name_prefix):
"""Searches for jobs matching the given ``job_name_prefix``."""
json = self._fetch_json()
jobs = json['response']
for job in jobs:
if job.startswith(job_name_prefix):
yield self._build_results(jobs, job) | python | def prefix_search(self, job_name_prefix):
"""Searches for jobs matching the given ``job_name_prefix``."""
json = self._fetch_json()
jobs = json['response']
for job in jobs:
if job.startswith(job_name_prefix):
yield self._build_results(jobs, job) | [
"def",
"prefix_search",
"(",
"self",
",",
"job_name_prefix",
")",
":",
"json",
"=",
"self",
".",
"_fetch_json",
"(",
")",
"jobs",
"=",
"json",
"[",
"'response'",
"]",
"for",
"job",
"in",
"jobs",
":",
"if",
"job",
".",
"startswith",
"(",
"job_name_prefix"... | Searches for jobs matching the given ``job_name_prefix``. | [
"Searches",
"for",
"jobs",
"matching",
"the",
"given",
"job_name_prefix",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/luigi_grep.py#L38-L44 |
31,624 | spotify/luigi | luigi/tools/luigi_grep.py | LuigiGrep.status_search | def status_search(self, status):
"""Searches for jobs matching the given ``status``."""
json = self._fetch_json()
jobs = json['response']
for job in jobs:
job_info = jobs[job]
if job_info['status'].lower() == status.lower():
yield self._build_results(jobs, job) | python | def status_search(self, status):
"""Searches for jobs matching the given ``status``."""
json = self._fetch_json()
jobs = json['response']
for job in jobs:
job_info = jobs[job]
if job_info['status'].lower() == status.lower():
yield self._build_results(jobs, job) | [
"def",
"status_search",
"(",
"self",
",",
"status",
")",
":",
"json",
"=",
"self",
".",
"_fetch_json",
"(",
")",
"jobs",
"=",
"json",
"[",
"'response'",
"]",
"for",
"job",
"in",
"jobs",
":",
"job_info",
"=",
"jobs",
"[",
"job",
"]",
"if",
"job_info",... | Searches for jobs matching the given ``status``. | [
"Searches",
"for",
"jobs",
"matching",
"the",
"given",
"status",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/tools/luigi_grep.py#L46-L53 |
31,625 | spotify/luigi | luigi/local_target.py | LocalFileSystem.move | def move(self, old_path, new_path, raise_if_exists=False):
"""
Move file atomically. If source and destination are located
on different filesystems, atomicity is approximated
but cannot be guaranteed.
"""
if raise_if_exists and os.path.exists(new_path):
raise FileAlreadyExists('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.mkdir(d)
try:
os.rename(old_path, new_path)
except OSError as err:
if err.errno == errno.EXDEV:
new_path_tmp = '%s-%09d' % (new_path, random.randint(0, 999999999))
shutil.copy(old_path, new_path_tmp)
os.rename(new_path_tmp, new_path)
os.remove(old_path)
else:
raise err | python | def move(self, old_path, new_path, raise_if_exists=False):
"""
Move file atomically. If source and destination are located
on different filesystems, atomicity is approximated
but cannot be guaranteed.
"""
if raise_if_exists and os.path.exists(new_path):
raise FileAlreadyExists('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.mkdir(d)
try:
os.rename(old_path, new_path)
except OSError as err:
if err.errno == errno.EXDEV:
new_path_tmp = '%s-%09d' % (new_path, random.randint(0, 999999999))
shutil.copy(old_path, new_path_tmp)
os.rename(new_path_tmp, new_path)
os.remove(old_path)
else:
raise err | [
"def",
"move",
"(",
"self",
",",
"old_path",
",",
"new_path",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"if",
"raise_if_exists",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"new_path",
")",
":",
"raise",
"FileAlreadyExists",
"(",
"'Destination exists... | Move file atomically. If source and destination are located
on different filesystems, atomicity is approximated
but cannot be guaranteed. | [
"Move",
"file",
"atomically",
".",
"If",
"source",
"and",
"destination",
"are",
"located",
"on",
"different",
"filesystems",
"atomicity",
"is",
"approximated",
"but",
"cannot",
"be",
"guaranteed",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/local_target.py#L100-L120 |
31,626 | spotify/luigi | luigi/local_target.py | LocalTarget.makedirs | def makedirs(self):
"""
Create all parent folders if they do not exist.
"""
normpath = os.path.normpath(self.path)
parentfolder = os.path.dirname(normpath)
if parentfolder:
try:
os.makedirs(parentfolder)
except OSError:
pass | python | def makedirs(self):
"""
Create all parent folders if they do not exist.
"""
normpath = os.path.normpath(self.path)
parentfolder = os.path.dirname(normpath)
if parentfolder:
try:
os.makedirs(parentfolder)
except OSError:
pass | [
"def",
"makedirs",
"(",
"self",
")",
":",
"normpath",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"self",
".",
"path",
")",
"parentfolder",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"normpath",
")",
"if",
"parentfolder",
":",
"try",
":",
"os",
... | Create all parent folders if they do not exist. | [
"Create",
"all",
"parent",
"folders",
"if",
"they",
"do",
"not",
"exist",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/local_target.py#L146-L156 |
31,627 | spotify/luigi | luigi/contrib/lsf.py | LSFJobTask.fetch_task_failures | def fetch_task_failures(self):
"""
Read in the error file from bsub
"""
error_file = os.path.join(self.tmp_dir, "job.err")
if os.path.isfile(error_file):
with open(error_file, "r") as f_err:
errors = f_err.readlines()
else:
errors = ''
return errors | python | def fetch_task_failures(self):
"""
Read in the error file from bsub
"""
error_file = os.path.join(self.tmp_dir, "job.err")
if os.path.isfile(error_file):
with open(error_file, "r") as f_err:
errors = f_err.readlines()
else:
errors = ''
return errors | [
"def",
"fetch_task_failures",
"(",
"self",
")",
":",
"error_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tmp_dir",
",",
"\"job.err\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"error_file",
")",
":",
"with",
"open",
"(",
"e... | Read in the error file from bsub | [
"Read",
"in",
"the",
"error",
"file",
"from",
"bsub"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L119-L129 |
31,628 | spotify/luigi | luigi/contrib/lsf.py | LSFJobTask.fetch_task_output | def fetch_task_output(self):
"""
Read in the output file
"""
# Read in the output file
if os.path.isfile(os.path.join(self.tmp_dir, "job.out")):
with open(os.path.join(self.tmp_dir, "job.out"), "r") as f_out:
outputs = f_out.readlines()
else:
outputs = ''
return outputs | python | def fetch_task_output(self):
"""
Read in the output file
"""
# Read in the output file
if os.path.isfile(os.path.join(self.tmp_dir, "job.out")):
with open(os.path.join(self.tmp_dir, "job.out"), "r") as f_out:
outputs = f_out.readlines()
else:
outputs = ''
return outputs | [
"def",
"fetch_task_output",
"(",
"self",
")",
":",
"# Read in the output file",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tmp_dir",
",",
"\"job.out\"",
")",
")",
":",
"with",
"open",
"(",
"os",
".",... | Read in the output file | [
"Read",
"in",
"the",
"output",
"file"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L131-L141 |
31,629 | spotify/luigi | luigi/contrib/lsf.py | LSFJobTask._run_job | def _run_job(self):
"""
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
"""
args = []
if isinstance(self.output(), list):
log_output = os.path.split(self.output()[0].path)
else:
log_output = os.path.split(self.output().path)
args += ["bsub", "-q", self.queue_flag]
args += ["-n", str(self.n_cpu_flag)]
args += ["-M", str(self.memory_flag)]
args += ["-R", "rusage[%s]" % self.resource_flag]
args += ["-W", str(self.runtime_flag)]
if self.job_name_flag:
args += ["-J", str(self.job_name_flag)]
args += ["-o", os.path.join(log_output[0], "job.out")]
args += ["-e", os.path.join(log_output[0], "job.err")]
if self.extra_bsub_args:
args += self.extra_bsub_args.split()
# Find where the runner file is
runner_path = os.path.abspath(lsf_runner.__file__)
args += [runner_path]
args += [self.tmp_dir]
# That should do it. Let the world know what we're doing.
LOGGER.info("### LSF SUBMISSION ARGS: %s",
" ".join([str(a) for a in args]))
# Submit the job
run_job_proc = subprocess.Popen(
[str(a) for a in args],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=self.tmp_dir)
output = run_job_proc.communicate()[0]
# ASSUMPTION
# The result will be of the format
# Job <123> is submitted ot queue <myqueue>
# So get the number in those first brackets.
# I cannot think of a better workaround that leaves logic on the Task side of things.
LOGGER.info("### JOB SUBMISSION OUTPUT: %s", str(output))
self.job_id = int(output.split("<")[1].split(">")[0])
LOGGER.info(
"Job %ssubmitted as job %s",
self.job_name_flag + ' ',
str(self.job_id)
)
self._track_job()
# If we want to save the job temporaries, then do so
# We'll move them to be next to the job output
if self.save_job_info:
LOGGER.info("Saving up temporary bits")
# dest_dir = self.output().path
shutil.move(self.tmp_dir, "/".join(log_output[0:-1]))
# Now delete the temporaries, if they're there.
self._finish() | python | def _run_job(self):
"""
Build a bsub argument that will run lsf_runner.py on the directory we've specified.
"""
args = []
if isinstance(self.output(), list):
log_output = os.path.split(self.output()[0].path)
else:
log_output = os.path.split(self.output().path)
args += ["bsub", "-q", self.queue_flag]
args += ["-n", str(self.n_cpu_flag)]
args += ["-M", str(self.memory_flag)]
args += ["-R", "rusage[%s]" % self.resource_flag]
args += ["-W", str(self.runtime_flag)]
if self.job_name_flag:
args += ["-J", str(self.job_name_flag)]
args += ["-o", os.path.join(log_output[0], "job.out")]
args += ["-e", os.path.join(log_output[0], "job.err")]
if self.extra_bsub_args:
args += self.extra_bsub_args.split()
# Find where the runner file is
runner_path = os.path.abspath(lsf_runner.__file__)
args += [runner_path]
args += [self.tmp_dir]
# That should do it. Let the world know what we're doing.
LOGGER.info("### LSF SUBMISSION ARGS: %s",
" ".join([str(a) for a in args]))
# Submit the job
run_job_proc = subprocess.Popen(
[str(a) for a in args],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=self.tmp_dir)
output = run_job_proc.communicate()[0]
# ASSUMPTION
# The result will be of the format
# Job <123> is submitted ot queue <myqueue>
# So get the number in those first brackets.
# I cannot think of a better workaround that leaves logic on the Task side of things.
LOGGER.info("### JOB SUBMISSION OUTPUT: %s", str(output))
self.job_id = int(output.split("<")[1].split(">")[0])
LOGGER.info(
"Job %ssubmitted as job %s",
self.job_name_flag + ' ',
str(self.job_id)
)
self._track_job()
# If we want to save the job temporaries, then do so
# We'll move them to be next to the job output
if self.save_job_info:
LOGGER.info("Saving up temporary bits")
# dest_dir = self.output().path
shutil.move(self.tmp_dir, "/".join(log_output[0:-1]))
# Now delete the temporaries, if they're there.
self._finish() | [
"def",
"_run_job",
"(",
"self",
")",
":",
"args",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
".",
"output",
"(",
")",
",",
"list",
")",
":",
"log_output",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"output",
"(",
")",
"[",
"0"... | Build a bsub argument that will run lsf_runner.py on the directory we've specified. | [
"Build",
"a",
"bsub",
"argument",
"that",
"will",
"run",
"lsf_runner",
".",
"py",
"on",
"the",
"directory",
"we",
"ve",
"specified",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/lsf.py#L219-L283 |
31,630 | spotify/luigi | examples/spark_als.py | UserItemMatrix.output | def output(self):
"""
Returns the target output for this task.
In this case, a successful execution of this task will create a file in HDFS.
:return: the target output for this task.
:rtype: object (:py:class:`~luigi.target.Target`)
"""
return luigi.contrib.hdfs.HdfsTarget('data-matrix', format=luigi.format.Gzip) | python | def output(self):
"""
Returns the target output for this task.
In this case, a successful execution of this task will create a file in HDFS.
:return: the target output for this task.
:rtype: object (:py:class:`~luigi.target.Target`)
"""
return luigi.contrib.hdfs.HdfsTarget('data-matrix', format=luigi.format.Gzip) | [
"def",
"output",
"(",
"self",
")",
":",
"return",
"luigi",
".",
"contrib",
".",
"hdfs",
".",
"HdfsTarget",
"(",
"'data-matrix'",
",",
"format",
"=",
"luigi",
".",
"format",
".",
"Gzip",
")"
] | Returns the target output for this task.
In this case, a successful execution of this task will create a file in HDFS.
:return: the target output for this task.
:rtype: object (:py:class:`~luigi.target.Target`) | [
"Returns",
"the",
"target",
"output",
"for",
"this",
"task",
".",
"In",
"this",
"case",
"a",
"successful",
"execution",
"of",
"this",
"task",
"will",
"create",
"a",
"file",
"in",
"HDFS",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/spark_als.py#L49-L57 |
31,631 | spotify/luigi | luigi/server.py | run | def run(api_port=8082, address=None, unix_socket=None, scheduler=None):
"""
Runs one instance of the API server.
"""
if scheduler is None:
scheduler = Scheduler()
# load scheduler state
scheduler.load()
_init_api(
scheduler=scheduler,
api_port=api_port,
address=address,
unix_socket=unix_socket,
)
# prune work DAG every 60 seconds
pruner = tornado.ioloop.PeriodicCallback(scheduler.prune, 60000)
pruner.start()
def shutdown_handler(signum, frame):
exit_handler()
sys.exit(0)
@atexit.register
def exit_handler():
logger.info("Scheduler instance shutting down")
scheduler.dump()
stop()
signal.signal(signal.SIGINT, shutdown_handler)
signal.signal(signal.SIGTERM, shutdown_handler)
if os.name == 'nt':
signal.signal(signal.SIGBREAK, shutdown_handler)
else:
signal.signal(signal.SIGQUIT, shutdown_handler)
logger.info("Scheduler starting up")
tornado.ioloop.IOLoop.instance().start() | python | def run(api_port=8082, address=None, unix_socket=None, scheduler=None):
"""
Runs one instance of the API server.
"""
if scheduler is None:
scheduler = Scheduler()
# load scheduler state
scheduler.load()
_init_api(
scheduler=scheduler,
api_port=api_port,
address=address,
unix_socket=unix_socket,
)
# prune work DAG every 60 seconds
pruner = tornado.ioloop.PeriodicCallback(scheduler.prune, 60000)
pruner.start()
def shutdown_handler(signum, frame):
exit_handler()
sys.exit(0)
@atexit.register
def exit_handler():
logger.info("Scheduler instance shutting down")
scheduler.dump()
stop()
signal.signal(signal.SIGINT, shutdown_handler)
signal.signal(signal.SIGTERM, shutdown_handler)
if os.name == 'nt':
signal.signal(signal.SIGBREAK, shutdown_handler)
else:
signal.signal(signal.SIGQUIT, shutdown_handler)
logger.info("Scheduler starting up")
tornado.ioloop.IOLoop.instance().start() | [
"def",
"run",
"(",
"api_port",
"=",
"8082",
",",
"address",
"=",
"None",
",",
"unix_socket",
"=",
"None",
",",
"scheduler",
"=",
"None",
")",
":",
"if",
"scheduler",
"is",
"None",
":",
"scheduler",
"=",
"Scheduler",
"(",
")",
"# load scheduler state",
"s... | Runs one instance of the API server. | [
"Runs",
"one",
"instance",
"of",
"the",
"API",
"server",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/server.py#L322-L362 |
31,632 | spotify/luigi | luigi/contrib/salesforce.py | get_soql_fields | def get_soql_fields(soql):
"""
Gets queried columns names.
"""
soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE) # get fields
soql_fields = re.sub(' ', '', soql_fields.group()) # remove extra spaces
soql_fields = re.sub('\t', '', soql_fields) # remove tabs
fields = re.split(',|\n|\r|', soql_fields) # split on commas and newlines
fields = [field for field in fields if field != ''] # remove empty strings
return fields | python | def get_soql_fields(soql):
"""
Gets queried columns names.
"""
soql_fields = re.search('(?<=select)(?s)(.*)(?=from)', soql, re.IGNORECASE) # get fields
soql_fields = re.sub(' ', '', soql_fields.group()) # remove extra spaces
soql_fields = re.sub('\t', '', soql_fields) # remove tabs
fields = re.split(',|\n|\r|', soql_fields) # split on commas and newlines
fields = [field for field in fields if field != ''] # remove empty strings
return fields | [
"def",
"get_soql_fields",
"(",
"soql",
")",
":",
"soql_fields",
"=",
"re",
".",
"search",
"(",
"'(?<=select)(?s)(.*)(?=from)'",
",",
"soql",
",",
"re",
".",
"IGNORECASE",
")",
"# get fields",
"soql_fields",
"=",
"re",
".",
"sub",
"(",
"' '",
",",
"''",
","... | Gets queried columns names. | [
"Gets",
"queried",
"columns",
"names",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L43-L52 |
31,633 | spotify/luigi | luigi/contrib/salesforce.py | QuerySalesforce.merge_batch_results | def merge_batch_results(self, result_ids):
"""
Merges the resulting files of a multi-result batch bulk query.
"""
outfile = open(self.output().path, 'w')
if self.content_type.lower() == 'csv':
for i, result_id in enumerate(result_ids):
with open("%s.%d" % (self.output().path, i), 'r') as f:
header = f.readline()
if i == 0:
outfile.write(header)
for line in f:
outfile.write(line)
else:
raise Exception("Batch result merging not implemented for %s" % self.content_type)
outfile.close() | python | def merge_batch_results(self, result_ids):
"""
Merges the resulting files of a multi-result batch bulk query.
"""
outfile = open(self.output().path, 'w')
if self.content_type.lower() == 'csv':
for i, result_id in enumerate(result_ids):
with open("%s.%d" % (self.output().path, i), 'r') as f:
header = f.readline()
if i == 0:
outfile.write(header)
for line in f:
outfile.write(line)
else:
raise Exception("Batch result merging not implemented for %s" % self.content_type)
outfile.close() | [
"def",
"merge_batch_results",
"(",
"self",
",",
"result_ids",
")",
":",
"outfile",
"=",
"open",
"(",
"self",
".",
"output",
"(",
")",
".",
"path",
",",
"'w'",
")",
"if",
"self",
".",
"content_type",
".",
"lower",
"(",
")",
"==",
"'csv'",
":",
"for",
... | Merges the resulting files of a multi-result batch bulk query. | [
"Merges",
"the",
"resulting",
"files",
"of",
"a",
"multi",
"-",
"result",
"batch",
"bulk",
"query",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L212-L229 |
31,634 | spotify/luigi | luigi/contrib/salesforce.py | SalesforceAPI.start_session | def start_session(self):
"""
Starts a Salesforce session and determines which SF instance to use for future requests.
"""
if self.has_active_session():
raise Exception("Session already in progress.")
response = requests.post(self._get_login_url(),
headers=self._get_login_headers(),
data=self._get_login_xml())
response.raise_for_status()
root = ET.fromstring(response.text)
for e in root.iter("%ssessionId" % self.SOAP_NS):
if self.session_id:
raise Exception("Invalid login attempt. Multiple session ids found.")
self.session_id = e.text
for e in root.iter("%sserverUrl" % self.SOAP_NS):
if self.server_url:
raise Exception("Invalid login attempt. Multiple server urls found.")
self.server_url = e.text
if not self.has_active_session():
raise Exception("Invalid login attempt resulted in null sessionId [%s] and/or serverUrl [%s]." %
(self.session_id, self.server_url))
self.hostname = urlsplit(self.server_url).hostname | python | def start_session(self):
"""
Starts a Salesforce session and determines which SF instance to use for future requests.
"""
if self.has_active_session():
raise Exception("Session already in progress.")
response = requests.post(self._get_login_url(),
headers=self._get_login_headers(),
data=self._get_login_xml())
response.raise_for_status()
root = ET.fromstring(response.text)
for e in root.iter("%ssessionId" % self.SOAP_NS):
if self.session_id:
raise Exception("Invalid login attempt. Multiple session ids found.")
self.session_id = e.text
for e in root.iter("%sserverUrl" % self.SOAP_NS):
if self.server_url:
raise Exception("Invalid login attempt. Multiple server urls found.")
self.server_url = e.text
if not self.has_active_session():
raise Exception("Invalid login attempt resulted in null sessionId [%s] and/or serverUrl [%s]." %
(self.session_id, self.server_url))
self.hostname = urlsplit(self.server_url).hostname | [
"def",
"start_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_active_session",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"Session already in progress.\"",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"_get_login_url",
"(",
")",
... | Starts a Salesforce session and determines which SF instance to use for future requests. | [
"Starts",
"a",
"Salesforce",
"session",
"and",
"determines",
"which",
"SF",
"instance",
"to",
"use",
"for",
"future",
"requests",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L255-L281 |
31,635 | spotify/luigi | luigi/contrib/salesforce.py | SalesforceAPI.query | def query(self, query, **kwargs):
"""
Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload.
:param query: the SOQL query to send to Salesforce, e.g. "SELECT id from Lead WHERE email = 'a@b.com'"
"""
params = {'q': query}
response = requests.get(self._get_norm_query_url(),
headers=self._get_rest_headers(),
params=params,
**kwargs)
if response.status_code != requests.codes.ok:
raise Exception(response.content)
return response.json() | python | def query(self, query, **kwargs):
"""
Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload.
:param query: the SOQL query to send to Salesforce, e.g. "SELECT id from Lead WHERE email = 'a@b.com'"
"""
params = {'q': query}
response = requests.get(self._get_norm_query_url(),
headers=self._get_rest_headers(),
params=params,
**kwargs)
if response.status_code != requests.codes.ok:
raise Exception(response.content)
return response.json() | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'q'",
":",
"query",
"}",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_get_norm_query_url",
"(",
")",
",",
"headers",
"=",
"self",
"."... | Return the result of a Salesforce SOQL query as a dict decoded from the Salesforce response JSON payload.
:param query: the SOQL query to send to Salesforce, e.g. "SELECT id from Lead WHERE email = 'a@b.com'" | [
"Return",
"the",
"result",
"of",
"a",
"Salesforce",
"SOQL",
"query",
"as",
"a",
"dict",
"decoded",
"from",
"the",
"Salesforce",
"response",
"JSON",
"payload",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L286-L300 |
31,636 | spotify/luigi | luigi/contrib/salesforce.py | SalesforceAPI.query_more | def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs):
"""
Retrieves more results from a query that returned more results
than the batch maximum. Returns a dict decoded from the Salesforce
response JSON payload.
:param next_records_identifier: either the Id of the next Salesforce
object in the result, or a URL to the
next record in the result.
:param identifier_is_url: True if `next_records_identifier` should be
treated as a URL, False if
`next_records_identifer` should be treated as
an Id.
"""
if identifier_is_url:
# Don't use `self.base_url` here because the full URI is provided
url = (u'https://{instance}{next_record_url}'
.format(instance=self.hostname,
next_record_url=next_records_identifier))
else:
url = self._get_norm_query_url() + '{next_record_id}'
url = url.format(next_record_id=next_records_identifier)
response = requests.get(url, headers=self._get_rest_headers(), **kwargs)
response.raise_for_status()
return response.json() | python | def query_more(self, next_records_identifier, identifier_is_url=False, **kwargs):
"""
Retrieves more results from a query that returned more results
than the batch maximum. Returns a dict decoded from the Salesforce
response JSON payload.
:param next_records_identifier: either the Id of the next Salesforce
object in the result, or a URL to the
next record in the result.
:param identifier_is_url: True if `next_records_identifier` should be
treated as a URL, False if
`next_records_identifer` should be treated as
an Id.
"""
if identifier_is_url:
# Don't use `self.base_url` here because the full URI is provided
url = (u'https://{instance}{next_record_url}'
.format(instance=self.hostname,
next_record_url=next_records_identifier))
else:
url = self._get_norm_query_url() + '{next_record_id}'
url = url.format(next_record_id=next_records_identifier)
response = requests.get(url, headers=self._get_rest_headers(), **kwargs)
response.raise_for_status()
return response.json() | [
"def",
"query_more",
"(",
"self",
",",
"next_records_identifier",
",",
"identifier_is_url",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"identifier_is_url",
":",
"# Don't use `self.base_url` here because the full URI is provided",
"url",
"=",
"(",
"u'https://... | Retrieves more results from a query that returned more results
than the batch maximum. Returns a dict decoded from the Salesforce
response JSON payload.
:param next_records_identifier: either the Id of the next Salesforce
object in the result, or a URL to the
next record in the result.
:param identifier_is_url: True if `next_records_identifier` should be
treated as a URL, False if
`next_records_identifer` should be treated as
an Id. | [
"Retrieves",
"more",
"results",
"from",
"a",
"query",
"that",
"returned",
"more",
"results",
"than",
"the",
"batch",
"maximum",
".",
"Returns",
"a",
"dict",
"decoded",
"from",
"the",
"Salesforce",
"response",
"JSON",
"payload",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L302-L328 |
31,637 | spotify/luigi | luigi/contrib/salesforce.py | SalesforceAPI.get_job_details | def get_job_details(self, job_id):
"""
Gets all details for existing job
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: job info as xml
"""
response = requests.get(self._get_job_details_url(job_id))
response.raise_for_status()
return response | python | def get_job_details(self, job_id):
"""
Gets all details for existing job
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: job info as xml
"""
response = requests.get(self._get_job_details_url(job_id))
response.raise_for_status()
return response | [
"def",
"get_job_details",
"(",
"self",
",",
"job_id",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_get_job_details_url",
"(",
"job_id",
")",
")",
"response",
".",
"raise_for_status",
"(",
")",
"return",
"response"
] | Gets all details for existing job
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: job info as xml | [
"Gets",
"all",
"details",
"for",
"existing",
"job"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L415-L426 |
31,638 | spotify/luigi | luigi/contrib/salesforce.py | SalesforceAPI.abort_job | def abort_job(self, job_id):
"""
Abort an existing job. When a job is aborted, no more records are processed.
Changes to data may already have been committed and aren't rolled back.
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: abort response as xml
"""
response = requests.post(self._get_abort_job_url(job_id),
headers=self._get_abort_job_headers(),
data=self._get_abort_job_xml())
response.raise_for_status()
return response | python | def abort_job(self, job_id):
"""
Abort an existing job. When a job is aborted, no more records are processed.
Changes to data may already have been committed and aren't rolled back.
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: abort response as xml
"""
response = requests.post(self._get_abort_job_url(job_id),
headers=self._get_abort_job_headers(),
data=self._get_abort_job_xml())
response.raise_for_status()
return response | [
"def",
"abort_job",
"(",
"self",
",",
"job_id",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"_get_abort_job_url",
"(",
"job_id",
")",
",",
"headers",
"=",
"self",
".",
"_get_abort_job_headers",
"(",
")",
",",
"data",
"=",
"self"... | Abort an existing job. When a job is aborted, no more records are processed.
Changes to data may already have been committed and aren't rolled back.
:param job_id: job_id as returned by 'create_operation_job(...)'
:return: abort response as xml | [
"Abort",
"an",
"existing",
"job",
".",
"When",
"a",
"job",
"is",
"aborted",
"no",
"more",
"records",
"are",
"processed",
".",
"Changes",
"to",
"data",
"may",
"already",
"have",
"been",
"committed",
"and",
"aren",
"t",
"rolled",
"back",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L428-L441 |
31,639 | spotify/luigi | luigi/contrib/salesforce.py | SalesforceAPI.create_batch | def create_batch(self, job_id, data, file_type):
"""
Creates a batch with either a string of data or a file containing data.
If a file is provided, this will pull the contents of the file_target into memory when running.
That shouldn't be a problem for any files that meet the Salesforce single batch upload
size limit (10MB) and is done to ensure compressed files can be uploaded properly.
:param job_id: job_id as returned by 'create_operation_job(...)'
:param data:
:return: Returns batch_id
"""
if not job_id or not self.has_active_session():
raise Exception("Can not create a batch without a valid job_id and an active session.")
headers = self._get_create_batch_content_headers(file_type)
headers['Content-Length'] = str(len(data))
response = requests.post(self._get_create_batch_url(job_id),
headers=headers,
data=data)
response.raise_for_status()
root = ET.fromstring(response.text)
batch_id = root.find('%sid' % self.API_NS).text
return batch_id | python | def create_batch(self, job_id, data, file_type):
"""
Creates a batch with either a string of data or a file containing data.
If a file is provided, this will pull the contents of the file_target into memory when running.
That shouldn't be a problem for any files that meet the Salesforce single batch upload
size limit (10MB) and is done to ensure compressed files can be uploaded properly.
:param job_id: job_id as returned by 'create_operation_job(...)'
:param data:
:return: Returns batch_id
"""
if not job_id or not self.has_active_session():
raise Exception("Can not create a batch without a valid job_id and an active session.")
headers = self._get_create_batch_content_headers(file_type)
headers['Content-Length'] = str(len(data))
response = requests.post(self._get_create_batch_url(job_id),
headers=headers,
data=data)
response.raise_for_status()
root = ET.fromstring(response.text)
batch_id = root.find('%sid' % self.API_NS).text
return batch_id | [
"def",
"create_batch",
"(",
"self",
",",
"job_id",
",",
"data",
",",
"file_type",
")",
":",
"if",
"not",
"job_id",
"or",
"not",
"self",
".",
"has_active_session",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"Can not create a batch without a valid job_id and an act... | Creates a batch with either a string of data or a file containing data.
If a file is provided, this will pull the contents of the file_target into memory when running.
That shouldn't be a problem for any files that meet the Salesforce single batch upload
size limit (10MB) and is done to ensure compressed files can be uploaded properly.
:param job_id: job_id as returned by 'create_operation_job(...)'
:param data:
:return: Returns batch_id | [
"Creates",
"a",
"batch",
"with",
"either",
"a",
"string",
"of",
"data",
"or",
"a",
"file",
"containing",
"data",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L460-L486 |
31,640 | spotify/luigi | luigi/contrib/salesforce.py | SalesforceAPI.get_batch_result_ids | def get_batch_result_ids(self, job_id, batch_id):
"""
Get result IDs of a batch that has completed processing.
:param job_id: job_id as returned by 'create_operation_job(...)'
:param batch_id: batch_id as returned by 'create_batch(...)'
:return: list of batch result IDs to be used in 'get_batch_result(...)'
"""
response = requests.get(self._get_batch_results_url(job_id, batch_id),
headers=self._get_batch_info_headers())
response.raise_for_status()
root = ET.fromstring(response.text)
result_ids = [r.text for r in root.findall('%sresult' % self.API_NS)]
return result_ids | python | def get_batch_result_ids(self, job_id, batch_id):
"""
Get result IDs of a batch that has completed processing.
:param job_id: job_id as returned by 'create_operation_job(...)'
:param batch_id: batch_id as returned by 'create_batch(...)'
:return: list of batch result IDs to be used in 'get_batch_result(...)'
"""
response = requests.get(self._get_batch_results_url(job_id, batch_id),
headers=self._get_batch_info_headers())
response.raise_for_status()
root = ET.fromstring(response.text)
result_ids = [r.text for r in root.findall('%sresult' % self.API_NS)]
return result_ids | [
"def",
"get_batch_result_ids",
"(",
"self",
",",
"job_id",
",",
"batch_id",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_get_batch_results_url",
"(",
"job_id",
",",
"batch_id",
")",
",",
"headers",
"=",
"self",
".",
"_get_batch_info... | Get result IDs of a batch that has completed processing.
:param job_id: job_id as returned by 'create_operation_job(...)'
:param batch_id: batch_id as returned by 'create_batch(...)'
:return: list of batch result IDs to be used in 'get_batch_result(...)' | [
"Get",
"result",
"IDs",
"of",
"a",
"batch",
"that",
"has",
"completed",
"processing",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/salesforce.py#L518-L533 |
31,641 | spotify/luigi | luigi/contrib/sge.py | _parse_qstat_state | def _parse_qstat_state(qstat_out, job_id):
"""Parse "state" column from `qstat` output for given job_id
Returns state for the *first* job matching job_id. Returns 'u' if
`qstat` output is empty or job_id is not found.
"""
if qstat_out.strip() == '':
return 'u'
lines = qstat_out.split('\n')
# skip past header
while not lines.pop(0).startswith('---'):
pass
for line in lines:
if line:
job, prior, name, user, state = line.strip().split()[0:5]
if int(job) == int(job_id):
return state
return 'u' | python | def _parse_qstat_state(qstat_out, job_id):
"""Parse "state" column from `qstat` output for given job_id
Returns state for the *first* job matching job_id. Returns 'u' if
`qstat` output is empty or job_id is not found.
"""
if qstat_out.strip() == '':
return 'u'
lines = qstat_out.split('\n')
# skip past header
while not lines.pop(0).startswith('---'):
pass
for line in lines:
if line:
job, prior, name, user, state = line.strip().split()[0:5]
if int(job) == int(job_id):
return state
return 'u' | [
"def",
"_parse_qstat_state",
"(",
"qstat_out",
",",
"job_id",
")",
":",
"if",
"qstat_out",
".",
"strip",
"(",
")",
"==",
"''",
":",
"return",
"'u'",
"lines",
"=",
"qstat_out",
".",
"split",
"(",
"'\\n'",
")",
"# skip past header",
"while",
"not",
"lines",
... | Parse "state" column from `qstat` output for given job_id
Returns state for the *first* job matching job_id. Returns 'u' if
`qstat` output is empty or job_id is not found. | [
"Parse",
"state",
"column",
"from",
"qstat",
"output",
"for",
"given",
"job_id"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/sge.py#L113-L131 |
31,642 | spotify/luigi | examples/elasticsearch_index.py | FakeDocuments.run | def run(self):
"""
Writes data in JSON format into the task's output target.
The data objects have the following attributes:
* `_id` is the default Elasticsearch id field,
* `text`: the text,
* `date`: the day when the data was created.
"""
today = datetime.date.today()
with self.output().open('w') as output:
for i in range(5):
output.write(json.dumps({'_id': i, 'text': 'Hi %s' % i,
'date': str(today)}))
output.write('\n') | python | def run(self):
"""
Writes data in JSON format into the task's output target.
The data objects have the following attributes:
* `_id` is the default Elasticsearch id field,
* `text`: the text,
* `date`: the day when the data was created.
"""
today = datetime.date.today()
with self.output().open('w') as output:
for i in range(5):
output.write(json.dumps({'_id': i, 'text': 'Hi %s' % i,
'date': str(today)}))
output.write('\n') | [
"def",
"run",
"(",
"self",
")",
":",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"with",
"self",
".",
"output",
"(",
")",
".",
"open",
"(",
"'w'",
")",
"as",
"output",
":",
"for",
"i",
"in",
"range",
"(",
"5",
")",
":",
"ou... | Writes data in JSON format into the task's output target.
The data objects have the following attributes:
* `_id` is the default Elasticsearch id field,
* `text`: the text,
* `date`: the day when the data was created. | [
"Writes",
"data",
"in",
"JSON",
"format",
"into",
"the",
"task",
"s",
"output",
"target",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/elasticsearch_index.py#L32-L48 |
31,643 | spotify/luigi | luigi/contrib/hdfs/clients.py | get_autoconfig_client | def get_autoconfig_client(client_cache=_AUTOCONFIG_CLIENT):
"""
Creates the client as specified in the `luigi.cfg` configuration.
"""
try:
return client_cache.client
except AttributeError:
configured_client = hdfs_config.get_configured_hdfs_client()
if configured_client == "webhdfs":
client_cache.client = hdfs_webhdfs_client.WebHdfsClient()
elif configured_client == "snakebite":
client_cache.client = hdfs_snakebite_client.SnakebiteHdfsClient()
elif configured_client == "snakebite_with_hadoopcli_fallback":
client_cache.client = luigi.contrib.target.CascadingClient([
hdfs_snakebite_client.SnakebiteHdfsClient(),
hdfs_hadoopcli_clients.create_hadoopcli_client(),
])
elif configured_client == "hadoopcli":
client_cache.client = hdfs_hadoopcli_clients.create_hadoopcli_client()
else:
raise Exception("Unknown hdfs client " + configured_client)
return client_cache.client | python | def get_autoconfig_client(client_cache=_AUTOCONFIG_CLIENT):
"""
Creates the client as specified in the `luigi.cfg` configuration.
"""
try:
return client_cache.client
except AttributeError:
configured_client = hdfs_config.get_configured_hdfs_client()
if configured_client == "webhdfs":
client_cache.client = hdfs_webhdfs_client.WebHdfsClient()
elif configured_client == "snakebite":
client_cache.client = hdfs_snakebite_client.SnakebiteHdfsClient()
elif configured_client == "snakebite_with_hadoopcli_fallback":
client_cache.client = luigi.contrib.target.CascadingClient([
hdfs_snakebite_client.SnakebiteHdfsClient(),
hdfs_hadoopcli_clients.create_hadoopcli_client(),
])
elif configured_client == "hadoopcli":
client_cache.client = hdfs_hadoopcli_clients.create_hadoopcli_client()
else:
raise Exception("Unknown hdfs client " + configured_client)
return client_cache.client | [
"def",
"get_autoconfig_client",
"(",
"client_cache",
"=",
"_AUTOCONFIG_CLIENT",
")",
":",
"try",
":",
"return",
"client_cache",
".",
"client",
"except",
"AttributeError",
":",
"configured_client",
"=",
"hdfs_config",
".",
"get_configured_hdfs_client",
"(",
")",
"if",
... | Creates the client as specified in the `luigi.cfg` configuration. | [
"Creates",
"the",
"client",
"as",
"specified",
"in",
"the",
"luigi",
".",
"cfg",
"configuration",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/clients.py#L36-L57 |
31,644 | spotify/luigi | luigi/notifications.py | send_email_ses | def send_email_ses(sender, subject, message, recipients, image_png):
"""
Sends notification through AWS SES.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from boto3 import client as boto3_client
client = boto3_client('ses')
msg_root = generate_email(sender, subject, message, recipients, image_png)
response = client.send_raw_email(Source=sender,
Destinations=recipients,
RawMessage={'Data': msg_root.as_string()})
logger.debug(("Message sent to SES.\nMessageId: {},\nRequestId: {},\n"
"HTTPSStatusCode: {}").format(response['MessageId'],
response['ResponseMetadata']['RequestId'],
response['ResponseMetadata']['HTTPStatusCode'])) | python | def send_email_ses(sender, subject, message, recipients, image_png):
"""
Sends notification through AWS SES.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from boto3 import client as boto3_client
client = boto3_client('ses')
msg_root = generate_email(sender, subject, message, recipients, image_png)
response = client.send_raw_email(Source=sender,
Destinations=recipients,
RawMessage={'Data': msg_root.as_string()})
logger.debug(("Message sent to SES.\nMessageId: {},\nRequestId: {},\n"
"HTTPSStatusCode: {}").format(response['MessageId'],
response['ResponseMetadata']['RequestId'],
response['ResponseMetadata']['HTTPStatusCode'])) | [
"def",
"send_email_ses",
"(",
"sender",
",",
"subject",
",",
"message",
",",
"recipients",
",",
"image_png",
")",
":",
"from",
"boto3",
"import",
"client",
"as",
"boto3_client",
"client",
"=",
"boto3_client",
"(",
"'ses'",
")",
"msg_root",
"=",
"generate_email... | Sends notification through AWS SES.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. | [
"Sends",
"notification",
"through",
"AWS",
"SES",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L210-L232 |
31,645 | spotify/luigi | luigi/notifications.py | send_email_sns | def send_email_sns(sender, subject, message, topic_ARN, image_png):
"""
Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from boto3 import resource as boto3_resource
sns = boto3_resource('sns')
topic = sns.Topic(topic_ARN[0])
# Subject is max 100 chars
if len(subject) > 100:
subject = subject[0:48] + '...' + subject[-49:]
response = topic.publish(Subject=subject, Message=message)
logger.debug(("Message sent to SNS.\nMessageId: {},\nRequestId: {},\n"
"HTTPSStatusCode: {}").format(response['MessageId'],
response['ResponseMetadata']['RequestId'],
response['ResponseMetadata']['HTTPStatusCode'])) | python | def send_email_sns(sender, subject, message, topic_ARN, image_png):
"""
Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from boto3 import resource as boto3_resource
sns = boto3_resource('sns')
topic = sns.Topic(topic_ARN[0])
# Subject is max 100 chars
if len(subject) > 100:
subject = subject[0:48] + '...' + subject[-49:]
response = topic.publish(Subject=subject, Message=message)
logger.debug(("Message sent to SNS.\nMessageId: {},\nRequestId: {},\n"
"HTTPSStatusCode: {}").format(response['MessageId'],
response['ResponseMetadata']['RequestId'],
response['ResponseMetadata']['HTTPStatusCode'])) | [
"def",
"send_email_sns",
"(",
"sender",
",",
"subject",
",",
"message",
",",
"topic_ARN",
",",
"image_png",
")",
":",
"from",
"boto3",
"import",
"resource",
"as",
"boto3_resource",
"sns",
"=",
"boto3_resource",
"(",
"'sns'",
")",
"topic",
"=",
"sns",
".",
... | Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html. | [
"Sends",
"notification",
"through",
"AWS",
"SNS",
".",
"Takes",
"Topic",
"ARN",
"from",
"recipients",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L264-L288 |
31,646 | spotify/luigi | luigi/notifications.py | send_email | def send_email(subject, message, sender, recipients, image_png=None):
"""
Decides whether to send notification. Notification is cancelled if there are
no recipients or if stdout is onto tty or if in debug mode.
Dispatches on config value email.method. Default is 'smtp'.
"""
notifiers = {
'ses': send_email_ses,
'sendgrid': send_email_sendgrid,
'smtp': send_email_smtp,
'sns': send_email_sns,
}
subject = _prefix(subject)
if not recipients or recipients == (None,):
return
if _email_disabled_reason():
logger.info("Not sending email to %r because %s",
recipients, _email_disabled_reason())
return
# Clean the recipients lists to allow multiple email addresses, comma
# separated in luigi.cfg
recipients_tmp = []
for r in recipients:
recipients_tmp.extend([a.strip() for a in r.split(',') if a.strip()])
# Replace original recipients with the clean list
recipients = recipients_tmp
logger.info("Sending email to %r", recipients)
# Get appropriate sender and call it to send the notification
email_sender = notifiers[email().method]
email_sender(sender, subject, message, recipients, image_png) | python | def send_email(subject, message, sender, recipients, image_png=None):
"""
Decides whether to send notification. Notification is cancelled if there are
no recipients or if stdout is onto tty or if in debug mode.
Dispatches on config value email.method. Default is 'smtp'.
"""
notifiers = {
'ses': send_email_ses,
'sendgrid': send_email_sendgrid,
'smtp': send_email_smtp,
'sns': send_email_sns,
}
subject = _prefix(subject)
if not recipients or recipients == (None,):
return
if _email_disabled_reason():
logger.info("Not sending email to %r because %s",
recipients, _email_disabled_reason())
return
# Clean the recipients lists to allow multiple email addresses, comma
# separated in luigi.cfg
recipients_tmp = []
for r in recipients:
recipients_tmp.extend([a.strip() for a in r.split(',') if a.strip()])
# Replace original recipients with the clean list
recipients = recipients_tmp
logger.info("Sending email to %r", recipients)
# Get appropriate sender and call it to send the notification
email_sender = notifiers[email().method]
email_sender(sender, subject, message, recipients, image_png) | [
"def",
"send_email",
"(",
"subject",
",",
"message",
",",
"sender",
",",
"recipients",
",",
"image_png",
"=",
"None",
")",
":",
"notifiers",
"=",
"{",
"'ses'",
":",
"send_email_ses",
",",
"'sendgrid'",
":",
"send_email_sendgrid",
",",
"'smtp'",
":",
"send_em... | Decides whether to send notification. Notification is cancelled if there are
no recipients or if stdout is onto tty or if in debug mode.
Dispatches on config value email.method. Default is 'smtp'. | [
"Decides",
"whether",
"to",
"send",
"notification",
".",
"Notification",
"is",
"cancelled",
"if",
"there",
"are",
"no",
"recipients",
"or",
"if",
"stdout",
"is",
"onto",
"tty",
"or",
"if",
"in",
"debug",
"mode",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L291-L327 |
31,647 | spotify/luigi | luigi/notifications.py | send_error_email | def send_error_email(subject, message, additional_recipients=None):
"""
Sends an email to the configured error email, if it's configured.
"""
recipients = _email_recipients(additional_recipients)
sender = email().sender
send_email(
subject=subject,
message=message,
sender=sender,
recipients=recipients
) | python | def send_error_email(subject, message, additional_recipients=None):
"""
Sends an email to the configured error email, if it's configured.
"""
recipients = _email_recipients(additional_recipients)
sender = email().sender
send_email(
subject=subject,
message=message,
sender=sender,
recipients=recipients
) | [
"def",
"send_error_email",
"(",
"subject",
",",
"message",
",",
"additional_recipients",
"=",
"None",
")",
":",
"recipients",
"=",
"_email_recipients",
"(",
"additional_recipients",
")",
"sender",
"=",
"email",
"(",
")",
".",
"sender",
"send_email",
"(",
"subjec... | Sends an email to the configured error email, if it's configured. | [
"Sends",
"an",
"email",
"to",
"the",
"configured",
"error",
"email",
"if",
"it",
"s",
"configured",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L341-L352 |
31,648 | spotify/luigi | luigi/notifications.py | format_task_error | def format_task_error(headline, task, command, formatted_exception=None):
"""
Format a message body for an error email related to a luigi.task.Task
:param headline: Summary line for the message
:param task: `luigi.task.Task` instance where this error occurred
:param formatted_exception: optional string showing traceback
:return: message body
"""
if formatted_exception:
formatted_exception = wrap_traceback(formatted_exception)
else:
formatted_exception = ""
if email().format == 'html':
msg_template = textwrap.dedent('''
<html>
<body>
<h2>{headline}</h2>
<table style="border-top: 1px solid black; border-bottom: 1px solid black">
<thead>
<tr><th>name</th><td>{name}</td></tr>
</thead>
<tbody>
{param_rows}
</tbody>
</table>
</pre>
<h2>Command line</h2>
<pre>
{command}
</pre>
<h2>Traceback</h2>
{traceback}
</body>
</html>
''')
str_params = task.to_str_params()
params = '\n'.join('<tr><th>{}</th><td>{}</td></tr>'.format(*items) for items in str_params.items())
body = msg_template.format(headline=headline, name=task.task_family, param_rows=params,
command=command, traceback=formatted_exception)
else:
msg_template = textwrap.dedent('''\
{headline}
Name: {name}
Parameters:
{params}
Command line:
{command}
{traceback}
''')
str_params = task.to_str_params()
max_width = max([0] + [len(x) for x in str_params.keys()])
params = '\n'.join(' {:{width}}: {}'.format(*items, width=max_width) for items in str_params.items())
body = msg_template.format(headline=headline, name=task.task_family, params=params,
command=command, traceback=formatted_exception)
return body | python | def format_task_error(headline, task, command, formatted_exception=None):
"""
Format a message body for an error email related to a luigi.task.Task
:param headline: Summary line for the message
:param task: `luigi.task.Task` instance where this error occurred
:param formatted_exception: optional string showing traceback
:return: message body
"""
if formatted_exception:
formatted_exception = wrap_traceback(formatted_exception)
else:
formatted_exception = ""
if email().format == 'html':
msg_template = textwrap.dedent('''
<html>
<body>
<h2>{headline}</h2>
<table style="border-top: 1px solid black; border-bottom: 1px solid black">
<thead>
<tr><th>name</th><td>{name}</td></tr>
</thead>
<tbody>
{param_rows}
</tbody>
</table>
</pre>
<h2>Command line</h2>
<pre>
{command}
</pre>
<h2>Traceback</h2>
{traceback}
</body>
</html>
''')
str_params = task.to_str_params()
params = '\n'.join('<tr><th>{}</th><td>{}</td></tr>'.format(*items) for items in str_params.items())
body = msg_template.format(headline=headline, name=task.task_family, param_rows=params,
command=command, traceback=formatted_exception)
else:
msg_template = textwrap.dedent('''\
{headline}
Name: {name}
Parameters:
{params}
Command line:
{command}
{traceback}
''')
str_params = task.to_str_params()
max_width = max([0] + [len(x) for x in str_params.keys()])
params = '\n'.join(' {:{width}}: {}'.format(*items, width=max_width) for items in str_params.items())
body = msg_template.format(headline=headline, name=task.task_family, params=params,
command=command, traceback=formatted_exception)
return body | [
"def",
"format_task_error",
"(",
"headline",
",",
"task",
",",
"command",
",",
"formatted_exception",
"=",
"None",
")",
":",
"if",
"formatted_exception",
":",
"formatted_exception",
"=",
"wrap_traceback",
"(",
"formatted_exception",
")",
"else",
":",
"formatted_exce... | Format a message body for an error email related to a luigi.task.Task
:param headline: Summary line for the message
:param task: `luigi.task.Task` instance where this error occurred
:param formatted_exception: optional string showing traceback
:return: message body | [
"Format",
"a",
"message",
"body",
"for",
"an",
"error",
"email",
"related",
"to",
"a",
"luigi",
".",
"task",
".",
"Task"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/notifications.py#L366-L434 |
31,649 | spotify/luigi | luigi/contrib/hdfs/webhdfs_client.py | WebHdfsClient.exists | def exists(self, path):
"""
Returns true if the path exists and false otherwise.
"""
import hdfs
try:
self.client.status(path)
return True
except hdfs.util.HdfsError as e:
if str(e).startswith('File does not exist: '):
return False
else:
raise e | python | def exists(self, path):
"""
Returns true if the path exists and false otherwise.
"""
import hdfs
try:
self.client.status(path)
return True
except hdfs.util.HdfsError as e:
if str(e).startswith('File does not exist: '):
return False
else:
raise e | [
"def",
"exists",
"(",
"self",
",",
"path",
")",
":",
"import",
"hdfs",
"try",
":",
"self",
".",
"client",
".",
"status",
"(",
"path",
")",
"return",
"True",
"except",
"hdfs",
".",
"util",
".",
"HdfsError",
"as",
"e",
":",
"if",
"str",
"(",
"e",
"... | Returns true if the path exists and false otherwise. | [
"Returns",
"true",
"if",
"the",
"path",
"exists",
"and",
"false",
"otherwise",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/webhdfs_client.py#L89-L101 |
31,650 | spotify/luigi | luigi/contrib/hdfs/webhdfs_client.py | WebHdfsClient.touchz | def touchz(self, path):
"""
To touchz using the web hdfs "write" cmd.
"""
self.client.write(path, data='', overwrite=False) | python | def touchz(self, path):
"""
To touchz using the web hdfs "write" cmd.
"""
self.client.write(path, data='', overwrite=False) | [
"def",
"touchz",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"client",
".",
"write",
"(",
"path",
",",
"data",
"=",
"''",
",",
"overwrite",
"=",
"False",
")"
] | To touchz using the web hdfs "write" cmd. | [
"To",
"touchz",
"using",
"the",
"web",
"hdfs",
"write",
"cmd",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/hdfs/webhdfs_client.py#L179-L183 |
31,651 | spotify/luigi | luigi/contrib/azureblob.py | AzureBlobTarget.open | def open(self, mode):
"""
Open the target for reading or writing
:param char mode:
'r' for reading and 'w' for writing.
'b' is not supported and will be stripped if used. For binary mode, use `format`
:return:
* :class:`.ReadableAzureBlobFile` if 'r'
* :class:`.AtomicAzureBlobFile` if 'w'
"""
if mode not in ('r', 'w'):
raise ValueError("Unsupported open mode '%s'" % mode)
if mode == 'r':
return self.format.pipe_reader(ReadableAzureBlobFile(self.container, self.blob, self.client, self.download_when_reading, **self.azure_blob_options))
else:
return self.format.pipe_writer(AtomicAzureBlobFile(self.container, self.blob, self.client, **self.azure_blob_options)) | python | def open(self, mode):
"""
Open the target for reading or writing
:param char mode:
'r' for reading and 'w' for writing.
'b' is not supported and will be stripped if used. For binary mode, use `format`
:return:
* :class:`.ReadableAzureBlobFile` if 'r'
* :class:`.AtomicAzureBlobFile` if 'w'
"""
if mode not in ('r', 'w'):
raise ValueError("Unsupported open mode '%s'" % mode)
if mode == 'r':
return self.format.pipe_reader(ReadableAzureBlobFile(self.container, self.blob, self.client, self.download_when_reading, **self.azure_blob_options))
else:
return self.format.pipe_writer(AtomicAzureBlobFile(self.container, self.blob, self.client, **self.azure_blob_options)) | [
"def",
"open",
"(",
"self",
",",
"mode",
")",
":",
"if",
"mode",
"not",
"in",
"(",
"'r'",
",",
"'w'",
")",
":",
"raise",
"ValueError",
"(",
"\"Unsupported open mode '%s'\"",
"%",
"mode",
")",
"if",
"mode",
"==",
"'r'",
":",
"return",
"self",
".",
"fo... | Open the target for reading or writing
:param char mode:
'r' for reading and 'w' for writing.
'b' is not supported and will be stripped if used. For binary mode, use `format`
:return:
* :class:`.ReadableAzureBlobFile` if 'r'
* :class:`.AtomicAzureBlobFile` if 'w' | [
"Open",
"the",
"target",
"for",
"reading",
"or",
"writing"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/azureblob.py#L275-L292 |
31,652 | spotify/luigi | luigi/contrib/simulate.py | RunAnywayTarget.get_path | def get_path(self):
"""
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
"""
md5_hash = hashlib.md5(self.task_id.encode()).hexdigest()
logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id)
return os.path.join(self.temp_dir, str(self.unique.value), md5_hash) | python | def get_path(self):
"""
Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments
"""
md5_hash = hashlib.md5(self.task_id.encode()).hexdigest()
logger.debug('Hash %s corresponds to task %s', md5_hash, self.task_id)
return os.path.join(self.temp_dir, str(self.unique.value), md5_hash) | [
"def",
"get_path",
"(",
"self",
")",
":",
"md5_hash",
"=",
"hashlib",
".",
"md5",
"(",
"self",
".",
"task_id",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"logger",
".",
"debug",
"(",
"'Hash %s corresponds to task %s'",
",",
"md5_hash",
","... | Returns a temporary file path based on a MD5 hash generated with the task's name and its arguments | [
"Returns",
"a",
"temporary",
"file",
"path",
"based",
"on",
"a",
"MD5",
"hash",
"generated",
"with",
"the",
"task",
"s",
"name",
"and",
"its",
"arguments"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/simulate.py#L82-L89 |
31,653 | spotify/luigi | luigi/contrib/simulate.py | RunAnywayTarget.done | def done(self):
"""
Creates temporary file to mark the task as `done`
"""
logger.info('Marking %s as done', self)
fn = self.get_path()
try:
os.makedirs(os.path.dirname(fn))
except OSError:
pass
open(fn, 'w').close() | python | def done(self):
"""
Creates temporary file to mark the task as `done`
"""
logger.info('Marking %s as done', self)
fn = self.get_path()
try:
os.makedirs(os.path.dirname(fn))
except OSError:
pass
open(fn, 'w').close() | [
"def",
"done",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Marking %s as done'",
",",
"self",
")",
"fn",
"=",
"self",
".",
"get_path",
"(",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fn",
")",
"... | Creates temporary file to mark the task as `done` | [
"Creates",
"temporary",
"file",
"to",
"mark",
"the",
"task",
"as",
"done"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/simulate.py#L97-L108 |
31,654 | spotify/luigi | luigi/contrib/s3.py | S3Client.exists | def exists(self, path):
"""
Does provided path exist on S3?
"""
(bucket, key) = self._path_to_bucket_and_key(path)
# root always exists
if self._is_root(key):
return True
# file
if self._exists(bucket, key):
return True
if self.isdir(path):
return True
logger.debug('Path %s does not exist', path)
return False | python | def exists(self, path):
"""
Does provided path exist on S3?
"""
(bucket, key) = self._path_to_bucket_and_key(path)
# root always exists
if self._is_root(key):
return True
# file
if self._exists(bucket, key):
return True
if self.isdir(path):
return True
logger.debug('Path %s does not exist', path)
return False | [
"def",
"exists",
"(",
"self",
",",
"path",
")",
":",
"(",
"bucket",
",",
"key",
")",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"# root always exists",
"if",
"self",
".",
"_is_root",
"(",
"key",
")",
":",
"return",
"True",
"# file",
... | Does provided path exist on S3? | [
"Does",
"provided",
"path",
"exist",
"on",
"S3?"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L177-L195 |
31,655 | spotify/luigi | luigi/contrib/s3.py | S3Client.get_key | def get_key(self, path):
"""
Returns the object summary at the path
"""
(bucket, key) = self._path_to_bucket_and_key(path)
if self._exists(bucket, key):
return self.s3.ObjectSummary(bucket, key) | python | def get_key(self, path):
"""
Returns the object summary at the path
"""
(bucket, key) = self._path_to_bucket_and_key(path)
if self._exists(bucket, key):
return self.s3.ObjectSummary(bucket, key) | [
"def",
"get_key",
"(",
"self",
",",
"path",
")",
":",
"(",
"bucket",
",",
"key",
")",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"if",
"self",
".",
"_exists",
"(",
"bucket",
",",
"key",
")",
":",
"return",
"self",
".",
"s3",
"."... | Returns the object summary at the path | [
"Returns",
"the",
"object",
"summary",
"at",
"the",
"path"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L247-L254 |
31,656 | spotify/luigi | luigi/contrib/s3.py | S3Client.get | def get(self, s3_path, destination_local_path):
"""
Get an object stored in S3 and write it to a local path.
"""
(bucket, key) = self._path_to_bucket_and_key(s3_path)
# download the file
self.s3.meta.client.download_file(bucket, key, destination_local_path) | python | def get(self, s3_path, destination_local_path):
"""
Get an object stored in S3 and write it to a local path.
"""
(bucket, key) = self._path_to_bucket_and_key(s3_path)
# download the file
self.s3.meta.client.download_file(bucket, key, destination_local_path) | [
"def",
"get",
"(",
"self",
",",
"s3_path",
",",
"destination_local_path",
")",
":",
"(",
"bucket",
",",
"key",
")",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"s3_path",
")",
"# download the file",
"self",
".",
"s3",
".",
"meta",
".",
"client",
".",... | Get an object stored in S3 and write it to a local path. | [
"Get",
"an",
"object",
"stored",
"in",
"S3",
"and",
"write",
"it",
"to",
"a",
"local",
"path",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L383-L389 |
31,657 | spotify/luigi | luigi/contrib/s3.py | S3Client.get_as_bytes | def get_as_bytes(self, s3_path):
"""
Get the contents of an object stored in S3 as bytes
:param s3_path: URL for target S3 location
:return: File contents as pure bytes
"""
(bucket, key) = self._path_to_bucket_and_key(s3_path)
obj = self.s3.Object(bucket, key)
contents = obj.get()['Body'].read()
return contents | python | def get_as_bytes(self, s3_path):
"""
Get the contents of an object stored in S3 as bytes
:param s3_path: URL for target S3 location
:return: File contents as pure bytes
"""
(bucket, key) = self._path_to_bucket_and_key(s3_path)
obj = self.s3.Object(bucket, key)
contents = obj.get()['Body'].read()
return contents | [
"def",
"get_as_bytes",
"(",
"self",
",",
"s3_path",
")",
":",
"(",
"bucket",
",",
"key",
")",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"s3_path",
")",
"obj",
"=",
"self",
".",
"s3",
".",
"Object",
"(",
"bucket",
",",
"key",
")",
"contents",
... | Get the contents of an object stored in S3 as bytes
:param s3_path: URL for target S3 location
:return: File contents as pure bytes | [
"Get",
"the",
"contents",
"of",
"an",
"object",
"stored",
"in",
"S3",
"as",
"bytes"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L391-L401 |
31,658 | spotify/luigi | luigi/contrib/s3.py | S3Client.get_as_string | def get_as_string(self, s3_path, encoding='utf-8'):
"""
Get the contents of an object stored in S3 as string.
:param s3_path: URL for target S3 location
:param encoding: Encoding to decode bytes to string
:return: File contents as a string
"""
content = self.get_as_bytes(s3_path)
return content.decode(encoding) | python | def get_as_string(self, s3_path, encoding='utf-8'):
"""
Get the contents of an object stored in S3 as string.
:param s3_path: URL for target S3 location
:param encoding: Encoding to decode bytes to string
:return: File contents as a string
"""
content = self.get_as_bytes(s3_path)
return content.decode(encoding) | [
"def",
"get_as_string",
"(",
"self",
",",
"s3_path",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"content",
"=",
"self",
".",
"get_as_bytes",
"(",
"s3_path",
")",
"return",
"content",
".",
"decode",
"(",
"encoding",
")"
] | Get the contents of an object stored in S3 as string.
:param s3_path: URL for target S3 location
:param encoding: Encoding to decode bytes to string
:return: File contents as a string | [
"Get",
"the",
"contents",
"of",
"an",
"object",
"stored",
"in",
"S3",
"as",
"string",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L403-L412 |
31,659 | spotify/luigi | luigi/contrib/s3.py | S3Client.isdir | def isdir(self, path):
"""
Is the parameter S3 path a directory?
"""
(bucket, key) = self._path_to_bucket_and_key(path)
s3_bucket = self.s3.Bucket(bucket)
# root is a directory
if self._is_root(key):
return True
for suffix in (S3_DIRECTORY_MARKER_SUFFIX_0,
S3_DIRECTORY_MARKER_SUFFIX_1):
try:
self.s3.meta.client.get_object(
Bucket=bucket, Key=key + suffix)
except botocore.exceptions.ClientError as e:
if not e.response['Error']['Code'] in ['NoSuchKey', '404']:
raise
else:
return True
# files with this prefix
key_path = self._add_path_delimiter(key)
s3_bucket_list_result = list(itertools.islice(
s3_bucket.objects.filter(Prefix=key_path), 1))
if s3_bucket_list_result:
return True
return False | python | def isdir(self, path):
"""
Is the parameter S3 path a directory?
"""
(bucket, key) = self._path_to_bucket_and_key(path)
s3_bucket = self.s3.Bucket(bucket)
# root is a directory
if self._is_root(key):
return True
for suffix in (S3_DIRECTORY_MARKER_SUFFIX_0,
S3_DIRECTORY_MARKER_SUFFIX_1):
try:
self.s3.meta.client.get_object(
Bucket=bucket, Key=key + suffix)
except botocore.exceptions.ClientError as e:
if not e.response['Error']['Code'] in ['NoSuchKey', '404']:
raise
else:
return True
# files with this prefix
key_path = self._add_path_delimiter(key)
s3_bucket_list_result = list(itertools.islice(
s3_bucket.objects.filter(Prefix=key_path), 1))
if s3_bucket_list_result:
return True
return False | [
"def",
"isdir",
"(",
"self",
",",
"path",
")",
":",
"(",
"bucket",
",",
"key",
")",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"s3_bucket",
"=",
"self",
".",
"s3",
".",
"Bucket",
"(",
"bucket",
")",
"# root is a directory",
"if",
"s... | Is the parameter S3 path a directory? | [
"Is",
"the",
"parameter",
"S3",
"path",
"a",
"directory?"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/s3.py#L414-L444 |
31,660 | spotify/luigi | luigi/contrib/ftp.py | RemoteFileSystem.exists | def exists(self, path, mtime=None):
"""
Return `True` if file or directory at `path` exist, False otherwise.
Additional check on modified time when mtime is passed in.
Return False if the file's modified time is older mtime.
"""
self._connect()
if self.sftp:
exists = self._sftp_exists(path, mtime)
else:
exists = self._ftp_exists(path, mtime)
self._close()
return exists | python | def exists(self, path, mtime=None):
"""
Return `True` if file or directory at `path` exist, False otherwise.
Additional check on modified time when mtime is passed in.
Return False if the file's modified time is older mtime.
"""
self._connect()
if self.sftp:
exists = self._sftp_exists(path, mtime)
else:
exists = self._ftp_exists(path, mtime)
self._close()
return exists | [
"def",
"exists",
"(",
"self",
",",
"path",
",",
"mtime",
"=",
"None",
")",
":",
"self",
".",
"_connect",
"(",
")",
"if",
"self",
".",
"sftp",
":",
"exists",
"=",
"self",
".",
"_sftp_exists",
"(",
"path",
",",
"mtime",
")",
"else",
":",
"exists",
... | Return `True` if file or directory at `path` exist, False otherwise.
Additional check on modified time when mtime is passed in.
Return False if the file's modified time is older mtime. | [
"Return",
"True",
"if",
"file",
"or",
"directory",
"at",
"path",
"exist",
"False",
"otherwise",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L109-L126 |
31,661 | spotify/luigi | luigi/contrib/ftp.py | RemoteFileSystem._rm_recursive | def _rm_recursive(self, ftp, path):
"""
Recursively delete a directory tree on a remote server.
Source: https://gist.github.com/artlogic/2632647
"""
wd = ftp.pwd()
# check if it is a file first, because some FTP servers don't return
# correctly on ftp.nlst(file)
try:
ftp.cwd(path)
except ftplib.all_errors:
# this is a file, we will just delete the file
ftp.delete(path)
return
try:
names = ftp.nlst()
except ftplib.all_errors:
# some FTP servers complain when you try and list non-existent paths
return
for name in names:
if os.path.split(name)[1] in ('.', '..'):
continue
try:
ftp.cwd(name) # if we can cwd to it, it's a folder
ftp.cwd(wd) # don't try a nuke a folder we're in
ftp.cwd(path) # then go back to where we were
self._rm_recursive(ftp, name)
except ftplib.all_errors:
ftp.delete(name)
try:
ftp.cwd(wd) # do not delete the folder that we are in
ftp.rmd(path)
except ftplib.all_errors as e:
print('_rm_recursive: Could not remove {0}: {1}'.format(path, e)) | python | def _rm_recursive(self, ftp, path):
"""
Recursively delete a directory tree on a remote server.
Source: https://gist.github.com/artlogic/2632647
"""
wd = ftp.pwd()
# check if it is a file first, because some FTP servers don't return
# correctly on ftp.nlst(file)
try:
ftp.cwd(path)
except ftplib.all_errors:
# this is a file, we will just delete the file
ftp.delete(path)
return
try:
names = ftp.nlst()
except ftplib.all_errors:
# some FTP servers complain when you try and list non-existent paths
return
for name in names:
if os.path.split(name)[1] in ('.', '..'):
continue
try:
ftp.cwd(name) # if we can cwd to it, it's a folder
ftp.cwd(wd) # don't try a nuke a folder we're in
ftp.cwd(path) # then go back to where we were
self._rm_recursive(ftp, name)
except ftplib.all_errors:
ftp.delete(name)
try:
ftp.cwd(wd) # do not delete the folder that we are in
ftp.rmd(path)
except ftplib.all_errors as e:
print('_rm_recursive: Could not remove {0}: {1}'.format(path, e)) | [
"def",
"_rm_recursive",
"(",
"self",
",",
"ftp",
",",
"path",
")",
":",
"wd",
"=",
"ftp",
".",
"pwd",
"(",
")",
"# check if it is a file first, because some FTP servers don't return",
"# correctly on ftp.nlst(file)",
"try",
":",
"ftp",
".",
"cwd",
"(",
"path",
")"... | Recursively delete a directory tree on a remote server.
Source: https://gist.github.com/artlogic/2632647 | [
"Recursively",
"delete",
"a",
"directory",
"tree",
"on",
"a",
"remote",
"server",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L197-L236 |
31,662 | spotify/luigi | luigi/contrib/ftp.py | RemoteTarget.open | def open(self, mode):
"""
Open the FileSystem target.
This method returns a file-like object which can either be read from or written to depending
on the specified mode.
:param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will
open the FileSystemTarget in write mode. Subclasses can implement
additional options.
:type mode: str
"""
if mode == 'w':
return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path))
elif mode == 'r':
temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp')
self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0, 1e10)
# download file to local
self._fs.get(self.path, self.__tmp_path)
return self.format.pipe_reader(
FileWrapper(io.BufferedReader(io.FileIO(self.__tmp_path, 'r')))
)
else:
raise Exception("mode must be 'r' or 'w' (got: %s)" % mode) | python | def open(self, mode):
"""
Open the FileSystem target.
This method returns a file-like object which can either be read from or written to depending
on the specified mode.
:param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will
open the FileSystemTarget in write mode. Subclasses can implement
additional options.
:type mode: str
"""
if mode == 'w':
return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path))
elif mode == 'r':
temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp')
self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0, 1e10)
# download file to local
self._fs.get(self.path, self.__tmp_path)
return self.format.pipe_reader(
FileWrapper(io.BufferedReader(io.FileIO(self.__tmp_path, 'r')))
)
else:
raise Exception("mode must be 'r' or 'w' (got: %s)" % mode) | [
"def",
"open",
"(",
"self",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"'w'",
":",
"return",
"self",
".",
"format",
".",
"pipe_writer",
"(",
"AtomicFtpFile",
"(",
"self",
".",
"_fs",
",",
"self",
".",
"path",
")",
")",
"elif",
"mode",
"==",
"'r'",
... | Open the FileSystem target.
This method returns a file-like object which can either be read from or written to depending
on the specified mode.
:param mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will
open the FileSystemTarget in write mode. Subclasses can implement
additional options.
:type mode: str | [
"Open",
"the",
"FileSystem",
"target",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/ftp.py#L394-L419 |
31,663 | spotify/luigi | luigi/contrib/mongodb.py | MongoTarget.get_collection | def get_collection(self):
"""
Return targeted mongo collection to query on
"""
db_mongo = self._mongo_client[self._index]
return db_mongo[self._collection] | python | def get_collection(self):
"""
Return targeted mongo collection to query on
"""
db_mongo = self._mongo_client[self._index]
return db_mongo[self._collection] | [
"def",
"get_collection",
"(",
"self",
")",
":",
"db_mongo",
"=",
"self",
".",
"_mongo_client",
"[",
"self",
".",
"_index",
"]",
"return",
"db_mongo",
"[",
"self",
".",
"_collection",
"]"
] | Return targeted mongo collection to query on | [
"Return",
"targeted",
"mongo",
"collection",
"to",
"query",
"on"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L38-L43 |
31,664 | spotify/luigi | luigi/contrib/mongodb.py | MongoCellTarget.write | def write(self, value):
"""
Write value to the target
"""
self.get_collection().update_one(
{'_id': self._document_id},
{'$set': {self._path: value}},
upsert=True
) | python | def write(self, value):
"""
Write value to the target
"""
self.get_collection().update_one(
{'_id': self._document_id},
{'$set': {self._path: value}},
upsert=True
) | [
"def",
"write",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"get_collection",
"(",
")",
".",
"update_one",
"(",
"{",
"'_id'",
":",
"self",
".",
"_document_id",
"}",
",",
"{",
"'$set'",
":",
"{",
"self",
".",
"_path",
":",
"value",
"}",
"}",
... | Write value to the target | [
"Write",
"value",
"to",
"the",
"target"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L91-L99 |
31,665 | spotify/luigi | luigi/contrib/mongodb.py | MongoRangeTarget.read | def read(self):
"""
Read the targets value
"""
cursor = self.get_collection().find(
{
'_id': {'$in': self._document_ids},
self._field: {'$exists': True}
},
{self._field: True}
)
return {doc['_id']: doc[self._field] for doc in cursor} | python | def read(self):
"""
Read the targets value
"""
cursor = self.get_collection().find(
{
'_id': {'$in': self._document_ids},
self._field: {'$exists': True}
},
{self._field: True}
)
return {doc['_id']: doc[self._field] for doc in cursor} | [
"def",
"read",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"get_collection",
"(",
")",
".",
"find",
"(",
"{",
"'_id'",
":",
"{",
"'$in'",
":",
"self",
".",
"_document_ids",
"}",
",",
"self",
".",
"_field",
":",
"{",
"'$exists'",
":",
"True",... | Read the targets value | [
"Read",
"the",
"targets",
"value"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L125-L137 |
31,666 | spotify/luigi | luigi/contrib/mongodb.py | MongoRangeTarget.get_empty_ids | def get_empty_ids(self):
"""
Get documents id with missing targeted field
"""
cursor = self.get_collection().find(
{
'_id': {'$in': self._document_ids},
self._field: {'$exists': True}
},
{'_id': True}
)
return set(self._document_ids) - {doc['_id'] for doc in cursor} | python | def get_empty_ids(self):
"""
Get documents id with missing targeted field
"""
cursor = self.get_collection().find(
{
'_id': {'$in': self._document_ids},
self._field: {'$exists': True}
},
{'_id': True}
)
return set(self._document_ids) - {doc['_id'] for doc in cursor} | [
"def",
"get_empty_ids",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"get_collection",
"(",
")",
".",
"find",
"(",
"{",
"'_id'",
":",
"{",
"'$in'",
":",
"self",
".",
"_document_ids",
"}",
",",
"self",
".",
"_field",
":",
"{",
"'$exists'",
":",
... | Get documents id with missing targeted field | [
"Get",
"documents",
"id",
"with",
"missing",
"targeted",
"field"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L157-L169 |
31,667 | spotify/luigi | luigi/setup_logging.py | BaseLogging._section | def _section(cls, opts):
"""Get logging settings from config file section "logging"."""
if isinstance(cls.config, LuigiConfigParser):
return False
try:
logging_config = cls.config['logging']
except (TypeError, KeyError, NoSectionError):
return False
logging.config.dictConfig(logging_config)
return True | python | def _section(cls, opts):
"""Get logging settings from config file section "logging"."""
if isinstance(cls.config, LuigiConfigParser):
return False
try:
logging_config = cls.config['logging']
except (TypeError, KeyError, NoSectionError):
return False
logging.config.dictConfig(logging_config)
return True | [
"def",
"_section",
"(",
"cls",
",",
"opts",
")",
":",
"if",
"isinstance",
"(",
"cls",
".",
"config",
",",
"LuigiConfigParser",
")",
":",
"return",
"False",
"try",
":",
"logging_config",
"=",
"cls",
".",
"config",
"[",
"'logging'",
"]",
"except",
"(",
"... | Get logging settings from config file section "logging". | [
"Get",
"logging",
"settings",
"from",
"config",
"file",
"section",
"logging",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L40-L49 |
31,668 | spotify/luigi | luigi/setup_logging.py | BaseLogging.setup | def setup(cls,
opts=type('opts', (), {
'background': None,
'logdir': None,
'logging_conf_file': None,
'log_level': 'DEBUG'
})):
"""Setup logging via CLI params and config."""
logger = logging.getLogger('luigi')
if cls._configured:
logger.info('logging already configured')
return False
cls._configured = True
if cls.config.getboolean('core', 'no_configure_logging', False):
logger.info('logging disabled in settings')
return False
configured = cls._cli(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured via special settings')
return True
configured = cls._conf(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured via *.conf file')
return True
configured = cls._section(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured via config section')
return True
configured = cls._default(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured by default settings')
return configured | python | def setup(cls,
opts=type('opts', (), {
'background': None,
'logdir': None,
'logging_conf_file': None,
'log_level': 'DEBUG'
})):
"""Setup logging via CLI params and config."""
logger = logging.getLogger('luigi')
if cls._configured:
logger.info('logging already configured')
return False
cls._configured = True
if cls.config.getboolean('core', 'no_configure_logging', False):
logger.info('logging disabled in settings')
return False
configured = cls._cli(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured via special settings')
return True
configured = cls._conf(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured via *.conf file')
return True
configured = cls._section(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured via config section')
return True
configured = cls._default(opts)
if configured:
logger = logging.getLogger('luigi')
logger.info('logging configured by default settings')
return configured | [
"def",
"setup",
"(",
"cls",
",",
"opts",
"=",
"type",
"(",
"'opts'",
",",
"(",
")",
",",
"{",
"'background'",
":",
"None",
",",
"'logdir'",
":",
"None",
",",
"'logging_conf_file'",
":",
"None",
",",
"'log_level'",
":",
"'DEBUG'",
"}",
")",
")",
":",
... | Setup logging via CLI params and config. | [
"Setup",
"logging",
"via",
"CLI",
"params",
"and",
"config",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L52-L93 |
31,669 | spotify/luigi | luigi/setup_logging.py | DaemonLogging._cli | def _cli(cls, opts):
"""Setup logging via CLI options
If `--background` -- set INFO level for root logger.
If `--logdir` -- set logging with next params:
default Luigi's formatter,
INFO level,
output in logdir in `luigi-server.log` file
"""
if opts.background:
logging.getLogger().setLevel(logging.INFO)
return True
if opts.logdir:
logging.basicConfig(
level=logging.INFO,
format=cls._log_format,
filename=os.path.join(opts.logdir, "luigi-server.log"))
return True
return False | python | def _cli(cls, opts):
"""Setup logging via CLI options
If `--background` -- set INFO level for root logger.
If `--logdir` -- set logging with next params:
default Luigi's formatter,
INFO level,
output in logdir in `luigi-server.log` file
"""
if opts.background:
logging.getLogger().setLevel(logging.INFO)
return True
if opts.logdir:
logging.basicConfig(
level=logging.INFO,
format=cls._log_format,
filename=os.path.join(opts.logdir, "luigi-server.log"))
return True
return False | [
"def",
"_cli",
"(",
"cls",
",",
"opts",
")",
":",
"if",
"opts",
".",
"background",
":",
"logging",
".",
"getLogger",
"(",
")",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"return",
"True",
"if",
"opts",
".",
"logdir",
":",
"logging",
".",
"b... | Setup logging via CLI options
If `--background` -- set INFO level for root logger.
If `--logdir` -- set logging with next params:
default Luigi's formatter,
INFO level,
output in logdir in `luigi-server.log` file | [
"Setup",
"logging",
"via",
"CLI",
"options"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/setup_logging.py#L103-L123 |
31,670 | spotify/luigi | luigi/contrib/gcs.py | GCSClient.listdir | def listdir(self, path):
"""
Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path.
"""
bucket, obj = self._path_to_bucket_and_key(path)
obj_prefix = self._add_path_delimiter(obj)
if self._is_root(obj_prefix):
obj_prefix = ''
obj_prefix_len = len(obj_prefix)
for it in self._list_iter(bucket, obj_prefix):
yield self._add_path_delimiter(path) + it['name'][obj_prefix_len:] | python | def listdir(self, path):
"""
Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path.
"""
bucket, obj = self._path_to_bucket_and_key(path)
obj_prefix = self._add_path_delimiter(obj)
if self._is_root(obj_prefix):
obj_prefix = ''
obj_prefix_len = len(obj_prefix)
for it in self._list_iter(bucket, obj_prefix):
yield self._add_path_delimiter(path) + it['name'][obj_prefix_len:] | [
"def",
"listdir",
"(",
"self",
",",
"path",
")",
":",
"bucket",
",",
"obj",
"=",
"self",
".",
"_path_to_bucket_and_key",
"(",
"path",
")",
"obj_prefix",
"=",
"self",
".",
"_add_path_delimiter",
"(",
"obj",
")",
"if",
"self",
".",
"_is_root",
"(",
"obj_pr... | Get an iterable with GCS folder contents.
Iterable contains paths relative to queried path. | [
"Get",
"an",
"iterable",
"with",
"GCS",
"folder",
"contents",
".",
"Iterable",
"contains",
"paths",
"relative",
"to",
"queried",
"path",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L351-L364 |
31,671 | spotify/luigi | luigi/contrib/gcs.py | GCSClient.list_wildcard | def list_wildcard(self, wildcard_path):
"""Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iterator.py...)
"""
path, wildcard_obj = wildcard_path.rsplit('/', 1)
assert '*' not in path, "The '*' wildcard character is only supported after the last '/'"
wildcard_parts = wildcard_obj.split('*')
assert len(wildcard_parts) == 2, "Only one '*' wildcard is supported"
for it in self.listdir(path):
if it.startswith(path + '/' + wildcard_parts[0]) and it.endswith(wildcard_parts[1]) and \
len(it) >= len(path + '/' + wildcard_parts[0]) + len(wildcard_parts[1]):
yield it | python | def list_wildcard(self, wildcard_path):
"""Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iterator.py...)
"""
path, wildcard_obj = wildcard_path.rsplit('/', 1)
assert '*' not in path, "The '*' wildcard character is only supported after the last '/'"
wildcard_parts = wildcard_obj.split('*')
assert len(wildcard_parts) == 2, "Only one '*' wildcard is supported"
for it in self.listdir(path):
if it.startswith(path + '/' + wildcard_parts[0]) and it.endswith(wildcard_parts[1]) and \
len(it) >= len(path + '/' + wildcard_parts[0]) + len(wildcard_parts[1]):
yield it | [
"def",
"list_wildcard",
"(",
"self",
",",
"wildcard_path",
")",
":",
"path",
",",
"wildcard_obj",
"=",
"wildcard_path",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"assert",
"'*'",
"not",
"in",
"path",
",",
"\"The '*' wildcard character is only supported after the l... | Yields full object URIs matching the given wildcard.
Currently only the '*' wildcard after the last path delimiter is supported.
(If we need "full" wildcard functionality we should bring in gsutil dependency with its
https://github.com/GoogleCloudPlatform/gsutil/blob/master/gslib/wildcard_iterator.py...) | [
"Yields",
"full",
"object",
"URIs",
"matching",
"the",
"given",
"wildcard",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L366-L382 |
31,672 | spotify/luigi | luigi/contrib/gcs.py | GCSClient.download | def download(self, path, chunksize=None, chunk_callback=lambda _: False):
"""Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True.
"""
chunksize = chunksize or self.chunksize
bucket, obj = self._path_to_bucket_and_key(path)
with tempfile.NamedTemporaryFile(delete=False) as fp:
# We can't return the tempfile reference because of a bug in python: http://bugs.python.org/issue18879
return_fp = _DeleteOnCloseFile(fp.name, 'r')
# Special case empty files because chunk-based downloading doesn't work.
result = self.client.objects().get(bucket=bucket, object=obj).execute()
if int(result['size']) == 0:
return return_fp
request = self.client.objects().get_media(bucket=bucket, object=obj)
downloader = http.MediaIoBaseDownload(fp, request, chunksize=chunksize)
attempts = 0
done = False
while not done:
error = None
try:
_, done = downloader.next_chunk()
if chunk_callback(fp):
done = True
except errors.HttpError as err:
error = err
if err.resp.status < 500:
raise
logger.warning('Error downloading file, retrying', exc_info=True)
except RETRYABLE_ERRORS as err:
logger.warning('Error downloading file, retrying', exc_info=True)
error = err
if error:
attempts += 1
if attempts >= NUM_RETRIES:
raise error
else:
attempts = 0
return return_fp | python | def download(self, path, chunksize=None, chunk_callback=lambda _: False):
"""Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True.
"""
chunksize = chunksize or self.chunksize
bucket, obj = self._path_to_bucket_and_key(path)
with tempfile.NamedTemporaryFile(delete=False) as fp:
# We can't return the tempfile reference because of a bug in python: http://bugs.python.org/issue18879
return_fp = _DeleteOnCloseFile(fp.name, 'r')
# Special case empty files because chunk-based downloading doesn't work.
result = self.client.objects().get(bucket=bucket, object=obj).execute()
if int(result['size']) == 0:
return return_fp
request = self.client.objects().get_media(bucket=bucket, object=obj)
downloader = http.MediaIoBaseDownload(fp, request, chunksize=chunksize)
attempts = 0
done = False
while not done:
error = None
try:
_, done = downloader.next_chunk()
if chunk_callback(fp):
done = True
except errors.HttpError as err:
error = err
if err.resp.status < 500:
raise
logger.warning('Error downloading file, retrying', exc_info=True)
except RETRYABLE_ERRORS as err:
logger.warning('Error downloading file, retrying', exc_info=True)
error = err
if error:
attempts += 1
if attempts >= NUM_RETRIES:
raise error
else:
attempts = 0
return return_fp | [
"def",
"download",
"(",
"self",
",",
"path",
",",
"chunksize",
"=",
"None",
",",
"chunk_callback",
"=",
"lambda",
"_",
":",
"False",
")",
":",
"chunksize",
"=",
"chunksize",
"or",
"self",
".",
"chunksize",
"bucket",
",",
"obj",
"=",
"self",
".",
"_path... | Downloads the object contents to local file system.
Optionally stops after the first chunk for which chunk_callback returns True. | [
"Downloads",
"the",
"object",
"contents",
"to",
"local",
"file",
"system",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcs.py#L384-L428 |
31,673 | spotify/luigi | luigi/format.py | OutputPipeProcessWrapper._finish | def _finish(self):
"""
Closes and waits for subprocess to exit.
"""
if self._process.returncode is None:
self._process.stdin.flush()
self._process.stdin.close()
self._process.wait()
self.closed = True | python | def _finish(self):
"""
Closes and waits for subprocess to exit.
"""
if self._process.returncode is None:
self._process.stdin.flush()
self._process.stdin.close()
self._process.wait()
self.closed = True | [
"def",
"_finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
".",
"returncode",
"is",
"None",
":",
"self",
".",
"_process",
".",
"stdin",
".",
"flush",
"(",
")",
"self",
".",
"_process",
".",
"stdin",
".",
"close",
"(",
")",
"self",
".",... | Closes and waits for subprocess to exit. | [
"Closes",
"and",
"waits",
"for",
"subprocess",
"to",
"exit",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/format.py#L197-L205 |
31,674 | spotify/luigi | luigi/worker.py | check_complete | def check_complete(task, out_queue):
"""
Checks if task is complete, puts the result to out_queue.
"""
logger.debug("Checking if %s is complete", task)
try:
is_complete = task.complete()
except Exception:
is_complete = TracebackWrapper(traceback.format_exc())
out_queue.put((task, is_complete)) | python | def check_complete(task, out_queue):
"""
Checks if task is complete, puts the result to out_queue.
"""
logger.debug("Checking if %s is complete", task)
try:
is_complete = task.complete()
except Exception:
is_complete = TracebackWrapper(traceback.format_exc())
out_queue.put((task, is_complete)) | [
"def",
"check_complete",
"(",
"task",
",",
"out_queue",
")",
":",
"logger",
".",
"debug",
"(",
"\"Checking if %s is complete\"",
",",
"task",
")",
"try",
":",
"is_complete",
"=",
"task",
".",
"complete",
"(",
")",
"except",
"Exception",
":",
"is_complete",
"... | Checks if task is complete, puts the result to out_queue. | [
"Checks",
"if",
"task",
"is",
"complete",
"puts",
"the",
"result",
"to",
"out_queue",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L395-L404 |
31,675 | spotify/luigi | luigi/worker.py | Worker.add | def add(self, task, multiprocess=False, processes=0):
"""
Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before.
"""
if self._first_task is None and hasattr(task, 'task_id'):
self._first_task = task.task_id
self.add_succeeded = True
if multiprocess:
queue = multiprocessing.Manager().Queue()
pool = multiprocessing.Pool(processes=processes if processes > 0 else None)
else:
queue = DequeQueue()
pool = SingleProcessPool()
self._validate_task(task)
pool.apply_async(check_complete, [task, queue])
# we track queue size ourselves because len(queue) won't work for multiprocessing
queue_size = 1
try:
seen = {task.task_id}
while queue_size:
current = queue.get()
queue_size -= 1
item, is_complete = current
for next in self._add(item, is_complete):
if next.task_id not in seen:
self._validate_task(next)
seen.add(next.task_id)
pool.apply_async(check_complete, [next, queue])
queue_size += 1
except (KeyboardInterrupt, TaskException):
raise
except Exception as ex:
self.add_succeeded = False
formatted_traceback = traceback.format_exc()
self._log_unexpected_error(task)
task.trigger_event(Event.BROKEN_TASK, task, ex)
self._email_unexpected_error(task, formatted_traceback)
raise
finally:
pool.close()
pool.join()
return self.add_succeeded | python | def add(self, task, multiprocess=False, processes=0):
"""
Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before.
"""
if self._first_task is None and hasattr(task, 'task_id'):
self._first_task = task.task_id
self.add_succeeded = True
if multiprocess:
queue = multiprocessing.Manager().Queue()
pool = multiprocessing.Pool(processes=processes if processes > 0 else None)
else:
queue = DequeQueue()
pool = SingleProcessPool()
self._validate_task(task)
pool.apply_async(check_complete, [task, queue])
# we track queue size ourselves because len(queue) won't work for multiprocessing
queue_size = 1
try:
seen = {task.task_id}
while queue_size:
current = queue.get()
queue_size -= 1
item, is_complete = current
for next in self._add(item, is_complete):
if next.task_id not in seen:
self._validate_task(next)
seen.add(next.task_id)
pool.apply_async(check_complete, [next, queue])
queue_size += 1
except (KeyboardInterrupt, TaskException):
raise
except Exception as ex:
self.add_succeeded = False
formatted_traceback = traceback.format_exc()
self._log_unexpected_error(task)
task.trigger_event(Event.BROKEN_TASK, task, ex)
self._email_unexpected_error(task, formatted_traceback)
raise
finally:
pool.close()
pool.join()
return self.add_succeeded | [
"def",
"add",
"(",
"self",
",",
"task",
",",
"multiprocess",
"=",
"False",
",",
"processes",
"=",
"0",
")",
":",
"if",
"self",
".",
"_first_task",
"is",
"None",
"and",
"hasattr",
"(",
"task",
",",
"'task_id'",
")",
":",
"self",
".",
"_first_task",
"=... | Add a Task for the worker to check and possibly schedule and run.
Returns True if task and its dependencies were successfully scheduled or completed before. | [
"Add",
"a",
"Task",
"for",
"the",
"worker",
"to",
"check",
"and",
"possibly",
"schedule",
"and",
"run",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L725-L769 |
31,676 | spotify/luigi | luigi/worker.py | Worker._purge_children | def _purge_children(self):
"""
Find dead children and put a response on the result queue.
:return:
"""
for task_id, p in six.iteritems(self._running_tasks):
if not p.is_alive() and p.exitcode:
error_msg = 'Task {} died unexpectedly with exit code {}'.format(task_id, p.exitcode)
p.task.trigger_event(Event.PROCESS_FAILURE, p.task, error_msg)
elif p.timeout_time is not None and time.time() > float(p.timeout_time) and p.is_alive():
p.terminate()
error_msg = 'Task {} timed out after {} seconds and was terminated.'.format(task_id, p.worker_timeout)
p.task.trigger_event(Event.TIMEOUT, p.task, error_msg)
else:
continue
logger.info(error_msg)
self._task_result_queue.put((task_id, FAILED, error_msg, [], [])) | python | def _purge_children(self):
"""
Find dead children and put a response on the result queue.
:return:
"""
for task_id, p in six.iteritems(self._running_tasks):
if not p.is_alive() and p.exitcode:
error_msg = 'Task {} died unexpectedly with exit code {}'.format(task_id, p.exitcode)
p.task.trigger_event(Event.PROCESS_FAILURE, p.task, error_msg)
elif p.timeout_time is not None and time.time() > float(p.timeout_time) and p.is_alive():
p.terminate()
error_msg = 'Task {} timed out after {} seconds and was terminated.'.format(task_id, p.worker_timeout)
p.task.trigger_event(Event.TIMEOUT, p.task, error_msg)
else:
continue
logger.info(error_msg)
self._task_result_queue.put((task_id, FAILED, error_msg, [], [])) | [
"def",
"_purge_children",
"(",
"self",
")",
":",
"for",
"task_id",
",",
"p",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_running_tasks",
")",
":",
"if",
"not",
"p",
".",
"is_alive",
"(",
")",
"and",
"p",
".",
"exitcode",
":",
"error_msg",
"=",... | Find dead children and put a response on the result queue.
:return: | [
"Find",
"dead",
"children",
"and",
"put",
"a",
"response",
"on",
"the",
"result",
"queue",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1021-L1039 |
31,677 | spotify/luigi | luigi/worker.py | Worker._keep_alive | def _keep_alive(self, get_work_response):
"""
Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pending_tasks.
If worker-count-uniques is true, it will also
require that one of the tasks is unique to this worker.
"""
if not self._config.keep_alive:
return False
elif self._assistant:
return True
elif self._config.count_last_scheduled:
return get_work_response.n_pending_last_scheduled > 0
elif self._config.count_uniques:
return get_work_response.n_unique_pending > 0
elif get_work_response.n_pending_tasks == 0:
return False
elif not self._config.max_keep_alive_idle_duration:
return True
elif not self._idle_since:
return True
else:
time_to_shutdown = self._idle_since + self._config.max_keep_alive_idle_duration - datetime.datetime.now()
logger.debug("[%s] %s until shutdown", self._id, time_to_shutdown)
return time_to_shutdown > datetime.timedelta(0) | python | def _keep_alive(self, get_work_response):
"""
Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pending_tasks.
If worker-count-uniques is true, it will also
require that one of the tasks is unique to this worker.
"""
if not self._config.keep_alive:
return False
elif self._assistant:
return True
elif self._config.count_last_scheduled:
return get_work_response.n_pending_last_scheduled > 0
elif self._config.count_uniques:
return get_work_response.n_unique_pending > 0
elif get_work_response.n_pending_tasks == 0:
return False
elif not self._config.max_keep_alive_idle_duration:
return True
elif not self._idle_since:
return True
else:
time_to_shutdown = self._idle_since + self._config.max_keep_alive_idle_duration - datetime.datetime.now()
logger.debug("[%s] %s until shutdown", self._id, time_to_shutdown)
return time_to_shutdown > datetime.timedelta(0) | [
"def",
"_keep_alive",
"(",
"self",
",",
"get_work_response",
")",
":",
"if",
"not",
"self",
".",
"_config",
".",
"keep_alive",
":",
"return",
"False",
"elif",
"self",
".",
"_assistant",
":",
"return",
"True",
"elif",
"self",
".",
"_config",
".",
"count_las... | Returns true if a worker should stay alive given.
If worker-keep-alive is not set, this will always return false.
For an assistant, it will always return the value of worker-keep-alive.
Otherwise, it will return true for nonzero n_pending_tasks.
If worker-count-uniques is true, it will also
require that one of the tasks is unique to this worker. | [
"Returns",
"true",
"if",
"a",
"worker",
"should",
"stay",
"alive",
"given",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1120-L1148 |
31,678 | spotify/luigi | luigi/worker.py | Worker.run | def run(self):
"""
Returns True if all scheduled tasks were executed successfully.
"""
logger.info('Running Worker with %d processes', self.worker_processes)
sleeper = self._sleeper()
self.run_succeeded = True
self._add_worker()
while True:
while len(self._running_tasks) >= self.worker_processes > 0:
logger.debug('%d running tasks, waiting for next task to finish', len(self._running_tasks))
self._handle_next_task()
get_work_response = self._get_work()
if get_work_response.worker_state == WORKER_STATE_DISABLED:
self._start_phasing_out()
if get_work_response.task_id is None:
if not self._stop_requesting_work:
self._log_remote_tasks(get_work_response)
if len(self._running_tasks) == 0:
self._idle_since = self._idle_since or datetime.datetime.now()
if self._keep_alive(get_work_response):
six.next(sleeper)
continue
else:
break
else:
self._handle_next_task()
continue
# task_id is not None:
logger.debug("Pending tasks: %s", get_work_response.n_pending_tasks)
self._run_task(get_work_response.task_id)
while len(self._running_tasks):
logger.debug('Shut down Worker, %d more tasks to go', len(self._running_tasks))
self._handle_next_task()
return self.run_succeeded | python | def run(self):
"""
Returns True if all scheduled tasks were executed successfully.
"""
logger.info('Running Worker with %d processes', self.worker_processes)
sleeper = self._sleeper()
self.run_succeeded = True
self._add_worker()
while True:
while len(self._running_tasks) >= self.worker_processes > 0:
logger.debug('%d running tasks, waiting for next task to finish', len(self._running_tasks))
self._handle_next_task()
get_work_response = self._get_work()
if get_work_response.worker_state == WORKER_STATE_DISABLED:
self._start_phasing_out()
if get_work_response.task_id is None:
if not self._stop_requesting_work:
self._log_remote_tasks(get_work_response)
if len(self._running_tasks) == 0:
self._idle_since = self._idle_since or datetime.datetime.now()
if self._keep_alive(get_work_response):
six.next(sleeper)
continue
else:
break
else:
self._handle_next_task()
continue
# task_id is not None:
logger.debug("Pending tasks: %s", get_work_response.n_pending_tasks)
self._run_task(get_work_response.task_id)
while len(self._running_tasks):
logger.debug('Shut down Worker, %d more tasks to go', len(self._running_tasks))
self._handle_next_task()
return self.run_succeeded | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Running Worker with %d processes'",
",",
"self",
".",
"worker_processes",
")",
"sleeper",
"=",
"self",
".",
"_sleeper",
"(",
")",
"self",
".",
"run_succeeded",
"=",
"True",
"self",
".",
"_a... | Returns True if all scheduled tasks were executed successfully. | [
"Returns",
"True",
"if",
"all",
"scheduled",
"tasks",
"were",
"executed",
"successfully",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/worker.py#L1165-L1208 |
31,679 | spotify/luigi | luigi/db_task_history.py | _upgrade_schema | def _upgrade_schema(engine):
"""
Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database.
"""
inspector = reflection.Inspector.from_engine(engine)
with engine.connect() as conn:
# Upgrade 1. Add task_id column and index to tasks
if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]:
logger.warning('Upgrading DbTaskHistory schema: Adding tasks.task_id')
conn.execute('ALTER TABLE tasks ADD COLUMN task_id VARCHAR(200)')
conn.execute('CREATE INDEX ix_task_id ON tasks (task_id)')
# Upgrade 2. Alter value column to be TEXT, note that this is idempotent so no if-guard
if 'mysql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY COLUMN value TEXT')
elif 'oracle' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY value TEXT')
elif 'mssql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TEXT')
elif 'postgresql' in engine.dialect.name:
if str([x for x in inspector.get_columns('task_parameters')
if x['name'] == 'value'][0]['type']) != 'TEXT':
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TYPE TEXT')
elif 'sqlite' in engine.dialect.name:
# SQLite does not support changing column types. A database file will need
# to be used to pickup this migration change.
for i in conn.execute('PRAGMA table_info(task_parameters);').fetchall():
if i['name'] == 'value' and i['type'] != 'TEXT':
logger.warning(
'SQLite can not change column types. Please use a new database '
'to pickup column type changes.'
)
else:
logger.warning(
'SQLAlcheny dialect {} could not be migrated to the TEXT type'.format(
engine.dialect
)
) | python | def _upgrade_schema(engine):
"""
Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database.
"""
inspector = reflection.Inspector.from_engine(engine)
with engine.connect() as conn:
# Upgrade 1. Add task_id column and index to tasks
if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]:
logger.warning('Upgrading DbTaskHistory schema: Adding tasks.task_id')
conn.execute('ALTER TABLE tasks ADD COLUMN task_id VARCHAR(200)')
conn.execute('CREATE INDEX ix_task_id ON tasks (task_id)')
# Upgrade 2. Alter value column to be TEXT, note that this is idempotent so no if-guard
if 'mysql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY COLUMN value TEXT')
elif 'oracle' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters MODIFY value TEXT')
elif 'mssql' in engine.dialect.name:
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TEXT')
elif 'postgresql' in engine.dialect.name:
if str([x for x in inspector.get_columns('task_parameters')
if x['name'] == 'value'][0]['type']) != 'TEXT':
conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TYPE TEXT')
elif 'sqlite' in engine.dialect.name:
# SQLite does not support changing column types. A database file will need
# to be used to pickup this migration change.
for i in conn.execute('PRAGMA table_info(task_parameters);').fetchall():
if i['name'] == 'value' and i['type'] != 'TEXT':
logger.warning(
'SQLite can not change column types. Please use a new database '
'to pickup column type changes.'
)
else:
logger.warning(
'SQLAlcheny dialect {} could not be migrated to the TEXT type'.format(
engine.dialect
)
) | [
"def",
"_upgrade_schema",
"(",
"engine",
")",
":",
"inspector",
"=",
"reflection",
".",
"Inspector",
".",
"from_engine",
"(",
"engine",
")",
"with",
"engine",
".",
"connect",
"(",
")",
"as",
"conn",
":",
"# Upgrade 1. Add task_id column and index to tasks",
"if",... | Ensure the database schema is up to date with the codebase.
:param engine: SQLAlchemy engine of the underlying database. | [
"Ensure",
"the",
"database",
"schema",
"is",
"up",
"to",
"date",
"with",
"the",
"codebase",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L243-L283 |
31,680 | spotify/luigi | luigi/db_task_history.py | DbTaskHistory.find_all_by_parameters | def find_all_by_parameters(self, task_name, session=None, **task_params):
"""
Find tasks with the given task_name and the same parameters as the kwargs.
"""
with self._session(session) as session:
query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == task_name)
for (k, v) in six.iteritems(task_params):
alias = sqlalchemy.orm.aliased(TaskParameter)
query = query.join(alias).filter(alias.name == k, alias.value == v)
tasks = query.order_by(TaskEvent.ts)
for task in tasks:
# Sanity check
assert all(k in task.parameters and v == str(task.parameters[k].value) for (k, v) in six.iteritems(task_params))
yield task | python | def find_all_by_parameters(self, task_name, session=None, **task_params):
"""
Find tasks with the given task_name and the same parameters as the kwargs.
"""
with self._session(session) as session:
query = session.query(TaskRecord).join(TaskEvent).filter(TaskRecord.name == task_name)
for (k, v) in six.iteritems(task_params):
alias = sqlalchemy.orm.aliased(TaskParameter)
query = query.join(alias).filter(alias.name == k, alias.value == v)
tasks = query.order_by(TaskEvent.ts)
for task in tasks:
# Sanity check
assert all(k in task.parameters and v == str(task.parameters[k].value) for (k, v) in six.iteritems(task_params))
yield task | [
"def",
"find_all_by_parameters",
"(",
"self",
",",
"task_name",
",",
"session",
"=",
"None",
",",
"*",
"*",
"task_params",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"query",
"=",
"session",
".",
"query",
"(",
... | Find tasks with the given task_name and the same parameters as the kwargs. | [
"Find",
"tasks",
"with",
"the",
"given",
"task_name",
"and",
"the",
"same",
"parameters",
"as",
"the",
"kwargs",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L134-L149 |
31,681 | spotify/luigi | luigi/db_task_history.py | DbTaskHistory.find_all_runs | def find_all_runs(self, session=None):
"""
Return all tasks that have been updated.
"""
with self._session(session) as session:
return session.query(TaskRecord).all() | python | def find_all_runs(self, session=None):
"""
Return all tasks that have been updated.
"""
with self._session(session) as session:
return session.query(TaskRecord).all() | [
"def",
"find_all_runs",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"return",
"session",
".",
"query",
"(",
"TaskRecord",
")",
".",
"all",
"(",
")"
] | Return all tasks that have been updated. | [
"Return",
"all",
"tasks",
"that",
"have",
"been",
"updated",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L170-L175 |
31,682 | spotify/luigi | luigi/db_task_history.py | DbTaskHistory.find_task_by_id | def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) | python | def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) | [
"def",
"find_task_by_id",
"(",
"self",
",",
"id",
",",
"session",
"=",
"None",
")",
":",
"with",
"self",
".",
"_session",
"(",
"session",
")",
"as",
"session",
":",
"return",
"session",
".",
"query",
"(",
"TaskRecord",
")",
".",
"get",
"(",
"id",
")"... | Find task with the given record ID. | [
"Find",
"task",
"with",
"the",
"given",
"record",
"ID",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/db_task_history.py#L184-L189 |
31,683 | spotify/luigi | luigi/contrib/gcp.py | get_authenticate_kwargs | def get_authenticate_kwargs(oauth_credentials=None, http_=None):
"""Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If that also fails, tries using httplib2.Http()
Used by `gcs.GCSClient` and `bigquery.BigQueryClient` to initiate the API Client
"""
if oauth_credentials:
authenticate_kwargs = {
"credentials": oauth_credentials
}
elif http_:
authenticate_kwargs = {
"http": http_
}
else:
# neither http_ or credentials provided
try:
# try default credentials
credentials, _ = google.auth.default()
authenticate_kwargs = {
"credentials": credentials
}
except google.auth.exceptions.DefaultCredentialsError:
# try http using httplib2
authenticate_kwargs = {
"http": httplib2.Http()
}
return authenticate_kwargs | python | def get_authenticate_kwargs(oauth_credentials=None, http_=None):
"""Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If that also fails, tries using httplib2.Http()
Used by `gcs.GCSClient` and `bigquery.BigQueryClient` to initiate the API Client
"""
if oauth_credentials:
authenticate_kwargs = {
"credentials": oauth_credentials
}
elif http_:
authenticate_kwargs = {
"http": http_
}
else:
# neither http_ or credentials provided
try:
# try default credentials
credentials, _ = google.auth.default()
authenticate_kwargs = {
"credentials": credentials
}
except google.auth.exceptions.DefaultCredentialsError:
# try http using httplib2
authenticate_kwargs = {
"http": httplib2.Http()
}
return authenticate_kwargs | [
"def",
"get_authenticate_kwargs",
"(",
"oauth_credentials",
"=",
"None",
",",
"http_",
"=",
"None",
")",
":",
"if",
"oauth_credentials",
":",
"authenticate_kwargs",
"=",
"{",
"\"credentials\"",
":",
"oauth_credentials",
"}",
"elif",
"http_",
":",
"authenticate_kwarg... | Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If that also fails, tries using httplib2.Http()
Used by `gcs.GCSClient` and `bigquery.BigQueryClient` to initiate the API Client | [
"Returns",
"a",
"dictionary",
"with",
"keyword",
"arguments",
"for",
"use",
"with",
"discovery"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/gcp.py#L15-L46 |
31,684 | spotify/luigi | luigi/contrib/redshift.py | _CredentialsMixin._credentials | def _credentials(self):
"""
Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError.
"""
if self.aws_account_id and self.aws_arn_role_name:
return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format(
id=self.aws_account_id,
role=self.aws_arn_role_name
)
elif self.aws_access_key_id and self.aws_secret_access_key:
return 'aws_access_key_id={key};aws_secret_access_key={secret}{opt}'.format(
key=self.aws_access_key_id,
secret=self.aws_secret_access_key,
opt=';token={}'.format(self.aws_session_token) if self.aws_session_token else ''
)
else:
raise NotImplementedError("Missing Credentials. "
"Ensure one of the pairs of auth args below are set "
"in a configuration file, environment variables or by "
"being overridden in the task: "
"'aws_access_key_id' AND 'aws_secret_access_key' OR "
"'aws_account_id' AND 'aws_arn_role_name'") | python | def _credentials(self):
"""
Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError.
"""
if self.aws_account_id and self.aws_arn_role_name:
return 'aws_iam_role=arn:aws:iam::{id}:role/{role}'.format(
id=self.aws_account_id,
role=self.aws_arn_role_name
)
elif self.aws_access_key_id and self.aws_secret_access_key:
return 'aws_access_key_id={key};aws_secret_access_key={secret}{opt}'.format(
key=self.aws_access_key_id,
secret=self.aws_secret_access_key,
opt=';token={}'.format(self.aws_session_token) if self.aws_session_token else ''
)
else:
raise NotImplementedError("Missing Credentials. "
"Ensure one of the pairs of auth args below are set "
"in a configuration file, environment variables or by "
"being overridden in the task: "
"'aws_access_key_id' AND 'aws_secret_access_key' OR "
"'aws_account_id' AND 'aws_arn_role_name'") | [
"def",
"_credentials",
"(",
"self",
")",
":",
"if",
"self",
".",
"aws_account_id",
"and",
"self",
".",
"aws_arn_role_name",
":",
"return",
"'aws_iam_role=arn:aws:iam::{id}:role/{role}'",
".",
"format",
"(",
"id",
"=",
"self",
".",
"aws_account_id",
",",
"role",
... | Return a credential string for the provided task. If no valid
credentials are set, raise a NotImplementedError. | [
"Return",
"a",
"credential",
"string",
"for",
"the",
"provided",
"task",
".",
"If",
"no",
"valid",
"credentials",
"are",
"set",
"raise",
"a",
"NotImplementedError",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L100-L123 |
31,685 | spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.create_schema | def create_schema(self, connection):
"""
Will create the schema in the database
"""
if '.' not in self.table:
return
query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0])
connection.cursor().execute(query) | python | def create_schema(self, connection):
"""
Will create the schema in the database
"""
if '.' not in self.table:
return
query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0])
connection.cursor().execute(query) | [
"def",
"create_schema",
"(",
"self",
",",
"connection",
")",
":",
"if",
"'.'",
"not",
"in",
"self",
".",
"table",
":",
"return",
"query",
"=",
"'CREATE SCHEMA IF NOT EXISTS {schema_name};'",
".",
"format",
"(",
"schema_name",
"=",
"self",
".",
"table",
".",
... | Will create the schema in the database | [
"Will",
"create",
"the",
"schema",
"in",
"the",
"database"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L283-L291 |
31,686 | spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.run | def run(self):
"""
If the target table doesn't exist, self.create_table
will be called to attempt to create the table.
"""
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path()
output = self.output()
connection = output.connect()
cursor = connection.cursor()
self.init_copy(connection)
self.copy(cursor, path)
self.post_copy(cursor)
if self.enable_metadata_columns:
self.post_copy_metacolumns(cursor)
# update marker table
output.touch(connection)
connection.commit()
# commit and clean up
connection.close() | python | def run(self):
"""
If the target table doesn't exist, self.create_table
will be called to attempt to create the table.
"""
if not (self.table):
raise Exception("table need to be specified")
path = self.s3_load_path()
output = self.output()
connection = output.connect()
cursor = connection.cursor()
self.init_copy(connection)
self.copy(cursor, path)
self.post_copy(cursor)
if self.enable_metadata_columns:
self.post_copy_metacolumns(cursor)
# update marker table
output.touch(connection)
connection.commit()
# commit and clean up
connection.close() | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"table",
")",
":",
"raise",
"Exception",
"(",
"\"table need to be specified\"",
")",
"path",
"=",
"self",
".",
"s3_load_path",
"(",
")",
"output",
"=",
"self",
".",
"output",
"(",
")",... | If the target table doesn't exist, self.create_table
will be called to attempt to create the table. | [
"If",
"the",
"target",
"table",
"doesn",
"t",
"exist",
"self",
".",
"create_table",
"will",
"be",
"called",
"to",
"attempt",
"to",
"create",
"the",
"table",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L359-L384 |
31,687 | spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.does_schema_exist | def does_schema_exist(self, connection):
"""
Determine whether the schema already exists.
"""
if '.' in self.table:
query = ("select 1 as schema_exists "
"from pg_namespace "
"where nspname = lower(%s) limit 1")
else:
return True
cursor = connection.cursor()
try:
schema = self.table.split('.')[0]
cursor.execute(query, [schema])
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | python | def does_schema_exist(self, connection):
"""
Determine whether the schema already exists.
"""
if '.' in self.table:
query = ("select 1 as schema_exists "
"from pg_namespace "
"where nspname = lower(%s) limit 1")
else:
return True
cursor = connection.cursor()
try:
schema = self.table.split('.')[0]
cursor.execute(query, [schema])
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | [
"def",
"does_schema_exist",
"(",
"self",
",",
"connection",
")",
":",
"if",
"'.'",
"in",
"self",
".",
"table",
":",
"query",
"=",
"(",
"\"select 1 as schema_exists \"",
"\"from pg_namespace \"",
"\"where nspname = lower(%s) limit 1\"",
")",
"else",
":",
"return",
"T... | Determine whether the schema already exists. | [
"Determine",
"whether",
"the",
"schema",
"already",
"exists",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L424-L443 |
31,688 | spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.does_table_exist | def does_table_exist(self, connection):
"""
Determine whether the table already exists.
"""
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = lower(%s) and table_name = lower(%s) limit 1")
else:
query = ("select 1 as table_exists "
"from pg_table_def "
"where tablename = lower(%s) limit 1")
cursor = connection.cursor()
try:
cursor.execute(query, tuple(self.table.split('.')))
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | python | def does_table_exist(self, connection):
"""
Determine whether the table already exists.
"""
if '.' in self.table:
query = ("select 1 as table_exists "
"from information_schema.tables "
"where table_schema = lower(%s) and table_name = lower(%s) limit 1")
else:
query = ("select 1 as table_exists "
"from pg_table_def "
"where tablename = lower(%s) limit 1")
cursor = connection.cursor()
try:
cursor.execute(query, tuple(self.table.split('.')))
result = cursor.fetchone()
return bool(result)
finally:
cursor.close() | [
"def",
"does_table_exist",
"(",
"self",
",",
"connection",
")",
":",
"if",
"'.'",
"in",
"self",
".",
"table",
":",
"query",
"=",
"(",
"\"select 1 as table_exists \"",
"\"from information_schema.tables \"",
"\"where table_schema = lower(%s) and table_name = lower(%s) limit 1\"... | Determine whether the table already exists. | [
"Determine",
"whether",
"the",
"table",
"already",
"exists",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L445-L464 |
31,689 | spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.init_copy | def init_copy(self, connection):
"""
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
"""
if not self.does_schema_exist(connection):
logger.info("Creating schema for %s", self.table)
self.create_schema(connection)
if not self.does_table_exist(connection):
logger.info("Creating table %s", self.table)
self.create_table(connection)
if self.enable_metadata_columns:
self._add_metadata_columns(connection)
if self.do_truncate_table:
logger.info("Truncating table %s", self.table)
self.truncate_table(connection)
if self.do_prune():
logger.info("Removing %s older than %s from %s", self.prune_column, self.prune_date, self.prune_table)
self.prune(connection) | python | def init_copy(self, connection):
"""
Perform pre-copy sql - such as creating table, truncating, or removing data older than x.
"""
if not self.does_schema_exist(connection):
logger.info("Creating schema for %s", self.table)
self.create_schema(connection)
if not self.does_table_exist(connection):
logger.info("Creating table %s", self.table)
self.create_table(connection)
if self.enable_metadata_columns:
self._add_metadata_columns(connection)
if self.do_truncate_table:
logger.info("Truncating table %s", self.table)
self.truncate_table(connection)
if self.do_prune():
logger.info("Removing %s older than %s from %s", self.prune_column, self.prune_date, self.prune_table)
self.prune(connection) | [
"def",
"init_copy",
"(",
"self",
",",
"connection",
")",
":",
"if",
"not",
"self",
".",
"does_schema_exist",
"(",
"connection",
")",
":",
"logger",
".",
"info",
"(",
"\"Creating schema for %s\"",
",",
"self",
".",
"table",
")",
"self",
".",
"create_schema",
... | Perform pre-copy sql - such as creating table, truncating, or removing data older than x. | [
"Perform",
"pre",
"-",
"copy",
"sql",
"-",
"such",
"as",
"creating",
"table",
"truncating",
"or",
"removing",
"data",
"older",
"than",
"x",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L466-L487 |
31,690 | spotify/luigi | luigi/contrib/redshift.py | S3CopyToTable.post_copy_metacolums | def post_copy_metacolums(self, cursor):
"""
Performs post-copy to fill metadata columns.
"""
logger.info('Executing post copy metadata queries')
for query in self.metadata_queries:
cursor.execute(query) | python | def post_copy_metacolums(self, cursor):
"""
Performs post-copy to fill metadata columns.
"""
logger.info('Executing post copy metadata queries')
for query in self.metadata_queries:
cursor.execute(query) | [
"def",
"post_copy_metacolums",
"(",
"self",
",",
"cursor",
")",
":",
"logger",
".",
"info",
"(",
"'Executing post copy metadata queries'",
")",
"for",
"query",
"in",
"self",
".",
"metadata_queries",
":",
"cursor",
".",
"execute",
"(",
"query",
")"
] | Performs post-copy to fill metadata columns. | [
"Performs",
"post",
"-",
"copy",
"to",
"fill",
"metadata",
"columns",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L497-L503 |
31,691 | spotify/luigi | luigi/contrib/redshift.py | KillOpenRedshiftSessions.output | def output(self):
"""
Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this.
"""
# uses class name as a meta-table
return RedshiftTarget(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
table=self.__class__.__name__,
update_id=self.update_id) | python | def output(self):
"""
Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this.
"""
# uses class name as a meta-table
return RedshiftTarget(
host=self.host,
database=self.database,
user=self.user,
password=self.password,
table=self.__class__.__name__,
update_id=self.update_id) | [
"def",
"output",
"(",
"self",
")",
":",
"# uses class name as a meta-table",
"return",
"RedshiftTarget",
"(",
"host",
"=",
"self",
".",
"host",
",",
"database",
"=",
"self",
".",
"database",
",",
"user",
"=",
"self",
".",
"user",
",",
"password",
"=",
"sel... | Returns a RedshiftTarget representing the inserted dataset.
Normally you don't override this. | [
"Returns",
"a",
"RedshiftTarget",
"representing",
"the",
"inserted",
"dataset",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L649-L662 |
31,692 | spotify/luigi | luigi/contrib/redshift.py | KillOpenRedshiftSessions.run | def run(self):
"""
Kill any open Redshift sessions for the given database.
"""
connection = self.output().connect()
# kill any sessions other than ours and
# internal Redshift sessions (rdsdb)
query = ("select pg_terminate_backend(process) "
"from STV_SESSIONS "
"where db_name=%s "
"and user_name != 'rdsdb' "
"and process != pg_backend_pid()")
cursor = connection.cursor()
logger.info('Killing all open Redshift sessions for database: %s', self.database)
try:
cursor.execute(query, (self.database,))
cursor.close()
connection.commit()
except psycopg2.DatabaseError as e:
if e.message and 'EOF' in e.message:
# sometimes this operation kills the current session.
# rebuild the connection. Need to pause for 30-60 seconds
# before Redshift will allow us back in.
connection.close()
logger.info('Pausing %s seconds for Redshift to reset connection', self.connection_reset_wait_seconds)
time.sleep(self.connection_reset_wait_seconds)
logger.info('Reconnecting to Redshift')
connection = self.output().connect()
else:
raise
try:
self.output().touch(connection)
connection.commit()
finally:
connection.close()
logger.info('Done killing all open Redshift sessions for database: %s', self.database) | python | def run(self):
"""
Kill any open Redshift sessions for the given database.
"""
connection = self.output().connect()
# kill any sessions other than ours and
# internal Redshift sessions (rdsdb)
query = ("select pg_terminate_backend(process) "
"from STV_SESSIONS "
"where db_name=%s "
"and user_name != 'rdsdb' "
"and process != pg_backend_pid()")
cursor = connection.cursor()
logger.info('Killing all open Redshift sessions for database: %s', self.database)
try:
cursor.execute(query, (self.database,))
cursor.close()
connection.commit()
except psycopg2.DatabaseError as e:
if e.message and 'EOF' in e.message:
# sometimes this operation kills the current session.
# rebuild the connection. Need to pause for 30-60 seconds
# before Redshift will allow us back in.
connection.close()
logger.info('Pausing %s seconds for Redshift to reset connection', self.connection_reset_wait_seconds)
time.sleep(self.connection_reset_wait_seconds)
logger.info('Reconnecting to Redshift')
connection = self.output().connect()
else:
raise
try:
self.output().touch(connection)
connection.commit()
finally:
connection.close()
logger.info('Done killing all open Redshift sessions for database: %s', self.database) | [
"def",
"run",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"output",
"(",
")",
".",
"connect",
"(",
")",
"# kill any sessions other than ours and",
"# internal Redshift sessions (rdsdb)",
"query",
"=",
"(",
"\"select pg_terminate_backend(process) \"",
"\"from ... | Kill any open Redshift sessions for the given database. | [
"Kill",
"any",
"open",
"Redshift",
"sessions",
"for",
"the",
"given",
"database",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/redshift.py#L664-L701 |
31,693 | spotify/luigi | luigi/date_interval.py | DateInterval.dates | def dates(self):
''' Returns a list of dates in this date interval.'''
dates = []
d = self.date_a
while d < self.date_b:
dates.append(d)
d += datetime.timedelta(1)
return dates | python | def dates(self):
''' Returns a list of dates in this date interval.'''
dates = []
d = self.date_a
while d < self.date_b:
dates.append(d)
d += datetime.timedelta(1)
return dates | [
"def",
"dates",
"(",
"self",
")",
":",
"dates",
"=",
"[",
"]",
"d",
"=",
"self",
".",
"date_a",
"while",
"d",
"<",
"self",
".",
"date_b",
":",
"dates",
".",
"append",
"(",
"d",
")",
"d",
"+=",
"datetime",
".",
"timedelta",
"(",
"1",
")",
"retur... | Returns a list of dates in this date interval. | [
"Returns",
"a",
"list",
"of",
"dates",
"in",
"this",
"date",
"interval",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/date_interval.py#L67-L75 |
31,694 | spotify/luigi | examples/ftp_experiment_outputs.py | ExperimentTask.run | def run(self):
"""
The execution of this task will write 4 lines of data on this task's target output.
"""
with self.output().open('w') as outfile:
print("data 0 200 10 50 60", file=outfile)
print("data 1 190 9 52 60", file=outfile)
print("data 2 200 10 52 60", file=outfile)
print("data 3 195 1 52 60", file=outfile) | python | def run(self):
"""
The execution of this task will write 4 lines of data on this task's target output.
"""
with self.output().open('w') as outfile:
print("data 0 200 10 50 60", file=outfile)
print("data 1 190 9 52 60", file=outfile)
print("data 2 200 10 52 60", file=outfile)
print("data 3 195 1 52 60", file=outfile) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"self",
".",
"output",
"(",
")",
".",
"open",
"(",
"'w'",
")",
"as",
"outfile",
":",
"print",
"(",
"\"data 0 200 10 50 60\"",
",",
"file",
"=",
"outfile",
")",
"print",
"(",
"\"data 1 190 9 52 60\"",
",",
"f... | The execution of this task will write 4 lines of data on this task's target output. | [
"The",
"execution",
"of",
"this",
"task",
"will",
"write",
"4",
"lines",
"of",
"data",
"on",
"this",
"task",
"s",
"target",
"output",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/examples/ftp_experiment_outputs.py#L46-L54 |
31,695 | spotify/luigi | luigi/mock.py | MockFileSystem.copy | def copy(self, path, dest, raise_if_exists=False):
"""
Copies the contents of a single file path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data()[path]
self.get_all_data()[dest] = contents | python | def copy(self, path, dest, raise_if_exists=False):
"""
Copies the contents of a single file path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data()[path]
self.get_all_data()[dest] = contents | [
"def",
"copy",
"(",
"self",
",",
"path",
",",
"dest",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"if",
"raise_if_exists",
"and",
"dest",
"in",
"self",
".",
"get_all_data",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Destination exists: %s'",
"%",
"... | Copies the contents of a single file path to dest | [
"Copies",
"the",
"contents",
"of",
"a",
"single",
"file",
"path",
"to",
"dest"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L40-L47 |
31,696 | spotify/luigi | luigi/mock.py | MockFileSystem.remove | def remove(self, path, recursive=True, skip_trash=True):
"""
Removes the given mockfile. skip_trash doesn't have any meaning.
"""
if recursive:
to_delete = []
for s in self.get_all_data().keys():
if s.startswith(path):
to_delete.append(s)
for s in to_delete:
self.get_all_data().pop(s)
else:
self.get_all_data().pop(path) | python | def remove(self, path, recursive=True, skip_trash=True):
"""
Removes the given mockfile. skip_trash doesn't have any meaning.
"""
if recursive:
to_delete = []
for s in self.get_all_data().keys():
if s.startswith(path):
to_delete.append(s)
for s in to_delete:
self.get_all_data().pop(s)
else:
self.get_all_data().pop(path) | [
"def",
"remove",
"(",
"self",
",",
"path",
",",
"recursive",
"=",
"True",
",",
"skip_trash",
"=",
"True",
")",
":",
"if",
"recursive",
":",
"to_delete",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"get_all_data",
"(",
")",
".",
"keys",
"(",
")",
... | Removes the given mockfile. skip_trash doesn't have any meaning. | [
"Removes",
"the",
"given",
"mockfile",
".",
"skip_trash",
"doesn",
"t",
"have",
"any",
"meaning",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L61-L73 |
31,697 | spotify/luigi | luigi/mock.py | MockFileSystem.move | def move(self, path, dest, raise_if_exists=False):
"""
Moves a single file from path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data().pop(path)
self.get_all_data()[dest] = contents | python | def move(self, path, dest, raise_if_exists=False):
"""
Moves a single file from path to dest
"""
if raise_if_exists and dest in self.get_all_data():
raise RuntimeError('Destination exists: %s' % path)
contents = self.get_all_data().pop(path)
self.get_all_data()[dest] = contents | [
"def",
"move",
"(",
"self",
",",
"path",
",",
"dest",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"if",
"raise_if_exists",
"and",
"dest",
"in",
"self",
".",
"get_all_data",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Destination exists: %s'",
"%",
"... | Moves a single file from path to dest | [
"Moves",
"a",
"single",
"file",
"from",
"path",
"to",
"dest"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L75-L82 |
31,698 | spotify/luigi | luigi/mock.py | MockTarget.move | def move(self, path, raise_if_exists=False):
"""
Call MockFileSystem's move command
"""
self.fs.move(self.path, path, raise_if_exists) | python | def move(self, path, raise_if_exists=False):
"""
Call MockFileSystem's move command
"""
self.fs.move(self.path, path, raise_if_exists) | [
"def",
"move",
"(",
"self",
",",
"path",
",",
"raise_if_exists",
"=",
"False",
")",
":",
"self",
".",
"fs",
".",
"move",
"(",
"self",
".",
"path",
",",
"path",
",",
"raise_if_exists",
")"
] | Call MockFileSystem's move command | [
"Call",
"MockFileSystem",
"s",
"move",
"command"
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/mock.py#L122-L126 |
31,699 | spotify/luigi | luigi/parameter.py | _recursively_freeze | def _recursively_freeze(value):
"""
Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively.
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list) or isinstance(value, tuple):
return tuple(_recursively_freeze(v) for v in value)
return value | python | def _recursively_freeze(value):
"""
Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively.
"""
if isinstance(value, Mapping):
return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items()))
elif isinstance(value, list) or isinstance(value, tuple):
return tuple(_recursively_freeze(v) for v in value)
return value | [
"def",
"_recursively_freeze",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Mapping",
")",
":",
"return",
"_FrozenOrderedDict",
"(",
"(",
"(",
"k",
",",
"_recursively_freeze",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"value",
"... | Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. | [
"Recursively",
"walks",
"Mapping",
"s",
"and",
"list",
"s",
"and",
"converts",
"them",
"to",
"_FrozenOrderedDict",
"and",
"tuples",
"respectively",
"."
] | c5eca1c3c3ee2a7eb612486192a0da146710a1e9 | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/parameter.py#L929-L937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.