function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def test_login_with_wrong_domain(self):
project = Domain.get_or_create_with_name('api-test-fail', is_active=True)
self.addCleanup(project.delete)
self.assertAuthenticationFail(LoginAndDomainAuthentication(),
self._get_request_with_api_key(domain=project.name)) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def test_auth_type_basic_no_domain(self):
self.assertAuthenticationFail(LoginAndDomainAuthentication(),
self._get_request_with_basic_auth()) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def setUpClass(cls):
super().setUpClass()
cls.role_with_permission = UserRole.create(
cls.domain, 'edit-data', permissions=Permissions(edit_data=True)
)
cls.role_without_permission = UserRole.create(
cls.domain, 'no-edit-data', permissions=Permissions(edit_data=False)
)
cls.role_with_permission_but_no_api_access = UserRole.create(
cls.domain, 'no-api-access', permissions=Permissions(edit_data=True, access_api=False)
)
cls.domain_admin = WebUser.create(cls.domain, 'domain_admin', cls.password, None, None, is_admin=True)
cls.user_with_permission = WebUser.create(cls.domain, 'permission', cls.password, None, None,
role_id=cls.role_with_permission.get_id)
cls.user_without_permission = WebUser.create(cls.domain, 'no-permission', cls.password, None, None,
role_id=cls.role_without_permission.get_id)
cls.user_with_permission_but_no_api_access = WebUser.create(
cls.domain, 'no-api-access', cls.password, None, None,
role_id=cls.role_with_permission_but_no_api_access.get_id,
) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def test_login_no_auth_with_domain(self):
self.assertAuthenticationFail(self.require_edit_data, self._get_request(domain=self.domain)) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def test_login_with_domain_no_permissions(self):
self.assertAuthenticationFail(self.require_edit_data,
self._get_request_with_api_key(domain=self.domain)) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def test_domain_admin_with_explicit_roles(self):
api_key_with_explicit_permissions, _ = HQApiKey.objects.get_or_create(
user=WebUser.get_django_user(self.domain_admin),
name='explicit_with_permission',
role_id=self.role_with_permission.get_id,
)
api_key_without_explicit_permissions, _ = HQApiKey.objects.get_or_create(
user=WebUser.get_django_user(self.domain_admin),
name='explicit_without_permission',
role_id=self.role_without_permission.get_id,
)
self.assertAuthenticationSuccess(self.require_edit_data,
self._get_request(
domain=self.domain,
HTTP_AUTHORIZATION=self._construct_api_auth_header(
self.domain_admin.username,
api_key_with_explicit_permissions
)
))
self.assertAuthenticationFail(self.require_edit_data,
self._get_request(
domain=self.domain,
HTTP_AUTHORIZATION=self._construct_api_auth_header(
self.domain_admin.username,
api_key_without_explicit_permissions
)
)) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def test_login_with_explicit_permission_and_roles(self):
api_key_with_explicit_permissions, _ = HQApiKey.objects.get_or_create(
user=WebUser.get_django_user(self.user_with_permission),
name='explicit_with_permission',
role_id=self.role_with_permission.get_id,
)
api_key_without_explicit_permissions, _ = HQApiKey.objects.get_or_create(
user=WebUser.get_django_user(self.user_with_permission),
name='explicit_without_permission',
role_id=self.role_without_permission.get_id,
)
self.assertAuthenticationSuccess(self.require_edit_data,
self._get_request(
domain=self.domain,
HTTP_AUTHORIZATION=self._construct_api_auth_header(
self.user_with_permission.username,
api_key_with_explicit_permissions
)
))
self.assertAuthenticationFail(self.require_edit_data,
self._get_request(
domain=self.domain,
HTTP_AUTHORIZATION=self._construct_api_auth_header(
self.user_with_permission.username,
api_key_without_explicit_permissions
)
)) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def test_login_with_wrong_permission(self):
api_key_without_permissions, _ = HQApiKey.objects.get_or_create(
user=WebUser.get_django_user(self.user_without_permission)
)
self.assertAuthenticationFail(self.require_edit_data,
self._get_request(
domain=self.domain,
HTTP_AUTHORIZATION=self._construct_api_auth_header(
self.user_without_permission.username,
api_key_without_permissions
)
)) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def test_explicit_role_wrong_domain(self):
project = Domain.get_or_create_with_name('api-test-fail-2', is_active=True)
self.addCleanup(project.delete)
user = WebUser.create(self.domain, 'multi_domain_admin', '***', None, None, is_admin=True)
user.add_domain_membership(project.name, is_admin=True)
user.save()
self.addCleanup(user.delete, self.domain, deleted_by=None)
unscoped_api_key, _ = HQApiKey.objects.get_or_create(
user=WebUser.get_django_user(user),
name='unscoped',
)
# this key should only be able to access default project, not new one
scoped_api_key, _ = HQApiKey.objects.get_or_create(
user=WebUser.get_django_user(user),
name='explicit_with_permission_wrong_domain',
role_id=self.role_with_permission.get_id,
)
unscoped_auth_header = self._construct_api_auth_header(user.username, unscoped_api_key)
scoped_auth_header = self._construct_api_auth_header(user.username, scoped_api_key)
for domain in [self.domain, project.name]:
self.assertAuthenticationSuccess(self.require_edit_data,
self._get_request(
domain=domain,
HTTP_AUTHORIZATION=unscoped_auth_header))
self.assertAuthenticationSuccess(self.require_edit_data,
self._get_request(
domain=self.domain,
HTTP_AUTHORIZATION=scoped_auth_header
))
self.assertAuthenticationFail(self.require_edit_data,
self._get_request(
domain=project.name,
HTTP_AUTHORIZATION=scoped_auth_header
)) | dimagi/commcare-hq | [
465,
201,
465,
202,
1247158807
] |
def forwards(self, orm): | drawquest/drawquest-web | [
19,
6,
19,
2,
1447125196
] |
def backwards(self, orm):
# Renaming column for 'Comment.parent_content' to match new field type.
db.rename_column('canvas_comment', 'parent_content_id', 'parent_content')
# Changing field 'Comment.parent_content'
db.alter_column('canvas_comment', 'parent_content', self.gf('django.db.models.fields.CharField')(max_length=32))
# Renaming column for 'Comment.reply_content' to match new field type.
db.rename_column('canvas_comment', 'reply_content_id', 'reply_content')
# Changing field 'Comment.reply_content'
db.alter_column('canvas_comment', 'reply_content', self.gf('django.db.models.fields.CharField')(max_length=32)) | drawquest/drawquest-web | [
19,
6,
19,
2,
1447125196
] |
def read_kl(filename):
with open(filename, 'r') as f:
inp = f.read()
inlist = inp.split('\n')
inlist = [ x for x in inlist if x != '']
inlist = [ x for x in inlist if x[0] != '#']
inlist = [x.split(' ') for x in inlist]
#print inlist
x_in = np.array([ float(x[0]) for x in inlist])
y_in = np.array([ float(x[1]) for x in inlist])
return x_in, y_in | DocBO/mubosym | [
14,
8,
14,
1,
1441211238
] |
def __init__(self, filename, tst = False):
self.vx, self.vy = read_kl(filename)
self.f_interp = interp1d(self.vx, self.vy, kind = 'linear', bounds_error=False)
# Test:
if tst:
x_dense = np.linspace(-1., 15., 200)
y_dense = []
for xx in x_dense:
y_dense.append(self.f_interp(xx))
lines = plt.plot( x_dense, y_dense )
plt.show() | DocBO/mubosym | [
14,
8,
14,
1,
1441211238
] |
def strip_caret_codes(text):
"""Strip out any caret codes from a string.
:param str text: The text to strip the codes from
:returns str: The clean text
"""
text = text.replace('^^', '\x00')
for token, foo in ANSI_CODES.items():
text = text.replace(token, '')
return text.replace('\x00', '^') | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def word_wrap(text, columns=80, indent=4, padding=2):
"""Given a block of text, break it into a list of lines wrapped to length.
:param str text: The text to wrap
:param int columns: The number of columns to wrap the text to
:param int indent: The number of spaces to indent additionally lines to
:param int padding: The number of columns to pad each side with
:returns list: A list of wrapped strings
"""
paragraphs = PARA_BREAK.split(text)
lines = []
columns -= padding
for para in paragraphs:
if para.isspace():
continue
line = ' ' * indent
for word in para.split():
if (len(line) + 1 + len(word)) > columns:
lines.append(line)
line = ' ' * padding
line += word
else:
line += ' ' + word
if not line.isspace():
lines.append(line)
return lines | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def __init__(self):
self.local_option = UNKNOWN # Local state of an option
self.remote_option = UNKNOWN # Remote state of an option
self.reply_pending = False # Are we expecting a reply? | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def __init__(self, sock, addr_tup):
"""Create a new client connection.
:param socket.socket sock: The socket of the new connection
:param tuple addr_tup: A tuple of (address, port number)
"""
self.protocol = 'telnet'
self.active = True # Turns False when the connection is lost
self.sock = sock # The connection's socket
self.fileno = sock.fileno() # The socket's file descriptor
self.address = addr_tup[0] # The client's remote TCP/IP address
self.port = addr_tup[1] # The client's remote port
self.terminal_type = 'ANSI' # set via request_terminal_type()
self.use_ansi = True
self.columns = 80
self.rows = 24
self.send_pending = False
self.send_buffer = ''
self.recv_buffer = ''
self.bytes_sent = 0
self.bytes_received = 0
self.cmd_ready = False
self.command_list = []
self.connect_time = time.time()
self.last_input_time = time.time()
self.line_mode = True
# State variables for interpreting incoming telnet commands
self.telnet_got_iac = False # Are we inside an IAC sequence?
self.telnet_got_cmd = None # Did we get a telnet command?
self.telnet_got_sb = False # Are we inside a subnegotiation?
self.telnet_opt_dict = {} # Mapping for up to 256 TelnetOptions
self.telnet_echo = False # Echo input back to the client?
self.telnet_echo_password = False # Echo back '*' for passwords?
self.telnet_sb_buffer = '' # Buffer for sub-negotiations | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def get_command(self):
"""Get a line of text that was received from the client.
The client's cmd_ready attribute will be true if lines are available.
:returns str: The found command or None
"""
cmd = None
count = len(self.command_list)
if count > 0:
cmd = self.command_list.pop(0)
# If that was the last line, turn off lines_pending
if count == 1:
self.cmd_ready = False
return cmd | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def send_cc(self, text):
"""Send text with caret codes converted to ANSI codes.
:param str text: The text to send
:returns None:
"""
self.send(colorize(text, self.use_ansi)) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def deactivate(self):
"""Set the client to disconnect on the next server poll."""
self.active = False | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def idle(self):
"""Return the client's idle time.
Idle time is the number of seconds that have elapsed since the client
last sent us some input.
:returns float: The idle time, in seconds
"""
return time.time() - self.last_input_time | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def request_do_sga(self):
"""Request client to Suppress Go-Ahead.
See RFC 858.
"""
self._iac_do(SGA)
self._note_reply_pending(SGA, True) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def request_wont_echo(self):
"""Tell the client that we would like to stop echoing their text.
See RFC 857.
"""
self._iac_wont(ECHO)
self._note_reply_pending(ECHO, True)
self.telnet_echo = False | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def password_mode_off(self):
"""Tell client we are done echoing (we lied) and show typing again."""
self._iac_wont(ECHO)
self._note_reply_pending(ECHO, True) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def request_terminal_type(self):
"""Request the terminal type from the client.
See RFC 779.
"""
self._iac_do(TTYPE)
self._note_reply_pending(TTYPE, True) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def socket_send(self):
"""Send data to the client socket.
Called by TelnetServer when there is data ready to send.
"""
if len(self.send_buffer):
try:
# Convert to ANSI before sending.
sent = self.sock.send(bytes(self.send_buffer, "cp1252"))
except socket.error as err:
logging.error("SEND error '{}' from {}".format(
err, self.addrport()))
self.active = False
return
self.bytes_sent += sent
self.send_buffer = self.send_buffer[sent:]
else:
self.send_pending = False | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _recv_byte(self, byte):
"""Process receiving a single byte.
Non-printable filtering currently disabled because it did not play
well with extended character sets.
:param str byte: The byte to buffer
:returns None:
"""
# Filter out non-printing characters.
# if (byte >= ' ' and byte <= '~') or byte == '\n':
if self.telnet_echo:
self._echo_byte(byte)
self.recv_buffer += byte | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _iac_sniffer(self, byte):
"""Check incoming data for Telnet IAC sequences.
Passes the data, if any, with the IAC commands stripped
to _recv_byte().
:param str byte: The byte to check
:returns None:
"""
# Are we not currently in an IAC sequence coming from the client?
if self.telnet_got_iac is False:
if byte == IAC:
# Well, we are now
self.telnet_got_iac = True
return
# Are we currently in a sub-negotiation?
elif self.telnet_got_sb is True:
# Sanity check on length.
if len(self.telnet_sb_buffer) < 64:
self.telnet_sb_buffer += byte
else:
self.telnet_got_sb = False
self.telnet_sb_buffer = ""
return
else:
# Just a normal NVT character
self._recv_byte(byte)
return
# Byte handling when already in an IAC sequence sent from the client
else:
# Did we get sent a second IAC?
if byte == IAC and self.telnet_got_sb is True:
# Must be an escaped 255 (IAC + IAC)
self.telnet_sb_buffer += byte
self.telnet_got_iac = False
return
# Do we already have an IAC + CMD?
elif self.telnet_got_cmd:
# Yes, so handle the option
self._three_byte_cmd(byte)
return
# We have IAC but no CMD
else:
# Is this the middle byte of a three-byte command?
if byte == DO:
self.telnet_got_cmd = DO
return
elif byte == DONT:
self.telnet_got_cmd = DONT
return
elif byte == WILL:
self.telnet_got_cmd = WILL
return
elif byte == WONT:
self.telnet_got_cmd = WONT
return
else:
# Nope, must be a two-byte command
self._two_byte_cmd(byte) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _three_byte_cmd(self, option):
"""Handle incoming Telnet commands that are three bytes long.
:param str option: The received option byte
:returns None:
"""
cmd = self.telnet_got_cmd
logging.debug("Got three byte cmd {}:{}"
.format(_COMMAND_NAMES.get(cmd, "?"),
_OPTION_NAMES.get(option, "?")))
# Incoming DO's and DONT's refer to the status of this end
if cmd == DO:
if option == BINARY or option == SGA or option == ECHO:
if self._check_reply_pending(option):
self._note_reply_pending(option, False)
self._note_local_option(option, True)
elif (self._check_local_option(option) is False
or self._check_local_option(option) is UNKNOWN):
self._note_local_option(option, True)
self._iac_will(option)
# Just nod unless setting echo
if option == ECHO:
self.telnet_echo = True
else:
# All other options = Default to refusing once
if self._check_local_option(option) is UNKNOWN:
self._note_local_option(option, False)
self._iac_wont(option)
elif cmd == DONT:
if option == BINARY or option == SGA or option == ECHO:
if self._check_reply_pending(option):
self._note_reply_pending(option, False)
self._note_local_option(option, False)
elif (self._check_local_option(option) is True
or self._check_local_option(option) is UNKNOWN):
self._note_local_option(option, False)
self._iac_wont(option)
# Just nod unless setting echo
if option == ECHO:
self.telnet_echo = False
else:
# All other options = Default to ignoring
pass
# Incoming WILL's and WONT's refer to the status of the client
elif cmd == WILL:
if option == ECHO:
# Nutjob client offering to echo the server...
if self._check_remote_option(ECHO) is UNKNOWN:
self._note_remote_option(ECHO, False)
# No no, bad client!
self._iac_dont(ECHO)
elif option == NAWS or option == SGA:
if self._check_reply_pending(option):
self._note_reply_pending(option, False)
self._note_remote_option(option, True)
elif (self._check_remote_option(option) is False
or self._check_remote_option(option) is UNKNOWN):
self._note_remote_option(option, True)
self._iac_do(option)
# Client should respond with SB (for NAWS)
elif option == TTYPE:
if self._check_reply_pending(TTYPE):
self._note_reply_pending(TTYPE, False)
self._note_remote_option(TTYPE, True)
# Tell them to send their terminal type
self.send("{}{}{}{}{}{}".format(IAC, SB, TTYPE,
SEND, IAC, SE))
elif (self._check_remote_option(TTYPE) is False
or self._check_remote_option(TTYPE) is UNKNOWN):
self._note_remote_option(TTYPE, True)
self._iac_do(TTYPE)
elif cmd == WONT:
if option == ECHO:
# Client states it wont echo us -- good,
# they're not supposes to.
if self._check_remote_option(ECHO) is UNKNOWN:
self._note_remote_option(ECHO, False)
self._iac_dont(ECHO)
elif option == SGA or option == TTYPE:
if self._check_reply_pending(option):
self._note_reply_pending(option, False)
self._note_remote_option(option, False)
elif (self._check_remote_option(option) is True
or self._check_remote_option(option) is UNKNOWN):
self._note_remote_option(option, False)
self._iac_dont(option)
# Should TTYPE be below this?
else:
# All other options = Default to ignoring
pass
else:
logging.warning("Send an invalid 3 byte command")
self.telnet_got_iac = False
self.telnet_got_cmd = None | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _check_local_option(self, option):
"""Test the status of local negotiated Telnet options."""
if option not in self.telnet_opt_dict:
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].local_option | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _check_remote_option(self, option):
"""Test the status of remote negotiated Telnet options."""
if option not in self.telnet_opt_dict:
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].remote_option | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _check_reply_pending(self, option):
"""Test the status of requested Telnet options."""
if option not in self.telnet_opt_dict:
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].reply_pending | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _iac_do(self, option):
"""Send a Telnet IAC "DO" sequence."""
self.send("{}{}{}".format(IAC, DO, option)) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def _iac_will(self, option):
"""Send a Telnet IAC "WILL" sequence."""
self.send("{}{}{}".format(IAC, WILL, option)) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def __init__(self, port=23, address='', on_connect=None,
on_disconnect=None, max_connections=MAX_CONNECTIONS,
timeout=0.1, server_socket=None, create_client=True):
""" Create a new Telnet server.
:param int port: The port to listen for new connection on; on
UNIX-like platforms you made need root access to
use ports under 1025
:param str address: The address of the LOCAL network interface to
bind the listening port to; you can usually leave
this blank unless you want to restrict traffic
to a specific network device
:param callable on_connect: Callback for new telnet connections
:param callable on_disconnect: Callback for lost telnet connections
:param int max_connections: Maximum simultaneous connections the
server will allow
:param float timeout: Amount of time that the server will wait for
client input while polling
:param socket server_socket: Optional, an existing server socket to use
:param bool create_client: Whether to create new client instances or
pass the incoming sockets directly to the
on_connect callback
"""
self.port = port
self.address = address
self.on_connect = on_connect
self.on_disconnect = on_disconnect
self.max_connections = min(max_connections, MAX_CONNECTIONS)
self.timeout = timeout
self.create_client = create_client
self.server_socket = None
self.server_fileno = None
if server_socket is None:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((address, port))
server_socket.listen(5)
else:
if server_socket == 0:
server_socket = None
else:
server_socket = socket.fromfd(server_socket, socket.AF_INET,
socket.SOCK_STREAM)
if server_socket:
self.server_socket = server_socket
self.server_fileno = server_socket.fileno()
# Dictionary of active clients,
# key = file descriptor, value = TelnetClient instance
self.clients = {} | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def client_count(self):
"""Return the number of active connections.
:returns int: The client count
"""
return len(self.clients) | whutch/atria | [
16,
4,
16,
22,
1394417605
] |
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/food/shared_drink_charde.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def validate(self):
self.set_active()
self.create_custom_field_for_workflow_state()
self.update_default_workflow_status()
self.validate_docstatus() | frappe/frappe | [
4495,
2418,
4495,
1493,
1307520856
] |
def create_custom_field_for_workflow_state(self):
frappe.clear_cache(doctype=self.document_type)
meta = frappe.get_meta(self.document_type)
if not meta.get_field(self.workflow_state_field):
# create custom field
frappe.get_doc({
"doctype":"Custom Field",
"dt": self.document_type,
"__islocal": 1,
"fieldname": self.workflow_state_field,
"label": self.workflow_state_field.replace("_", " ").title(),
"hidden": 1,
"allow_on_submit": 1,
"no_copy": 1,
"fieldtype": "Link",
"options": "Workflow State",
"owner": "Administrator"
}).save()
frappe.msgprint(_("Created Custom Field {0} in {1}").format(self.workflow_state_field,
self.document_type)) | frappe/frappe | [
4495,
2418,
4495,
1493,
1307520856
] |
def update_doc_status(self):
'''
Checks if the docstatus of a state was updated.
If yes then the docstatus of the document with same state will be updated
'''
doc_before_save = self.get_doc_before_save()
before_save_states, new_states = {}, {}
if doc_before_save:
for d in doc_before_save.states:
before_save_states[d.state] = d
for d in self.states:
new_states[d.state] = d
for key in new_states:
if key in before_save_states:
if not new_states[key].doc_status == before_save_states[key].doc_status:
frappe.db.set_value(self.document_type, {
self.workflow_state_field: before_save_states[key].state
},
'docstatus',
new_states[key].doc_status,
update_modified = False) | frappe/frappe | [
4495,
2418,
4495,
1493,
1307520856
] |
def get_state(state):
for s in self.states:
if s.state==state:
return s
frappe.throw(frappe._("{0} not a valid State").format(state)) | frappe/frappe | [
4495,
2418,
4495,
1493,
1307520856
] |
def set_active(self):
if int(self.is_active or 0):
# clear all other
frappe.db.sql("""UPDATE `tabWorkflow` SET `is_active`=0
WHERE `document_type`=%s""",
self.document_type) | frappe/frappe | [
4495,
2418,
4495,
1493,
1307520856
] |
def get_fieldnames_for(doctype):
return [f.fieldname for f in frappe.get_meta(doctype).fields \
if f.fieldname not in no_value_fields] | frappe/frappe | [
4495,
2418,
4495,
1493,
1307520856
] |
def create(kernel):
result = Tangible()
result.template = "object/tangible/furniture/all/shared_frn_all_lamp_candlestick_tbl_s03.iff"
result.attribute_template_id = 6
result.stfName("frn_n","frn_lamp_candlestick_coronet") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def get_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='OpenStack provisioning and orchestration library with command-line tools'
)
parser.add_argument(
'-v', '--version',
action='version', version=__version__ ,
)
parser.add_argument(
'--user',
help='the username to connect to the remote host', action='store', default='ubuntu', dest='user'
)
parser.add_argument(
'--hosts',
help='the remote host to connect to ', action='store', default=None, dest='hosts'
)
parser.add_argument(
'-i', '--key-filename',
help='referencing file paths to SSH key files to try when connecting', action='store', dest='key_filename', default=None
)
parser.add_argument(
'--password',
help='the password used by the SSH layer when connecting to remote hosts', action='store', dest='password', default=None
)
subparser = parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
provision_parser = subparser.add_parser(
'provision',
help='provision and manage OpenStack'
)
provision_subparser = provision_parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
entry_points = [
(ep.name, ep.load())
for ep in pkg_resources.iter_entry_points('provision')
]
entry_points.sort(
key=lambda (name, fn): getattr(fn, 'priority', 100),
)
for (name, fn) in entry_points:
p = provision_subparser.add_parser(
name,
description=fn.__doc__,
help=fn.__doc__,
)
fn(p)
return parser | jiasir/playback | [
5,
5,
5,
2,
1425471009
] |
def main():
try:
_main()
except:
pass | jiasir/playback | [
5,
5,
5,
2,
1425471009
] |
def __init__(self, lat_tile_start, lat_tile_end, lon_tile_start, lon_tile_end,
username, password, arcsecond_sampling = 1, mask_water = True,
store_geolocation_grids=False):
'''
Initialize Data Fetcher
@param lat_tile_start: Latitude of the southwest corner of the starting tile
@param lat_tile_end: Latitude of the southwset corner of the last tile
@param lon_tile_start: Longitude of the southwest corner of the starting tile
@param lon_tile_end: Longitude of the southwest corner of the last tile
@param username: NASA Earth Data username
@param password: NASA Earth Data Password
@param arcsecond_sampling: Sample spacing of the SRTM data, either 1 arc-
second or 3 arc-seconds
@param mask_water: True if the water bodies should be masked, false otherwise
@param store_geolocation_grids: Store grids of latitude and longitude in the metadata
'''
assert arcsecond_sampling == 1 or arcsecond_sampling == 3, "Sampling should be 1 or 3 arc-seconds"
self.lat_tile_start = lat_tile_start
self.lat_tile_end = lat_tile_end
self.lon_tile_start = lon_tile_start
self.lon_tile_end = lon_tile_end
self.username = username
self.password = password
self.arcsecond_sampling = arcsecond_sampling
self.mask_water = mask_water
self.store_geolocation_grids = store_geolocation_grids
self._missing_data_projection = '\n'.join([
'GEOGCS["WGS 84",',
' DATUM["WGS_1984",',
' SPHEROID["WGS 84",6378137,298.257223563,',
' AUTHORITY["EPSG","7030"]],',
' AUTHORITY["EPSG","6326"]],',
' PRIMEM["Greenwich",0,',
' AUTHORITY["EPSG","8901"]],',
' UNIT["degree",0.0174532925199433,',
' AUTHORITY["EPSG","9122"]],',
' AUTHORITY["EPSG","4326"]]'
]) | skdaccess/skdaccess | [
44,
13,
44,
1,
1463415207
] |
def output(self):
'''
Generate SRTM data wrapper
@return SRTM Image Wrapper
'''
lat_tile_array = np.arange(self.lat_tile_start, self.lat_tile_end+1)
lon_tile_array = np.arange(self.lon_tile_start, self.lon_tile_end+1)
lat_grid,lon_grid = np.meshgrid(lat_tile_array, lon_tile_array)
lat_grid = lat_grid.ravel()
lon_grid = lon_grid.ravel() | skdaccess/skdaccess | [
44,
13,
44,
1,
1463415207
] |
def getCoordinates(filename):
'''
Determine the longitude and latitude of the lowerleft corner of the input filename
@param in_filename: Input SRTM filename
@return Latitude of southwest corner, Longitude of southwest corner
'''
lat_start = int(filename[1:3]) | skdaccess/skdaccess | [
44,
13,
44,
1,
1463415207
] |
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/ithorian/shared_ith_backpack_s01.iff"
result.attribute_template_id = 11
result.stfName("wearables_name","ith_backpack_s01") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def complete_login(self, request, app, token, **kwargs):
resp = requests.get(
self.profile_url,
headers={"Authorization": "Bearer " + token.token},
)
extra_data = resp.json().get("data")
if USE_API_V2:
# Extract tier/pledge level for Patreon API v2:
try:
member_id = extra_data["relationships"]["memberships"]["data"][0]["id"]
member_url = (
"{0}/members/{1}?include="
"currently_entitled_tiers&fields%5Btier%5D=title"
).format(API_URL, member_id)
resp_member = requests.get(
member_url,
headers={"Authorization": "Bearer " + token.token},
)
pledge_title = resp_member.json()["included"][0]["attributes"]["title"]
extra_data["pledge_level"] = pledge_title
except (KeyError, IndexError):
extra_data["pledge_level"] = None
pass
return self.get_provider().sociallogin_from_response(request, extra_data) | pennersr/django-allauth | [
7816,
2745,
7816,
352,
1286741452
] |
def make_target(args):
try:
target = NovaCompute(user=args.user, hosts=args.hosts.split(','), key_filename=args.key_filename,
password=args.password)
except AttributeError:
sys.stderr.write('No hosts found. Please using --hosts param.')
sys.exit(1)
return target | jiasir/playback | [
5,
5,
5,
2,
1425471009
] |
def get_parser(self, prog_name):
parser = super(Install, self).get_parser(prog_name)
parser.add_argument('--user',
help='the username to connect to the remote host',
action='store', default='ubuntu', dest='user')
parser.add_argument('--hosts',
help='the remote host to connect to ',
action='store', default=None, dest='hosts')
parser.add_argument('-i', '--key-filename',
help='referencing file paths to SSH key files to try when connecting',
action='store', dest='key_filename', default=None)
parser.add_argument('--password',
help='the password used by the SSH layer when connecting to remote hosts',
action='store', dest='password', default=None)
parser.add_argument('--my-ip',
help='the host management ip',
action='store', default=None, dest='my_ip')
parser.add_argument('--rabbit-hosts',
help='rabbit hosts e.g. CONTROLLER1,CONTROLLER2',
action='store', default=None, dest='rabbit_hosts')
parser.add_argument('--rabbit-user',
help='the user for rabbit, default openstack',
action='store', default='openstack', dest='rabbit_user')
parser.add_argument('--rabbit-pass',
help='the password for rabbit openstack user', action='store',
default=None, dest='rabbit_pass')
parser.add_argument('--auth-uri',
help='keystone internal endpoint e.g. http://CONTROLLER_VIP:5000',
action='store', default=None, dest='auth_uri')
parser.add_argument('--auth-url',
help='keystone admin endpoint e.g. http://CONTROLLER_VIP:35357',
action='store', default=None, dest='auth_url')
parser.add_argument('--nova-pass',
help='passowrd for nova user',
action='store', default=None, dest='nova_pass')
parser.add_argument('--novncproxy-base-url',
help='nova vnc proxy base url e.g. http://CONTROLLER_VIP:6080/vnc_auto.html',
action='store', default=None, dest='novncproxy_base_url')
parser.add_argument('--glance-api-servers',
help='glance host e.g. http://CONTROLLER_VIP:9292',
action='store', default=None, dest='glance_api_servers')
parser.add_argument('--neutron-endpoint',
help='neutron endpoint e.g. http://CONTROLLER_VIP:9696',
action='store', default=None, dest='neutron_endpoint')
parser.add_argument('--neutron-pass',
help='the password for neutron user',
action='store', default=None, dest='neutron_pass')
parser.add_argument('--rbd-secret-uuid',
help='ceph rbd secret for nova libvirt',
action='store', default=None, dest='rbd_secret_uuid')
parser.add_argument('--memcached-servers',
help='memcached servers e.g. CONTROLLER1:11211,CONTROLLER2:11211',
action='store', default=None, dest='memcached_servers')
return parser | jiasir/playback | [
5,
5,
5,
2,
1425471009
] |
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/simple_kit/shared_tumble_blender.iff"
result.attribute_template_id = -1
result.stfName("loot_n","tumble_blender") | anhstudios/swganh | [
62,
37,
62,
37,
1297996365
] |
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization. | bnzk/djangocms-misc | [
2,
1,
2,
15,
1471614214
] |
def __init__(self):
self.monitor = TacticMonitor() | Southpaw-TACTIC/TACTIC | [
473,
170,
473,
29,
1378771601
] |
def init(self):
self.monitor.mode = "init"
self.monitor.execute() | Southpaw-TACTIC/TACTIC | [
473,
170,
473,
29,
1378771601
] |
def write_stop_monitor():
'''write a stop.monitor file to notify TacticMonitor to exit'''
log_dir = "%s/log" % Environment.get_tmp_dir()
if not os.path.exists(log_dir):
os.makedirs(log_dir) | Southpaw-TACTIC/TACTIC | [
473,
170,
473,
29,
1378771601
] |
def stop(): | Southpaw-TACTIC/TACTIC | [
473,
170,
473,
29,
1378771601
] |
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# create an event that SvcDoRun can wait on and SvcStop
# can set.
self.stop_event = win32event.CreateEvent(None, 0, 0, None) | Southpaw-TACTIC/TACTIC | [
473,
170,
473,
29,
1378771601
] |
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
stop()
win32event.SetEvent(self.stop_event) | Southpaw-TACTIC/TACTIC | [
473,
170,
473,
29,
1378771601
] |
def setUp(self):
super().setUp()
self.host = "abc.com"
self.port = 80
self.api_path = "/v1/"
self.path_list = ['test', 'more', 'test']
self.complete_path = "/v1/test/more/test"
self.ws = MagicMock(auto_spec=WebService)
self.api = APIHelper(self.host, self.port, self.api_path, self.ws) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_get(self):
self.api.get(self.path_list, None)
self._test_ws_function_args(self.ws.get) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_put(self):
self.api.put(self.path_list, None, None)
self._test_ws_function_args(self.ws.put) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def setUp(self):
super().setUp()
self.config = {'server_host': "mb.org", "server_port": 443}
self.set_config_values(self.config)
self.ws = MagicMock(auto_spec=WebService)
self.api = MBAPIHelper(self.ws) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def assertInPath(self, ws_function, path):
self.assertIn(path, ws_function.call_args[0][2]) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def assertInQuery(self, ws_function, argname, value=None):
query_args = ws_function.call_args[1]['queryargs']
self.assertIn(argname, query_args)
self.assertEqual(value, query_args[argname]) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_get_release(self):
inc_args_list = ['test']
self.api.get_release_by_id("1", None, inc=inc_args_list)
self._test_ws_function_args(self.ws.get)
self.assertInPath(self.ws.get, "/release/1")
self._test_inc_args(self.ws.get, inc_args_list) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_get_collection(self):
inc_args_list = ["releases", "artist-credits", "media"]
self.api.get_collection("1", None)
self._test_ws_function_args(self.ws.get)
self.assertInPath(self.ws.get, "collection")
self.assertInPath(self.ws.get, "1/releases")
self._test_inc_args(self.ws.get, inc_args_list) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_put_collection(self):
self.api.put_to_collection("1", ["1", "2", "3"], None)
self._test_ws_function_args(self.ws.put)
self.assertInPath(self.ws.put, "collection/1/releases/1;2;3") | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_xml_ratings_empty(self):
ratings = dict()
xmldata = self.api._xml_ratings(ratings)
self.assertEqual(
xmldata,
'<?xml version="1.0" encoding="UTF-8"?>'
'<metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#">'
'<recording-list></recording-list>'
'</metadata>'
) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_xml_ratings_multiple(self):
ratings = {
("recording", 'a'): 1,
("recording", 'b'): 2,
("nonrecording", 'c'): 3,
}
xmldata = self.api._xml_ratings(ratings)
self.assertEqual(
xmldata,
'<?xml version="1.0" encoding="UTF-8"?>'
'<metadata xmlns="http://musicbrainz.org/ns/mmd-2.0#">'
'<recording-list>'
'<recording id="a"><user-rating>20</user-rating></recording>'
'<recording id="b"><user-rating>40</user-rating></recording>'
'</recording-list>'
'</metadata>'
) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_xml_ratings_raises_value_error(self):
ratings = {("recording", 'a'): 'foo'}
self.assertRaises(ValueError, self.api._xml_ratings, ratings) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def setUp(self):
super().setUp()
self.config = {'acoustid_apikey': "apikey"}
self.set_config_values(self.config)
self.ws = MagicMock(auto_spec=WebService)
self.api = AcoustIdAPIHelper(self.ws)
self.api.acoustid_host = 'acoustid_host'
self.api.acoustid_port = 443
self.api.client_key = "key"
self.api.client_version = "ver" | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def test_encode_acoustid_args_static_empty(self):
args = dict()
result = self.api._encode_acoustid_args(args)
expected = 'client=key&clientversion=ver&format=json'
self.assertEqual(result, expected) | metabrainz/picard | [
3087,
366,
3087,
9,
1313533823
] |
def testMediaChange(app):
vmname = "test-many-devices"
app.uri = tests.utils.URIs.test_remote
app.open(show_console=vmname)
win = app.find_details_window(vmname,
click_details=True, shutdown=True)
hw = win.find("hw-list")
tab = win.find("disk-tab")
combo = win.find("media-combo")
entry = win.find("media-entry")
appl = win.find("config-apply")
# Floppy + physical
hw.find("Floppy 1", "table cell").click()
combo.click_combo_entry()
combo.find(r"Floppy_install_label \(/dev/fdb\)")
lib.utils.check(lambda: entry.text == "No media detected (/dev/fda)")
entry.click()
entry.click_secondary_icon()
lib.utils.check(lambda: not entry.text)
appl.click()
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda: not entry.text)
# Enter /dev/fdb, after apply it should change to pretty label
entry.set_text("/dev/fdb")
appl.click()
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda:
entry.text == "Floppy_install_label (/dev/fdb)")
# Specify manual path
path = "/pool-dir/UPPER"
entry.set_text(path)
appl.click()
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda: entry.text == path)
# Go to Floppy 2, make sure previous path is in recent list
hw.find("Floppy 2", "table cell").click()
combo.click_combo_entry()
combo.find(path)
entry.click()
# Use the storage browser to select new floppy storage
tab.find("Browse", "push button").click()
app.select_storagebrowser_volume("pool-dir", "iso-vol")
appl.click()
# Browse for image
hw.find("IDE CDROM 1", "table cell").click()
combo.click_combo_entry()
combo.find(r"Fedora12_media \(/dev/sr0\)")
entry.click()
tab.find("Browse", "push button").click()
app.select_storagebrowser_volume("pool-dir", "backingl1.img")
# Check 'already in use' dialog
appl.click()
app.click_alert_button("already in use by", "No")
lib.utils.check(lambda: appl.sensitive)
appl.click()
app.click_alert_button("already in use by", "Yes")
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda: "backing" in entry.text)
entry.set_text("")
appl.click()
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda: not entry.text) | virt-manager/virt-manager | [
1688,
378,
1688,
80,
1432252820
] |
def db2a(db):
return np.power(10, (db / 20.0)) | reuk/waveguide | [
135,
19,
135,
7,
1440435580
] |
def series_coeffs(c):
return reduce(lambda (a, b), (x, y): (
np.convolve(a, x), np.convolve(b, y)), c) | reuk/waveguide | [
135,
19,
135,
7,
1440435580
] |
def get_linkwitz_riley_coeffs(gain, lo, hi, sr):
def get_c(cutoff, sr):
wcT = pi * cutoff / sr
return 1 / tan(wcT)
def get_lopass_coeffs(gain, cutoff, sr):
c = get_c(cutoff, sr)
a0 = c * c + c * sqrt(2) + 1
b = [gain / a0, 2 * gain / a0, gain / a0]
a = [1, (-2 * (c * c - 1)) / a0, (c * c - c * sqrt(2) + 1) / a0]
return b, a
def get_hipass_coeffs(gain, cutoff, sr):
c = get_c(cutoff, sr)
a0 = c * c + c * sqrt(2) + 1
b = [(gain * c * c) / a0, (-2 * gain * c * c) / a0, (gain * c * c) / a0]
a = [1, (-2 * (c * c - 1)) / a0, (c * c - c * sqrt(2) + 1) / a0]
return b, a
return twopass_coeffs([get_lopass_coeffs(gain, hi, sr),
get_hipass_coeffs(gain, lo, sr)]) | reuk/waveguide | [
135,
19,
135,
7,
1440435580
] |
def get_peak_coeffs(gain, centre, sr, Q):
A = db2a(gain / 2)
w0 = 2 * pi * centre / sr
cw0 = cos(w0)
sw0 = sin(w0)
alpha = sw0 / 2 * Q
a0 = 1 + alpha / A
b = [(1 + (alpha * A)) / a0, (-2 * cw0) / a0, (1 - alpha * A) / a0]
a = [1, (-2 * cw0) / a0, (1 - alpha / A) / a0]
return b, a | reuk/waveguide | [
135,
19,
135,
7,
1440435580
] |
def biquad_step(i, bm, bc):
out = i * bc.b0 + bm.z1
bm.z1 = i * bc.b1 - bc.a1 * out + bm.z2
bm.z2 = i * bc.b2 - bc.a2 * out
return out | reuk/waveguide | [
135,
19,
135,
7,
1440435580
] |
def impedance_filter(c):
num = c[0]
den = c[1]
summed = [a + b for a, b in zip(den, num)]
subbed = [a - b for a, b in zip(den, num)]
norm = 1 / subbed[0]
summed = [i * norm for i in summed]
subbed = [i * norm for i in subbed]
return [summed, subbed] | reuk/waveguide | [
135,
19,
135,
7,
1440435580
] |
def main():
edges = [30, 60, 120, 240]
corners = zip(edges[:-1], edges[1:])
centres = [(a + b) / 2 for a, b in corners] | reuk/waveguide | [
135,
19,
135,
7,
1440435580
] |