repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
lk-geimfari/mimesis
mimesis/providers/business.py
Business.price_in_btc
def price_in_btc(self, minimum: float = 0, maximum: float = 2) -> str: """Generate random price in BTC. :param minimum: Minimum value of price. :param maximum: Maximum value of price. :return: Price in BTC. """ return '{} BTC'.format( self.random.uniform( minimum, maximum, precision=7, ), )
python
def price_in_btc(self, minimum: float = 0, maximum: float = 2) -> str: """Generate random price in BTC. :param minimum: Minimum value of price. :param maximum: Maximum value of price. :return: Price in BTC. """ return '{} BTC'.format( self.random.uniform( minimum, maximum, precision=7, ), )
[ "def", "price_in_btc", "(", "self", ",", "minimum", ":", "float", "=", "0", ",", "maximum", ":", "float", "=", "2", ")", "->", "str", ":", "return", "'{} BTC'", ".", "format", "(", "self", ".", "random", ".", "uniform", "(", "minimum", ",", "maximum"...
Generate random price in BTC. :param minimum: Minimum value of price. :param maximum: Maximum value of price. :return: Price in BTC.
[ "Generate", "random", "price", "in", "BTC", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/business.py#L104-L117
train
222,900
lk-geimfari/mimesis
mimesis/builtins/it.py
ItalySpecProvider.fiscal_code
def fiscal_code(self, gender: Optional[Gender] = None) -> str: """Return a random fiscal code. :param gender: Gender's enum object. :return: Fiscal code. Example: RSSMRA66R05D612U """ code = ''.join(self.random.choices(string.ascii_uppercase, k=6)) code += self.random.custom_code(mask='##') month_codes = self._data['fiscal_code']['month_codes'] code += self.random.choice(month_codes) birth_day = self.random.randint(101, 131) self._validate_enum(gender, Gender) if gender == Gender.FEMALE: birth_day += 40 code += str(birth_day)[1:] city_letters = self._data['fiscal_code']['city_letters'] code += self.random.choice(city_letters) code += self.random.custom_code(mask='###@') return code
python
def fiscal_code(self, gender: Optional[Gender] = None) -> str: """Return a random fiscal code. :param gender: Gender's enum object. :return: Fiscal code. Example: RSSMRA66R05D612U """ code = ''.join(self.random.choices(string.ascii_uppercase, k=6)) code += self.random.custom_code(mask='##') month_codes = self._data['fiscal_code']['month_codes'] code += self.random.choice(month_codes) birth_day = self.random.randint(101, 131) self._validate_enum(gender, Gender) if gender == Gender.FEMALE: birth_day += 40 code += str(birth_day)[1:] city_letters = self._data['fiscal_code']['city_letters'] code += self.random.choice(city_letters) code += self.random.custom_code(mask='###@') return code
[ "def", "fiscal_code", "(", "self", ",", "gender", ":", "Optional", "[", "Gender", "]", "=", "None", ")", "->", "str", ":", "code", "=", "''", ".", "join", "(", "self", ".", "random", ".", "choices", "(", "string", ".", "ascii_uppercase", ",", "k", ...
Return a random fiscal code. :param gender: Gender's enum object. :return: Fiscal code. Example: RSSMRA66R05D612U
[ "Return", "a", "random", "fiscal", "code", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/it.py#L28-L54
train
222,901
lk-geimfari/mimesis
mimesis/random.py
get_random_item
def get_random_item(enum: Any, rnd: Optional[Random] = None) -> Any: """Get random item of enum object. :param enum: Enum object. :param rnd: Custom random object. :return: Random item of enum. """ if rnd and isinstance(rnd, Random): return rnd.choice(list(enum)) return random_module.choice(list(enum))
python
def get_random_item(enum: Any, rnd: Optional[Random] = None) -> Any: """Get random item of enum object. :param enum: Enum object. :param rnd: Custom random object. :return: Random item of enum. """ if rnd and isinstance(rnd, Random): return rnd.choice(list(enum)) return random_module.choice(list(enum))
[ "def", "get_random_item", "(", "enum", ":", "Any", ",", "rnd", ":", "Optional", "[", "Random", "]", "=", "None", ")", "->", "Any", ":", "if", "rnd", "and", "isinstance", "(", "rnd", ",", "Random", ")", ":", "return", "rnd", ".", "choice", "(", "lis...
Get random item of enum object. :param enum: Enum object. :param rnd: Custom random object. :return: Random item of enum.
[ "Get", "random", "item", "of", "enum", "object", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/random.py#L103-L112
train
222,902
lk-geimfari/mimesis
mimesis/random.py
Random.randints
def randints(self, amount: int = 3, a: int = 1, b: int = 100) -> List[int]: """Generate list of random integers. :param amount: Amount of elements. :param a: Minimum value of range. :param b: Maximum value of range. :return: List of random integers. :raises ValueError: if amount less or equal to zero. """ if amount <= 0: raise ValueError('Amount out of range.') return [int(self.random() * (b - a)) + a for _ in range(amount)]
python
def randints(self, amount: int = 3, a: int = 1, b: int = 100) -> List[int]: """Generate list of random integers. :param amount: Amount of elements. :param a: Minimum value of range. :param b: Maximum value of range. :return: List of random integers. :raises ValueError: if amount less or equal to zero. """ if amount <= 0: raise ValueError('Amount out of range.') return [int(self.random() * (b - a)) + a for _ in range(amount)]
[ "def", "randints", "(", "self", ",", "amount", ":", "int", "=", "3", ",", "a", ":", "int", "=", "1", ",", "b", ":", "int", "=", "100", ")", "->", "List", "[", "int", "]", ":", "if", "amount", "<=", "0", ":", "raise", "ValueError", "(", "'Amou...
Generate list of random integers. :param amount: Amount of elements. :param a: Minimum value of range. :param b: Maximum value of range. :return: List of random integers. :raises ValueError: if amount less or equal to zero.
[ "Generate", "list", "of", "random", "integers", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/random.py#L29-L43
train
222,903
lk-geimfari/mimesis
mimesis/random.py
Random.urandom
def urandom(*args: Any, **kwargs: Any) -> bytes: """Return a bytes object containing random bytes. :return: Bytes. """ return os.urandom(*args, **kwargs)
python
def urandom(*args: Any, **kwargs: Any) -> bytes: """Return a bytes object containing random bytes. :return: Bytes. """ return os.urandom(*args, **kwargs)
[ "def", "urandom", "(", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "bytes", ":", "return", "os", ".", "urandom", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Return a bytes object containing random bytes. :return: Bytes.
[ "Return", "a", "bytes", "object", "containing", "random", "bytes", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/random.py#L46-L51
train
222,904
lk-geimfari/mimesis
mimesis/random.py
Random.schoice
def schoice(self, seq: str, end: int = 10) -> str: """Choice function which returns string created from sequence. :param seq: Sequence of letters or digits. :type seq: tuple or list :param end: Max value. :return: Single string. """ return ''.join(self.choice(list(seq)) for _ in range(end))
python
def schoice(self, seq: str, end: int = 10) -> str: """Choice function which returns string created from sequence. :param seq: Sequence of letters or digits. :type seq: tuple or list :param end: Max value. :return: Single string. """ return ''.join(self.choice(list(seq)) for _ in range(end))
[ "def", "schoice", "(", "self", ",", "seq", ":", "str", ",", "end", ":", "int", "=", "10", ")", "->", "str", ":", "return", "''", ".", "join", "(", "self", ".", "choice", "(", "list", "(", "seq", ")", ")", "for", "_", "in", "range", "(", "end"...
Choice function which returns string created from sequence. :param seq: Sequence of letters or digits. :type seq: tuple or list :param end: Max value. :return: Single string.
[ "Choice", "function", "which", "returns", "string", "created", "from", "sequence", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/random.py#L53-L62
train
222,905
lk-geimfari/mimesis
mimesis/random.py
Random.custom_code
def custom_code(self, mask: str = '@###', char: str = '@', digit: str = '#') -> str: """Generate custom code using ascii uppercase and random integers. :param mask: Mask of code. :param char: Placeholder for characters. :param digit: Placeholder for digits. :return: Custom code. """ char_code = ord(char) digit_code = ord(digit) code = bytearray(len(mask)) def random_int(a: int, b: int) -> int: b = b - a return int(self.random() * b) + a _mask = mask.encode() for i, p in enumerate(_mask): if p == char_code: a = random_int(65, 91) # A-Z elif p == digit_code: a = random_int(48, 58) # 0-9 else: a = p code[i] = a return code.decode()
python
def custom_code(self, mask: str = '@###', char: str = '@', digit: str = '#') -> str: """Generate custom code using ascii uppercase and random integers. :param mask: Mask of code. :param char: Placeholder for characters. :param digit: Placeholder for digits. :return: Custom code. """ char_code = ord(char) digit_code = ord(digit) code = bytearray(len(mask)) def random_int(a: int, b: int) -> int: b = b - a return int(self.random() * b) + a _mask = mask.encode() for i, p in enumerate(_mask): if p == char_code: a = random_int(65, 91) # A-Z elif p == digit_code: a = random_int(48, 58) # 0-9 else: a = p code[i] = a return code.decode()
[ "def", "custom_code", "(", "self", ",", "mask", ":", "str", "=", "'@###'", ",", "char", ":", "str", "=", "'@'", ",", "digit", ":", "str", "=", "'#'", ")", "->", "str", ":", "char_code", "=", "ord", "(", "char", ")", "digit_code", "=", "ord", "(",...
Generate custom code using ascii uppercase and random integers. :param mask: Mask of code. :param char: Placeholder for characters. :param digit: Placeholder for digits. :return: Custom code.
[ "Generate", "custom", "code", "using", "ascii", "uppercase", "and", "random", "integers", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/random.py#L64-L90
train
222,906
lk-geimfari/mimesis
mimesis/providers/path.py
Path.user
def user(self) -> str: """Generate a random user. :return: Path to user. :Example: /home/oretha """ user = self.random.choice(USERNAMES) user = user.capitalize() if 'win' in self.platform else user.lower() return str(self._pathlib_home / user)
python
def user(self) -> str: """Generate a random user. :return: Path to user. :Example: /home/oretha """ user = self.random.choice(USERNAMES) user = user.capitalize() if 'win' in self.platform else user.lower() return str(self._pathlib_home / user)
[ "def", "user", "(", "self", ")", "->", "str", ":", "user", "=", "self", ".", "random", ".", "choice", "(", "USERNAMES", ")", "user", "=", "user", ".", "capitalize", "(", ")", "if", "'win'", "in", "self", ".", "platform", "else", "user", ".", "lower...
Generate a random user. :return: Path to user. :Example: /home/oretha
[ "Generate", "a", "random", "user", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/path.py#L61-L71
train
222,907
lk-geimfari/mimesis
mimesis/providers/path.py
Path.users_folder
def users_folder(self) -> str: """Generate a random path to user's folders. :return: Path. :Example: /home/taneka/Pictures """ user = self.user() folder = self.random.choice(FOLDERS) return str(self._pathlib_home / user / folder)
python
def users_folder(self) -> str: """Generate a random path to user's folders. :return: Path. :Example: /home/taneka/Pictures """ user = self.user() folder = self.random.choice(FOLDERS) return str(self._pathlib_home / user / folder)
[ "def", "users_folder", "(", "self", ")", "->", "str", ":", "user", "=", "self", ".", "user", "(", ")", "folder", "=", "self", ".", "random", ".", "choice", "(", "FOLDERS", ")", "return", "str", "(", "self", ".", "_pathlib_home", "/", "user", "/", "...
Generate a random path to user's folders. :return: Path. :Example: /home/taneka/Pictures
[ "Generate", "a", "random", "path", "to", "user", "s", "folders", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/path.py#L73-L83
train
222,908
lk-geimfari/mimesis
mimesis/providers/path.py
Path.dev_dir
def dev_dir(self) -> str: """Generate a random path to development directory. :return: Path. :Example: /home/sherrell/Development/Python """ user = self.user() folder = self.random.choice(['Development', 'Dev']) stack = self.random.choice(PROGRAMMING_LANGS) return str(self._pathlib_home / user / folder / stack)
python
def dev_dir(self) -> str: """Generate a random path to development directory. :return: Path. :Example: /home/sherrell/Development/Python """ user = self.user() folder = self.random.choice(['Development', 'Dev']) stack = self.random.choice(PROGRAMMING_LANGS) return str(self._pathlib_home / user / folder / stack)
[ "def", "dev_dir", "(", "self", ")", "->", "str", ":", "user", "=", "self", ".", "user", "(", ")", "folder", "=", "self", ".", "random", ".", "choice", "(", "[", "'Development'", ",", "'Dev'", "]", ")", "stack", "=", "self", ".", "random", ".", "c...
Generate a random path to development directory. :return: Path. :Example: /home/sherrell/Development/Python
[ "Generate", "a", "random", "path", "to", "development", "directory", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/path.py#L85-L96
train
222,909
lk-geimfari/mimesis
mimesis/providers/path.py
Path.project_dir
def project_dir(self) -> str: """Generate a random path to project directory. :return: Path to project. :Example: /home/sherika/Development/Falcon/mercenary """ dev_dir = self.dev_dir() project = self.random.choice(PROJECT_NAMES) return str(self._pathlib_home / dev_dir / project)
python
def project_dir(self) -> str: """Generate a random path to project directory. :return: Path to project. :Example: /home/sherika/Development/Falcon/mercenary """ dev_dir = self.dev_dir() project = self.random.choice(PROJECT_NAMES) return str(self._pathlib_home / dev_dir / project)
[ "def", "project_dir", "(", "self", ")", "->", "str", ":", "dev_dir", "=", "self", ".", "dev_dir", "(", ")", "project", "=", "self", ".", "random", ".", "choice", "(", "PROJECT_NAMES", ")", "return", "str", "(", "self", ".", "_pathlib_home", "/", "dev_d...
Generate a random path to project directory. :return: Path to project. :Example: /home/sherika/Development/Falcon/mercenary
[ "Generate", "a", "random", "path", "to", "project", "directory", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/path.py#L98-L108
train
222,910
lk-geimfari/mimesis
mimesis/providers/file.py
File.__sub
def __sub(self, string: str = '') -> str: """Replace spaces in string. :param string: String. :return: String without spaces. """ replacer = self.random.choice(['_', '-']) return re.sub(r'\s+', replacer, string.strip())
python
def __sub(self, string: str = '') -> str: """Replace spaces in string. :param string: String. :return: String without spaces. """ replacer = self.random.choice(['_', '-']) return re.sub(r'\s+', replacer, string.strip())
[ "def", "__sub", "(", "self", ",", "string", ":", "str", "=", "''", ")", "->", "str", ":", "replacer", "=", "self", ".", "random", ".", "choice", "(", "[", "'_'", ",", "'-'", "]", ")", "return", "re", ".", "sub", "(", "r'\\s+'", ",", "replacer", ...
Replace spaces in string. :param string: String. :return: String without spaces.
[ "Replace", "spaces", "in", "string", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/file.py#L33-L40
train
222,911
lk-geimfari/mimesis
mimesis/providers/file.py
File.extension
def extension(self, file_type: Optional[FileType] = None) -> str: """Get a random file extension from list. :param file_type: Enum object FileType. :return: Extension of the file. :Example: .py """ key = self._validate_enum(item=file_type, enum=FileType) extensions = EXTENSIONS[key] return self.random.choice(extensions)
python
def extension(self, file_type: Optional[FileType] = None) -> str: """Get a random file extension from list. :param file_type: Enum object FileType. :return: Extension of the file. :Example: .py """ key = self._validate_enum(item=file_type, enum=FileType) extensions = EXTENSIONS[key] return self.random.choice(extensions)
[ "def", "extension", "(", "self", ",", "file_type", ":", "Optional", "[", "FileType", "]", "=", "None", ")", "->", "str", ":", "key", "=", "self", ".", "_validate_enum", "(", "item", "=", "file_type", ",", "enum", "=", "FileType", ")", "extensions", "="...
Get a random file extension from list. :param file_type: Enum object FileType. :return: Extension of the file. :Example: .py
[ "Get", "a", "random", "file", "extension", "from", "list", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/file.py#L42-L53
train
222,912
lk-geimfari/mimesis
mimesis/providers/file.py
File.mime_type
def mime_type(self, type_: Optional[MimeType] = None) -> str: """Get a random mime type from list. :param type_: Enum object MimeType. :return: Mime type. """ key = self._validate_enum(item=type_, enum=MimeType) types = MIME_TYPES[key] return self.random.choice(types)
python
def mime_type(self, type_: Optional[MimeType] = None) -> str: """Get a random mime type from list. :param type_: Enum object MimeType. :return: Mime type. """ key = self._validate_enum(item=type_, enum=MimeType) types = MIME_TYPES[key] return self.random.choice(types)
[ "def", "mime_type", "(", "self", ",", "type_", ":", "Optional", "[", "MimeType", "]", "=", "None", ")", "->", "str", ":", "key", "=", "self", ".", "_validate_enum", "(", "item", "=", "type_", ",", "enum", "=", "MimeType", ")", "types", "=", "MIME_TYP...
Get a random mime type from list. :param type_: Enum object MimeType. :return: Mime type.
[ "Get", "a", "random", "mime", "type", "from", "list", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/file.py#L55-L63
train
222,913
lk-geimfari/mimesis
mimesis/providers/file.py
File.file_name
def file_name(self, file_type: Optional[FileType] = None) -> str: """Get a random file name with some extension. :param file_type: Enum object FileType :return: File name. :Example: legislative.txt """ name = self.__text.word() ext = self.extension(file_type) return '{name}{ext}'.format( name=self.__sub(name), ext=ext, )
python
def file_name(self, file_type: Optional[FileType] = None) -> str: """Get a random file name with some extension. :param file_type: Enum object FileType :return: File name. :Example: legislative.txt """ name = self.__text.word() ext = self.extension(file_type) return '{name}{ext}'.format( name=self.__sub(name), ext=ext, )
[ "def", "file_name", "(", "self", ",", "file_type", ":", "Optional", "[", "FileType", "]", "=", "None", ")", "->", "str", ":", "name", "=", "self", ".", "__text", ".", "word", "(", ")", "ext", "=", "self", ".", "extension", "(", "file_type", ")", "r...
Get a random file name with some extension. :param file_type: Enum object FileType :return: File name. :Example: legislative.txt
[ "Get", "a", "random", "file", "name", "with", "some", "extension", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/file.py#L84-L99
train
222,914
lk-geimfari/mimesis
mimesis/builtins/de.py
GermanySpecProvider.noun
def noun(self, plural: bool = False) -> str: """Return a random noun in German. :param plural: Return noun in plural. :return: Noun. """ key = 'plural' if \ plural else 'noun' return self.random.choice(self._data[key])
python
def noun(self, plural: bool = False) -> str: """Return a random noun in German. :param plural: Return noun in plural. :return: Noun. """ key = 'plural' if \ plural else 'noun' return self.random.choice(self._data[key])
[ "def", "noun", "(", "self", ",", "plural", ":", "bool", "=", "False", ")", "->", "str", ":", "key", "=", "'plural'", "if", "plural", "else", "'noun'", "return", "self", ".", "random", ".", "choice", "(", "self", ".", "_data", "[", "key", "]", ")" ]
Return a random noun in German. :param plural: Return noun in plural. :return: Noun.
[ "Return", "a", "random", "noun", "in", "German", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/de.py#L24-L33
train
222,915
lk-geimfari/mimesis
mimesis/providers/payment.py
Payment.bitcoin_address
def bitcoin_address(self) -> str: """Generate a random bitcoin address. :return: Bitcoin address. :Example: 3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX """ type_ = self.random.choice(['1', '3']) letters = string.ascii_letters + string.digits return type_ + ''.join( self.random.choice(letters) for _ in range(33))
python
def bitcoin_address(self) -> str: """Generate a random bitcoin address. :return: Bitcoin address. :Example: 3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX """ type_ = self.random.choice(['1', '3']) letters = string.ascii_letters + string.digits return type_ + ''.join( self.random.choice(letters) for _ in range(33))
[ "def", "bitcoin_address", "(", "self", ")", "->", "str", ":", "type_", "=", "self", ".", "random", ".", "choice", "(", "[", "'1'", ",", "'3'", "]", ")", "letters", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "return", "type_", ...
Generate a random bitcoin address. :return: Bitcoin address. :Example: 3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
[ "Generate", "a", "random", "bitcoin", "address", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/payment.py#L57-L68
train
222,916
lk-geimfari/mimesis
mimesis/providers/payment.py
Payment.ethereum_address
def ethereum_address(self) -> str: """Generate a random Ethereum address. .. Note: The address will look like Ethereum address, but keep in mind that it is not the valid address. :return: Ethereum address. :Example: 0xe8ece9e6ff7dba52d4c07d37418036a89af9698d """ bits = self.random.getrandbits(160) address = bits.to_bytes(20, byteorder='big') return '0x' + address.hex()
python
def ethereum_address(self) -> str: """Generate a random Ethereum address. .. Note: The address will look like Ethereum address, but keep in mind that it is not the valid address. :return: Ethereum address. :Example: 0xe8ece9e6ff7dba52d4c07d37418036a89af9698d """ bits = self.random.getrandbits(160) address = bits.to_bytes(20, byteorder='big') return '0x' + address.hex()
[ "def", "ethereum_address", "(", "self", ")", "->", "str", ":", "bits", "=", "self", ".", "random", ".", "getrandbits", "(", "160", ")", "address", "=", "bits", ".", "to_bytes", "(", "20", ",", "byteorder", "=", "'big'", ")", "return", "'0x'", "+", "a...
Generate a random Ethereum address. .. Note: The address will look like Ethereum address, but keep in mind that it is not the valid address. :return: Ethereum address. :Example: 0xe8ece9e6ff7dba52d4c07d37418036a89af9698d
[ "Generate", "a", "random", "Ethereum", "address", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/payment.py#L70-L83
train
222,917
lk-geimfari/mimesis
mimesis/providers/payment.py
Payment.credit_card_number
def credit_card_number(self, card_type: Optional[CardType] = None) -> str: """Generate a random credit card number. :param card_type: Issuing Network. Default is Visa. :return: Credit card number. :raises NotImplementedError: if cart_type is not supported. :Example: 4455 5299 1152 2450 """ length = 16 regex = re.compile(r'(\d{4})(\d{4})(\d{4})(\d{4})') if card_type is None: card_type = get_random_item(CardType, rnd=self.random) if card_type == CardType.VISA: number = self.random.randint(4000, 4999) elif card_type == CardType.MASTER_CARD: number = self.random.choice([ self.random.randint(2221, 2720), self.random.randint(5100, 5599), ]) elif card_type == CardType.AMERICAN_EXPRESS: number = self.random.choice([34, 37]) length = 15 regex = re.compile(r'(\d{4})(\d{6})(\d{5})') else: raise NonEnumerableError(CardType) str_num = str(number) while len(str_num) < length - 1: str_num += self.random.choice(string.digits) groups = regex.search( # type: ignore str_num + luhn_checksum(str_num), ).groups() card = ' '.join(groups) return card
python
def credit_card_number(self, card_type: Optional[CardType] = None) -> str: """Generate a random credit card number. :param card_type: Issuing Network. Default is Visa. :return: Credit card number. :raises NotImplementedError: if cart_type is not supported. :Example: 4455 5299 1152 2450 """ length = 16 regex = re.compile(r'(\d{4})(\d{4})(\d{4})(\d{4})') if card_type is None: card_type = get_random_item(CardType, rnd=self.random) if card_type == CardType.VISA: number = self.random.randint(4000, 4999) elif card_type == CardType.MASTER_CARD: number = self.random.choice([ self.random.randint(2221, 2720), self.random.randint(5100, 5599), ]) elif card_type == CardType.AMERICAN_EXPRESS: number = self.random.choice([34, 37]) length = 15 regex = re.compile(r'(\d{4})(\d{6})(\d{5})') else: raise NonEnumerableError(CardType) str_num = str(number) while len(str_num) < length - 1: str_num += self.random.choice(string.digits) groups = regex.search( # type: ignore str_num + luhn_checksum(str_num), ).groups() card = ' '.join(groups) return card
[ "def", "credit_card_number", "(", "self", ",", "card_type", ":", "Optional", "[", "CardType", "]", "=", "None", ")", "->", "str", ":", "length", "=", "16", "regex", "=", "re", ".", "compile", "(", "r'(\\d{4})(\\d{4})(\\d{4})(\\d{4})'", ")", "if", "card_type"...
Generate a random credit card number. :param card_type: Issuing Network. Default is Visa. :return: Credit card number. :raises NotImplementedError: if cart_type is not supported. :Example: 4455 5299 1152 2450
[ "Generate", "a", "random", "credit", "card", "number", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/payment.py#L95-L133
train
222,918
lk-geimfari/mimesis
mimesis/providers/payment.py
Payment.credit_card_expiration_date
def credit_card_expiration_date(self, minimum: int = 16, maximum: int = 25) -> str: """Generate a random expiration date for credit card. :param minimum: Date of issue. :param maximum: Maximum of expiration_date. :return: Expiration date of credit card. :Example: 03/19. """ month = self.random.randint(1, 12) year = self.random.randint(minimum, maximum) return '{0:02d}/{1}'.format(month, year)
python
def credit_card_expiration_date(self, minimum: int = 16, maximum: int = 25) -> str: """Generate a random expiration date for credit card. :param minimum: Date of issue. :param maximum: Maximum of expiration_date. :return: Expiration date of credit card. :Example: 03/19. """ month = self.random.randint(1, 12) year = self.random.randint(minimum, maximum) return '{0:02d}/{1}'.format(month, year)
[ "def", "credit_card_expiration_date", "(", "self", ",", "minimum", ":", "int", "=", "16", ",", "maximum", ":", "int", "=", "25", ")", "->", "str", ":", "month", "=", "self", ".", "random", ".", "randint", "(", "1", ",", "12", ")", "year", "=", "sel...
Generate a random expiration date for credit card. :param minimum: Date of issue. :param maximum: Maximum of expiration_date. :return: Expiration date of credit card. :Example: 03/19.
[ "Generate", "a", "random", "expiration", "date", "for", "credit", "card", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/payment.py#L135-L148
train
222,919
lk-geimfari/mimesis
mimesis/providers/payment.py
Payment.credit_card_owner
def credit_card_owner(self, gender: Optional[Gender] = None) -> dict: """Generate credit card owner. :param gender: Gender of credit card owner. :type gender: Gender's enum object. :return: """ owner = { 'credit_card': self.credit_card_number(), 'expiration_date': self.credit_card_expiration_date(), 'owner': self.__person.full_name(gender=gender).upper(), } return owner
python
def credit_card_owner(self, gender: Optional[Gender] = None) -> dict: """Generate credit card owner. :param gender: Gender of credit card owner. :type gender: Gender's enum object. :return: """ owner = { 'credit_card': self.credit_card_number(), 'expiration_date': self.credit_card_expiration_date(), 'owner': self.__person.full_name(gender=gender).upper(), } return owner
[ "def", "credit_card_owner", "(", "self", ",", "gender", ":", "Optional", "[", "Gender", "]", "=", "None", ")", "->", "dict", ":", "owner", "=", "{", "'credit_card'", ":", "self", ".", "credit_card_number", "(", ")", ",", "'expiration_date'", ":", "self", ...
Generate credit card owner. :param gender: Gender of credit card owner. :type gender: Gender's enum object. :return:
[ "Generate", "credit", "card", "owner", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/payment.py#L160-L172
train
222,920
lk-geimfari/mimesis
mimesis/providers/text.py
Text.alphabet
def alphabet(self, lower_case: bool = False) -> list: """Get an alphabet for current locale. :param lower_case: Return alphabet in lower case. :return: Alphabet. """ case = 'uppercase' if \ not lower_case else 'lowercase' alpha = self._data['alphabet'].get(case) return alpha
python
def alphabet(self, lower_case: bool = False) -> list: """Get an alphabet for current locale. :param lower_case: Return alphabet in lower case. :return: Alphabet. """ case = 'uppercase' if \ not lower_case else 'lowercase' alpha = self._data['alphabet'].get(case) return alpha
[ "def", "alphabet", "(", "self", ",", "lower_case", ":", "bool", "=", "False", ")", "->", "list", ":", "case", "=", "'uppercase'", "if", "not", "lower_case", "else", "'lowercase'", "alpha", "=", "self", ".", "_data", "[", "'alphabet'", "]", ".", "get", ...
Get an alphabet for current locale. :param lower_case: Return alphabet in lower case. :return: Alphabet.
[ "Get", "an", "alphabet", "for", "current", "locale", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L31-L41
train
222,921
lk-geimfari/mimesis
mimesis/providers/text.py
Text.level
def level(self) -> str: """Generate a random level of danger or something else. :return: Level. :Example: critical. """ levels = self._data['level'] return self.random.choice(levels)
python
def level(self) -> str: """Generate a random level of danger or something else. :return: Level. :Example: critical. """ levels = self._data['level'] return self.random.choice(levels)
[ "def", "level", "(", "self", ")", "->", "str", ":", "levels", "=", "self", ".", "_data", "[", "'level'", "]", "return", "self", ".", "random", ".", "choice", "(", "levels", ")" ]
Generate a random level of danger or something else. :return: Level. :Example: critical.
[ "Generate", "a", "random", "level", "of", "danger", "or", "something", "else", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L43-L52
train
222,922
lk-geimfari/mimesis
mimesis/providers/text.py
Text.text
def text(self, quantity: int = 5) -> str: """Generate the text. :param quantity: Quantity of sentences. :return: Text. """ text = '' for _ in range(quantity): text += ' ' + self.random.choice(self._data['text']) return text.strip()
python
def text(self, quantity: int = 5) -> str: """Generate the text. :param quantity: Quantity of sentences. :return: Text. """ text = '' for _ in range(quantity): text += ' ' + self.random.choice(self._data['text']) return text.strip()
[ "def", "text", "(", "self", ",", "quantity", ":", "int", "=", "5", ")", "->", "str", ":", "text", "=", "''", "for", "_", "in", "range", "(", "quantity", ")", ":", "text", "+=", "' '", "+", "self", ".", "random", ".", "choice", "(", "self", ".",...
Generate the text. :param quantity: Quantity of sentences. :return: Text.
[ "Generate", "the", "text", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L54-L63
train
222,923
lk-geimfari/mimesis
mimesis/providers/text.py
Text.words
def words(self, quantity: int = 5) -> List[str]: """Generate lis of the random words. :param quantity: Quantity of words. Default is 5. :return: Word list. :Example: [science, network, god, octopus, love] """ words = self._data['words'].get('normal') words_list = [self.random.choice(words) for _ in range(quantity)] return words_list
python
def words(self, quantity: int = 5) -> List[str]: """Generate lis of the random words. :param quantity: Quantity of words. Default is 5. :return: Word list. :Example: [science, network, god, octopus, love] """ words = self._data['words'].get('normal') words_list = [self.random.choice(words) for _ in range(quantity)] return words_list
[ "def", "words", "(", "self", ",", "quantity", ":", "int", "=", "5", ")", "->", "List", "[", "str", "]", ":", "words", "=", "self", ".", "_data", "[", "'words'", "]", ".", "get", "(", "'normal'", ")", "words_list", "=", "[", "self", ".", "random",...
Generate lis of the random words. :param quantity: Quantity of words. Default is 5. :return: Word list. :Example: [science, network, god, octopus, love]
[ "Generate", "lis", "of", "the", "random", "words", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L79-L90
train
222,924
lk-geimfari/mimesis
mimesis/providers/text.py
Text.swear_word
def swear_word(self) -> str: """Get a random swear word. :return: Swear word. :Example: Damn. """ bad_words = self._data['words'].get('bad') return self.random.choice(bad_words)
python
def swear_word(self) -> str: """Get a random swear word. :return: Swear word. :Example: Damn. """ bad_words = self._data['words'].get('bad') return self.random.choice(bad_words)
[ "def", "swear_word", "(", "self", ")", "->", "str", ":", "bad_words", "=", "self", ".", "_data", "[", "'words'", "]", ".", "get", "(", "'bad'", ")", "return", "self", ".", "random", ".", "choice", "(", "bad_words", ")" ]
Get a random swear word. :return: Swear word. :Example: Damn.
[ "Get", "a", "random", "swear", "word", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L102-L111
train
222,925
lk-geimfari/mimesis
mimesis/providers/text.py
Text.quote
def quote(self) -> str: """Get a random quote. :return: Quote from movie. :Example: "Bond... James Bond." """ quotes = self._data['quotes'] return self.random.choice(quotes)
python
def quote(self) -> str: """Get a random quote. :return: Quote from movie. :Example: "Bond... James Bond." """ quotes = self._data['quotes'] return self.random.choice(quotes)
[ "def", "quote", "(", "self", ")", "->", "str", ":", "quotes", "=", "self", ".", "_data", "[", "'quotes'", "]", "return", "self", ".", "random", ".", "choice", "(", "quotes", ")" ]
Get a random quote. :return: Quote from movie. :Example: "Bond... James Bond."
[ "Get", "a", "random", "quote", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L113-L122
train
222,926
lk-geimfari/mimesis
mimesis/providers/text.py
Text.color
def color(self) -> str: """Get a random name of color. :return: Color name. :Example: Red. """ colors = self._data['color'] return self.random.choice(colors)
python
def color(self) -> str: """Get a random name of color. :return: Color name. :Example: Red. """ colors = self._data['color'] return self.random.choice(colors)
[ "def", "color", "(", "self", ")", "->", "str", ":", "colors", "=", "self", ".", "_data", "[", "'color'", "]", "return", "self", ".", "random", ".", "choice", "(", "colors", ")" ]
Get a random name of color. :return: Color name. :Example: Red.
[ "Get", "a", "random", "name", "of", "color", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L124-L133
train
222,927
lk-geimfari/mimesis
mimesis/providers/text.py
Text._hex_to_rgb
def _hex_to_rgb(color: str) -> Tuple[int, ...]: """Convert hex color to RGB format. :param color: Hex color. :return: RGB tuple. """ if color.startswith('#'): color = color.lstrip('#') return tuple(int(color[i:i + 2], 16) for i in (0, 2, 4))
python
def _hex_to_rgb(color: str) -> Tuple[int, ...]: """Convert hex color to RGB format. :param color: Hex color. :return: RGB tuple. """ if color.startswith('#'): color = color.lstrip('#') return tuple(int(color[i:i + 2], 16) for i in (0, 2, 4))
[ "def", "_hex_to_rgb", "(", "color", ":", "str", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "if", "color", ".", "startswith", "(", "'#'", ")", ":", "color", "=", "color", ".", "lstrip", "(", "'#'", ")", "return", "tuple", "(", "int", "(...
Convert hex color to RGB format. :param color: Hex color. :return: RGB tuple.
[ "Convert", "hex", "color", "to", "RGB", "format", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L136-L144
train
222,928
lk-geimfari/mimesis
mimesis/providers/text.py
Text.hex_color
def hex_color(self, safe: bool = False) -> str: """Generate a random hex color. :param safe: Get safe Flat UI hex color. :return: Hex color code. :Example: #d8346b """ if safe: return self.random.choice(SAFE_COLORS) return '#{:06x}'.format( self.random.randint(0x000000, 0xffffff))
python
def hex_color(self, safe: bool = False) -> str: """Generate a random hex color. :param safe: Get safe Flat UI hex color. :return: Hex color code. :Example: #d8346b """ if safe: return self.random.choice(SAFE_COLORS) return '#{:06x}'.format( self.random.randint(0x000000, 0xffffff))
[ "def", "hex_color", "(", "self", ",", "safe", ":", "bool", "=", "False", ")", "->", "str", ":", "if", "safe", ":", "return", "self", ".", "random", ".", "choice", "(", "SAFE_COLORS", ")", "return", "'#{:06x}'", ".", "format", "(", "self", ".", "rando...
Generate a random hex color. :param safe: Get safe Flat UI hex color. :return: Hex color code. :Example: #d8346b
[ "Generate", "a", "random", "hex", "color", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L146-L159
train
222,929
lk-geimfari/mimesis
mimesis/providers/text.py
Text.rgb_color
def rgb_color(self, safe: bool = False) -> Tuple[int, ...]: """Generate a random rgb color tuple. :param safe: Get safe RGB tuple. :return: RGB tuple. :Example: (252, 85, 32) """ color = self.hex_color(safe) return self._hex_to_rgb(color)
python
def rgb_color(self, safe: bool = False) -> Tuple[int, ...]: """Generate a random rgb color tuple. :param safe: Get safe RGB tuple. :return: RGB tuple. :Example: (252, 85, 32) """ color = self.hex_color(safe) return self._hex_to_rgb(color)
[ "def", "rgb_color", "(", "self", ",", "safe", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "color", "=", "self", ".", "hex_color", "(", "safe", ")", "return", "self", ".", "_hex_to_rgb", "(", "color", ")" ]
Generate a random rgb color tuple. :param safe: Get safe RGB tuple. :return: RGB tuple. :Example: (252, 85, 32)
[ "Generate", "a", "random", "rgb", "color", "tuple", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L161-L171
train
222,930
lk-geimfari/mimesis
mimesis/providers/text.py
Text.answer
def answer(self) -> str: """Get a random answer in current language. :return: An answer. :Example: No """ answers = self._data['answers'] return self.random.choice(answers)
python
def answer(self) -> str: """Get a random answer in current language. :return: An answer. :Example: No """ answers = self._data['answers'] return self.random.choice(answers)
[ "def", "answer", "(", "self", ")", "->", "str", ":", "answers", "=", "self", ".", "_data", "[", "'answers'", "]", "return", "self", ".", "random", ".", "choice", "(", "answers", ")" ]
Get a random answer in current language. :return: An answer. :Example: No
[ "Get", "a", "random", "answer", "in", "current", "language", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L173-L182
train
222,931
lk-geimfari/mimesis
mimesis/providers/code.py
Code.issn
def issn(self, mask: str = '####-####') -> str: """Generate a random ISSN. :param mask: Mask of ISSN. :return: ISSN. """ return self.random.custom_code(mask=mask)
python
def issn(self, mask: str = '####-####') -> str: """Generate a random ISSN. :param mask: Mask of ISSN. :return: ISSN. """ return self.random.custom_code(mask=mask)
[ "def", "issn", "(", "self", ",", "mask", ":", "str", "=", "'####-####'", ")", "->", "str", ":", "return", "self", ".", "random", ".", "custom_code", "(", "mask", "=", "mask", ")" ]
Generate a random ISSN. :param mask: Mask of ISSN. :return: ISSN.
[ "Generate", "a", "random", "ISSN", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/code.py#L46-L52
train
222,932
lk-geimfari/mimesis
mimesis/providers/code.py
Code.isbn
def isbn(self, fmt: Optional[ISBNFormat] = None, locale: str = 'en') -> str: """Generate ISBN for current locale. To change ISBN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.ISBNFormat` :param fmt: ISBN format. :param locale: Locale code. :return: ISBN. :raises NonEnumerableError: if fmt is not enum ISBNFormat. """ fmt_value = self._validate_enum(item=fmt, enum=ISBNFormat) mask = ISBN_MASKS[fmt_value].format( ISBN_GROUPS[locale]) return self.random.custom_code(mask)
python
def isbn(self, fmt: Optional[ISBNFormat] = None, locale: str = 'en') -> str: """Generate ISBN for current locale. To change ISBN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.ISBNFormat` :param fmt: ISBN format. :param locale: Locale code. :return: ISBN. :raises NonEnumerableError: if fmt is not enum ISBNFormat. """ fmt_value = self._validate_enum(item=fmt, enum=ISBNFormat) mask = ISBN_MASKS[fmt_value].format( ISBN_GROUPS[locale]) return self.random.custom_code(mask)
[ "def", "isbn", "(", "self", ",", "fmt", ":", "Optional", "[", "ISBNFormat", "]", "=", "None", ",", "locale", ":", "str", "=", "'en'", ")", "->", "str", ":", "fmt_value", "=", "self", ".", "_validate_enum", "(", "item", "=", "fmt", ",", "enum", "=",...
Generate ISBN for current locale. To change ISBN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.ISBNFormat` :param fmt: ISBN format. :param locale: Locale code. :return: ISBN. :raises NonEnumerableError: if fmt is not enum ISBNFormat.
[ "Generate", "ISBN", "for", "current", "locale", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/code.py#L54-L69
train
222,933
lk-geimfari/mimesis
mimesis/providers/code.py
Code.ean
def ean(self, fmt: Optional[EANFormat] = None) -> str: """Generate EAN. To change EAN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.EANFormat`. :param fmt: Format of EAN. :return: EAN. :raises NonEnumerableError: if fmt is not enum EANFormat. """ key = self._validate_enum( item=fmt, enum=EANFormat, ) mask = EAN_MASKS[key] return self.random.custom_code(mask=mask)
python
def ean(self, fmt: Optional[EANFormat] = None) -> str: """Generate EAN. To change EAN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.EANFormat`. :param fmt: Format of EAN. :return: EAN. :raises NonEnumerableError: if fmt is not enum EANFormat. """ key = self._validate_enum( item=fmt, enum=EANFormat, ) mask = EAN_MASKS[key] return self.random.custom_code(mask=mask)
[ "def", "ean", "(", "self", ",", "fmt", ":", "Optional", "[", "EANFormat", "]", "=", "None", ")", "->", "str", ":", "key", "=", "self", ".", "_validate_enum", "(", "item", "=", "fmt", ",", "enum", "=", "EANFormat", ",", ")", "mask", "=", "EAN_MASKS"...
Generate EAN. To change EAN format, pass parameter ``fmt`` with needed value of the enum object :class:`~mimesis.enums.EANFormat`. :param fmt: Format of EAN. :return: EAN. :raises NonEnumerableError: if fmt is not enum EANFormat.
[ "Generate", "EAN", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/code.py#L71-L86
train
222,934
lk-geimfari/mimesis
mimesis/providers/code.py
Code.imei
def imei(self) -> str: """Generate a random IMEI. :return: IMEI. """ num = self.random.choice(IMEI_TACS) num = num + str(self.random.randint(100000, 999999)) return num + luhn_checksum(num)
python
def imei(self) -> str: """Generate a random IMEI. :return: IMEI. """ num = self.random.choice(IMEI_TACS) num = num + str(self.random.randint(100000, 999999)) return num + luhn_checksum(num)
[ "def", "imei", "(", "self", ")", "->", "str", ":", "num", "=", "self", ".", "random", ".", "choice", "(", "IMEI_TACS", ")", "num", "=", "num", "+", "str", "(", "self", ".", "random", ".", "randint", "(", "100000", ",", "999999", ")", ")", "return...
Generate a random IMEI. :return: IMEI.
[ "Generate", "a", "random", "IMEI", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/code.py#L88-L95
train
222,935
lk-geimfari/mimesis
mimesis/providers/code.py
Code.pin
def pin(self, mask: str = '####') -> str: """Generate a random PIN code. :param mask: Mask of pin code. :return: PIN code. """ return self.random.custom_code(mask=mask)
python
def pin(self, mask: str = '####') -> str: """Generate a random PIN code. :param mask: Mask of pin code. :return: PIN code. """ return self.random.custom_code(mask=mask)
[ "def", "pin", "(", "self", ",", "mask", ":", "str", "=", "'####'", ")", "->", "str", ":", "return", "self", ".", "random", ".", "custom_code", "(", "mask", "=", "mask", ")" ]
Generate a random PIN code. :param mask: Mask of pin code. :return: PIN code.
[ "Generate", "a", "random", "PIN", "code", "." ]
4b16ee7a8dba6281a904654a88dbb4b052869fc5
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/code.py#L97-L103
train
222,936
sassoftware/saspy
saspy/sasbase.py
SASsession.submit
def submit(self, code: str, results: str = '', prompt: dict = None) -> dict: ''' This method is used to submit any SAS code. It returns the Log and Listing as a python dictionary. - code - the SAS statements you want to execute - results - format of results. 'HTML' by default, alternatively 'TEXT' - prompt - dict of names:flags to prompt for; create macro variables (used in submitted code), then keep or delete the keys which are the names of the macro variables. The boolean flag is to either hide what you type and delete the macros, or show what you type and keep the macros (they will still be available later). for example (what you type for pw will not be displayed, user and dsname will): .. code-block:: python results_dict = sas.submit( """ libname tera teradata server=teracop1 user=&user pw=&pw; proc print data=tera.&dsname (obs=10); run; """ , prompt = {'user': False, 'pw': True, 'dsname': False} ) Returns - a Dict containing two keys:values, [LOG, LST]. LOG is text and LST is 'results' (HTML or TEXT) NOTE: to view HTML results in the ipykernel, issue: from IPython.display import HTML and use HTML() instead of print() In Zeppelin, the html LST results can be displayed via print("%html "+ ll['LST']) to diplay as HTML. i.e,: results = sas.submit("data a; x=1; run; proc print;run') print(results['LOG']) HTML(results['LST']) ''' if self.nosub: return dict(LOG=code, LST='') prompt = prompt if prompt is not None else {} if results == '': if self.results.upper() == 'PANDAS': results = 'HTML' else: results = self.results ll = self._io.submit(code, results, prompt) return ll
python
def submit(self, code: str, results: str = '', prompt: dict = None) -> dict: ''' This method is used to submit any SAS code. It returns the Log and Listing as a python dictionary. - code - the SAS statements you want to execute - results - format of results. 'HTML' by default, alternatively 'TEXT' - prompt - dict of names:flags to prompt for; create macro variables (used in submitted code), then keep or delete the keys which are the names of the macro variables. The boolean flag is to either hide what you type and delete the macros, or show what you type and keep the macros (they will still be available later). for example (what you type for pw will not be displayed, user and dsname will): .. code-block:: python results_dict = sas.submit( """ libname tera teradata server=teracop1 user=&user pw=&pw; proc print data=tera.&dsname (obs=10); run; """ , prompt = {'user': False, 'pw': True, 'dsname': False} ) Returns - a Dict containing two keys:values, [LOG, LST]. LOG is text and LST is 'results' (HTML or TEXT) NOTE: to view HTML results in the ipykernel, issue: from IPython.display import HTML and use HTML() instead of print() In Zeppelin, the html LST results can be displayed via print("%html "+ ll['LST']) to diplay as HTML. i.e,: results = sas.submit("data a; x=1; run; proc print;run') print(results['LOG']) HTML(results['LST']) ''' if self.nosub: return dict(LOG=code, LST='') prompt = prompt if prompt is not None else {} if results == '': if self.results.upper() == 'PANDAS': results = 'HTML' else: results = self.results ll = self._io.submit(code, results, prompt) return ll
[ "def", "submit", "(", "self", ",", "code", ":", "str", ",", "results", ":", "str", "=", "''", ",", "prompt", ":", "dict", "=", "None", ")", "->", "dict", ":", "if", "self", ".", "nosub", ":", "return", "dict", "(", "LOG", "=", "code", ",", "LST...
This method is used to submit any SAS code. It returns the Log and Listing as a python dictionary. - code - the SAS statements you want to execute - results - format of results. 'HTML' by default, alternatively 'TEXT' - prompt - dict of names:flags to prompt for; create macro variables (used in submitted code), then keep or delete the keys which are the names of the macro variables. The boolean flag is to either hide what you type and delete the macros, or show what you type and keep the macros (they will still be available later). for example (what you type for pw will not be displayed, user and dsname will): .. code-block:: python results_dict = sas.submit( """ libname tera teradata server=teracop1 user=&user pw=&pw; proc print data=tera.&dsname (obs=10); run; """ , prompt = {'user': False, 'pw': True, 'dsname': False} ) Returns - a Dict containing two keys:values, [LOG, LST]. LOG is text and LST is 'results' (HTML or TEXT) NOTE: to view HTML results in the ipykernel, issue: from IPython.display import HTML and use HTML() instead of print() In Zeppelin, the html LST results can be displayed via print("%html "+ ll['LST']) to diplay as HTML. i.e,: results = sas.submit("data a; x=1; run; proc print;run') print(results['LOG']) HTML(results['LST'])
[ "This", "method", "is", "used", "to", "submit", "any", "SAS", "code", ".", "It", "returns", "the", "Log", "and", "Listing", "as", "a", "python", "dictionary", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L446-L492
train
222,937
sassoftware/saspy
saspy/sasbase.py
SASsession.exist
def exist(self, table: str, libref: str = "") -> bool: """ Does the SAS data set currently exist :param table: the name of the SAS Data Set :param libref: the libref for the Data Set, defaults to WORK, or USER if assigned :return: Boolean True it the Data Set exists and False if it does not :rtype: bool """ return self._io.exist(table, libref)
python
def exist(self, table: str, libref: str = "") -> bool: """ Does the SAS data set currently exist :param table: the name of the SAS Data Set :param libref: the libref for the Data Set, defaults to WORK, or USER if assigned :return: Boolean True it the Data Set exists and False if it does not :rtype: bool """ return self._io.exist(table, libref)
[ "def", "exist", "(", "self", ",", "table", ":", "str", ",", "libref", ":", "str", "=", "\"\"", ")", "->", "bool", ":", "return", "self", ".", "_io", ".", "exist", "(", "table", ",", "libref", ")" ]
Does the SAS data set currently exist :param table: the name of the SAS Data Set :param libref: the libref for the Data Set, defaults to WORK, or USER if assigned :return: Boolean True it the Data Set exists and False if it does not :rtype: bool
[ "Does", "the", "SAS", "data", "set", "currently", "exist" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L540-L549
train
222,938
sassoftware/saspy
saspy/sasbase.py
SASsession.sasstat
def sasstat(self) -> 'SASstat': """ This methods creates a SASstat object which you can use to run various analytics. See the sasstat.py module. :return: sasstat object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASstat(self)
python
def sasstat(self) -> 'SASstat': """ This methods creates a SASstat object which you can use to run various analytics. See the sasstat.py module. :return: sasstat object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASstat(self)
[ "def", "sasstat", "(", "self", ")", "->", "'SASstat'", ":", "if", "not", "self", ".", "_loaded_macros", ":", "self", ".", "_loadmacros", "(", ")", "self", ".", "_loaded_macros", "=", "True", "return", "SASstat", "(", "self", ")" ]
This methods creates a SASstat object which you can use to run various analytics. See the sasstat.py module. :return: sasstat object
[ "This", "methods", "creates", "a", "SASstat", "object", "which", "you", "can", "use", "to", "run", "various", "analytics", ".", "See", "the", "sasstat", ".", "py", "module", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L562-L573
train
222,939
sassoftware/saspy
saspy/sasbase.py
SASsession.sasml
def sasml(self) -> 'SASml': """ This methods creates a SASML object which you can use to run various analytics. See the sasml.py module. :return: sasml object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASml(self)
python
def sasml(self) -> 'SASml': """ This methods creates a SASML object which you can use to run various analytics. See the sasml.py module. :return: sasml object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASml(self)
[ "def", "sasml", "(", "self", ")", "->", "'SASml'", ":", "if", "not", "self", ".", "_loaded_macros", ":", "self", ".", "_loadmacros", "(", ")", "self", ".", "_loaded_macros", "=", "True", "return", "SASml", "(", "self", ")" ]
This methods creates a SASML object which you can use to run various analytics. See the sasml.py module. :return: sasml object
[ "This", "methods", "creates", "a", "SASML", "object", "which", "you", "can", "use", "to", "run", "various", "analytics", ".", "See", "the", "sasml", ".", "py", "module", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L575-L585
train
222,940
sassoftware/saspy
saspy/sasbase.py
SASsession.sasqc
def sasqc(self) -> 'SASqc': """ This methods creates a SASqc object which you can use to run various analytics. See the sasqc.py module. :return: sasqc object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASqc(self)
python
def sasqc(self) -> 'SASqc': """ This methods creates a SASqc object which you can use to run various analytics. See the sasqc.py module. :return: sasqc object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASqc(self)
[ "def", "sasqc", "(", "self", ")", "->", "'SASqc'", ":", "if", "not", "self", ".", "_loaded_macros", ":", "self", ".", "_loadmacros", "(", ")", "self", ".", "_loaded_macros", "=", "True", "return", "SASqc", "(", "self", ")" ]
This methods creates a SASqc object which you can use to run various analytics. See the sasqc.py module. :return: sasqc object
[ "This", "methods", "creates", "a", "SASqc", "object", "which", "you", "can", "use", "to", "run", "various", "analytics", ".", "See", "the", "sasqc", ".", "py", "module", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L587-L597
train
222,941
sassoftware/saspy
saspy/sasbase.py
SASsession.sasutil
def sasutil(self) -> 'SASutil': """ This methods creates a SASutil object which you can use to run various analytics. See the sasutil.py module. :return: sasutil object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASutil(self)
python
def sasutil(self) -> 'SASutil': """ This methods creates a SASutil object which you can use to run various analytics. See the sasutil.py module. :return: sasutil object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASutil(self)
[ "def", "sasutil", "(", "self", ")", "->", "'SASutil'", ":", "if", "not", "self", ".", "_loaded_macros", ":", "self", ".", "_loadmacros", "(", ")", "self", ".", "_loaded_macros", "=", "True", "return", "SASutil", "(", "self", ")" ]
This methods creates a SASutil object which you can use to run various analytics. See the sasutil.py module. :return: sasutil object
[ "This", "methods", "creates", "a", "SASutil", "object", "which", "you", "can", "use", "to", "run", "various", "analytics", ".", "See", "the", "sasutil", ".", "py", "module", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L599-L610
train
222,942
sassoftware/saspy
saspy/sasbase.py
SASsession.sasviyaml
def sasviyaml(self) -> 'SASViyaML': """ This methods creates a SASViyaML object which you can use to run various analytics. See the SASViyaML.py module. :return: SASViyaML object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASViyaML(self)
python
def sasviyaml(self) -> 'SASViyaML': """ This methods creates a SASViyaML object which you can use to run various analytics. See the SASViyaML.py module. :return: SASViyaML object """ if not self._loaded_macros: self._loadmacros() self._loaded_macros = True return SASViyaML(self)
[ "def", "sasviyaml", "(", "self", ")", "->", "'SASViyaML'", ":", "if", "not", "self", ".", "_loaded_macros", ":", "self", ".", "_loadmacros", "(", ")", "self", ".", "_loaded_macros", "=", "True", "return", "SASViyaML", "(", "self", ")" ]
This methods creates a SASViyaML object which you can use to run various analytics. See the SASViyaML.py module. :return: SASViyaML object
[ "This", "methods", "creates", "a", "SASViyaML", "object", "which", "you", "can", "use", "to", "run", "various", "analytics", ".", "See", "the", "SASViyaML", ".", "py", "module", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L612-L623
train
222,943
sassoftware/saspy
saspy/sasbase.py
SASsession._loadmacros
def _loadmacros(self): """ Load the SAS macros at the start of the session :return: """ macro_path = os.path.dirname(os.path.realpath(__file__)) fd = os.open(macro_path + '/' + 'libname_gen.sas', os.O_RDONLY) code = b'options nosource;\n' code += os.read(fd, 32767) code += b'\noptions source;' self._io._asubmit(code.decode(), results='text') os.close(fd)
python
def _loadmacros(self): """ Load the SAS macros at the start of the session :return: """ macro_path = os.path.dirname(os.path.realpath(__file__)) fd = os.open(macro_path + '/' + 'libname_gen.sas', os.O_RDONLY) code = b'options nosource;\n' code += os.read(fd, 32767) code += b'\noptions source;' self._io._asubmit(code.decode(), results='text') os.close(fd)
[ "def", "_loadmacros", "(", "self", ")", ":", "macro_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "fd", "=", "os", ".", "open", "(", "macro_path", "+", "'/'", "+", "'libname_gen.sas...
Load the SAS macros at the start of the session :return:
[ "Load", "the", "SAS", "macros", "at", "the", "start", "of", "the", "session" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L625-L638
train
222,944
sassoftware/saspy
saspy/sasbase.py
SASsession.sasdata
def sasdata(self, table: str, libref: str = '', results: str = '', dsopts: dict = None) -> 'SASdata': """ Method to define an existing SAS dataset so that it can be accessed via SASPy :param table: the name of the SAS Data Set :param libref: the libref for the Data Set, defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, Pandas, HTML and TEXT are the valid options :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :return: SASdata object """ dsopts = dsopts if dsopts is not None else {} if results == '': results = self.results sd = SASdata(self, libref, table, results, dsopts) if not self.exist(sd.table, sd.libref): if not self.batch: print( "Table " + sd.libref + '.' + sd.table + " does not exist. This SASdata object will not be useful until the data set is created.") return sd
python
def sasdata(self, table: str, libref: str = '', results: str = '', dsopts: dict = None) -> 'SASdata': """ Method to define an existing SAS dataset so that it can be accessed via SASPy :param table: the name of the SAS Data Set :param libref: the libref for the Data Set, defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, Pandas, HTML and TEXT are the valid options :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :return: SASdata object """ dsopts = dsopts if dsopts is not None else {} if results == '': results = self.results sd = SASdata(self, libref, table, results, dsopts) if not self.exist(sd.table, sd.libref): if not self.batch: print( "Table " + sd.libref + '.' + sd.table + " does not exist. This SASdata object will not be useful until the data set is created.") return sd
[ "def", "sasdata", "(", "self", ",", "table", ":", "str", ",", "libref", ":", "str", "=", "''", ",", "results", ":", "str", "=", "''", ",", "dsopts", ":", "dict", "=", "None", ")", "->", "'SASdata'", ":", "dsopts", "=", "dsopts", "if", "dsopts", "...
Method to define an existing SAS dataset so that it can be accessed via SASPy :param table: the name of the SAS Data Set :param libref: the libref for the Data Set, defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, Pandas, HTML and TEXT are the valid options :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :return: SASdata object
[ "Method", "to", "define", "an", "existing", "SAS", "dataset", "so", "that", "it", "can", "be", "accessed", "via", "SASPy" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L640-L677
train
222,945
sassoftware/saspy
saspy/sasbase.py
SASsession.datasets
def datasets(self, libref: str = '') -> str: """ This method is used to query a libref. The results show information about the libref including members. :param libref: the libref to query :return: """ code = "proc datasets" if libref: code += " dd=" + libref code += "; quit;" if self.nosub: print(code) else: if self.results.lower() == 'html': ll = self._io.submit(code, "html") if not self.batch: self.DISPLAY(self.HTML(ll['LST'])) else: return ll else: ll = self._io.submit(code, "text") if self.batch: return ll['LOG'].rsplit(";*\';*\";*/;\n")[0] else: print(ll['LOG'].rsplit(";*\';*\";*/;\n")[0])
python
def datasets(self, libref: str = '') -> str: """ This method is used to query a libref. The results show information about the libref including members. :param libref: the libref to query :return: """ code = "proc datasets" if libref: code += " dd=" + libref code += "; quit;" if self.nosub: print(code) else: if self.results.lower() == 'html': ll = self._io.submit(code, "html") if not self.batch: self.DISPLAY(self.HTML(ll['LST'])) else: return ll else: ll = self._io.submit(code, "text") if self.batch: return ll['LOG'].rsplit(";*\';*\";*/;\n")[0] else: print(ll['LOG'].rsplit(";*\';*\";*/;\n")[0])
[ "def", "datasets", "(", "self", ",", "libref", ":", "str", "=", "''", ")", "->", "str", ":", "code", "=", "\"proc datasets\"", "if", "libref", ":", "code", "+=", "\" dd=\"", "+", "libref", "code", "+=", "\"; quit;\"", "if", "self", ".", "nosub", ":", ...
This method is used to query a libref. The results show information about the libref including members. :param libref: the libref to query :return:
[ "This", "method", "is", "used", "to", "query", "a", "libref", ".", "The", "results", "show", "information", "about", "the", "libref", "including", "members", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L705-L731
train
222,946
sassoftware/saspy
saspy/sasbase.py
SASsession.upload
def upload(self, localfile: str, remotefile: str, overwrite: bool = True, permission: str = '', **kwargs): """ This method uploads a local file to the SAS servers file system. :param localfile: path to the local file :param remotefile: path to remote file to create or overwrite :param overwrite: overwrite the output file if it exists? :param permission: permissions to set on the new file. See SAS Filename Statement Doc for syntax :return: SAS Log """ if self.nosub: print("too complicated to show the code, read the source :), sorry.") return None else: log = self._io.upload(localfile, remotefile, overwrite, permission, **kwargs) return log
python
def upload(self, localfile: str, remotefile: str, overwrite: bool = True, permission: str = '', **kwargs): """ This method uploads a local file to the SAS servers file system. :param localfile: path to the local file :param remotefile: path to remote file to create or overwrite :param overwrite: overwrite the output file if it exists? :param permission: permissions to set on the new file. See SAS Filename Statement Doc for syntax :return: SAS Log """ if self.nosub: print("too complicated to show the code, read the source :), sorry.") return None else: log = self._io.upload(localfile, remotefile, overwrite, permission, **kwargs) return log
[ "def", "upload", "(", "self", ",", "localfile", ":", "str", ",", "remotefile", ":", "str", ",", "overwrite", ":", "bool", "=", "True", ",", "permission", ":", "str", "=", "''", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "nosub", ":", "...
This method uploads a local file to the SAS servers file system. :param localfile: path to the local file :param remotefile: path to remote file to create or overwrite :param overwrite: overwrite the output file if it exists? :param permission: permissions to set on the new file. See SAS Filename Statement Doc for syntax :return: SAS Log
[ "This", "method", "uploads", "a", "local", "file", "to", "the", "SAS", "servers", "file", "system", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L792-L808
train
222,947
sassoftware/saspy
saspy/sasbase.py
SASsession.df2sd
def df2sd(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '', results: str = '', keep_outer_quotes: bool = False) -> 'SASdata': """ This is an alias for 'dataframe2sasdata'. Why type all that? :param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them :return: SASdata object """ return self.dataframe2sasdata(df, table, libref, results, keep_outer_quotes)
python
def df2sd(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '', results: str = '', keep_outer_quotes: bool = False) -> 'SASdata': """ This is an alias for 'dataframe2sasdata'. Why type all that? :param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them :return: SASdata object """ return self.dataframe2sasdata(df, table, libref, results, keep_outer_quotes)
[ "def", "df2sd", "(", "self", ",", "df", ":", "'pd.DataFrame'", ",", "table", ":", "str", "=", "'_df'", ",", "libref", ":", "str", "=", "''", ",", "results", ":", "str", "=", "''", ",", "keep_outer_quotes", ":", "bool", "=", "False", ")", "->", "'SA...
This is an alias for 'dataframe2sasdata'. Why type all that? :param df: :class:`pandas.DataFrame` Pandas Data Frame to import to a SAS Data Set :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them :return: SASdata object
[ "This", "is", "an", "alias", "for", "dataframe2sasdata", ".", "Why", "type", "all", "that?" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L827-L839
train
222,948
sassoftware/saspy
saspy/sasbase.py
SASsession.dataframe2sasdata
def dataframe2sasdata(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '', results: str = '', keep_outer_quotes: bool = False) -> 'SASdata': """ This method imports a Pandas Data Frame to a SAS Data Set, returning the SASdata object for the new Data Set. :param df: Pandas Data Frame to import to a SAS Data Set :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them :return: SASdata object """ if libref != '': if libref.upper() not in self.assigned_librefs(): print("The libref specified is not assigned in this SAS Session.") return None if results == '': results = self.results if self.nosub: print("too complicated to show the code, read the source :), sorry.") return None else: self._io.dataframe2sasdata(df, table, libref, keep_outer_quotes) if self.exist(table, libref): return SASdata(self, libref, table, results) else: return None
python
def dataframe2sasdata(self, df: 'pd.DataFrame', table: str = '_df', libref: str = '', results: str = '', keep_outer_quotes: bool = False) -> 'SASdata': """ This method imports a Pandas Data Frame to a SAS Data Set, returning the SASdata object for the new Data Set. :param df: Pandas Data Frame to import to a SAS Data Set :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them :return: SASdata object """ if libref != '': if libref.upper() not in self.assigned_librefs(): print("The libref specified is not assigned in this SAS Session.") return None if results == '': results = self.results if self.nosub: print("too complicated to show the code, read the source :), sorry.") return None else: self._io.dataframe2sasdata(df, table, libref, keep_outer_quotes) if self.exist(table, libref): return SASdata(self, libref, table, results) else: return None
[ "def", "dataframe2sasdata", "(", "self", ",", "df", ":", "'pd.DataFrame'", ",", "table", ":", "str", "=", "'_df'", ",", "libref", ":", "str", "=", "''", ",", "results", ":", "str", "=", "''", ",", "keep_outer_quotes", ":", "bool", "=", "False", ")", ...
This method imports a Pandas Data Frame to a SAS Data Set, returning the SASdata object for the new Data Set. :param df: Pandas Data Frame to import to a SAS Data Set :param table: the name of the SAS Data Set to create :param libref: the libref for the SAS Data Set being created. Defaults to WORK, or USER if assigned :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :param keep_outer_quotes: the defualt is for SAS to strip outer quotes from delimitted data. This lets you keep them :return: SASdata object
[ "This", "method", "imports", "a", "Pandas", "Data", "Frame", "to", "a", "SAS", "Data", "Set", "returning", "the", "SASdata", "object", "for", "the", "new", "Data", "Set", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L841-L869
train
222,949
sassoftware/saspy
saspy/sasbase.py
SASsession.sd2df
def sd2df(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ This is an alias for 'sasdata2dataframe'. Why type all that? SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: dictionary :return: Pandas data frame """ dsopts = dsopts if dsopts is not None else {} return self.sasdata2dataframe(table, libref, dsopts, method, **kwargs)
python
def sd2df(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ This is an alias for 'sasdata2dataframe'. Why type all that? SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: dictionary :return: Pandas data frame """ dsopts = dsopts if dsopts is not None else {} return self.sasdata2dataframe(table, libref, dsopts, method, **kwargs)
[ "def", "sd2df", "(", "self", ",", "table", ":", "str", ",", "libref", ":", "str", "=", "''", ",", "dsopts", ":", "dict", "=", "None", ",", "method", ":", "str", "=", "'MEMORY'", ",", "*", "*", "kwargs", ")", "->", "'pd.DataFrame'", ":", "dsopts", ...
This is an alias for 'sasdata2dataframe'. Why type all that? SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: dictionary :return: Pandas data frame
[ "This", "is", "an", "alias", "for", "sasdata2dataframe", ".", "Why", "type", "all", "that?", "SASdata", "object", "that", "refers", "to", "the", "Sas", "Data", "Set", "you", "want", "to", "export", "to", "a", "Pandas", "Data", "Frame" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L871-L902
train
222,950
sassoftware/saspy
saspy/sasbase.py
SASsession.sd2df_CSV
def sd2df_CSV(self, table: str, libref: str = '', dsopts: dict = None, tempfile: str = None, tempkeep: bool = False, **kwargs) -> 'pd.DataFrame': """ This is an alias for 'sasdata2dataframe' specifying method='CSV'. Why type all that? SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: dictionary :return: Pandas data frame """ dsopts = dsopts if dsopts is not None else {} return self.sasdata2dataframe(table, libref, dsopts, method='CSV', tempfile=tempfile, tempkeep=tempkeep, **kwargs)
python
def sd2df_CSV(self, table: str, libref: str = '', dsopts: dict = None, tempfile: str = None, tempkeep: bool = False, **kwargs) -> 'pd.DataFrame': """ This is an alias for 'sasdata2dataframe' specifying method='CSV'. Why type all that? SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: dictionary :return: Pandas data frame """ dsopts = dsopts if dsopts is not None else {} return self.sasdata2dataframe(table, libref, dsopts, method='CSV', tempfile=tempfile, tempkeep=tempkeep, **kwargs)
[ "def", "sd2df_CSV", "(", "self", ",", "table", ":", "str", ",", "libref", ":", "str", "=", "''", ",", "dsopts", ":", "dict", "=", "None", ",", "tempfile", ":", "str", "=", "None", ",", "tempkeep", ":", "bool", "=", "False", ",", "*", "*", "kwargs...
This is an alias for 'sasdata2dataframe' specifying method='CSV'. Why type all that? SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: dictionary :return: Pandas data frame
[ "This", "is", "an", "alias", "for", "sasdata2dataframe", "specifying", "method", "=", "CSV", ".", "Why", "type", "all", "that?", "SASdata", "object", "that", "refers", "to", "the", "Sas", "Data", "Set", "you", "want", "to", "export", "to", "a", "Pandas", ...
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L904-L937
train
222,951
sassoftware/saspy
saspy/sasbase.py
SASsession.sasdata2dataframe
def sasdata2dataframe(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object. SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: dictionary :return: Pandas data frame """ dsopts = dsopts if dsopts is not None else {} if self.exist(table, libref) == 0: print('The SAS Data Set ' + libref + '.' + table + ' does not exist') return None if self.nosub: print("too complicated to show the code, read the source :), sorry.") return None else: return self._io.sasdata2dataframe(table, libref, dsopts, method=method, **kwargs)
python
def sasdata2dataframe(self, table: str, libref: str = '', dsopts: dict = None, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object. SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: dictionary :return: Pandas data frame """ dsopts = dsopts if dsopts is not None else {} if self.exist(table, libref) == 0: print('The SAS Data Set ' + libref + '.' + table + ' does not exist') return None if self.nosub: print("too complicated to show the code, read the source :), sorry.") return None else: return self._io.sasdata2dataframe(table, libref, dsopts, method=method, **kwargs)
[ "def", "sasdata2dataframe", "(", "self", ",", "table", ":", "str", ",", "libref", ":", "str", "=", "''", ",", "dsopts", ":", "dict", "=", "None", ",", "method", ":", "str", "=", "'MEMORY'", ",", "*", "*", "kwargs", ")", "->", "'pd.DataFrame'", ":", ...
This method exports the SAS Data Set to a Pandas Data Frame, returning the Data Frame object. SASdata object that refers to the Sas Data Set you want to export to a Pandas Data Frame :param table: the name of the SAS Data Set you want to export to a Pandas Data Frame :param libref: the libref for the SAS Data Set. :param dsopts: a dictionary containing any of the following SAS data set options(where, drop, keep, obs, firstobs): - where is a string - keep are strings or list of strings. - drop are strings or list of strings. - obs is a numbers - either string or int - first obs is a numbers - either string or int - format is a string or dictionary { var: format } .. code-block:: python {'where' : 'msrp < 20000 and make = "Ford"' 'keep' : 'msrp enginesize Cylinders Horsepower Weight' 'drop' : ['msrp', 'enginesize', 'Cylinders', 'Horsepower', 'Weight'] 'obs' : 10 'firstobs' : '12' 'format' : {'money': 'dollar10', 'time': 'tod5.'} } :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: dictionary :return: Pandas data frame
[ "This", "method", "exports", "the", "SAS", "Data", "Set", "to", "a", "Pandas", "Data", "Frame", "returning", "the", "Data", "Frame", "object", ".", "SASdata", "object", "that", "refers", "to", "the", "Sas", "Data", "Set", "you", "want", "to", "export", "...
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L939-L979
train
222,952
sassoftware/saspy
saspy/sasbase.py
SASsession.disconnect
def disconnect(self): """ This method disconnects an IOM session to allow for reconnecting when switching networks See the Advanced topics section of the doc for details """ if self.sascfg.mode != 'IOM': res = "This method is only available with the IOM access method" else: res = self._io.disconnect() return res
python
def disconnect(self): """ This method disconnects an IOM session to allow for reconnecting when switching networks See the Advanced topics section of the doc for details """ if self.sascfg.mode != 'IOM': res = "This method is only available with the IOM access method" else: res = self._io.disconnect() return res
[ "def", "disconnect", "(", "self", ")", ":", "if", "self", ".", "sascfg", ".", "mode", "!=", "'IOM'", ":", "res", "=", "\"This method is only available with the IOM access method\"", "else", ":", "res", "=", "self", ".", "_io", ".", "disconnect", "(", ")", "r...
This method disconnects an IOM session to allow for reconnecting when switching networks See the Advanced topics section of the doc for details
[ "This", "method", "disconnects", "an", "IOM", "session", "to", "allow", "for", "reconnecting", "when", "switching", "networks", "See", "the", "Advanced", "topics", "section", "of", "the", "doc", "for", "details" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L1159-L1168
train
222,953
sassoftware/saspy
saspy/sasiostdio.py
SASsessionSTDIO.exist
def exist(self, table: str, libref: str ="") -> bool: """ table - the name of the SAS Data Set libref - the libref for the Data Set, defaults to WORK, or USER if assigned Returns True it the Data Set exists and False if it does not """ code = "data _null_; e = exist('" if len(libref): code += libref+"." code += table+"');\n" code += "v = exist('" if len(libref): code += libref+"." code += table+"', 'VIEW');\n if e or v then e = 1;\n" code += "te='TABLE_EXISTS='; put te e;run;" ll = self.submit(code, "text") l2 = ll['LOG'].rpartition("TABLE_EXISTS= ") l2 = l2[2].partition("\n") exists = int(l2[0]) return bool(exists)
python
def exist(self, table: str, libref: str ="") -> bool: """ table - the name of the SAS Data Set libref - the libref for the Data Set, defaults to WORK, or USER if assigned Returns True it the Data Set exists and False if it does not """ code = "data _null_; e = exist('" if len(libref): code += libref+"." code += table+"');\n" code += "v = exist('" if len(libref): code += libref+"." code += table+"', 'VIEW');\n if e or v then e = 1;\n" code += "te='TABLE_EXISTS='; put te e;run;" ll = self.submit(code, "text") l2 = ll['LOG'].rpartition("TABLE_EXISTS= ") l2 = l2[2].partition("\n") exists = int(l2[0]) return bool(exists)
[ "def", "exist", "(", "self", ",", "table", ":", "str", ",", "libref", ":", "str", "=", "\"\"", ")", "->", "bool", ":", "code", "=", "\"data _null_; e = exist('\"", "if", "len", "(", "libref", ")", ":", "code", "+=", "libref", "+", "\".\"", "code", "+...
table - the name of the SAS Data Set libref - the libref for the Data Set, defaults to WORK, or USER if assigned Returns True it the Data Set exists and False if it does not
[ "table", "-", "the", "name", "of", "the", "SAS", "Data", "Set", "libref", "-", "the", "libref", "for", "the", "Data", "Set", "defaults", "to", "WORK", "or", "USER", "if", "assigned" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasiostdio.py#L900-L923
train
222,954
sassoftware/saspy
saspy/sasdata.py
SASdata.set_results
def set_results(self, results: str): """ This method set the results attribute for the SASdata object; it stays in effect till changed results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'. :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :return: None """ if results.upper() == "HTML": self.HTML = 1 else: self.HTML = 0 self.results = results
python
def set_results(self, results: str): """ This method set the results attribute for the SASdata object; it stays in effect till changed results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'. :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :return: None """ if results.upper() == "HTML": self.HTML = 1 else: self.HTML = 0 self.results = results
[ "def", "set_results", "(", "self", ",", "results", ":", "str", ")", ":", "if", "results", ".", "upper", "(", ")", "==", "\"HTML\"", ":", "self", ".", "HTML", "=", "1", "else", ":", "self", ".", "HTML", "=", "0", "self", ".", "results", "=", "resu...
This method set the results attribute for the SASdata object; it stays in effect till changed results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'. :param results: format of results, SASsession.results is default, PANDAS, HTML or TEXT are the alternatives :return: None
[ "This", "method", "set", "the", "results", "attribute", "for", "the", "SASdata", "object", ";", "it", "stays", "in", "effect", "till", "changed", "results", "-", "set", "the", "default", "result", "type", "for", "this", "SASdata", "object", ".", "Pandas", ...
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L116-L128
train
222,955
sassoftware/saspy
saspy/sasdata.py
SASdata._returnPD
def _returnPD(self, code, tablename, **kwargs): """ private function to take a sas code normally to create a table, generate pandas data frame and cleanup. :param code: string of SAS code :param tablename: the name of the SAS Data Set :param kwargs: :return: Pandas Data Frame """ libref = kwargs.get('libref','work') ll = self.sas._io.submit(code) check, errorMsg = self._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) if isinstance(tablename, str): pd = self.sas.sasdata2dataframe(tablename, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, tablename)) elif isinstance(tablename, list): pd = dict() for t in tablename: # strip leading '_' from names and capitalize for dictionary labels if self.sas.exist(t, libref): pd[t.replace('_', '').capitalize()] = self.sas.sasdata2dataframe(t, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, t)) else: raise SyntaxError("The tablename must be a string or list %s was submitted" % str(type(tablename))) return pd
python
def _returnPD(self, code, tablename, **kwargs): """ private function to take a sas code normally to create a table, generate pandas data frame and cleanup. :param code: string of SAS code :param tablename: the name of the SAS Data Set :param kwargs: :return: Pandas Data Frame """ libref = kwargs.get('libref','work') ll = self.sas._io.submit(code) check, errorMsg = self._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) if isinstance(tablename, str): pd = self.sas.sasdata2dataframe(tablename, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, tablename)) elif isinstance(tablename, list): pd = dict() for t in tablename: # strip leading '_' from names and capitalize for dictionary labels if self.sas.exist(t, libref): pd[t.replace('_', '').capitalize()] = self.sas.sasdata2dataframe(t, libref) self.sas._io.submit("proc delete data=%s.%s; run;" % (libref, t)) else: raise SyntaxError("The tablename must be a string or list %s was submitted" % str(type(tablename))) return pd
[ "def", "_returnPD", "(", "self", ",", "code", ",", "tablename", ",", "*", "*", "kwargs", ")", ":", "libref", "=", "kwargs", ".", "get", "(", "'libref'", ",", "'work'", ")", "ll", "=", "self", ".", "sas", ".", "_io", ".", "submit", "(", "code", ")...
private function to take a sas code normally to create a table, generate pandas data frame and cleanup. :param code: string of SAS code :param tablename: the name of the SAS Data Set :param kwargs: :return: Pandas Data Frame
[ "private", "function", "to", "take", "a", "sas", "code", "normally", "to", "create", "a", "table", "generate", "pandas", "data", "frame", "and", "cleanup", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L145-L172
train
222,956
sassoftware/saspy
saspy/sasdata.py
SASdata.where
def where(self, where: str) -> 'SASdata': """ This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object """ sd = SASdata(self.sas, self.libref, self.table, dsopts=dict(self.dsopts)) sd.HTML = self.HTML sd.dsopts['where'] = where return sd
python
def where(self, where: str) -> 'SASdata': """ This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object """ sd = SASdata(self.sas, self.libref, self.table, dsopts=dict(self.dsopts)) sd.HTML = self.HTML sd.dsopts['where'] = where return sd
[ "def", "where", "(", "self", ",", "where", ":", "str", ")", "->", "'SASdata'", ":", "sd", "=", "SASdata", "(", "self", ".", "sas", ",", "self", ".", "libref", ",", "self", ".", "table", ",", "dsopts", "=", "dict", "(", "self", ".", "dsopts", ")",...
This method returns a clone of the SASdata object, with the where attribute set. The original SASdata object is not affected. :param where: the where clause to apply :return: SAS data object
[ "This", "method", "returns", "a", "clone", "of", "the", "SASdata", "object", "with", "the", "where", "attribute", "set", ".", "The", "original", "SASdata", "object", "is", "not", "affected", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L180-L190
train
222,957
sassoftware/saspy
saspy/sasdata.py
SASdata.head
def head(self, obs=5): """ display the first n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ topts = dict(self.dsopts) topts['obs'] = obs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _head ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_head') else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
python
def head(self, obs=5): """ display the first n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ topts = dict(self.dsopts) topts['obs'] = obs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _head ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_head') else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "head", "(", "self", ",", "obs", "=", "5", ")", ":", "topts", "=", "dict", "(", "self", ".", "dsopts", ")", "topts", "[", "'obs'", "]", "=", "obs", "code", "=", "\"proc print data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", "...
display the first n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return:
[ "display", "the", "first", "n", "rows", "of", "a", "table" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L192-L225
train
222,958
sassoftware/saspy
saspy/sasdata.py
SASdata.tail
def tail(self, obs=5): """ display the last n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" nosub = self.sas.nosub self.sas.nosub = False le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: lastobs = obs firstobs = lastobs - (obs - 1) if firstobs < 1: firstobs = 1 topts = dict(self.dsopts) topts['obs'] = lastobs topts['firstobs'] = firstobs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" self.sas.nosub = nosub if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _tail ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_tail') else: if self.HTML: if not le: ll = self.sas._io.submit(code) else: ll = le if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not le: ll = self.sas._io.submit(code, "text") else: ll = le if not self.sas.batch: print(ll['LST']) else: return ll
python
def tail(self, obs=5): """ display the last n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return: """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" nosub = self.sas.nosub self.sas.nosub = False le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: lastobs = obs firstobs = lastobs - (obs - 1) if firstobs < 1: firstobs = 1 topts = dict(self.dsopts) topts['obs'] = lastobs topts['firstobs'] = firstobs code = "proc print data=" + self.libref + '.' + self.table + self.sas._dsopts(topts) + ";run;" self.sas.nosub = nosub if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "data _tail ; set %s.%s %s; run;" % (self.libref, self.table, self.sas._dsopts(topts)) return self._returnPD(code, '_tail') else: if self.HTML: if not le: ll = self.sas._io.submit(code) else: ll = le if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not le: ll = self.sas._io.submit(code, "text") else: ll = le if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "tail", "(", "self", ",", "obs", "=", "5", ")", ":", "code", "=", "\"proc sql;select count(*) format best32. into :lastobs from \"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";%...
display the last n rows of a table :param obs: the number of rows of the table that you want to display. The default is 5 :return:
[ "display", "the", "last", "n", "rows", "of", "a", "table" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L227-L285
train
222,959
sassoftware/saspy
saspy/sasdata.py
SASdata.obs
def obs(self): """ return the number of observations for your SASdata object """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" if self.sas.nosub: print(code) return le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: print("The SASdata object is not valid. The table doesn't exist in this SAS session at this time.") lastobs = None return lastobs
python
def obs(self): """ return the number of observations for your SASdata object """ code = "proc sql;select count(*) format best32. into :lastobs from " + self.libref + '.' + self.table + self._dsopts() + ";%put lastobs=&lastobs tom;quit;" if self.sas.nosub: print(code) return le = self._is_valid() if not le: ll = self.sas.submit(code, "text") lastobs = ll['LOG'].rpartition("lastobs=") lastobs = lastobs[2].partition(" tom") lastobs = int(lastobs[0]) else: print("The SASdata object is not valid. The table doesn't exist in this SAS session at this time.") lastobs = None return lastobs
[ "def", "obs", "(", "self", ")", ":", "code", "=", "\"proc sql;select count(*) format best32. into :lastobs from \"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";%put lastobs=&lastobs tom;quit;\...
return the number of observations for your SASdata object
[ "return", "the", "number", "of", "observations", "for", "your", "SASdata", "object" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L287-L308
train
222,960
sassoftware/saspy
saspy/sasdata.py
SASdata.contents
def contents(self): """ display metadata about the table. size, number of rows, columns and their data type ... :return: output """ code = "proc contents data=" + self.libref + '.' + self.table + self._dsopts() + ";run;" if self.sas.nosub: print(code) return ll = self._is_valid() if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;" % (self.libref, self.table, self._dsopts()) code += "ods output Attributes=work._attributes;" code += "ods output EngineHost=work._EngineHost;" code += "ods output Variables=work._Variables;" code += "ods output Sortedby=work._Sortedby;" code += "run;" return self._returnPD(code, ['_attributes', '_EngineHost', '_Variables', '_Sortedby']) else: if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
python
def contents(self): """ display metadata about the table. size, number of rows, columns and their data type ... :return: output """ code = "proc contents data=" + self.libref + '.' + self.table + self._dsopts() + ";run;" if self.sas.nosub: print(code) return ll = self._is_valid() if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;" % (self.libref, self.table, self._dsopts()) code += "ods output Attributes=work._attributes;" code += "ods output EngineHost=work._EngineHost;" code += "ods output Variables=work._Variables;" code += "ods output Sortedby=work._Sortedby;" code += "run;" return self._returnPD(code, ['_attributes', '_EngineHost', '_Variables', '_Sortedby']) else: if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "contents", "(", "self", ")", ":", "code", "=", "\"proc contents data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "self", ".", "_dsopts", "(", ")", "+", "\";run;\"", "if", "self", ".", "sas", ".", "nosub", ":",...
display metadata about the table. size, number of rows, columns and their data type ... :return: output
[ "display", "metadata", "about", "the", "table", ".", "size", "number", "of", "rows", "columns", "and", "their", "data", "type", "..." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L449-L485
train
222,961
sassoftware/saspy
saspy/sasdata.py
SASdata.columnInfo
def columnInfo(self): """ display metadata about the table, size, number of rows, columns and their data type """ code = "proc contents data=" + self.libref + '.' + self.table + ' ' + self._dsopts() + ";ods select Variables;run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;ods output Variables=work._variables ;run;" % (self.libref, self.table, self._dsopts()) pd = self._returnPD(code, '_variables') pd['Type'] = pd['Type'].str.rstrip() return pd else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
python
def columnInfo(self): """ display metadata about the table, size, number of rows, columns and their data type """ code = "proc contents data=" + self.libref + '.' + self.table + ' ' + self._dsopts() + ";ods select Variables;run;" if self.sas.nosub: print(code) return if self.results.upper() == 'PANDAS': code = "proc contents data=%s.%s %s ;ods output Variables=work._variables ;run;" % (self.libref, self.table, self._dsopts()) pd = self._returnPD(code, '_variables') pd['Type'] = pd['Type'].str.rstrip() return pd else: ll = self._is_valid() if self.HTML: if not ll: ll = self.sas._io.submit(code) if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll else: if not ll: ll = self.sas._io.submit(code, "text") if not self.sas.batch: print(ll['LST']) else: return ll
[ "def", "columnInfo", "(", "self", ")", ":", "code", "=", "\"proc contents data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+", "' '", "+", "self", ".", "_dsopts", "(", ")", "+", "\";ods select Variables;run;\"", "if", "self", ...
display metadata about the table, size, number of rows, columns and their data type
[ "display", "metadata", "about", "the", "table", "size", "number", "of", "rows", "columns", "and", "their", "data", "type" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L487-L518
train
222,962
sassoftware/saspy
saspy/sasdata.py
SASdata.sort
def sort(self, by: str, out: object = '', **kwargs) -> 'SASdata': """ Sort the SAS Data Set :param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;) :param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER if assigned or a sas data object'' will sort in place if allowed :param kwargs: :return: SASdata object if out= not specified, or a new SASdata object for out= when specified :Example: #. wkcars.sort('type') #. wkcars2 = sas.sasdata('cars2') #. wkcars.sort('cylinders', wkcars2) #. cars2=cars.sort('DESCENDING origin', out='foobar') #. cars.sort('type').head() #. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type')) #. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars')) """ outstr = '' options = '' if out: if isinstance(out, str): fn = out.partition('.') if fn[1] == '.': libref = fn[0] table = fn[2] outstr = "out=%s.%s" % (libref, table) else: libref = '' table = fn[0] outstr = "out=" + table else: libref = out.libref table = out.table outstr = "out=%s.%s" % (out.libref, out.table) if 'options' in kwargs: options = kwargs['options'] code = "proc sort data=%s.%s%s %s %s ;\n" % (self.libref, self.table, self._dsopts(), outstr, options) code += "by %s;" % by code += "run\n;" runcode = True if self.sas.nosub: print(code) runcode = False ll = self._is_valid() if ll: runcode = False if runcode: ll = self.sas.submit(code, "text") elog = [] for line in ll['LOG'].splitlines(): if line.startswith('ERROR'): elog.append(line) if len(elog): raise RuntimeError("\n".join(elog)) if out: if not isinstance(out, str): return out else: return self.sas.sasdata(table, libref, self.results) else: return self
python
def sort(self, by: str, out: object = '', **kwargs) -> 'SASdata': """ Sort the SAS Data Set :param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;) :param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER if assigned or a sas data object'' will sort in place if allowed :param kwargs: :return: SASdata object if out= not specified, or a new SASdata object for out= when specified :Example: #. wkcars.sort('type') #. wkcars2 = sas.sasdata('cars2') #. wkcars.sort('cylinders', wkcars2) #. cars2=cars.sort('DESCENDING origin', out='foobar') #. cars.sort('type').head() #. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type')) #. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars')) """ outstr = '' options = '' if out: if isinstance(out, str): fn = out.partition('.') if fn[1] == '.': libref = fn[0] table = fn[2] outstr = "out=%s.%s" % (libref, table) else: libref = '' table = fn[0] outstr = "out=" + table else: libref = out.libref table = out.table outstr = "out=%s.%s" % (out.libref, out.table) if 'options' in kwargs: options = kwargs['options'] code = "proc sort data=%s.%s%s %s %s ;\n" % (self.libref, self.table, self._dsopts(), outstr, options) code += "by %s;" % by code += "run\n;" runcode = True if self.sas.nosub: print(code) runcode = False ll = self._is_valid() if ll: runcode = False if runcode: ll = self.sas.submit(code, "text") elog = [] for line in ll['LOG'].splitlines(): if line.startswith('ERROR'): elog.append(line) if len(elog): raise RuntimeError("\n".join(elog)) if out: if not isinstance(out, str): return out else: return self.sas.sasdata(table, libref, self.results) else: return self
[ "def", "sort", "(", "self", ",", "by", ":", "str", ",", "out", ":", "object", "=", "''", ",", "*", "*", "kwargs", ")", "->", "'SASdata'", ":", "outstr", "=", "''", "options", "=", "''", "if", "out", ":", "if", "isinstance", "(", "out", ",", "st...
Sort the SAS Data Set :param by: REQUIRED variable to sort by (BY <DESCENDING> variable-1 <<DESCENDING> variable-2 ...>;) :param out: OPTIONAL takes either a string 'libref.table' or 'table' which will go to WORK or USER if assigned or a sas data object'' will sort in place if allowed :param kwargs: :return: SASdata object if out= not specified, or a new SASdata object for out= when specified :Example: #. wkcars.sort('type') #. wkcars2 = sas.sasdata('cars2') #. wkcars.sort('cylinders', wkcars2) #. cars2=cars.sort('DESCENDING origin', out='foobar') #. cars.sort('type').head() #. stat_results = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type')) #. stat_results2 = stat.reg(model='horsepower = Cylinders EngineSize', by='type', data=wkcars.sort('type','work.cars'))
[ "Sort", "the", "SAS", "Data", "Set" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L733-L799
train
222,963
sassoftware/saspy
saspy/sasdata.py
SASdata.to_csv
def to_csv(self, file: str, opts: dict = None) -> str: """ This method will export a SAS Data Set to a file in CSV format. :param file: the OS filesystem path of the file to be created (exported from this SAS Data Set) :return: """ opts = opts if opts is not None else {} ll = self._is_valid() if ll: if not self.sas.batch: print(ll['LOG']) else: return ll else: return self.sas.write_csv(file, self.table, self.libref, self.dsopts, opts)
python
def to_csv(self, file: str, opts: dict = None) -> str: """ This method will export a SAS Data Set to a file in CSV format. :param file: the OS filesystem path of the file to be created (exported from this SAS Data Set) :return: """ opts = opts if opts is not None else {} ll = self._is_valid() if ll: if not self.sas.batch: print(ll['LOG']) else: return ll else: return self.sas.write_csv(file, self.table, self.libref, self.dsopts, opts)
[ "def", "to_csv", "(", "self", ",", "file", ":", "str", ",", "opts", ":", "dict", "=", "None", ")", "->", "str", ":", "opts", "=", "opts", "if", "opts", "is", "not", "None", "else", "{", "}", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", ...
This method will export a SAS Data Set to a file in CSV format. :param file: the OS filesystem path of the file to be created (exported from this SAS Data Set) :return:
[ "This", "method", "will", "export", "a", "SAS", "Data", "Set", "to", "a", "file", "in", "CSV", "format", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L912-L927
train
222,964
sassoftware/saspy
saspy/sasdata.py
SASdata.score
def score(self, file: str = '', code: str = '', out: 'SASdata' = None) -> 'SASdata': """ This method is meant to update a SAS Data object with a model score file. :param file: a file reference to the SAS score code :param code: a string of the valid SAS score code :param out: Where to the write the file. Defaults to update in place :return: The Scored SAS Data object. """ if out is not None: outTable = out.table outLibref = out.libref else: outTable = self.table outLibref = self.libref codestr = code code = "data %s.%s%s;" % (outLibref, outTable, self._dsopts()) code += "set %s.%s%s;" % (self.libref, self.table, self._dsopts()) if len(file)>0: code += '%%include "%s";' % file else: code += "%s;" %codestr code += "run;" if self.sas.nosub: print(code) return None ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
python
def score(self, file: str = '', code: str = '', out: 'SASdata' = None) -> 'SASdata': """ This method is meant to update a SAS Data object with a model score file. :param file: a file reference to the SAS score code :param code: a string of the valid SAS score code :param out: Where to the write the file. Defaults to update in place :return: The Scored SAS Data object. """ if out is not None: outTable = out.table outLibref = out.libref else: outTable = self.table outLibref = self.libref codestr = code code = "data %s.%s%s;" % (outLibref, outTable, self._dsopts()) code += "set %s.%s%s;" % (self.libref, self.table, self._dsopts()) if len(file)>0: code += '%%include "%s";' % file else: code += "%s;" %codestr code += "run;" if self.sas.nosub: print(code) return None ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
[ "def", "score", "(", "self", ",", "file", ":", "str", "=", "''", ",", "code", ":", "str", "=", "''", ",", "out", ":", "'SASdata'", "=", "None", ")", "->", "'SASdata'", ":", "if", "out", "is", "not", "None", ":", "outTable", "=", "out", ".", "ta...
This method is meant to update a SAS Data object with a model score file. :param file: a file reference to the SAS score code :param code: a string of the valid SAS score code :param out: Where to the write the file. Defaults to update in place :return: The Scored SAS Data object.
[ "This", "method", "is", "meant", "to", "update", "a", "SAS", "Data", "object", "with", "a", "model", "score", "file", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L929-L966
train
222,965
sassoftware/saspy
saspy/sasdata.py
SASdata.to_df
def to_df(self, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: :return: Pandas data frame """ ll = self._is_valid() if ll: print(ll['LOG']) return None else: return self.sas.sasdata2dataframe(self.table, self.libref, self.dsopts, method, **kwargs)
python
def to_df(self, method: str = 'MEMORY', **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: :return: Pandas data frame """ ll = self._is_valid() if ll: print(ll['LOG']) return None else: return self.sas.sasdata2dataframe(self.table, self.libref, self.dsopts, method, **kwargs)
[ "def", "to_df", "(", "self", ",", "method", ":", "str", "=", "'MEMORY'", ",", "*", "*", "kwargs", ")", "->", "'pd.DataFrame'", ":", "ll", "=", "self", ".", "_is_valid", "(", ")", "if", "ll", ":", "print", "(", "ll", "[", "'LOG'", "]", ")", "retur...
Export this SAS Data Set to a Pandas Data Frame :param method: defaults to MEMORY; the original method. CSV is the other choice which uses an intermediary csv file; faster for large data :param kwargs: :return: Pandas data frame
[ "Export", "this", "SAS", "Data", "Set", "to", "a", "Pandas", "Data", "Frame" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L978-L991
train
222,966
sassoftware/saspy
saspy/sasdata.py
SASdata.to_df_CSV
def to_df_CSV(self, tempfile: str=None, tempkeep: bool=False, **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame via CSV file :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: :return: Pandas data frame :rtype: 'pd.DataFrame' """ return self.to_df(method='CSV', tempfile=tempfile, tempkeep=tempkeep, **kwargs)
python
def to_df_CSV(self, tempfile: str=None, tempkeep: bool=False, **kwargs) -> 'pd.DataFrame': """ Export this SAS Data Set to a Pandas Data Frame via CSV file :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: :return: Pandas data frame :rtype: 'pd.DataFrame' """ return self.to_df(method='CSV', tempfile=tempfile, tempkeep=tempkeep, **kwargs)
[ "def", "to_df_CSV", "(", "self", ",", "tempfile", ":", "str", "=", "None", ",", "tempkeep", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", "->", "'pd.DataFrame'", ":", "return", "self", ".", "to_df", "(", "method", "=", "'CSV'", ",", "tempf...
Export this SAS Data Set to a Pandas Data Frame via CSV file :param tempfile: [optional] an OS path for a file to use for the local CSV file; default it a temporary file that's cleaned up :param tempkeep: if you specify your own file to use with tempfile=, this controls whether it's cleaned up after using it :param kwargs: :return: Pandas data frame :rtype: 'pd.DataFrame'
[ "Export", "this", "SAS", "Data", "Set", "to", "a", "Pandas", "Data", "Frame", "via", "CSV", "file" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L993-L1003
train
222,967
sassoftware/saspy
saspy/sasdata.py
SASdata.series
def series(self, x: str, y: list, title: str = '') -> object: """ This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots. :param x: the x axis variable; generally a time or continuous variable. :param y: the y axis variable(s), you can specify a single column or a list of columns :param title: an optional Title for the chart :return: graph object """ code = "proc sgplot data=" + self.libref + '.' + self.table + self._dsopts() + ";\n" if len(title) > 0: code += '\ttitle "' + title + '";\n' if isinstance(y, list): num = len(y) else: num = 1 y = [y] for i in range(num): code += "\tseries x=" + x + " y=" + str(y[i]) + ";\n" code += 'run;\n' + 'title;' if self.sas.nosub: print(code) return ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
python
def series(self, x: str, y: list, title: str = '') -> object: """ This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots. :param x: the x axis variable; generally a time or continuous variable. :param y: the y axis variable(s), you can specify a single column or a list of columns :param title: an optional Title for the chart :return: graph object """ code = "proc sgplot data=" + self.libref + '.' + self.table + self._dsopts() + ";\n" if len(title) > 0: code += '\ttitle "' + title + '";\n' if isinstance(y, list): num = len(y) else: num = 1 y = [y] for i in range(num): code += "\tseries x=" + x + " y=" + str(y[i]) + ";\n" code += 'run;\n' + 'title;' if self.sas.nosub: print(code) return ll = self._is_valid() if not ll: html = self.HTML self.HTML = 1 ll = self.sas._io.submit(code) self.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) else: return ll
[ "def", "series", "(", "self", ",", "x", ":", "str", ",", "y", ":", "list", ",", "title", ":", "str", "=", "''", ")", "->", "object", ":", "code", "=", "\"proc sgplot data=\"", "+", "self", ".", "libref", "+", "'.'", "+", "self", ".", "table", "+"...
This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots. :param x: the x axis variable; generally a time or continuous variable. :param y: the y axis variable(s), you can specify a single column or a list of columns :param title: an optional Title for the chart :return: graph object
[ "This", "method", "plots", "a", "series", "of", "x", "y", "coordinates", ".", "You", "can", "provide", "a", "list", "of", "y", "columns", "for", "multiple", "line", "plots", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdata.py#L1201-L1239
train
222,968
sassoftware/saspy
saspy/sasproccommons.py
SASProcCommons._charlist
def _charlist(self, data) -> list: """ Private method to return the variables in a SAS Data set that are of type char :param data: SAS Data object to process :return: list of character variables :rtype: list """ # Get list of character variables to add to nominal list char_string = """ data _null_; file LOG; d = open('{0}.{1}'); nvars = attrn(d, 'NVARS'); put 'VARLIST='; do i = 1 to nvars; vart = vartype(d, i); var = varname(d, i); if vart eq 'C' then put var; end; put 'VARLISTend='; run; """ # ignore teach_me_SAS mode to run contents nosub = self.sas.nosub self.sas.nosub = False ll = self.sas.submit(char_string.format(data.libref, data.table + data._dsopts())) self.sas.nosub = nosub l2 = ll['LOG'].partition("VARLIST=\n") l2 = l2[2].rpartition("VARLISTend=\n") charlist1 = l2[0].split("\n") del charlist1[len(charlist1) - 1] charlist1 = [x.casefold() for x in charlist1] return charlist1
python
def _charlist(self, data) -> list: """ Private method to return the variables in a SAS Data set that are of type char :param data: SAS Data object to process :return: list of character variables :rtype: list """ # Get list of character variables to add to nominal list char_string = """ data _null_; file LOG; d = open('{0}.{1}'); nvars = attrn(d, 'NVARS'); put 'VARLIST='; do i = 1 to nvars; vart = vartype(d, i); var = varname(d, i); if vart eq 'C' then put var; end; put 'VARLISTend='; run; """ # ignore teach_me_SAS mode to run contents nosub = self.sas.nosub self.sas.nosub = False ll = self.sas.submit(char_string.format(data.libref, data.table + data._dsopts())) self.sas.nosub = nosub l2 = ll['LOG'].partition("VARLIST=\n") l2 = l2[2].rpartition("VARLISTend=\n") charlist1 = l2[0].split("\n") del charlist1[len(charlist1) - 1] charlist1 = [x.casefold() for x in charlist1] return charlist1
[ "def", "_charlist", "(", "self", ",", "data", ")", "->", "list", ":", "# Get list of character variables to add to nominal list", "char_string", "=", "\"\"\"\n data _null_; file LOG;\n d = open('{0}.{1}');\n nvars = attrn(d, 'NVARS');\n put 'VARLIST=';\n ...
Private method to return the variables in a SAS Data set that are of type char :param data: SAS Data object to process :return: list of character variables :rtype: list
[ "Private", "method", "to", "return", "the", "variables", "in", "a", "SAS", "Data", "set", "that", "are", "of", "type", "char" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasproccommons.py#L328-L360
train
222,969
sassoftware/saspy
saspy/sasioiom.py
SASsessionIOM.disconnect
def disconnect(self): """ This method disconnects an IOM session to allow for reconnecting when switching networks """ if not self.sascfg.reconnect: return "Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect" pgm = b'\n'+b'tom says EOL=DISCONNECT \n' self.stdin[0].send(pgm) while True: try: log = self.stderr[0].recv(4096).decode(errors='replace') except (BlockingIOError): log = b'' if len(log) > 0: if log.count("DISCONNECT") >= 1: break return log.rstrip("DISCONNECT")
python
def disconnect(self): """ This method disconnects an IOM session to allow for reconnecting when switching networks """ if not self.sascfg.reconnect: return "Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect" pgm = b'\n'+b'tom says EOL=DISCONNECT \n' self.stdin[0].send(pgm) while True: try: log = self.stderr[0].recv(4096).decode(errors='replace') except (BlockingIOError): log = b'' if len(log) > 0: if log.count("DISCONNECT") >= 1: break return log.rstrip("DISCONNECT")
[ "def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "sascfg", ".", "reconnect", ":", "return", "\"Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect\"", "pgm", "=", "b'\\n'", "+", "b'tom says EOL=DISCONNECT ...
This method disconnects an IOM session to allow for reconnecting when switching networks
[ "This", "method", "disconnects", "an", "IOM", "session", "to", "allow", "for", "reconnecting", "when", "switching", "networks" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasioiom.py#L1034-L1055
train
222,970
sassoftware/saspy
saspy/sasdecorator.py
procDecorator.proc_decorator
def proc_decorator(req_set): """ Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword arguments actually passed in to the function. """ def decorator(func): @wraps(func) def inner(self, *args, **kwargs): proc = func.__name__.lower() inner.proc_decorator = kwargs self.logger.debug("processing proc:{}".format(func.__name__)) self.logger.debug(req_set) self.logger.debug("kwargs type: " + str(type(kwargs))) if proc in ['hplogistic', 'hpreg']: kwargs['ODSGraphics'] = kwargs.get('ODSGraphics', False) if proc == 'hpcluster': proc = 'hpclus' legal_set = set(kwargs.keys()) self.logger.debug(legal_set) return SASProcCommons._run_proc(self, proc, req_set, legal_set, **kwargs) return inner return decorator
python
def proc_decorator(req_set): """ Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword arguments actually passed in to the function. """ def decorator(func): @wraps(func) def inner(self, *args, **kwargs): proc = func.__name__.lower() inner.proc_decorator = kwargs self.logger.debug("processing proc:{}".format(func.__name__)) self.logger.debug(req_set) self.logger.debug("kwargs type: " + str(type(kwargs))) if proc in ['hplogistic', 'hpreg']: kwargs['ODSGraphics'] = kwargs.get('ODSGraphics', False) if proc == 'hpcluster': proc = 'hpclus' legal_set = set(kwargs.keys()) self.logger.debug(legal_set) return SASProcCommons._run_proc(self, proc, req_set, legal_set, **kwargs) return inner return decorator
[ "def", "proc_decorator", "(", "req_set", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "proc", "=", "func", ".", "__name__", ...
Decorator that provides the wrapped function with an attribute 'actual_kwargs' containing just those keyword arguments actually passed in to the function.
[ "Decorator", "that", "provides", "the", "wrapped", "function", "with", "an", "attribute", "actual_kwargs", "containing", "just", "those", "keyword", "arguments", "actually", "passed", "in", "to", "the", "function", "." ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasdecorator.py#L15-L37
train
222,971
sassoftware/saspy
saspy/sasresults.py
SASresults.ALL
def ALL(self): """ This method shows all the results attributes for a given object """ if not self.sas.batch: for i in self._names: if i.upper()!='LOG': x = self.__getattr__(i) if isinstance(x, pd.DataFrame): if self.sas.sascfg.display.lower() == 'zeppelin': print("%text "+i+"\n"+str(x)+"\n") else: self.sas.DISPLAY(x) else: ret = [] for i in self._names: if i.upper()!='LOG': ret.append(self.__getattr__(i)) return ret
python
def ALL(self): """ This method shows all the results attributes for a given object """ if not self.sas.batch: for i in self._names: if i.upper()!='LOG': x = self.__getattr__(i) if isinstance(x, pd.DataFrame): if self.sas.sascfg.display.lower() == 'zeppelin': print("%text "+i+"\n"+str(x)+"\n") else: self.sas.DISPLAY(x) else: ret = [] for i in self._names: if i.upper()!='LOG': ret.append(self.__getattr__(i)) return ret
[ "def", "ALL", "(", "self", ")", ":", "if", "not", "self", ".", "sas", ".", "batch", ":", "for", "i", "in", "self", ".", "_names", ":", "if", "i", ".", "upper", "(", ")", "!=", "'LOG'", ":", "x", "=", "self", ".", "__getattr__", "(", "i", ")",...
This method shows all the results attributes for a given object
[ "This", "method", "shows", "all", "the", "results", "attributes", "for", "a", "given", "object" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasresults.py#L108-L126
train
222,972
sassoftware/saspy
saspy/sastabulate.py
Tabulate.execute_table
def execute_table(self, _output_type, **kwargs: dict) -> 'SASresults': """ executes a PROC TABULATE statement You must specify an output type to use this method, of 'HTML', 'text', or 'Pandas'. There are three convenience functions for generating specific output; see: .text_table() .table() .to_dataframe() :param _output_type: style of output to use :param left: the query for the left side of the table :param top: the query for the top of the table :return: """ left = kwargs.pop('left', None) top = kwargs.pop('top', None) sets = dict(classes=set(), vars=set()) left._gather(sets) if top: top._gather(sets) table = top \ and '%s, %s' % (str(left), str(top)) \ or str(left) proc_kwargs = dict( cls=' '.join(sets['classes']), var=' '.join(sets['vars']), table=table ) # permit additional valid options if passed; for now, just 'where' proc_kwargs.update(kwargs) # we can't easily use the SASProcCommons approach for submiting, # since this is merely an output / display proc for us; # but we can at least use it to check valid options in the canonical saspy way required_options = {'cls', 'var', 'table'} allowed_options = {'cls', 'var', 'table', 'where'} verifiedKwargs = sp.sasproccommons.SASProcCommons._stmt_check(self, required_options, allowed_options, proc_kwargs) if (_output_type == 'Pandas'): # for pandas, use the out= directive code = "proc tabulate data=%s.%s %s out=temptab;\n" % ( self.data.libref, self.data.table, self.data._dsopts()) else: code = "proc tabulate data=%s.%s %s;\n" % (self.data.libref, self.data.table, self.data._dsopts()) # build the code for arg, value in verifiedKwargs.items(): code += " %s %s;\n" % (arg == 'cls' and 'class' or arg, value) code += "run;" # teach_me_SAS if self.sas.nosub: print(code) return # submit the code ll = self.data._is_valid() if _output_type == 'HTML': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code) self.data.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) check, errorMsg = self.data._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) else: return ll elif _output_type == 'text': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code, 'text') self.data.HTML = html print(ll['LST']) return elif _output_type == 'Pandas': return self.to_nested_dataframe(code)
python
def execute_table(self, _output_type, **kwargs: dict) -> 'SASresults': """ executes a PROC TABULATE statement You must specify an output type to use this method, of 'HTML', 'text', or 'Pandas'. There are three convenience functions for generating specific output; see: .text_table() .table() .to_dataframe() :param _output_type: style of output to use :param left: the query for the left side of the table :param top: the query for the top of the table :return: """ left = kwargs.pop('left', None) top = kwargs.pop('top', None) sets = dict(classes=set(), vars=set()) left._gather(sets) if top: top._gather(sets) table = top \ and '%s, %s' % (str(left), str(top)) \ or str(left) proc_kwargs = dict( cls=' '.join(sets['classes']), var=' '.join(sets['vars']), table=table ) # permit additional valid options if passed; for now, just 'where' proc_kwargs.update(kwargs) # we can't easily use the SASProcCommons approach for submiting, # since this is merely an output / display proc for us; # but we can at least use it to check valid options in the canonical saspy way required_options = {'cls', 'var', 'table'} allowed_options = {'cls', 'var', 'table', 'where'} verifiedKwargs = sp.sasproccommons.SASProcCommons._stmt_check(self, required_options, allowed_options, proc_kwargs) if (_output_type == 'Pandas'): # for pandas, use the out= directive code = "proc tabulate data=%s.%s %s out=temptab;\n" % ( self.data.libref, self.data.table, self.data._dsopts()) else: code = "proc tabulate data=%s.%s %s;\n" % (self.data.libref, self.data.table, self.data._dsopts()) # build the code for arg, value in verifiedKwargs.items(): code += " %s %s;\n" % (arg == 'cls' and 'class' or arg, value) code += "run;" # teach_me_SAS if self.sas.nosub: print(code) return # submit the code ll = self.data._is_valid() if _output_type == 'HTML': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code) self.data.HTML = html if not self.sas.batch: self.sas.DISPLAY(self.sas.HTML(ll['LST'])) check, errorMsg = self.data._checkLogForError(ll['LOG']) if not check: raise ValueError("Internal code execution failed: " + errorMsg) else: return ll elif _output_type == 'text': if not ll: html = self.data.HTML self.data.HTML = 1 ll = self.sas._io.submit(code, 'text') self.data.HTML = html print(ll['LST']) return elif _output_type == 'Pandas': return self.to_nested_dataframe(code)
[ "def", "execute_table", "(", "self", ",", "_output_type", ",", "*", "*", "kwargs", ":", "dict", ")", "->", "'SASresults'", ":", "left", "=", "kwargs", ".", "pop", "(", "'left'", ",", "None", ")", "top", "=", "kwargs", ".", "pop", "(", "'top'", ",", ...
executes a PROC TABULATE statement You must specify an output type to use this method, of 'HTML', 'text', or 'Pandas'. There are three convenience functions for generating specific output; see: .text_table() .table() .to_dataframe() :param _output_type: style of output to use :param left: the query for the left side of the table :param top: the query for the top of the table :return:
[ "executes", "a", "PROC", "TABULATE", "statement" ]
e433f71990f249d3a6c3db323ceb11cb2d462cf9
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sastabulate.py#L243-L330
train
222,973
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Container.dumps_content
def dumps_content(self, **kwargs): r"""Represent the container as a string in LaTeX syntax. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the container """ return dumps_list(self, escape=self.escape, token=self.content_separator, **kwargs)
python
def dumps_content(self, **kwargs): r"""Represent the container as a string in LaTeX syntax. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the container """ return dumps_list(self, escape=self.escape, token=self.content_separator, **kwargs)
[ "def", "dumps_content", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "dumps_list", "(", "self", ",", "escape", "=", "self", ".", "escape", ",", "token", "=", "self", ".", "content_separator", ",", "*", "*", "kwargs", ")" ]
r"""Represent the container as a string in LaTeX syntax. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the container
[ "r", "Represent", "the", "container", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L53-L69
train
222,974
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Container._propagate_packages
def _propagate_packages(self): """Make sure packages get propagated.""" for item in self.data: if isinstance(item, LatexObject): if isinstance(item, Container): item._propagate_packages() for p in item.packages: self.packages.add(p)
python
def _propagate_packages(self): """Make sure packages get propagated.""" for item in self.data: if isinstance(item, LatexObject): if isinstance(item, Container): item._propagate_packages() for p in item.packages: self.packages.add(p)
[ "def", "_propagate_packages", "(", "self", ")", ":", "for", "item", "in", "self", ".", "data", ":", "if", "isinstance", "(", "item", ",", "LatexObject", ")", ":", "if", "isinstance", "(", "item", ",", "Container", ")", ":", "item", ".", "_propagate_packa...
Make sure packages get propagated.
[ "Make", "sure", "packages", "get", "propagated", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L71-L79
train
222,975
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Container.create
def create(self, child): """Add a LaTeX object to current container, context-manager style. Args ---- child: `~.Container` An object to be added to the current container """ prev_data = self.data self.data = child.data # This way append works appends to the child yield child # allows with ... as to be used as well self.data = prev_data self.append(child)
python
def create(self, child): """Add a LaTeX object to current container, context-manager style. Args ---- child: `~.Container` An object to be added to the current container """ prev_data = self.data self.data = child.data # This way append works appends to the child yield child # allows with ... as to be used as well self.data = prev_data self.append(child)
[ "def", "create", "(", "self", ",", "child", ")", ":", "prev_data", "=", "self", ".", "data", "self", ".", "data", "=", "child", ".", "data", "# This way append works appends to the child", "yield", "child", "# allows with ... as to be used as well", "self", ".", "...
Add a LaTeX object to current container, context-manager style. Args ---- child: `~.Container` An object to be added to the current container
[ "Add", "a", "LaTeX", "object", "to", "current", "container", "context", "-", "manager", "style", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L95-L110
train
222,976
JelteF/PyLaTeX
pylatex/base_classes/containers.py
Environment.dumps
def dumps(self): """Represent the environment as a string in LaTeX syntax. Returns ------- str A LaTeX string representing the environment. """ content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' # Something other than None needs to be used as extra arguments, that # way the options end up behind the latex_name argument. if self.arguments is None: extra_arguments = Arguments() else: extra_arguments = self.arguments begin = Command('begin', self.start_arguments, self.options, extra_arguments=extra_arguments) begin.arguments._positional_args.insert(0, self.latex_name) string += begin.dumps() + self.content_separator string += content + self.content_separator string += Command('end', self.latex_name).dumps() return string
python
def dumps(self): """Represent the environment as a string in LaTeX syntax. Returns ------- str A LaTeX string representing the environment. """ content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' # Something other than None needs to be used as extra arguments, that # way the options end up behind the latex_name argument. if self.arguments is None: extra_arguments = Arguments() else: extra_arguments = self.arguments begin = Command('begin', self.start_arguments, self.options, extra_arguments=extra_arguments) begin.arguments._positional_args.insert(0, self.latex_name) string += begin.dumps() + self.content_separator string += content + self.content_separator string += Command('end', self.latex_name).dumps() return string
[ "def", "dumps", "(", "self", ")", ":", "content", "=", "self", ".", "dumps_content", "(", ")", "if", "not", "content", ".", "strip", "(", ")", "and", "self", ".", "omit_if_empty", ":", "return", "''", "string", "=", "''", "# Something other than None needs...
Represent the environment as a string in LaTeX syntax. Returns ------- str A LaTeX string representing the environment.
[ "Represent", "the", "environment", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L157-L188
train
222,977
JelteF/PyLaTeX
pylatex/base_classes/containers.py
ContainerCommand.dumps
def dumps(self): r"""Convert the container to a string in latex syntax.""" content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' start = Command(self.latex_name, arguments=self.arguments, options=self.options) string += start.dumps() + '{ \n' if content != '': string += content + '\n}' else: string += '}' return string
python
def dumps(self): r"""Convert the container to a string in latex syntax.""" content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' start = Command(self.latex_name, arguments=self.arguments, options=self.options) string += start.dumps() + '{ \n' if content != '': string += content + '\n}' else: string += '}' return string
[ "def", "dumps", "(", "self", ")", ":", "content", "=", "self", ".", "dumps_content", "(", ")", "if", "not", "content", ".", "strip", "(", ")", "and", "self", ".", "omit_if_empty", ":", "return", "''", "string", "=", "''", "start", "=", "Command", "("...
r"""Convert the container to a string in latex syntax.
[ "r", "Convert", "the", "container", "to", "a", "string", "in", "latex", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/base_classes/containers.py#L223-L243
train
222,978
JelteF/PyLaTeX
pylatex/section.py
Section.dumps
def dumps(self): """Represent the section as a string in LaTeX syntax. Returns ------- str """ if not self.numbering: num = '*' else: num = '' string = Command(self.latex_name + num, self.title).dumps() if self.label is not None: string += '%\n' + self.label.dumps() string += '%\n' + self.dumps_content() return string
python
def dumps(self): """Represent the section as a string in LaTeX syntax. Returns ------- str """ if not self.numbering: num = '*' else: num = '' string = Command(self.latex_name + num, self.title).dumps() if self.label is not None: string += '%\n' + self.label.dumps() string += '%\n' + self.dumps_content() return string
[ "def", "dumps", "(", "self", ")", ":", "if", "not", "self", ".", "numbering", ":", "num", "=", "'*'", "else", ":", "num", "=", "''", "string", "=", "Command", "(", "self", ".", "latex_name", "+", "num", ",", "self", ".", "title", ")", ".", "dumps...
Represent the section as a string in LaTeX syntax. Returns ------- str
[ "Represent", "the", "section", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/section.py#L60-L79
train
222,979
JelteF/PyLaTeX
pylatex/table.py
_get_table_width
def _get_table_width(table_spec): """Calculate the width of a table based on its spec. Args ---- table_spec: str The LaTeX column specification for a table. Returns ------- int The width of a table which uses the specification supplied. """ # Remove things like {\bfseries} cleaner_spec = re.sub(r'{[^}]*}', '', table_spec) # Remove X[] in tabu environments so they dont interfere with column count cleaner_spec = re.sub(r'X\[(.*?(.))\]', r'\2', cleaner_spec) spec_counter = Counter(cleaner_spec) return sum(spec_counter[l] for l in COLUMN_LETTERS)
python
def _get_table_width(table_spec): """Calculate the width of a table based on its spec. Args ---- table_spec: str The LaTeX column specification for a table. Returns ------- int The width of a table which uses the specification supplied. """ # Remove things like {\bfseries} cleaner_spec = re.sub(r'{[^}]*}', '', table_spec) # Remove X[] in tabu environments so they dont interfere with column count cleaner_spec = re.sub(r'X\[(.*?(.))\]', r'\2', cleaner_spec) spec_counter = Counter(cleaner_spec) return sum(spec_counter[l] for l in COLUMN_LETTERS)
[ "def", "_get_table_width", "(", "table_spec", ")", ":", "# Remove things like {\\bfseries}", "cleaner_spec", "=", "re", ".", "sub", "(", "r'{[^}]*}'", ",", "''", ",", "table_spec", ")", "# Remove X[] in tabu environments so they dont interfere with column count", "cleaner_spe...
Calculate the width of a table based on its spec. Args ---- table_spec: str The LaTeX column specification for a table. Returns ------- int The width of a table which uses the specification supplied.
[ "Calculate", "the", "width", "of", "a", "table", "based", "on", "its", "spec", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L24-L46
train
222,980
JelteF/PyLaTeX
pylatex/table.py
Tabular.dumps
def dumps(self): r"""Turn the Latex Object into a string in Latex format.""" string = "" if self.row_height is not None: row_height = Command('renewcommand', arguments=[ NoEscape(r'\arraystretch'), self.row_height]) string += row_height.dumps() + '%\n' if self.col_space is not None: col_space = Command('setlength', arguments=[ NoEscape(r'\tabcolsep'), self.col_space]) string += col_space.dumps() + '%\n' return string + super().dumps()
python
def dumps(self): r"""Turn the Latex Object into a string in Latex format.""" string = "" if self.row_height is not None: row_height = Command('renewcommand', arguments=[ NoEscape(r'\arraystretch'), self.row_height]) string += row_height.dumps() + '%\n' if self.col_space is not None: col_space = Command('setlength', arguments=[ NoEscape(r'\tabcolsep'), self.col_space]) string += col_space.dumps() + '%\n' return string + super().dumps()
[ "def", "dumps", "(", "self", ")", ":", "string", "=", "\"\"", "if", "self", ".", "row_height", "is", "not", "None", ":", "row_height", "=", "Command", "(", "'renewcommand'", ",", "arguments", "=", "[", "NoEscape", "(", "r'\\arraystretch'", ")", ",", "sel...
r"""Turn the Latex Object into a string in Latex format.
[ "r", "Turn", "the", "Latex", "Object", "into", "a", "string", "in", "Latex", "format", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L112-L129
train
222,981
JelteF/PyLaTeX
pylatex/table.py
Tabular.dumps_content
def dumps_content(self, **kwargs): r"""Represent the content of the tabular in LaTeX syntax. This adds the top and bottomrule when using a booktabs style tabular. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the """ content = '' if self.booktabs: content += '\\toprule%\n' content += super().dumps_content(**kwargs) if self.booktabs: content += '\\bottomrule%\n' return NoEscape(content)
python
def dumps_content(self, **kwargs): r"""Represent the content of the tabular in LaTeX syntax. This adds the top and bottomrule when using a booktabs style tabular. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the """ content = '' if self.booktabs: content += '\\toprule%\n' content += super().dumps_content(**kwargs) if self.booktabs: content += '\\bottomrule%\n' return NoEscape(content)
[ "def", "dumps_content", "(", "self", ",", "*", "*", "kwargs", ")", ":", "content", "=", "''", "if", "self", ".", "booktabs", ":", "content", "+=", "'\\\\toprule%\\n'", "content", "+=", "super", "(", ")", ".", "dumps_content", "(", "*", "*", "kwargs", "...
r"""Represent the content of the tabular in LaTeX syntax. This adds the top and bottomrule when using a booktabs style tabular. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the
[ "r", "Represent", "the", "content", "of", "the", "tabular", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L131-L156
train
222,982
JelteF/PyLaTeX
pylatex/table.py
Tabular.add_hline
def add_hline(self, start=None, end=None, *, color=None, cmidruleoption=None): r"""Add a horizontal line to the table. Args ---- start: int At what cell the line should begin end: int At what cell the line should end color: str The hline color. cmidruleoption: str The option to be used for the booktabs cmidrule, i.e. the ``x`` in ``\cmidrule(x){1-3}``. """ if self.booktabs: hline = 'midrule' cline = 'cmidrule' if cmidruleoption is not None: cline += '(' + cmidruleoption + ')' else: hline = 'hline' cline = 'cline' if color is not None: if not self.color: self.packages.append(Package('xcolor', options='table')) self.color = True color_command = Command(command="arrayrulecolor", arguments=color) self.append(color_command) if start is None and end is None: self.append(Command(hline)) else: if start is None: start = 1 elif end is None: end = self.width self.append(Command(cline, dumps_list([start, NoEscape('-'), end])))
python
def add_hline(self, start=None, end=None, *, color=None, cmidruleoption=None): r"""Add a horizontal line to the table. Args ---- start: int At what cell the line should begin end: int At what cell the line should end color: str The hline color. cmidruleoption: str The option to be used for the booktabs cmidrule, i.e. the ``x`` in ``\cmidrule(x){1-3}``. """ if self.booktabs: hline = 'midrule' cline = 'cmidrule' if cmidruleoption is not None: cline += '(' + cmidruleoption + ')' else: hline = 'hline' cline = 'cline' if color is not None: if not self.color: self.packages.append(Package('xcolor', options='table')) self.color = True color_command = Command(command="arrayrulecolor", arguments=color) self.append(color_command) if start is None and end is None: self.append(Command(hline)) else: if start is None: start = 1 elif end is None: end = self.width self.append(Command(cline, dumps_list([start, NoEscape('-'), end])))
[ "def", "add_hline", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", ",", "color", "=", "None", ",", "cmidruleoption", "=", "None", ")", ":", "if", "self", ".", "booktabs", ":", "hline", "=", "'midrule'", "cline", "=", "'c...
r"""Add a horizontal line to the table. Args ---- start: int At what cell the line should begin end: int At what cell the line should end color: str The hline color. cmidruleoption: str The option to be used for the booktabs cmidrule, i.e. the ``x`` in ``\cmidrule(x){1-3}``.
[ "r", "Add", "a", "horizontal", "line", "to", "the", "table", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L158-L199
train
222,983
JelteF/PyLaTeX
pylatex/table.py
Tabular.add_row
def add_row(self, *cells, color=None, escape=None, mapper=None, strict=True): """Add a row of cells to the table. Args ---- cells: iterable, such as a `list` or `tuple` There's two ways to use this method. The first method is to pass the content of each cell as a separate argument. The second method is to pass a single argument that is an iterable that contains each contents. color: str The name of the color used to highlight the row mapper: callable or `list` A function or a list of functions that should be called on all entries of the list after converting them to a string, for instance bold strict: bool Check for correct count of cells in row or not. """ if len(cells) == 1 and _is_iterable(cells): cells = cells[0] if escape is None: escape = self.escape # Propagate packages used in cells for c in cells: if isinstance(c, LatexObject): for p in c.packages: self.packages.add(p) # Count cell contents cell_count = 0 for c in cells: if isinstance(c, MultiColumn): cell_count += c.size else: cell_count += 1 if strict and cell_count != self.width: msg = "Number of cells added to table ({}) " \ "did not match table width ({})".format(cell_count, self.width) raise TableRowSizeError(msg) if color is not None: if not self.color: self.packages.append(Package("xcolor", options='table')) self.color = True color_command = Command(command="rowcolor", arguments=color) self.append(color_command) self.append(dumps_list(cells, escape=escape, token='&', mapper=mapper) + NoEscape(r'\\'))
python
def add_row(self, *cells, color=None, escape=None, mapper=None, strict=True): """Add a row of cells to the table. Args ---- cells: iterable, such as a `list` or `tuple` There's two ways to use this method. The first method is to pass the content of each cell as a separate argument. The second method is to pass a single argument that is an iterable that contains each contents. color: str The name of the color used to highlight the row mapper: callable or `list` A function or a list of functions that should be called on all entries of the list after converting them to a string, for instance bold strict: bool Check for correct count of cells in row or not. """ if len(cells) == 1 and _is_iterable(cells): cells = cells[0] if escape is None: escape = self.escape # Propagate packages used in cells for c in cells: if isinstance(c, LatexObject): for p in c.packages: self.packages.add(p) # Count cell contents cell_count = 0 for c in cells: if isinstance(c, MultiColumn): cell_count += c.size else: cell_count += 1 if strict and cell_count != self.width: msg = "Number of cells added to table ({}) " \ "did not match table width ({})".format(cell_count, self.width) raise TableRowSizeError(msg) if color is not None: if not self.color: self.packages.append(Package("xcolor", options='table')) self.color = True color_command = Command(command="rowcolor", arguments=color) self.append(color_command) self.append(dumps_list(cells, escape=escape, token='&', mapper=mapper) + NoEscape(r'\\'))
[ "def", "add_row", "(", "self", ",", "*", "cells", ",", "color", "=", "None", ",", "escape", "=", "None", ",", "mapper", "=", "None", ",", "strict", "=", "True", ")", ":", "if", "len", "(", "cells", ")", "==", "1", "and", "_is_iterable", "(", "cel...
Add a row of cells to the table. Args ---- cells: iterable, such as a `list` or `tuple` There's two ways to use this method. The first method is to pass the content of each cell as a separate argument. The second method is to pass a single argument that is an iterable that contains each contents. color: str The name of the color used to highlight the row mapper: callable or `list` A function or a list of functions that should be called on all entries of the list after converting them to a string, for instance bold strict: bool Check for correct count of cells in row or not.
[ "Add", "a", "row", "of", "cells", "to", "the", "table", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L206-L261
train
222,984
JelteF/PyLaTeX
pylatex/table.py
MultiColumn.dumps
def dumps(self): """Represent the multicolumn as a string in LaTeX syntax. Returns ------- str """ args = [self.size, self.align, self.dumps_content()] string = Command(self.latex_name, args).dumps() return string
python
def dumps(self): """Represent the multicolumn as a string in LaTeX syntax. Returns ------- str """ args = [self.size, self.align, self.dumps_content()] string = Command(self.latex_name, args).dumps() return string
[ "def", "dumps", "(", "self", ")", ":", "args", "=", "[", "self", ".", "size", ",", "self", ".", "align", ",", "self", ".", "dumps_content", "(", ")", "]", "string", "=", "Command", "(", "self", ".", "latex_name", ",", "args", ")", ".", "dumps", "...
Represent the multicolumn as a string in LaTeX syntax. Returns ------- str
[ "Represent", "the", "multicolumn", "as", "a", "string", "in", "LaTeX", "syntax", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L311-L322
train
222,985
JelteF/PyLaTeX
pylatex/table.py
Tabu.dumps
def dumps(self): """Turn the tabu object into a string in Latex format.""" _s = super().dumps() # Tabu tables support a unusual syntax: # \begin{tabu} spread 0pt {<col format...>} # # Since this syntax isn't common, it doesn't make # sense to support it in the baseclass (e.g., Environment) # rather, here we fix the LaTeX string post-hoc if self._preamble: if _s.startswith(r"\begin{longtabu}"): _s = _s[:16] + self._preamble + _s[16:] elif _s.startswith(r"\begin{tabu}"): _s = _s[:12] + self._preamble + _s[12:] else: raise TableError("Can't apply preamble to Tabu table " "(unexpected initial command sequence)") return _s
python
def dumps(self): """Turn the tabu object into a string in Latex format.""" _s = super().dumps() # Tabu tables support a unusual syntax: # \begin{tabu} spread 0pt {<col format...>} # # Since this syntax isn't common, it doesn't make # sense to support it in the baseclass (e.g., Environment) # rather, here we fix the LaTeX string post-hoc if self._preamble: if _s.startswith(r"\begin{longtabu}"): _s = _s[:16] + self._preamble + _s[16:] elif _s.startswith(r"\begin{tabu}"): _s = _s[:12] + self._preamble + _s[12:] else: raise TableError("Can't apply preamble to Tabu table " "(unexpected initial command sequence)") return _s
[ "def", "dumps", "(", "self", ")", ":", "_s", "=", "super", "(", ")", ".", "dumps", "(", ")", "# Tabu tables support a unusual syntax:", "# \\begin{tabu} spread 0pt {<col format...>}", "#", "# Since this syntax isn't common, it doesn't make", "# sense to support it in the basecl...
Turn the tabu object into a string in Latex format.
[ "Turn", "the", "tabu", "object", "into", "a", "string", "in", "Latex", "format", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L428-L448
train
222,986
JelteF/PyLaTeX
pylatex/table.py
LongTable.end_table_header
def end_table_header(self): r"""End the table header which will appear on every page.""" if self.header: msg = "Table already has a header" raise TableError(msg) self.header = True self.append(Command(r'endhead'))
python
def end_table_header(self): r"""End the table header which will appear on every page.""" if self.header: msg = "Table already has a header" raise TableError(msg) self.header = True self.append(Command(r'endhead'))
[ "def", "end_table_header", "(", "self", ")", ":", "if", "self", ".", "header", ":", "msg", "=", "\"Table already has a header\"", "raise", "TableError", "(", "msg", ")", "self", ".", "header", "=", "True", "self", ".", "append", "(", "Command", "(", "r'end...
r"""End the table header which will appear on every page.
[ "r", "End", "the", "table", "header", "which", "will", "appear", "on", "every", "page", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L460-L469
train
222,987
JelteF/PyLaTeX
pylatex/table.py
LongTable.end_table_footer
def end_table_footer(self): r"""End the table foot which will appear on every page.""" if self.foot: msg = "Table already has a foot" raise TableError(msg) self.foot = True self.append(Command('endfoot'))
python
def end_table_footer(self): r"""End the table foot which will appear on every page.""" if self.foot: msg = "Table already has a foot" raise TableError(msg) self.foot = True self.append(Command('endfoot'))
[ "def", "end_table_footer", "(", "self", ")", ":", "if", "self", ".", "foot", ":", "msg", "=", "\"Table already has a foot\"", "raise", "TableError", "(", "msg", ")", "self", ".", "foot", "=", "True", "self", ".", "append", "(", "Command", "(", "'endfoot'",...
r"""End the table foot which will appear on every page.
[ "r", "End", "the", "table", "foot", "which", "will", "appear", "on", "every", "page", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L471-L480
train
222,988
JelteF/PyLaTeX
pylatex/table.py
LongTable.end_table_last_footer
def end_table_last_footer(self): r"""End the table foot which will appear on the last page.""" if self.lastFoot: msg = "Table already has a last foot" raise TableError(msg) self.lastFoot = True self.append(Command('endlastfoot'))
python
def end_table_last_footer(self): r"""End the table foot which will appear on the last page.""" if self.lastFoot: msg = "Table already has a last foot" raise TableError(msg) self.lastFoot = True self.append(Command('endlastfoot'))
[ "def", "end_table_last_footer", "(", "self", ")", ":", "if", "self", ".", "lastFoot", ":", "msg", "=", "\"Table already has a last foot\"", "raise", "TableError", "(", "msg", ")", "self", ".", "lastFoot", "=", "True", "self", ".", "append", "(", "Command", "...
r"""End the table foot which will appear on the last page.
[ "r", "End", "the", "table", "foot", "which", "will", "appear", "on", "the", "last", "page", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/table.py#L482-L491
train
222,989
JelteF/PyLaTeX
pylatex/utils.py
escape_latex
def escape_latex(s): r"""Escape characters that are special in latex. Args ---- s : `str`, `NoEscape` or anything that can be converted to string The string to be escaped. If this is not a string, it will be converted to a string using `str`. If it is a `NoEscape` string, it will pass through unchanged. Returns ------- NoEscape The string, with special characters in latex escaped. Examples -------- >>> escape_latex("Total cost: $30,000") 'Total cost: \$30,000' >>> escape_latex("Issue #5 occurs in 30% of all cases") 'Issue \#5 occurs in 30\% of all cases' >>> print(escape_latex("Total cost: $30,000")) References ---------- * http://tex.stackexchange.com/a/34586/43228 * http://stackoverflow.com/a/16264094/2570866 """ if isinstance(s, NoEscape): return s return NoEscape(''.join(_latex_special_chars.get(c, c) for c in str(s)))
python
def escape_latex(s): r"""Escape characters that are special in latex. Args ---- s : `str`, `NoEscape` or anything that can be converted to string The string to be escaped. If this is not a string, it will be converted to a string using `str`. If it is a `NoEscape` string, it will pass through unchanged. Returns ------- NoEscape The string, with special characters in latex escaped. Examples -------- >>> escape_latex("Total cost: $30,000") 'Total cost: \$30,000' >>> escape_latex("Issue #5 occurs in 30% of all cases") 'Issue \#5 occurs in 30\% of all cases' >>> print(escape_latex("Total cost: $30,000")) References ---------- * http://tex.stackexchange.com/a/34586/43228 * http://stackoverflow.com/a/16264094/2570866 """ if isinstance(s, NoEscape): return s return NoEscape(''.join(_latex_special_chars.get(c, c) for c in str(s)))
[ "def", "escape_latex", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "NoEscape", ")", ":", "return", "s", "return", "NoEscape", "(", "''", ".", "join", "(", "_latex_special_chars", ".", "get", "(", "c", ",", "c", ")", "for", "c", "in", "st...
r"""Escape characters that are special in latex. Args ---- s : `str`, `NoEscape` or anything that can be converted to string The string to be escaped. If this is not a string, it will be converted to a string using `str`. If it is a `NoEscape` string, it will pass through unchanged. Returns ------- NoEscape The string, with special characters in latex escaped. Examples -------- >>> escape_latex("Total cost: $30,000") 'Total cost: \$30,000' >>> escape_latex("Issue #5 occurs in 30% of all cases") 'Issue \#5 occurs in 30\% of all cases' >>> print(escape_latex("Total cost: $30,000")) References ---------- * http://tex.stackexchange.com/a/34586/43228 * http://stackoverflow.com/a/16264094/2570866
[ "r", "Escape", "characters", "that", "are", "special", "in", "latex", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L68-L100
train
222,990
JelteF/PyLaTeX
pylatex/utils.py
fix_filename
def fix_filename(path): r"""Fix filenames for use in LaTeX. Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg' Args ---- filename : str The filen name to be changed. Returns ------- str The new filename. Examples -------- >>> fix_filename("foo.bar.pdf") '{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.pdf") '/etc/local/{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.baz/document.pdf") '/etc/local/foo.bar.baz/document.pdf' >>> fix_filename("/etc/local/foo.bar.baz/foo~1/document.pdf") '\detokenize{/etc/local/foo.bar.baz/foo~1/document.pdf}' """ path_parts = path.split('/' if os.name == 'posix' else '\\') dir_parts = path_parts[:-1] filename = path_parts[-1] file_parts = filename.split('.') if len(file_parts) > 2: filename = '{' + '.'.join(file_parts[0:-1]) + '}.' + file_parts[-1] dir_parts.append(filename) fixed_path = '/'.join(dir_parts) if '~' in fixed_path: fixed_path = r'\detokenize{' + fixed_path + '}' return fixed_path
python
def fix_filename(path): r"""Fix filenames for use in LaTeX. Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg' Args ---- filename : str The filen name to be changed. Returns ------- str The new filename. Examples -------- >>> fix_filename("foo.bar.pdf") '{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.pdf") '/etc/local/{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.baz/document.pdf") '/etc/local/foo.bar.baz/document.pdf' >>> fix_filename("/etc/local/foo.bar.baz/foo~1/document.pdf") '\detokenize{/etc/local/foo.bar.baz/foo~1/document.pdf}' """ path_parts = path.split('/' if os.name == 'posix' else '\\') dir_parts = path_parts[:-1] filename = path_parts[-1] file_parts = filename.split('.') if len(file_parts) > 2: filename = '{' + '.'.join(file_parts[0:-1]) + '}.' + file_parts[-1] dir_parts.append(filename) fixed_path = '/'.join(dir_parts) if '~' in fixed_path: fixed_path = r'\detokenize{' + fixed_path + '}' return fixed_path
[ "def", "fix_filename", "(", "path", ")", ":", "path_parts", "=", "path", ".", "split", "(", "'/'", "if", "os", ".", "name", "==", "'posix'", "else", "'\\\\'", ")", "dir_parts", "=", "path_parts", "[", ":", "-", "1", "]", "filename", "=", "path_parts", ...
r"""Fix filenames for use in LaTeX. Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg' Args ---- filename : str The filen name to be changed. Returns ------- str The new filename. Examples -------- >>> fix_filename("foo.bar.pdf") '{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.pdf") '/etc/local/{foo.bar}.pdf' >>> fix_filename("/etc/local/foo.bar.baz/document.pdf") '/etc/local/foo.bar.baz/document.pdf' >>> fix_filename("/etc/local/foo.bar.baz/foo~1/document.pdf") '\detokenize{/etc/local/foo.bar.baz/foo~1/document.pdf}'
[ "r", "Fix", "filenames", "for", "use", "in", "LaTeX", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L103-L146
train
222,991
JelteF/PyLaTeX
pylatex/utils.py
dumps_list
def dumps_list(l, *, escape=True, token='%\n', mapper=None, as_content=True): r"""Try to generate a LaTeX string of a list that can contain anything. Args ---- l : list A list of objects to be converted into a single string. escape : bool Whether to escape special LaTeX characters in converted text. token : str The token (default is a newline) to separate objects in the list. mapper: callable or `list` A function, class or a list of functions/classes that should be called on all entries of the list after converting them to a string, for instance `~.bold` or `~.MediumText`. as_content: bool Indicates whether the items in the list should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape A single LaTeX string. Examples -------- >>> dumps_list([r"\textbf{Test}", r"\nth{4}"]) '\\textbf{Test}%\n\\nth{4}' >>> print(dumps_list([r"\textbf{Test}", r"\nth{4}"])) \textbf{Test} \nth{4} >>> print(pylatex.utils.dumps_list(["There are", 4, "lights!"])) There are 4 lights! >>> print(dumps_list(["$100%", "True"], escape=True)) \$100\% True """ strings = (_latex_item_to_string(i, escape=escape, as_content=as_content) for i in l) if mapper is not None: if not isinstance(mapper, list): mapper = [mapper] for m in mapper: strings = [m(s) for s in strings] strings = [_latex_item_to_string(s) for s in strings] return NoEscape(token.join(strings))
python
def dumps_list(l, *, escape=True, token='%\n', mapper=None, as_content=True): r"""Try to generate a LaTeX string of a list that can contain anything. Args ---- l : list A list of objects to be converted into a single string. escape : bool Whether to escape special LaTeX characters in converted text. token : str The token (default is a newline) to separate objects in the list. mapper: callable or `list` A function, class or a list of functions/classes that should be called on all entries of the list after converting them to a string, for instance `~.bold` or `~.MediumText`. as_content: bool Indicates whether the items in the list should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape A single LaTeX string. Examples -------- >>> dumps_list([r"\textbf{Test}", r"\nth{4}"]) '\\textbf{Test}%\n\\nth{4}' >>> print(dumps_list([r"\textbf{Test}", r"\nth{4}"])) \textbf{Test} \nth{4} >>> print(pylatex.utils.dumps_list(["There are", 4, "lights!"])) There are 4 lights! >>> print(dumps_list(["$100%", "True"], escape=True)) \$100\% True """ strings = (_latex_item_to_string(i, escape=escape, as_content=as_content) for i in l) if mapper is not None: if not isinstance(mapper, list): mapper = [mapper] for m in mapper: strings = [m(s) for s in strings] strings = [_latex_item_to_string(s) for s in strings] return NoEscape(token.join(strings))
[ "def", "dumps_list", "(", "l", ",", "*", ",", "escape", "=", "True", ",", "token", "=", "'%\\n'", ",", "mapper", "=", "None", ",", "as_content", "=", "True", ")", ":", "strings", "=", "(", "_latex_item_to_string", "(", "i", ",", "escape", "=", "escap...
r"""Try to generate a LaTeX string of a list that can contain anything. Args ---- l : list A list of objects to be converted into a single string. escape : bool Whether to escape special LaTeX characters in converted text. token : str The token (default is a newline) to separate objects in the list. mapper: callable or `list` A function, class or a list of functions/classes that should be called on all entries of the list after converting them to a string, for instance `~.bold` or `~.MediumText`. as_content: bool Indicates whether the items in the list should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape A single LaTeX string. Examples -------- >>> dumps_list([r"\textbf{Test}", r"\nth{4}"]) '\\textbf{Test}%\n\\nth{4}' >>> print(dumps_list([r"\textbf{Test}", r"\nth{4}"])) \textbf{Test} \nth{4} >>> print(pylatex.utils.dumps_list(["There are", 4, "lights!"])) There are 4 lights! >>> print(dumps_list(["$100%", "True"], escape=True)) \$100\% True
[ "r", "Try", "to", "generate", "a", "LaTeX", "string", "of", "a", "list", "that", "can", "contain", "anything", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L149-L199
train
222,992
JelteF/PyLaTeX
pylatex/utils.py
_latex_item_to_string
def _latex_item_to_string(item, *, escape=False, as_content=False): """Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape Latex """ if isinstance(item, pylatex.base_classes.LatexObject): if as_content: return item.dumps_as_content() else: return item.dumps() elif not isinstance(item, str): item = str(item) if escape: item = escape_latex(item) return item
python
def _latex_item_to_string(item, *, escape=False, as_content=False): """Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape Latex """ if isinstance(item, pylatex.base_classes.LatexObject): if as_content: return item.dumps_as_content() else: return item.dumps() elif not isinstance(item, str): item = str(item) if escape: item = escape_latex(item) return item
[ "def", "_latex_item_to_string", "(", "item", ",", "*", ",", "escape", "=", "False", ",", "as_content", "=", "False", ")", ":", "if", "isinstance", "(", "item", ",", "pylatex", ".", "base_classes", ".", "LatexObject", ")", ":", "if", "as_content", ":", "r...
Use the render method when possible, otherwise uses str. Args ---- item: object An object that needs to be converted to a string escape: bool Flag that indicates if escaping is needed as_content: bool Indicates whether the item should be dumped using `~.LatexObject.dumps_as_content` Returns ------- NoEscape Latex
[ "Use", "the", "render", "method", "when", "possible", "otherwise", "uses", "str", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L202-L232
train
222,993
JelteF/PyLaTeX
pylatex/utils.py
bold
def bold(s, *, escape=True): r"""Make a string appear bold in LaTeX formatting. bold() wraps a given string in the LaTeX command \textbf{}. Args ---- s : str The string to be formatted. escape: bool If true the bold text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> bold("hello") '\\textbf{hello}' >>> print(bold("hello")) \textbf{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textbf{' + s + '}')
python
def bold(s, *, escape=True): r"""Make a string appear bold in LaTeX formatting. bold() wraps a given string in the LaTeX command \textbf{}. Args ---- s : str The string to be formatted. escape: bool If true the bold text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> bold("hello") '\\textbf{hello}' >>> print(bold("hello")) \textbf{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textbf{' + s + '}')
[ "def", "bold", "(", "s", ",", "*", ",", "escape", "=", "True", ")", ":", "if", "escape", ":", "s", "=", "escape_latex", "(", "s", ")", "return", "NoEscape", "(", "r'\\textbf{'", "+", "s", "+", "'}'", ")" ]
r"""Make a string appear bold in LaTeX formatting. bold() wraps a given string in the LaTeX command \textbf{}. Args ---- s : str The string to be formatted. escape: bool If true the bold text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> bold("hello") '\\textbf{hello}' >>> print(bold("hello")) \textbf{hello}
[ "r", "Make", "a", "string", "appear", "bold", "in", "LaTeX", "formatting", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L235-L263
train
222,994
JelteF/PyLaTeX
pylatex/utils.py
italic
def italic(s, *, escape=True): r"""Make a string appear italicized in LaTeX formatting. italic() wraps a given string in the LaTeX command \textit{}. Args ---- s : str The string to be formatted. escape: bool If true the italic text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> italic("hello") '\\textit{hello}' >>> print(italic("hello")) \textit{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textit{' + s + '}')
python
def italic(s, *, escape=True): r"""Make a string appear italicized in LaTeX formatting. italic() wraps a given string in the LaTeX command \textit{}. Args ---- s : str The string to be formatted. escape: bool If true the italic text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> italic("hello") '\\textit{hello}' >>> print(italic("hello")) \textit{hello} """ if escape: s = escape_latex(s) return NoEscape(r'\textit{' + s + '}')
[ "def", "italic", "(", "s", ",", "*", ",", "escape", "=", "True", ")", ":", "if", "escape", ":", "s", "=", "escape_latex", "(", "s", ")", "return", "NoEscape", "(", "r'\\textit{'", "+", "s", "+", "'}'", ")" ]
r"""Make a string appear italicized in LaTeX formatting. italic() wraps a given string in the LaTeX command \textit{}. Args ---- s : str The string to be formatted. escape: bool If true the italic text will be escaped Returns ------- NoEscape The formatted string. Examples -------- >>> italic("hello") '\\textit{hello}' >>> print(italic("hello")) \textit{hello}
[ "r", "Make", "a", "string", "appear", "italicized", "in", "LaTeX", "formatting", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/utils.py#L266-L293
train
222,995
JelteF/PyLaTeX
docs/source/conf.py
auto_change_docstring
def auto_change_docstring(app, what, name, obj, options, lines): r"""Make some automatic changes to docstrings. Things this function does are: - Add a title to module docstrings - Merge lines that end with a '\' with the next line. """ if what == 'module' and name.startswith('pylatex'): lines.insert(0, len(name) * '=') lines.insert(0, name) hits = 0 for i, line in enumerate(lines.copy()): if line.endswith('\\'): lines[i - hits] += lines.pop(i + 1 - hits) hits += 1
python
def auto_change_docstring(app, what, name, obj, options, lines): r"""Make some automatic changes to docstrings. Things this function does are: - Add a title to module docstrings - Merge lines that end with a '\' with the next line. """ if what == 'module' and name.startswith('pylatex'): lines.insert(0, len(name) * '=') lines.insert(0, name) hits = 0 for i, line in enumerate(lines.copy()): if line.endswith('\\'): lines[i - hits] += lines.pop(i + 1 - hits) hits += 1
[ "def", "auto_change_docstring", "(", "app", ",", "what", ",", "name", ",", "obj", ",", "options", ",", "lines", ")", ":", "if", "what", "==", "'module'", "and", "name", ".", "startswith", "(", "'pylatex'", ")", ":", "lines", ".", "insert", "(", "0", ...
r"""Make some automatic changes to docstrings. Things this function does are: - Add a title to module docstrings - Merge lines that end with a '\' with the next line.
[ "r", "Make", "some", "automatic", "changes", "to", "docstrings", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/docs/source/conf.py#L100-L116
train
222,996
JelteF/PyLaTeX
pylatex/labelref.py
_remove_invalid_char
def _remove_invalid_char(s): """Remove invalid and dangerous characters from a string.""" s = ''.join([i if ord(i) >= 32 and ord(i) < 127 else '' for i in s]) s = s.translate(dict.fromkeys(map(ord, "_%~#\\{}\":"))) return s
python
def _remove_invalid_char(s): """Remove invalid and dangerous characters from a string.""" s = ''.join([i if ord(i) >= 32 and ord(i) < 127 else '' for i in s]) s = s.translate(dict.fromkeys(map(ord, "_%~#\\{}\":"))) return s
[ "def", "_remove_invalid_char", "(", "s", ")", ":", "s", "=", "''", ".", "join", "(", "[", "i", "if", "ord", "(", "i", ")", ">=", "32", "and", "ord", "(", "i", ")", "<", "127", "else", "''", "for", "i", "in", "s", "]", ")", "s", "=", "s", ...
Remove invalid and dangerous characters from a string.
[ "Remove", "invalid", "and", "dangerous", "characters", "from", "a", "string", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/labelref.py#L9-L14
train
222,997
JelteF/PyLaTeX
pylatex/figure.py
Figure.add_image
def add_image(self, filename, *, width=NoEscape(r'0.8\textwidth'), placement=NoEscape(r'\centering')): """Add an image to the figure. Args ---- filename: str Filename of the image. width: str The width of the image placement: str Placement of the figure, `None` is also accepted. """ if width is not None: if self.escape: width = escape_latex(width) width = 'width=' + str(width) if placement is not None: self.append(placement) self.append(StandAloneGraphic(image_options=width, filename=fix_filename(filename)))
python
def add_image(self, filename, *, width=NoEscape(r'0.8\textwidth'), placement=NoEscape(r'\centering')): """Add an image to the figure. Args ---- filename: str Filename of the image. width: str The width of the image placement: str Placement of the figure, `None` is also accepted. """ if width is not None: if self.escape: width = escape_latex(width) width = 'width=' + str(width) if placement is not None: self.append(placement) self.append(StandAloneGraphic(image_options=width, filename=fix_filename(filename)))
[ "def", "add_image", "(", "self", ",", "filename", ",", "*", ",", "width", "=", "NoEscape", "(", "r'0.8\\textwidth'", ")", ",", "placement", "=", "NoEscape", "(", "r'\\centering'", ")", ")", ":", "if", "width", "is", "not", "None", ":", "if", "self", "....
Add an image to the figure. Args ---- filename: str Filename of the image. width: str The width of the image placement: str Placement of the figure, `None` is also accepted.
[ "Add", "an", "image", "to", "the", "figure", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L20-L45
train
222,998
JelteF/PyLaTeX
pylatex/figure.py
Figure._save_plot
def _save_plot(self, *args, extension='pdf', **kwargs): """Save the plot. Returns ------- str The basename with which the plot has been saved. """ import matplotlib.pyplot as plt tmp_path = make_temp_dir() filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.')) filepath = posixpath.join(tmp_path, filename) plt.savefig(filepath, *args, **kwargs) return filepath
python
def _save_plot(self, *args, extension='pdf', **kwargs): """Save the plot. Returns ------- str The basename with which the plot has been saved. """ import matplotlib.pyplot as plt tmp_path = make_temp_dir() filename = '{}.{}'.format(str(uuid.uuid4()), extension.strip('.')) filepath = posixpath.join(tmp_path, filename) plt.savefig(filepath, *args, **kwargs) return filepath
[ "def", "_save_plot", "(", "self", ",", "*", "args", ",", "extension", "=", "'pdf'", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "tmp_path", "=", "make_temp_dir", "(", ")", "filename", "=", "'{}.{}'", ".", "for...
Save the plot. Returns ------- str The basename with which the plot has been saved.
[ "Save", "the", "plot", "." ]
62d9d9912ce8445e6629cdbcb80ad86143a1ed23
https://github.com/JelteF/PyLaTeX/blob/62d9d9912ce8445e6629cdbcb80ad86143a1ed23/pylatex/figure.py#L47-L62
train
222,999