uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9df5d7c49bc0d43f3fdb3230 | train | function | def _on_message(*args):
print('!!! Here is default callback function, '
'please pass in your own customized callback function to handle received data !!!')
print(args[1])
| def _on_message(*args):
| print('!!! Here is default callback function, '
'please pass in your own customized callback function to handle received data !!!')
print(args[1])
| .close()
return result
def __del__(self):
try:
self.ws.close()
except Exception:
pass # already closed connection, quit silent
# --------------------------------------------
# Below are default behavior to be used for websocket, feel free to override by yourself
d... | 64 | 64 | 40 | 7 | 56 | RafaelHMachado/Cioffis_Automation | venv/Lib/site-packages/binance_dex/lib/sockets.py | Python | _on_message | _on_message | 59 | 62 | 59 | 59 | 5bd51163e9fa16f4f5757f433850d1506312cf83 | bigcode/the-stack | train |
ed10918feef3a8b859b5ee36 | train | function | def _on_error(ws, error):
print(error)
| def _on_error(ws, error):
| print(error)
| are default behavior to be used for websocket, feel free to override by yourself
def _on_message(*args):
print('!!! Here is default callback function, '
'please pass in your own customized callback function to handle received data !!!')
print(args[1])
def _on_error(ws, error):
| 64 | 64 | 12 | 8 | 56 | RafaelHMachado/Cioffis_Automation | venv/Lib/site-packages/binance_dex/lib/sockets.py | Python | _on_error | _on_error | 65 | 66 | 65 | 65 | be010273b98dd5d0b2251cee9a76f5eda29ded0b | bigcode/the-stack | train |
28ecf842d2c3f265e0390710 | train | class | class AccountService(object):
def __init__(self, user):
self.user = user
@classmethod
def get_username_base(self, firstname, lastname):
base = ""
first = slugify(firstname)
last = slugify(lastname)
if first and last:
base = "%s.%s" % (first[0], last)
... | class AccountService(object):
| def __init__(self, user):
self.user = user
@classmethod
def get_username_base(self, firstname, lastname):
base = ""
first = slugify(firstname)
last = slugify(lastname)
if first and last:
base = "%s.%s" % (first[0], last)
elif last:
bas... | from django.conf import settings
from django.template.defaultfilters import slugify
from django.utils.crypto import constant_time_compare
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from froide.accesstoken.models import AccessToken
from froid... | 256 | 256 | 2,147 | 5 | 251 | sthapa/froide | froide/account/services.py | Python | AccountService | AccountService | 48 | 366 | 48 | 48 | 1f6f4be69070d5c209138cf6aea3a43f20ce392d | bigcode/the-stack | train |
929f4ffe7cc5e912a6e1d29a | train | function | def get_user_for_email(email):
try:
return User.objects.get(email=email)
except User.DoesNotExist:
return False
| def get_user_for_email(email):
| try:
return User.objects.get(email=email)
except User.DoesNotExist:
return False
| _utils import save_obj_unique
from froide.helper.email_sending import mail_registry
from .models import User, AccountBlocklist
from . import account_activated
ONE_TIME_LOGIN_PURPOSE = "onetimelogin"
ONE_TIME_LOGIN_EXPIRY = timedelta(hours=72)
def get_user_for_email(email):
| 64 | 64 | 29 | 7 | 57 | sthapa/froide | froide/account/services.py | Python | get_user_for_email | get_user_for_email | 27 | 31 | 27 | 27 | ebb42b2e8cbb2cd8e7478ba49fb24e582bad7d9d | bigcode/the-stack | train |
8cdcad15d583dc9a7accf3b6 | train | class | class Opera(Browser):
"""Opera-specific interface.
Includes webdriver installation, and wptrunner setup methods.
"""
product = "opera"
binary = "/usr/bin/opera"
requirements = "requirements_opera.txt"
def install(self, dest=None):
raise NotImplementedError
def platform_string... | class Opera(Browser):
| """Opera-specific interface.
Includes webdriver installation, and wptrunner setup methods.
"""
product = "opera"
binary = "/usr/bin/opera"
requirements = "requirements_opera.txt"
def install(self, dest=None):
raise NotImplementedError
def platform_string(self):
platfo... | (.*)", version_string)
if not m:
return None
return m.group(1)
class ChromeAndroid(Browser):
"""Chrome-specific interface for Android.
Includes webdriver installation.
"""
product = "chrome_android"
requirements = "requirements_chrome_android.txt"
def install(se... | 141 | 141 | 472 | 5 | 135 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Opera | Opera | 375 | 434 | 375 | 375 | 6c611ccdb822e44e7d5b5643af1d6feecdfbbdfa | bigcode/the-stack | train |
4ae1456991f2deb02b610d8a | train | class | class Firefox(Browser):
"""Firefox-specific interface.
Includes installation, webdriver installation, and wptrunner setup methods.
"""
product = "firefox"
binary = "browsers/firefox/firefox"
platform_ini = "browsers/firefox/platform.ini"
requirements = "requirements_firefox.txt"
def p... | class Firefox(Browser):
| """Firefox-specific interface.
Includes installation, webdriver installation, and wptrunner setup methods.
"""
product = "firefox"
binary = "browsers/firefox/firefox"
platform_ini = "browsers/firefox/platform.ini"
requirements = "requirements_firefox.txt"
def platform_string_geckodriv... | IO
from utils import call, get, untar, unzip
logger = logging.getLogger(__name__)
uname = platform.uname()
class Browser(object):
__metaclass__ = ABCMeta
@abstractmethod
def install(self, dest=None):
"""Install the browser."""
return NotImplemented
@abstractmethod
def install_... | 256 | 256 | 1,899 | 5 | 250 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Firefox | Firefox | 61 | 286 | 61 | 61 | 1ec7729cc4e07c8646dffae00ec50f4c4fa5e1fc | bigcode/the-stack | train |
2215b23e1605e537bdf75476 | train | class | class Edge(Browser):
"""Edge-specific interface."""
product = "edge"
requirements = "requirements_edge.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
return find_executable("Micro... | class Edge(Browser):
| """Edge-specific interface."""
product = "edge"
requirements = "requirements_edge.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
return find_executable("MicrosoftWebDriver")
... | def version(self, binary):
"""Retrieve the release version of the installed browser."""
binary = binary or self.binary
output = call(binary, "--version")
return re.search(r"[0-9\.]+( [a-z]+)?$", output.strip()).group(0)
class Edge(Browser):
| 64 | 64 | 95 | 5 | 59 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Edge | Edge | 437 | 456 | 437 | 437 | 5f5235edddc15d6adc07cf5db5baaf4f957eefb9 | bigcode/the-stack | train |
eb03e5214240417f235a0ea6 | train | class | class Safari(Browser):
"""Safari-specific interface.
Includes installation, webdriver installation, and wptrunner setup methods.
"""
product = "safari"
requirements = "requirements_safari.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
... | class Safari(Browser):
| """Safari-specific interface.
Includes installation, webdriver installation, and wptrunner setup methods.
"""
product = "safari"
requirements = "requirements_safari.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedErr... | Error
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
return find_executable("IEDriverServer.exe")
def install_webdriver(self, dest=None):
raise NotImplementedError
def version(self, binary):
return None
class Safari(Browser):
| 64 | 64 | 111 | 5 | 58 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Safari | Safari | 481 | 503 | 481 | 481 | 18968ee96f4069727ec12f1aa47392b3b2254dd1 | bigcode/the-stack | train |
70eb93a638c9bf1e1370bc08 | train | class | class WebKit(Browser):
"""WebKit-specific interface."""
product = "webkit"
requirements = "requirements_webkit.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self, path=None):
return None
def find_webdriver(self):
return None
def ins... | class WebKit(Browser):
| """WebKit-specific interface."""
product = "webkit"
requirements = "requirements_webkit.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self, path=None):
return None
def find_webdriver(self):
return None
def install_webdriver(self):
... | raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
raise NotImplementedError
def install_webdriver(self, dest=None):
raise NotImplementedError
def version(self, binary):
return None
class WebKit(Browser):
| 64 | 64 | 90 | 6 | 57 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | WebKit | WebKit | 581 | 600 | 581 | 581 | 45b30c06a143e8b348f44603955557b031546ce0 | bigcode/the-stack | train |
b998a03d4371ff27ee2fe066 | train | class | class Browser(object):
__metaclass__ = ABCMeta
@abstractmethod
def install(self, dest=None):
"""Install the browser."""
return NotImplemented
@abstractmethod
def install_webdriver(self, dest=None):
"""Install the WebDriver implementation for this browser."""
return ... | class Browser(object):
| __metaclass__ = ABCMeta
@abstractmethod
def install(self, dest=None):
"""Install the browser."""
return NotImplemented
@abstractmethod
def install_webdriver(self, dest=None):
"""Install the WebDriver implementation for this browser."""
return NotImplemented
@ab... | ABCMeta, abstractmethod
from ConfigParser import RawConfigParser
from datetime import datetime, timedelta
from distutils.spawn import find_executable
from io import BytesIO
from utils import call, get, untar, unzip
logger = logging.getLogger(__name__)
uname = platform.uname()
class Browser(object):
| 66 | 66 | 223 | 4 | 62 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Browser | Browser | 22 | 58 | 22 | 22 | 919480cbabf17c97fb2dc0e25f0fe8e5b88545aa | bigcode/the-stack | train |
c5be9e2fc5b1c668cf214bf0 | train | class | class InternetExplorer(Browser):
"""Internet Explorer-specific interface."""
product = "ie"
requirements = "requirements_ie.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
return f... | class InternetExplorer(Browser):
| """Internet Explorer-specific interface."""
product = "ie"
requirements = "requirements_ie.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
return find_executable("IEDriverServer.ex... | Error
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
return find_executable("MicrosoftWebDriver")
def install_webdriver(self, dest=None):
raise NotImplementedError
def version(self, binary):
return None
class InternetExplorer(Browser):
| 64 | 64 | 98 | 6 | 57 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | InternetExplorer | InternetExplorer | 459 | 478 | 459 | 459 | c34401b60aba52cb9c92928a965c9dae75df29a3 | bigcode/the-stack | train |
0e0943bb67d3121f0470fa6c | train | class | class Sauce(Browser):
"""Sauce-specific interface."""
product = "sauce"
requirements = "requirements_sauce.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
raise NotImplementedError... | class Sauce(Browser):
| """Sauce-specific interface."""
product = "sauce"
requirements = "requirements_sauce.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdriver(self):
raise NotImplementedError
def install_webd... | ):
raise NotImplementedError
def version(self, binary):
"""Retrieve the release version of the installed browser."""
output = call(binary, "--version")
return re.search(r"[0-9\.]+( [a-z]+)?$", output.strip()).group(0)
class Sauce(Browser):
| 64 | 64 | 94 | 5 | 59 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Sauce | Sauce | 559 | 578 | 559 | 559 | 288ac059cf871a6ae16a612bd8cb00dad31a8f72 | bigcode/the-stack | train |
019fd04cae5a3aa1ea9cfaa1 | train | class | class ChromeAndroid(Browser):
"""Chrome-specific interface for Android.
Includes webdriver installation.
"""
product = "chrome_android"
requirements = "requirements_chrome_android.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise No... | class ChromeAndroid(Browser):
| """Chrome-specific interface for Android.
Includes webdriver installation.
"""
product = "chrome_android"
requirements = "requirements_chrome_android.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def fin... | def version(self, binary=None):
binary = binary or self.binary
version_string = call(binary, "--version").strip()
m = re.match(r"Google Chrome (.*)", version_string)
if not m:
return None
return m.group(1)
class ChromeAndroid(Browser):
| 64 | 64 | 114 | 6 | 58 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | ChromeAndroid | ChromeAndroid | 349 | 372 | 349 | 349 | 996fc16d07b9a3169f9713133ba48067fee4b63d | bigcode/the-stack | train |
96eea4f0ea40efd338757efb | train | class | class Servo(Browser):
"""Servo-specific interface."""
product = "servo"
requirements = "requirements_servo.txt"
def platform_components(self):
platform = {
"Linux": "linux",
"Windows": "win",
"Darwin": "mac"
}.get(uname[0])
if platform is No... | class Servo(Browser):
| """Servo-specific interface."""
product = "servo"
requirements = "requirements_servo.txt"
def platform_components(self):
platform = {
"Linux": "linux",
"Windows": "win",
"Darwin": "mac"
}.get(uname[0])
if platform is None:
raise ... | interface.
Includes installation, webdriver installation, and wptrunner setup methods.
"""
product = "safari"
requirements = "requirements_safari.txt"
def install(self, dest=None):
raise NotImplementedError
def find_binary(self):
raise NotImplementedError
def find_webdr... | 107 | 107 | 358 | 5 | 101 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Servo | Servo | 506 | 556 | 506 | 506 | 016b85d80698b7436d22b81c46a5cf9c12ad4980 | bigcode/the-stack | train |
1708c5d296b6c52676d169ae | train | class | class Chrome(Browser):
"""Chrome-specific interface.
Includes webdriver installation, and wptrunner setup methods.
"""
product = "chrome"
binary = "/usr/bin/google-chrome"
requirements = "requirements_chrome.txt"
def install(self, dest=None):
raise NotImplementedError
def pla... | class Chrome(Browser):
| """Chrome-specific interface.
Includes webdriver installation, and wptrunner setup methods.
"""
product = "chrome"
binary = "/usr/bin/google-chrome"
requirements = "requirements_chrome.txt"
def install(self, dest=None):
raise NotImplementedError
def platform_string(self):
... | zip":
unzip(get(url).raw, dest=dest)
else:
untar(get(url).raw, dest=dest)
return find_executable(os.path.join(dest, "geckodriver"))
def version(self, binary=None):
"""Retrieve the release version of the installed browser."""
binary = binary or self.find_binar... | 120 | 120 | 400 | 5 | 115 | zipated/src | third_party/blink/tools/blinkpy/third_party/wpt/wpt/tools/wpt/browser.py | Python | Chrome | Chrome | 289 | 346 | 289 | 289 | 1588deede8ac4f40e6be9969f2057ea6712604c9 | bigcode/the-stack | train |
18e3cd01a323d1dd055fc6f0 | train | class | @docstring_formatter(sim_methods=SIMILARITY_METHODS, log_levels=LOG_LEVELS, supported=SUPPORTED_EXT)
class SumoPrepare(SumoMode):
""" Sumo mode for data pre-processing and creation of multiplex network files. Constructor args are set \
in 'prepare' subparser.
Args:
| infiles (list): comma-delimited... | @docstring_formatter(sim_methods=SIMILARITY_METHODS, log_levels=LOG_LEVELS, supported=SUPPORTED_EXT)
class SumoPrepare(SumoMode):
| """ Sumo mode for data pre-processing and creation of multiplex network files. Constructor args are set \
in 'prepare' subparser.
Args:
| infiles (list): comma-delimited list of paths to input files, containing standardized feature matrices, \
with samples in columns and features in row... | from collections import Counter
from sumo.constants import PREPARE_ARGS, SUPPORTED_EXT, SIMILARITY_METHODS, LOG_LEVELS
from sumo.modes.mode import SumoMode
from sumo.modes.prepare.similarity import feature_to_adjacency
from sumo.utils import plot_heatmap_seaborn, save_arrays_to_npz, setup_logger, docstring_formatter, c... | 139 | 256 | 2,138 | 34 | 104 | ratan-lab/sumo | src/sumo/modes/prepare/prepare.py | Python | SumoPrepare | SumoPrepare | 12 | 210 | 12 | 13 | 55695588f78b73ed2396e130a7200ecbc32a1940 | bigcode/the-stack | train |
a2bf11ade76128cc724fee5d | train | class | class KytosConfig():
"""Handle settings of Kytos."""
def __init__(self):
"""Parse the command line.
The contructor set defaults parameters that can be used by KytosConfig.
"""
self.options = {}
conf_parser = ArgumentParser(add_help=False)
conf_parser.add_argume... | class KytosConfig():
| """Handle settings of Kytos."""
def __init__(self):
"""Parse the command line.
The contructor set defaults parameters that can be used by KytosConfig.
"""
self.options = {}
conf_parser = ArgumentParser(add_help=False)
conf_parser.add_argument("-c", "--conf",
... | """Here you can control the config parameters to run Kytos controller.
Basically you can use a config file (-c option) and use arguments on command
line. If you specify a config file, then and option configured inside this file
will be overridden by the option on command line.
"""
import json
import os
import uuid
im... | 183 | 256 | 1,163 | 6 | 177 | hdiogenes/kytos | kytos/core/config.py | Python | KytosConfig | KytosConfig | 27 | 186 | 27 | 27 | 37e171327019f7751f6f926e2fcef5a60ad40aa6 | bigcode/the-stack | train |
7b1fd58ca747588cd7161a68 | train | function | def _render_config_templates(templates,
destination=Path(__file__).parent,
**kwargs):
"""Create a config file based on a template file.
If no destination is passed, the new conf file will be created on the
directory of the template file.
Args:
... | def _render_config_templates(templates,
destination=Path(__file__).parent,
**kwargs):
| """Create a config file based on a template file.
If no destination is passed, the new conf file will be created on the
directory of the template file.
Args:
template (string): Path of the template file
destination (string): Directory in which the config file will
... | if isinstance(value, str):
return json.loads(value)
return value
options.napps_pre_installed = _parse_json(options.napps_pre_installed)
options.vlan_pool = _parse_json(options.vlan_pool)
options.authenticate_urls = _parse_json(options.authenticate_urls)
... | 86 | 86 | 289 | 21 | 64 | hdiogenes/kytos | kytos/core/config.py | Python | _render_config_templates | _render_config_templates | 189 | 222 | 189 | 191 | 4783c5ee21e79ce4cd39ae64a86de09dde46af27 | bigcode/the-stack | train |
1bf35e67acde952d7fb78a05 | train | class | class BaseCADFStrategy(object):
"""
constructs the target_type_uri from the request path and body
examples:
(1) path: .../v2/zones/012345678abcdef/recordsets/012345678abcdef
=> <prefix>/zones/zone/recordsets/recordset
(2) path: .../servers/1234567890abcdef/action
body: {"addFloatin... | class BaseCADFStrategy(object):
| """
constructs the target_type_uri from the request path and body
examples:
(1) path: .../v2/zones/012345678abcdef/recordsets/012345678abcdef
=> <prefix>/zones/zone/recordsets/recordset
(2) path: .../servers/1234567890abcdef/action
body: {"addFloatingIp": {"address": "x.x.x.x", "fi... | # Copyright 2018 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the 'License'); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | 165 | 256 | 3,681 | 7 | 157 | sapcc/openstack-watcher-middleware | watcher/cadf_strategy.py | Python | BaseCADFStrategy | BaseCADFStrategy | 24 | 452 | 24 | 24 | 5bfb7c989c929bcf7ed9aa0112f9bc1e2daa2a6c | bigcode/the-stack | train |
541033f671eaa657703bcfca | train | class | class SwiftCADFStrategy(BaseCADFStrategy):
"""
determines the target_type_uri from a swift (object-store) request
path of swift request might look like: ../AUTH_accountname/containername/objectname
and the corresponding target_type_uri like: <prefix>/account/container/object
"""
def __init__(s... | class SwiftCADFStrategy(BaseCADFStrategy):
| """
determines the target_type_uri from a swift (object-store) request
path of swift request might look like: ../AUTH_accountname/containername/objectname
and the corresponding target_type_uri like: <prefix>/account/container/object
"""
def __init__(self,
target_type_uri_prefi... | target_type_uri
"""
# ignore if previous part is version as in /v3/<project_id>/.. or /v3/<path_keyword>/
if common.is_version_string(previous_part):
return None
# replace plural ending with 'ies' by singular ending with 'y'
if common.is_uid_string(part):
... | 256 | 256 | 1,073 | 10 | 245 | sapcc/openstack-watcher-middleware | watcher/cadf_strategy.py | Python | SwiftCADFStrategy | SwiftCADFStrategy | 455 | 580 | 455 | 455 | a8d66f649a6c482088cf09dae036e690a853f045 | bigcode/the-stack | train |
99181d57d84fc99deeb0c9ac | train | function | def update_pr_main():
"""Main method"""
parser = argparse.ArgumentParser(description="Build package.", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--pr-number", "-p", dest="pr_number", type=int, required=True, help="PR number")
parser.add_argument(
"--repo", "-r", dest="... | def update_pr_main():
| """Main method"""
parser = argparse.ArgumentParser(description="Build package.", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("--pr-number", "-p", dest="pr_number", type=int, required=True, help="PR number")
parser.add_argument(
"--repo", "-r", dest="repo_id", default="Azu... | ), build_conf=True)
# Commit that
do_commit(sdk_repo, "Packaging update of {}".format(package_name), head_branch, None) # Unused
# Push all commits at once
sdk_repo.git.push("origin", head_branch, set_upstream=True)
def update_pr_main():
| 65 | 65 | 218 | 5 | 60 | rsdoherty/azure-sdk-for-python | tools/azure-sdk-tools/packaging_tools/update_pr.py | Python | update_pr_main | update_pr_main | 63 | 84 | 63 | 63 | e6b0a3836c4361b8f7d15568dd816ebd9a86f05f | bigcode/the-stack | train |
06a47b21a9c1eb14fd3610a0 | train | function | def update_pr(gh_token, repo_id, pr_number):
from github import Github
con = Github(gh_token)
repo = con.get_repo(repo_id)
sdk_pr = repo.get_pull(pr_number)
files = [one_file.filename for one_file in sdk_pr.get_files() if one_file.status not in ["removed"]]
# "get_files" of Github only download... | def update_pr(gh_token, repo_id, pr_number):
| from github import Github
con = Github(gh_token)
repo = con.get_repo(repo_id)
sdk_pr = repo.get_pull(pr_number)
files = [one_file.filename for one_file in sdk_pr.get_files() if one_file.status not in ["removed"]]
# "get_files" of Github only download the first 300 files. Might not be enough.
... | import argparse
import logging
import os
from pathlib import Path
import re
import tempfile
from azure_devtools.ci_tools.git_tools import (
do_commit,
)
from azure_devtools.ci_tools.github_tools import manage_git_folder, configure_user
from git import Repo
from github import Github
from . import build_packaging_... | 122 | 124 | 415 | 13 | 109 | rsdoherty/azure-sdk-for-python | tools/azure-sdk-tools/packaging_tools/update_pr.py | Python | update_pr | update_pr | 23 | 60 | 23 | 23 | 2fa3eb6dd78e62d72fe9428ccaaadc7718929fd4 | bigcode/the-stack | train |
e1e41cc0bef1bc1e7e7e9386 | train | class | class TestModelCreation(unittest.TestCase):
def test_signal_creation(self):
class TestModel(BaseModel):
signal = Signal()
self.assertTrue(hasattr(TestModel, '_signals'))
def test_signals_model(self):
class TestModel(BaseModel):
a1 = Signal()
a2 = Sig... | class TestModelCreation(unittest.TestCase):
| def test_signal_creation(self):
class TestModel(BaseModel):
signal = Signal()
self.assertTrue(hasattr(TestModel, '_signals'))
def test_signals_model(self):
class TestModel(BaseModel):
a1 = Signal()
a2 = Signal()
tm = TestModel()
self... | import unittest
from time import sleep
from experimentor.core.exceptions import ModelDefinitionException
from experimentor.core.signal import Signal
from experimentor.models.decorators import make_async_thread
from experimentor.models.devices.base_device import ModelDevice
from experimentor.models.models import MetaMo... | 67 | 100 | 335 | 8 | 58 | aquilesC/experimentor | tests/test_model_creation.py | Python | TestModelCreation | TestModelCreation | 11 | 62 | 11 | 11 | cad6c0bb4bac3ae57042671d62163cbc7f355668 | bigcode/the-stack | train |
0cdb32033ec8e7cc4660e2c7 | train | class | class Migration(migrations.Migration):
dependencies = [
('bom', '0022_auto_20190811_2140'),
]
operations = [
migrations.AlterModelOptions(
name='partclass',
options={'ordering': ['code']},
),
migrations.AlterModelOptions(
name='partrevisi... | class Migration(migrations.Migration):
| dependencies = [
('bom', '0022_auto_20190811_2140'),
]
operations = [
migrations.AlterModelOptions(
name='partclass',
options={'ordering': ['code']},
),
migrations.AlterModelOptions(
name='partrevision',
options={'ordering': ['... | # Generated by Django 2.2.5 on 2019-12-05 23:46
from django.db import migrations, models
import django.utils.timezone
import bom
def update_part_classes(apps, schema_editor):
Part = apps.get_model('bom', 'Part')
PartClass = apps.get_model('bom', 'PartClass')
Organization = apps.get_model('bom', 'Organizat... | 163 | 256 | 2,994 | 7 | 156 | FixturFab/django-bomf | bom/migrations/0023_auto_20191205_2351.py | Python | Migration | Migration | 19 | 255 | 19 | 20 | dbf36dfdeb88fa95f4600c705c61d7c9d83e0ff2 | bigcode/the-stack | train |
8ec7a53f9146a4a14d5db707 | train | function | def update_part_classes(apps, schema_editor):
Part = apps.get_model('bom', 'Part')
PartClass = apps.get_model('bom', 'PartClass')
Organization = apps.get_model('bom', 'Organization')
for o in Organization.objects.all():
for p in Part.objects.filter(organization=o):
pc = p.number_cla... | def update_part_classes(apps, schema_editor):
| Part = apps.get_model('bom', 'Part')
PartClass = apps.get_model('bom', 'PartClass')
Organization = apps.get_model('bom', 'Organization')
for o in Organization.objects.all():
for p in Part.objects.filter(organization=o):
pc = p.number_class
new_pc, _ = PartClass.objects.g... | # Generated by Django 2.2.5 on 2019-12-05 23:46
from django.db import migrations, models
import django.utils.timezone
import bom
def update_part_classes(apps, schema_editor):
| 50 | 64 | 116 | 10 | 39 | FixturFab/django-bomf | bom/migrations/0023_auto_20191205_2351.py | Python | update_part_classes | update_part_classes | 7 | 17 | 7 | 7 | 5338b107fde996b13904c7b00e5f007be74bad4f | bigcode/the-stack | train |
c11c4df9ac1028414bbbe50f | train | class | class AzureVmWorkloadProtectedItem(ProtectedItem):
"""Azure VM workload-specific protected item.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: AzureVmWorkloadSAPAseDatabaseProtectedItem,
AzureVmWorkloadSAPHanaDatabaseProtectedItem,
AzureVmWorkloadSQLDa... | class AzureVmWorkloadProtectedItem(ProtectedItem):
| """Azure VM workload-specific protected item.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: AzureVmWorkloadSAPAseDatabaseProtectedItem,
AzureVmWorkloadSAPHanaDatabaseProtectedItem,
AzureVmWorkloadSQLDatabaseProtectedItem
All required parameters mu... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 97 | 256 | 2,254 | 11 | 85 | SanjayHukumRana/azure-sdk-for-python | sdk/recoveryservices/azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/azure_vm_workload_protected_item_py3.py | Python | AzureVmWorkloadProtectedItem | AzureVmWorkloadProtectedItem | 15 | 163 | 15 | 15 | 1619d5f8cdb58ac0613059ce92a93002039e7acf | bigcode/the-stack | train |
3a4cf43df91eda0b85b5faa9 | train | function | def conll2seq(conll, char2int_codebook, upos2int, deprel2int, deprel=True, return_chars=False):
"""
:param conll: the conllu (pyconll) object loaded from file to convert
:param char2int_codebook: dictionary codebook encoding the chars to int indices
:param upos2int: dictionary encoding the upos tags to... | def conll2seq(conll, char2int_codebook, upos2int, deprel2int, deprel=True, return_chars=False):
| """
:param conll: the conllu (pyconll) object loaded from file to convert
:param char2int_codebook: dictionary codebook encoding the chars to int indices
:param upos2int: dictionary encoding the upos tags to int
:param deprel2int: dictionary encoding the deprel tags to int
:param deprel: if dep... | int.get)(charseq[1], upos2int["_"]) # defaults to '_' which is None for conllu format
if charseq.shape[0] == 3:
# defaults to '_' which is None for conllu format
ret[2, :] = np.vectorize(deprel2int.get)(charseq[2], deprel2int["_"])
return ret
def conll2seq(conll, char2int_codebook, upos2int, de... | 119 | 119 | 399 | 34 | 84 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | conll2seq | conll2seq | 129 | 161 | 129 | 129 | 9360b2f1eae9963945691a1454c7d5c77fe032e8 | bigcode/the-stack | train |
3e8460f98da1ce792d394b5f | train | function | def process_all(flist, utf8_char2int_codebook, return_data=False, save_processed=True):
"""
Processes a list of conllu files (must be valid or will fail)
Will save the processed char level codes in a pickle file in the same directory as the conllu files
if return_data is true will keep all data in memor... | def process_all(flist, utf8_char2int_codebook, return_data=False, save_processed=True):
| """
Processes a list of conllu files (must be valid or will fail)
Will save the processed char level codes in a pickle file in the same directory as the conllu files
if return_data is true will keep all data in memory and return it, use with caution.
Else the return value is an empty list
:param... | _codebook, upos2int, deprel2int, deprel)
if save_to:
with open(save_to, "wb") as fout:
# print("saving data to: {}".format(path_leaf(save_to)))
pickle.dump(ret, fout, protocol=pickle.HIGHEST_PROTOCOL)
return ret
def process_all(flist, utf8_char2int_codebook, return_data=False, sa... | 91 | 91 | 304 | 22 | 68 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | process_all | process_all | 186 | 214 | 186 | 186 | b07440ab95409ee4ec127b939484814925271f2a | bigcode/the-stack | train |
e9879eaf4d3480eca76fef19 | train | function | def filter_conllu_files(conllufiles, blacklist):
prefiltered_conllu = []
for f in conllufiles:
todel = list(filter(lambda bl: bl in f, blacklist))
if len(todel) == 0:
prefiltered_conllu.append(f)
conllu_train = [f for f in prefiltered_conllu if "-train" in f]
conllu_test = [f... | def filter_conllu_files(conllufiles, blacklist):
| prefiltered_conllu = []
for f in conllufiles:
todel = list(filter(lambda bl: bl in f, blacklist))
if len(todel) == 0:
prefiltered_conllu.append(f)
conllu_train = [f for f in prefiltered_conllu if "-train" in f]
conllu_test = [f for f in prefiltered_conllu if "-test" in f]
... | .basename(head)
def get_all_files_recurse(rootdir):
allfiles = []
for root, directories, filenames in os.walk(rootdir):
for filename in filenames:
allfiles.append(os.path.join(root, filename))
return allfiles
def filter_conllu_files(conllufiles, blacklist):
| 64 | 64 | 138 | 12 | 51 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | filter_conllu_files | filter_conllu_files | 49 | 58 | 49 | 49 | 8b7ec9791df77a5054d96a212ceee8ff617d7063 | bigcode/the-stack | train |
df0c910159ddd7fe175e71d7 | train | function | def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
| def path_leaf(path):
| head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
| Dict(enumerate(DEPREL_LIST))
DEPREL_CHAR2IDX = SortedDict(zip(DEPREL_LIST, range(len(DEPREL_LIST))))
# from https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format
def path_leaf(path):
| 64 | 64 | 24 | 5 | 58 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | path_leaf | path_leaf | 36 | 38 | 36 | 36 | 24dc2f1470ffc1c87fa15dc9c21f362b061673ec | bigcode/the-stack | train |
abfdbbfa53cd1a1726f44e5f | train | function | def get_all_files_recurse(rootdir):
allfiles = []
for root, directories, filenames in os.walk(rootdir):
for filename in filenames:
allfiles.append(os.path.join(root, filename))
return allfiles
| def get_all_files_recurse(rootdir):
| allfiles = []
for root, directories, filenames in os.walk(rootdir):
for filename in filenames:
allfiles.append(os.path.join(root, filename))
return allfiles
| L_LIST))))
# from https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format
def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def get_all_files_recurse(rootdir):
| 64 | 64 | 49 | 9 | 55 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | get_all_files_recurse | get_all_files_recurse | 41 | 46 | 41 | 41 | 6e6cc28b57f9ac2bf3b8ca34fc1320c8fd6c9fc2 | bigcode/the-stack | train |
e8057640064f182848c43529 | train | function | def seq2charlevel(sequence, deprel=True):
"""
Creates a matrix with character level description of the tag annotation for the training and testing of
Language Part of Speech Neural Networks
:param sequence: conllu (pyconll) sequence
:param deprel: if True will also extract deprel to the output
:... | def seq2charlevel(sequence, deprel=True):
| """
Creates a matrix with character level description of the tag annotation for the training and testing of
Language Part of Speech Neural Networks
:param sequence: conllu (pyconll) sequence
:param deprel: if True will also extract deprel to the output
:return: a numpy array of chars where the f... | allfiles.append(os.path.join(root, filename))
return allfiles
def filter_conllu_files(conllufiles, blacklist):
prefiltered_conllu = []
for f in conllufiles:
todel = list(filter(lambda bl: bl in f, blacklist))
if len(todel) == 0:
prefiltered_conllu.append(f)
conllu_train = ... | 165 | 165 | 551 | 12 | 152 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | seq2charlevel | seq2charlevel | 61 | 103 | 61 | 61 | 7132721e5cbc6711f1dd532df67dd0b4b629ec04 | bigcode/the-stack | train |
a2b077cd2b367b3f5329264b | train | function | def charseq2int(charseq, char2int_codebook, upos2int, deprel2int):
"""
:param charseq: character sequence in a numpy matrix form where shape = (2,N) or (3,N)
charseq[0] is the character sequence
charseq[1] is the upos tag
charseq[2] is the deprel tag
:param char2int_code... | def charseq2int(charseq, char2int_codebook, upos2int, deprel2int):
| """
:param charseq: character sequence in a numpy matrix form where shape = (2,N) or (3,N)
charseq[0] is the character sequence
charseq[1] is the upos tag
charseq[2] is the deprel tag
:param char2int_codebook: dictionary codebook encoding the chars to int indices
:pa... | # set index to the new absolute text position
index = idx_end
except Exception as e:
print("Token exception: ", e)
pass
if deprel:
ret = np.stack([l_txt, l_tags_upos, l_tags_deprel])
else:
ret = np.stack([l_txt, l_tags_upos])
return ret
def charse... | 106 | 106 | 355 | 25 | 80 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | charseq2int | charseq2int | 106 | 126 | 106 | 106 | 99477b15fc3720a9ff27e8d8a4c8bab91e2af30c | bigcode/the-stack | train |
5c17b1d3cd6a37bf50203d00 | train | function | def process_conllu_file(fname, char2int_codebook, upos2int, deprel2int, deprel=True, save_to=None):
"""
Processes the input file (must be a conllu file) and outputs the charlevel encoded matrices.
If save_to is a valid output filename it will save it
:param fname:
:param char2int_codebook:
:para... | def process_conllu_file(fname, char2int_codebook, upos2int, deprel2int, deprel=True, save_to=None):
| """
Processes the input file (must be a conllu file) and outputs the charlevel encoded matrices.
If save_to is a valid output filename it will save it
:param fname:
:param char2int_codebook:
:param upos2int:
:param deprel2int:
:param deprel:
:param save_to:
:return: the entire fi... | conll2seq ", e)
pass
ret = list_ind_charseq
if return_chars:
ret = (list_charseq, list_ind_charseq)
return ret
def process_conllu_file(fname, char2int_codebook, upos2int, deprel2int, deprel=True, save_to=None):
| 73 | 73 | 244 | 33 | 39 | leomrocha/minibrain | predictors/sequence/text/langmodels/utils/preprocess_conllu.py | Python | process_conllu_file | process_conllu_file | 164 | 183 | 164 | 164 | bf97572ac1ef0b00505ae0ffc6c7be6f314424db | bigcode/the-stack | train |
33051239e07e1348ec4a2f16 | train | class | class BooleanField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be either True or False."),
}
description = _("Boolean (Either True or False)")
def __init__(self, *args, **kwargs):
kwargs['blank'] = True
if 'default' not in k... | class BooleanField(Field):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be either True or False."),
}
description = _("Boolean (Either True or False)")
def __init__(self, *args, **kwargs):
kwargs['blank'] = True
if 'default' not in kwargs and not kwargs.get('n... | prepared:
value = self.get_prep_value(value)
value = connection.ops.validate_autopk_value(value)
return value
def get_prep_value(self, value):
if value is None:
return None
return int(value)
def contribute_to_class(self, cls, name):
assert n... | 140 | 140 | 468 | 5 | 134 | five3/django | django/db/models/fields/__init__.py | Python | BooleanField | BooleanField | 564 | 617 | 564 | 564 | 8acfaec9cfe4b80648f010dc5cd8e3563cabc3a1 | bigcode/the-stack | train |
debd1b33b46c52b579f95170 | train | class | class TimeField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value has an invalid format. It must be in "
"HH:MM[:ss[.uuuuuu]] format."),
'invalid_time': _("'%s' value has the correct format "
"(HH:MM[:ss[.uuuu... | class TimeField(Field):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value has an invalid format. It must be in "
"HH:MM[:ss[.uuuuuu]] format."),
'invalid_time': _("'%s' value has the correct format "
"(HH:MM[:ss[.uuuuuu]]) but it is an inval... | formfield(self, **kwargs):
defaults = {'form_class': forms.SlugField}
defaults.update(kwargs)
return super(SlugField, self).formfield(**defaults)
class SmallIntegerField(IntegerField):
description = _("Small integer")
def get_internal_type(self):
return "SmallIntegerField"
cl... | 166 | 166 | 556 | 5 | 161 | five3/django | django/db/models/fields/__init__.py | Python | TimeField | TimeField | 1,199 | 1,266 | 1,199 | 1,199 | 75e7b32fddcf32c69452825d1cdacecd40834253 | bigcode/the-stack | train |
62a226c68542c4d814849abd | train | class | class URLField(CharField):
description = _("URL")
def __init__(self, verbose_name=None, name=None, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
CharField.__init__(self, verbose_name, name, **kwargs)
self.validators.append(validators.URLValidator())
def formfield(... | class URLField(CharField):
| description = _("URL")
def __init__(self, verbose_name=None, name=None, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
CharField.__init__(self, verbose_name, name, **kwargs)
self.validators.append(validators.URLValidator())
def formfield(self, **kwargs):
# ... | self._get_val_from_obj(obj)
return '' if val is None else val.isoformat()
def formfield(self, **kwargs):
defaults = {'form_class': forms.TimeField}
defaults.update(kwargs)
return super(TimeField, self).formfield(**defaults)
class URLField(CharField):
| 64 | 64 | 132 | 6 | 58 | five3/django | django/db/models/fields/__init__.py | Python | URLField | URLField | 1,268 | 1,283 | 1,268 | 1,268 | 405ac935c2513b24410d85cd93950cce2834e6ca | bigcode/the-stack | train |
4d52bac78b5d9d30f0c6091c | train | class | class BigIntegerField(IntegerField):
empty_strings_allowed = False
description = _("Big (8 byte) integer")
MAX_BIGINT = 9223372036854775807
def get_internal_type(self):
return "BigIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1,... | class BigIntegerField(IntegerField):
| empty_strings_allowed = False
description = _("Big (8 byte) integer")
MAX_BIGINT = 9223372036854775807
def get_internal_type(self):
return "BigIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1,
'max_value': Big... | msg = self.error_messages['invalid'] % value
raise exceptions.ValidationError(msg)
def formfield(self, **kwargs):
defaults = {'form_class': forms.IntegerField}
defaults.update(kwargs)
return super(IntegerField, self).formfield(**defaults)
class BigIntegerField(Intege... | 64 | 64 | 111 | 7 | 57 | five3/django | django/db/models/fields/__init__.py | Python | BigIntegerField | BigIntegerField | 1,013 | 1,025 | 1,013 | 1,013 | 26fa3a98e4354c69c45cfe2531ef81cf3c94ff58 | bigcode/the-stack | train |
3953a0f6e851b204d079bea1 | train | class | class EmailField(CharField):
default_validators = [validators.validate_email]
description = _("E-mail address")
def __init__(self, *args, **kwargs):
# max_length should be overridden to 254 characters to be fully
# compliant with RFCs 3696 and 5321
kwargs['max_length'] = kwargs.get... | class EmailField(CharField):
| default_validators = [validators.validate_email]
description = _("E-mail address")
def __init__(self, *args, **kwargs):
# max_length should be overridden to 254 characters to be fully
# compliant with RFCs 3696 and 5321
kwargs['max_length'] = kwargs.get('max_length', 75)
Ch... | (self, **kwargs):
defaults = {
'max_digits': self.max_digits,
'decimal_places': self.decimal_places,
'form_class': forms.DecimalField,
}
defaults.update(kwargs)
return super(DecimalField, self).formfield(**defaults)
class EmailField(CharField):
| 64 | 64 | 159 | 6 | 58 | five3/django | django/db/models/fields/__init__.py | Python | EmailField | EmailField | 904 | 922 | 904 | 904 | b920b019647e75f9c65b7fc41b562d0e1d1e6e65 | bigcode/the-stack | train |
cabaa073754db6dc6b90ab07 | train | class | class PositiveSmallIntegerField(IntegerField):
description = _("Positive small integer")
def get_internal_type(self):
return "PositiveSmallIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': 0}
defaults.update(kwargs)
return super(PositiveSmallIntegerField... | class PositiveSmallIntegerField(IntegerField):
| description = _("Positive small integer")
def get_internal_type(self):
return "PositiveSmallIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': 0}
defaults.update(kwargs)
return super(PositiveSmallIntegerField, self).formfield(**defaults)
| Positive integer")
def get_internal_type(self):
return "PositiveIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': 0}
defaults.update(kwargs)
return super(PositiveIntegerField, self).formfield(**defaults)
class PositiveSmallIntegerField(IntegerField):
| 64 | 64 | 71 | 8 | 56 | five3/django | django/db/models/fields/__init__.py | Python | PositiveSmallIntegerField | PositiveSmallIntegerField | 1,148 | 1,157 | 1,148 | 1,148 | 045c166a47a28b24e1fe03389de08845cc99f097 | bigcode/the-stack | train |
534643f4e3feaa7656c032f7 | train | class | class TextField(Field):
description = _("Text")
def get_internal_type(self):
return "TextField"
def get_prep_value(self, value):
if isinstance(value, six.string_types) or value is None:
return value
return smart_unicode(value)
def formfield(self, **kwargs):
... | class TextField(Field):
| description = _("Text")
def get_internal_type(self):
return "TextField"
def get_prep_value(self, value):
if isinstance(value, six.string_types) or value is None:
return value
return smart_unicode(value)
def formfield(self, **kwargs):
defaults = {'widget': f... | defaults = {'form_class': forms.SlugField}
defaults.update(kwargs)
return super(SlugField, self).formfield(**defaults)
class SmallIntegerField(IntegerField):
description = _("Small integer")
def get_internal_type(self):
return "SmallIntegerField"
class TextField(Field):
| 64 | 64 | 95 | 5 | 59 | five3/django | django/db/models/fields/__init__.py | Python | TextField | TextField | 1,183 | 1,197 | 1,183 | 1,183 | 6c60fd7f16408899907bbf8171db6f59d7848d85 | bigcode/the-stack | train |
7e79cf8bbcb912e25f14f0f7 | train | class | class GenericIPAddressField(Field):
empty_strings_allowed = True
description = _("IP address")
default_error_messages = {}
def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs):
self.unpack_ipv4 = unpack_ipv4
self.default_validators, invalid_error_message = \
... | class GenericIPAddressField(Field):
| empty_strings_allowed = True
description = _("IP address")
default_error_messages = {}
def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs):
self.unpack_ipv4 = unpack_ipv4
self.default_validators, invalid_error_message = \
validators.ip_address_validators(... | *args, **kwargs):
kwargs['max_length'] = 15
Field.__init__(self, *args, **kwargs)
def get_internal_type(self):
return "IPAddressField"
def formfield(self, **kwargs):
defaults = {'form_class': forms.IPAddressField}
defaults.update(kwargs)
return super(IPAddressF... | 88 | 88 | 295 | 6 | 82 | five3/django | django/db/models/fields/__init__.py | Python | GenericIPAddressField | GenericIPAddressField | 1,043 | 1,081 | 1,043 | 1,043 | 3840435157460ce7f08dce6164910150a02ac5ec | bigcode/the-stack | train |
d8ba4d5c2d953916649cb00b | train | class | class NOT_PROVIDED:
pass
| class NOT_PROVIDED:
| pass
| , total_ordering
from django.utils.text import capfirst
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode, force_unicode
from django.utils.ipv6 import clean_ipv6_address
from django.utils import six
class NOT_PROVIDED:
| 64 | 64 | 9 | 6 | 57 | five3/django | django/db/models/fields/__init__.py | Python | NOT_PROVIDED | NOT_PROVIDED | 26 | 27 | 26 | 26 | 21851e69c3952c979fd5f943d56360fb47c5c6c7 | bigcode/the-stack | train |
105628bb9b07a1c6454a52e0 | train | class | class FieldDoesNotExist(Exception):
pass
| class FieldDoesNotExist(Exception):
| pass
| ED:
pass
# The values to use for "blank" in SelectFields. Will be appended to the start
# of most "choices" lists.
BLANK_CHOICE_DASH = [("", "---------")]
BLANK_CHOICE_NONE = [("", "None")]
class FieldDoesNotExist(Exception):
| 63 | 64 | 10 | 7 | 56 | five3/django | django/db/models/fields/__init__.py | Python | FieldDoesNotExist | FieldDoesNotExist | 34 | 35 | 34 | 34 | a1e5502a6f3143b8d3224cd33cd1f3a63ef919be | bigcode/the-stack | train |
cc602549cd32c9a073ee9d12 | train | class | class DateTimeField(DateField):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value has an invalid format. It must be in "
"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
'invalid_date': _("'%s' value has the correct format "
... | class DateTimeField(DateField):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value has an invalid format. It must be in "
"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
'invalid_date': _("'%s' value has the correct format "
"(YYYY-MM-DD) but it is an... | _previous_by_FIELD, field=self,
is_next=False))
def get_prep_lookup(self, lookup_type, value):
# For "__month", "__day", and "__week_day" lookups, convert the value
# to an int so the database backend always sees a consistent type.
if lookup_type in ('month', 'day', 'w... | 247 | 247 | 826 | 7 | 240 | five3/django | django/db/models/fields/__init__.py | Python | DateTimeField | DateTimeField | 747 | 842 | 747 | 747 | e3b230678e5dcd2709c094cf2f34bb1889624d51 | bigcode/the-stack | train |
4905c930e75812a32180c06f | train | class | class AutoField(Field):
description = _("Integer")
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be an integer."),
}
def __init__(self, *args, **kwargs):
assert kwargs.get('primary_key', False) is True, \
"%ss must have primar... | class AutoField(Field):
| description = _("Integer")
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be an integer."),
}
def __init__(self, *args, **kwargs):
assert kwargs.get('primary_key', False) is True, \
"%ss must have primary_key=True." % self.__cl... | return getattr(obj, self.attname)
def __repr__(self):
"""
Displays the module, class and name of the field.
"""
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
name = getattr(self, 'name', None)
if name is not None:
return '<... | 101 | 101 | 338 | 5 | 95 | five3/django | django/db/models/fields/__init__.py | Python | AutoField | AutoField | 514 | 562 | 514 | 514 | 663b205c53920e5743f84eaf108e6cf9f3d2f1d5 | bigcode/the-stack | train |
40b96fe7c41254985428808a | train | class | class IPAddressField(Field):
empty_strings_allowed = False
description = _("IPv4 address")
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 15
Field.__init__(self, *args, **kwargs)
def get_internal_type(self):
return "IPAddressField"
def formfield(self, **kwargs... | class IPAddressField(Field):
| empty_strings_allowed = False
description = _("IPv4 address")
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 15
Field.__init__(self, *args, **kwargs)
def get_internal_type(self):
return "IPAddressField"
def formfield(self, **kwargs):
defaults = {'form_... | def formfield(self, **kwargs):
defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1,
'max_value': BigIntegerField.MAX_BIGINT}
defaults.update(kwargs)
return super(BigIntegerField, self).formfield(**defaults)
class IPAddressField(Field):
| 64 | 64 | 110 | 6 | 58 | five3/django | django/db/models/fields/__init__.py | Python | IPAddressField | IPAddressField | 1,027 | 1,041 | 1,027 | 1,027 | d44d4c7cd606449b64257ae1b70c4be8727e5f52 | bigcode/the-stack | train |
db75ea2f4c8b2002c35ca8ba | train | class | @total_ordering
class Field(object):
"""Base class for all field types"""
# Designates whether empty strings fundamentally are allowed at the
# database level.
empty_strings_allowed = True
# These track each time a Field instance is created. Used to retain order.
# The auto_creation_counter is... | @total_ordering
class Field(object):
| """Base class for all field types"""
# Designates whether empty strings fundamentally are allowed at the
# database level.
empty_strings_allowed = True
# These track each time a Field instance is created. Used to retain order.
# The auto_creation_counter is used for fields that Django implicit... | clean_ipv6_address
from django.utils import six
class NOT_PROVIDED:
pass
# The values to use for "blank" in SelectFields. Will be appended to the start
# of most "choices" lists.
BLANK_CHOICE_DASH = [("", "---------")]
BLANK_CHOICE_NONE = [("", "None")]
class FieldDoesNotExist(Exception):
pass
# A guide to... | 256 | 256 | 3,680 | 9 | 247 | five3/django | django/db/models/fields/__init__.py | Python | Field | Field | 52 | 512 | 52 | 53 | dbcca03549690454648552e11bbc4b3cafd2654a | bigcode/the-stack | train |
2216e7d863166403f4e7c05a | train | class | class CommaSeparatedIntegerField(CharField):
default_validators = [validators.validate_comma_separated_integer_list]
description = _("Comma-separated integers")
def formfield(self, **kwargs):
defaults = {
'error_messages': {
'invalid': _('Enter only digits separated by c... | class CommaSeparatedIntegerField(CharField):
| default_validators = [validators.validate_comma_separated_integer_list]
description = _("Comma-separated integers")
def formfield(self, **kwargs):
defaults = {
'error_messages': {
'invalid': _('Enter only digits separated by commas.'),
}
}
def... | value in the form field (to pass into widget for example).
defaults = {'max_length': self.max_length}
defaults.update(kwargs)
return super(CharField, self).formfield(**defaults)
# TODO: Maybe move this into contrib, because it's specialized.
class CommaSeparatedIntegerField(CharField):
| 64 | 64 | 89 | 9 | 55 | five3/django | django/db/models/fields/__init__.py | Python | CommaSeparatedIntegerField | CommaSeparatedIntegerField | 646 | 657 | 646 | 646 | 5e2d883c2e3b2e19b59e944961cdef087566b2da | bigcode/the-stack | train |
e06a72a463c747b0d8e16e26 | train | class | class PositiveIntegerField(IntegerField):
description = _("Positive integer")
def get_internal_type(self):
return "PositiveIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': 0}
defaults.update(kwargs)
return super(PositiveIntegerField, self).formfield(**d... | class PositiveIntegerField(IntegerField):
| description = _("Positive integer")
def get_internal_type(self):
return "PositiveIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': 0}
defaults.update(kwargs)
return super(PositiveIntegerField, self).formfield(**defaults)
| 'form_class': forms.NullBooleanField,
'required': not self.blank,
'label': capfirst(self.verbose_name),
'help_text': self.help_text}
defaults.update(kwargs)
return super(NullBooleanField, self).formfield(**defaults)
class PositiveIntegerField(IntegerField)... | 64 | 64 | 67 | 7 | 57 | five3/django | django/db/models/fields/__init__.py | Python | PositiveIntegerField | PositiveIntegerField | 1,137 | 1,146 | 1,137 | 1,137 | 7fe0fa4a2914ce5383b3f3a8a50708312037a7a6 | bigcode/the-stack | train |
e88bc63c355268ee30cc1023 | train | class | class FilePathField(Field):
description = _("File path")
def __init__(self, verbose_name=None, name=None, path='', match=None,
recursive=False, allow_files=True, allow_folders=False, **kwargs):
self.path, self.match, self.recursive = path, match, recursive
self.allow_files, sel... | class FilePathField(Field):
| description = _("File path")
def __init__(self, verbose_name=None, name=None, path='', match=None,
recursive=False, allow_files=True, allow_folders=False, **kwargs):
self.path, self.match, self.recursive = path, match, recursive
self.allow_files, self.allow_folders = allow_fil... | , **kwargs):
# As with CharField, this will cause email validation to be performed
# twice.
defaults = {
'form_class': forms.EmailField,
}
defaults.update(kwargs)
return super(EmailField, self).formfield(**defaults)
class FilePathField(Field):
| 64 | 64 | 214 | 6 | 58 | five3/django | django/db/models/fields/__init__.py | Python | FilePathField | FilePathField | 924 | 947 | 924 | 924 | 8ee80bd3685db85e0ffe9e417e364352deefb603 | bigcode/the-stack | train |
49f7aca23756c7f99c697c4c | train | class | class CharField(Field):
description = _("String (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
super(CharField, self).__init__(*args, **kwargs)
self.validators.append(validators.MaxLengthValidator(self.max_length))
def get_internal_type(self):
return "CharField"
... | class CharField(Field):
| description = _("String (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
super(CharField, self).__init__(*args, **kwargs)
self.validators.append(validators.MaxLengthValidator(self.max_length))
def get_internal_type(self):
return "CharField"
def to_python(self, val... | .has_default() or 'initial' in kwargs))
defaults = {'choices': self.get_choices(
include_blank=include_blank)}
else:
defaults = {'form_class': forms.BooleanField}
defaults.update(kwargs)
return super(BooleanField, self).formfield(**d... | 64 | 64 | 206 | 5 | 59 | five3/django | django/db/models/fields/__init__.py | Python | CharField | CharField | 619 | 643 | 619 | 619 | 511838f0c2b3a81d1321801848de0d589008e567 | bigcode/the-stack | train |
ad7becdeddb0da2c84111deb | train | class | class SmallIntegerField(IntegerField):
description = _("Small integer")
def get_internal_type(self):
return "SmallIntegerField"
| class SmallIntegerField(IntegerField):
| description = _("Small integer")
def get_internal_type(self):
return "SmallIntegerField"
| , **kwargs)
def get_internal_type(self):
return "SlugField"
def formfield(self, **kwargs):
defaults = {'form_class': forms.SlugField}
defaults.update(kwargs)
return super(SlugField, self).formfield(**defaults)
class SmallIntegerField(IntegerField):
| 64 | 64 | 28 | 7 | 57 | five3/django | django/db/models/fields/__init__.py | Python | SmallIntegerField | SmallIntegerField | 1,177 | 1,181 | 1,177 | 1,177 | 1254e89a839f065609eb3b4e19ab832eb021a750 | bigcode/the-stack | train |
d430f31cd1d3b956d0eab646 | train | class | class FloatField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be a float."),
}
description = _("Floating point number")
def get_prep_value(self, value):
if value is None:
return None
return float(value)
def g... | class FloatField(Field):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be a float."),
}
description = _("Floating point number")
def get_prep_value(self, value):
if value is None:
return None
return float(value)
def get_internal_type(self):
... | .FilePathField,
'allow_files': self.allow_files,
'allow_folders': self.allow_folders,
}
defaults.update(kwargs)
return super(FilePathField, self).formfield(**defaults)
def get_internal_type(self):
return "FilePathField"
class FloatField(Field):
| 64 | 64 | 172 | 5 | 59 | five3/django | django/db/models/fields/__init__.py | Python | FloatField | FloatField | 949 | 976 | 949 | 949 | 88c56e902e062c2000d6959fdfa2abf410247346 | bigcode/the-stack | train |
3a2a2c8581507f603d425f0a | train | class | class DecimalField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be a decimal number."),
}
description = _("Decimal number")
def __init__(self, verbose_name=None, name=None, max_digits=None,
decimal_places=None, **kwargs):
... | class DecimalField(Field):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be a decimal number."),
}
description = _("Decimal number")
def __init__(self, verbose_name=None, name=None, max_digits=None,
decimal_places=None, **kwargs):
self.max_digits, self... | _prep_value(self, value, connection, prepared=False):
# Casts datetimes into the format expected by the backend
if not prepared:
value = self.get_prep_value(value)
return connection.ops.value_to_db_datetime(value)
def value_to_string(self, obj):
val = self._get_val_from_... | 128 | 128 | 429 | 5 | 123 | five3/django | django/db/models/fields/__init__.py | Python | DecimalField | DecimalField | 844 | 902 | 844 | 844 | f9bd2743eeb6024452cfb82d2516e40b65374247 | bigcode/the-stack | train |
ca33e334836f35a06a305bba | train | class | class NullBooleanField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be either None, True or False."),
}
description = _("Boolean (Either True, False or None)")
def __init__(self, *args, **kwargs):
kwargs['null'] = True
kwargs... | class NullBooleanField(Field):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be either None, True or False."),
}
description = _("Boolean (Either True, False or None)")
def __init__(self, *args, **kwargs):
kwargs['null'] = True
kwargs['blank'] = True
Field.... | (self, value, connection, prepared=False):
if not prepared:
value = self.get_prep_value(value)
return value or None
def get_prep_value(self, value):
if value and ':' in value:
try:
return clean_ipv6_address(value, self.unpack_ipv4)
except ... | 123 | 123 | 411 | 6 | 117 | five3/django | django/db/models/fields/__init__.py | Python | NullBooleanField | NullBooleanField | 1,084 | 1,135 | 1,084 | 1,084 | eb89cadf4038e3aaffed9df11ddb9d9a12d5eae9 | bigcode/the-stack | train |
e466e4288a9cd598c5f1e3ab | train | class | class SlugField(CharField):
description = _("Slug (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 50)
# Set db_index=True unless it's been set manually.
if 'db_index' not in kwargs:
kwargs['db_index'] = True
... | class SlugField(CharField):
| description = _("Slug (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 50)
# Set db_index=True unless it's been set manually.
if 'db_index' not in kwargs:
kwargs['db_index'] = True
super(SlugField, self).__... | integer")
def get_internal_type(self):
return "PositiveSmallIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': 0}
defaults.update(kwargs)
return super(PositiveSmallIntegerField, self).formfield(**defaults)
class SlugField(CharField):
| 64 | 64 | 149 | 7 | 57 | five3/django | django/db/models/fields/__init__.py | Python | SlugField | SlugField | 1,159 | 1,175 | 1,159 | 1,159 | 1f6727c764027b87ba70813edea10d9cb0c83084 | bigcode/the-stack | train |
234d0a02b1854ecda2f44314 | train | class | class IntegerField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be an integer."),
}
description = _("Integer")
def get_prep_value(self, value):
if value is None:
return None
return int(value)
def get_prep_loo... | class IntegerField(Field):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value must be an integer."),
}
description = _("Integer")
def get_prep_value(self, value):
if value is None:
return None
return int(value)
def get_prep_lookup(self, lookup_type, valu... | (TypeError, ValueError):
msg = self.error_messages['invalid'] % value
raise exceptions.ValidationError(msg)
def formfield(self, **kwargs):
defaults = {'form_class': forms.FloatField}
defaults.update(kwargs)
return super(FloatField, self).formfield(**defaults)
class ... | 69 | 69 | 231 | 5 | 64 | five3/django | django/db/models/fields/__init__.py | Python | IntegerField | IntegerField | 978 | 1,011 | 978 | 978 | ffe0d0556295cd053bf739710a6339d864390d9e | bigcode/the-stack | train |
733900cc1b51595f35b6c403 | train | class | class DateField(Field):
empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value has an invalid date format. It must be "
"in YYYY-MM-DD format."),
'invalid_date': _("'%s' value has the correct format (YYYY-MM-DD) "
"but it ... | class DateField(Field):
| empty_strings_allowed = False
default_error_messages = {
'invalid': _("'%s' value has an invalid date format. It must be "
"in YYYY-MM-DD format."),
'invalid_date': _("'%s' value has the correct format (YYYY-MM-DD) "
"but it is an invalid date."),
... | is None:
return value
return smart_unicode(value)
def get_prep_value(self, value):
return self.to_python(value)
def formfield(self, **kwargs):
# Passing max_length to forms.CharField means that the value's length
# will be validated twice. This is considered accept... | 222 | 222 | 741 | 5 | 217 | five3/django | django/db/models/fields/__init__.py | Python | DateField | DateField | 659 | 745 | 659 | 659 | 84c78c9c75fe2935c1c8a7a0fdceaa887d6d02ae | bigcode/the-stack | train |
a6120f27b7c222831eee4a35 | train | class | class UserManager(BaseUserManager):
def _create_user(self, password, **extra_fields):
"""
Creates and saves a User with the given email,and password.
"""
try:
user = self.model(**extra_fields)
user.set_password(password)
user.save(using=self._db)
... | class UserManager(BaseUserManager):
| def _create_user(self, password, **extra_fields):
"""
Creates and saves a User with the given email,and password.
"""
try:
user = self.model(**extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
excep... | from django.contrib.auth.models import (
AbstractBaseUser, PermissionsMixin, BaseUserManager
)
class UserManager(BaseUserManager):
| 27 | 64 | 197 | 7 | 20 | kenalizadeh/Olaf-Food-Delivery-Backend | olaf/user/managers.py | Python | UserManager | UserManager | 6 | 32 | 6 | 7 | ff862d531e9b13669829440f9661a8b1533eee19 | bigcode/the-stack | train |
d5d60800238e68e803de20f7 | train | function | def keyPressed(tecla, x, y):
print("Tecla %s %d %d" % (tecla,x,y))
global dx, dy, dz
if tecla == b'\x1b': # ESCAPE
glutLeaveMainLoop()
elif tecla == b'x' or tecla == b'X':
print('x')
dx = 0.5
dy = 0
dz = 0
elif tecla == b'y' or tecla == b'Y':
print... | def keyPressed(tecla, x, y):
| print("Tecla %s %d %d" % (tecla,x,y))
global dx, dy, dz
if tecla == b'\x1b': # ESCAPE
glutLeaveMainLoop()
elif tecla == b'x' or tecla == b'X':
print('x')
dx = 0.5
dy = 0
dz = 0
elif tecla == b'y' or tecla == b'Y':
print('y')
dx = 0
... | xrot = xrot + 0.02 # X rotation
#yrot = yrot + 0.02 # Y rotation
#zrot = zrot + 0.02 # Z rotation
glutSwapBuffers()
def keyPressed(tecla, x, y):
| 64 | 64 | 175 | 10 | 54 | allan8991/Computacao_grafica | dado/dado.py | Python | keyPressed | keyPressed | 124 | 143 | 124 | 124 | 8e309a3d542395a6f5c0099db2c63208cf5b8580 | bigcode/the-stack | train |
f5df14766b0a7c996eff64de | train | function | def main():
global window
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
# get a 640 x 480 window
glutInitWindowSize(640, 480)
# the window starts at the upper left corner of the screen
glutInitWindowPosition(0, 0)
window = glutCreateWindow... | def main():
| global window
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
# get a 640 x 480 window
glutInitWindowSize(640, 480)
# the window starts at the upper left corner of the screen
glutInitWindowPosition(0, 0)
window = glutCreateWindow("Textura")
... | ("DIREITA")
xrot += dx # X rotation
yrot += dy # Y rotation
zrot += dz
elif tecla == GLUT_KEY_UP:
print("CIMA")
elif tecla == GLUT_KEY_DOWN:
print("BAIXO")
def main():
| 64 | 64 | 203 | 3 | 61 | allan8991/Computacao_grafica | dado/dado.py | Python | main | main | 163 | 194 | 163 | 163 | 445431c746f3b4ea9c6d25256128b5f4085da62a | bigcode/the-stack | train |
d4894cbd621d33db390a1e6c | train | function | def teclaEspecialPressionada(tecla, x, y):
global xrot, yrot, zrot, dx, dy, dz
if tecla == GLUT_KEY_LEFT:
print("ESQUERDA")
xrot -= dx # X rotation
yrot -= dy # Y rotation
zrot -= dz
elif tecla == GLUT_KEY_RIGHT:
pri... | def teclaEspecialPressionada(tecla, x, y):
| global xrot, yrot, zrot, dx, dy, dz
if tecla == GLUT_KEY_LEFT:
print("ESQUERDA")
xrot -= dx # X rotation
yrot -= dy # Y rotation
zrot -= dz
elif tecla == GLUT_KEY_RIGHT:
print("DIREITA")
xrot += dx ... | = 0.5
dz = 0
elif tecla == b'z' or tecla == b'Z':
print('z')
dx = 0
dy = 0
dz = 0.5
def teclaEspecialPressionada(tecla, x, y):
| 64 | 64 | 143 | 13 | 50 | allan8991/Computacao_grafica | dado/dado.py | Python | teclaEspecialPressionada | teclaEspecialPressionada | 145 | 161 | 145 | 145 | 7bd8120d1385bc07d3d4ec4bd7516830469d5b9c | bigcode/the-stack | train |
bb175d0f5d6aa7d2a7b9f739 | train | function | def DrawGLScene():
global xrot, yrot, zrot, texture
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glClearColor(0.5,0.5,0.5,1.0)
glTranslatef(0.0,0.0,-5.0)
glRotatef(xrot,1.0,0.0,0.0)
glRotatef(yrot,0.0,1.0,0.0)
gl... | def DrawGLScene():
| global xrot, yrot, zrot, texture
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glClearColor(0.5,0.5,0.5,1.0)
glTranslatef(0.0,0.0,-5.0)
glRotatef(xrot,1.0,0.0,0.0)
glRotatef(yrot,0.0,1.0,0.0)
glRotatef(zrot,0.0,0.... | glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
################################################################################
def InitGL(Width, Height):
LoadTextures()
glEnable(GL_TEXTURE_2D)
glClearColor(0.... | 256 | 256 | 1,150 | 5 | 251 | allan8991/Computacao_grafica | dado/dado.py | Python | DrawGLScene | DrawGLScene | 66 | 121 | 66 | 66 | 52eb8e2a615f268163556627505aa6454997f5d3 | bigcode/the-stack | train |
6aba0b616e1b3d1b752fcbc8 | train | function | def ReSizeGLScene(Width, Height):
if Height == 0:
Height = 1
glViewport(0, 0, Width, Height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
| def ReSizeGLScene(Width, Height):
| if Height == 0:
Height = 1
glViewport(0, 0, Width, Height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
| )
glShadeModel(GL_SMOOTH)
glMatrixMode(GL_PROJECTION)
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
def ReSizeGLScene(Width, Height):
| 64 | 64 | 85 | 10 | 54 | allan8991/Computacao_grafica | dado/dado.py | Python | ReSizeGLScene | ReSizeGLScene | 57 | 64 | 57 | 57 | 5c95af175af1562340c254d76293e1d6cfe085d3 | bigcode/the-stack | train |
491ab2f73cadfa971de7138f | train | function | def InitGL(Width, Height):
LoadTextures()
glEnable(GL_TEXTURE_2D)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
glMatrixMode(GL_PROJECTION)
gluPerspective(45... | def InitGL(Width, Height):
| LoadTextures()
glEnable(GL_TEXTURE_2D)
glClearColor(0.0, 0.0, 0.0, 0.0)
glClearDepth(1.0)
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
glMatrixMode(GL_PROJECTION)
gluPerspective(45.0, float(Width)/float(Height), 0.1, 100... | _2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
################################################################################
def InitGL(Width, Height):
| 64 | 64 | 125 | 9 | 54 | allan8991/Computacao_grafica | dado/dado.py | Python | InitGL | InitGL | 45 | 55 | 45 | 45 | d742eb9419a58b845fe1beb6780b54e5a6a69e9d | bigcode/the-stack | train |
6bb6c79defb098eea0ddcef5 | train | function | def LoadTextures():
global texture
texture = glGenTextures(2) # Gera 2 IDs para as texturas
################################################################################
reader = png.Reader(filename='dado.png')
w, h, pixels, metadata = reader.read_flat()
if(metadata['alpha']):
modo =... | def LoadTextures():
| global texture
texture = glGenTextures(2) # Gera 2 IDs para as texturas
################################################################################
reader = png.Reader(filename='dado.png')
w, h, pixels, metadata = reader.read_flat()
if(metadata['alpha']):
modo = GL_RGBA
else:
... | al string
# so instead of saying: ESCAPE = 27, we use the following.
ESCAPE = '\033'
# Number of the glut window.
window = 0
# Rotations for cube.
xrot = yrot = zrot = 0.0
dx = 0
dy = 0
dz = 0
# texture = []
def LoadTextures():
| 82 | 82 | 274 | 4 | 78 | allan8991/Computacao_grafica | dado/dado.py | Python | LoadTextures | LoadTextures | 22 | 42 | 22 | 22 | 4c0582012892a0bbdc8e1ea386360096a3175a8f | bigcode/the-stack | train |
fd757b471cfbcd3ea4c4d813 | train | function | def vnc(request, instance_id):
try:
console = api.server_vnc_console(request, instance_id)
instance = api.server_get(request, instance_id)
return shortcuts.redirect(console.url +
("&title=%s(%s)" % (instance.name, instance_id)))
except:
redirect = reverse("horizon... | def vnc(request, instance_id):
| try:
console = api.server_vnc_console(request, instance_id)
instance = api.server_get(request, instance_id)
return shortcuts.redirect(console.url +
("&title=%s(%s)" % (instance.name, instance_id)))
except:
redirect = reverse("horizon:nova:instances_and_volumes:ind... | tail)
except:
data = _('Unable to get log for instance "%s".') % instance_id
exceptions.handle(request, ignore=True)
response = http.HttpResponse(mimetype='text/plain')
response.write(data)
response.flush()
return response
def vnc(request, instance_id):
| 64 | 64 | 109 | 8 | 55 | StackOps/horizon | horizon/dashboards/nova/instances_and_volumes/instances/views.py | Python | vnc | vnc | 58 | 67 | 58 | 58 | ad3ab378ed9bd87f00752ee82bc93d79e2c2d4ff | bigcode/the-stack | train |
74926dfe4cba708b90442d64 | train | class | class DetailView(tabs.TabView):
tab_group_class = InstanceDetailTabs
template_name = 'nova/instances_and_volumes/instances/detail.html'
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
context["instance"] = self.get_data()
return con... | class DetailView(tabs.TabView):
| tab_group_class = InstanceDetailTabs
template_name = 'nova/instances_and_volumes/instances/detail.html'
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
context["instance"] = self.get_data()
return context
def get_data(self):
... | ")
msg = _('Unable to retrieve instance details.')
exceptions.handle(self.request, msg, redirect=redirect)
return self.object
def get_initial(self):
return {'instance': self.kwargs['instance_id'],
'tenant_id': self.request.user.tenant_id,
... | 79 | 79 | 265 | 8 | 71 | StackOps/horizon | horizon/dashboards/nova/instances_and_volumes/instances/views.py | Python | DetailView | DetailView | 92 | 123 | 92 | 92 | 6e36bb0f9374d91f69c8f07420f96c388a866370 | bigcode/the-stack | train |
946d3121a5a06e50456d67f7 | train | function | def console(request, instance_id):
try:
# TODO(jakedahn): clean this up once the api supports tailing.
tail = request.GET.get('length', None)
data = api.server_console_output(request,
instance_id,
tail_length=tai... | def console(request, instance_id):
| try:
# TODO(jakedahn): clean this up once the api supports tailing.
tail = request.GET.get('length', None)
data = api.server_console_output(request,
instance_id,
tail_length=tail)
except:
data = _('Un... | import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import api
from horizon import exceptions
from horizon import forms
from horizon import tabs
from .forms import UpdateInstance
from .tabs import InstanceDetailTabs
LOG = logging.getLogger(__name__)
def console(request, instance_id):... | 64 | 64 | 111 | 7 | 57 | StackOps/horizon | horizon/dashboards/nova/instances_and_volumes/instances/views.py | Python | console | console | 42 | 55 | 42 | 42 | 5542869ee9e90a447e13ec497b72f49b7984cd86 | bigcode/the-stack | train |
fab4707c8b83a7637d90e18a | train | class | class UpdateView(forms.ModalFormView):
form_class = UpdateInstance
template_name = 'nova/instances_and_volumes/instances/update.html'
context_object_name = 'instance'
def get_object(self, *args, **kwargs):
if not hasattr(self, "object"):
instance_id = self.kwargs['instance_id']
... | class UpdateView(forms.ModalFormView):
| form_class = UpdateInstance
template_name = 'nova/instances_and_volumes/instances/update.html'
context_object_name = 'instance'
def get_object(self, *args, **kwargs):
if not hasattr(self, "object"):
instance_id = self.kwargs['instance_id']
try:
self.objec... | .name, instance_id)))
except:
redirect = reverse("horizon:nova:instances_and_volumes:index")
msg = _('Unable to get VNC console for instance "%s".') % instance_id
exceptions.handle(request, msg, redirect=redirect)
class UpdateView(forms.ModalFormView):
| 64 | 64 | 177 | 9 | 55 | StackOps/horizon | horizon/dashboards/nova/instances_and_volumes/instances/views.py | Python | UpdateView | UpdateView | 70 | 89 | 70 | 70 | 9e710c0cfd428a0eb5e048465de603155bcb46e6 | bigcode/the-stack | train |
0d0c4f46a8bcaabb63d72306 | train | class | class Migration(migrations.Migration):
dependencies = [("shop", "0033_auto_20161212_1756")]
operations = [
migrations.AlterField(
model_name="creditnote",
name="pdf",
field=models.FileField(blank=True, null=True, upload_to="creditnotes/"),
),
migrati... | class Migration(migrations.Migration):
| dependencies = [("shop", "0033_auto_20161212_1756")]
operations = [
migrations.AlterField(
model_name="creditnote",
name="pdf",
field=models.FileField(blank=True, null=True, upload_to="creditnotes/"),
),
migrations.AlterField(
model_name="... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-31 17:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 89 | 298 | 7 | 46 | flokli/bornhack-website | src/shop/migrations/0034_auto_20170131_1849.py | Python | Migration | Migration | 8 | 56 | 8 | 9 | 6a13c7103a7ee2af28f6cb990fbf4f8641a1bedc | bigcode/the-stack | train |
9a31f280d08d6a97ef8b553e | train | class | class PerturbedSurface_p:
def __init__(self,waterLevel):
self.waterLevel=waterLevel
def uOfXT(self,x,t):
if ct.signedDistance(x) < 0:
return -(L[1] - self.waterLevel)*ct.rho_1*ct.g[1] - (self.waterLevel - x[1])*ct.rho_0*ct.g[1]
else:
return -(L[1] - self.waterLeve... | class PerturbedSurface_p:
| def __init__(self,waterLevel):
self.waterLevel=waterLevel
def uOfXT(self,x,t):
if ct.signedDistance(x) < 0:
return -(L[1] - self.waterLevel)*ct.rho_1*ct.g[1] - (self.waterLevel - x[1])*ct.rho_0*ct.g[1]
else:
return -(L[1] - self.waterLevel)*ct.rho_1*ct.g[1]
| usiveFluxBoundaryConditions = {0: {},
1: {1: lambda x, flag: domain.bc[flag].u_diffusive.init_cython()},
2: {2: lambda x, flag: domain.bc[flag].v_diffusive.init_cython()}}
class PerturbedSurface_p:
| 64 | 64 | 115 | 6 | 58 | dloney/proteus | proteus/tests/solver_tests_mprans/import_modules/twp_navier_stokes_p.py | Python | PerturbedSurface_p | PerturbedSurface_p | 172 | 179 | 172 | 172 | 005caaa90af316da875bcae91d8c15664b49a529 | bigcode/the-stack | train |
dcecf67ab85797e5840f2eb3 | train | class | class AtRest:
def __init__(self):
pass
def uOfXT(self,x,t):
return 0.0
| class AtRest:
| def __init__(self):
pass
def uOfXT(self,x,t):
return 0.0
| Level)*ct.rho_1*ct.g[1] - (self.waterLevel - x[1])*ct.rho_0*ct.g[1]
else:
return -(L[1] - self.waterLevel)*ct.rho_1*ct.g[1]
class AtRest:
| 64 | 64 | 30 | 4 | 60 | dloney/proteus | proteus/tests/solver_tests_mprans/import_modules/twp_navier_stokes_p.py | Python | AtRest | AtRest | 181 | 185 | 181 | 181 | 31e76ee29242d01b2db37c45a6a1e0caed02066e | bigcode/the-stack | train |
ca273cdf8972fd40052efc1e | train | class | class TestModuleUserApi(unittest.TestCase):
"""ModuleUserApi unit test stubs"""
def setUp(self):
self.api = ModuleUserApi() # noqa: E501
def tearDown(self):
pass
def test_user_create_ezsignuser_v1(self):
"""Test case for user_create_ezsignuser_v1
Create a new User of... | class TestModuleUserApi(unittest.TestCase):
| """ModuleUserApi unit test stubs"""
def setUp(self):
self.api = ModuleUserApi() # noqa: E501
def tearDown(self):
pass
def test_user_create_ezsignuser_v1(self):
"""Test case for user_create_ezsignuser_v1
Create a new User of type Ezsignuser # noqa: E501
"""
... | 1.7
Contact: support-api@ezmax.ca
Generated by: https://openapi-generator.tech
"""
import unittest
import eZmaxApi
from eZmaxApi.api.module_user_api import ModuleUserApi # noqa: E501
class TestModuleUserApi(unittest.TestCase):
| 64 | 64 | 98 | 9 | 54 | ezmaxinc/eZmax-SDK-python | test/test_module_user_api.py | Python | TestModuleUserApi | TestModuleUserApi | 18 | 32 | 18 | 18 | ae4c9709329ddd0858c0a56ec2d7f74a2559d048 | bigcode/the-stack | train |
8f3e8dcf7464fee2674698c1 | train | class | class Executor(JenkinsBase):
"""
Class to hold information on nodes that are attached as slaves to the
master jenkins instance
"""
def __init__(self, baseurl, nodename, jenkins_obj, number):
"""
Init a node object by providing all relevant pointers to it
:param baseurl: basi... | class Executor(JenkinsBase):
| """
Class to hold information on nodes that are attached as slaves to the
master jenkins instance
"""
def __init__(self, baseurl, nodename, jenkins_obj, number):
"""
Init a node object by providing all relevant pointers to it
:param baseurl: basic url for querying informatio... | """
Module for jenkinsapi Executer class
"""
from jenkinsapi.jenkinsbase import JenkinsBase
import logging
log = logging.getLogger(__name__)
class Executor(JenkinsBase):
| 39 | 103 | 345 | 6 | 33 | pkocandr/jenkinsapi | jenkinsapi/executor.py | Python | Executor | Executor | 11 | 63 | 11 | 11 | 0f55bf647c3a851f23e438504d7d9e3b1380e87d | bigcode/the-stack | train |
cc522352c18bde2159dec60c | train | class | class ProjectFlagsTest(unittest.TestCase):
def setUp(self):
self.obj = {
'objects': {
'0': {'isa': 'PBXProject', 'buildConfigurationList': '4a'},
'1': {'isa': 'PBXNativeTarget', 'name': 'app', 'buildConfigurationList': '3',
'buildPhases': ['c... | class ProjectFlagsTest(unittest.TestCase):
| def setUp(self):
self.obj = {
'objects': {
'0': {'isa': 'PBXProject', 'buildConfigurationList': '4a'},
'1': {'isa': 'PBXNativeTarget', 'name': 'app', 'buildConfigurationList': '3',
'buildPhases': ['compile']},
'2': {'isa': 'PB... | import unittest
from pbxproj.XcodeProject import *
class ProjectFlagsTest(unittest.TestCase):
| 20 | 256 | 4,261 | 8 | 12 | LZYongcn/mod-pbxproj | tests/pbxextensions/TestProjectFlags.py | Python | ProjectFlagsTest | ProjectFlagsTest | 5 | 314 | 5 | 5 | 74e60064649aa919d4d88c0018eec64c0efb8ab4 | bigcode/the-stack | train |
59bf16a10f9c8acf9c63b123 | train | class | @pytest.mark.skip("These are destructive, so run them manually")
class TestSpeechToTextV1(TestCase):
def setUp(self):
self.speech_to_text = watson_developer_cloud.SpeechToTextV1(username=os.getenv('SPEECH_TO_TEXT_USERNAME'),
password=os.get... | @pytest.mark.skip("These are destructive, so run them manually")
class TestSpeechToTextV1(TestCase):
| def setUp(self):
self.speech_to_text = watson_developer_cloud.SpeechToTextV1(username=os.getenv('SPEECH_TO_TEXT_USERNAME'),
password=os.getenv('SPEECH_TO_TEXT_PASSWORD'))
self.custom_models = self.speech_to_text.list_custom_models()... | from unittest import TestCase
import pytest
import os
import watson_developer_cloud
@pytest.mark.skip("These are destructive, so run them manually")
class TestSpeechToTextV1(TestCase):
| 42 | 64 | 175 | 23 | 18 | trishamoyer/python-sdk | test/test_integration_speech_to_text_v1.py | Python | TestSpeechToTextV1 | TestSpeechToTextV1 | 6 | 19 | 6 | 7 | da2e20b9b05e1fb7946210851f407b8f4fd3e49d | bigcode/the-stack | train |
6655267954b55645520cf8fb | train | class | class MyDataset_testset(Dataset):
CATEGORIES = [
"__background",
"person",
"bicycle",
"car",
"motorcycle",
"airplane",
"bus",
"train",
"truck",
"boat",
"traffic light",
"fire hydrant",
"stop sign",
"park... | class MyDataset_testset(Dataset):
| CATEGORIES = [
"__background",
"person",
"bicycle",
"car",
"motorcycle",
"airplane",
"bus",
"train",
"truck",
"boat",
"traffic light",
"fire hydrant",
"stop sign",
"parking meter",
"bench",
... | from maskrcnn_benchmark.structures.bounding_box import BoxList
from PIL import Image , ImageDraw
import torch , time
import pandas as pd
import numpy as np
import ast
from torch.utils.data import Dataset
class MyDataset_testset(Dataset):
| 55 | 256 | 1,422 | 8 | 46 | liatsasl/EAM_docker | modules/detector/maskrcnn_benchmark/data/datasets/mydataset_testset.py | Python | MyDataset_testset | MyDataset_testset | 9 | 206 | 9 | 10 | 6518f1c0d51bd0dd463073334802bddb624d45dc | bigcode/the-stack | train |
dd3a54b7ff7751f54b695e92 | train | class | class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def detect_cycle(self):
color = ['white'] * self.vertices
visited = [False] * self.vertices
stack = []
... | class Graph:
| def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def detect_cycle(self):
color = ['white'] * self.vertices
visited = [False] * self.vertices
stack = []
for v i... | - vertices that are not processed (inital state of all vertices)
Gray - vertices that are in DFS
Black - fully traversed vertices (i.e its progenies are also done)
If while traversing any adjacent node is colored Gray, that means cycle exists
"""
from collections import defaultdict
class Graph:
| 64 | 64 | 174 | 3 | 60 | eengineergz/Lambda | 2-resources/_External-learning-resources/02-pyth/python-ds-master/data_structures/graphs/cycle_in_directed_graph_using_colors.py | Python | Graph | Graph | 12 | 47 | 12 | 13 | 65c3bef3f5450845f41faadd2b225dcb7f3e42cd | bigcode/the-stack | train |
79bf3cbffe46ccc06c406359 | train | function | def experiment(n_epochs, n_iterations, ep_per_run, save_states_to_disk):
np.random.seed()
# MDP
mdp = LQR.generate(dimensions=2, max_pos=10., max_action=5., episodic=True)
approximator = Regressor(LinearApproximator,
input_shape=mdp.info.observation_space.shape,
... | def experiment(n_epochs, n_iterations, ep_per_run, save_states_to_disk):
| np.random.seed()
# MDP
mdp = LQR.generate(dimensions=2, max_pos=10., max_action=5., episodic=True)
approximator = Regressor(LinearApproximator,
input_shape=mdp.info.observation_space.shape,
output_shape=mdp.info.action_space.shape)
sigma =... | .algorithms.policy_search import REINFORCE
from mushroom_rl.approximators.parametric import LinearApproximator
from mushroom_rl.approximators.regressor import Regressor
from mushroom_rl.core import Core
from mushroom_rl.environments import LQR
from mushroom_rl.policy import StateStdGaussianPolicy
from mushroom_rl.utils... | 129 | 129 | 431 | 17 | 111 | k4ntz/mushroom-rl | examples/plotting_and_normalization.py | Python | experiment | experiment | 28 | 77 | 28 | 28 | bf271958b4a4727db06bf19ef7432223afbfcf15 | bigcode/the-stack | train |
98d0c153b4a0b12c81cc3b36 | train | function | def main(argv=None):
if os.path.exists(FLAGS.output_path):
shutil.rmtree(FLAGS.output_path)
os.makedirs(FLAGS.output_path)
os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu
with tf.get_default_graph().as_default():
input_image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name=... | def main(argv=None):
| if os.path.exists(FLAGS.output_path):
shutil.rmtree(FLAGS.output_path)
os.makedirs(FLAGS.output_path)
os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu
with tf.get_default_graph().as_default():
input_image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image')
... | _size = img.shape
im_size_min = np.min(img_size[0:2])
im_size_max = np.max(img_size[0:2])
im_scale = float(600) / float(im_size_min)
if np.round(im_scale * im_size_max) > 1200:
im_scale = float(1200) / float(im_size_max)
new_h = int(img_size[0] * im_scale)
new_w = int(img_size[1] * im_s... | 215 | 215 | 717 | 5 | 210 | kernelforce/text-detection-ctpn | main/demo.py | Python | main | main | 54 | 117 | 54 | 54 | f79f5d22c31081a1d95b6f9d229b58f63a6a275d | bigcode/the-stack | train |
c170bc71096f13c6fdbfb1d3 | train | function | def resize_image(img):
img_size = img.shape
im_size_min = np.min(img_size[0:2])
im_size_max = np.max(img_size[0:2])
im_scale = float(600) / float(im_size_min)
if np.round(im_scale * im_size_max) > 1200:
im_scale = float(1200) / float(im_size_max)
new_h = int(img_size[0] * im_scale)
... | def resize_image(img):
| img_size = img.shape
im_size_min = np.min(img_size[0:2])
im_size_max = np.max(img_size[0:2])
im_scale = float(600) / float(im_size_min)
if np.round(im_scale * im_size_max) > 1200:
im_scale = float(1200) / float(im_size_max)
new_h = int(img_size[0] * im_scale)
new_w = int(img_size[1]... | dirnames, filenames in os.walk(FLAGS.test_data_path):
for filename in filenames:
for ext in exts:
if filename.endswith(ext):
files.append(os.path.join(parent, filename))
break
print('Find {} images'.format(len(files)))
return files
def... | 65 | 65 | 217 | 5 | 59 | kernelforce/text-detection-ctpn | main/demo.py | Python | resize_image | resize_image | 36 | 51 | 36 | 36 | 91c39c6518ffaabc62c8956f8172d424a7471b38 | bigcode/the-stack | train |
ad6782ee80fef032deb557a7 | train | function | def get_images():
files = []
exts = ['jpg', 'png', 'jpeg', 'JPG']
for parent, dirnames, filenames in os.walk(FLAGS.test_data_path):
for filename in filenames:
for ext in exts:
if filename.endswith(ext):
files.append(os.path.join(parent, filename))
... | def get_images():
| files = []
exts = ['jpg', 'png', 'jpeg', 'JPG']
for parent, dirnames, filenames in os.walk(FLAGS.test_data_path):
for filename in filenames:
for ext in exts:
if filename.endswith(ext):
files.append(os.path.join(parent, filename))
br... | _path', 'data/demo/', '')
tf.app.flags.DEFINE_string('output_path', 'data/res/', '')
tf.app.flags.DEFINE_string('gpu', '0', '')
tf.app.flags.DEFINE_string('checkpoint_path', 'checkpoints_mlt/', '')
FLAGS = tf.app.flags.FLAGS
def get_images():
| 64 | 64 | 89 | 4 | 59 | kernelforce/text-detection-ctpn | main/demo.py | Python | get_images | get_images | 23 | 33 | 23 | 23 | 022f01c21cc5889be74961b5136f8d4f7bc31009 | bigcode/the-stack | train |
b75947c9ad5c5c3b8d92cbcf | train | class | class Match(object):
"""Match Classes"""
def __init__(
self, linenumber, columnnumber, linenumberend,
columnnumberend, filename, rule, message=None):
"""Init"""
self.linenumber = linenumber
self.columnnumber = columnnumber
self.linenumberend = linenumbere... | class Match(object):
| """Match Classes"""
def __init__(
self, linenumber, columnnumber, linenumberend,
columnnumberend, filename, rule, message=None):
"""Init"""
self.linenumber = linenumber
self.columnnumber = columnnumber
self.linenumberend = linenumberend
self.colum... |
self.message = message
def __eq__(self, item):
"""Override unique"""
return ((self.path, self.message) == (item.path, item.message))
def __hash__(self):
"""Hash for comparisons"""
return hash((self.path, self.message))
class Match(object):
| 65 | 65 | 217 | 4 | 61 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | Match | Match | 324 | 353 | 324 | 324 | 885a3a73416c11f45a5adb36237951c5386c7f7b | bigcode/the-stack | train |
cda4ee68d6d9eb82f309150b | train | class | class ParseError(cfnlint.CloudFormationLintRule):
"""Parse Lint Rule"""
id = 'E0000'
shortdesc = 'Parsing error found when parsing the template'
description = 'Checks for Null values and Duplicate values in resources'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['base']
| class ParseError(cfnlint.CloudFormationLintRule):
| """Parse Lint Rule"""
id = 'E0000'
shortdesc = 'Parsing error found when parsing the template'
description = 'Checks for Null values and Duplicate values in resources'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['base']
| = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
class ParseError(cfnlint.CloudFormationLintRule):
| 64 | 64 | 78 | 11 | 53 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | ParseError | ParseError | 910 | 916 | 910 | 910 | 68068b9a1bc10b7fcf39fdfd0e0bbef8fd7943c1 | bigcode/the-stack | train |
20ba321635d1b6cccc8b4216 | train | class | class Template(object):
"""Class for a CloudFormation template"""
# pylint: disable=dangerous-default-value
def __init__(self, filename, template, regions=['us-east-1']):
self.filename = filename
self.template = template
self.regions = regions
self.sections = [
'... | class Template(object):
| """Class for a CloudFormation template"""
# pylint: disable=dangerous-default-value
def __init__(self, filename, template, regions=['us-east-1']):
self.filename = filename
self.template = template
self.regions = regions
self.sections = [
'AWSTemplateFormatVersion... | self.message) == (item.path, item.message))
def __hash__(self):
"""Hash for comparisons"""
return hash((self.path, self.message))
class Match(object):
"""Match Classes"""
def __init__(
self, linenumber, columnnumber, linenumberend,
columnnumberend, filename, rule... | 255 | 256 | 3,758 | 4 | 251 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | Template | Template | 356 | 851 | 356 | 356 | e6b1eb060e65e1c45da825c2ef36fff219ed9a0e | bigcode/the-stack | train |
cda403cccaea2ea73513c74d | train | class | class RuleError(cfnlint.CloudFormationLintRule):
"""Rule processing Error"""
id = 'E0002'
shortdesc = 'Error processing rule on the template'
description = 'Errors found when processing a rule on the template'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['base', 'rule']
| class RuleError(cfnlint.CloudFormationLintRule):
| """Rule processing Error"""
id = 'E0002'
shortdesc = 'Error processing rule on the template'
description = 'Errors found when processing a rule on the template'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['base', 'rule']
| shortdesc = 'Error found when transforming the template'
description = 'Errors found when performing transformation on the template'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['base', 'transform']
class RuleError(cfnlint.CloudFormationLintRule):
| 64 | 64 | 79 | 11 | 53 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | RuleError | RuleError | 926 | 932 | 926 | 926 | 66d9eaa38161447504e9bbc5cd34429c63be5e22 | bigcode/the-stack | train |
3cd8b949ee061d8f29294d6d | train | function | def camel_to_snake(s):
"""
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r... | def camel_to_snake(s):
| """
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower(... | self.rules.run(
self.filename, self.cfn))
# uniq the list of incidents
return_matches = []
for _, match in enumerate(matches):
if not any(match == u for u in return_matches):
return_matches.append(match)
return return_matches
def camel_to... | 64 | 64 | 115 | 7 | 56 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | camel_to_snake | camel_to_snake | 899 | 907 | 899 | 899 | 6dca1af00c488d9cb1200d7d1d6b4aa1e9a1b493 | bigcode/the-stack | train |
5440fd932f60eea2c08d8ff6 | train | class | class RulesCollection(object):
"""Collection of rules"""
def __init__(self, ignore_rules=None):
self.rules = []
# Make Ignore Rules not required
if ignore_rules:
self.ignore_rules = ignore_rules
else:
self.ignore_rules = []
def register(self, rule):... | class RulesCollection(object):
| """Collection of rules"""
def __init__(self, ignore_rules=None):
self.rules = []
# Make Ignore Rules not required
if ignore_rules:
self.ignore_rules = ignore_rules
else:
self.ignore_rules = []
def register(self, rule):
"""Register rules"""
... | return wrapper
@matching
# pylint: disable=W0613
def matchall(self, filename, cfn):
"""Match the entire file"""
if not self.match:
return []
return self.match(cfn) # pylint: disable=E1102
@matching
# pylint: disable=W0613
def matchall_resource_properties(... | 255 | 256 | 1,468 | 5 | 250 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | RulesCollection | RulesCollection | 123 | 304 | 123 | 123 | 4f2b90e9d01551e4eaff2266bcb61c022179fc43 | bigcode/the-stack | train |
f1a179f4f75f84e4c5261e34 | train | class | class CloudFormationLintRule(object):
"""CloudFormation linter rules"""
id = ''
shortdesc = ''
description = ''
source_url = ''
tags = []
logger = logging.getLogger(__name__)
resource_property_types = []
resource_sub_property_types = []
def __repr__(self):
return '%s: ... | class CloudFormationLintRule(object):
| """CloudFormation linter rules"""
id = ''
shortdesc = ''
description = ''
source_url = ''
tags = []
logger = logging.getLogger(__name__)
resource_property_types = []
resource_sub_property_types = []
def __repr__(self):
return '%s: %s' % (self.id, self.shortdesc)
d... | , copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNE... | 198 | 198 | 662 | 7 | 191 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | CloudFormationLintRule | CloudFormationLintRule | 31 | 120 | 31 | 31 | 11718765bdba969961035fc2fa82090aa4d9f0ce | bigcode/the-stack | train |
30865707373353ef06eeb4fb | train | class | class Runner(object):
"""Run all the rules"""
def __init__(
self, rules, filename, template, regions, verbosity=0):
self.rules = rules
self.filename = filename
self.verbosity = verbosity
self.cfn = Template(filename, template, regions)
def transform(self):
... | class Runner(object):
| """Run all the rules"""
def __init__(
self, rules, filename, template, regions, verbosity=0):
self.rules = rules
self.filename = filename
self.verbosity = verbosity
self.cfn = Template(filename, template, regions)
def transform(self):
"""Transform logic... | + child_path + [dict_name],
**kwargs)
)
else:
if check_value:
matches.extend(
check_value(
... | 84 | 84 | 280 | 4 | 79 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | Runner | Runner | 854 | 896 | 854 | 854 | 893ebb82208161a6f215e763a124566ddaab1e8a | bigcode/the-stack | train |
039b1e84a70e050dc87d7e78 | train | class | class RuleMatch(object):
"""Rules Error"""
def __init__(self, path, message):
"""Init"""
self.path = path
self.message = message
def __eq__(self, item):
"""Override unique"""
return ((self.path, self.message) == (item.path, item.message))
def __hash__(self):
... | class RuleMatch(object):
| """Rules Error"""
def __init__(self, path, message):
"""Init"""
self.path = path
self.message = message
def __eq__(self, item):
"""Override unique"""
return ((self.path, self.message) == (item.path, item.message))
def __hash__(self):
"""Hash for compari... | ))
return matches
@classmethod
def create_from_directory(cls, rulesdir):
"""Create rules from directory"""
result = cls([])
if rulesdir != '':
result.rules = cfnlint.helpers.load_plugins(os.path.expanduser(rulesdir))
return result
class RuleMatch(object):
| 64 | 64 | 91 | 5 | 58 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | RuleMatch | RuleMatch | 307 | 321 | 307 | 307 | 510454c69898c66459e65d9344ba71cc648d865c | bigcode/the-stack | train |
b56a98a4671f7ca4030ea724 | train | class | class TransformError(cfnlint.CloudFormationLintRule):
"""Transform Lint Rule"""
id = 'E0001'
shortdesc = 'Error found when transforming the template'
description = 'Errors found when performing transformation on the template'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['bas... | class TransformError(cfnlint.CloudFormationLintRule):
| """Transform Lint Rule"""
id = 'E0001'
shortdesc = 'Error found when transforming the template'
description = 'Errors found when performing transformation on the template'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['base', 'transform']
| '
shortdesc = 'Parsing error found when parsing the template'
description = 'Checks for Null values and Duplicate values in resources'
source_url = 'https://github.com/awslabs/cfn-python-lint'
tags = ['base']
class TransformError(cfnlint.CloudFormationLintRule):
| 64 | 64 | 79 | 11 | 53 | aarongorka/cfn-python-lint | src/cfnlint/__init__.py | Python | TransformError | TransformError | 918 | 924 | 918 | 918 | 78a221dea9efa74455f617c13d9bad66dba4b4aa | bigcode/the-stack | train |
14752c3b3057cabeb55033f8 | train | function | def get_overlap_info(base_file, file1, file2, quiet=True):
base_toks = get_tokens(base_file)
toks1 = get_tokens(file1)
toks2 = get_tokens(file2)
if file1 == None:
toks1 = base_toks
if file2 == None:
toks2 = base_toks
same = toks1 == toks2
d1 = diff_tokens(base_toks, toks1... | def get_overlap_info(base_file, file1, file2, quiet=True):
| base_toks = get_tokens(base_file)
toks1 = get_tokens(file1)
toks2 = get_tokens(file2)
if file1 == None:
toks1 = base_toks
if file2 == None:
toks2 = base_toks
same = toks1 == toks2
d1 = diff_tokens(base_toks, toks1)
d2 = diff_tokens(base_toks, toks2)
sz1 = size_of... | _), (a, b)) in inss:
lines.append('[INSERT] %d -> %d-%d (%d):\n' % (i, a, b-1, b-a))
lines.append(' '.join(toks2[a:b]))
lines.append('\n')
s = ''.join(lines)
return s
def print_diff(d, toks1, toks2):
print(diff_to_str(d, toks1, toks2))
def get_overlap_info(base_file, ... | 112 | 112 | 376 | 16 | 96 | mstmhsmt/cca | cca/esecfse2018/overlap.py | Python | get_overlap_info | get_overlap_info | 177 | 229 | 177 | 177 | 194a151a7866a4762b627c04859060efcd9a62b2 | bigcode/the-stack | train |
8ca17c741ec795e6a6470544 | train | function | def size_of_diff(d):
sz = 0
for ((i1, i2), _) in d['delete']:
sz += i2 - i1
for ((i1, i2), (j1, j2)) in d['replace']:
sz += i2 - i1 + j2 - j1
for (_, (j1, j2)) in d['insert']:
sz += j2 - j1
return sz
| def size_of_diff(d):
| sz = 0
for ((i1, i2), _) in d['delete']:
sz += i2 - i1
for ((i1, i2), (j1, j2)) in d['replace']:
sz += i2 - i1 + j2 - j1
for (_, (j1, j2)) in d['insert']:
sz += j2 - j1
return sz
| for (r3, r4) in repls2:
(a2, b2) = r4
y = toks2[a2:b2]
if x == y:
o += overlap_of_ranges(r1, r3)
return o
def size_of_diff(d):
| 64 | 64 | 100 | 6 | 57 | mstmhsmt/cca | cca/esecfse2018/overlap.py | Python | size_of_diff | size_of_diff | 132 | 143 | 132 | 132 | 0233f935d79b5b380b3c53d01fe4b15237f9acce | bigcode/the-stack | train |
658202b19daf037bd68a3474 | train | function | def overlap_of_insert(base_toks, toks1, toks2):
ib1 = insert_of_tokens(base_toks, toks1)
ib2 = insert_of_tokens(base_toks, toks2)
o = 0
for (i, insl1) in ib1.items():
try:
insl2 = ib2[i]
m = SequenceMatcher(isjunk=None, a=insl1, b=insl2, autojunk=False)
for nt... | def overlap_of_insert(base_toks, toks1, toks2):
| ib1 = insert_of_tokens(base_toks, toks1)
ib2 = insert_of_tokens(base_toks, toks2)
o = 0
for (i, insl1) in ib1.items():
try:
insl2 = ib2[i]
m = SequenceMatcher(isjunk=None, a=insl1, b=insl2, autojunk=False)
for nt in m.get_matching_blocks():
o +... | for (tag, i1, _, j1, j2) in m.get_opcodes():
if tag in ('insert', 'replace'):
ins_tbl[i1] = toks2[j1:j2]
return ins_tbl
def overlap_of_insert(base_toks, toks1, toks2):
| 64 | 64 | 126 | 14 | 49 | mstmhsmt/cca | cca/esecfse2018/overlap.py | Python | overlap_of_insert | overlap_of_insert | 80 | 93 | 80 | 80 | 6e0e34638e79eba9faf28c6440d45e1d3c3fb39e | bigcode/the-stack | train |
cf24a3c9b140541e03676f06 | train | function | def meet_of_tokens(toks1, toks2): # returns index set (left toks)
m = SequenceMatcher(isjunk=None, a=toks1, b=toks2, autojunk=False)
toks = set()
for nt in m.get_matching_blocks():
for i in range(nt.a, nt.a+nt.size):
toks.add(i)
return toks
| def meet_of_tokens(toks1, toks2): # returns index set (left toks)
| m = SequenceMatcher(isjunk=None, a=toks1, b=toks2, autojunk=False)
toks = set()
for nt in m.get_matching_blocks():
for i in range(nt.a, nt.a+nt.size):
toks.add(i)
return toks
| seq[-1] += r
else:
seq.append(r)
except IndexError:
seq.append(tok)
else:
seq.append(tok)
except IndexError:
break
return seq
def meet_of_tokens(toks1, toks2): # returns index set (le... | 64 | 64 | 79 | 19 | 44 | mstmhsmt/cca | cca/esecfse2018/overlap.py | Python | meet_of_tokens | meet_of_tokens | 64 | 70 | 64 | 64 | 3e76de0a18f04803158eb34e6c2858cbb7994ae6 | bigcode/the-stack | train |
c80ce082ae165f1e8d7b674b | train | function | def diff_tokens(toks1, toks2):
m = SequenceMatcher(isjunk=None, a=toks1, b=toks2, autojunk=False)
d = {'replace':[],'delete':[],'insert':[]}
for (tag, i1, i2, j1, j2) in m.get_opcodes():
if tag != 'equal':
d[tag].append(((i1, i2), (j1, j2)))
return d
| def diff_tokens(toks1, toks2):
| m = SequenceMatcher(isjunk=None, a=toks1, b=toks2, autojunk=False)
d = {'replace':[],'delete':[],'insert':[]}
for (tag, i1, i2, j1, j2) in m.get_opcodes():
if tag != 'equal':
d[tag].append(((i1, i2), (j1, j2)))
return d
| [i]
m = SequenceMatcher(isjunk=None, a=insl1, b=insl2, autojunk=False)
for nt in m.get_matching_blocks():
o += nt.size
except KeyError:
pass
return o
def diff_tokens(toks1, toks2):
| 64 | 64 | 102 | 10 | 53 | mstmhsmt/cca | cca/esecfse2018/overlap.py | Python | diff_tokens | diff_tokens | 95 | 101 | 95 | 95 | 96b75dbd504374d2d80c7cb77c7745f70532dbc9 | bigcode/the-stack | train |
d378e3f86cc2431688d242bb | train | function | def get_tokens(path):
toks = []
try:
with open(path, 'r') as f:
for tok in tokenizer.tokenize(f.read()):
toks.append(tok.value)
except Exception as e:
pass
seq = []
while True:
try:
tok = toks.pop(0)
if tok == '.':
... | def get_tokens(path):
| toks = []
try:
with open(path, 'r') as f:
for tok in tokenizer.tokenize(f.read()):
toks.append(tok.value)
except Exception as e:
pass
seq = []
while True:
try:
tok = toks.pop(0)
if tok == '.':
try:
... | implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
__author__ = 'Masatomo Hashimoto <m.hashimoto@stair.center>'
import sys
from difflib import SequenceMatcher
from javalang import tokenizer
def get_tokens(path):
| 64 | 64 | 141 | 5 | 58 | mstmhsmt/cca | cca/esecfse2018/overlap.py | Python | get_tokens | get_tokens | 29 | 62 | 29 | 29 | af9726b0bcceedde81e349905c189646445ad2f7 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.