_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q275000
S3Pipeline._make_fileobj
test
def _make_fileobj(self): """ Build file object from items. """ bio = BytesIO() f = gzip.GzipFile(mode='wb', fileobj=bio) if self.use_gzip else bio # Build file object using ItemExporter exporter = JsonLinesItemExporter(f) exporter.start_exporting() for item in self.items:
python
{ "resource": "" }
q275001
Client.get_account_state
test
def get_account_state(self, address, **kwargs): """ Returns the account state information associated with a specific address. :param address: a 34-bit length address (eg. AJBENSwajTzQtwyJFkiJSv7MAaaMc7DsRz) :type address: str
python
{ "resource": "" }
q275002
Client.get_asset_state
test
def get_asset_state(self, asset_id, **kwargs): """ Returns the asset information associated with a specific asset ID. :param asset_id: an asset identifier (the transaction ID of the RegistTransaction when the asset is registered) :type asset_id: str
python
{ "resource": "" }
q275003
Client.get_block
test
def get_block(self, block_hash, verbose=True, **kwargs): """ Returns the block information associated with a specific hash value or block index. :param block_hash: a block hash value or a block index (block height) :param verbose: a boolean indicating whether the detailed block information should be returned in JSON format (otherwise the block information is returned as an hexadecimal string by the JSON-RPC endpoint) :type block_hash: str or int :type verbose: bool
python
{ "resource": "" }
q275004
Client.get_block_hash
test
def get_block_hash(self, block_index, **kwargs): """ Returns the hash value associated with a specific block index. :param block_index: a block index (block height)
python
{ "resource": "" }
q275005
Client.get_block_sys_fee
test
def get_block_sys_fee(self, block_index, **kwargs): """ Returns the system fees associated with a specific block index. :param block_index: a block index (block
python
{ "resource": "" }
q275006
Client.get_contract_state
test
def get_contract_state(self, script_hash, **kwargs): """ Returns the contract information associated with a specific script hash. :param script_hash: contract script
python
{ "resource": "" }
q275007
Client.get_raw_transaction
test
def get_raw_transaction(self, tx_hash, verbose=True, **kwargs): """ Returns detailed information associated with a specific transaction hash. :param tx_hash: transaction hash :param verbose: a boolean indicating whether the detailed transaction information should be returned in JSON format (otherwise the transaction information is returned as an hexadecimal string by the JSON-RPC endpoint) :type tx_hash: str :type verbose: bool :return: dictionary containing
python
{ "resource": "" }
q275008
Client.get_storage
test
def get_storage(self, script_hash, key, **kwargs): """ Returns the value stored in the storage of a contract script hash for a given key. :param script_hash: contract script hash :param key: key to look up in the storage :type script_hash: str :type key: str :return: value associated with the storage key :rtype: bytearray """ hexkey =
python
{ "resource": "" }
q275009
Client.get_tx_out
test
def get_tx_out(self, tx_hash, index, **kwargs): """ Returns the transaction output information corresponding to a hash and index. :param tx_hash: transaction hash :param index: index of the transaction output to be obtained in the transaction (starts from 0) :type tx_hash: str :type index: int
python
{ "resource": "" }
q275010
Client.invoke
test
def invoke(self, script_hash, params, **kwargs): """ Invokes a contract with given parameters and returns the result. It should be noted that the name of the function invoked in the contract should be part of paramaters. :param script_hash: contract script hash :param params: list of paramaters to be passed in to the smart contract :type script_hash: str :type params: list :return: result of the invocation :rtype: dictionary
python
{ "resource": "" }
q275011
Client.invoke_function
test
def invoke_function(self, script_hash, operation, params, **kwargs): """ Invokes a contract's function with given parameters and returns the result. :param script_hash: contract script hash :param operation: name of the operation to invoke :param params: list of paramaters to be passed in to the smart contract :type script_hash: str :type operation: str :type params: list :return: result of the invocation :rtype: dictionary """
python
{ "resource": "" }
q275012
Client.invoke_script
test
def invoke_script(self, script, **kwargs): """ Invokes a script on the VM and returns the result. :param script: script runnable by the VM :type script: str :return: result of the invocation :rtype: dictionary
python
{ "resource": "" }
q275013
Client.send_raw_transaction
test
def send_raw_transaction(self, hextx, **kwargs): """ Broadcasts a transaction over the NEO network and returns the result. :param hextx: hexadecimal string that has been serialized :type hextx: str :return: result of the transaction
python
{ "resource": "" }
q275014
Client.validate_address
test
def validate_address(self, addr, **kwargs): """ Validates if the considered string is a valid NEO address. :param hex: string containing a potential NEO address
python
{ "resource": "" }
q275015
Client._call
test
def _call(self, method, params=None, request_id=None): """ Calls the JSON-RPC endpoint. """ params = params or [] # Determines which 'id' value to use and increment the counter associated with the current # client instance if applicable. rid = request_id or self._id_counter if request_id is None: self._id_counter += 1 # Prepares the payload and the headers that will be used to forge the request. payload = {'jsonrpc': '2.0', 'method': method, 'params': params, 'id': rid} headers = {'Content-Type': 'application/json'} scheme = 'https' if self.tls else 'http' url = '{}://{}:{}'.format(scheme, self.host, self.port) # Calls the JSON-RPC endpoint! try: response = self.session.post(url, headers=headers, data=json.dumps(payload)) response.raise_for_status() except HTTPError: raise TransportError( 'Got unsuccessful response from server (status code: {})'.format( response.status_code), response=response) # Ensures the response body can be deserialized to JSON. try: response_data = response.json()
python
{ "resource": "" }
q275016
is_hash256
test
def is_hash256(s): """ Returns True if the considered string is a valid SHA256 hash. """ if not s or not isinstance(s, str):
python
{ "resource": "" }
q275017
is_hash160
test
def is_hash160(s): """ Returns True if the considered string is a valid RIPEMD160 hash. """ if not s or not isinstance(s, str): return False if not len(s) == 40: return False for c in s:
python
{ "resource": "" }
q275018
encode_invocation_params
test
def encode_invocation_params(params): """ Returns a list of paramaters meant to be passed to JSON-RPC endpoints. """ final_params = [] for p in params: if isinstance(p, bool): final_params.append({'type': ContractParameterTypes.BOOLEAN.value, 'value': p}) elif isinstance(p, int): final_params.append({'type': ContractParameterTypes.INTEGER.value, 'value': p}) elif is_hash256(p):
python
{ "resource": "" }
q275019
decode_invocation_result
test
def decode_invocation_result(result): """ Tries to decode the values embedded in an invocation result dictionary. """ if 'stack' not in result: return
python
{ "resource": "" }
q275020
first_kwonly_arg
test
def first_kwonly_arg(name): """ Emulates keyword-only arguments under python2. Works with both python2 and python3. With this decorator you can convert all or some of the default arguments of your function into kwonly arguments. Use ``KWONLY_REQUIRED`` as the default value of required kwonly args. :param name: The name of the first default argument to be treated as a keyword-only argument. This default argument along with all default arguments that follow this one will be treated as keyword only arguments. You can also pass here the ``FIRST_DEFAULT_ARG`` constant in order to select the first default argument. This way you turn all default arguments into keyword-only arguments. As a shortcut you can use the ``@kwonly_defaults`` decorator (without any parameters) instead of ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``. >>> from kwonly_args import first_kwonly_arg, KWONLY_REQUIRED, FIRST_DEFAULT_ARG, kwonly_defaults >>> >>> # this decoration converts the ``d1`` and ``d2`` default args into kwonly args >>> @first_kwonly_arg('d1') >>> def func(a0, a1, d0='d0', d1='d1', d2='d2', *args, **kwargs): >>> print(a0, a1, d0, d1, d2, args, kwargs) >>> >>> func(0, 1, 2, 3, 4) 0 1 2 d1 d2 (3, 4) {} >>> >>> func(0, 1, 2, 3, 4, d2='my_param') 0 1 2 d1 my_param (3, 4) {} >>> >>> # d0 is an optional deyword argument, d1 is required >>> def func(d0='d0', d1=KWONLY_REQUIRED): >>> print(d0, d1) >>> >>> # The ``FIRST_DEFAULT_ARG`` constant automatically selects the first default argument so it >>> # turns all default arguments into keyword-only ones. Both d0 and d1 are keyword-only arguments. >>> @first_kwonly_arg(FIRST_DEFAULT_ARG) >>> def func(a0, a1, d0='d0', d1='d1'): >>> print(a0, a1, d0, d1) >>> >>> # ``@kwonly_defaults`` is a shortcut for the ``@first_kwonly_arg(FIRST_DEFAULT_ARG)`` >>> # in the previous example. This example has the same effect as the previous one. >>> @kwonly_defaults >>> def func(a0, a1, d0='d0', d1='d1'): >>> print(a0, a1, d0, d1) """ def decorate(wrapped): if sys.version_info[0] == 2: arg_names, varargs, _, defaults = inspect.getargspec(wrapped) else: arg_names, varargs, _, defaults = inspect.getfullargspec(wrapped)[:4] if not defaults: raise TypeError("You can't use @first_kwonly_arg on a function that doesn't have default arguments!") first_default_index = len(arg_names) - len(defaults) if name is FIRST_DEFAULT_ARG: first_kwonly_index = first_default_index else: try:
python
{ "resource": "" }
q275021
snap_tz
test
def snap_tz(dttm, instruction, timezone): """This function handles timezone aware datetimes. Sometimes it is necessary to keep daylight saving time switches in mind. Args: instruction (string): a string that encodes 0 to n transformations of a time, i.e. "-1h@h", "@mon+2d+4h", ... dttm (datetime): a datetime with timezone timezone: a pytz timezone Returns: datetime: The datetime resulting from applying all transformations to the input datetime. Example: >>> import pytz >>> CET = pytz.timezone("Europe/Berlin") >>> dttm = CET.localize(datetime(2017, 3, 26, 3, 44) >>> dttm datetime.datetime(2017, 3, 26,
python
{ "resource": "" }
q275022
SnapTransformation.apply_to_with_tz
test
def apply_to_with_tz(self, dttm, timezone): """We make sure that after truncating we use the correct timezone, even if we 'jump' over a daylight saving time switch. I.e. if we apply "@d" to `Sun Oct 30 04:30:00 CET 2016` (1477798200)
python
{ "resource": "" }
q275023
Barcode.save
test
def save(self, filename, options=None): """Renders the barcode and saves it in `filename`. :parameters: filename : String Filename to save the barcode in (without filename
python
{ "resource": "" }
q275024
Barcode.render
test
def render(self, writer_options=None): """Renders the barcode using `self.writer`. :parameters: writer_options : Dict Options for `self.writer`, see writer docs for details. :returns: Output of the writers render method. """ options = Barcode.default_writer_options.copy() options.update(writer_options or {})
python
{ "resource": "" }
q275025
EuropeanArticleNumber13.calculate_checksum
test
def calculate_checksum(self): """Calculates the checksum for EAN13-Code. :returns: The checksum for `self.ean`. :rtype: Integer """ def sum_(x, y): return int(x) + int(y)
python
{ "resource": "" }
q275026
BaseWriter.render
test
def render(self, code): """Renders the barcode to whatever the inheriting writer provides, using the registered callbacks. :parameters: code : List List of strings matching the writer spec (only contain 0 or 1). """ if self._callbacks['initialize'] is not None: self._callbacks['initialize'](code) ypos = 1.0 for line in code: # Left quiet zone is x startposition xpos = self.quiet_zone for mod in line: if mod == '0': color = self.background else: color = self.foreground self._callbacks['paint_module'](xpos, ypos, self.module_width, color)
python
{ "resource": "" }
q275027
PerlSession.connect
test
def connect(cls, settings): """ Call that method in the pyramid configuration phase. """ server = serializer('json').loads(settings['kvs.perlsess']) server.setdefault('key_prefix', 'perlsess::')
python
{ "resource": "" }
q275028
main
test
def main(ctx, edit, create): """ Simple command line tool to help manage environment variables stored in a S3-like system. Facilitates editing text files remotely stored, as well as downloading and uploading files. """ # configs this module logger to behave properly # logger messages will go to stderr (check __init__.py/patch.py) # client output should be generated with click.echo() to go to stdout try: click_log.basic_config('s3conf') logger.debug('Running main entrypoint') if edit: if ctx.invoked_subcommand is None: logger.debug('Using config file %s', config.LOCAL_CONFIG_FILE)
python
{ "resource": "" }
q275029
download
test
def download(remote_path, local_path): """ Download a file or folder from the S3-like service. If REMOTE_PATH has a trailing slash it is considered to be a folder, e.g.: "s3://my-bucket/my-folder/". In this case, LOCAL_PATH must be a folder as well. The files and subfolder structure in REMOTE_PATH are copied to LOCAL_PATH. If REMOTE_PATH does not have a trailing slash, it is
python
{ "resource": "" }
q275030
upload
test
def upload(remote_path, local_path): """ Upload a file or folder to the S3-like service. If LOCAL_PATH is a folder, the files and subfolder structure in LOCAL_PATH are copied to REMOTE_PATH. If LOCAL_PATH is a file, the REMOTE_PATH file
python
{ "resource": "" }
q275031
downsync
test
def downsync(section, map_files): """ For each section defined in the local config file, creates a folder inside the local config folder named after the section. Downloads the environemnt file defined by the S3CONF variable for this section to this folder. """ try: settings = config.Settings(section=section) storage = STORAGES['s3'](settings=settings) conf
python
{ "resource": "" }
q275032
diff
test
def diff(section): """ For each section defined in the local config file, look up for a folder inside the local config folder named after the section. Uploads the environemnt file named as in the S3CONF variable for this section to the remote S3CONF path. """ try: settings = config.Settings(section=section) storage = STORAGES['s3'](settings=settings)
python
{ "resource": "" }
q275033
parse_env_var
test
def parse_env_var(value): """ Split a env var text like ENV_VAR_NAME=env_var_value into a tuple ('ENV_VAR_NAME', 'env_var_value') """ k, _, v = value.partition('=') # Remove any leading and trailing spaces in key, value
python
{ "resource": "" }
q275034
basic
test
def basic(username, password): """Add basic authentication to the requests of the clients.""" none()
python
{ "resource": "" }
q275035
api_key
test
def api_key(api_key): """Authenticate via an api key.""" none() _config.api_key_prefix["Authorization"] = "api-key"
python
{ "resource": "" }
q275036
_get_json_content_from_folder
test
def _get_json_content_from_folder(folder): """yield objects from json files in the folder and subfolders.""" for dirpath, dirnames, filenames in os.walk(folder): for filename in filenames: if filename.lower().endswith(".json"):
python
{ "resource": "" }
q275037
get_schemas
test
def get_schemas(): """Return a dict of schema names mapping to a Schema. The schema is of type schul_cloud_resources_api_v1.schema.Schema """ schemas = {} for name
python
{ "resource": "" }
q275038
Schema.get_schema
test
def get_schema(self): """Return the schema.""" path = os.path.join(self._get_schema_folder(), self._name + ".json") with open(path, "rb") as file:
python
{ "resource": "" }
q275039
Schema.get_resolver
test
def get_resolver(self): """Return a jsonschema.RefResolver for the schemas. All schemas returned be get_schemas() are resolved locally. """ store = {} for schema in get_schemas().values():
python
{ "resource": "" }
q275040
Schema.validate
test
def validate(self, object): """Validate an object against the schema. This function just passes if the schema matches the object. If the object does not match the schema, a ValidationException is raised.
python
{ "resource": "" }
q275041
Schema.get_valid_examples
test
def get_valid_examples(self): """Return a list of valid examples for the given schema.""" path
python
{ "resource": "" }
q275042
Schema.get_invalid_examples
test
def get_invalid_examples(self): """Return a list of examples which violate the schema.""" path
python
{ "resource": "" }
q275043
OneDriveAuth.auth_user_get_url
test
def auth_user_get_url(self, scope=None): 'Build authorization URL for User Agent.' if not self.client_id: raise AuthMissingError('No client_id specified') return '{}?{}'.format(self.auth_url_user, urllib.urlencode(dict(
python
{ "resource": "" }
q275044
OneDriveAuth.auth_user_process_url
test
def auth_user_process_url(self, url): 'Process tokens and errors from redirect_uri.' url = urlparse.urlparse(url) url_qs = dict(it.chain.from_iterable( urlparse.parse_qsl(v) for v in [url.query, url.fragment] )) if url_qs.get('error'): raise APIAuthError(
python
{ "resource": "" }
q275045
OneDriveAuth.auth_get_token
test
def auth_get_token(self, check_scope=True): 'Refresh or acquire access_token.' res = self.auth_access_data_raw =
python
{ "resource": "" }
q275046
OneDriveAPIWrapper.get_user_id
test
def get_user_id(self): 'Returns "id" of a OneDrive user.' if
python
{ "resource": "" }
q275047
OneDriveAPIWrapper.listdir
test
def listdir(self, folder_id='me/skydrive', limit=None, offset=None): 'Get OneDrive object representing list of objects in a folder.'
python
{ "resource": "" }
q275048
OneDriveAPIWrapper.mkdir
test
def mkdir(self, name=None, folder_id='me/skydrive', metadata=dict()): '''Create a folder with a specified "name" attribute. folder_id allows to specify a parent folder. metadata mapping may contain additional folder properties to pass to an API.'''
python
{ "resource": "" }
q275049
OneDriveAPIWrapper.comment_add
test
def comment_add(self, obj_id, message): 'Add comment message to a specified object.' return self( self._api_url_join(obj_id, 'comments'),
python
{ "resource": "" }
q275050
decode_obj
test
def decode_obj(obj, force=False): 'Convert or dump object to unicode.' if isinstance(obj, unicode): return obj elif isinstance(obj, bytes): if force_encoding is not None: return obj.decode(force_encoding) if chardet: enc_guess = chardet.detect(obj) if enc_guess['confidence']
python
{ "resource": "" }
q275051
set_drop_target
test
def set_drop_target(obj, root, designer, inspector): "Recursively create and set the drop target for obj and childs" if obj._meta.container: dt = ToolBoxDropTarget(obj, root, designer=designer,
python
{ "resource": "" }
q275052
ToolBox.start_drag_opperation
test
def start_drag_opperation(self, evt): "Event handler for drag&drop functionality" # get the control ctrl = self.menu_ctrl_map[evt.GetToolId()] # create our own data format and use it in a custom data object ldata = wx.CustomDataObject("gui") ldata.SetData(ctrl._meta.name) # only strings are allowed! # Also create a Bitmap version of the drawing bmp = ctrl._image.GetBitmap() # Now make a data object for the bitmap and also a composite # data object holding both of the others. bdata = wx.BitmapDataObject(bmp) data = wx.DataObjectComposite() data.Add(ldata)
python
{ "resource": "" }
q275053
ToolBox.set_default_tlw
test
def set_default_tlw(self, tlw, designer, inspector): "track default top level
python
{ "resource": "" }
q275054
inspect
test
def inspect(obj): "Open the inspector windows for a given object" from gui.tools.inspector import InspectorTool inspector =
python
{ "resource": "" }
q275055
shell
test
def shell(): "Open a shell" from gui.tools.debug import Shell
python
{ "resource": "" }
q275056
migrate_font
test
def migrate_font(font): "Convert PythonCard font description to gui2py style" if 'faceName' in font: font['face'] = font.pop('faceName') if 'family' in
python
{ "resource": "" }
q275057
HtmlBox.load_page
test
def load_page(self, location): "Loads HTML page from location and then displays it" if not location:
python
{ "resource": "" }
q275058
GetParam
test
def GetParam(tag, param, default=__SENTINEL): """ Convenience function for accessing tag parameters""" if tag.HasParam(param): return tag.GetParam(param) else:
python
{ "resource": "" }
q275059
send
test
def send(evt): "Process an outgoing communication" # get the text written by the user (input textbox control) msg = ctrl_input.value # send the message (replace with socket/queue/etc.) gui.alert(msg, "Message")
python
{ "resource": "" }
q275060
wellcome_tip
test
def wellcome_tip(wx_obj): "Show a tip message" msg = ("Close the main window to exit & save.\n" "Drag & Drop / Click the controls from the ToolBox to create new ones.\n" "Left click on the created controls to select them.\n" "Double click to edit the default property.\n" "Right click to pop-up the context menu.\n") # create a super tool tip manager and set some styles stt = STT.SuperToolTip(msg) stt.SetHeader("Welcome to gui2py designer!") stt.SetDrawHeaderLine(True) stt.ApplyStyle("Office 2007 Blue") stt.SetDropShadow(True) stt.SetHeaderBitmap(images.designer.GetBitmap()) stt.SetEndDelay(15000) # hide in 15 s # create a independent tip window, show/hide manually (avoid binding wx_obj)
python
{ "resource": "" }
q275061
BasicDesigner.mouse_down
test
def mouse_down(self, evt): "Get the selected object and store start position" if DEBUG: print "down!" if (not evt.ControlDown() and not evt.ShiftDown()) or evt.AltDown(): for obj in self.selection: # clear marker if obj.sel_marker: obj.sel_marker.show(False) obj.sel_marker.destroy() obj.sel_marker = None self.selection = [] # clear previous selection wx_obj = evt.GetEventObject() if wx_obj.Parent is None or evt.AltDown(): if not evt.AltDown(): evt.Skip() # start the rubberband effect (multiple selection using the mouse) self.current = wx_obj self.overlay = wx.Overlay() self.pos = evt.GetPosition() self.parent.wx_obj.CaptureMouse() #if self.inspector and hasattr(wx_obj, "obj"): # self.inspector.inspect(wx_obj.obj) # inspect top level window #self.dclick = False else: # create the selection marker and assign it to the control obj
python
{ "resource": "" }
q275062
BasicDesigner.mouse_move
test
def mouse_move(self, evt): "Move the selected object" if DEBUG: print "move!" if self.current and not self.overlay: wx_obj = self.current sx, sy = self.start x, y = wx.GetMousePosition() # calculate the new position (this will overwrite relative dimensions): x, y = (x + sx, y + sy) if evt.ShiftDown(): # snap to grid: x = x / GRID_SIZE[0] * GRID_SIZE[0] y = y / GRID_SIZE[1] * GRID_SIZE[1] # calculate the diff to use in the rest of the selected objects: ox, oy = wx_obj.obj.pos dx, dy = (x - ox), (y - oy) # move all selected objects: for obj in self.selection: x, y = obj.pos x = x + dx y = y + dy obj.pos = (wx.Point(x, y)) elif self.overlay: wx_obj = self.current pos = evt.GetPosition() # convert to relative client coordinates of the containter:
python
{ "resource": "" }
q275063
BasicDesigner.do_resize
test
def do_resize(self, evt, wx_obj, (n, w, s, e)): "Called by SelectionTag" # calculate the pos (minus the offset, not in a panel like rw!) pos = wx_obj.ScreenToClient(wx.GetMousePosition()) x, y = pos if evt.ShiftDown(): # snap to grid: x = x / GRID_SIZE[0] * GRID_SIZE[0] y = y / GRID_SIZE[1] * GRID_SIZE[1] pos = wx.Point(x, y) if not self.resizing or self.resizing != (wx_obj, (n, w, s, e)): self.pos = list(pos) # store starting point self.resizing = (wx_obj, (n, w, s, e)) # track obj and handle else: delta = pos - self.pos if DEBUG: print "RESIZING: n, w, s, e", n, w, s, e if n or w or s or e: # resize according the direction (n, w, s, e) x = wx_obj.Position[0] + e * delta[0] y = wx_obj.Position[1] + n * delta[1] if w or e: if not isinstance(wx_obj, wx.TopLevelWindow): width = wx_obj.Size[0] + (w - e) * delta[0] else: width = wx_obj.ClientSize[0] + (w - e) * delta[0] else: width = None if n or s: height = wx_obj.Size[1] + (s - n) * delta[1] else: height = None else: # just move x = wx_obj.Position[0] + delta[0] y = wx_obj.Position[1] + delta[1] width = height = None
python
{ "resource": "" }
q275064
BasicDesigner.key_press
test
def key_press(self, event): "support cursor keys to move components one pixel at a time" key = event.GetKeyCode() if key in (wx.WXK_LEFT, wx.WXK_UP, wx.WXK_RIGHT, wx.WXK_DOWN): for obj in self.selection: x, y = obj.pos if event.ShiftDown(): # snap to grid:t # for now I'm only going to align to grid # in the direction of the cursor movement if key == wx.WXK_LEFT: x = (x - GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0] elif key == wx.WXK_RIGHT: x = (x + GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0] elif key == wx.WXK_UP: y = (y - GRID_SIZE[1]) / GRID_SIZE[1] * GRID_SIZE[1] elif key == wx.WXK_DOWN: y = (y + GRID_SIZE[1])
python
{ "resource": "" }
q275065
BasicDesigner.delete
test
def delete(self, event): "delete all of the selected objects" # get the selected objects (if any) for obj in self.selection: if obj: if DEBUG: print "deleting", obj.name
python
{ "resource": "" }
q275066
BasicDesigner.duplicate
test
def duplicate(self, event): "create a copy of each selected object" # duplicate the selected objects (if any) new_selection = [] for obj in self.selection: if obj: if DEBUG: print "duplicating", obj.name obj.sel_marker.destroy() obj.sel_marker = None obj2 = obj.duplicate() obj2.sel_marker
python
{ "resource": "" }
q275067
Facade.refresh
test
def refresh(self): "Capture the new control superficial image after an update" self.bmp = self.obj.snapshot()
python
{ "resource": "" }
q275068
CustomToolTipWindow.CalculateBestPosition
test
def CalculateBestPosition(self,widget): "When dealing with a Top-Level window position it absolute lower-right" if isinstance(widget, wx.Frame): screen = wx.ClientDisplayRect()[2:] left,top = widget.ClientToScreenXY(0,0) right,bottom = widget.ClientToScreenXY(*widget.GetClientRect()[2:]) size = self.GetSize()
python
{ "resource": "" }
q275069
wx_ListCtrl.GetPyData
test
def GetPyData(self, item): "Returns the pyth item data associated with the item" wx_data = self.GetItemData(item)
python
{ "resource": "" }
q275070
wx_ListCtrl.SetPyData
test
def SetPyData(self, item, py_data): "Set the python item data associated wit the wx item" wx_data = wx.NewId() # create a suitable
python
{ "resource": "" }
q275071
wx_ListCtrl.FindPyData
test
def FindPyData(self, start, py_data): "Do a reverse look up for an item containing the requested data" # first, look at our internal dict: wx_data = self._wx_data_map[py_data] # do the real search at the wx control: if wx.VERSION < (3, 0, 0) or 'classic' in wx.version():
python
{ "resource": "" }
q275072
wx_ListCtrl.DeleteItem
test
def DeleteItem(self, item): "Remove the item from the list and unset the related data" wx_data = self.GetItemData(item) py_data = self._py_data_map[wx_data]
python
{ "resource": "" }
q275073
wx_ListCtrl.DeleteAllItems
test
def DeleteAllItems(self): "Remove all the item from the list and unset the related data" self._py_data_map.clear()
python
{ "resource": "" }
q275074
ListView.clear_all
test
def clear_all(self): "Remove all items and column headings" self.clear() for
python
{ "resource": "" }
q275075
ItemContainerControl._set_selection
test
def _set_selection(self, index, dummy=False): "Sets the item at index 'n' to be the selected item." # only change selection if index is None and not dummy: if index is None: self.wx_obj.SetSelection(-1) # clean up text if control supports it: if hasattr(self.wx_obj, "SetValue"): self.wx_obj.SetValue("") else: self.wx_obj.SetSelection(index) # send a programmatically event (not issued by wx) wx_event = ItemContainerControlSelectEvent(self._commandtype,
python
{ "resource": "" }
q275076
ItemContainerControl._get_string_selection
test
def _get_string_selection(self): "Returns the label of the selected item or an empty string if none" if self.multiselect: return [self.wx_obj.GetString(i) for i in
python
{ "resource": "" }
q275077
ItemContainerControl.set_data
test
def set_data(self, n, data): "Associate the given client data with the item at position n." self.wx_obj.SetClientData(n, data)
python
{ "resource": "" }
q275078
ItemContainerControl.append
test
def append(self, a_string, data=None): "Adds the item to the control, associating the given data
python
{ "resource": "" }
q275079
represent
test
def represent(obj, prefix, parent="", indent=0, context=False, max_cols=80): "Construct a string representing the object" try: name = getattr(obj, "name", "") class_name = "%s.%s" % (prefix, obj.__class__.__name__) padding = len(class_name) + 1 + indent * 4 + (5 if context else 0) params = [] for (k, spec) in sorted(obj._meta.specs.items(), key=get_sort_key): if k == "index": # index is really defined by creation order continue # also, avoid infinite recursion if k == "parent" and parent != "": v = parent else: v = getattr(obj, k, "") if (not isinstance(spec, InternalSpec) and v != spec.default and (k != 'id' or v > 0) and isinstance(v, (basestring, int, long, float, bool, dict, list, decimal.Decimal, datetime.datetime, datetime.date, datetime.time, Font, Color)) and repr(v) != 'None' ): v = repr(v)
python
{ "resource": "" }
q275080
get
test
def get(obj_name, init=False): "Find an object already created" wx_parent = None # check if new_parent is given as string (useful for designer!) if isinstance(obj_name, basestring): # find the object reference in the already created gui2py objects # TODO: only useful for designer, get a better way obj_parent = COMPONENTS.get(obj_name) if not obj_parent: # try to find window (it can be a plain wx frame/control) wx_parent = wx.FindWindowByName(obj_name) if wx_parent: # store gui object
python
{ "resource": "" }
q275081
Component.duplicate
test
def duplicate(self, new_parent=None): "Create a new object exactly similar to self" kwargs = {} for spec_name, spec in self._meta.specs.items(): value = getattr(self, spec_name) if isinstance(value, Color): print "COLOR", value, value.default if value.default: value = None if value is not None: kwargs[spec_name] = value del kwargs['parent']
python
{ "resource": "" }
q275082
SizerMixin._sizer_add
test
def _sizer_add(self, child): "called when adding a control to the window" if self.sizer: if DEBUG: print "adding to sizer:", child.name border = None if not border: border = child.sizer_border flags = child._sizer_flags if child.sizer_align: flags |= child._sizer_align if child.sizer_expand: flags |= wx.EXPAND if 'grid' in self.sizer:
python
{ "resource": "" }
q275083
ControlSuper.set_parent
test
def set_parent(self, new_parent, init=False): "Re-parent a child control with the new wx_obj parent" Component.set_parent(self, new_parent, init) # if not called from constructor, we must also reparent in wx: if not init:
python
{ "resource": "" }
q275084
ImageBackgroundMixin.__tile_background
test
def __tile_background(self, dc): "make several copies of the background bitmap" sz = self.wx_obj.GetClientSize() bmp = self._bitmap.get_bits() w = bmp.GetWidth() h = bmp.GetHeight() if isinstance(self, wx.ScrolledWindow): # adjust for scrolled position spx, spy = self.wx_obj.GetScrollPixelsPerUnit() vsx, vsy = self.wx_obj.GetViewStart() dx, dy = (spx * vsx) % w, (spy * vsy) % h else:
python
{ "resource": "" }
q275085
ImageBackgroundMixin.__on_erase_background
test
def __on_erase_background(self, evt): "Draw the image as background" if self._bitmap: dc = evt.GetDC() if not dc: dc = wx.ClientDC(self) r = self.wx_obj.GetUpdateRegion().GetBox() dc.SetClippingRegion(r.x, r.y, r.width, r.height)
python
{ "resource": "" }
q275086
Label.__on_paint
test
def __on_paint(self, event): "Custom draws the label when transparent background is needed" # use a Device Context that supports anti-aliased drawing
python
{ "resource": "" }
q275087
find_modules
test
def find_modules(rootpath, skip): """ Look for every file in the directory tree and return a dict Hacked from sphinx.autodoc """ INITPY = '__init__.py' rootpath = os.path.normpath(os.path.abspath(rootpath)) if INITPY in os.listdir(rootpath): root_package = rootpath.split(os.path.sep)[-1] print "Searching modules in", rootpath else: print "No modules in", rootpath return def makename(package, module): """Join package and module with a dot.""" if package: name = package if module: name += '.' + module else: name = module return name skipall = [] for m in skip.keys(): if skip[m] is None: skipall.append(m) tree = {} saved = 0 found = 0 def save(module, submodule): name = module+ "."+ submodule
python
{ "resource": "" }
q275088
GridView._get_column_headings
test
def _get_column_headings(self): "Return a list of children sub-components that are column headings" # return it in the same order as inserted in the Grid
python
{ "resource": "" }
q275089
GridTable.ResetView
test
def ResetView(self, grid): "Update the grid if rows and columns have been added or deleted" grid.BeginBatch() for current, new, delmsg, addmsg in [ (self._rows, self.GetNumberRows(), gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED, gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED), (self._cols, self.GetNumberCols(), gridlib.GRIDTABLE_NOTIFY_COLS_DELETED, gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED),
python
{ "resource": "" }
q275090
GridTable.UpdateValues
test
def UpdateValues(self, grid): "Update all displayed values" # This sends an event to the grid table to update all of the values msg = gridlib.GridTableMessage(self,
python
{ "resource": "" }
q275091
GridTable._updateColAttrs
test
def _updateColAttrs(self, grid): "update the column attributes to add the appropriate renderer" col = 0 for column in self.columns: attr = gridlib.GridCellAttr() if False: # column.readonly attr.SetReadOnly()
python
{ "resource": "" }
q275092
GridTable.SortColumn
test
def SortColumn(self, col): "col -> sort the data based on the column indexed by col" name = self.columns[col].name _data = [] for row in self.data: rowname, entry = row
python
{ "resource": "" }
q275093
GridModel.clear
test
def clear(self): "Remove all rows and reset internal structures" ## list has no clear ... remove items in reverse order for i in range(len(self)-1, -1, -1): del self[i]
python
{ "resource": "" }
q275094
ComboCellEditor.Create
test
def Create(self, parent, id, evtHandler): "Called to create the control, which must derive from wxControl." self._tc = wx.ComboBox(parent, id, "", (100, 50)) self.SetControl(self._tc)
python
{ "resource": "" }
q275095
ComboCellEditor.BeginEdit
test
def BeginEdit(self, row, col, grid): "Fetch the value from the table and prepare the edit control" self.startValue = grid.GetTable().GetValue(row, col) choices = grid.GetTable().columns[col]._choices
python
{ "resource": "" }
q275096
ComboCellEditor.EndEdit
test
def EndEdit(self, row, col, grid, val=None): "Complete the editing of the current cell. Returns True if changed" changed = False val = self._tc.GetStringSelection() print "val", val, row, col, self.startValue if val != self.startValue:
python
{ "resource": "" }
q275097
ComboCellEditor.IsAcceptedKey
test
def IsAcceptedKey(self, evt): "Return True to allow the given key to start editing" ## Oops, there's a bug here, we'll have to do it ourself.. ##return self.base_IsAcceptedKey(evt)
python
{ "resource": "" }
q275098
ComboCellEditor.StartingKey
test
def StartingKey(self, evt): "This will be called to let the editor do something with the first key" key = evt.GetKeyCode() ch = None if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4, wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]: ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0) elif key <
python
{ "resource": "" }
q275099
TypeHandler
test
def TypeHandler(type_name): """ A metaclass generator. Returns a metaclass which will register it's class as the class that handles input type=typeName """ def metaclass(name, bases, dict):
python
{ "resource": "" }