repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
mardix/Mocha
mocha/cli.py
assets2s3
def assets2s3(): """ Upload assets files to S3 """ import flask_s3 header("Assets2S3...") print("") print("Building assets files..." ) print("") build_assets(application.app) print("") print("Uploading assets files to S3 ...") flask_s3.create_all(application.app) print("")
python
def assets2s3(): """ Upload assets files to S3 """ import flask_s3 header("Assets2S3...") print("") print("Building assets files..." ) print("") build_assets(application.app) print("") print("Uploading assets files to S3 ...") flask_s3.create_all(application.app) print("")
[ "def", "assets2s3", "(", ")", ":", "import", "flask_s3", "header", "(", "\"Assets2S3...\"", ")", "print", "(", "\"\"", ")", "print", "(", "\"Building assets files...\"", ")", "print", "(", "\"\"", ")", "build_assets", "(", "application", ".", "app", ")", "pr...
Upload assets files to S3
[ "Upload", "assets", "files", "to", "S3" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L285-L297
train
Upload assets files to S3
mardix/Mocha
mocha/cli.py
cmd
def cmd(): """ Help to run the command line :return: """ global application mochapyfile = os.path.join(os.path.join(CWD, "brew.py")) if os.path.isfile(mochapyfile): cwd_to_sys_path() application = import_string("brew") else: print("-" * 80) print("** Miss...
python
def cmd(): """ Help to run the command line :return: """ global application mochapyfile = os.path.join(os.path.join(CWD, "brew.py")) if os.path.isfile(mochapyfile): cwd_to_sys_path() application = import_string("brew") else: print("-" * 80) print("** Miss...
[ "def", "cmd", "(", ")", ":", "global", "application", "mochapyfile", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "join", "(", "CWD", ",", "\"brew.py\"", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "mochapyfile", ")"...
Help to run the command line :return:
[ "Help", "to", "run", "the", "command", "line", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/cli.py#L337-L354
train
Help to run the command line
mardix/Mocha
mocha/contrib/auth/models.py
AuthUserRole.initialize__
def initialize__(cls): """ Mocha specific To setup some models data after :return: """ [cls.new(level=r[0], name=r[1]) for r in cls.ROLES]
python
def initialize__(cls): """ Mocha specific To setup some models data after :return: """ [cls.new(level=r[0], name=r[1]) for r in cls.ROLES]
[ "def", "initialize__", "(", "cls", ")", ":", "[", "cls", ".", "new", "(", "level", "=", "r", "[", "0", "]", ",", "name", "=", "r", "[", "1", "]", ")", "for", "r", "in", "cls", ".", "ROLES", "]" ]
Mocha specific To setup some models data after :return:
[ "Mocha", "specific", "To", "setup", "some", "models", "data", "after", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L36-L42
train
Initialize the base class with some data.
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.new
def new(cls, username, password=None, email=None, first_name="", last_name="", login_method=None, role="MEMBER" ): """ Create a new user :param username: str :param password: str :para...
python
def new(cls, username, password=None, email=None, first_name="", last_name="", login_method=None, role="MEMBER" ): """ Create a new user :param username: str :param password: str :para...
[ "def", "new", "(", "cls", ",", "username", ",", "password", "=", "None", ",", "email", "=", "None", ",", "first_name", "=", "\"\"", ",", "last_name", "=", "\"\"", ",", "login_method", "=", "None", ",", "role", "=", "\"MEMBER\"", ")", ":", "data", "="...
Create a new user :param username: str :param password: str :param email: str :param first_name: str :param last_name: str :param login_method: str :param role: str :return: AuthUser
[ "Create", "a", "new", "user", ":", "param", "username", ":", "str", ":", "param", "password", ":", "str", ":", "param", "email", ":", "str", ":", "param", "first_name", ":", "str", ":", "param", "last_name", ":", "str", ":", "param", "login_method", ":...
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L99-L163
train
Create a new user in the database.
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.get_by_username
def get_by_username(cls, username): """ Return a User by email address """ return cls.query().filter(cls.username == username).first()
python
def get_by_username(cls, username): """ Return a User by email address """ return cls.query().filter(cls.username == username).first()
[ "def", "get_by_username", "(", "cls", ",", "username", ")", ":", "return", "cls", ".", "query", "(", ")", ".", "filter", "(", "cls", ".", "username", "==", "username", ")", ".", "first", "(", ")" ]
Return a User by email address
[ "Return", "a", "User", "by", "email", "address" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L166-L170
train
Return a User by username
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.get_by_email
def get_by_email(cls, email): """ Return a User by email address """ return cls.query().filter(cls.email == email).first()
python
def get_by_email(cls, email): """ Return a User by email address """ return cls.query().filter(cls.email == email).first()
[ "def", "get_by_email", "(", "cls", ",", "email", ")", ":", "return", "cls", ".", "query", "(", ")", ".", "filter", "(", "cls", ".", "email", "==", "email", ")", ".", "first", "(", ")" ]
Return a User by email address
[ "Return", "a", "User", "by", "email", "address" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L173-L177
train
Return a User by email address
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.search_by_name
def search_by_name(cls, query, name): """ Make a search :param query: :param name: :return: """ query = query.filter(db.or_(cls.first_name.contains(name), cls.last_name.contains(name))) return query
python
def search_by_name(cls, query, name): """ Make a search :param query: :param name: :return: """ query = query.filter(db.or_(cls.first_name.contains(name), cls.last_name.contains(name))) return query
[ "def", "search_by_name", "(", "cls", ",", "query", ",", "name", ")", ":", "query", "=", "query", ".", "filter", "(", "db", ".", "or_", "(", "cls", ".", "first_name", ".", "contains", "(", "name", ")", ",", "cls", ".", "last_name", ".", "contains", ...
Make a search :param query: :param name: :return:
[ "Make", "a", "search", ":", "param", "query", ":", ":", "param", "name", ":", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L180-L189
train
Make a search query by name
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.change_username
def change_username(self, username): """ Change username :param username: email or str :return: """ username = username.lower() if self.username != username: if self.get_by_username(username): raise exceptions.AuthError("Username exists...
python
def change_username(self, username): """ Change username :param username: email or str :return: """ username = username.lower() if self.username != username: if self.get_by_username(username): raise exceptions.AuthError("Username exists...
[ "def", "change_username", "(", "self", ",", "username", ")", ":", "username", "=", "username", ".", "lower", "(", ")", "if", "self", ".", "username", "!=", "username", ":", "if", "self", ".", "get_by_username", "(", "username", ")", ":", "raise", "except...
Change username :param username: email or str :return:
[ "Change", "username", ":", "param", "username", ":", "email", "or", "str", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L211-L221
train
Change username of the user.
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.change_email
def change_email(self, email, as_username=False): """ Change account email :param email: :param as_username :return: the email provided """ email = email.lower() data = {"email": email} if self.email != email: if self.get_by_email(email...
python
def change_email(self, email, as_username=False): """ Change account email :param email: :param as_username :return: the email provided """ email = email.lower() data = {"email": email} if self.email != email: if self.get_by_email(email...
[ "def", "change_email", "(", "self", ",", "email", ",", "as_username", "=", "False", ")", ":", "email", "=", "email", ".", "lower", "(", ")", "data", "=", "{", "\"email\"", ":", "email", "}", "if", "self", ".", "email", "!=", "email", ":", "if", "se...
Change account email :param email: :param as_username :return: the email provided
[ "Change", "account", "email", ":", "param", "email", ":", ":", "param", "as_username", ":", "return", ":", "the", "email", "provided" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L223-L241
train
Change the email of the user.
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.change_password
def change_password(self, password): """ Change the password. :param password: :return: """ self.update(password_hash=self.encrypt_password(password), require_password_change=False) # Whenever the password is changed, reset the secret key to i...
python
def change_password(self, password): """ Change the password. :param password: :return: """ self.update(password_hash=self.encrypt_password(password), require_password_change=False) # Whenever the password is changed, reset the secret key to i...
[ "def", "change_password", "(", "self", ",", "password", ")", ":", "self", ".", "update", "(", "password_hash", "=", "self", ".", "encrypt_password", "(", "password", ")", ",", "require_password_change", "=", "False", ")", "# Whenever the password is changed, reset t...
Change the password. :param password: :return:
[ "Change", "the", "password", ".", ":", "param", "password", ":", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L243-L254
train
Change the password of the current node.
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.set_options
def set_options(self, **kwargs): """ Set the options. Existing value will persist :param kwargs: :return: """ options = self.options options.update(kwargs) self.update(options=options)
python
def set_options(self, **kwargs): """ Set the options. Existing value will persist :param kwargs: :return: """ options = self.options options.update(kwargs) self.update(options=options)
[ "def", "set_options", "(", "self", ",", "*", "*", "kwargs", ")", ":", "options", "=", "self", ".", "options", "options", ".", "update", "(", "kwargs", ")", "self", ".", "update", "(", "options", "=", "options", ")" ]
Set the options. Existing value will persist :param kwargs: :return:
[ "Set", "the", "options", ".", "Existing", "value", "will", "persist", ":", "param", "kwargs", ":", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L275-L283
train
Set the options. Existing value will persist
mardix/Mocha
mocha/contrib/auth/models.py
AuthUser.has_any_roles
def has_any_roles(self, *roles): """ Check if user has any of the roles requested :param roles: tuple of roles string :return: bool """ roles = map(utils.slugify, list(roles)) return True \ if AuthUserRole.query() \ .join(AuthUser) \ ...
python
def has_any_roles(self, *roles): """ Check if user has any of the roles requested :param roles: tuple of roles string :return: bool """ roles = map(utils.slugify, list(roles)) return True \ if AuthUserRole.query() \ .join(AuthUser) \ ...
[ "def", "has_any_roles", "(", "self", ",", "*", "roles", ")", ":", "roles", "=", "map", "(", "utils", ".", "slugify", ",", "list", "(", "roles", ")", ")", "return", "True", "if", "AuthUserRole", ".", "query", "(", ")", ".", "join", "(", "AuthUser", ...
Check if user has any of the roles requested :param roles: tuple of roles string :return: bool
[ "Check", "if", "user", "has", "any", "of", "the", "roles", "requested", ":", "param", "roles", ":", "tuple", "of", "roles", "string", ":", "return", ":", "bool" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L291-L305
train
Check if user has any of the requested roles
mardix/Mocha
mocha/contrib/auth/models.py
AuthUserFederation.new
def new(cls, user, provider, federated_id): """ Create a new login :param user: AuthUser :param provider: str - ie: facebook, twitter, ... :param federated_id: str - an id associated to provider :return: """ if cls.get_user(provider, federated_id): ...
python
def new(cls, user, provider, federated_id): """ Create a new login :param user: AuthUser :param provider: str - ie: facebook, twitter, ... :param federated_id: str - an id associated to provider :return: """ if cls.get_user(provider, federated_id): ...
[ "def", "new", "(", "cls", ",", "user", ",", "provider", ",", "federated_id", ")", ":", "if", "cls", ".", "get_user", "(", "provider", ",", "federated_id", ")", ":", "raise", "exceptions", ".", "AuthError", "(", "\"Federation already\"", ")", "return", "cls...
Create a new login :param user: AuthUser :param provider: str - ie: facebook, twitter, ... :param federated_id: str - an id associated to provider :return:
[ "Create", "a", "new", "login", ":", "param", "user", ":", "AuthUser", ":", "param", "provider", ":", "str", "-", "ie", ":", "facebook", "twitter", "...", ":", "param", "federated_id", ":", "str", "-", "an", "id", "associated", "to", "provider", ":", "r...
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/models.py#L327-L340
train
Create a new login - related recordset.
swharden/webinspect
webinspect/webinspect.py
launch
def launch(thing,title=False): """analyze a thing, create a nice HTML document, and launch it.""" html=htmlFromThing(thing,title=title) if not html: print("no HTML was generated.") return fname="%s/%s.html"%(tempfile.gettempdir(),str(time.time())) with open(fname,'w') as f: ...
python
def launch(thing,title=False): """analyze a thing, create a nice HTML document, and launch it.""" html=htmlFromThing(thing,title=title) if not html: print("no HTML was generated.") return fname="%s/%s.html"%(tempfile.gettempdir(),str(time.time())) with open(fname,'w') as f: ...
[ "def", "launch", "(", "thing", ",", "title", "=", "False", ")", ":", "html", "=", "htmlFromThing", "(", "thing", ",", "title", "=", "title", ")", "if", "not", "html", ":", "print", "(", "\"no HTML was generated.\"", ")", "return", "fname", "=", "\"%s/%s....
analyze a thing, create a nice HTML document, and launch it.
[ "analyze", "a", "thing", "create", "a", "nice", "HTML", "document", "and", "launch", "it", "." ]
432674b61666d66e5be330b61f9fad0b46dac84e
https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L24-L33
train
analyze a thing create a nice HTML document and launch it.
swharden/webinspect
webinspect/webinspect.py
exceptionToString
def exceptionToString(e): """when you "except Exception as e", give me the e and I'll give you a string.""" exc_type, exc_obj, exc_tb = sys.exc_info() s="EXCEPTION THROWN UNEXPECTEDLY" s+=" FILE: %s\n"%os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] s+=" LINE: %s\n"%exc_tb.tb_lineno ...
python
def exceptionToString(e): """when you "except Exception as e", give me the e and I'll give you a string.""" exc_type, exc_obj, exc_tb = sys.exc_info() s="EXCEPTION THROWN UNEXPECTEDLY" s+=" FILE: %s\n"%os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] s+=" LINE: %s\n"%exc_tb.tb_lineno ...
[ "def", "exceptionToString", "(", "e", ")", ":", "exc_type", ",", "exc_obj", ",", "exc_tb", "=", "sys", ".", "exc_info", "(", ")", "s", "=", "\"EXCEPTION THROWN UNEXPECTEDLY\"", "s", "+=", "\" FILE: %s\\n\"", "%", "os", ".", "path", ".", "split", "(", "exc...
when you "except Exception as e", give me the e and I'll give you a string.
[ "when", "you", "except", "Exception", "as", "e", "give", "me", "the", "e", "and", "I", "ll", "give", "you", "a", "string", "." ]
432674b61666d66e5be330b61f9fad0b46dac84e
https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L35-L42
train
when you except Exception as e give me the e and I ll give you a string.
swharden/webinspect
webinspect/webinspect.py
analyzeThing
def analyzeThing(originalThing2): """analyze an object and all its attirbutes. Returns a dictionary.""" originalThing = copy.copy(originalThing2) things={} for name in sorted(dir(originalThing)): print("analyzing",name) thing = copy.copy(originalThing) if name in webinspec...
python
def analyzeThing(originalThing2): """analyze an object and all its attirbutes. Returns a dictionary.""" originalThing = copy.copy(originalThing2) things={} for name in sorted(dir(originalThing)): print("analyzing",name) thing = copy.copy(originalThing) if name in webinspec...
[ "def", "analyzeThing", "(", "originalThing2", ")", ":", "originalThing", "=", "copy", ".", "copy", "(", "originalThing2", ")", "things", "=", "{", "}", "for", "name", "in", "sorted", "(", "dir", "(", "originalThing", ")", ")", ":", "print", "(", "\"analy...
analyze an object and all its attirbutes. Returns a dictionary.
[ "analyze", "an", "object", "and", "all", "its", "attirbutes", ".", "Returns", "a", "dictionary", "." ]
432674b61666d66e5be330b61f9fad0b46dac84e
https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L66-L94
train
analyze an object and all its attirbutes. Returns a dictionary.
swharden/webinspect
webinspect/webinspect.py
websafe
def websafe(s): """return a string with HTML-safe text""" s=s.replace("<","&lt;").replace(">","&gt;") s=s.replace(r'\x',r' \x') s=s.replace("\n","<br>") return s
python
def websafe(s): """return a string with HTML-safe text""" s=s.replace("<","&lt;").replace(">","&gt;") s=s.replace(r'\x',r' \x') s=s.replace("\n","<br>") return s
[ "def", "websafe", "(", "s", ")", ":", "s", "=", "s", ".", "replace", "(", "\"<\"", ",", "\"&lt;\"", ")", ".", "replace", "(", "\">\"", ",", "\"&gt;\"", ")", "s", "=", "s", ".", "replace", "(", "r'\\x'", ",", "r' \\x'", ")", "s", "=", "s", ".", ...
return a string with HTML-safe text
[ "return", "a", "string", "with", "HTML", "-", "safe", "text" ]
432674b61666d66e5be330b61f9fad0b46dac84e
https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L96-L101
train
return a string with HTML - safe text
swharden/webinspect
webinspect/webinspect.py
htmlFromThing
def htmlFromThing(thing,title): """create pretty formatted HTML from a things dictionary.""" try: thing2 = copy.copy(thing) except: print("crashed copying the thing! I can't document it.") return False stuff=analyzeThing(thing2) names2=list(stuff.keys()) for i,na...
python
def htmlFromThing(thing,title): """create pretty formatted HTML from a things dictionary.""" try: thing2 = copy.copy(thing) except: print("crashed copying the thing! I can't document it.") return False stuff=analyzeThing(thing2) names2=list(stuff.keys()) for i,na...
[ "def", "htmlFromThing", "(", "thing", ",", "title", ")", ":", "try", ":", "thing2", "=", "copy", ".", "copy", "(", "thing", ")", "except", ":", "print", "(", "\"crashed copying the thing! I can't document it.\"", ")", "return", "False", "stuff", "=", "analyzeT...
create pretty formatted HTML from a things dictionary.
[ "create", "pretty", "formatted", "HTML", "from", "a", "things", "dictionary", "." ]
432674b61666d66e5be330b61f9fad0b46dac84e
https://github.com/swharden/webinspect/blob/432674b61666d66e5be330b61f9fad0b46dac84e/webinspect/webinspect.py#L103-L188
train
create pretty formatted HTML from a dictionary of things.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient.subscribe_to_data
def subscribe_to_data( self, subscriber: Callable[[bytes], bool], ) -> None: """ Not thread-safe. """ self._data_subscribers.append(subscriber)
python
def subscribe_to_data( self, subscriber: Callable[[bytes], bool], ) -> None: """ Not thread-safe. """ self._data_subscribers.append(subscriber)
[ "def", "subscribe_to_data", "(", "self", ",", "subscriber", ":", "Callable", "[", "[", "bytes", "]", ",", "bool", "]", ",", ")", "->", "None", ":", "self", ".", "_data_subscribers", ".", "append", "(", "subscriber", ")" ]
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L74-L82
train
Subscribe to the data of the current node.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient.unsubscribe_from_data
def unsubscribe_from_data( self, subscriber: Callable[[bytes], bool], ) -> None: """ Not thread-safe. """ self._data_subscribers.remove(subscriber)
python
def unsubscribe_from_data( self, subscriber: Callable[[bytes], bool], ) -> None: """ Not thread-safe. """ self._data_subscribers.remove(subscriber)
[ "def", "unsubscribe_from_data", "(", "self", ",", "subscriber", ":", "Callable", "[", "[", "bytes", "]", ",", "bool", "]", ",", ")", "->", "None", ":", "self", ".", "_data_subscribers", ".", "remove", "(", "subscriber", ")" ]
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L84-L92
train
Unsubscribe from the data.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient.subscribe_to_chat
def subscribe_to_chat( self, subscriber: Callable[[events.ChatMessageWasReceived], None], ) -> None: """ Not thread-safe. """ self._chat_subscribers.append(subscriber)
python
def subscribe_to_chat( self, subscriber: Callable[[events.ChatMessageWasReceived], None], ) -> None: """ Not thread-safe. """ self._chat_subscribers.append(subscriber)
[ "def", "subscribe_to_chat", "(", "self", ",", "subscriber", ":", "Callable", "[", "[", "events", ".", "ChatMessageWasReceived", "]", ",", "None", "]", ",", ")", "->", "None", ":", "self", ".", "_chat_subscribers", ".", "append", "(", "subscriber", ")" ]
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L94-L102
train
Subscribe to chat messages.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient.unsubscribe_from_chat
def unsubscribe_from_chat( self, subscriber: Callable[[events.ChatMessageWasReceived], None], ) -> None: """ Not thread-safe. """ self._chat_subscribers.remove(subscriber)
python
def unsubscribe_from_chat( self, subscriber: Callable[[events.ChatMessageWasReceived], None], ) -> None: """ Not thread-safe. """ self._chat_subscribers.remove(subscriber)
[ "def", "unsubscribe_from_chat", "(", "self", ",", "subscriber", ":", "Callable", "[", "[", "events", ".", "ChatMessageWasReceived", "]", ",", "None", "]", ",", ")", "->", "None", ":", "self", ".", "_chat_subscribers", ".", "remove", "(", "subscriber", ")" ]
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L104-L112
train
Unsubscribe from a chat message.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient._handle_chat_event
def _handle_chat_event(self, event: events.ChatMessageWasReceived) -> None: """ Not thread-safe. """ for subscriber in self._chat_subscribers: try: subscriber(event) except Exception: LOG.exception(self._prefix_log_message( ...
python
def _handle_chat_event(self, event: events.ChatMessageWasReceived) -> None: """ Not thread-safe. """ for subscriber in self._chat_subscribers: try: subscriber(event) except Exception: LOG.exception(self._prefix_log_message( ...
[ "def", "_handle_chat_event", "(", "self", ",", "event", ":", "events", ".", "ChatMessageWasReceived", ")", "->", "None", ":", "for", "subscriber", "in", "self", ".", "_chat_subscribers", ":", "try", ":", "subscriber", "(", "event", ")", "except", "Exception", ...
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L114-L126
train
Handle a chat event.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient.subscribe_to_human_connection_events
def subscribe_to_human_connection_events( self, subscriber: Callable[[events.HumanConnectionEvent], None], ) -> None: """ Not thread-safe. """ self._human_connection_subscribers.append(subscriber)
python
def subscribe_to_human_connection_events( self, subscriber: Callable[[events.HumanConnectionEvent], None], ) -> None: """ Not thread-safe. """ self._human_connection_subscribers.append(subscriber)
[ "def", "subscribe_to_human_connection_events", "(", "self", ",", "subscriber", ":", "Callable", "[", "[", "events", ".", "HumanConnectionEvent", "]", ",", "None", "]", ",", ")", "->", "None", ":", "self", ".", "_human_connection_subscribers", ".", "append", "(",...
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L128-L136
train
Subscribe to human - connection events.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient.unsubscribe_from_human_connection_events
def unsubscribe_from_human_connection_events( self, subscriber: Callable[[events.HumanConnectionEvent], None], ) -> None: """ Not thread-safe. """ self._human_connection_subscribers.remove(subscriber)
python
def unsubscribe_from_human_connection_events( self, subscriber: Callable[[events.HumanConnectionEvent], None], ) -> None: """ Not thread-safe. """ self._human_connection_subscribers.remove(subscriber)
[ "def", "unsubscribe_from_human_connection_events", "(", "self", ",", "subscriber", ":", "Callable", "[", "[", "events", ".", "HumanConnectionEvent", "]", ",", "None", "]", ",", ")", "->", "None", ":", "self", ".", "_human_connection_subscribers", ".", "remove", ...
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L138-L146
train
Unsubscribe from human - connection events.
IL2HorusTeam/il2fb-ds-middleware
il2fb/ds/middleware/console/client.py
ConsoleClient._handle_human_connection_event
def _handle_human_connection_event( self, event: events.HumanConnectionEvent, ) -> None: """ Not thread-safe. """ for subscriber in self._human_connection_subscribers: try: subscriber(event) except Exception: LO...
python
def _handle_human_connection_event( self, event: events.HumanConnectionEvent, ) -> None: """ Not thread-safe. """ for subscriber in self._human_connection_subscribers: try: subscriber(event) except Exception: LO...
[ "def", "_handle_human_connection_event", "(", "self", ",", "event", ":", "events", ".", "HumanConnectionEvent", ",", ")", "->", "None", ":", "for", "subscriber", "in", "self", ".", "_human_connection_subscribers", ":", "try", ":", "subscriber", "(", "event", ")"...
Not thread-safe.
[ "Not", "thread", "-", "safe", "." ]
7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf
https://github.com/IL2HorusTeam/il2fb-ds-middleware/blob/7ebde962f5774263b4b9c3dd9c7d2e5e51493dcf/il2fb/ds/middleware/console/client.py#L148-L163
train
Handle human connection events.
ronhanson/python-tbx
tbx/text.py
slugify
def slugify(text, delim='-'): """Generates an slightly worse ASCII-only slug.""" punctuation_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+') result = [] for word in punctuation_re.split(text.lower()): word = normalize_text(word) if word: result.append(word) ...
python
def slugify(text, delim='-'): """Generates an slightly worse ASCII-only slug.""" punctuation_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+') result = [] for word in punctuation_re.split(text.lower()): word = normalize_text(word) if word: result.append(word) ...
[ "def", "slugify", "(", "text", ",", "delim", "=", "'-'", ")", ":", "punctuation_re", "=", "re", ".", "compile", "(", "r'[\\t !\"#$%&\\'()*\\-/<=>?@\\[\\\\\\]^_`{|},.:]+'", ")", "result", "=", "[", "]", "for", "word", "in", "punctuation_re", ".", "split", "(", ...
Generates an slightly worse ASCII-only slug.
[ "Generates", "an", "slightly", "worse", "ASCII", "-", "only", "slug", "." ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L48-L57
train
Generates an slightly worse ASCII - only slug.
ronhanson/python-tbx
tbx/text.py
javascript_escape
def javascript_escape(s, quote_double_quotes=True): """ Escape characters for javascript strings. """ ustring_re = re.compile(u"([\u0080-\uffff])") def fix(match): return r"\u%04x" % ord(match.group(1)) if type(s) == str: s = s.decode('utf-8') elif type(s) != six.text_type:...
python
def javascript_escape(s, quote_double_quotes=True): """ Escape characters for javascript strings. """ ustring_re = re.compile(u"([\u0080-\uffff])") def fix(match): return r"\u%04x" % ord(match.group(1)) if type(s) == str: s = s.decode('utf-8') elif type(s) != six.text_type:...
[ "def", "javascript_escape", "(", "s", ",", "quote_double_quotes", "=", "True", ")", ":", "ustring_re", "=", "re", ".", "compile", "(", "u\"([\\u0080-\\uffff])\"", ")", "def", "fix", "(", "match", ")", ":", "return", "r\"\\u%04x\"", "%", "ord", "(", "match", ...
Escape characters for javascript strings.
[ "Escape", "characters", "for", "javascript", "strings", "." ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L84-L104
train
Escape characters for javascript strings.
ronhanson/python-tbx
tbx/text.py
send_mail
def send_mail(send_from, send_to, subject, text, server, mime='plain', files=None): """ Send an email with attachments. :param send_from: from email adress :param send_to: to email adress :param subject: email subject :param text: text of the email in html :param server: SMTP server :par...
python
def send_mail(send_from, send_to, subject, text, server, mime='plain', files=None): """ Send an email with attachments. :param send_from: from email adress :param send_to: to email adress :param subject: email subject :param text: text of the email in html :param server: SMTP server :par...
[ "def", "send_mail", "(", "send_from", ",", "send_to", ",", "subject", ",", "text", ",", "server", ",", "mime", "=", "'plain'", ",", "files", "=", "None", ")", ":", "if", "not", "files", ":", "files", "=", "[", "]", "assert", "type", "(", "send_to", ...
Send an email with attachments. :param send_from: from email adress :param send_to: to email adress :param subject: email subject :param text: text of the email in html :param server: SMTP server :param files: files to attach :return: None
[ "Send", "an", "email", "with", "attachments", ".", ":", "param", "send_from", ":", "from", "email", "adress", ":", "param", "send_to", ":", "to", "email", "adress", ":", "param", "subject", ":", "email", "subject", ":", "param", "text", ":", "text", "of"...
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L107-L144
train
Send an email with attachments.
ronhanson/python-tbx
tbx/text.py
hms_to_seconds
def hms_to_seconds(time_string): """ Converts string 'hh:mm:ss.ssssss' as a float """ s = time_string.split(':') hours = int(s[0]) minutes = int(s[1]) secs = float(s[2]) return hours * 3600 + minutes * 60 + secs
python
def hms_to_seconds(time_string): """ Converts string 'hh:mm:ss.ssssss' as a float """ s = time_string.split(':') hours = int(s[0]) minutes = int(s[1]) secs = float(s[2]) return hours * 3600 + minutes * 60 + secs
[ "def", "hms_to_seconds", "(", "time_string", ")", ":", "s", "=", "time_string", ".", "split", "(", "':'", ")", "hours", "=", "int", "(", "s", "[", "0", "]", ")", "minutes", "=", "int", "(", "s", "[", "1", "]", ")", "secs", "=", "float", "(", "s...
Converts string 'hh:mm:ss.ssssss' as a float
[ "Converts", "string", "hh", ":", "mm", ":", "ss", ".", "ssssss", "as", "a", "float" ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L147-L155
train
Converts string hh : mm : ss. ssssss. ssssss to seconds
ronhanson/python-tbx
tbx/text.py
seconds_to_hms_verbose
def seconds_to_hms_verbose(t): """ Converts seconds float to 'H hours 8 minutes, 30 seconds' format """ hours = int((t / 3600)) mins = int((t / 60) % 60) secs = int(t % 60) return ' '.join([ (hours + ' hour' + ('s' if hours > 1 else '')) if hours > 0 else '', (mins + ' minute...
python
def seconds_to_hms_verbose(t): """ Converts seconds float to 'H hours 8 minutes, 30 seconds' format """ hours = int((t / 3600)) mins = int((t / 60) % 60) secs = int(t % 60) return ' '.join([ (hours + ' hour' + ('s' if hours > 1 else '')) if hours > 0 else '', (mins + ' minute...
[ "def", "seconds_to_hms_verbose", "(", "t", ")", ":", "hours", "=", "int", "(", "(", "t", "/", "3600", ")", ")", "mins", "=", "int", "(", "(", "t", "/", "60", ")", "%", "60", ")", "secs", "=", "int", "(", "t", "%", "60", ")", "return", "' '", ...
Converts seconds float to 'H hours 8 minutes, 30 seconds' format
[ "Converts", "seconds", "float", "to", "H", "hours", "8", "minutes", "30", "seconds", "format" ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L158-L169
train
Converts seconds float to H hours 8 minutes 30 seconds format
ronhanson/python-tbx
tbx/text.py
seconds_to_hms
def seconds_to_hms(seconds): """ Converts seconds float to 'hh:mm:ss.ssssss' format. """ hours = int(seconds / 3600.0) minutes = int((seconds / 60.0) % 60.0) secs = float(seconds % 60.0) return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs)
python
def seconds_to_hms(seconds): """ Converts seconds float to 'hh:mm:ss.ssssss' format. """ hours = int(seconds / 3600.0) minutes = int((seconds / 60.0) % 60.0) secs = float(seconds % 60.0) return "{0:02d}:{1:02d}:{2:02.6f}".format(hours, minutes, secs)
[ "def", "seconds_to_hms", "(", "seconds", ")", ":", "hours", "=", "int", "(", "seconds", "/", "3600.0", ")", "minutes", "=", "int", "(", "(", "seconds", "/", "60.0", ")", "%", "60.0", ")", "secs", "=", "float", "(", "seconds", "%", "60.0", ")", "ret...
Converts seconds float to 'hh:mm:ss.ssssss' format.
[ "Converts", "seconds", "float", "to", "hh", ":", "mm", ":", "ss", ".", "ssssss", "format", "." ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L172-L179
train
Converts seconds float to hh : mm : ss. ssssss format.
ronhanson/python-tbx
tbx/text.py
pretty_render
def pretty_render(data, format='text', indent=0): """ Render a dict based on a format """ if format == 'json': return render_json(data) elif format == 'html': return render_html(data) elif format == 'xml': return render_xml(data) else: return dict_to_plaintext...
python
def pretty_render(data, format='text', indent=0): """ Render a dict based on a format """ if format == 'json': return render_json(data) elif format == 'html': return render_html(data) elif format == 'xml': return render_xml(data) else: return dict_to_plaintext...
[ "def", "pretty_render", "(", "data", ",", "format", "=", "'text'", ",", "indent", "=", "0", ")", ":", "if", "format", "==", "'json'", ":", "return", "render_json", "(", "data", ")", "elif", "format", "==", "'html'", ":", "return", "render_html", "(", "...
Render a dict based on a format
[ "Render", "a", "dict", "based", "on", "a", "format" ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L263-L274
train
Render a dict based on a format
ronhanson/python-tbx
tbx/text.py
dict_to_xml
def dict_to_xml(xml_dict): """ Converts a dictionary to an XML ElementTree Element """ import lxml.etree as etree root_tag = list(xml_dict.keys())[0] root = etree.Element(root_tag) _dict_to_xml_recurse(root, xml_dict[root_tag]) return root
python
def dict_to_xml(xml_dict): """ Converts a dictionary to an XML ElementTree Element """ import lxml.etree as etree root_tag = list(xml_dict.keys())[0] root = etree.Element(root_tag) _dict_to_xml_recurse(root, xml_dict[root_tag]) return root
[ "def", "dict_to_xml", "(", "xml_dict", ")", ":", "import", "lxml", ".", "etree", "as", "etree", "root_tag", "=", "list", "(", "xml_dict", ".", "keys", "(", ")", ")", "[", "0", "]", "root", "=", "etree", ".", "Element", "(", "root_tag", ")", "_dict_to...
Converts a dictionary to an XML ElementTree Element
[ "Converts", "a", "dictionary", "to", "an", "XML", "ElementTree", "Element" ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L310-L318
train
Converts a dictionary to an XML ElementTree Element
ronhanson/python-tbx
tbx/text.py
uni
def uni(text): """ Tries to force to convert to unicode a text. REALLY DIRTY HACK TO TRY TO DETECT ENCODINGS... :param text: text to convert :return: unicode text """ if type(text) == six.text_type: for encoding in ['latin_1', 'ascii', 'utf-8']: try: strte...
python
def uni(text): """ Tries to force to convert to unicode a text. REALLY DIRTY HACK TO TRY TO DETECT ENCODINGS... :param text: text to convert :return: unicode text """ if type(text) == six.text_type: for encoding in ['latin_1', 'ascii', 'utf-8']: try: strte...
[ "def", "uni", "(", "text", ")", ":", "if", "type", "(", "text", ")", "==", "six", ".", "text_type", ":", "for", "encoding", "in", "[", "'latin_1'", ",", "'ascii'", ",", "'utf-8'", "]", ":", "try", ":", "strtext", "=", "text", ".", "encode", "(", ...
Tries to force to convert to unicode a text. REALLY DIRTY HACK TO TRY TO DETECT ENCODINGS... :param text: text to convert :return: unicode text
[ "Tries", "to", "force", "to", "convert", "to", "unicode", "a", "text", ".", "REALLY", "DIRTY", "HACK", "TO", "TRY", "TO", "DETECT", "ENCODINGS", "...", ":", "param", "text", ":", "text", "to", "convert", ":", "return", ":", "unicode", "text" ]
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L477-L502
train
Converts a text to unicode.
ronhanson/python-tbx
tbx/text.py
xml_get_tag
def xml_get_tag(xml, tag, parent_tag=None, multi_line=False): """ Returns the tag data for the first instance of the named tag, or for all instances if multi is true. If a parent tag is specified, then that will be required before the tag. """ expr_str = '[<:]' + tag + '.*?>(?P<matched_text>.+?)<' ...
python
def xml_get_tag(xml, tag, parent_tag=None, multi_line=False): """ Returns the tag data for the first instance of the named tag, or for all instances if multi is true. If a parent tag is specified, then that will be required before the tag. """ expr_str = '[<:]' + tag + '.*?>(?P<matched_text>.+?)<' ...
[ "def", "xml_get_tag", "(", "xml", ",", "tag", ",", "parent_tag", "=", "None", ",", "multi_line", "=", "False", ")", ":", "expr_str", "=", "'[<:]'", "+", "tag", "+", "'.*?>(?P<matched_text>.+?)<'", "if", "parent_tag", ":", "expr_str", "=", "'[<:]'", "+", "p...
Returns the tag data for the first instance of the named tag, or for all instances if multi is true. If a parent tag is specified, then that will be required before the tag.
[ "Returns", "the", "tag", "data", "for", "the", "first", "instance", "of", "the", "named", "tag", "or", "for", "all", "instances", "if", "multi", "is", "true", ".", "If", "a", "parent", "tag", "is", "specified", "then", "that", "will", "be", "required", ...
87f72ae0cadecafbcd144f1e930181fba77f6b83
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/text.py#L505-L520
train
Returns the tag data for the first instance of the named tag or for all instances of the named tag.
haizi-zh/scrapy-qiniu
scrapy_qiniu/impl.py
QiniuPipeline._extract_key_info
def _extract_key_info(self, request): """ 从欲下载资源的request中, 获得资源上传七牛时的bucket和key """ from scrapy.utils.request import request_fingerprint key_generator = request.meta.get('qiniu_key_generator') if key_generator: tmp = key_generator(request.url) buc...
python
def _extract_key_info(self, request): """ 从欲下载资源的request中, 获得资源上传七牛时的bucket和key """ from scrapy.utils.request import request_fingerprint key_generator = request.meta.get('qiniu_key_generator') if key_generator: tmp = key_generator(request.url) buc...
[ "def", "_extract_key_info", "(", "self", ",", "request", ")", ":", "from", "scrapy", ".", "utils", ".", "request", "import", "request_fingerprint", "key_generator", "=", "request", ".", "meta", ".", "get", "(", "'qiniu_key_generator'", ")", "if", "key_generator"...
从欲下载资源的request中, 获得资源上传七牛时的bucket和key
[ "从欲下载资源的request中", "获得资源上传七牛时的bucket和key" ]
9a3dddacd2e665cb3c86308772040946c3b82415
https://github.com/haizi-zh/scrapy-qiniu/blob/9a3dddacd2e665cb3c86308772040946c3b82415/scrapy_qiniu/impl.py#L122-L137
train
Extract key info from the request.
haizi-zh/scrapy-qiniu
scrapy_qiniu/impl.py
QiniuPipeline.fetch
def fetch(self, request, spider): """download_func""" info = self._extract_key_info(request) ret = self.store.fetch_file(request.url, info['key'], info['bucket']) return Response(request.url, body=json.dumps(ret))
python
def fetch(self, request, spider): """download_func""" info = self._extract_key_info(request) ret = self.store.fetch_file(request.url, info['key'], info['bucket']) return Response(request.url, body=json.dumps(ret))
[ "def", "fetch", "(", "self", ",", "request", ",", "spider", ")", ":", "info", "=", "self", ".", "_extract_key_info", "(", "request", ")", "ret", "=", "self", ".", "store", ".", "fetch_file", "(", "request", ".", "url", ",", "info", "[", "'key'", "]",...
download_func
[ "download_func" ]
9a3dddacd2e665cb3c86308772040946c3b82415
https://github.com/haizi-zh/scrapy-qiniu/blob/9a3dddacd2e665cb3c86308772040946c3b82415/scrapy_qiniu/impl.py#L139-L144
train
download_func - Downloads a file from the store
haizi-zh/scrapy-qiniu
scrapy_qiniu/impl.py
QiniuPipeline.get_media_requests
def get_media_requests(self, item, info): """ 根据item中的信息, 构造出需要下载的静态资源的Request对象 :param item: :param info: :return: """ key_generator = item.get(self.QINIU_KEY_GENERATOR_FIELD) return [Request(x, meta={'qiniu_key_generator': key_generator}) for x in item....
python
def get_media_requests(self, item, info): """ 根据item中的信息, 构造出需要下载的静态资源的Request对象 :param item: :param info: :return: """ key_generator = item.get(self.QINIU_KEY_GENERATOR_FIELD) return [Request(x, meta={'qiniu_key_generator': key_generator}) for x in item....
[ "def", "get_media_requests", "(", "self", ",", "item", ",", "info", ")", ":", "key_generator", "=", "item", ".", "get", "(", "self", ".", "QINIU_KEY_GENERATOR_FIELD", ")", "return", "[", "Request", "(", "x", ",", "meta", "=", "{", "'qiniu_key_generator'", ...
根据item中的信息, 构造出需要下载的静态资源的Request对象 :param item: :param info: :return:
[ "根据item中的信息", "构造出需要下载的静态资源的Request对象" ]
9a3dddacd2e665cb3c86308772040946c3b82415
https://github.com/haizi-zh/scrapy-qiniu/blob/9a3dddacd2e665cb3c86308772040946c3b82415/scrapy_qiniu/impl.py#L146-L155
train
get_media_requests 根据 item中的信息 return list of Request
haizi-zh/scrapy-qiniu
scrapy_qiniu/impl.py
QiniuPipeline.file_path
def file_path(self, request, response=None, info=None): """ 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 """ return json.dumps(self._extract_key_info(request))
python
def file_path(self, request, response=None, info=None): """ 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 """ return json.dumps(self._extract_key_info(request))
[ "def", "file_path", "(", "self", ",", "request", ",", "response", "=", "None", ",", "info", "=", "None", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "_extract_key_info", "(", "request", ")", ")" ]
抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息
[ "抓取到的资源存放到七牛的时候", "应该采用什么样的key?", "返回的path是一个JSON字符串", "其中有bucket和key的信息" ]
9a3dddacd2e665cb3c86308772040946c3b82415
https://github.com/haizi-zh/scrapy-qiniu/blob/9a3dddacd2e665cb3c86308772040946c3b82415/scrapy_qiniu/impl.py#L168-L172
train
Returns the path to the file that is used to store the object.
clement-alexandre/TotemBionet
totembionet/src/resource_table/resource_table.py
ResourceTable._build_table
def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]: """ Private method which build the table which map a State to the active multiplex. """ result: Dict[State, Tuple[Multiplex, ...]] = {} for state in self.influence_graph.all_states(): result[state] = tuple(multiplex for mu...
python
def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]: """ Private method which build the table which map a State to the active multiplex. """ result: Dict[State, Tuple[Multiplex, ...]] = {} for state in self.influence_graph.all_states(): result[state] = tuple(multiplex for mu...
[ "def", "_build_table", "(", "self", ")", "->", "Dict", "[", "State", ",", "Tuple", "[", "Multiplex", ",", "...", "]", "]", ":", "result", ":", "Dict", "[", "State", ",", "Tuple", "[", "Multiplex", ",", "...", "]", "]", "=", "{", "}", "for", "stat...
Private method which build the table which map a State to the active multiplex.
[ "Private", "method", "which", "build", "the", "table", "which", "map", "a", "State", "to", "the", "active", "multiplex", "." ]
f37a2f9358c1ce49f21c4a868b904da5dcd4614f
https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/resource_table/resource_table.py#L19-L25
train
Private method which builds the table which maps a State to the active multiplex.
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
_to_base36
def _to_base36(number): """ Convert a positive integer to a base36 string. Taken from Stack Overflow and modified. """ if number < 0: raise ValueError("Cannot encode negative numbers") chars = "" while number != 0: number, i = divmod(number, 36) # 36-character alphabet ...
python
def _to_base36(number): """ Convert a positive integer to a base36 string. Taken from Stack Overflow and modified. """ if number < 0: raise ValueError("Cannot encode negative numbers") chars = "" while number != 0: number, i = divmod(number, 36) # 36-character alphabet ...
[ "def", "_to_base36", "(", "number", ")", ":", "if", "number", "<", "0", ":", "raise", "ValueError", "(", "\"Cannot encode negative numbers\"", ")", "chars", "=", "\"\"", "while", "number", "!=", "0", ":", "number", ",", "i", "=", "divmod", "(", "number", ...
Convert a positive integer to a base36 string. Taken from Stack Overflow and modified.
[ "Convert", "a", "positive", "integer", "to", "a", "base36", "string", "." ]
704d3f887cc8963769ffbb116eb7e6909deeaecd
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L20-L34
train
Convert a positive integer to a base36 string.
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
_pad
def _pad(string, size): """ 'Pad' a string with leading zeroes to fit the given size, truncating if necessary. """ strlen = len(string) if strlen == size: return string if strlen < size: return _padding[0:size-strlen] + string return string[-size:]
python
def _pad(string, size): """ 'Pad' a string with leading zeroes to fit the given size, truncating if necessary. """ strlen = len(string) if strlen == size: return string if strlen < size: return _padding[0:size-strlen] + string return string[-size:]
[ "def", "_pad", "(", "string", ",", "size", ")", ":", "strlen", "=", "len", "(", "string", ")", "if", "strlen", "==", "size", ":", "return", "string", "if", "strlen", "<", "size", ":", "return", "_padding", "[", "0", ":", "size", "-", "strlen", "]",...
'Pad' a string with leading zeroes to fit the given size, truncating if necessary.
[ "Pad", "a", "string", "with", "leading", "zeroes", "to", "fit", "the", "given", "size", "truncating", "if", "necessary", "." ]
704d3f887cc8963769ffbb116eb7e6909deeaecd
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L38-L48
train
Pad a string with leading zeroes to fit the given size truncating if necessary.
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
_random_block
def _random_block(): """ Generate a random string of `BLOCK_SIZE` length. """ # TODO: Use a better RNG than random.randint random_number = random.randint(0, DISCRETE_VALUES) random_string = _to_base36(random_number) return _pad(random_string, BLOCK_SIZE)
python
def _random_block(): """ Generate a random string of `BLOCK_SIZE` length. """ # TODO: Use a better RNG than random.randint random_number = random.randint(0, DISCRETE_VALUES) random_string = _to_base36(random_number) return _pad(random_string, BLOCK_SIZE)
[ "def", "_random_block", "(", ")", ":", "# TODO: Use a better RNG than random.randint", "random_number", "=", "random", ".", "randint", "(", "0", ",", "DISCRETE_VALUES", ")", "random_string", "=", "_to_base36", "(", "random_number", ")", "return", "_pad", "(", "rando...
Generate a random string of `BLOCK_SIZE` length.
[ "Generate", "a", "random", "string", "of", "BLOCK_SIZE", "length", "." ]
704d3f887cc8963769ffbb116eb7e6909deeaecd
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L51-L58
train
Generate a random string of BLOCK_SIZE length.
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
get_process_fingerprint
def get_process_fingerprint(): """ Extract a unique fingerprint for the current process, using a combination of the process PID and the system's hostname. """ pid = os.getpid() hostname = socket.gethostname() padded_pid = _pad(_to_base36(pid), 2) hostname_hash = sum([ord(x) for x in host...
python
def get_process_fingerprint(): """ Extract a unique fingerprint for the current process, using a combination of the process PID and the system's hostname. """ pid = os.getpid() hostname = socket.gethostname() padded_pid = _pad(_to_base36(pid), 2) hostname_hash = sum([ord(x) for x in host...
[ "def", "get_process_fingerprint", "(", ")", ":", "pid", "=", "os", ".", "getpid", "(", ")", "hostname", "=", "socket", ".", "gethostname", "(", ")", "padded_pid", "=", "_pad", "(", "_to_base36", "(", "pid", ")", ",", "2", ")", "hostname_hash", "=", "su...
Extract a unique fingerprint for the current process, using a combination of the process PID and the system's hostname.
[ "Extract", "a", "unique", "fingerprint", "for", "the", "current", "process", "using", "a", "combination", "of", "the", "process", "PID", "and", "the", "system", "s", "hostname", "." ]
704d3f887cc8963769ffbb116eb7e6909deeaecd
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L64-L74
train
Extract a unique fingerprint for the current process.
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
CuidGenerator.counter
def counter(self): """ Rolling counter that ensures same-machine and same-time cuids don't collide. """ self._counter += 1 if self._counter >= DISCRETE_VALUES: self._counter = 0 return self._counter
python
def counter(self): """ Rolling counter that ensures same-machine and same-time cuids don't collide. """ self._counter += 1 if self._counter >= DISCRETE_VALUES: self._counter = 0 return self._counter
[ "def", "counter", "(", "self", ")", ":", "self", ".", "_counter", "+=", "1", "if", "self", ".", "_counter", ">=", "DISCRETE_VALUES", ":", "self", ".", "_counter", "=", "0", "return", "self", ".", "_counter" ]
Rolling counter that ensures same-machine and same-time cuids don't collide.
[ "Rolling", "counter", "that", "ensures", "same", "-", "machine", "and", "same", "-", "time", "cuids", "don", "t", "collide", "." ]
704d3f887cc8963769ffbb116eb7e6909deeaecd
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L103-L111
train
Return a rolling counter that ensures same - machine and same - time cuids don t collide.
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
CuidGenerator.cuid
def cuid(self): """ Generate a full-length cuid as a string. """ # start with a hardcoded lowercase c identifier = "c" # add a timestamp in milliseconds since the epoch, in base 36 millis = int(time.time() * 1000) identifier += _to_base36(millis) #...
python
def cuid(self): """ Generate a full-length cuid as a string. """ # start with a hardcoded lowercase c identifier = "c" # add a timestamp in milliseconds since the epoch, in base 36 millis = int(time.time() * 1000) identifier += _to_base36(millis) #...
[ "def", "cuid", "(", "self", ")", ":", "# start with a hardcoded lowercase c", "identifier", "=", "\"c\"", "# add a timestamp in milliseconds since the epoch, in base 36", "millis", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "identifier", "+=", ...
Generate a full-length cuid as a string.
[ "Generate", "a", "full", "-", "length", "cuid", "as", "a", "string", "." ]
704d3f887cc8963769ffbb116eb7e6909deeaecd
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L113-L132
train
Generate a full - length cuid as a string.
abnerjacobsen/tinydb-jsonorm
src/tinydb_jsonorm/cuid.py
CuidGenerator.slug
def slug(self): """ Generate a short (7-character) cuid as a bytestring. While this is a convenient shorthand, this is much less likely to be unique and should not be relied on. Prefer full-size cuids where possible. """ identifier = "" # use a truncated ...
python
def slug(self): """ Generate a short (7-character) cuid as a bytestring. While this is a convenient shorthand, this is much less likely to be unique and should not be relied on. Prefer full-size cuids where possible. """ identifier = "" # use a truncated ...
[ "def", "slug", "(", "self", ")", ":", "identifier", "=", "\"\"", "# use a truncated timestamp", "millis", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "millis_string", "=", "_to_base36", "(", "millis", ")", "identifier", "+=", "millis_...
Generate a short (7-character) cuid as a bytestring. While this is a convenient shorthand, this is much less likely to be unique and should not be relied on. Prefer full-size cuids where possible.
[ "Generate", "a", "short", "(", "7", "-", "character", ")", "cuid", "as", "a", "bytestring", "." ]
704d3f887cc8963769ffbb116eb7e6909deeaecd
https://github.com/abnerjacobsen/tinydb-jsonorm/blob/704d3f887cc8963769ffbb116eb7e6909deeaecd/src/tinydb_jsonorm/cuid.py#L134-L157
train
Generate a short ( 7 - character ) cuid as a bytestring.
PBR/MQ2
MQ2/plugins/xls_plugin.py
is_excel_file
def is_excel_file(inputfile): """ Return whether the provided file is a CSV file or not. This checks if the first row of the file can be splitted by ',' and if the resulting line contains more than 4 columns (Markers, linkage group, chromosome, trait). """ try: xlrd.open_workbook(inputf...
python
def is_excel_file(inputfile): """ Return whether the provided file is a CSV file or not. This checks if the first row of the file can be splitted by ',' and if the resulting line contains more than 4 columns (Markers, linkage group, chromosome, trait). """ try: xlrd.open_workbook(inputf...
[ "def", "is_excel_file", "(", "inputfile", ")", ":", "try", ":", "xlrd", ".", "open_workbook", "(", "inputfile", ")", "except", "Exception", "as", "err", ":", "print", "(", "err", ")", "return", "False", "return", "True" ]
Return whether the provided file is a CSV file or not. This checks if the first row of the file can be splitted by ',' and if the resulting line contains more than 4 columns (Markers, linkage group, chromosome, trait).
[ "Return", "whether", "the", "provided", "file", "is", "a", "CSV", "file", "or", "not", ".", "This", "checks", "if", "the", "first", "row", "of", "the", "file", "can", "be", "splitted", "by", "and", "if", "the", "resulting", "line", "contains", "more", ...
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L51-L63
train
Return whether the provided file is a CSV file or not.
PBR/MQ2
MQ2/plugins/xls_plugin.py
read_excel_file
def read_excel_file(inputfile, sheet_name): """ Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return """ workbook = xlrd.open_workbook(inputfile) ...
python
def read_excel_file(inputfile, sheet_name): """ Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return """ workbook = xlrd.open_workbook(inputfile) ...
[ "def", "read_excel_file", "(", "inputfile", ",", "sheet_name", ")", ":", "workbook", "=", "xlrd", ".", "open_workbook", "(", "inputfile", ")", "output", "=", "[", "]", "found", "=", "False", "for", "sheet", "in", "workbook", ".", "sheets", "(", ")", ":",...
Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return
[ "Return", "a", "matrix", "containing", "all", "the", "information", "present", "in", "the", "excel", "sheet", "of", "the", "specified", "excel", "document", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L66-L87
train
Reads an Excel file and returns a matrix containing all the information present in the specified excel sheet.
PBR/MQ2
MQ2/plugins/xls_plugin.py
get_map_matrix
def get_map_matrix(inputfile, sheet_name): """ Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map. :arg sheet_name: the excel sheet containing the data on which to retrieve the genetic map. """ matr...
python
def get_map_matrix(inputfile, sheet_name): """ Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map. :arg sheet_name: the excel sheet containing the data on which to retrieve the genetic map. """ matr...
[ "def", "get_map_matrix", "(", "inputfile", ",", "sheet_name", ")", ":", "matrix", "=", "read_excel_file", "(", "inputfile", ",", "sheet_name", ")", "output", "=", "[", "[", "'Locus'", ",", "'Group'", ",", "'Position'", "]", "]", "for", "row", "in", "matrix...
Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map. :arg sheet_name: the excel sheet containing the data on which to retrieve the genetic map.
[ "Return", "the", "matrix", "representation", "of", "the", "genetic", "map", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L138-L152
train
Returns the matrix representation of the genetic map.
PBR/MQ2
MQ2/plugins/xls_plugin.py
XslPlugin.valid_file
def valid_file(cls, filename): """ Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check. """ file_ex = os.path.splitext(filename)[1].replace('.', '', 1) return file_ex in SUPPORTED_FILES and is_excel_file(filename)
python
def valid_file(cls, filename): """ Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check. """ file_ex = os.path.splitext(filename)[1].replace('.', '', 1) return file_ex in SUPPORTED_FILES and is_excel_file(filename)
[ "def", "valid_file", "(", "cls", ",", "filename", ")", ":", "file_ex", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "replace", "(", "'.'", ",", "''", ",", "1", ")", "return", "file_ex", "in", "SUPPORTED_FILES", ...
Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check.
[ "Check", "if", "the", "provided", "file", "is", "a", "valid", "file", "for", "this", "plugin", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L174-L181
train
Check if the provided file is a valid file for this plugin.
PBR/MQ2
MQ2/plugins/xls_plugin.py
XslPlugin.get_files
def get_files(cls, folder): """ Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. :arg folder: the path to the folder containing the files to check. This folder may contain sub-...
python
def get_files(cls, folder): """ Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. :arg folder: the path to the folder containing the files to check. This folder may contain sub-...
[ "def", "get_files", "(", "cls", ",", "folder", ")", ":", "filelist", "=", "[", "]", "if", "folder", "is", "None", "or", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "return", "filelist", "for", "root", ",", "dirs", ",", "files",...
Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. :arg folder: the path to the folder containing the files to check. This folder may contain sub-folders.
[ "Retrieve", "the", "list", "of", "files", "the", "plugin", "can", "work", "on", ".", "Find", "this", "list", "based", "on", "the", "files", "name", "files", "extension", "or", "even", "actually", "by", "reading", "in", "the", "file", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L184-L202
train
Retrieve the list of files that can be used in the plugin.
PBR/MQ2
MQ2/plugins/xls_plugin.py
XslPlugin.get_session_identifiers
def get_session_identifiers(cls, folder=None, inputfile=None): """ Retrieve the list of session identifiers contained in the data on the folder or the inputfile. For this plugin, it returns the list of excel sheet available. :kwarg folder: the path to the folder containing the files to ...
python
def get_session_identifiers(cls, folder=None, inputfile=None): """ Retrieve the list of session identifiers contained in the data on the folder or the inputfile. For this plugin, it returns the list of excel sheet available. :kwarg folder: the path to the folder containing the files to ...
[ "def", "get_session_identifiers", "(", "cls", ",", "folder", "=", "None", ",", "inputfile", "=", "None", ")", ":", "sessions", "=", "[", "]", "if", "inputfile", "and", "folder", ":", "raise", "MQ2Exception", "(", "'You should specify either a folder or a file'", ...
Retrieve the list of session identifiers contained in the data on the folder or the inputfile. For this plugin, it returns the list of excel sheet available. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inpu...
[ "Retrieve", "the", "list", "of", "session", "identifiers", "contained", "in", "the", "data", "on", "the", "folder", "or", "the", "inputfile", ".", "For", "this", "plugin", "it", "returns", "the", "list", "of", "excel", "sheet", "available", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L205-L240
train
Retrieve the list of session identifiers contained in the folder or the inputfile.
PBR/MQ2
MQ2/plugins/xls_plugin.py
XslPlugin.convert_inputfiles
def convert_inputfiles(cls, folder=None, inputfile=None, session=None, lod_threshold=None, qtls_file='qtls.csv', matrix_file='qtls_matrix.csv', ...
python
def convert_inputfiles(cls, folder=None, inputfile=None, session=None, lod_threshold=None, qtls_file='qtls.csv', matrix_file='qtls_matrix.csv', ...
[ "def", "convert_inputfiles", "(", "cls", ",", "folder", "=", "None", ",", "inputfile", "=", "None", ",", "session", "=", "None", ",", "lod_threshold", "=", "None", ",", "qtls_file", "=", "'qtls.csv'", ",", "matrix_file", "=", "'qtls_matrix.csv'", ",", "map_f...
Convert the input files present in the given folder or inputfile. This method creates the matrix representation of the QTLs results providing for each marker position the LOD value found for each trait as well as a representation of the genetic map used in the experiment. ...
[ "Convert", "the", "input", "files", "present", "in", "the", "given", "folder", "or", "inputfile", ".", "This", "method", "creates", "the", "matrix", "representation", "of", "the", "QTLs", "results", "providing", "for", "each", "marker", "position", "the", "LOD...
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/xls_plugin.py#L243-L334
train
This method converts the input files present in the folder or inputfile into a genetic map.
cozy/python_cozy_management
cozy_management/helpers.py
file_rights
def file_rights(filepath, mode=None, uid=None, gid=None): ''' Change file rights ''' file_handle = os.open(filepath, os.O_RDONLY) if mode: os.fchmod(file_handle, mode) if uid: if not gid: gid = 0 os.fchown(file_handle, uid, gid) os.close(file_handle)
python
def file_rights(filepath, mode=None, uid=None, gid=None): ''' Change file rights ''' file_handle = os.open(filepath, os.O_RDONLY) if mode: os.fchmod(file_handle, mode) if uid: if not gid: gid = 0 os.fchown(file_handle, uid, gid) os.close(file_handle)
[ "def", "file_rights", "(", "filepath", ",", "mode", "=", "None", ",", "uid", "=", "None", ",", "gid", "=", "None", ")", ":", "file_handle", "=", "os", ".", "open", "(", "filepath", ",", "os", ".", "O_RDONLY", ")", "if", "mode", ":", "os", ".", "f...
Change file rights
[ "Change", "file", "rights" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/helpers.py#L16-L27
train
Change file rights
DavidDoukhan/py_sonicvisualiser
py_sonicvisualiser/SVEnv.py
SVEnv.init_from_wave_file
def init_from_wave_file(wavpath): """Init a sonic visualiser environment structure based the analysis of the main audio file. The audio file have to be encoded in wave Args: wavpath(str): the full path to the wavfile """ try: samplerate, data = SW.read(...
python
def init_from_wave_file(wavpath): """Init a sonic visualiser environment structure based the analysis of the main audio file. The audio file have to be encoded in wave Args: wavpath(str): the full path to the wavfile """ try: samplerate, data = SW.read(...
[ "def", "init_from_wave_file", "(", "wavpath", ")", ":", "try", ":", "samplerate", ",", "data", "=", "SW", ".", "read", "(", "wavpath", ")", "nframes", "=", "data", ".", "shape", "[", "0", "]", "except", ":", "# scipy cannot handle 24 bit wav files", "# and w...
Init a sonic visualiser environment structure based the analysis of the main audio file. The audio file have to be encoded in wave Args: wavpath(str): the full path to the wavfile
[ "Init", "a", "sonic", "visualiser", "environment", "structure", "based", "the", "analysis", "of", "the", "main", "audio", "file", ".", "The", "audio", "file", "have", "to", "be", "encoded", "in", "wave" ]
ebe83bd7dffb0275393255dcbcc6671cf0ade4a5
https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L79-L100
train
Initialize a sonic visualiser environment structure based the analysis of the main audio file.
DavidDoukhan/py_sonicvisualiser
py_sonicvisualiser/SVEnv.py
SVEnv.add_spectrogram
def add_spectrogram(self, view=None): """ add a spectrogram layer to the environment Kwargs: view(<DOM Element: view>): environment view used to display the spectrogram, if set to None, a new view is created Returns: <DOM Element: view>: the view u...
python
def add_spectrogram(self, view=None): """ add a spectrogram layer to the environment Kwargs: view(<DOM Element: view>): environment view used to display the spectrogram, if set to None, a new view is created Returns: <DOM Element: view>: the view u...
[ "def", "add_spectrogram", "(", "self", ",", "view", "=", "None", ")", ":", "spectrolayer", "=", "self", ".", "__add_spectrogram", "(", "0", ")", "spectroruler", "=", "self", ".", "__add_time_ruler", "(", ")", "if", "view", "is", "None", ":", "view", "=",...
add a spectrogram layer to the environment Kwargs: view(<DOM Element: view>): environment view used to display the spectrogram, if set to None, a new view is created Returns: <DOM Element: view>: the view used to store the spectrogram
[ "add", "a", "spectrogram", "layer", "to", "the", "environment", "Kwargs", ":", "view", "(", "<DOM", "Element", ":", "view", ">", ")", ":", "environment", "view", "used", "to", "display", "the", "spectrogram", "if", "set", "to", "None", "a", "new", "view"...
ebe83bd7dffb0275393255dcbcc6671cf0ade4a5
https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L124-L141
train
Adds a spectrogram layer to the environment
DavidDoukhan/py_sonicvisualiser
py_sonicvisualiser/SVEnv.py
SVEnv.add_continuous_annotations
def add_continuous_annotations(self, x, y, colourName='Purple', colour='#c832ff', name='', view=None, vscale=None, presentationName=None): """ add a continous annotation layer Args: x (float iterable): temporal indices of the dataset y (float iterable): values of the dataset...
python
def add_continuous_annotations(self, x, y, colourName='Purple', colour='#c832ff', name='', view=None, vscale=None, presentationName=None): """ add a continous annotation layer Args: x (float iterable): temporal indices of the dataset y (float iterable): values of the dataset...
[ "def", "add_continuous_annotations", "(", "self", ",", "x", ",", "y", ",", "colourName", "=", "'Purple'", ",", "colour", "=", "'#c832ff'", ",", "name", "=", "''", ",", "view", "=", "None", ",", "vscale", "=", "None", ",", "presentationName", "=", "None",...
add a continous annotation layer Args: x (float iterable): temporal indices of the dataset y (float iterable): values of the dataset Kwargs: view (<DOM Element: view>): environment view used to display the spectrogram, if set to None, a new view is created Return...
[ "add", "a", "continous", "annotation", "layer" ]
ebe83bd7dffb0275393255dcbcc6671cf0ade4a5
https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L145-L212
train
Adds a continous annotation layer to the environment.
DavidDoukhan/py_sonicvisualiser
py_sonicvisualiser/SVEnv.py
SVEnv.add_interval_annotations
def add_interval_annotations(self, temp_idx, durations, labels, values=None, colourName='Purple', colour='#c832ff', name='', view=None, presentationName = None): """ add a labelled interval annotation layer Args: temp_idx (float iterable): The temporal indices of invervals d...
python
def add_interval_annotations(self, temp_idx, durations, labels, values=None, colourName='Purple', colour='#c832ff', name='', view=None, presentationName = None): """ add a labelled interval annotation layer Args: temp_idx (float iterable): The temporal indices of invervals d...
[ "def", "add_interval_annotations", "(", "self", ",", "temp_idx", ",", "durations", ",", "labels", ",", "values", "=", "None", ",", "colourName", "=", "'Purple'", ",", "colour", "=", "'#c832ff'", ",", "name", "=", "''", ",", "view", "=", "None", ",", "pre...
add a labelled interval annotation layer Args: temp_idx (float iterable): The temporal indices of invervals durations (float iterable): intervals durations labels (string iterable): interval labels values (int iterable): interval numeric values, if set to None, values ar...
[ "add", "a", "labelled", "interval", "annotation", "layer" ]
ebe83bd7dffb0275393255dcbcc6671cf0ade4a5
https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L215-L277
train
Adds an interval annotation layer to the data model.
DavidDoukhan/py_sonicvisualiser
py_sonicvisualiser/SVEnv.py
SVEnv.save
def save(self, outfname): """ Save the environment of a sv file to be used with soniv visualiser Args: outfname(str): full path to the file storing the environment """ f = BZ2File(outfname, 'w') self.doc.writexml(f, addindent=' ', newl='\n') f....
python
def save(self, outfname): """ Save the environment of a sv file to be used with soniv visualiser Args: outfname(str): full path to the file storing the environment """ f = BZ2File(outfname, 'w') self.doc.writexml(f, addindent=' ', newl='\n') f....
[ "def", "save", "(", "self", ",", "outfname", ")", ":", "f", "=", "BZ2File", "(", "outfname", ",", "'w'", ")", "self", ".", "doc", ".", "writexml", "(", "f", ",", "addindent", "=", "' '", ",", "newl", "=", "'\\n'", ")", "f", ".", "close", "(", ...
Save the environment of a sv file to be used with soniv visualiser Args: outfname(str): full path to the file storing the environment
[ "Save", "the", "environment", "of", "a", "sv", "file", "to", "be", "used", "with", "soniv", "visualiser", "Args", ":", "outfname", "(", "str", ")", ":", "full", "path", "to", "the", "file", "storing", "the", "environment" ]
ebe83bd7dffb0275393255dcbcc6671cf0ade4a5
https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L280-L289
train
Save the environment of a sv file to be used with soniv visualiser
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.set_initial
def set_initial(self, C_in, scale_in, scale_high): r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`, setting the new physics scale $\Lambda$ to `scale_high`.""" self.C_in = C_in self.scale_in = scale_in self.scale_high = scale_high
python
def set_initial(self, C_in, scale_in, scale_high): r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`, setting the new physics scale $\Lambda$ to `scale_high`.""" self.C_in = C_in self.scale_in = scale_in self.scale_high = scale_high
[ "def", "set_initial", "(", "self", ",", "C_in", ",", "scale_in", ",", "scale_high", ")", ":", "self", ".", "C_in", "=", "C_in", "self", ".", "scale_in", "=", "scale_in", "self", ".", "scale_high", "=", "scale_high" ]
r"""Set the initial values for parameters and Wilson coefficients at the scale `scale_in`, setting the new physics scale $\Lambda$ to `scale_high`.
[ "r", "Set", "the", "initial", "values", "for", "parameters", "and", "Wilson", "coefficients", "at", "the", "scale", "scale_in", "setting", "the", "new", "physics", "scale", "$", "\\", "Lambda$", "to", "scale_high", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L23-L29
train
Set the initial values for parameters and Wilson coefficients at the scale scale_in and scale_high.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.load_initial
def load_initial(self, streams): """Load the initial values for parameters and Wilson coefficients from one or several files. `streams` should be a tuple of file-like objects strings.""" d = {} for stream in streams: s = io.load(stream) if 'BLOCK' not in ...
python
def load_initial(self, streams): """Load the initial values for parameters and Wilson coefficients from one or several files. `streams` should be a tuple of file-like objects strings.""" d = {} for stream in streams: s = io.load(stream) if 'BLOCK' not in ...
[ "def", "load_initial", "(", "self", ",", "streams", ")", ":", "d", "=", "{", "}", "for", "stream", "in", "streams", ":", "s", "=", "io", ".", "load", "(", "stream", ")", "if", "'BLOCK'", "not", "in", "s", ":", "raise", "ValueError", "(", "\"No BLOC...
Load the initial values for parameters and Wilson coefficients from one or several files. `streams` should be a tuple of file-like objects strings.
[ "Load", "the", "initial", "values", "for", "parameters", "and", "Wilson", "coefficients", "from", "one", "or", "several", "files", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L31-L47
train
Load the initial values for parameters and Wilson coefficients from one or several files.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.set_initial_wcxf
def set_initial_wcxf(self, wc, scale_high=None, get_smpar=False): """Load the initial values for Wilson coefficients from a wcxf.WC instance. Parameters: - `scale_high`: since Wilson coefficients are dimensionless in smeftrunner but not in WCxf, the high scale in GeV has to b...
python
def set_initial_wcxf(self, wc, scale_high=None, get_smpar=False): """Load the initial values for Wilson coefficients from a wcxf.WC instance. Parameters: - `scale_high`: since Wilson coefficients are dimensionless in smeftrunner but not in WCxf, the high scale in GeV has to b...
[ "def", "set_initial_wcxf", "(", "self", ",", "wc", ",", "scale_high", "=", "None", ",", "get_smpar", "=", "False", ")", ":", "import", "wcxf", "if", "wc", ".", "eft", "!=", "'SMEFT'", ":", "raise", "ValueError", "(", "\"Wilson coefficients use wrong EFT.\"", ...
Load the initial values for Wilson coefficients from a wcxf.WC instance. Parameters: - `scale_high`: since Wilson coefficients are dimensionless in smeftrunner but not in WCxf, the high scale in GeV has to be provided. If this parameter is None (default), either a previousl...
[ "Load", "the", "initial", "values", "for", "Wilson", "coefficients", "from", "a", "wcxf", ".", "WC", "instance", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L49-L103
train
Load the initial values for the Wilson coefficients from a WCxf instance.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.load_wcxf
def load_wcxf(self, stream, get_smpar=True): """Load the initial values for Wilson coefficients from a file-like object or a string in WCxf format. Note that Standard Model parameters have to be provided separately and are assumed to be in the weak basis used for the Warsaw basis as ...
python
def load_wcxf(self, stream, get_smpar=True): """Load the initial values for Wilson coefficients from a file-like object or a string in WCxf format. Note that Standard Model parameters have to be provided separately and are assumed to be in the weak basis used for the Warsaw basis as ...
[ "def", "load_wcxf", "(", "self", ",", "stream", ",", "get_smpar", "=", "True", ")", ":", "import", "wcxf", "wc", "=", "wcxf", ".", "WC", ".", "load", "(", "stream", ")", "self", ".", "set_initial_wcxf", "(", "wc", ",", "get_smpar", "=", "get_smpar", ...
Load the initial values for Wilson coefficients from a file-like object or a string in WCxf format. Note that Standard Model parameters have to be provided separately and are assumed to be in the weak basis used for the Warsaw basis as defined in WCxf, i.e. in the basis where the down-t...
[ "Load", "the", "initial", "values", "for", "Wilson", "coefficients", "from", "a", "file", "-", "like", "object", "or", "a", "string", "in", "WCxf", "format", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L105-L115
train
Load the initial values for Wilson coefficients from a file - like object or a string in WCxf format.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.dump
def dump(self, C_out, scale_out=None, stream=None, fmt='lha', skip_redundant=True): """Return a string representation of the parameters and Wilson coefficients `C_out` in DSixTools output format. If `stream` is specified, export it to a file. `fmt` defaults to `lha` (the SLHA-like DSixTo...
python
def dump(self, C_out, scale_out=None, stream=None, fmt='lha', skip_redundant=True): """Return a string representation of the parameters and Wilson coefficients `C_out` in DSixTools output format. If `stream` is specified, export it to a file. `fmt` defaults to `lha` (the SLHA-like DSixTo...
[ "def", "dump", "(", "self", ",", "C_out", ",", "scale_out", "=", "None", ",", "stream", "=", "None", ",", "fmt", "=", "'lha'", ",", "skip_redundant", "=", "True", ")", ":", "C", "=", "OrderedDict", "(", ")", "if", "scale_out", "is", "not", "None", ...
Return a string representation of the parameters and Wilson coefficients `C_out` in DSixTools output format. If `stream` is specified, export it to a file. `fmt` defaults to `lha` (the SLHA-like DSixTools format), but can also be `json` or `yaml` (see the pylha documentation).
[ "Return", "a", "string", "representation", "of", "the", "parameters", "and", "Wilson", "coefficients", "C_out", "in", "DSixTools", "output", "format", ".", "If", "stream", "is", "specified", "export", "it", "to", "a", "file", ".", "fmt", "defaults", "to", "l...
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L117-L132
train
Return a string representation of the parameters and Wilson coefficients C_out in DSixTools output format.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.get_wcxf
def get_wcxf(self, C_out, scale_out): """Return the Wilson coefficients `C_out` as a wcxf.WC instance. Note that the Wilson coefficients are rotated into the Warsaw basis as defined in WCxf, i.e. to the basis where the down-type and charged lepton mass matrices are diagonal.""" ...
python
def get_wcxf(self, C_out, scale_out): """Return the Wilson coefficients `C_out` as a wcxf.WC instance. Note that the Wilson coefficients are rotated into the Warsaw basis as defined in WCxf, i.e. to the basis where the down-type and charged lepton mass matrices are diagonal.""" ...
[ "def", "get_wcxf", "(", "self", ",", "C_out", ",", "scale_out", ")", ":", "import", "wcxf", "C", "=", "self", ".", "rotate_defaultbasis", "(", "C_out", ")", "d", "=", "wcxf", ".", "translators", ".", "smeft", ".", "arrays2wcxf", "(", "C", ")", "basis",...
Return the Wilson coefficients `C_out` as a wcxf.WC instance. Note that the Wilson coefficients are rotated into the Warsaw basis as defined in WCxf, i.e. to the basis where the down-type and charged lepton mass matrices are diagonal.
[ "Return", "the", "Wilson", "coefficients", "C_out", "as", "a", "wcxf", ".", "WC", "instance", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L134-L156
train
Return the Wilson coefficients C_out as a wcxf. WC instance.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.dump_wcxf
def dump_wcxf(self, C_out, scale_out, fmt='yaml', stream=None, **kwargs): """Return a string representation of the Wilson coefficients `C_out` in WCxf format. If `stream` is specified, export it to a file. `fmt` defaults to `yaml`, but can also be `json`. Note that the Wilson coefficien...
python
def dump_wcxf(self, C_out, scale_out, fmt='yaml', stream=None, **kwargs): """Return a string representation of the Wilson coefficients `C_out` in WCxf format. If `stream` is specified, export it to a file. `fmt` defaults to `yaml`, but can also be `json`. Note that the Wilson coefficien...
[ "def", "dump_wcxf", "(", "self", ",", "C_out", ",", "scale_out", ",", "fmt", "=", "'yaml'", ",", "stream", "=", "None", ",", "*", "*", "kwargs", ")", ":", "wc", "=", "self", ".", "get_wcxf", "(", "C_out", ",", "scale_out", ")", "return", "wc", ".",...
Return a string representation of the Wilson coefficients `C_out` in WCxf format. If `stream` is specified, export it to a file. `fmt` defaults to `yaml`, but can also be `json`. Note that the Wilson coefficients are rotated into the Warsaw basis as defined in WCxf, i.e. to the basis wh...
[ "Return", "a", "string", "representation", "of", "the", "Wilson", "coefficients", "C_out", "in", "WCxf", "format", ".", "If", "stream", "is", "specified", "export", "it", "to", "a", "file", ".", "fmt", "defaults", "to", "yaml", "but", "can", "also", "be", ...
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L158-L167
train
Dump the Wilson coefficients C_out into a string representation of the Wilson coefficients in WCxf format.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.rgevolve
def rgevolve(self, scale_out, **kwargs): """Solve the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients at `scale_out`. Additional keyword arguments will be passed to the ODE solver `scipy.integrate.odeint`.""" self._ch...
python
def rgevolve(self, scale_out, **kwargs): """Solve the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients at `scale_out`. Additional keyword arguments will be passed to the ODE solver `scipy.integrate.odeint`.""" self._ch...
[ "def", "rgevolve", "(", "self", ",", "scale_out", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_initial", "(", ")", "return", "rge", ".", "smeft_evolve", "(", "C_in", "=", "self", ".", "C_in", ",", "scale_high", "=", "self", ".", "scale_high"...
Solve the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients at `scale_out`. Additional keyword arguments will be passed to the ODE solver `scipy.integrate.odeint`.
[ "Solve", "the", "SMEFT", "RGEs", "from", "the", "initial", "scale", "to", "scale_out", ".", "Returns", "a", "dictionary", "with", "parameters", "and", "Wilson", "coefficients", "at", "scale_out", ".", "Additional", "keyword", "arguments", "will", "be", "passed",...
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L169-L179
train
Solve the SMEFT RGEs from the initial scale to scale_out.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT.rgevolve_leadinglog
def rgevolve_leadinglog(self, scale_out): """Compute the leading logarithmix approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`. """ ...
python
def rgevolve_leadinglog(self, scale_out): """Compute the leading logarithmix approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`. """ ...
[ "def", "rgevolve_leadinglog", "(", "self", ",", "scale_out", ")", ":", "self", ".", "_check_initial", "(", ")", "return", "rge", ".", "smeft_evolve_leadinglog", "(", "C_in", "=", "self", ".", "C_in", ",", "scale_high", "=", "self", ".", "scale_high", ",", ...
Compute the leading logarithmix approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`.
[ "Compute", "the", "leading", "logarithmix", "approximation", "to", "the", "solution", "of", "the", "SMEFT", "RGEs", "from", "the", "initial", "scale", "to", "scale_out", ".", "Returns", "a", "dictionary", "with", "parameters", "and", "Wilson", "coefficients", "....
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L181-L191
train
Compute the leading logarithmix approximation to the solution of the SMEFT RGEs from the initial scale to scale_out.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT._check_initial
def _check_initial(self): """Check if initial values and scale as well as the new physics scale have been set.""" if self.C_in is None: raise Exception("You have to specify the initial conditions first.") if self.scale_in is None: raise Exception("You have to spec...
python
def _check_initial(self): """Check if initial values and scale as well as the new physics scale have been set.""" if self.C_in is None: raise Exception("You have to specify the initial conditions first.") if self.scale_in is None: raise Exception("You have to spec...
[ "def", "_check_initial", "(", "self", ")", ":", "if", "self", ".", "C_in", "is", "None", ":", "raise", "Exception", "(", "\"You have to specify the initial conditions first.\"", ")", "if", "self", ".", "scale_in", "is", "None", ":", "raise", "Exception", "(", ...
Check if initial values and scale as well as the new physics scale have been set.
[ "Check", "if", "initial", "values", "and", "scale", "as", "well", "as", "the", "new", "physics", "scale", "have", "been", "set", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L193-L201
train
Check if initial values and scale as well as the new physics scale have been set.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT._run_sm_scale_in
def _run_sm_scale_in(self, C_out, scale_sm=91.1876): """Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.""" # initialize an empty SMEFT instance smeft_sm = SMEFT() C_in_sm = beta.C_...
python
def _run_sm_scale_in(self, C_out, scale_sm=91.1876): """Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.""" # initialize an empty SMEFT instance smeft_sm = SMEFT() C_in_sm = beta.C_...
[ "def", "_run_sm_scale_in", "(", "self", ",", "C_out", ",", "scale_sm", "=", "91.1876", ")", ":", "# initialize an empty SMEFT instance", "smeft_sm", "=", "SMEFT", "(", ")", "C_in_sm", "=", "beta", ".", "C_array2dict", "(", "np", ".", "zeros", "(", "9999", ")...
Get the SM parameters at the EW scale, using an estimate `C_out` of the Wilson coefficients at that scale, and run them to the input scale.
[ "Get", "the", "SM", "parameters", "at", "the", "EW", "scale", "using", "an", "estimate", "C_out", "of", "the", "Wilson", "coefficients", "at", "that", "scale", "and", "run", "them", "to", "the", "input", "scale", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L222-L238
train
Get the SM parameters at the EW scale using an estimate C_out and run them to the input scale.
DsixTools/python-smeftrunner
smeftrunner/classes.py
SMEFT._get_sm_scale_in
def _get_sm_scale_in(self, scale_sm=91.1876): """Get an estimate of the SM parameters at the input scale by running them from the EW scale using constant values for the Wilson coefficients (corresponding to their leading log approximated values at the EW scale). Note that this i...
python
def _get_sm_scale_in(self, scale_sm=91.1876): """Get an estimate of the SM parameters at the input scale by running them from the EW scale using constant values for the Wilson coefficients (corresponding to their leading log approximated values at the EW scale). Note that this i...
[ "def", "_get_sm_scale_in", "(", "self", ",", "scale_sm", "=", "91.1876", ")", ":", "# intialize a copy of ourselves", "_smeft", "=", "SMEFT", "(", ")", "_smeft", ".", "set_initial", "(", "self", ".", "C_in", ",", "self", ".", "scale_in", ",", "self", ".", ...
Get an estimate of the SM parameters at the input scale by running them from the EW scale using constant values for the Wilson coefficients (corresponding to their leading log approximated values at the EW scale). Note that this is not guaranteed to work and will fail if some of the ...
[ "Get", "an", "estimate", "of", "the", "SM", "parameters", "at", "the", "input", "scale", "by", "running", "them", "from", "the", "EW", "scale", "using", "constant", "values", "for", "the", "Wilson", "coefficients", "(", "corresponding", "to", "their", "leadi...
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/classes.py#L240-L257
train
Run the SM down in LL approximation at the input scale.
TheGhouls/oct
oct/results/models.py
set_database
def set_database(db_url, proxy, config): """Initialize the peewee database with the given configuration If the given db_url is a regular file, it will be used as sqlite database :param str db_url: the connection string for database or path if sqlite file :param peewee.Proxy proxy: the peewee proxy to ...
python
def set_database(db_url, proxy, config): """Initialize the peewee database with the given configuration If the given db_url is a regular file, it will be used as sqlite database :param str db_url: the connection string for database or path if sqlite file :param peewee.Proxy proxy: the peewee proxy to ...
[ "def", "set_database", "(", "db_url", ",", "proxy", ",", "config", ")", ":", "db_config", "=", "config", ".", "get", "(", "'results_database'", ",", "{", "}", ")", ".", "get", "(", "'params'", ",", "{", "}", ")", "if", "'testing'", "in", "config", "a...
Initialize the peewee database with the given configuration If the given db_url is a regular file, it will be used as sqlite database :param str db_url: the connection string for database or path if sqlite file :param peewee.Proxy proxy: the peewee proxy to initialise :param dict config: the configura...
[ "Initialize", "the", "peewee", "database", "with", "the", "given", "configuration" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/models.py#L65-L83
train
Initialize the peewee database with the given configuration
Kortemme-Lab/klab
klab/cluster/simple_qtop.py
sh
def sh(cmd): """ Run the given command in a shell. The command should be a single string containing a shell command. If the command contains the names of any local variables enclosed in braces, the actual values of the named variables will be filled in. (Note that this works on variables defi...
python
def sh(cmd): """ Run the given command in a shell. The command should be a single string containing a shell command. If the command contains the names of any local variables enclosed in braces, the actual values of the named variables will be filled in. (Note that this works on variables defi...
[ "def", "sh", "(", "cmd", ")", ":", "# Figure out what local variables are defined in the calling scope.", "import", "inspect", "frame", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "locals", "=", "frame", ".", "f_back", ".", "f_locals", "finally", ":...
Run the given command in a shell. The command should be a single string containing a shell command. If the command contains the names of any local variables enclosed in braces, the actual values of the named variables will be filled in. (Note that this works on variables defined in the calling scope,...
[ "Run", "the", "given", "command", "in", "a", "shell", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cluster/simple_qtop.py#L24-L54
train
Run a given command in a shell.
uw-it-aca/uw-restclients-sws
uw_sws/curriculum.py
get_curricula_by_department
def get_curricula_by_department( department, future_terms=0, view_unpublished=False): """ Returns a list of restclients.Curriculum models, for the passed Department model. """ if not isinstance(future_terms, int): raise ValueError(future_terms) if future_terms < 0 or future_term...
python
def get_curricula_by_department( department, future_terms=0, view_unpublished=False): """ Returns a list of restclients.Curriculum models, for the passed Department model. """ if not isinstance(future_terms, int): raise ValueError(future_terms) if future_terms < 0 or future_term...
[ "def", "get_curricula_by_department", "(", "department", ",", "future_terms", "=", "0", ",", "view_unpublished", "=", "False", ")", ":", "if", "not", "isinstance", "(", "future_terms", ",", "int", ")", ":", "raise", "ValueError", "(", "future_terms", ")", "if"...
Returns a list of restclients.Curriculum models, for the passed Department model.
[ "Returns", "a", "list", "of", "restclients", ".", "Curriculum", "models", "for", "the", "passed", "Department", "model", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/curriculum.py#L14-L33
train
Returns a list of restclients. Curriculum models for the passed crawler. Department is a string representing the label of the crawler.
uw-it-aca/uw-restclients-sws
uw_sws/curriculum.py
get_curricula_by_term
def get_curricula_by_term(term, view_unpublished=False): """ Returns a list of restclients.Curriculum models, for the passed Term model. """ view_unpublished = "true" if view_unpublished else "false" url = "{}?{}".format( curriculum_search_url_prefix, urlencode([ ...
python
def get_curricula_by_term(term, view_unpublished=False): """ Returns a list of restclients.Curriculum models, for the passed Term model. """ view_unpublished = "true" if view_unpublished else "false" url = "{}?{}".format( curriculum_search_url_prefix, urlencode([ ...
[ "def", "get_curricula_by_term", "(", "term", ",", "view_unpublished", "=", "False", ")", ":", "view_unpublished", "=", "\"true\"", "if", "view_unpublished", "else", "\"false\"", "url", "=", "\"{}?{}\"", ".", "format", "(", "curriculum_search_url_prefix", ",", "urlen...
Returns a list of restclients.Curriculum models, for the passed Term model.
[ "Returns", "a", "list", "of", "restclients", ".", "Curriculum", "models", "for", "the", "passed", "Term", "model", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/curriculum.py#L36-L48
train
Returns a list of restclients. Curriculum models for the passed Term model.
AtmaHou/atma
bleu.py
BP
def BP(candidate, references): """ calculate brevity penalty """ c = len(candidate) ref_lens = (len(reference) for reference in references) r = min(ref_lens, key=lambda ref_len: (abs(ref_len - c), ref_len)) if c > r: return 1 else: return math.exp(1 - r / c)
python
def BP(candidate, references): """ calculate brevity penalty """ c = len(candidate) ref_lens = (len(reference) for reference in references) r = min(ref_lens, key=lambda ref_len: (abs(ref_len - c), ref_len)) if c > r: return 1 else: return math.exp(1 - r / c)
[ "def", "BP", "(", "candidate", ",", "references", ")", ":", "c", "=", "len", "(", "candidate", ")", "ref_lens", "=", "(", "len", "(", "reference", ")", "for", "reference", "in", "references", ")", "r", "=", "min", "(", "ref_lens", ",", "key", "=", ...
calculate brevity penalty
[ "calculate", "brevity", "penalty" ]
41cd8ea9443a9c3b2dd71432f46f44a0f83093c7
https://github.com/AtmaHou/atma/blob/41cd8ea9443a9c3b2dd71432f46f44a0f83093c7/bleu.py#L10-L21
train
calculate brevity penalty
AtmaHou/atma
bleu.py
MP
def MP(candidate, references, n): """ calculate modified precision """ counts = Counter(ngrams(candidate, n)) if not counts: return 0 max_counts = {} for reference in references: reference_counts = Counter(ngrams(reference, n)) for ngram in counts: max_co...
python
def MP(candidate, references, n): """ calculate modified precision """ counts = Counter(ngrams(candidate, n)) if not counts: return 0 max_counts = {} for reference in references: reference_counts = Counter(ngrams(reference, n)) for ngram in counts: max_co...
[ "def", "MP", "(", "candidate", ",", "references", ",", "n", ")", ":", "counts", "=", "Counter", "(", "ngrams", "(", "candidate", ",", "n", ")", ")", "if", "not", "counts", ":", "return", "0", "max_counts", "=", "{", "}", "for", "reference", "in", "...
calculate modified precision
[ "calculate", "modified", "precision" ]
41cd8ea9443a9c3b2dd71432f46f44a0f83093c7
https://github.com/AtmaHou/atma/blob/41cd8ea9443a9c3b2dd71432f46f44a0f83093c7/bleu.py#L24-L40
train
calculate modified precision
AtmaHou/atma
bleu.py
bleu
def bleu(candidate, references, weights): """ Calculate BLEU for a single sentence, comment by atma The result of this code is same as the most popular perl script eg: weight = [0.25, 0.25, 0.25, 0.25] can = 'It is a guide to action which ensures that the military always obeys the comman...
python
def bleu(candidate, references, weights): """ Calculate BLEU for a single sentence, comment by atma The result of this code is same as the most popular perl script eg: weight = [0.25, 0.25, 0.25, 0.25] can = 'It is a guide to action which ensures that the military always obeys the comman...
[ "def", "bleu", "(", "candidate", ",", "references", ",", "weights", ")", ":", "p_ns", "=", "(", "MP", "(", "candidate", ",", "references", ",", "i", ")", "for", "i", ",", "_", "in", "enumerate", "(", "weights", ",", "start", "=", "1", ")", ")", "...
Calculate BLEU for a single sentence, comment by atma The result of this code is same as the most popular perl script eg: weight = [0.25, 0.25, 0.25, 0.25] can = 'It is a guide to action which ensures that the military always obeys the commands of the party'.lower().split() ref1 = 'It is...
[ "Calculate", "BLEU", "for", "a", "single", "sentence", "comment", "by", "atma", "The", "result", "of", "this", "code", "is", "same", "as", "the", "most", "popular", "perl", "script", "eg", ":", "weight", "=", "[", "0", ".", "25", "0", ".", "25", "0",...
41cd8ea9443a9c3b2dd71432f46f44a0f83093c7
https://github.com/AtmaHou/atma/blob/41cd8ea9443a9c3b2dd71432f46f44a0f83093c7/bleu.py#L43-L69
train
Calculate BLEU for a single sentence comment by atma
trendels/rhino
rhino/mapper.py
template2regex
def template2regex(template, ranges=None): """Convert a URL template to a regular expression. Converts a template, such as /{name}/ to a regular expression, e.g. /(?P<name>[^/]+)/ and a list of the named parameters found in the template (e.g. ['name']). Ranges are given after a colon in a template name...
python
def template2regex(template, ranges=None): """Convert a URL template to a regular expression. Converts a template, such as /{name}/ to a regular expression, e.g. /(?P<name>[^/]+)/ and a list of the named parameters found in the template (e.g. ['name']). Ranges are given after a colon in a template name...
[ "def", "template2regex", "(", "template", ",", "ranges", "=", "None", ")", ":", "if", "len", "(", "template", ")", "and", "-", "1", "<", "template", ".", "find", "(", "'|'", ")", "<", "len", "(", "template", ")", "-", "1", ":", "raise", "InvalidTem...
Convert a URL template to a regular expression. Converts a template, such as /{name}/ to a regular expression, e.g. /(?P<name>[^/]+)/ and a list of the named parameters found in the template (e.g. ['name']). Ranges are given after a colon in a template name to indicate a restriction on the characters t...
[ "Convert", "a", "URL", "template", "to", "a", "regular", "expression", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L119-L199
train
Convert a URL template to a regular expression.
trendels/rhino
rhino/mapper.py
template2path
def template2path(template, params, ranges=None): """Converts a template and a dict of parameters to a path fragment. Converts a template, such as /{name}/ and a dictionary of parameter values to a URL path (string). Parameter values that are used for buildig the path are converted to strings usin...
python
def template2path(template, params, ranges=None): """Converts a template and a dict of parameters to a path fragment. Converts a template, such as /{name}/ and a dictionary of parameter values to a URL path (string). Parameter values that are used for buildig the path are converted to strings usin...
[ "def", "template2path", "(", "template", ",", "params", ",", "ranges", "=", "None", ")", ":", "if", "len", "(", "template", ")", "and", "-", "1", "<", "template", ".", "find", "(", "'|'", ")", "<", "len", "(", "template", ")", "-", "1", ":", "rai...
Converts a template and a dict of parameters to a path fragment. Converts a template, such as /{name}/ and a dictionary of parameter values to a URL path (string). Parameter values that are used for buildig the path are converted to strings using `str()` and URI-escaped, then validated against the the...
[ "Converts", "a", "template", "and", "a", "dict", "of", "parameters", "to", "a", "path", "fragment", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L202-L319
train
Converts a template and a dictionary of parameters to a URL path fragment.
trendels/rhino
rhino/mapper.py
Context.add_callback
def add_callback(self, phase, fn): """Adds a callback to the context. The `phase` determines when and if the callback is executed, and which positional arguments are passed in: 'enter' : Called from `rhino.Resource`, after a handler for the current request has bee...
python
def add_callback(self, phase, fn): """Adds a callback to the context. The `phase` determines when and if the callback is executed, and which positional arguments are passed in: 'enter' : Called from `rhino.Resource`, after a handler for the current request has bee...
[ "def", "add_callback", "(", "self", ",", "phase", ",", "fn", ")", ":", "try", ":", "self", ".", "__callbacks", "[", "phase", "]", ".", "append", "(", "fn", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "\"Invalid callback phase '%s'. Must be one ...
Adds a callback to the context. The `phase` determines when and if the callback is executed, and which positional arguments are passed in: 'enter' : Called from `rhino.Resource`, after a handler for the current request has been resolved, but before the handler is called. ...
[ "Adds", "a", "callback", "to", "the", "context", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L336-L390
train
Adds a callback to the context.
trendels/rhino
rhino/mapper.py
Context.add_property
def add_property(self, name, fn, cached=True): """Adds a property to the Context. See `Mapper.add_ctx_property`, which uses this method to install the properties added on the Mapper level. """ if name in self.__properties: raise KeyError("Trying to add a property '%s...
python
def add_property(self, name, fn, cached=True): """Adds a property to the Context. See `Mapper.add_ctx_property`, which uses this method to install the properties added on the Mapper level. """ if name in self.__properties: raise KeyError("Trying to add a property '%s...
[ "def", "add_property", "(", "self", ",", "name", ",", "fn", ",", "cached", "=", "True", ")", ":", "if", "name", "in", "self", ".", "__properties", ":", "raise", "KeyError", "(", "\"Trying to add a property '%s' that already exists on this %s object.\"", "%", "(", ...
Adds a property to the Context. See `Mapper.add_ctx_property`, which uses this method to install the properties added on the Mapper level.
[ "Adds", "a", "property", "to", "the", "Context", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L405-L413
train
Adds a property to the Context.
trendels/rhino
rhino/mapper.py
Route.path
def path(self, args, kw): """Builds the URL path fragment for this route.""" params = self._pop_params(args, kw) if args or kw: raise InvalidArgumentError("Extra parameters (%s, %s) when building path for %s" % (args, kw, self.template)) return self.build_url(**params)
python
def path(self, args, kw): """Builds the URL path fragment for this route.""" params = self._pop_params(args, kw) if args or kw: raise InvalidArgumentError("Extra parameters (%s, %s) when building path for %s" % (args, kw, self.template)) return self.build_url(**params)
[ "def", "path", "(", "self", ",", "args", ",", "kw", ")", ":", "params", "=", "self", ".", "_pop_params", "(", "args", ",", "kw", ")", "if", "args", "or", "kw", ":", "raise", "InvalidArgumentError", "(", "\"Extra parameters (%s, %s) when building path for %s\""...
Builds the URL path fragment for this route.
[ "Builds", "the", "URL", "path", "fragment", "for", "this", "route", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L477-L482
train
Builds the URL path fragment for this route.
trendels/rhino
rhino/mapper.py
Mapper.add
def add(self, template, resource, name=None): """Add a route to a resource. The optional `name` assigns a name to this route that can be used when building URLs. The name must be unique within this Mapper object. """ # Special case for standalone handler functions if has...
python
def add(self, template, resource, name=None): """Add a route to a resource. The optional `name` assigns a name to this route that can be used when building URLs. The name must be unique within this Mapper object. """ # Special case for standalone handler functions if has...
[ "def", "add", "(", "self", ",", "template", ",", "resource", ",", "name", "=", "None", ")", ":", "# Special case for standalone handler functions", "if", "hasattr", "(", "resource", ",", "'_rhino_meta'", ")", ":", "route", "=", "Route", "(", "template", ",", ...
Add a route to a resource. The optional `name` assigns a name to this route that can be used when building URLs. The name must be unique within this Mapper object.
[ "Add", "a", "route", "to", "a", "resource", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L553-L576
train
Add a route to a resource.
trendels/rhino
rhino/mapper.py
Mapper.add_ctx_property
def add_ctx_property(self, name, fn, cached=True): """Install a context property. A context property is a factory function whos return value will be available as a property named `name` on `Context` objects passing through this mapper. The result will be cached unless `cached` is ...
python
def add_ctx_property(self, name, fn, cached=True): """Install a context property. A context property is a factory function whos return value will be available as a property named `name` on `Context` objects passing through this mapper. The result will be cached unless `cached` is ...
[ "def", "add_ctx_property", "(", "self", ",", "name", ",", "fn", ",", "cached", "=", "True", ")", ":", "if", "name", "in", "[", "item", "[", "0", "]", "for", "item", "in", "self", ".", "_ctx_properties", "]", ":", "raise", "InvalidArgumentError", "(", ...
Install a context property. A context property is a factory function whos return value will be available as a property named `name` on `Context` objects passing through this mapper. The result will be cached unless `cached` is False. The factory function will be called without ...
[ "Install", "a", "context", "property", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L614-L627
train
Install a context property.
trendels/rhino
rhino/mapper.py
Mapper.path
def path(self, target, args, kw): """Build a URL path fragment for a resource or route. Possible values for `target`: A string that does not start with a '.' and does not contain ':'. : Looks up the route of the same name on this mapper and returns it's path. A s...
python
def path(self, target, args, kw): """Build a URL path fragment for a resource or route. Possible values for `target`: A string that does not start with a '.' and does not contain ':'. : Looks up the route of the same name on this mapper and returns it's path. A s...
[ "def", "path", "(", "self", ",", "target", ",", "args", ",", "kw", ")", ":", "if", "type", "(", "target", ")", "in", "string_types", ":", "if", "':'", "in", "target", ":", "# Build path a nested route name", "prefix", ",", "rest", "=", "target", ".", "...
Build a URL path fragment for a resource or route. Possible values for `target`: A string that does not start with a '.' and does not contain ':'. : Looks up the route of the same name on this mapper and returns it's path. A string of the form 'a:b', 'a:b:c', etc. ...
[ "Build", "a", "URL", "path", "fragment", "for", "a", "resource", "or", "route", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L629-L673
train
Builds a URL path fragment for a resource or route.
trendels/rhino
rhino/mapper.py
Mapper.wsgi
def wsgi(self, environ, start_response): """Implements the mapper's WSGI interface.""" request = Request(environ) ctx = Context(request) try: try: response = self(request, ctx) ctx._run_callbacks('finalize', (request, response)) ...
python
def wsgi(self, environ, start_response): """Implements the mapper's WSGI interface.""" request = Request(environ) ctx = Context(request) try: try: response = self(request, ctx) ctx._run_callbacks('finalize', (request, response)) ...
[ "def", "wsgi", "(", "self", ",", "environ", ",", "start_response", ")", ":", "request", "=", "Request", "(", "environ", ")", "ctx", "=", "Context", "(", "request", ")", "try", ":", "try", ":", "response", "=", "self", "(", "request", ",", "ctx", ")",...
Implements the mapper's WSGI interface.
[ "Implements", "the", "mapper", "s", "WSGI", "interface", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L675-L693
train
Implements the mapper s WSGI interface.
trendels/rhino
rhino/mapper.py
Mapper.start_server
def start_server(self, host='localhost', port=9000, app=None): """Start a `wsgiref.simple_server` based server to run this mapper.""" from wsgiref.simple_server import make_server if app is None: app = self.wsgi server = make_server(host, port, app) server_addr = "%s:...
python
def start_server(self, host='localhost', port=9000, app=None): """Start a `wsgiref.simple_server` based server to run this mapper.""" from wsgiref.simple_server import make_server if app is None: app = self.wsgi server = make_server(host, port, app) server_addr = "%s:...
[ "def", "start_server", "(", "self", ",", "host", "=", "'localhost'", ",", "port", "=", "9000", ",", "app", "=", "None", ")", ":", "from", "wsgiref", ".", "simple_server", "import", "make_server", "if", "app", "is", "None", ":", "app", "=", "self", ".",...
Start a `wsgiref.simple_server` based server to run this mapper.
[ "Start", "a", "wsgiref", ".", "simple_server", "based", "server", "to", "run", "this", "mapper", "." ]
f1f0ef21b6080a2bd130b38b5bef163074c94aed
https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/mapper.py#L726-L734
train
Start a wsgiref. simple_server based server to run this mapper.
TUNE-Archive/freight_forwarder
freight_forwarder/registry/registry.py
Registry
def Registry(address='https://index.docker.io', **kwargs): """ :return: """ registry = None try: try: registry = V1(address, **kwargs) registry.ping() except RegistryException: registry = V2(address, **kwargs) registry.ping() except...
python
def Registry(address='https://index.docker.io', **kwargs): """ :return: """ registry = None try: try: registry = V1(address, **kwargs) registry.ping() except RegistryException: registry = V2(address, **kwargs) registry.ping() except...
[ "def", "Registry", "(", "address", "=", "'https://index.docker.io'", ",", "*", "*", "kwargs", ")", ":", "registry", "=", "None", "try", ":", "try", ":", "registry", "=", "V1", "(", "address", ",", "*", "*", "kwargs", ")", "registry", ".", "ping", "(", ...
:return:
[ ":", "return", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/registry/registry.py#L12-L30
train
Get a Registry object.
TUNE-Archive/freight_forwarder
freight_forwarder/registry/registry.py
V1.search
def search(self, terms): """ returns a dict {"name": "image_dict"} """ images = {} response = self._request_builder('GET', 'search', params={'q': terms}) if self._validate_response(response): body = json.loads(response.content.decode('utf-8'))['results'] ...
python
def search(self, terms): """ returns a dict {"name": "image_dict"} """ images = {} response = self._request_builder('GET', 'search', params={'q': terms}) if self._validate_response(response): body = json.loads(response.content.decode('utf-8'))['results'] ...
[ "def", "search", "(", "self", ",", "terms", ")", ":", "images", "=", "{", "}", "response", "=", "self", ".", "_request_builder", "(", "'GET'", ",", "'search'", ",", "params", "=", "{", "'q'", ":", "terms", "}", ")", "if", "self", ".", "_validate_resp...
returns a dict {"name": "image_dict"}
[ "returns", "a", "dict", "{", "name", ":", "image_dict", "}" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/registry/registry.py#L41-L53
train
search for images by terms
safarijv/sbo-sphinx
sbo_sphinx/apidoc.py
generate_docs
def generate_docs(app): """ Run sphinx-apidoc to generate Python API documentation for the project. """ config = app.config config_dir = app.env.srcdir source_root = os.path.join(config_dir, config.apidoc_source_root) output_root = os.path.join(config_dir, config.apidoc_output_root) exec...
python
def generate_docs(app): """ Run sphinx-apidoc to generate Python API documentation for the project. """ config = app.config config_dir = app.env.srcdir source_root = os.path.join(config_dir, config.apidoc_source_root) output_root = os.path.join(config_dir, config.apidoc_output_root) exec...
[ "def", "generate_docs", "(", "app", ")", ":", "config", "=", "app", ".", "config", "config_dir", "=", "app", ".", "env", ".", "srcdir", "source_root", "=", "os", ".", "path", ".", "join", "(", "config_dir", ",", "config", ".", "apidoc_source_root", ")", ...
Run sphinx-apidoc to generate Python API documentation for the project.
[ "Run", "sphinx", "-", "apidoc", "to", "generate", "Python", "API", "documentation", "for", "the", "project", "." ]
7a8efb7c49488131c90c19ef1a1563f595630a36
https://github.com/safarijv/sbo-sphinx/blob/7a8efb7c49488131c90c19ef1a1563f595630a36/sbo_sphinx/apidoc.py#L33-L51
train
Run sphinx - apidoc to generate Python API documentation for the project.
safarijv/sbo-sphinx
sbo_sphinx/apidoc.py
cleanup
def cleanup(output_root): """Remove any reST files which were generated by this extension""" if os.path.exists(output_root): if os.path.isdir(output_root): rmtree(output_root) else: os.remove(output_root)
python
def cleanup(output_root): """Remove any reST files which were generated by this extension""" if os.path.exists(output_root): if os.path.isdir(output_root): rmtree(output_root) else: os.remove(output_root)
[ "def", "cleanup", "(", "output_root", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "output_root", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "output_root", ")", ":", "rmtree", "(", "output_root", ")", "else", ":", "os", ".", "r...
Remove any reST files which were generated by this extension
[ "Remove", "any", "reST", "files", "which", "were", "generated", "by", "this", "extension" ]
7a8efb7c49488131c90c19ef1a1563f595630a36
https://github.com/safarijv/sbo-sphinx/blob/7a8efb7c49488131c90c19ef1a1563f595630a36/sbo_sphinx/apidoc.py#L54-L60
train
Remove any reST files which were generated by this extension
Kortemme-Lab/klab
klab/cluster/resubmit_eqw_jobs.py
qmod.cj
def cj(job_ids): '''Simple implementation where joblist is expected to be a list of integers (job ids). The full grammar for this command allows more granular control.''' for job_id in job_ids: job_id_types = set(map(type, job_ids)) assert(len(job_id_types) == 1 and type(1) == j...
python
def cj(job_ids): '''Simple implementation where joblist is expected to be a list of integers (job ids). The full grammar for this command allows more granular control.''' for job_id in job_ids: job_id_types = set(map(type, job_ids)) assert(len(job_id_types) == 1 and type(1) == j...
[ "def", "cj", "(", "job_ids", ")", ":", "for", "job_id", "in", "job_ids", ":", "job_id_types", "=", "set", "(", "map", "(", "type", ",", "job_ids", ")", ")", "assert", "(", "len", "(", "job_id_types", ")", "==", "1", "and", "type", "(", "1", ")", ...
Simple implementation where joblist is expected to be a list of integers (job ids). The full grammar for this command allows more granular control.
[ "Simple", "implementation", "where", "joblist", "is", "expected", "to", "be", "a", "list", "of", "integers", "(", "job", "ids", ")", ".", "The", "full", "grammar", "for", "this", "command", "allows", "more", "granular", "control", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/cluster/resubmit_eqw_jobs.py#L87-L93
train
Simple implementation where joblist is expected to be a list of integers. The full grammar for this command allows more granular control.
jreese/aioslack
aioslack/types.py
Auto.build
def build(cls: Type[T], data: Generic) -> T: """Build objects from dictionaries, recursively.""" fields = fields_dict(cls) kwargs: Dict[str, Any] = {} for key, value in data.items(): if key in fields: if isinstance(value, Mapping): t = fiel...
python
def build(cls: Type[T], data: Generic) -> T: """Build objects from dictionaries, recursively.""" fields = fields_dict(cls) kwargs: Dict[str, Any] = {} for key, value in data.items(): if key in fields: if isinstance(value, Mapping): t = fiel...
[ "def", "build", "(", "cls", ":", "Type", "[", "T", "]", ",", "data", ":", "Generic", ")", "->", "T", ":", "fields", "=", "fields_dict", "(", "cls", ")", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "for", "key", ",", "va...
Build objects from dictionaries, recursively.
[ "Build", "objects", "from", "dictionaries", "recursively", "." ]
5e705f557dde9e81903d84ffb2896ec0a074ad5c
https://github.com/jreese/aioslack/blob/5e705f557dde9e81903d84ffb2896ec0a074ad5c/aioslack/types.py#L36-L51
train
Build objects from dictionaries recursively.
jreese/aioslack
aioslack/types.py
Auto.generate
def generate( cls: Type[T], data: Generic, name: str = None, *, recursive: bool = True ) -> T: """Build dataclasses and objects from dictionaries, recursively.""" if name is None: name = cls.__name__ kls = make_class(name, {k: ib(default=None) for k in data}, bases=(cls,)...
python
def generate( cls: Type[T], data: Generic, name: str = None, *, recursive: bool = True ) -> T: """Build dataclasses and objects from dictionaries, recursively.""" if name is None: name = cls.__name__ kls = make_class(name, {k: ib(default=None) for k in data}, bases=(cls,)...
[ "def", "generate", "(", "cls", ":", "Type", "[", "T", "]", ",", "data", ":", "Generic", ",", "name", ":", "str", "=", "None", ",", "*", ",", "recursive", ":", "bool", "=", "True", ")", "->", "T", ":", "if", "name", "is", "None", ":", "name", ...
Build dataclasses and objects from dictionaries, recursively.
[ "Build", "dataclasses", "and", "objects", "from", "dictionaries", "recursively", "." ]
5e705f557dde9e81903d84ffb2896ec0a074ad5c
https://github.com/jreese/aioslack/blob/5e705f557dde9e81903d84ffb2896ec0a074ad5c/aioslack/types.py#L54-L69
train
Build dataclasses and objects from dictionaries recursively.
adaptive-learning/proso-apps
proso_models/models.py
emit_answer_event
def emit_answer_event(sender, instance, **kwargs): """ Save answer event to log file. """ if not issubclass(sender, Answer) or not kwargs['created']: return logger = get_events_logger() logger.emit('answer', { "user_id": instance.user_id, "is_correct": instance.item_asked...
python
def emit_answer_event(sender, instance, **kwargs): """ Save answer event to log file. """ if not issubclass(sender, Answer) or not kwargs['created']: return logger = get_events_logger() logger.emit('answer', { "user_id": instance.user_id, "is_correct": instance.item_asked...
[ "def", "emit_answer_event", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "sender", ",", "Answer", ")", "or", "not", "kwargs", "[", "'created'", "]", ":", "return", "logger", "=", "get_events_logger", ...
Save answer event to log file.
[ "Save", "answer", "event", "to", "log", "file", "." ]
8278c72e498d6ef8d392cc47b48473f4ec037142
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L1217-L1236
train
Save answer event to log file.
adaptive-learning/proso-apps
proso_models/models.py
ItemManager.get_all_available_leaves
def get_all_available_leaves(self, language=None, forbidden_item_ids=None): """ Get all available leaves. """ return self.get_all_leaves(language=language, forbidden_item_ids=forbidden_item_ids)
python
def get_all_available_leaves(self, language=None, forbidden_item_ids=None): """ Get all available leaves. """ return self.get_all_leaves(language=language, forbidden_item_ids=forbidden_item_ids)
[ "def", "get_all_available_leaves", "(", "self", ",", "language", "=", "None", ",", "forbidden_item_ids", "=", "None", ")", ":", "return", "self", ".", "get_all_leaves", "(", "language", "=", "language", ",", "forbidden_item_ids", "=", "forbidden_item_ids", ")" ]
Get all available leaves.
[ "Get", "all", "available", "leaves", "." ]
8278c72e498d6ef8d392cc47b48473f4ec037142
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L330-L334
train
Get all available leaves.
adaptive-learning/proso-apps
proso_models/models.py
ItemManager.filter_all_reachable_leaves_many
def filter_all_reachable_leaves_many(self, identifier_filters, language, forbidden_identifiers=None): """ Provides the same functionality as .. py:method:: ItemManager.filter_all_reachable_leaves(), but for more filters in the same time. Args: identifier_filters: list of ide...
python
def filter_all_reachable_leaves_many(self, identifier_filters, language, forbidden_identifiers=None): """ Provides the same functionality as .. py:method:: ItemManager.filter_all_reachable_leaves(), but for more filters in the same time. Args: identifier_filters: list of ide...
[ "def", "filter_all_reachable_leaves_many", "(", "self", ",", "identifier_filters", ",", "language", ",", "forbidden_identifiers", "=", "None", ")", ":", "for", "i", ",", "identifier_filter", "in", "enumerate", "(", "identifier_filters", ")", ":", "if", "len", "(",...
Provides the same functionality as .. py:method:: ItemManager.filter_all_reachable_leaves(), but for more filters in the same time. Args: identifier_filters: list of identifier filters language (str): language used for further filtering (some objects for differen...
[ "Provides", "the", "same", "functionality", "as", "..", "py", ":", "method", "::", "ItemManager", ".", "filter_all_reachable_leaves", "()", "but", "for", "more", "filters", "in", "the", "same", "time", "." ]
8278c72e498d6ef8d392cc47b48473f4ec037142
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L338-L395
train
This method returns a list of all reachable item IDs that are in the same language as the given list of identifier filters.