_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q265600
DescriptorPool.FindEnumTypeByName
validation
def FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self.FindFileContainingSymbol(full_name) return self._enum_descriptors[full_name]
python
{ "resource": "" }
q265601
DescriptorPool.FindExtensionByName
validation
def FindExtensionByName(self, full_name): """Loads the named extension descriptor from the pool. Args: full_name: The full name of the extension descriptor to load. Returns: A FieldDescriptor, describing the named extension. """ full_name = _NormalizeFullyQualifiedName(full_name) message_name, _, extension_name = full_name.rpartition('.') try: # Most extensions are nested inside a message. scope = self.FindMessageTypeByName(message_name) except KeyError: # Some extensions are defined at file scope. scope = self.FindFileContainingSymbol(full_name) return scope.extensions_by_name[extension_name]
python
{ "resource": "" }
q265602
DescriptorPool._ConvertEnumDescriptor
validation
def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, containing_type=None, scope=None): """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. Args: enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the enum descriptor. containing_type: The type containing this enum. scope: Scope containing available types. Returns: The added descriptor """ if package: enum_name = '.'.join((package, enum_proto.name)) else: enum_name = enum_proto.name if file_desc is None: file_name = None else: file_name = file_desc.name values = [self._MakeEnumValueDescriptor(value, index) for index, value in enumerate(enum_proto.value)] desc = descriptor.EnumDescriptor(name=enum_proto.name, full_name=enum_name, filename=file_name, file=file_desc, values=values, containing_type=containing_type, options=enum_proto.options) scope['.%s' % enum_name] = desc self._enum_descriptors[enum_name] = desc return desc
python
{ "resource": "" }
q265603
DescriptorPool._MakeFieldDescriptor
validation
def _MakeFieldDescriptor(self, field_proto, message_name, index, is_extension=False): """Creates a field descriptor from a FieldDescriptorProto. For message and enum type fields, this method will do a look up in the pool for the appropriate descriptor for that type. If it is unavailable, it will fall back to the _source function to create it. If this type is still unavailable, construction will fail. Args: field_proto: The proto describing the field. message_name: The name of the containing message. index: Index of the field is_extension: Indication that this field is for an extension. Returns: An initialized FieldDescriptor object """ if message_name: full_name = '.'.join((message_name, field_proto.name)) else: full_name = field_proto.name return descriptor.FieldDescriptor( name=field_proto.name, full_name=full_name, index=index, number=field_proto.number, type=field_proto.type, cpp_type=None, message_type=None, enum_type=None, containing_type=None, label=field_proto.label, has_default_value=False, default_value=None, is_extension=is_extension, extension_scope=None, options=field_proto.options)
python
{ "resource": "" }
q265604
get_tm_session
validation
def get_tm_session(session_factory, transaction_manager): """ Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using pyramid_tm it will automatically be committed or aborted depending on whether an exception is raised. - When using scripts you should wrap the session in a manager yourself. For example:: import transaction engine = get_engine(settings) session_factory = get_session_factory(engine) with transaction.manager: dbsession = get_tm_session(session_factory, transaction.manager) """ dbsession = session_factory() zope.sqlalchemy.register( dbsession, transaction_manager=transaction_manager) return dbsession
python
{ "resource": "" }
q265605
generate
validation
def generate(length=DEFAULT_LENGTH): """ Generate a random string of the specified length. The returned string is composed of an alphabet that shouldn't include any characters that are easily mistakeable for one another (I, 1, O, 0), and hopefully won't accidentally contain any English-language curse words. """ return ''.join(random.SystemRandom().choice(ALPHABET) for _ in range(length))
python
{ "resource": "" }
q265606
require
validation
def require(name, field, data_type): """Require that the named `field` has the right `data_type`""" if not isinstance(field, data_type): msg = '{0} must have {1}, got: {2}'.format(name, data_type, field) raise AssertionError(msg)
python
{ "resource": "" }
q265607
Client.flush
validation
def flush(self): """Forces a flush from the internal queue to the server""" queue = self.queue size = queue.qsize() queue.join() self.log.debug('successfully flushed %s items.', size)
python
{ "resource": "" }
q265608
open
validation
def open(name=None, fileobj=None, closefd=True): """ Use all decompressor possible to make the stream """ return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)
python
{ "resource": "" }
q265609
marv
validation
def marv(ctx, config, loglevel, logfilter, verbosity): """Manage a Marv site""" if config is None: cwd = os.path.abspath(os.path.curdir) while cwd != os.path.sep: config = os.path.join(cwd, 'marv.conf') if os.path.exists(config): break cwd = os.path.dirname(cwd) else: config = '/etc/marv/marv.conf' if not os.path.exists(config): config = None ctx.obj = config setup_logging(loglevel, verbosity, logfilter)
python
{ "resource": "" }
q265610
MessageSetItemDecoder
validation
def MessageSetItemDecoder(extensions_by_number): """Returns a decoder for a MessageSet item. The parameter is the _extensions_by_number map for the message class. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } """ type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) local_ReadTag = ReadTag local_DecodeVarint = _DecodeVarint local_SkipField = SkipField def DecodeItem(buffer, pos, end, message, field_dict): message_set_item_start = pos type_id = -1 message_start = -1 message_end = -1 # Technically, type_id and message can appear in any order, so we need # a little loop here. while 1: (tag_bytes, pos) = local_ReadTag(buffer, pos) if tag_bytes == type_id_tag_bytes: (type_id, pos) = local_DecodeVarint(buffer, pos) elif tag_bytes == message_tag_bytes: (size, message_start) = local_DecodeVarint(buffer, pos) pos = message_end = message_start + size elif tag_bytes == item_end_tag_bytes: break else: pos = SkipField(buffer, pos, end, tag_bytes) if pos == -1: raise _DecodeError('Missing group end tag.') if pos > end: raise _DecodeError('Truncated message.') if type_id == -1: raise _DecodeError('MessageSet item missing type_id.') if message_start == -1: raise _DecodeError('MessageSet item missing message.') extension = extensions_by_number.get(type_id) if extension is not None: value = field_dict.get(extension) if value is None: value = field_dict.setdefault( extension, extension.message_type._concrete_class()) if value._InternalParse(buffer, message_start,message_end) != message_end: # The only reason _InternalParse would return early is if it encountered # an end-group tag. raise _DecodeError('Unexpected end-group tag.') else: if not message._unknown_fields: message._unknown_fields = [] message._unknown_fields.append((MESSAGE_SET_ITEM_TAG, buffer[message_set_item_start:pos])) return pos return DecodeItem
python
{ "resource": "" }
q265611
get_app_name
validation
def get_app_name(): """Flask like implementation of getting the applicaiton name via the filename of the including file """ fn = getattr(sys.modules['__main__'], '__file__', None) if fn is None: return '__main__' return os.path.splitext(os.path.basename(fn))[0]
python
{ "resource": "" }
q265612
get_function
validation
def get_function(function_name): """ Given a Python function name, return the function it refers to. """ module, basename = str(function_name).rsplit('.', 1) try: return getattr(__import__(module, fromlist=[basename]), basename) except (ImportError, AttributeError): raise FunctionNotFound(function_name)
python
{ "resource": "" }
q265613
ViewServerRequestHandler.handle_add_fun
validation
def handle_add_fun(self, function_name): """Add a function to the function list, in order.""" function_name = function_name.strip() try: function = get_function(function_name) except Exception, exc: self.wfile.write(js_error(exc) + NEWLINE) return # This tests to see if the function has been decorated with the view # server synchronisation decorator (``decorate_view``). if not getattr(function, 'view_decorated', None): self.functions[function_name] = (self.function_counter, function) # The decorator gets called with the logger function. else: self.functions[function_name] = (self.function_counter, function(self.log)) self.function_counter += 1 return True
python
{ "resource": "" }
q265614
ViewServerRequestHandler.handle_map_doc
validation
def handle_map_doc(self, document): """Return the mapping of a document according to the function list.""" # This uses the stored set of functions, sorted by order of addition. for function in sorted(self.functions.values(), key=lambda x: x[0]): try: # It has to be run through ``list``, because it may be a # generator function. yield [list(function(document))] except Exception, exc: # Otherwise, return an empty list and log the event. yield [] self.log(repr(exc))
python
{ "resource": "" }
q265615
ViewServerRequestHandler.handle_reduce
validation
def handle_reduce(self, reduce_function_names, mapped_docs): """Reduce several mapped documents by several reduction functions.""" reduce_functions = [] # This gets a large list of reduction functions, given their names. for reduce_function_name in reduce_function_names: try: reduce_function = get_function(reduce_function_name) if getattr(reduce_function, 'view_decorated', None): reduce_function = reduce_function(self.log) reduce_functions.append(reduce_function) except Exception, exc: self.log(repr(exc)) reduce_functions.append(lambda *args, **kwargs: None) # Transform lots of (key, value) pairs into one (keys, values) pair. keys, values = zip( (key, value) for ((key, doc_id), value) in mapped_docs) # This gets the list of results from the reduction functions. results = [] for reduce_function in reduce_functions: try: results.append(reduce_function(keys, values, rereduce=False)) except Exception, exc: self.log(repr(exc)) results.append(None) return [True, results]
python
{ "resource": "" }
q265616
ViewServerRequestHandler.handle_rereduce
validation
def handle_rereduce(self, reduce_function_names, values): """Re-reduce a set of values, with a list of rereduction functions.""" # This gets a large list of reduction functions, given their names. reduce_functions = [] for reduce_function_name in reduce_function_names: try: reduce_function = get_function(reduce_function_name) if getattr(reduce_function, 'view_decorated', None): reduce_function = reduce_function(self.log) reduce_functions.append(reduce_function) except Exception, exc: self.log(repr(exc)) reduce_functions.append(lambda *args, **kwargs: None) # This gets the list of results from those functions. results = [] for reduce_function in reduce_functions: try: results.append(reduce_function(None, values, rereduce=True)) except Exception, exc: self.log(repr(exc)) results.append(None) return [True, results]
python
{ "resource": "" }
q265617
ViewServerRequestHandler.handle_validate
validation
def handle_validate(self, function_name, new_doc, old_doc, user_ctx): """Validate...this function is undocumented, but still in CouchDB.""" try: function = get_function(function_name) except Exception, exc: self.log(repr(exc)) return False try: return function(new_doc, old_doc, user_ctx) except Exception, exc: self.log(repr(exc)) return repr(exc)
python
{ "resource": "" }
q265618
ViewServerRequestHandler.handle
validation
def handle(self): """The main function called to handle a request.""" while True: try: line = self.rfile.readline() try: # All input data are lines of JSON like the following: # ["<cmd_name>" "<cmd_arg1>" "<cmd_arg2>" ...] # So I handle this by dispatching to various methods. cmd = json.loads(line) except Exception, exc: # Sometimes errors come up. Once again, I can't predict # anything, but can at least tell CouchDB about the error. self.wfile.write(repr(exc) + NEWLINE) continue else: # Automagically get the command handler. handler = getattr(self, 'handle_' + cmd[0], None) if not handler: # We are ready to not find commands. It probably won't # happen, but fortune favours the prepared. self.wfile.write( repr(CommandNotFound(cmd[0])) + NEWLINE) continue return_value = handler(*cmd[1:]) if not return_value: continue # We write the output back to CouchDB. self.wfile.write( one_lineify(json.dumps(return_value)) + NEWLINE) except Exception, exc: self.wfile.write(repr(exc) + NEWLINE) continue
python
{ "resource": "" }
q265619
ViewServerRequestHandler.log
validation
def log(self, string): """Log an event on the CouchDB server.""" self.wfile.write(json.dumps({'log': string}) + NEWLINE)
python
{ "resource": "" }
q265620
guid
validation
def guid(*args): """ Generates a universally unique ID. Any arguments only create more randomness. """ t = float(time.time() * 1000) r = float(random.random()*10000000000000) a = random.random() * 10000000000000 data = str(t) + ' ' + str(r) + ' ' + str(a) + ' ' + str(args) data = hashlib.md5(data.encode()).hexdigest()[:10] return data
python
{ "resource": "" }
q265621
AsyncProauth2.revoke_token
validation
def revoke_token(self, token, callback): ''' revoke_token removes the access token from the data_store ''' yield Task(self.data_store.remove, 'tokens', token=token) callback()
python
{ "resource": "" }
q265622
AsyncProauth2._auth
validation
def _auth(self, client_id, key, method, callback): ''' _auth - internal method to ensure the client_id and client_secret passed with the nonce match ''' available = auth_methods.keys() if method not in available: raise Proauth2Error('invalid_request', 'unsupported authentication method: %s' 'available methods: %s' % \ (method, '\n'.join(available))) client = yield Task(self.data_store.fetch, 'applications', client_id=client_id) if not client: raise Proauth2Error('access_denied') if not auth_methods[method](key, client['client_secret']): raise Proauth2Error('access_denied') callback()
python
{ "resource": "" }
q265623
AsyncProauth2._validate_request_code
validation
def _validate_request_code(self, code, client_id, callback): ''' _validate_request_code - internal method for verifying the the given nonce. also removes the nonce from the data_store, as they are intended for one-time use. ''' nonce = yield Task(self.data_store.fetch, 'nonce_codes', code=code) if not nonce: raise Proauth2Error('access_denied', 'invalid request code: %s' % code) if client_id != nonce['client_id']: raise Proauth2Error('access_denied', 'invalid request code: %s' % code) user_id = nonce['user_id'] expires = nonce['expires'] yield Task(self.data_store.remove, 'nonce_codes', code=code, client_id=client_id, user_id=user_id) if time() > expires: raise Proauth2Error('access_denied', 'request code %s expired' % code) callback(user_id)
python
{ "resource": "" }
q265624
AsyncProauth2._generate_token
validation
def _generate_token(self, length=32): ''' _generate_token - internal function for generating randomized alphanumberic strings of a given length ''' return ''.join(choice(ascii_letters + digits) for x in range(length))
python
{ "resource": "" }
q265625
merge_ordered
validation
def merge_ordered(ordereds: typing.Iterable[typing.Any]) -> typing.Iterable[typing.Any]: """Merge multiple ordered so that within-ordered order is preserved """ seen_set = set() add_seen = seen_set.add return reversed(tuple(map( lambda obj: add_seen(obj) or obj, filterfalse( seen_set.__contains__, chain.from_iterable(map(reversed, reversed(ordereds))), ), )))
python
{ "resource": "" }
q265626
validate_params
validation
def validate_params(required, optional, params): """ Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the key which has tells us what the user is using for the API request :returns: None or throws an exception if the validation fails """ missing_fields = [x for x in required if x not in params] if missing_fields: field_strings = ", ".join(missing_fields) raise Exception("Missing fields: %s" % field_strings) disallowed_fields = [x for x in params if x not in optional and x not in required] if disallowed_fields: field_strings = ", ".join(disallowed_fields) raise Exception("Disallowed fields: %s" % field_strings)
python
{ "resource": "" }
q265627
FileAge.__get_current_datetime
validation
def __get_current_datetime(self): """Get current datetime for every file.""" self.wql_time = "SELECT LocalDateTime FROM Win32_OperatingSystem" self.current_time = self.query(self.wql_time) # [{'LocalDateTime': '20160824161431.977000+480'}]' self.current_time_string = str( self.current_time[0].get('LocalDateTime').split('.')[0]) # '20160824161431' self.current_time_format = datetime.datetime.strptime( self.current_time_string, '%Y%m%d%H%M%S') # param: datetime.datetime(2016, 8, 24, 16, 14, 31) -> type: # datetime.datetime return self.current_time_format
python
{ "resource": "" }
q265628
BranchThread.run
validation
def run(self): """run your main spider here as for branch spider result data, you can return everything or do whatever with it in your own code :return: None """ config = config_creator() debug = config.debug branch_thread_sleep = config.branch_thread_sleep while 1: url = self.branch_queue.get() if debug: print('branch thread-{} start'.format(url)) branch_spider = self.branch_spider(url) sleep(random.randrange(*branch_thread_sleep)) branch_spider.request_page() if debug: print('branch thread-{} end'.format(url)) self.branch_queue.task_done()
python
{ "resource": "" }
q265629
get_version
validation
def get_version(relpath): """Read version info from a file without importing it""" from os.path import dirname, join if '__file__' not in globals(): # Allow to use function interactively root = '.' else: root = dirname(__file__) # The code below reads text file with unknown encoding in # in Python2/3 compatible way. Reading this text file # without specifying encoding will fail in Python 3 on some # systems (see http://goo.gl/5XmOH). Specifying encoding as # open() parameter is incompatible with Python 2 # cp437 is the encoding without missing points, safe against: # UnicodeDecodeError: 'charmap' codec can't decode byte... for line in open(join(root, relpath), 'rb'): line = line.decode('cp437') if '__version__' in line: if '"' in line: # __version__ = "0.9" return line.split('"')[1] elif "'" in line: return line.split("'")[1]
python
{ "resource": "" }
q265630
MakeDescriptor
validation
def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True, syntax=None): """Make a protobuf Descriptor given a DescriptorProto protobuf. Handles nested descriptors. Note that this is limited to the scope of defining a message inside of another message. Composite fields can currently only be resolved if the message is defined in the same scope as the field. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: Optional package name for the new message Descriptor (string). build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to False on recursion, so no duplicates are created. syntax: The syntax/semantics that should be used. Set to "proto3" to get proto3 field presence semantics. Returns: A Descriptor for protobuf messages. """ if api_implementation.Type() == 'cpp' and build_file_if_cpp: # The C++ implementation requires all descriptors to be backed by the same # definition in the C++ descriptor pool. To do this, we build a # FileDescriptorProto with the same definition as this descriptor and build # it into the pool. from typy.google.protobuf import descriptor_pb2 file_descriptor_proto = descriptor_pb2.FileDescriptorProto() file_descriptor_proto.message_type.add().MergeFrom(desc_proto) # Generate a random name for this proto file to prevent conflicts with any # imported ones. We need to specify a file name so the descriptor pool # accepts our FileDescriptorProto, but it is not important what that file # name is actually set to. proto_name = str(uuid.uuid4()) if package: file_descriptor_proto.name = os.path.join(package.replace('.', '/'), proto_name + '.proto') file_descriptor_proto.package = package else: file_descriptor_proto.name = proto_name + '.proto' _message.default_pool.Add(file_descriptor_proto) result = _message.default_pool.FindFileByName(file_descriptor_proto.name) if _USE_C_DESCRIPTORS: return result.message_types_by_name[desc_proto.name] full_message_name = [desc_proto.name] if package: full_message_name.insert(0, package) # Create Descriptors for enum types enum_types = {} for enum_proto in desc_proto.enum_type: full_name = '.'.join(full_message_name + [enum_proto.name]) enum_desc = EnumDescriptor( enum_proto.name, full_name, None, [ EnumValueDescriptor(enum_val.name, ii, enum_val.number) for ii, enum_val in enumerate(enum_proto.value)]) enum_types[full_name] = enum_desc # Create Descriptors for nested types nested_types = {} for nested_proto in desc_proto.nested_type: full_name = '.'.join(full_message_name + [nested_proto.name]) # Nested types are just those defined inside of the message, not all types # used by fields in the message, so no loops are possible here. nested_desc = MakeDescriptor(nested_proto, package='.'.join(full_message_name), build_file_if_cpp=False, syntax=syntax) nested_types[full_name] = nested_desc fields = [] for field_proto in desc_proto.field: full_name = '.'.join(full_message_name + [field_proto.name]) enum_desc = None nested_desc = None if field_proto.HasField('type_name'): type_name = field_proto.type_name full_type_name = '.'.join(full_message_name + [type_name[type_name.rfind('.')+1:]]) if full_type_name in nested_types: nested_desc = nested_types[full_type_name] elif full_type_name in enum_types: enum_desc = enum_types[full_type_name] # Else type_name references a non-local type, which isn't implemented field = FieldDescriptor( field_proto.name, full_name, field_proto.number - 1, field_proto.number, field_proto.type, FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), field_proto.label, None, nested_desc, enum_desc, None, False, None, options=field_proto.options, has_default_value=False) fields.append(field) desc_name = '.'.join(full_message_name) return Descriptor(desc_proto.name, desc_name, None, None, fields, list(nested_types.values()), list(enum_types.values()), [], options=desc_proto.options)
python
{ "resource": "" }
q265631
_NestedDescriptorBase.GetTopLevelContainingType
validation
def GetTopLevelContainingType(self): """Returns the root if this is a nested type, or itself if its the root.""" desc = self while desc.containing_type is not None: desc = desc.containing_type return desc
python
{ "resource": "" }
q265632
ServiceDescriptor.FindMethodByName
validation
def FindMethodByName(self, name): """Searches for the specified method, and returns its descriptor.""" for method in self.methods: if name == method.name: return method return None
python
{ "resource": "" }
q265633
MessageToJson
validation
def MessageToJson(message, including_default_value_fields=False): """Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serialized. If False, only serialize non-empty fields. Singular message fields and oneof fields are not affected by this option. Returns: A string containing the JSON formatted protocol buffer message. """ js = _MessageToJsonObject(message, including_default_value_fields) return json.dumps(js, indent=2)
python
{ "resource": "" }
q265634
_MessageToJsonObject
validation
def _MessageToJsonObject(message, including_default_value_fields): """Converts message to an object according to Proto3 JSON Specification.""" message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): return _WrapperMessageToJsonObject(message) if full_name in _WKTJSONMETHODS: return _WKTJSONMETHODS[full_name][0]( message, including_default_value_fields) js = {} return _RegularMessageToJsonObject( message, js, including_default_value_fields)
python
{ "resource": "" }
q265635
_StructMessageToJsonObject
validation
def _StructMessageToJsonObject(message, unused_including_default=False): """Converts Struct message according to Proto3 JSON Specification.""" fields = message.fields ret = {} for key in fields: ret[key] = _ValueMessageToJsonObject(fields[key]) return ret
python
{ "resource": "" }
q265636
Parse
validation
def Parse(text, message): """Parses a JSON representation of a protocol message into a message. Args: text: Message JSON representation. message: A protocol beffer message to merge into. Returns: The same message passed as argument. Raises:: ParseError: On JSON parsing problems. """ if not isinstance(text, six.text_type): text = text.decode('utf-8') try: if sys.version_info < (2, 7): # object_pair_hook is not supported before python2.7 js = json.loads(text) else: js = json.loads(text, object_pairs_hook=_DuplicateChecker) except ValueError as e: raise ParseError('Failed to load JSON: {0}.'.format(str(e))) _ConvertMessage(js, message) return message
python
{ "resource": "" }
q265637
_ConvertFieldValuePair
validation
def _ConvertFieldValuePair(js, message): """Convert field value pairs into regular message. Args: js: A JSON object to convert the field value pairs. message: A regular protocol message to record the data. Raises: ParseError: In case of problems converting. """ names = [] message_descriptor = message.DESCRIPTOR for name in js: try: field = message_descriptor.fields_by_camelcase_name.get(name, None) if not field: raise ParseError( 'Message type "{0}" has no field named "{1}".'.format( message_descriptor.full_name, name)) if name in names: raise ParseError( 'Message type "{0}" should not have multiple "{1}" fields.'.format( message.DESCRIPTOR.full_name, name)) names.append(name) # Check no other oneof field is parsed. if field.containing_oneof is not None: oneof_name = field.containing_oneof.name if oneof_name in names: raise ParseError('Message type "{0}" should not have multiple "{1}" ' 'oneof fields.'.format( message.DESCRIPTOR.full_name, oneof_name)) names.append(oneof_name) value = js[name] if value is None: message.ClearField(field.name) continue # Parse field value. if _IsMapEntry(field): message.ClearField(field.name) _ConvertMapFieldValue(value, message, field) elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: message.ClearField(field.name) if not isinstance(value, list): raise ParseError('repeated field {0} must be in [] which is ' '{1}.'.format(name, value)) if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: # Repeated message field. for item in value: sub_message = getattr(message, field.name).add() # None is a null_value in Value. if (item is None and sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'): raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') _ConvertMessage(item, sub_message) else: # Repeated scalar field. for item in value: if item is None: raise ParseError('null is not allowed to be used as an element' ' in a repeated field.') getattr(message, field.name).append( _ConvertScalarFieldValue(item, field)) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: sub_message = getattr(message, field.name) _ConvertMessage(value, sub_message) else: setattr(message, field.name, _ConvertScalarFieldValue(value, field)) except ParseError as e: if field and field.containing_oneof is None: raise ParseError('Failed to parse {0} field: {1}'.format(name, e)) else: raise ParseError(str(e)) except ValueError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e)) except TypeError as e: raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
python
{ "resource": "" }
q265638
_ConvertMessage
validation
def _ConvertMessage(value, message): """Convert a JSON object into a message. Args: value: A JSON object. message: A WKT or regular protocol message to record the data. Raises: ParseError: In case of convert problems. """ message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): _ConvertWrapperMessage(value, message) elif full_name in _WKTJSONMETHODS: _WKTJSONMETHODS[full_name][1](value, message) else: _ConvertFieldValuePair(value, message)
python
{ "resource": "" }
q265639
_ConvertValueMessage
validation
def _ConvertValueMessage(value, message): """Convert a JSON representation into Value message.""" if isinstance(value, dict): _ConvertStructMessage(value, message.struct_value) elif isinstance(value, list): _ConvertListValueMessage(value, message.list_value) elif value is None: message.null_value = 0 elif isinstance(value, bool): message.bool_value = value elif isinstance(value, six.string_types): message.string_value = value elif isinstance(value, _INT_OR_FLOAT): message.number_value = value else: raise ParseError('Unexpected type for Value message.')
python
{ "resource": "" }
q265640
_ConvertListValueMessage
validation
def _ConvertListValueMessage(value, message): """Convert a JSON representation into ListValue message.""" if not isinstance(value, list): raise ParseError( 'ListValue must be in [] which is {0}.'.format(value)) message.ClearField('values') for item in value: _ConvertValueMessage(item, message.values.add())
python
{ "resource": "" }
q265641
_ConvertStructMessage
validation
def _ConvertStructMessage(value, message): """Convert a JSON representation into Struct message.""" if not isinstance(value, dict): raise ParseError( 'Struct must be in a dict which is {0}.'.format(value)) for key in value: _ConvertValueMessage(value[key], message.fields[key]) return
python
{ "resource": "" }
q265642
update_config
validation
def update_config(new_config): """ Update config options with the provided dictionary of options. """ flask_app.base_config.update(new_config) # Check for changed working directory. if new_config.has_key('working_directory'): wd = os.path.abspath(new_config['working_directory']) if nbmanager.notebook_dir != wd: if not os.path.exists(wd): raise IOError('Path not found: %s' % wd) nbmanager.notebook_dir = wd
python
{ "resource": "" }
q265643
Timing.end_timing
validation
def end_timing(self): """ Completes measuring time interval and updates counter. """ if self._callback != None: elapsed = time.clock() * 1000 - self._start self._callback.end_timing(self._counter, elapsed)
python
{ "resource": "" }
q265644
Duration.ToJsonString
validation
def ToJsonString(self): """Converts Duration to string format. Returns: A string converted from self. The string format will contains 3, 6, or 9 fractional digits depending on the precision required to represent the exact Duration value. For example: "1s", "1.010s", "1.000000100s", "-3.100s" """ if self.seconds < 0 or self.nanos < 0: result = '-' seconds = - self.seconds + int((0 - self.nanos) // 1e9) nanos = (0 - self.nanos) % 1e9 else: result = '' seconds = self.seconds + int(self.nanos // 1e9) nanos = self.nanos % 1e9 result += '%d' % seconds if (nanos % 1e9) == 0: # If there are 0 fractional digits, the fractional # point '.' should be omitted when serializing. return result + 's' if (nanos % 1e6) == 0: # Serialize 3 fractional digits. return result + '.%03ds' % (nanos / 1e6) if (nanos % 1e3) == 0: # Serialize 6 fractional digits. return result + '.%06ds' % (nanos / 1e3) # Serialize 9 fractional digits. return result + '.%09ds' % nanos
python
{ "resource": "" }
q265645
Duration.FromJsonString
validation
def FromJsonString(self, value): """Converts a string to Duration. Args: value: A string to be converted. The string must end with 's'. Any fractional digits (or none) are accepted as long as they fit into precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s Raises: ParseError: On parsing problems. """ if len(value) < 1 or value[-1] != 's': raise ParseError( 'Duration must end with letter "s": {0}.'.format(value)) try: pos = value.find('.') if pos == -1: self.seconds = int(value[:-1]) self.nanos = 0 else: self.seconds = int(value[:pos]) if value[0] == '-': self.nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9)) else: self.nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9)) except ValueError: raise ParseError( 'Couldn\'t parse duration: {0}.'.format(value))
python
{ "resource": "" }
q265646
FieldMask.FromJsonString
validation
def FromJsonString(self, value): """Converts string to FieldMask according to proto3 JSON spec.""" self.Clear() for path in value.split(','): self.paths.append(path)
python
{ "resource": "" }
q265647
get_doc
validation
def get_doc(doc_id, db_name, server_url='http://127.0.0.1:5984/', rev=None): """Return a CouchDB document, given its ID, revision and database name.""" db = get_server(server_url)[db_name] if rev: headers, response = db.resource.get(doc_id, rev=rev) return couchdb.client.Document(response) return db[doc_id]
python
{ "resource": "" }
q265648
read
validation
def read(readme): """Give reST format README for pypi.""" extend = os.path.splitext(readme)[1] if (extend == '.rst'): import codecs return codecs.open(readme, 'r', 'utf-8').read() elif (extend == '.md'): import pypandoc return pypandoc.convert(readme, 'rst')
python
{ "resource": "" }
q265649
DataStore.remove
validation
def remove(self, collection, **kwargs): ''' remove records from collection whose parameters match kwargs ''' callback = kwargs.pop('callback') yield Op(self.db[collection].remove, kwargs) callback()
python
{ "resource": "" }
q265650
TrelloAPI._url
validation
def _url(self): """ Resolve the URL to this point. >>> trello = TrelloAPIV1('APIKEY') >>> trello.batch._url '1/batch' >>> trello.boards(board_id='BOARD_ID')._url '1/boards/BOARD_ID' >>> trello.boards(board_id='BOARD_ID')(field='FIELD')._url '1/boards/BOARD_ID/FIELD' >>> trello.boards(board_id='BOARD_ID').cards(filter='FILTER')._url '1/boards/BOARD_ID/cards/FILTER' """ if self._api_arg: mypart = str(self._api_arg) else: mypart = self._name if self._parent: return '/'.join(filter(None, [self._parent._url, mypart])) else: return mypart
python
{ "resource": "" }
q265651
TrelloAPI._api_call
validation
def _api_call(self, method_name, *args, **kwargs): """ Makes the HTTP request. """ params = kwargs.setdefault('params', {}) params.update({'key': self._apikey}) if self._token is not None: params.update({'token': self._token}) http_method = getattr(requests, method_name) return http_method(TRELLO_URL + self._url, *args, **kwargs)
python
{ "resource": "" }
q265652
_SkipFieldValue
validation
def _SkipFieldValue(tokenizer): """Skips over a field value. Args: tokenizer: A tokenizer to parse the field name and values. Raises: ParseError: In case an invalid field value is found. """ # String/bytes tokens can come in multiple adjacent string literals. # If we can consume one, consume as many as we can. if tokenizer.TryConsumeByteString(): while tokenizer.TryConsumeByteString(): pass return if (not tokenizer.TryConsumeIdentifier() and not tokenizer.TryConsumeInt64() and not tokenizer.TryConsumeUint64() and not tokenizer.TryConsumeFloat()): raise ParseError('Invalid field value: ' + tokenizer.token)
python
{ "resource": "" }
q265653
ParseInteger
validation
def ParseInteger(text, is_signed=False, is_long=False): """Parses an integer. Args: text: The text to parse. is_signed: True if a signed integer must be parsed. is_long: True if a long integer must be parsed. Returns: The integer value. Raises: ValueError: Thrown Iff the text is not a valid integer. """ # Do the actual parsing. Exception handling is propagated to caller. try: # We force 32-bit values to int and 64-bit values to long to make # alternate implementations where the distinction is more significant # (e.g. the C++ implementation) simpler. if is_long: result = long(text, 0) else: result = int(text, 0) except ValueError: raise ValueError('Couldn\'t parse integer: %s' % text) # Check if the integer is sane. Exceptions handled by callers. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)] checker.CheckValue(result) return result
python
{ "resource": "" }
q265654
_Printer.PrintMessage
validation
def PrintMessage(self, message): """Convert protobuf message to text format. Args: message: The protocol buffers message. """ fields = message.ListFields() if self.use_index_order: fields.sort(key=lambda x: x[0].index) for field, value in fields: if _IsMapEntry(field): for key in sorted(value): # This is slow for maps with submessage entires because it copies the # entire tree. Unfortunately this would take significant refactoring # of this file to work around. # # TODO(haberman): refactor and optimize if this becomes an issue. entry_submsg = field.message_type._concrete_class( key=key, value=value[key]) self.PrintField(field, entry_submsg) elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED: for element in value: self.PrintField(field, element) else: self.PrintField(field, value)
python
{ "resource": "" }
q265655
_Parser._ParseOrMerge
validation
def _ParseOrMerge(self, lines, message): """Converts an text representation of a protocol message into a message. Args: lines: Lines of a message's text representation. message: A protocol buffer message to merge into. Raises: ParseError: On text parsing problems. """ tokenizer = _Tokenizer(lines) while not tokenizer.AtEnd(): self._MergeField(tokenizer, message)
python
{ "resource": "" }
q265656
_Parser._MergeMessageField
validation
def _MergeMessageField(self, tokenizer, message, field): """Merges a single scalar field into a message. Args: tokenizer: A tokenizer to parse the field value. message: The message of which field is a member. field: The descriptor of the field to be merged. Raises: ParseError: In case of text parsing problems. """ is_map_entry = _IsMapEntry(field) if tokenizer.TryConsume('<'): end_token = '>' else: tokenizer.Consume('{') end_token = '}' if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: if field.is_extension: sub_message = message.Extensions[field].add() elif is_map_entry: # pylint: disable=protected-access sub_message = field.message_type._concrete_class() else: sub_message = getattr(message, field.name).add() else: if field.is_extension: sub_message = message.Extensions[field] else: sub_message = getattr(message, field.name) sub_message.SetInParent() while not tokenizer.TryConsume(end_token): if tokenizer.AtEnd(): raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,)) self._MergeField(tokenizer, sub_message) if is_map_entry: value_cpptype = field.message_type.fields_by_name['value'].cpp_type if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: value = getattr(message, field.name)[sub_message.key] value.MergeFrom(sub_message.value) else: getattr(message, field.name)[sub_message.key] = sub_message.value
python
{ "resource": "" }
q265657
_Tokenizer.ConsumeIdentifier
validation
def ConsumeIdentifier(self): """Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier couldn't be consumed. """ result = self.token if not self._IDENTIFIER.match(result): raise self._ParseError('Expected identifier.') self.NextToken() return result
python
{ "resource": "" }
q265658
_Tokenizer.ConsumeInt32
validation
def ConsumeInt32(self): """Consumes a signed 32bit integer number. Returns: The integer parsed. Raises: ParseError: If a signed 32bit integer couldn't be consumed. """ try: result = ParseInteger(self.token, is_signed=True, is_long=False) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
python
{ "resource": "" }
q265659
_Tokenizer.ConsumeFloat
validation
def ConsumeFloat(self): """Consumes an floating point number. Returns: The number parsed. Raises: ParseError: If a floating point number couldn't be consumed. """ try: result = ParseFloat(self.token) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
python
{ "resource": "" }
q265660
_Tokenizer.ConsumeBool
validation
def ConsumeBool(self): """Consumes a boolean value. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed. """ try: result = ParseBool(self.token) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
python
{ "resource": "" }
q265661
_Tokenizer._ConsumeSingleByteString
validation
def _ConsumeSingleByteString(self): """Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token. Returns: The token parsed. Raises: ParseError: When the wrong format data is found. """ text = self.token if len(text) < 1 or text[0] not in _QUOTES: raise self._ParseError('Expected string but found: %r' % (text,)) if len(text) < 2 or text[-1] != text[0]: raise self._ParseError('String missing ending quote: %r' % (text,)) try: result = text_encoding.CUnescape(text[1:-1]) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
python
{ "resource": "" }
q265662
arkt_to_unixt
validation
def arkt_to_unixt(ark_timestamp): """ convert ark timestamp to unix timestamp""" res = datetime.datetime(2017, 3, 21, 15, 55, 44) + datetime.timedelta(seconds=ark_timestamp) return res.timestamp()
python
{ "resource": "" }
q265663
Mssql.close
validation
def close(self): """Close the connection.""" try: self.conn.close() self.logger.debug("Close connect succeed.") except pymssql.Error as e: self.unknown("Close connect error: %s" % e)
python
{ "resource": "" }
q265664
Preprocessor.process_macros
validation
def process_macros(self, content: str) -> str: '''Replace macros with content defined in the config. :param content: Markdown content :returns: Markdown content without macros ''' def _sub(macro): name = macro.group('body') params = self.get_options(macro.group('options')) return self.options['macros'].get(name, '').format_map(params) return self.pattern.sub(_sub, content)
python
{ "resource": "" }
q265665
get_unique_pathname
validation
def get_unique_pathname(path, root=''): """Return a pathname possibly with a number appended to it so that it is unique in the directory.""" path = os.path.join(root, path) # consider the path supplied, then the paths with numbers appended potentialPaths = itertools.chain((path,), __get_numbered_paths(path)) potentialPaths = six.moves.filterfalse(os.path.exists, potentialPaths) return next(potentialPaths)
python
{ "resource": "" }
q265666
__get_numbered_paths
validation
def __get_numbered_paths(filepath): """Append numbers in sequential order to the filename or folder name Numbers should be appended before the extension on a filename.""" format = '%s (%%d)%s' % splitext_files_only(filepath) return map(lambda n: format % n, itertools.count(1))
python
{ "resource": "" }
q265667
splitext_files_only
validation
def splitext_files_only(filepath): "Custom version of splitext that doesn't perform splitext on directories" return ( (filepath, '') if os.path.isdir(filepath) else os.path.splitext(filepath) )
python
{ "resource": "" }
q265668
set_time
validation
def set_time(filename, mod_time): """ Set the modified time of a file """ log.debug('Setting modified time to %s', mod_time) mtime = calendar.timegm(mod_time.utctimetuple()) # utctimetuple discards microseconds, so restore it (for consistency) mtime += mod_time.microsecond / 1000000 atime = os.stat(filename).st_atime os.utime(filename, (atime, mtime))
python
{ "resource": "" }
q265669
get_time
validation
def get_time(filename): """ Get the modified time for a file as a datetime instance """ ts = os.stat(filename).st_mtime return datetime.datetime.utcfromtimestamp(ts)
python
{ "resource": "" }
q265670
ensure_dir_exists
validation
def ensure_dir_exists(func): "wrap a function that returns a dir, making sure it exists" @functools.wraps(func) def make_if_not_present(): dir = func() if not os.path.isdir(dir): os.makedirs(dir) return dir return make_if_not_present
python
{ "resource": "" }
q265671
is_hidden
validation
def is_hidden(path): """ Check whether a file is presumed hidden, either because the pathname starts with dot or because the platform indicates such. """ full_path = os.path.abspath(path) name = os.path.basename(full_path) def no(path): return False platform_hidden = globals().get('is_hidden_' + platform.system(), no) return name.startswith('.') or platform_hidden(full_path)
python
{ "resource": "" }
q265672
SerialReader.age
validation
def age(self): """ Get closer to your EOL """ # 0 means this composer will never decompose if self.rounds == 1: self.do_run = False elif self.rounds > 1: self.rounds -= 1
python
{ "resource": "" }
q265673
SerialReader.run
validation
def run(self): """ Open a connection over the serial line and receive data lines """ if not self.device: return try: data = "" while (self.do_run): try: if (self.device.inWaiting() > 1): l = self.device.readline()[:-2] l = l.decode("UTF-8") if (l == "["): # start recording data = "[" elif (l == "]") and (len(data) > 4) and (data[0] == "["): # now parse the input data = data + "]" self.store.register_json(data) self.age() elif (l[0:3] == " {"): # this is a data line data = data + " " + l else: # this is a slow interface - give it some time sleep(1) # then count down.. self.age() except (UnicodeDecodeError, ValueError): # only accepting unicode: throw away the whole bunch data = "" # and count down the exit condition self.age() except serial.serialutil.SerialException: print("Could not connect to the serial line at " + self.device_name)
python
{ "resource": "" }
q265674
ThreadCreator.append_main_thread
validation
def append_main_thread(self): """create & start main thread :return: None """ thread = MainThread(main_queue=self.main_queue, main_spider=self.main_spider, branch_spider=self.branch_spider) thread.daemon = True thread.start()
python
{ "resource": "" }
q265675
getTextFromNode
validation
def getTextFromNode(node): """ Scans through all children of node and gathers the text. If node has non-text child-nodes then NotTextNodeError is raised. """ t = "" for n in node.childNodes: if n.nodeType == n.TEXT_NODE: t += n.nodeValue else: raise NotTextNodeError return t
python
{ "resource": "" }
q265676
AmbientSMS.getbalance
validation
def getbalance(self, url='http://services.ambientmobile.co.za/credits'): """ Get the number of credits remaining at AmbientSMS """ postXMLList = [] postXMLList.append("<api-key>%s</api-key>" % self.api_key) postXMLList.append("<password>%s</password>" % self.password) postXML = '<sms>%s</sms>' % "".join(postXMLList) result = self.curl(url, postXML) if result.get("credits", None): return result["credits"] else: raise AmbientSMSError(result["status"])
python
{ "resource": "" }
q265677
AmbientSMS.sendmsg
validation
def sendmsg(self, message, recipient_mobiles=[], url='http://services.ambientmobile.co.za/sms', concatenate_message=True, message_id=str(time()).replace(".", ""), reply_path=None, allow_duplicates=True, allow_invalid_numbers=True, ): """ Send a mesage via the AmbientSMS API server """ if not recipient_mobiles or not(isinstance(recipient_mobiles, list) \ or isinstance(recipient_mobiles, tuple)): raise AmbientSMSError("Missing recipients") if not message or not len(message): raise AmbientSMSError("Missing message") postXMLList = [] postXMLList.append("<api-key>%s</api-key>" % self.api_key) postXMLList.append("<password>%s</password>" % self.password) postXMLList.append("<recipients>%s</recipients>" % \ "".join(["<mobile>%s</mobile>" % \ m for m in recipient_mobiles])) postXMLList.append("<msg>%s</msg>" % message) postXMLList.append("<concat>%s</concat>" % \ (1 if concatenate_message else 0)) postXMLList.append("<message_id>%s</message_id>" % message_id) postXMLList.append("<allow_duplicates>%s</allow_duplicates>" % \ (1 if allow_duplicates else 0)) postXMLList.append( "<allow_invalid_numbers>%s</allow_invalid_numbers>" % \ (1 if allow_invalid_numbers else 0) ) if reply_path: postXMLList.append("<reply_path>%s</reply_path>" % reply_path) postXML = '<sms>%s</sms>' % "".join(postXMLList) result = self.curl(url, postXML) status = result.get("status", None) if status and int(status) in [0, 1, 2]: return result else: raise AmbientSMSError(int(status))
python
{ "resource": "" }
q265678
AmbientSMS.curl
validation
def curl(self, url, post): """ Inteface for sending web requests to the AmbientSMS API Server """ try: req = urllib2.Request(url) req.add_header("Content-type", "application/xml") data = urllib2.urlopen(req, post.encode('utf-8')).read() except urllib2.URLError, v: raise AmbientSMSError(v) return dictFromXml(data)
python
{ "resource": "" }
q265679
DefaultMinifier.contents
validation
def contents(self, f, text): """ Called for each file Must return file content Can be wrapped :type f: static_bundle.files.StaticFileResult :type text: str|unicode :rtype: str|unicode """ text += self._read(f.abs_path) + "\r\n" return text
python
{ "resource": "" }
q265680
is_date_type
validation
def is_date_type(cls): """Return True if the class is a date type.""" if not isinstance(cls, type): return False return issubclass(cls, date) and not issubclass(cls, datetime)
python
{ "resource": "" }
q265681
to_datetime
validation
def to_datetime(when): """ Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If when is a time it sets the date to the epoch. If when is None or a datetime it returns when. Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is a datetime with tzinfo set in which case it remains the same. """ if when is None or is_datetime(when): return when if is_time(when): return datetime.combine(epoch.date(), when) if is_date(when): return datetime.combine(when, time(0)) raise TypeError("unable to convert {} to datetime".format(when.__class__.__name__))
python
{ "resource": "" }
q265682
totz
validation
def totz(when, tz=None): """ Return a date, time, or datetime converted to a datetime in the given timezone. If when is a datetime and has no timezone it is assumed to be local time. Date and time objects are also assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be converted to a datetime. """ if when is None: return None when = to_datetime(when) if when.tzinfo is None: when = when.replace(tzinfo=localtz) return when.astimezone(tz or utc)
python
{ "resource": "" }
q265683
ts
validation
def ts(when, tz=None): """ Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called on the datetime to convert it to the provided timezone. It will be converted to UTC if no timezone is provided. """ if not when: return None when = totz(when, tz) return calendar.timegm(when.timetuple())
python
{ "resource": "" }
q265684
tsms
validation
def tsms(when, tz=None): """ Return a Unix timestamp in milliseconds for the provided datetime. The `totz` function is called on the datetime to convert it to the provided timezone. It will be converted to UTC if no timezone is provided. """ if not when: return None when = totz(when, tz) return calendar.timegm(when.timetuple()) * 1000 + int(round(when.microsecond / 1000.0))
python
{ "resource": "" }
q265685
fromts
validation
def fromts(ts, tzin=None, tzout=None): """ Return the datetime representation of the provided Unix timestamp. By defaults the timestamp is interpreted as UTC. If tzin is set it will be interpreted as this timestamp instead. By default the output datetime will have UTC time. If tzout is set it will be converted in this timezone instead. """ if ts is None: return None when = datetime.utcfromtimestamp(ts).replace(tzinfo=tzin or utc) return totz(when, tzout)
python
{ "resource": "" }
q265686
fromtsms
validation
def fromtsms(ts, tzin=None, tzout=None): """ Return the Unix timestamp in milliseconds as a datetime object. If tz is set it will be converted to the requested timezone otherwise it defaults to UTC. """ if ts is None: return None when = datetime.utcfromtimestamp(ts / 1000).replace(microsecond=ts % 1000 * 1000) when = when.replace(tzinfo=tzin or utc) return totz(when, tzout)
python
{ "resource": "" }
q265687
truncate
validation
def truncate(when, unit, week_start=mon): """Return the datetime truncated to the precision of the provided unit.""" if is_datetime(when): if unit == millisecond: return when.replace(microsecond=int(round(when.microsecond / 1000.0)) * 1000) elif unit == second: return when.replace(microsecond=0) elif unit == minute: return when.replace(second=0, microsecond=0) elif unit == hour: return when.replace(minute=0, second=0, microsecond=0) elif unit == day: return when.replace(hour=0, minute=0, second=0, microsecond=0) elif unit == week: weekday = prevweekday(when, week_start) return when.replace(year=weekday.year, month=weekday.month, day=weekday.day, hour=0, minute=0, second=0, microsecond=0) elif unit == month: return when.replace(day=1, hour=0, minute=0, second=0, microsecond=0) elif unit == year: return when.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) elif is_date(when): if unit == week: return prevweekday(when, week_start) elif unit == month: return when.replace(day=1) elif unit == year: return when.replace(month=1, day=1) elif is_time(when): if unit == millisecond: return when.replace(microsecond=int(when.microsecond / 1000.0) * 1000) elif unit == second: return when.replace(microsecond=0) elif unit == minute: return when.replace(second=0, microsecond=0) return when
python
{ "resource": "" }
q265688
weekday
validation
def weekday(when, weekday, start=mon): """Return the date for the day of this week.""" if isinstance(when, datetime): when = when.date() today = when.weekday() delta = weekday - today if weekday < start and today >= start: delta += 7 elif weekday >= start and today < start: delta -= 7 return when + timedelta(days=delta)
python
{ "resource": "" }
q265689
_GetNativeEolStyle
validation
def _GetNativeEolStyle(platform=sys.platform): ''' Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the current platform. ''' _NATIVE_EOL_STYLE_MAP = { 'win32' : EOL_STYLE_WINDOWS, 'linux2' : EOL_STYLE_UNIX, 'linux' : EOL_STYLE_UNIX, 'darwin' : EOL_STYLE_MAC, } result = _NATIVE_EOL_STYLE_MAP.get(platform) if result is None: from ._exceptions import UnknownPlatformError raise UnknownPlatformError(platform) return result
python
{ "resource": "" }
q265690
NormalizePath
validation
def NormalizePath(path): ''' Normalizes a path maintaining the final slashes. Some environment variables need the final slash in order to work. Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used in the Visual Studio projects. :param unicode path: The path to normalize. :rtype: unicode :returns: Normalized path ''' if path.endswith('/') or path.endswith('\\'): slash = os.path.sep else: slash = '' return os.path.normpath(path) + slash
python
{ "resource": "" }
q265691
CanonicalPath
validation
def CanonicalPath(path): ''' Returns a version of a path that is unique. Given two paths path1 and path2: CanonicalPath(path1) == CanonicalPath(path2) if and only if they represent the same file on the host OS. Takes account of case, slashes and relative paths. :param unicode path: The original path. :rtype: unicode :returns: The unique path. ''' path = os.path.normpath(path) path = os.path.abspath(path) path = os.path.normcase(path) return path
python
{ "resource": "" }
q265692
StandardizePath
validation
def StandardizePath(path, strip=False): ''' Replaces all slashes and backslashes with the target separator StandardPath: We are defining that the standard-path is the one with only back-slashes in it, either on Windows or any other platform. :param bool strip: If True, removes additional slashes from the end of the path. ''' path = path.replace(SEPARATOR_WINDOWS, SEPARATOR_UNIX) if strip: path = path.rstrip(SEPARATOR_UNIX) return path
python
{ "resource": "" }
q265693
CopyFile
validation
def CopyFile(source_filename, target_filename, override=True, md5_check=False, copy_symlink=True): ''' Copy a file from source to target. :param source_filename: @see _DoCopyFile :param target_filename: @see _DoCopyFile :param bool md5_check: If True, checks md5 files (of both source and target files), if they match, skip this copy and return MD5_SKIP Md5 files are assumed to be {source, target} + '.md5' If any file is missing (source, target or md5), the copy will always be made. :param copy_symlink: @see _DoCopyFile :raises FileAlreadyExistsError: If target_filename already exists, and override is False :raises NotImplementedProtocol: If file protocol is not accepted Protocols allowed are: source_filename: local, ftp, http target_filename: local, ftp :rtype: None | MD5_SKIP :returns: MD5_SKIP if the file was not copied because there was a matching .md5 file .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information ''' from ._exceptions import FileNotFoundError # Check override if not override and Exists(target_filename): from ._exceptions import FileAlreadyExistsError raise FileAlreadyExistsError(target_filename) # Don't do md5 check for md5 files themselves. md5_check = md5_check and not target_filename.endswith('.md5') # If we enabled md5 checks, ignore copy of files that haven't changed their md5 contents. if md5_check: source_md5_filename = source_filename + '.md5' target_md5_filename = target_filename + '.md5' try: source_md5_contents = GetFileContents(source_md5_filename) except FileNotFoundError: source_md5_contents = None try: target_md5_contents = GetFileContents(target_md5_filename) except FileNotFoundError: target_md5_contents = None if source_md5_contents is not None and \ source_md5_contents == target_md5_contents and \ Exists(target_filename): return MD5_SKIP # Copy source file _DoCopyFile(source_filename, target_filename, copy_symlink=copy_symlink) # If we have a source_md5, but no target_md5, create the target_md5 file if md5_check and source_md5_contents is not None and source_md5_contents != target_md5_contents: CreateFile(target_md5_filename, source_md5_contents)
python
{ "resource": "" }
q265694
_CopyFileLocal
validation
def _CopyFileLocal(source_filename, target_filename, copy_symlink=True): ''' Copy a file locally to a directory. :param unicode source_filename: The filename to copy from. :param unicode target_filename: The filename to copy to. :param bool copy_symlink: If True and source_filename is a symlink, target_filename will also be created as a symlink. If False, the file being linked will be copied instead. ''' import shutil try: # >>> Create the target_filename directory if necessary dir_name = os.path.dirname(target_filename) if dir_name and not os.path.isdir(dir_name): os.makedirs(dir_name) if copy_symlink and IsLink(source_filename): # >>> Delete the target_filename if it already exists if os.path.isfile(target_filename) or IsLink(target_filename): DeleteFile(target_filename) # >>> Obtain the relative path from link to source_filename (linkto) source_filename = ReadLink(source_filename) CreateLink(source_filename, target_filename) else: # shutil can't copy links in Windows, so we must find the real file manually if sys.platform == 'win32': while IsLink(source_filename): link = ReadLink(source_filename) if os.path.isabs(link): source_filename = link else: source_filename = os.path.join(os.path.dirname(source_filename), link) shutil.copyfile(source_filename, target_filename) shutil.copymode(source_filename, target_filename) except Exception as e: reraise(e, 'While executiong _filesystem._CopyFileLocal(%s, %s)' % (source_filename, target_filename))
python
{ "resource": "" }
q265695
CopyFiles
validation
def CopyFiles(source_dir, target_dir, create_target_dir=False, md5_check=False): ''' Copy files from the given source to the target. :param unicode source_dir: A filename, URL or a file mask. Ex. x:\coilib50 x:\coilib50\* http://server/directory/file ftp://server/directory/file :param unicode target_dir: A directory or an URL Ex. d:\Temp ftp://server/directory :param bool create_target_dir: If True, creates the target path if it doesn't exists. :param bool md5_check: .. seealso:: CopyFile :raises DirectoryNotFoundError: If target_dir does not exist, and create_target_dir is False .. seealso:: CopyFile for documentation on accepted protocols .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information ''' import fnmatch # Check if we were given a directory or a directory with mask if IsDir(source_dir): # Yes, it's a directory, copy everything from it source_mask = '*' else: # Split directory and mask source_dir, source_mask = os.path.split(source_dir) # Create directory if necessary if not IsDir(target_dir): if create_target_dir: CreateDirectory(target_dir) else: from ._exceptions import DirectoryNotFoundError raise DirectoryNotFoundError(target_dir) # List and match files filenames = ListFiles(source_dir) # Check if we have a source directory if filenames is None: return # Copy files for i_filename in filenames: if md5_check and i_filename.endswith('.md5'): continue # md5 files will be copied by CopyFile when copying their associated files if fnmatch.fnmatch(i_filename, source_mask): source_path = source_dir + '/' + i_filename target_path = target_dir + '/' + i_filename if IsDir(source_path): # If we found a directory, copy it recursively CopyFiles(source_path, target_path, create_target_dir=True, md5_check=md5_check) else: CopyFile(source_path, target_path, md5_check=md5_check)
python
{ "resource": "" }
q265696
CopyFilesX
validation
def CopyFilesX(file_mapping): ''' Copies files into directories, according to a file mapping :param list(tuple(unicode,unicode)) file_mapping: A list of mappings between the directory in the target and the source. For syntax, @see: ExtendedPathMask :rtype: list(tuple(unicode,unicode)) :returns: List of files copied. (source_filename, target_filename) .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information ''' # List files that match the mapping files = [] for i_target_path, i_source_path_mask in file_mapping: tree_recurse, flat_recurse, dirname, in_filters, out_filters = ExtendedPathMask.Split(i_source_path_mask) _AssertIsLocal(dirname) filenames = FindFiles(dirname, in_filters, out_filters, tree_recurse) for i_source_filename in filenames: if os.path.isdir(i_source_filename): continue # Do not copy dirs i_target_filename = i_source_filename[len(dirname) + 1:] if flat_recurse: i_target_filename = os.path.basename(i_target_filename) i_target_filename = os.path.join(i_target_path, i_target_filename) files.append(( StandardizePath(i_source_filename), StandardizePath(i_target_filename) )) # Copy files for i_source_filename, i_target_filename in files: # Create target dir if necessary target_dir = os.path.dirname(i_target_filename) CreateDirectory(target_dir) CopyFile(i_source_filename, i_target_filename) return files
python
{ "resource": "" }
q265697
CopyDirectory
validation
def CopyDirectory(source_dir, target_dir, override=False): ''' Recursively copy a directory tree. :param unicode source_dir: Where files will come from :param unicode target_dir: Where files will go to :param bool override: If True and target_dir already exists, it will be deleted before copying. :raises NotImplementedForRemotePathError: If trying to copy to/from remote directories ''' _AssertIsLocal(source_dir) _AssertIsLocal(target_dir) if override and IsDir(target_dir): DeleteDirectory(target_dir, skip_on_error=False) import shutil shutil.copytree(source_dir, target_dir)
python
{ "resource": "" }
q265698
DeleteFile
validation
def DeleteFile(target_filename): ''' Deletes the given local filename. .. note:: If file doesn't exist this method has no effect. :param unicode target_filename: A local filename :raises NotImplementedForRemotePathError: If trying to delete a non-local path :raises FileOnlyActionError: Raised when filename refers to a directory. ''' _AssertIsLocal(target_filename) try: if IsLink(target_filename): DeleteLink(target_filename) elif IsFile(target_filename): os.remove(target_filename) elif IsDir(target_filename): from ._exceptions import FileOnlyActionError raise FileOnlyActionError(target_filename) except Exception as e: reraise(e, 'While executing filesystem.DeleteFile(%s)' % (target_filename))
python
{ "resource": "" }
q265699
AppendToFile
validation
def AppendToFile(filename, contents, eol_style=EOL_STYLE_NATIVE, encoding=None, binary=False): ''' Appends content to a local file. :param unicode filename: :param unicode contents: :type eol_style: EOL_STYLE_XXX constant :param eol_style: Replaces the EOL by the appropriate EOL depending on the eol_style value. Considers that all content is using only "\n" as EOL. :param unicode encoding: Target file's content encoding. Defaults to sys.getfilesystemencoding() :param bool binary: If True, content is appended in binary mode. In this case, `contents` must be `bytes` and not `unicode` :raises NotImplementedForRemotePathError: If trying to modify a non-local path :raises ValueError: If trying to mix unicode `contents` without `encoding`, or `encoding` without unicode `contents` ''' _AssertIsLocal(filename) assert isinstance(contents, six.text_type) ^ binary, 'Must always receive unicode contents, unless binary=True' if not binary: # Replaces eol on each line by the given eol_style. contents = _HandleContentsEol(contents, eol_style) # Handle encoding here, and always write in binary mode. We can't use io.open because it # tries to do its own line ending handling. contents = contents.encode(encoding or sys.getfilesystemencoding()) oss = open(filename, 'ab') try: oss.write(contents) finally: oss.close()
python
{ "resource": "" }