repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
jpype-project/jpype | setupext/build_ext.py | BuildExtCommand.initialize_options | python | def initialize_options(self, *args):
import distutils.sysconfig
cfg_vars = distutils.sysconfig.get_config_vars()
# if 'CFLAGS' in cfg_vars:
# cfg_vars['CFLAGS'] = cfg_vars['CFLAGS'].replace('-Wstrict-prototypes', '')
for k,v in cfg_vars.items():
if isinstance(v,str)... | omit -Wstrict-prototypes from CFLAGS since its only valid for C code. | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/setupext/build_ext.py#L37-L51 | null | class BuildExtCommand(build_ext):
"""
Override some behavior in extension building:
1. Numpy:
If not opted out, try to use NumPy and define macro 'HAVE_NUMPY', so arrays
returned from Java can be wrapped efficiently in a ndarray.
2. handle compiler flags for different compilers via a di... |
jpype-project/jpype | jpype/_cygwin.py | WindowsJVMFinder._get_from_registry | python | def _get_from_registry(self):
from ._windows import reg_keys
for location in reg_keys:
location = location.replace('\\', '/')
jreKey = "/proc/registry/HKEY_LOCAL_MACHINE/{}".format(location)
try:
with open(jreKey + "/CurrentVersion") as f:
... | Retrieves the path to the default Java installation stored in the
Windows registry
:return: The path found in the registry, or None | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_cygwin.py#L44-L67 | null | class WindowsJVMFinder(_jvmfinder.JVMFinder):
"""
Windows JVM library finder class
"""
def __init__(self):
"""
Sets up members
"""
# Call the parent constructor
_jvmfinder.JVMFinder.__init__(self)
# Library file name
self._libfile = "jvm.dll"
... |
jpype-project/jpype | jpype/_classpath.py | addClassPath | python | def addClassPath(path1):
global _CLASSPATHS
path1=_os.path.abspath(path1)
if _sys.platform=='cygwin':
path1=_posix2win(path1)
_CLASSPATHS.add(str(path1)) | Add a path to the java class path | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_classpath.py#L57-L63 | null | import os as _os
import sys as _sys
import glob as _glob
__all__=['addClassPath', 'getClassPath']
_CLASSPATHS=set()
_SEP = _os.path.pathsep
if _sys.platform=='cygwin':
_SEP=';'
def _init():
global _CLASSPATHS
global _SEP
classpath=_os.environ.get("CLASSPATH")
if classpath:
_CLASSPATHS|=se... |
jpype-project/jpype | jpype/_classpath.py | getClassPath | python | def getClassPath():
global _CLASSPATHS
global _SEP
out=[]
for path in _CLASSPATHS:
if path=='':
continue
if path.endswith('*'):
paths=_glob.glob(path+".jar")
if len(path)==0:
continue
out.extend(paths)
else:
... | Get the full java class path.
Includes user added paths and the environment CLASSPATH. | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_classpath.py#L65-L83 | null | import os as _os
import sys as _sys
import glob as _glob
__all__=['addClassPath', 'getClassPath']
_CLASSPATHS=set()
_SEP = _os.path.pathsep
if _sys.platform=='cygwin':
_SEP=';'
def _init():
global _CLASSPATHS
global _SEP
classpath=_os.environ.get("CLASSPATH")
if classpath:
_CLASSPATHS|=se... |
jpype-project/jpype | jpype/_core.py | startJVM | python | def startJVM(jvm=None, *args, **kwargs):
if jvm is None:
jvm = get_default_jvm_path()
# Check to see that the user has not set the classpath
# Otherwise use the default if not specified
if not _hasClassPath(args) and 'classpath' not in kwargs:
kwargs['classpath']=_classpa... | Starts a Java Virtual Machine. Without options it will start
the JVM with the default classpath and jvm. The default classpath
will be determined by jpype.getClassPath(). The default JVM is
determined by jpype.getDefaultJVMPath().
Args:
jvm (str): Path to the jvm library file (libjvm.so, jvm... | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_core.py#L70-L112 | [
"def getClassPath():\n \"\"\" Get the full java class path.\n\n Includes user added paths and the environment CLASSPATH.\n \"\"\"\n global _CLASSPATHS\n global _SEP\n out=[]\n for path in _CLASSPATHS:\n if path=='':\n continue\n if path.endswith('*'):\n paths... | #*****************************************************************************
# Copyright 2004-2008 Steve Menard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.... |
jpype-project/jpype | jpype/_core.py | get_default_jvm_path | python | def get_default_jvm_path():
if sys.platform == "cygwin":
# Cygwin
from ._cygwin import WindowsJVMFinder
finder = WindowsJVMFinder()
elif sys.platform == "win32":
# Windows
from ._windows import WindowsJVMFinder
finder = WindowsJVMFinder()
elif sys.platform == ... | Retrieves the path to the default or first found JVM library
:return: The path to the JVM shared library file
:raise ValueError: No JVM library found | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_core.py#L131-L155 | [
"def get_jvm_path(self):\n \"\"\"\n Retrieves the path to the default or first found JVM library\n\n :return: The path to the JVM shared library file\n :raise ValueError: No JVM library found\n \"\"\"\n for method in self._methods:\n try:\n jvm = method()\n\n # If foun... | #*****************************************************************************
# Copyright 2004-2008 Steve Menard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.... |
jpype-project/jpype | jpype/_jvmfinder.py | JVMFinder.find_libjvm | python | def find_libjvm(self, java_home):
found_jamvm = False
non_supported_jvm = ('cacao', 'jamvm')
found_non_supported_jvm = False
# Look for the file
for root, _, names in os.walk(java_home):
if self._libfile in names:
# Found it, but check for non support... | Recursively looks for the given file
:param java_home: A Java home folder
:param filename: Name of the file to find
:return: The first found file path, or None | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L48-L82 | null | class JVMFinder(object):
"""
JVM library finder base class
"""
def __init__(self):
"""
Sets up members
"""
# Library file name
self._libfile = "libjvm.so"
# Predefined locations
self._locations = ("/usr/lib/jvm", "/usr/java")
# Search met... |
jpype-project/jpype | jpype/_jvmfinder.py | JVMFinder.find_possible_homes | python | def find_possible_homes(self, parents):
homes = []
java_names = ('jre', 'jdk', 'java')
for parent in parents:
for childname in sorted(os.listdir(parent)):
# Compute the real path
path = os.path.realpath(os.path.join(parent, childname))
... | Generator that looks for the first-level children folders that could be
Java installations, according to their name
:param parents: A list of parent directories
:return: The possible JVM installation folders | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L85-L111 | null | class JVMFinder(object):
"""
JVM library finder base class
"""
def __init__(self):
"""
Sets up members
"""
# Library file name
self._libfile = "libjvm.so"
# Predefined locations
self._locations = ("/usr/lib/jvm", "/usr/java")
# Search met... |
jpype-project/jpype | jpype/_jvmfinder.py | JVMFinder.get_jvm_path | python | def get_jvm_path(self):
for method in self._methods:
try:
jvm = method()
# If found check the architecture
if jvm:
self.check(jvm)
except NotImplementedError:
# Ignore missing implementations
... | Retrieves the path to the default or first found JVM library
:return: The path to the JVM shared library file
:raise ValueError: No JVM library found | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L122-L153 | [
"def check(self, jvm):\n \"\"\"\n Check if the jvm is valid for this architecture.\n\n This method should be overriden for each architecture.\n :raise JVMNotSupportedException: If the jvm is not supported.\n \"\"\"\n pass\n",
"def _get_from_java_home(self):\n \"\"\"\n Retrieves the Java li... | class JVMFinder(object):
"""
JVM library finder base class
"""
def __init__(self):
"""
Sets up members
"""
# Library file name
self._libfile = "libjvm.so"
# Predefined locations
self._locations = ("/usr/lib/jvm", "/usr/java")
# Search met... |
jpype-project/jpype | jpype/_jvmfinder.py | JVMFinder._get_from_java_home | python | def _get_from_java_home(self):
# Get the environment variable
java_home = os.getenv("JAVA_HOME")
if java_home and os.path.exists(java_home):
# Get the real installation path
java_home = os.path.realpath(java_home)
# Cygwin has a bug in realpath
if... | Retrieves the Java library path according to the JAVA_HOME environment
variable
:return: The path to the JVM library, or None | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L156-L174 | [
"def find_libjvm(self, java_home):\n \"\"\"\n Recursively looks for the given file\n\n :param java_home: A Java home folder\n :param filename: Name of the file to find\n :return: The first found file path, or None\n \"\"\"\n found_jamvm = False\n non_supported_jvm = ('cacao', 'jamvm')\n f... | class JVMFinder(object):
"""
JVM library finder base class
"""
def __init__(self):
"""
Sets up members
"""
# Library file name
self._libfile = "libjvm.so"
# Predefined locations
self._locations = ("/usr/lib/jvm", "/usr/java")
# Search met... |
jpype-project/jpype | jpype/_jvmfinder.py | JVMFinder._get_from_known_locations | python | def _get_from_known_locations(self):
for home in self.find_possible_homes(self._locations):
jvm = self.find_libjvm(home)
if jvm is not None:
return jvm | Retrieves the first existing Java library path in the predefined known
locations
:return: The path to the JVM library, or None | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L177-L187 | [
"def find_libjvm(self, java_home):\n \"\"\"\n Recursively looks for the given file\n\n :param java_home: A Java home folder\n :param filename: Name of the file to find\n :return: The first found file path, or None\n \"\"\"\n found_jamvm = False\n non_supported_jvm = ('cacao', 'jamvm')\n f... | class JVMFinder(object):
"""
JVM library finder base class
"""
def __init__(self):
"""
Sets up members
"""
# Library file name
self._libfile = "libjvm.so"
# Predefined locations
self._locations = ("/usr/lib/jvm", "/usr/java")
# Search met... |
jpype-project/jpype | setupext/build_java.py | BuildJavaCommand.run | python | def run(self):
buildDir = os.path.join("..","build","lib")
buildXmlFile = os.path.join("native","build.xml")
command = [self.distribution.ant, '-Dbuild=%s'%buildDir, '-f', buildXmlFile]
cmdStr= ' '.join(command)
self.announce(" %s"%cmdStr, level=distutils.log.INFO)
try:
subprocess.check... | Run command. | train | https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/setupext/build_java.py#L22-L33 | null | class BuildJavaCommand(distutils.cmd.Command):
"""A custom command to create jar file during build."""
description = 'run ant to make a jar'
user_options = []
def initialize_options(self):
"""Set default values for options."""
pass
def finalize_options(self):
"""Post-process options."""
pas... |
apacha/OMR-Datasets | omrdatasettools/converters/ImageMover.py | ImageMover.move_images | python | def move_images(self, image_directory):
image_paths = glob(image_directory + "/**/*.png", recursive=True)
for image_path in image_paths:
destination = image_path.replace("\\image\\", "\\")
shutil.move(image_path, destination)
image_folders = glob(image_directory + "/**/i... | Moves png-files one directory up from path/image/*.png -> path/*.png | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/converters/ImageMover.py#L9-L18 | null | class ImageMover():
|
apacha/OMR-Datasets | omrdatasettools/image_generators/HomusImageGenerator.py | HomusImageGenerator.create_images | python | def create_images(raw_data_directory: str,
destination_directory: str,
stroke_thicknesses: List[int],
canvas_width: int = None,
canvas_height: int = None,
staff_line_spacing: int = 14,
sta... | Creates a visual representation of the Homus Dataset by parsing all text-files and the symbols as specified
by the parameters by drawing lines that connect the points from each stroke of each symbol.
Each symbol will be drawn in the center of a fixed canvas, specified by width and height.
:par... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/HomusImageGenerator.py#L13-L105 | [
"def initialize_from_string(content: str) -> 'HomusSymbol':\n \"\"\"\n Create and initializes a new symbol from a string\n\n :param content: The content of a symbol as read from the text-file\n :return: The initialized symbol\n :rtype: HomusSymbol\n \"\"\"\n\n if content is None or content is \... | class HomusImageGenerator:
@staticmethod
@staticmethod
def add_arguments_for_homus_image_generator(parser: argparse.ArgumentParser):
parser.add_argument("-s", "--stroke_thicknesses", dest="stroke_thicknesses", default="3",
help="Stroke thicknesses for drawing the genera... |
apacha/OMR-Datasets | omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py | MuscimaPlusPlusDatasetDownloader.download_and_extract_dataset | python | def download_and_extract_dataset(self, destination_directory: str):
if not os.path.exists(self.get_dataset_filename()):
print("Downloading MUSCIMA++ Dataset...")
self.download_file(self.get_dataset_download_url(), self.get_dataset_filename())
if not os.path.exists(self.get_image... | Downloads and extracts the MUSCIMA++ dataset along with the images from the CVC-MUSCIMA dataset
that were manually annotated (140 out of 1000 images). | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py#L33-L54 | [
"def copytree(src, dst):\n if not os.path.exists(dst):\n os.makedirs(dst)\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n DatasetDownloader.copytree(s, d)\n else:\n if not os.path.exist... | class MuscimaPlusPlusDatasetDownloader(DatasetDownloader):
""" Downloads the Muscima++ dataset
https://ufal.mff.cuni.cz/muscima
Copyright 2017 Jan Hajic jr. under CC-BY-NC-SA 4.0 license
"""
def get_dataset_download_url(self) -> str:
# Official URL: "https://lindat.mff.cuni.cz/repos... |
apacha/OMR-Datasets | omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py | MuscimaPlusPlusDatasetDownloader.download_and_extract_measure_annotations | python | def download_and_extract_measure_annotations(self, destination_directory: str):
if not os.path.exists(self.get_measure_annotation_filename()):
print("Downloading MUSCIMA++ Measure Annotations...")
self.download_file(self.get_measure_annotation_download_url(), self.get_measure_annotation_... | Downloads the annotations only of stave-measures, system-measures and staves that were extracted
from the MUSCIMA++ dataset via the :class:`omrdatasettools.converters.MuscimaPlusPlusAnnotationConverter`.
The annotations from that extraction are provided in a simple json format with one annotation
... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py#L56-L77 | [
"def copytree(src, dst):\n if not os.path.exists(dst):\n os.makedirs(dst)\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n DatasetDownloader.copytree(s, d)\n else:\n if not os.path.exist... | class MuscimaPlusPlusDatasetDownloader(DatasetDownloader):
""" Downloads the Muscima++ dataset
https://ufal.mff.cuni.cz/muscima
Copyright 2017 Jan Hajic jr. under CC-BY-NC-SA 4.0 license
"""
def get_dataset_download_url(self) -> str:
# Official URL: "https://lindat.mff.cuni.cz/repos... |
apacha/OMR-Datasets | omrdatasettools/image_generators/MuscimaPlusPlusImageGenerator.py | MuscimaPlusPlusImageGenerator.extract_and_render_all_symbol_masks | python | def extract_and_render_all_symbol_masks(self, raw_data_directory: str, destination_directory: str):
print("Extracting Symbols from Muscima++ Dataset...")
xml_files = self.get_all_xml_file_paths(raw_data_directory)
crop_objects = self.load_crop_objects_from_xml_files(xml_files)
self.rend... | Extracts all symbols from the raw XML documents and generates individual symbols from the masks
:param raw_data_directory: The directory, that contains the xml-files and matching images
:param destination_directory: The directory, in which the symbols should be generated into. One sub-folder per
... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/MuscimaPlusPlusImageGenerator.py#L23-L35 | [
"def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]:\n \"\"\" Loads all XML-files that are located in the folder.\n :param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to\n \"\"\"\n raw_data_directory = os.path.join(raw_data_directory, \"v1... | class MuscimaPlusPlusImageGenerator:
def __init__(self) -> None:
super().__init__()
self.path_of_this_file = os.path.dirname(os.path.realpath(__file__))
def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]:
""" Loads all XML-files that are located in the folder.
... |
apacha/OMR-Datasets | omrdatasettools/image_generators/MuscimaPlusPlusImageGenerator.py | MuscimaPlusPlusImageGenerator.get_all_xml_file_paths | python | def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]:
raw_data_directory = os.path.join(raw_data_directory, "v1.0", "data", "cropobjects_manual")
xml_files = [y for x in os.walk(raw_data_directory) for y in glob(os.path.join(x[0], '*.xml'))]
return xml_files | Loads all XML-files that are located in the folder.
:param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/MuscimaPlusPlusImageGenerator.py#L37-L43 | null | class MuscimaPlusPlusImageGenerator:
def __init__(self) -> None:
super().__init__()
self.path_of_this_file = os.path.dirname(os.path.realpath(__file__))
def extract_and_render_all_symbol_masks(self, raw_data_directory: str, destination_directory: str):
"""
Extracts all symbols f... |
apacha/OMR-Datasets | omrdatasettools/converters/ImageColorInverter.py | ImageColorInverter.invert_images | python | def invert_images(self, image_directory: str, image_file_ending: str = "*.bmp"):
image_paths = [y for x in os.walk(image_directory) for y in glob(os.path.join(x[0], image_file_ending))]
for image_path in tqdm(image_paths, desc="Inverting all images in directory {0}".format(image_directory)):
... | In-situ converts the white on black images of a directory to black on white images
:param image_directory: The directory, that contains the images
:param image_file_ending: The pattern for finding files in the image_directory | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/converters/ImageColorInverter.py#L15-L26 | null | class ImageColorInverter:
""" Class for inverting white-on-black images to black-on-white images """
def __init__(self) -> None:
super().__init__()
|
apacha/OMR-Datasets | omrdatasettools/image_generators/CapitanImageGenerator.py | CapitanImageGenerator.create_capitan_images | python | def create_capitan_images(self, raw_data_directory: str,
destination_directory: str,
stroke_thicknesses: List[int]) -> None:
symbols = self.load_capitan_symbols(raw_data_directory)
self.draw_capitan_stroke_images(symbols, destination_directory,... | Creates a visual representation of the Capitan strokes by parsing all text-files and the symbols as specified
by the parameters by drawing lines that connect the points from each stroke of each symbol.
:param raw_data_directory: The directory, that contains the raw capitan dataset
:param destin... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/CapitanImageGenerator.py#L13-L29 | [
"def load_capitan_symbols(self, raw_data_directory: str) -> List[CapitanSymbol]:\n data_path = os.path.join(raw_data_directory, \"BimodalHandwrittenSymbols\", \"data\")\n with open(data_path) as file:\n data = file.read()\n\n symbol_strings = data.splitlines()\n symbols = []\n for symbol_strin... | class CapitanImageGenerator:
def load_capitan_symbols(self, raw_data_directory: str) -> List[CapitanSymbol]:
data_path = os.path.join(raw_data_directory, "BimodalHandwrittenSymbols", "data")
with open(data_path) as file:
data = file.read()
symbol_strings = data.splitlines()
... |
apacha/OMR-Datasets | omrdatasettools/image_generators/CapitanImageGenerator.py | CapitanImageGenerator.draw_capitan_stroke_images | python | def draw_capitan_stroke_images(self, symbols: List[CapitanSymbol],
destination_directory: str,
stroke_thicknesses: List[int]) -> None:
total_number_of_symbols = len(symbols) * len(stroke_thicknesses)
output = "Generating {0} images w... | Creates a visual representation of the Capitan strokes by drawing lines that connect the points
from each stroke of each symbol.
:param symbols: The list of parsed Capitan-symbols
:param destination_directory: The directory, in which the symbols should be generated into. One sub-folder per
... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/CapitanImageGenerator.py#L44-L82 | null | class CapitanImageGenerator:
def create_capitan_images(self, raw_data_directory: str,
destination_directory: str,
stroke_thicknesses: List[int]) -> None:
"""
Creates a visual representation of the Capitan strokes by parsing all text-files a... |
apacha/OMR-Datasets | omrdatasettools/image_generators/CapitanSymbol.py | CapitanSymbol.initialize_from_string | python | def initialize_from_string(content: str) -> 'CapitanSymbol':
if content is None or content is "":
return None
parts = content.split(":")
min_x = 100000
max_x = 0
min_y = 100000
max_y = 0
symbol_name = parts[0]
sequence = parts[1]
im... | Create and initializes a new symbol from a string
:param content: The content of a symbol as read from the text-file in the form <label>:<sequence>:<image>
:return: The initialized symbol
:rtype: CapitanSymbol | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/CapitanSymbol.py#L30-L70 | null | class CapitanSymbol:
def __init__(self, content: str, stroke: List[SimplePoint2D], image_data: numpy.ndarray, symbol_class: str,
dimensions: Rectangle) -> None:
super().__init__()
self.dimensions = dimensions
self.symbol_class = symbol_class
self.content = content
... |
apacha/OMR-Datasets | omrdatasettools/image_generators/CapitanSymbol.py | CapitanSymbol.draw_capitan_score_bitmap | python | def draw_capitan_score_bitmap(self, export_path: ExportPath) -> None:
with Image.fromarray(self.image_data, mode='L') as image:
image.save(export_path.get_full_path()) | Draws the 30x30 symbol into the given file
:param export_path: The path, where the symbols should be created on disk | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/CapitanSymbol.py#L72-L78 | [
"def get_full_path(self, offset: int = None):\n \"\"\"\n :return: Returns the full path that will join all fields according to the following format if no offset if provided:\n 'destination_directory'/'symbol_class'/'raw_file_name_without_extension'_'stroke_thickness'.'extension',\n e.g.: data/images/3-4... | class CapitanSymbol:
def __init__(self, content: str, stroke: List[SimplePoint2D], image_data: numpy.ndarray, symbol_class: str,
dimensions: Rectangle) -> None:
super().__init__()
self.dimensions = dimensions
self.symbol_class = symbol_class
self.content = content
... |
apacha/OMR-Datasets | omrdatasettools/image_generators/CapitanSymbol.py | CapitanSymbol.draw_capitan_stroke_onto_canvas | python | def draw_capitan_stroke_onto_canvas(self, export_path: ExportPath, stroke_thickness: int, margin: int):
width = int(self.dimensions.width + 2 * margin)
height = int(self.dimensions.height + 2 * margin)
offset = Point2D(self.dimensions.origin.x - margin, self.dimensions.origin.y - margin)
... | Draws the symbol strokes onto a canvas
:param export_path: The path, where the symbols should be created on disk
:param stroke_thickness:
:param margin: | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/CapitanSymbol.py#L80-L106 | [
"def __euclidean_distance(a: SimplePoint2D, b: SimplePoint2D) -> float:\n return (a.x - b.x) * (a.x - b.x) + abs(a.y - b.y) * abs(a.y - b.y)\n",
"def __subtract_offset(a: SimplePoint2D, b: SimplePoint2D) -> SimplePoint2D:\n return SimplePoint2D(a.x - b.x, a.y - b.y)\n",
"def get_full_path(self, offset: in... | class CapitanSymbol:
def __init__(self, content: str, stroke: List[SimplePoint2D], image_data: numpy.ndarray, symbol_class: str,
dimensions: Rectangle) -> None:
super().__init__()
self.dimensions = dimensions
self.symbol_class = symbol_class
self.content = content
... |
apacha/OMR-Datasets | omrdatasettools/image_generators/Rectangle.py | Rectangle.overlap | python | def overlap(r1: 'Rectangle', r2: 'Rectangle'):
h_overlaps = (r1.left <= r2.right) and (r1.right >= r2.left)
v_overlaps = (r1.bottom >= r2.top) and (r1.top <= r2.bottom)
return h_overlaps and v_overlaps | Overlapping rectangles overlap both horizontally & vertically | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/Rectangle.py#L18-L24 | null | class Rectangle:
def __init__(self, origin: Point2D, width: int, height: int):
super().__init__()
self.height = height
self.width = width
self.origin = origin # Resembles the left top point
self.left = origin.x
self.top = origin.y
self.right = self.left + sel... |
apacha/OMR-Datasets | omrdatasettools/image_generators/AudiverisOmrImageGenerator.py | AudiverisOmrImageGenerator.extract_symbols | python | def extract_symbols(self, raw_data_directory: str, destination_directory: str):
print("Extracting Symbols from Audiveris OMR Dataset...")
all_xml_files = [y for x in os.walk(raw_data_directory) for y in glob(os.path.join(x[0], '*.xml'))]
all_image_files = [y for x in os.walk(raw_data_directory)... | Extracts the symbols from the raw XML documents and matching images of the Audiveris OMR dataset into
individual symbols
:param raw_data_directory: The directory, that contains the xml-files and matching images
:param destination_directory: The directory, in which the symbols should be generate... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/AudiverisOmrImageGenerator.py#L16-L35 | [
"def __extract_symbols(self, xml_file: str, image_file: str, destination_directory: str):\n # xml_file, image_file = 'data/audiveris_omr_raw\\\\IMSLP06053p1.xml', 'data/audiveris_omr_raw\\\\IMSLP06053p1.png'\n # xml_file, image_file = 'data/audiveris_omr_raw\\\\mops-1.xml', 'data/audiveris_omr_raw\\\\mops-1.p... | class AudiverisOmrImageGenerator:
def __init__(self) -> None:
super().__init__()
def __extract_symbols(self, xml_file: str, image_file: str, destination_directory: str):
# xml_file, image_file = 'data/audiveris_omr_raw\\IMSLP06053p1.xml', 'data/audiveris_omr_raw\\IMSLP06053p1.png'
# xm... |
apacha/OMR-Datasets | omrdatasettools/converters/csv_to_crop_object_conversion.py | convert_csv_annotations_to_cropobject | python | def convert_csv_annotations_to_cropobject(annotations_path: str, image_path: str) -> List[CropObject]:
annotations = pd.read_csv(annotations_path)
image = Image.open(image_path) # type: Image.Image
crop_objects = []
node_id = 0
for index, annotation in annotations.iterrows():
# Annotation e... | Converts a normalized dataset of objects into crop-objects.
:param annotations_path: Path to the csv-file that contains bounding boxes in the following
format for a single image:
image_name,top,left,bottom,right,class_name,confidence
CVC-MUSCIMA_W-01_N-10... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/converters/csv_to_crop_object_conversion.py#L14-L48 | null | import argparse
import os
from glob import glob
from typing import List
import pandas as pd
from PIL import Image
from muscima.cropobject import CropObject
import numpy as np
from muscima.io import export_cropobject_list
from tqdm import tqdm
def write_crop_objects_to_disk(crop_objects: List[CropObject], output_dir... |
apacha/OMR-Datasets | omrdatasettools/image_generators/ExportPath.py | ExportPath.get_full_path | python | def get_full_path(self, offset: int = None):
stroke_thickness = ""
if self.stroke_thickness is not None:
stroke_thickness = "_{0}".format(self.stroke_thickness)
staffline_offset = ""
if offset is not None:
staffline_offset = "_offset_{0}".format(offset)
... | :return: Returns the full path that will join all fields according to the following format if no offset if provided:
'destination_directory'/'symbol_class'/'raw_file_name_without_extension'_'stroke_thickness'.'extension',
e.g.: data/images/3-4-Time/1-13_3.png
or with an additional offset-append... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/ExportPath.py#L14-L34 | null | class ExportPath:
def __init__(self, destination_directory: str, symbol_class: str, raw_file_name_without_extension: str,
extension: str = "png", stroke_thickness: int = None) -> None:
super().__init__()
self.stroke_thickness = stroke_thickness
self.extension = extension
... |
apacha/OMR-Datasets | omrdatasettools/image_generators/HomusSymbol.py | HomusSymbol.initialize_from_string | python | def initialize_from_string(content: str) -> 'HomusSymbol':
if content is None or content is "":
return None
lines = content.splitlines()
min_x = sys.maxsize
max_x = 0
min_y = sys.maxsize
max_y = 0
symbol_name = lines[0]
strokes = []
... | Create and initializes a new symbol from a string
:param content: The content of a symbol as read from the text-file
:return: The initialized symbol
:rtype: HomusSymbol | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/HomusSymbol.py#L21-L62 | null | class HomusSymbol:
def __init__(self, content: str, strokes: List[List[Point2D]], symbol_class: str, dimensions: Rectangle) -> None:
super().__init__()
self.dimensions = dimensions
self.symbol_class = symbol_class
self.content = content
self.strokes = strokes
@staticmeth... |
apacha/OMR-Datasets | omrdatasettools/image_generators/HomusSymbol.py | HomusSymbol.draw_into_bitmap | python | def draw_into_bitmap(self, export_path: ExportPath, stroke_thickness: int, margin: int = 0) -> None:
self.draw_onto_canvas(export_path,
stroke_thickness,
margin,
self.dimensions.width + 2 * margin,
... | Draws the symbol in the original size that it has plus an optional margin
:param export_path: The path, where the symbols should be created on disk
:param stroke_thickness: Pen-thickness for drawing the symbol in pixels
:param margin: An optional margin for each symbol | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/HomusSymbol.py#L64-L76 | [
"def draw_onto_canvas(self, export_path: ExportPath, stroke_thickness: int, margin: int, destination_width: int,\n destination_height: int, staff_line_spacing: int = 14,\n staff_line_vertical_offsets: List[int] = None,\n bounding_boxes: dict = None, random... | class HomusSymbol:
def __init__(self, content: str, strokes: List[List[Point2D]], symbol_class: str, dimensions: Rectangle) -> None:
super().__init__()
self.dimensions = dimensions
self.symbol_class = symbol_class
self.content = content
self.strokes = strokes
@staticmeth... |
apacha/OMR-Datasets | omrdatasettools/image_generators/HomusSymbol.py | HomusSymbol.draw_onto_canvas | python | def draw_onto_canvas(self, export_path: ExportPath, stroke_thickness: int, margin: int, destination_width: int,
destination_height: int, staff_line_spacing: int = 14,
staff_line_vertical_offsets: List[int] = None,
bounding_boxes: dict = None, ra... | Draws the symbol onto a canvas with a fixed size
:param bounding_boxes: The dictionary into which the bounding-boxes will be added of each generated image
:param export_path: The path, where the symbols should be created on disk
:param stroke_thickness:
:param margin:
:param des... | train | https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/image_generators/HomusSymbol.py#L78-L148 | [
"def get_full_path(self, offset: int = None):\n \"\"\"\n :return: Returns the full path that will join all fields according to the following format if no offset if provided:\n 'destination_directory'/'symbol_class'/'raw_file_name_without_extension'_'stroke_thickness'.'extension',\n e.g.: data/images/3-4... | class HomusSymbol:
def __init__(self, content: str, strokes: List[List[Point2D]], symbol_class: str, dimensions: Rectangle) -> None:
super().__init__()
self.dimensions = dimensions
self.symbol_class = symbol_class
self.content = content
self.strokes = strokes
@staticmeth... |
thoth-station/solver | thoth/solver/python/base.py | compare_version | python | def compare_version(a, b): # Ignore PyDocStyleBear
def _range(q):
"""Convert a version string to array of integers.
"1.2.3" -> [1, 2, 3]
:param q: str
:return: List[int]
"""
r = []
for n in q.replace("-", ".").split("."):
try:
r... | Compare two version strings.
:param a: str
:param b: str
:return: -1 / 0 / 1 | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L40-L94 | [
"def _range(q):\n \"\"\"Convert a version string to array of integers.\n\n \"1.2.3\" -> [1, 2, 3]\n\n :param q: str\n :return: List[int]\n \"\"\"\n r = []\n for n in q.replace(\"-\", \".\").split(\".\"):\n try:\n r.append(int(n))\n except ValueError:\n # sort... | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/base.py | get_ecosystem_solver | python | def get_ecosystem_solver(ecosystem_name, parser_kwargs=None, fetcher_kwargs=None):
from .python import PythonSolver
if ecosystem_name.lower() == "pypi":
source = Source(url="https://pypi.org/simple", warehouse_api_url="https://pypi.org/pypi", warehouse=True)
return PythonSolver(parser_kwargs, f... | Get Solver subclass instance for particular ecosystem.
:param ecosystem_name: name of ecosystem for which solver should be get
:param parser_kwargs: parser key-value arguments for constructor
:param fetcher_kwargs: fetcher key-value arguments for constructor
:return: Solver | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L297-L311 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/base.py | Dependency.check | python | def check(self, version): # Ignore PyDocStyleBear
def _compare_spec(spec):
if len(spec) == 1:
spec = ("=", spec[0])
token = Tokens.operators.index(spec[0])
comparison = compare_version(version, spec[1])
if token in [Tokens.EQ1, Tokens.EQ2]:
... | Check if `version` fits into our dependency specification.
:param version: str
:return: bool | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L143-L181 | [
"def _compare_spec(spec):\n if len(spec) == 1:\n spec = (\"=\", spec[0])\n\n token = Tokens.operators.index(spec[0])\n comparison = compare_version(version, spec[1])\n if token in [Tokens.EQ1, Tokens.EQ2]:\n return comparison == 0\n elif token == Tokens.GT:\n return comparison ==... | class Dependency(object):
"""A Dependency consists of (package) name and version spec."""
def __init__(self, name, spec):
"""Initialize instance."""
self._name = name
# spec is a list where each item is either 2-tuple (operator, version) or list of these
# example: [[('>=', '0.6... |
thoth-station/solver | thoth/solver/python/base.py | DependencyParser.compose_sep | python | def compose_sep(deps, separator):
result = {}
for dep in deps:
if dep.name not in result:
result[dep.name] = separator.join([op + ver for op, ver in dep.spec])
else:
result[dep.name] += separator + separator.join([op + ver for op, ver in dep.spec])... | Opposite of parse().
:param deps: list of Dependency()
:param separator: when joining dependencies, use this separator
:return: dict of {name: version spec} | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L197-L210 | null | class DependencyParser(object):
"""Base class for Dependency parsing."""
def __init__(self, **parser_kwargs):
"""Construct dependency parser."""
if parser_kwargs:
raise NotImplementedError
def parse(self, specs):
"""Abstract method for Dependency parsing."""
pas... |
thoth-station/solver | thoth/solver/python/base.py | Solver.solve | python | def solve(self, dependencies, graceful=True, all_versions=False): # Ignore PyDocStyleBear
def _compare_version_index_url(v1, v2):
"""Get a wrapper around compare version to omit index url when sorting."""
return compare_version(v1[0], v2[0])
solved = {}
for dep in self... | Solve `dependencies` against upstream repository.
:param dependencies: List, List of dependencies in native format
:param graceful: bool, Print info output to stdout
:param all_versions: bool, Return all matched versions instead of the latest
:return: Dict[str, str], Matched versions | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/base.py#L250-L294 | null | class Solver(object):
"""Base class for resolving dependencies."""
def __init__(self, dep_parser=None, fetcher=None, highest_dependency_version=True):
"""Initialize instance."""
self._dependency_parser = dep_parser
self._release_fetcher = fetcher
self._highest_dependency_version... |
thoth-station/solver | thoth/solver/compile.py | pip_compile | python | def pip_compile(*packages: str):
result = None
packages = "\n".join(packages)
with tempfile.TemporaryDirectory() as tmp_dirname, cwd(tmp_dirname):
with open("requirements.in", "w") as requirements_file:
requirements_file.write(packages)
runner = CliRunner()
try:
... | Run pip-compile to pin down packages, also resolve their transitive dependencies. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/compile.py#L30-L52 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/cli.py | _print_version | python | def _print_version(ctx, _, value):
if not value or ctx.resilient_parsing:
return
click.echo(analyzer_version)
ctx.exit() | Print solver version and exit. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/cli.py#L37-L42 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/cli.py | cli | python | def cli(ctx=None, verbose=0):
if ctx:
ctx.auto_envvar_prefix = "THOTH_SOLVER"
if verbose:
_LOG.setLevel(logging.DEBUG)
_LOG.debug("Debug mode is on") | Thoth solver command line interface. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/cli.py#L56-L64 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/cli.py | pypi | python | def pypi(
click_ctx,
requirements,
index=None,
python_version=3,
exclude_packages=None,
output=None,
subgraph_check_api=None,
no_transitive=True,
no_pretty=False,
):
requirements = [requirement.strip() for requirement in requirements.split("\\n") if requirement]
if not requi... | Manipulate with dependency requirements using PyPI. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/cli.py#L110-L149 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | _create_entry | python | def _create_entry(entry: dict, source: Source = None) -> dict:
entry["package_name"] = entry["package"].pop("package_name")
entry["package_version"] = entry["package"].pop("installed_version")
if source:
entry["index_url"] = source.url
entry["sha256"] = []
for item in source.get_pac... | Filter and normalize the output of pipdeptree entry. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L40-L56 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | _get_environment_details | python | def _get_environment_details(python_bin: str) -> list:
cmd = "{} -m pipdeptree --json".format(python_bin)
output = run_command(cmd, is_json=True).stdout
return [_create_entry(entry) for entry in output] | Get information about packages in environment where packages get installed. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L59-L63 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | _should_resolve_subgraph | python | def _should_resolve_subgraph(subgraph_check_api: str, package_name: str, package_version: str, index_url: str) -> bool:
_LOGGER.info(
"Checking if the given dependency subgraph for package %r in version %r from index %r should be resolved",
package_name,
package_version,
index_url,
... | Ask the given subgraph check API if the given package in the given version should be included in the resolution.
This subgraph resolving avoidence serves two purposes - we don't need to
resolve dependency subgraphs that were already analyzed and we also avoid
analyzing of "core" packages (like setuptools) ... | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L66-L99 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | _install_requirement | python | def _install_requirement(
python_bin: str, package: str, version: str = None, index_url: str = None, clean: bool = True
) -> None:
previous_version = _pipdeptree(python_bin, package)
try:
cmd = "{} -m pip install --force-reinstall --no-cache-dir --no-deps {}".format(python_bin, quote(package))
... | Install requirements specified using suggested pip binary. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L103-L155 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | _pipdeptree | python | def _pipdeptree(python_bin, package_name: str = None, warn: bool = False) -> typing.Optional[dict]:
cmd = "{} -m pipdeptree --json".format(python_bin)
_LOGGER.debug("Obtaining pip dependency tree using: %r", cmd)
output = run_command(cmd, is_json=True).stdout
if not package_name:
return output... | Get pip dependency tree by executing pipdeptree tool. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L158-L177 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | _get_dependency_specification | python | def _get_dependency_specification(dep_spec: typing.List[tuple]) -> str:
return ",".join(dep_range[0] + dep_range[1] for dep_range in dep_spec) | Get string representation of dependency specification as provided by PythonDependencyParser. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L180-L182 | null | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | _do_resolve_index | python | def _do_resolve_index(
python_bin: str,
solver: PythonSolver,
*,
all_solvers: typing.List[PythonSolver],
requirements: typing.List[str],
exclude_packages: set = None,
transitive: bool = True,
subgraph_check_api: str = None,
) -> dict:
index_url = solver.release_fetcher.index_url
... | Perform resolution of requirements against the given solver. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L209-L353 | [
"def _create_entry(entry: dict, source: Source = None) -> dict:\n \"\"\"Filter and normalize the output of pipdeptree entry.\"\"\"\n entry[\"package_name\"] = entry[\"package\"].pop(\"package_name\")\n entry[\"package_version\"] = entry[\"package\"].pop(\"installed_version\")\n\n if source:\n ent... | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python.py | resolve | python | def resolve(
requirements: typing.List[str],
index_urls: list = None,
python_version: int = 3,
exclude_packages: set = None,
transitive: bool = True,
subgraph_check_api: str = None,
) -> dict:
assert python_version in (2, 3), "Unknown Python version"
if subgraph_check_api and not transi... | Resolve given requirements for the given Python version. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python.py#L356-L401 | [
"def _get_environment_details(python_bin: str) -> list:\n \"\"\"Get information about packages in environment where packages get installed.\"\"\"\n cmd = \"{} -m pipdeptree --json\".format(python_bin)\n output = run_command(cmd, is_json=True).stdout\n return [_create_entry(entry) for entry in output]\n"... | #!/usr/bin/env python3
# thoth-solver
# Copyright(C) 2018, 2019 Fridolin Pokorny
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
thoth-station/solver | thoth/solver/python/python_solver.py | PythonReleasesFetcher.fetch_releases | python | def fetch_releases(self, package_name):
package_name = self.source.normalize_package_name(package_name)
releases = self.source.get_package_versions(package_name)
releases_with_index_url = [(item, self.index_url) for item in releases]
return package_name, releases_with_index_url | Fetch package and index_url for a package_name. | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python_solver.py#L49-L54 | null | class PythonReleasesFetcher(ReleasesFetcher):
"""A releases fetcher based on PEP compatible simple API (also supporting Warehouse API)."""
def __init__(self, source: Source):
"""Initialize an instance of this class."""
self.source = source
@property
def index_url(self):
"""Get... |
thoth-station/solver | thoth/solver/python/python_solver.py | PythonDependencyParser.parse_python | python | def parse_python(spec): # Ignore PyDocStyleBear
def _extract_op_version(spec):
# https://www.python.org/dev/peps/pep-0440/#compatible-release
if spec.operator == "~=":
version = spec.version.split(".")
if len(version) in {2, 3, 4}:
if... | Parse PyPI specification of a single dependency.
:param spec: str, for example "Django>=1.5,<1.8"
:return: [Django [[('>=', '1.5'), ('<', '1.8')]]] | train | https://github.com/thoth-station/solver/blob/de9bd6e744cb4d5f70320ba77d6875ccb8b876c4/thoth/solver/python/python_solver.py#L66-L122 | null | class PythonDependencyParser(DependencyParser):
"""Python Dependency parsing."""
@staticmethod
def parse(self, specs):
"""Parse specs."""
return [self.parse_python(s) for s in specs]
@staticmethod
def compose(deps):
"""Compose deps."""
return DependencyParser.comp... |
pysal/mapclassify | mapclassify/classifiers.py | headTail_breaks | python | def headTail_breaks(values, cuts):
values = np.array(values)
mean = np.mean(values)
cuts.append(mean)
if len(values) > 1:
return headTail_breaks(values[values >= mean], cuts)
return cuts | head tail breaks helper function | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L35-L44 | [
"def headTail_breaks(values, cuts):\n \"\"\"\n head tail breaks helper function\n \"\"\"\n values = np.array(values)\n mean = np.mean(values)\n cuts.append(mean)\n if len(values) > 1:\n return headTail_breaks(values[values >= mean], cuts)\n return cuts\n"
] | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | quantile | python | def quantile(y, k=4):
w = 100. / k
p = np.arange(w, 100 + w, w)
if p[-1] > 100.0:
p[-1] = 100.0
q = np.array([stats.scoreatpercentile(y, pct) for pct in p])
q = np.unique(q)
k_q = len(q)
if k_q < k:
Warn('Warning: Not enough unique values in array to form k classes',
... | Calculates the quantiles for an array
Parameters
----------
y : array
(n,1), values to classify
k : int
number of quantiles
Returns
-------
q : array
(n,1), quantile values
Examples
--------
>>> import numpy as np
>>> import mapclass... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L47-L97 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | binC | python | def binC(y, bins):
if np.ndim(y) == 1:
k = 1
n = np.shape(y)[0]
else:
n, k = np.shape(y)
b = np.zeros((n, k), dtype='int')
for i, bin in enumerate(bins):
b[np.nonzero(y == bin)] = i
# check for non-binned items and warn if needed
vals = set(y.flatten())
for ... | Bin categorical/qualitative data
Parameters
----------
y : array
(n,q), categorical values
bins : array
(k,1), unique values associated with each bin
Return
------
b : array
(n,q), bin membership, values between 0 and k-1
Examples
--------
>>>... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L100-L164 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | bin | python | def bin(y, bins):
if np.ndim(y) == 1:
k = 1
n = np.shape(y)[0]
else:
n, k = np.shape(y)
b = np.zeros((n, k), dtype='int')
i = len(bins)
if type(bins) != list:
bins = bins.tolist()
binsc = copy.copy(bins)
while binsc:
i -= 1
c = binsc.pop(-1)
... | bin interval/ratio data
Parameters
----------
y : array
(n,q), values to bin
bins : array
(k,1), upper bounds of each bin (monotonic)
Returns
-------
b : array
(n,q), values of values between 0 and k-1
Examples
--------
>>> import numpy as np
>>>... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L167-L228 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | bin1d | python | def bin1d(x, bins):
left = [-float("inf")]
left.extend(bins[0:-1])
right = bins
cuts = list(zip(left, right))
k = len(bins)
binIds = np.zeros(x.shape, dtype='int')
while cuts:
k -= 1
l, r = cuts.pop(-1)
binIds += (x > l) * (x <= r) * k
counts = np.bincount(binIds,... | Place values of a 1-d array into bins and determine counts of values in
each bin
Parameters
----------
x : array
(n, 1), values to bin
bins : array
(k,1), upper bounds of each bin (monotonic)
Returns
-------
binIds : array
1-d array of integer bin Ids
... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L231-L278 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | _kmeans | python | def _kmeans(y, k=5):
y = y * 1. # KMEANS needs float or double dtype
centroids = KMEANS(y, k)[0]
centroids.sort()
try:
class_ids = np.abs(y - centroids).argmin(axis=1)
except:
class_ids = np.abs(y[:, np.newaxis] - centroids).argmin(axis=1)
uc = np.unique(class_ids)
cuts = ... | Helper function to do kmeans in one dimension | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L289-L310 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | natural_breaks | python | def natural_breaks(values, k=5):
values = np.array(values)
uv = np.unique(values)
uvk = len(uv)
if uvk < k:
Warn('Warning: Not enough unique values in array to form k classes',
UserWarning)
Warn('Warning: setting k to %d' % uvk, UserWarning)
k = uvk
kres = _kmean... | natural breaks helper function
Jenks natural breaks is kmeans in one dimension | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L313-L332 | [
"def _kmeans(y, k=5):\n \"\"\"\n Helper function to do kmeans in one dimension\n \"\"\"\n\n y = y * 1. # KMEANS needs float or double dtype\n centroids = KMEANS(y, k)[0]\n centroids.sort()\n try:\n class_ids = np.abs(y - centroids).argmin(axis=1)\n except:\n class_ids = np.abs... | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | _fisher_jenks_means | python | def _fisher_jenks_means(values, classes=5, sort=True):
if sort:
values.sort()
n_data = len(values)
mat1 = np.zeros((n_data + 1, classes + 1), dtype=np.int32)
mat2 = np.zeros((n_data + 1, classes + 1), dtype=np.float32)
mat1[1, 1:] = 1
mat2[2:, 1:] = np.inf
v = np.float32(0)
for ... | Jenks Optimal (Natural Breaks) algorithm implemented in Python.
Notes
-----
The original Python code comes from here:
http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/
and is based on a JAVA and Fortran code available here:
https://stat.ethz.ch/pipermail/r-sig-geo/200... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L336-L390 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | _fit | python | def _fit(y, classes):
tss = 0
for class_def in classes:
yc = y[class_def]
css = yc - yc.mean()
css *= css
tss += sum(css)
return tss | Calculate the total sum of squares for a vector y classified into
classes
Parameters
----------
y : array
(n,1), variable to be classified
classes : array
(k,1), integer values denoting class membership | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2226-L2245 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | gadf | python | def gadf(y, method="Quantiles", maxk=15, pct=0.8):
y = np.array(y)
adam = (np.abs(y - np.median(y))).sum()
for k in range(2, maxk + 1):
cl = kmethods[method](y, k)
gadf = 1 - cl.adcm / adam
if gadf > pct:
break
return (k, cl, gadf) | Evaluate the Goodness of Absolute Deviation Fit of a Classifier
Finds the minimum value of k for which gadf>pct
Parameters
----------
y : array
(n, 1) values to be classified
method : {'Quantiles, 'Fisher_Jenks', 'Maximum_Breaks', 'Natrual_Breaks'}
maxk : int
m... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2255-L2325 | null | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = [
'Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval', 'Fisher_Jenks',
'Fisher_Jenks_Sampled', 'Jenks_Caspall', 'Jenks_Caspall_Forced',
'Jenks_Caspall_Sampled', 'Max_P_Classifier', 'Maximum_Bre... |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier._update | python | def _update(self, data, *args, **kwargs):
if data is not None:
data = np.asarray(data).flatten()
data = np.append(data.flatten(), self.y)
else:
data = self.y
self.__init__(data, *args, **kwargs) | The only thing that *should* happen in this function is
1. input sanitization for pandas
2. classification/reclassification.
Using their __init__ methods, all classifiers can re-classify given
different input parameters or additional data.
If you've got a cleverer updating equa... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L455-L473 | [
"def __init__(self, y):\n y = np.asarray(y).flatten()\n self.name = 'Map Classifier'\n self.y = y\n self._classify()\n self._summary()\n",
"def __init__(self, y, pct=[1, 10, 50, 90, 99, 100]):\n self.pct = pct\n Map_Classifier.__init__(self, y)\n self.name = 'Percentiles'\n",
"def __init... | class Map_Classifier(object):
"""
Abstract class for all map classifications :cite:`Slocum_2009`
For an array :math:`y` of :math:`n` values, a map classifier places each
value :math:`y_i` into one of :math:`k` mutually exclusive and exhaustive
classes. Each classifer defines the classes based on d... |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.make | python | def make(cls, *args, **kwargs):
# only flag overrides return flag
to_annotate = copy.deepcopy(kwargs)
return_object = kwargs.pop('return_object', False)
return_bins = kwargs.pop('return_bins', False)
return_counts = kwargs.pop('return_counts', False)
rolling = kwargs.po... | Configure and create a classifier that will consume data and produce
classifications, given the configuration options specified by this
function.
Note that this like a *partial application* of the relevant class
constructor. `make` creates a function that returns classifications; it
... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L476-L618 | null | class Map_Classifier(object):
"""
Abstract class for all map classifications :cite:`Slocum_2009`
For an array :math:`y` of :math:`n` values, a map classifier places each
value :math:`y_i` into one of :math:`k` mutually exclusive and exhaustive
classes. Each classifer defines the classes based on d... |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.get_tss | python | def get_tss(self):
tss = 0
for class_def in self.classes:
if len(class_def) > 0:
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
tss += sum(css)
return tss | Total sum of squares around class means
Returns sum of squares over all class means | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L663-L676 | null | class Map_Classifier(object):
"""
Abstract class for all map classifications :cite:`Slocum_2009`
For an array :math:`y` of :math:`n` values, a map classifier places each
value :math:`y_i` into one of :math:`k` mutually exclusive and exhaustive
classes. Each classifer defines the classes based on d... |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.get_adcm | python | def get_adcm(self):
adcm = 0
for class_def in self.classes:
if len(class_def) > 0:
yc = self.y[class_def]
yc_med = np.median(yc)
ycd = np.abs(yc - yc_med)
adcm += sum(ycd)
return adcm | Absolute deviation around class median (ADCM).
Calculates the absolute deviations of each observation about its class
median as a measure of fit for the classification method.
Returns sum of ADCM over all classes | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L681-L697 | null | class Map_Classifier(object):
"""
Abstract class for all map classifications :cite:`Slocum_2009`
For an array :math:`y` of :math:`n` values, a map classifier places each
value :math:`y_i` into one of :math:`k` mutually exclusive and exhaustive
classes. Each classifer defines the classes based on d... |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.get_gadf | python | def get_gadf(self):
adam = (np.abs(self.y - np.median(self.y))).sum()
gadf = 1 - self.adcm / adam
return gadf | Goodness of absolute deviation of fit | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L699-L705 | null | class Map_Classifier(object):
"""
Abstract class for all map classifications :cite:`Slocum_2009`
For an array :math:`y` of :math:`n` values, a map classifier places each
value :math:`y_i` into one of :math:`k` mutually exclusive and exhaustive
classes. Each classifer defines the classes based on d... |
pysal/mapclassify | mapclassify/classifiers.py | Map_Classifier.find_bin | python | def find_bin(self, x):
x = np.asarray(x).flatten()
right = np.digitize(x, self.bins, right=True)
if right.max() == len(self.bins):
right[right == len(self.bins)] = len(self.bins) - 1
return right | Sort input or inputs according to the current bin estimate
Parameters
----------
x : array or numeric
a value or array of values to fit within the estimated
bins
Returns
-------
a bin index or array of bin indices that cla... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L751-L779 | null | class Map_Classifier(object):
"""
Abstract class for all map classifications :cite:`Slocum_2009`
For an array :math:`y` of :math:`n` values, a map classifier places each
value :math:`y_i` into one of :math:`k` mutually exclusive and exhaustive
classes. Each classifer defines the classes based on d... |
pysal/mapclassify | mapclassify/classifiers.py | Fisher_Jenks_Sampled.update | python | def update(self, y=None, inplace=False, **kwargs):
kwargs.update({'k': kwargs.pop('k', self.k)})
kwargs.update({'pct': kwargs.pop('pct', self.pct)})
kwargs.update({'truncate': kwargs.pop('truncate', self._truncated)})
if inplace:
self._update(y, **kwargs)
else:
... | Add data or change classification parameters.
Parameters
----------
y : array
(n,1) array of data to classify
inplace : bool
whether to conduct the update in place or to return a
copy estimated fro... | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L1586-L1609 | [
"def _update(self, data, *args, **kwargs):\n \"\"\"\n The only thing that *should* happen in this function is\n 1. input sanitization for pandas\n 2. classification/reclassification.\n\n Using their __init__ methods, all classifiers can re-classify given\n different input parameters or additional ... | class Fisher_Jenks_Sampled(Map_Classifier):
"""
Fisher Jenks optimal classifier - mean based using random sample
Parameters
----------
y : array
(n,1), values to classify
k : int
number of classes required
pct : float
The percentage of n t... |
pysal/mapclassify | mapclassify/classifiers.py | Max_P_Classifier._ss | python | def _ss(self, class_def):
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
return sum(css) | calculates sum of squares for a class | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2178-L2183 | null | class Max_P_Classifier(Map_Classifier):
"""
Max_P Map Classification
Based on Max_p regionalization algorithm
Parameters
----------
y : array
(n,1), values to classify
k : int
number of classes required
initial : int
number of initi... |
pysal/mapclassify | mapclassify/classifiers.py | Max_P_Classifier._swap | python | def _swap(self, class1, class2, a):
ss1 = self._ss(class1)
ss2 = self._ss(class2)
tss1 = ss1 + ss2
class1c = copy.copy(class1)
class2c = copy.copy(class2)
class1c.remove(a)
class2c.append(a)
ss1 = self._ss(class1c)
ss2 = self._ss(class2c)
t... | evaluate cost of moving a from class1 to class2 | train | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L2185-L2200 | null | class Max_P_Classifier(Map_Classifier):
"""
Max_P Map Classification
Based on Max_p regionalization algorithm
Parameters
----------
y : array
(n,1), values to classify
k : int
number of classes required
initial : int
number of initi... |
mikemaccana/python-docx | docx.py | opendocx | python | def opendocx(file):
'''Open a docx file, return a document XML tree'''
mydoc = zipfile.ZipFile(file)
xmlcontent = mydoc.read('word/document.xml')
document = etree.fromstring(xmlcontent)
return document | Open a docx file, return a document XML tree | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L81-L86 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | makeelement | python | def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,
attrnsprefix=None):
'''Create an element & return it'''
# Deal with list of nsprefix by making namespacemap
namespacemap = None
if isinstance(nsprefix, list):
namespacemap = {}
for prefix in nsprefix:
... | Create an element & return it | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L95-L131 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | pagebreak | python | def pagebreak(type='page', orient='portrait'):
'''Insert a break, default 'page'.
See http://openxmldeveloper.org/forums/thread/4075.aspx
Return our page break element.'''
# Need to enumerate different types of page breaks.
validtypes = ['page', 'section']
if type not in validtypes:
tmpl... | Insert a break, default 'page'.
See http://openxmldeveloper.org/forums/thread/4075.aspx
Return our page break element. | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L134-L160 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | paragraph | python | def paragraph(paratext, style='BodyText', breakbefore=False, jc='left'):
# Make our elements
paragraph = makeelement('p')
if not isinstance(paratext, list):
paratext = [(paratext, '')]
text_tuples = []
for pt in paratext:
text, char_styles_str = (pt if isinstance(pt, (list, tuple))
... | Return a new paragraph element containing *paratext*. The paragraph's
default style is 'Body Text', but a new style may be set using the
*style* parameter.
@param string jc: Paragraph alignment, possible values:
left, center, right, both (justified), ...
see http... | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L163-L229 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | heading | python | def heading(headingtext, headinglevel, lang='en'):
'''Make a new heading, return the heading element'''
lmap = {'en': 'Heading', 'it': 'Titolo'}
# Make our elements
paragraph = makeelement('p')
pr = makeelement('pPr')
pStyle = makeelement(
'pStyle', attributes={'val': lmap[lang]+str(head... | Make a new heading, return the heading element | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L278-L294 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | table | python | def table(contents, heading=True, colw=None, cwunit='dxa', tblw=0,
twunit='auto', borders={}, celstyle=None):
table = makeelement('tbl')
columns = len(contents[0])
# Table properties
tableprops = makeelement('tblPr')
tablestyle = makeelement('tblStyle', attributes={'val': ''})
tablepro... | Return a table element based on specified parameters
@param list contents: A list of lists describing contents. Every item in
the list can be a string or a valid XML element
itself. It can also be a list. In that case all the
listed elem... | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L297-L431 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | picture | python | def picture(
relationshiplist, picname, picdescription, pixelwidth=None,
pixelheight=None, nochangeaspect=True, nochangearrowheads=True,
imagefiledict=None):
if imagefiledict is None:
warn(
'Using picture() without imagefiledict parameter will be depreca'
'ted... | Take a relationshiplist, picture file name, and return a paragraph
containing the image and an updated relationshiplist | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L434-L614 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | search | python | def search(document, search):
'''Search a document for a regex, return success / fail result'''
result = False
searchre = re.compile(search)
for element in document.iter():
if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements
if element.text:
if searchre.... | Search a document for a regex, return success / fail result | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L617-L626 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | replace | python | def replace(document, search, replace):
newdocument = document
searchre = re.compile(search)
for element in newdocument.iter():
if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements
if element.text:
if searchre.search(element.text):
element... | Replace all occurences of string with a different string, return updated
document | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L629-L641 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | clean | python | def clean(document):
newdocument = document
# Clean empty text and r tags
for t in ('t', 'r'):
rmlist = []
for element in newdocument.iter():
if element.tag == '{%s}%s' % (nsprefixes['w'], t):
if not element.text and not len(element):
rmlist.... | Perform misc cleaning operations on documents.
Returns cleaned document. | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L644-L661 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | findTypeParent | python | def findTypeParent(element, tag):
p = element
while True:
p = p.getparent()
if p.tag == tag:
return p
# Not found
return None | Finds fist parent of element of the given type
@param object element: etree element
@param string the tag parent to search for
@return object element: the found parent or None when not found | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L664-L680 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | AdvSearch | python | def AdvSearch(document, search, bs=3):
'''Return set of all regex matches
This is an advanced version of python-docx.search() that takes into
account blocks of <bs> elements at a time.
What it does:
It searches the entire document body for text blocks.
Since the text to search could be spawned... | Return set of all regex matches
This is an advanced version of python-docx.search() that takes into
account blocks of <bs> elements at a time.
What it does:
It searches the entire document body for text blocks.
Since the text to search could be spawned across multiple text blocks,
we need to a... | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L683-L756 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | advReplace | python | def advReplace(document, search, replace, bs=3):
# Enables debug output
DEBUG = False
newdocument = document
# Compile the search regexp
searchre = re.compile(search)
# Will match against searchels. Searchels is a list that contains last
# n text elements found in the document. 1 < n < bs... | Replace all occurences of string with a different string, return updated
document
This is a modified version of python-docx.replace() that takes into
account blocks of <bs> elements at a time. The replace element can also
be a string or an xml etree element.
What it does:
It searches the entir... | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L759-L907 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | getdocumenttext | python | def getdocumenttext(document):
'''Return the raw text of a document, as a list of paragraphs.'''
paratextlist = []
# Compile a list of all paragraph (p) elements
paralist = []
for element in document.iter():
# Find p (paragraph) elements
if element.tag == '{'+nsprefixes['w']+'}p':
... | Return the raw text of a document, as a list of paragraphs. | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L910-L935 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | coreproperties | python | def coreproperties(title, subject, creator, keywords, lastmodifiedby=None):
coreprops = makeelement('coreProperties', nsprefix='cp')
coreprops.append(makeelement('title', tagtext=title, nsprefix='dc'))
coreprops.append(makeelement('subject', tagtext=subject, nsprefix='dc'))
coreprops.append(makeelement(... | Create core properties (common document properties referred to in the
'Dublin Core' specification). See appproperties() for other stuff. | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L938-L970 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | appproperties | python | def appproperties():
appprops = makeelement('Properties', nsprefix='ep')
appprops = etree.fromstring(
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Properties x'
'mlns="http://schemas.openxmlformats.org/officeDocument/2006/extended'
'-properties" xmlns:vt="http://schemas.openx... | Create app-specific properties. See docproperties() for more common
document properties. | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L973-L1003 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | websettings | python | def websettings():
'''Generate websettings'''
web = makeelement('webSettings')
web.append(makeelement('allowPNG'))
web.append(makeelement('doNotSaveAsSingleFile'))
return web | Generate websettings | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L1006-L1011 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | wordrelationships | python | def wordrelationships(relationshiplist):
'''Generate a Word relationships file'''
# Default list of relationships
# FIXME: using string hack instead of making element
#relationships = makeelement('Relationships', nsprefix='pr')
relationships = etree.fromstring(
'<Relationships xmlns="http://... | Generate a Word relationships file | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L1031-L1049 | [
"def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,\n attrnsprefix=None):\n '''Create an element & return it'''\n # Deal with list of nsprefix by making namespacemap\n namespacemap = None\n if isinstance(nsprefix, list):\n namespacemap = {}\n for prefix in... | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
mikemaccana/python-docx | docx.py | savedocx | python | def savedocx(
document, coreprops, appprops, contenttypes, websettings,
wordrelationships, output, imagefiledict=None):
if imagefiledict is None:
warn(
'Using savedocx() without imagefiledict parameter will be deprec'
'ated in the future.', PendingDeprecationWarning
... | Save a modified document | train | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L1052-L1107 | null | # encoding: utf-8
"""
Open and modify Microsoft Word 2007 docx files (called 'OpenXML' and
'Office OpenXML' by Microsoft)
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
"""
import os
import re
import time
import shutil
import zipfile
from lxml import ... |
nephila/djangocms-blog | djangocms_blog/models.py | BlogMetaMixin.get_meta_attribute | python | def get_meta_attribute(self, param):
return self._get_meta_value(param, getattr(self.app_config, param)) or '' | Retrieves django-meta attributes from apphook config instance
:param param: django-meta attribute passed as key | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/models.py#L58-L63 | null | class BlogMetaMixin(ModelMeta):
def get_locale(self):
return self.get_current_language()
def get_full_url(self):
"""
Return the url with protocol and domain url
"""
return self.build_absolute_uri(self.get_absolute_url())
|
nephila/djangocms-blog | djangocms_blog/admin.py | PostAdmin.make_published | python | def make_published(self, request, queryset):
cnt1 = queryset.filter(
date_published__isnull=True,
publish=False,
).update(date_published=timezone.now(), publish=True)
cnt2 = queryset.filter(
date_published__isnull=False,
publish=False,
).up... | Bulk action to mark selected posts as published. If
the date_published field is empty the current time is
saved as date_published.
queryset must not be empty (ensured by DjangoCMS). | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L121-L139 | null | class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = [
'title', 'author', 'date_published', 'app_config', 'all_languages_column',
'date_published_end'
]
search_fields = ('translation... |
nephila/djangocms-blog | djangocms_blog/admin.py | PostAdmin.make_unpublished | python | def make_unpublished(self, request, queryset):
updates = queryset.filter(publish=True)\
.update(publish=False)
messages.add_message(
request, messages.INFO,
__('%(updates)d entry unpublished.',
'%(updates)d entries unpublished.', updates) % {
... | Bulk action to mark selected posts as UNpublished.
queryset must not be empty (ensured by DjangoCMS). | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L141-L151 | null | class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = [
'title', 'author', 'date_published', 'app_config', 'all_languages_column',
'date_published_end'
]
search_fields = ('translation... |
nephila/djangocms-blog | djangocms_blog/admin.py | PostAdmin.get_urls | python | def get_urls(self):
urls = [
url(r'^publish/([0-9]+)/$', self.admin_site.admin_view(self.publish_post),
name='djangocms_blog_publish_article'),
]
urls.extend(super(PostAdmin, self).get_urls())
return urls | Customize the modeladmin urls | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L224-L233 | null | class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = [
'title', 'author', 'date_published', 'app_config', 'all_languages_column',
'date_published_end'
]
search_fields = ('translation... |
nephila/djangocms-blog | djangocms_blog/admin.py | PostAdmin.publish_post | python | def publish_post(self, request, pk):
language = get_language_from_request(request, check_path=True)
try:
post = Post.objects.get(pk=int(pk))
post.publish = True
post.save()
return HttpResponseRedirect(post.get_absolute_url(language))
except Excepti... | Admin view to publish a single post
:param request: request
:param pk: primary key of the post to publish
:return: Redirect to the post itself (if found) or fallback urls | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L247-L265 | null | class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = [
'title', 'author', 'date_published', 'app_config', 'all_languages_column',
'date_published_end'
]
search_fields = ('translation... |
nephila/djangocms-blog | djangocms_blog/admin.py | PostAdmin.has_restricted_sites | python | def has_restricted_sites(self, request):
sites = self.get_restricted_sites(request)
return sites and sites.count() == 1 | Whether the current user has permission on one site only
:param request: current request
:return: boolean: user has permission on only one site | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L267-L275 | null | class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = [
'title', 'author', 'date_published', 'app_config', 'all_languages_column',
'date_published_end'
]
search_fields = ('translation... |
nephila/djangocms-blog | djangocms_blog/admin.py | PostAdmin.get_restricted_sites | python | def get_restricted_sites(self, request):
try:
return request.user.get_sites()
except AttributeError: # pragma: no cover
return Site.objects.none() | The sites on which the user has permission on.
To return the permissions, the method check for the ``get_sites``
method on the user instance (e.g.: ``return request.user.get_sites()``)
which must return the queryset of enabled sites.
If the attribute does not exists, the user is conside... | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L277-L293 | null | class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = [
'title', 'author', 'date_published', 'app_config', 'all_languages_column',
'date_published_end'
]
search_fields = ('translation... |
nephila/djangocms-blog | djangocms_blog/admin.py | PostAdmin.get_fieldsets | python | def get_fieldsets(self, request, obj=None):
app_config_default = self._app_config_select(request, obj)
if app_config_default is None and request.method == 'GET':
return super(PostAdmin, self).get_fieldsets(request, obj)
if not obj:
config = app_config_default
else... | Customize the fieldsets according to the app settings
:param request: request
:param obj: post
:return: fieldsets configuration | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L302-L342 | [
"def get_setting(name):\n from django.conf import settings\n from django.utils.translation import ugettext_lazy as _\n from meta import settings as meta_settings\n\n PERMALINKS = (\n ('full_date', _('Full date')),\n ('short_date', _('Year / Month')),\n ('category', _('Category')),\... | class PostAdmin(PlaceholderAdminMixin, FrontendEditableAdminMixin,
ModelAppHookConfig, TranslatableAdmin):
form = PostAdminForm
list_display = [
'title', 'author', 'date_published', 'app_config', 'all_languages_column',
'date_published_end'
]
search_fields = ('translation... |
nephila/djangocms-blog | djangocms_blog/admin.py | BlogConfigAdmin.get_fieldsets | python | def get_fieldsets(self, request, obj=None):
return [
(None, {
'fields': ('type', 'namespace', 'app_title', 'object_name')
}),
(_('Generic'), {
'fields': (
'config.default_published', 'config.use_placeholder', 'config.use_abs... | Fieldsets configuration | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L387-L451 | null | class BlogConfigAdmin(BaseAppHookConfig, TranslatableAdmin):
@property
def declared_fieldsets(self):
return self.get_fieldsets(None)
def save_model(self, request, obj, form, change):
"""
Clear menu cache when changing menu structure
"""
if 'config.menu_structure' in... |
nephila/djangocms-blog | djangocms_blog/admin.py | BlogConfigAdmin.save_model | python | def save_model(self, request, obj, form, change):
if 'config.menu_structure' in form.changed_data:
from menus.menu_pool import menu_pool
menu_pool.clear(all=True)
return super(BlogConfigAdmin, self).save_model(request, obj, form, change) | Clear menu cache when changing menu structure | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L453-L460 | null | class BlogConfigAdmin(BaseAppHookConfig, TranslatableAdmin):
@property
def declared_fieldsets(self):
return self.get_fieldsets(None)
def get_fieldsets(self, request, obj=None):
"""
Fieldsets configuration
"""
return [
(None, {
'fields': ('... |
nephila/djangocms-blog | djangocms_blog/cms_wizards.py | PostWizardForm.clean_slug | python | def clean_slug(self):
source = self.cleaned_data.get('slug', '')
lang_choice = self.language_code
if not source:
source = slugify(self.cleaned_data.get('title', ''))
qs = Post._default_manager.active_translations(lang_choice).language(lang_choice)
used = list(qs.value... | Generate a valid slug, in case the given one is taken | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/cms_wizards.py#L55-L70 | [
"def slugify(base):\n if django.VERSION >= (1, 9):\n return django_slugify(base, allow_unicode=True)\n else:\n return django_slugify(base)\n"
] | class PostWizardForm(PostAdminFormBase):
default_appconfig = None
slug = forms.SlugField(
label=_('Slug'), max_length=767, required=False,
help_text=_('Leave empty for automatic slug, or override as required.'),
)
def __init__(self, *args, **kwargs):
if 'initial' not in kwargs ... |
nephila/djangocms-blog | djangocms_blog/cms_menus.py | BlogCategoryMenu.get_nodes | python | def get_nodes(self, request):
nodes = []
language = get_language_from_request(request, check_path=True)
current_site = get_current_site(request)
page_site = self.instance.node.site
if self.instance and page_site != current_site:
return []
categories_menu = ... | Generates the nodelist
:param request:
:return: list of nodes | train | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/cms_menus.py#L29-L122 | null | class BlogCategoryMenu(CMSAttachMenu):
"""
Main menu class
Handles all types of blog menu
"""
name = _('Blog menu')
_config = {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.