id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
24,700
google/flatbuffers
python/flatbuffers/builder.py
Builder.StartVector
def StartVector(self, elemSize, numElems, alignment): """ StartVector initializes bookkeeping for writing a new vector. A vector has the following format: - <UOffsetT: number of elements in this vector> - <T: data>+, where T is the type of elements of this vector. """ self.assertNotNested() self.nested = True self.Prep(N.Uint32Flags.bytewidth, elemSize*numElems) self.Prep(alignment, elemSize*numElems) # In case alignment > int. return self.Offset()
python
def StartVector(self, elemSize, numElems, alignment): """ StartVector initializes bookkeeping for writing a new vector. A vector has the following format: - <UOffsetT: number of elements in this vector> - <T: data>+, where T is the type of elements of this vector. """ self.assertNotNested() self.nested = True self.Prep(N.Uint32Flags.bytewidth, elemSize*numElems) self.Prep(alignment, elemSize*numElems) # In case alignment > int. return self.Offset()
[ "def", "StartVector", "(", "self", ",", "elemSize", ",", "numElems", ",", "alignment", ")", ":", "self", ".", "assertNotNested", "(", ")", "self", ".", "nested", "=", "True", "self", ".", "Prep", "(", "N", ".", "Uint32Flags", ".", "bytewidth", ",", "elemSize", "*", "numElems", ")", "self", ".", "Prep", "(", "alignment", ",", "elemSize", "*", "numElems", ")", "# In case alignment > int.", "return", "self", ".", "Offset", "(", ")" ]
StartVector initializes bookkeeping for writing a new vector. A vector has the following format: - <UOffsetT: number of elements in this vector> - <T: data>+, where T is the type of elements of this vector.
[ "StartVector", "initializes", "bookkeeping", "for", "writing", "a", "new", "vector", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L371-L384
24,701
google/flatbuffers
python/flatbuffers/builder.py
Builder.EndVector
def EndVector(self, vectorNumElems): """EndVector writes data necessary to finish vector construction.""" self.assertNested() ## @cond FLATBUFFERS_INTERNAL self.nested = False ## @endcond # we already made space for this, so write without PrependUint32 self.PlaceUOffsetT(vectorNumElems) return self.Offset()
python
def EndVector(self, vectorNumElems): """EndVector writes data necessary to finish vector construction.""" self.assertNested() ## @cond FLATBUFFERS_INTERNAL self.nested = False ## @endcond # we already made space for this, so write without PrependUint32 self.PlaceUOffsetT(vectorNumElems) return self.Offset()
[ "def", "EndVector", "(", "self", ",", "vectorNumElems", ")", ":", "self", ".", "assertNested", "(", ")", "## @cond FLATBUFFERS_INTERNAL", "self", ".", "nested", "=", "False", "## @endcond", "# we already made space for this, so write without PrependUint32", "self", ".", "PlaceUOffsetT", "(", "vectorNumElems", ")", "return", "self", ".", "Offset", "(", ")" ]
EndVector writes data necessary to finish vector construction.
[ "EndVector", "writes", "data", "necessary", "to", "finish", "vector", "construction", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L387-L396
24,702
google/flatbuffers
python/flatbuffers/builder.py
Builder.CreateString
def CreateString(self, s, encoding='utf-8', errors='strict'): """CreateString writes a null-terminated byte string as a vector.""" self.assertNotNested() ## @cond FLATBUFFERS_INTERNAL self.nested = True ## @endcond if isinstance(s, compat.string_types): x = s.encode(encoding, errors) elif isinstance(s, compat.binary_types): x = s else: raise TypeError("non-string passed to CreateString") self.Prep(N.UOffsetTFlags.bytewidth, (len(x)+1)*N.Uint8Flags.bytewidth) self.Place(0, N.Uint8Flags) l = UOffsetTFlags.py_type(len(s)) ## @cond FLATBUFFERS_INTERNAL self.head = UOffsetTFlags.py_type(self.Head() - l) ## @endcond self.Bytes[self.Head():self.Head()+l] = x return self.EndVector(len(x))
python
def CreateString(self, s, encoding='utf-8', errors='strict'): """CreateString writes a null-terminated byte string as a vector.""" self.assertNotNested() ## @cond FLATBUFFERS_INTERNAL self.nested = True ## @endcond if isinstance(s, compat.string_types): x = s.encode(encoding, errors) elif isinstance(s, compat.binary_types): x = s else: raise TypeError("non-string passed to CreateString") self.Prep(N.UOffsetTFlags.bytewidth, (len(x)+1)*N.Uint8Flags.bytewidth) self.Place(0, N.Uint8Flags) l = UOffsetTFlags.py_type(len(s)) ## @cond FLATBUFFERS_INTERNAL self.head = UOffsetTFlags.py_type(self.Head() - l) ## @endcond self.Bytes[self.Head():self.Head()+l] = x return self.EndVector(len(x))
[ "def", "CreateString", "(", "self", ",", "s", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "self", ".", "assertNotNested", "(", ")", "## @cond FLATBUFFERS_INTERNAL", "self", ".", "nested", "=", "True", "## @endcond", "if", "isinstance", "(", "s", ",", "compat", ".", "string_types", ")", ":", "x", "=", "s", ".", "encode", "(", "encoding", ",", "errors", ")", "elif", "isinstance", "(", "s", ",", "compat", ".", "binary_types", ")", ":", "x", "=", "s", "else", ":", "raise", "TypeError", "(", "\"non-string passed to CreateString\"", ")", "self", ".", "Prep", "(", "N", ".", "UOffsetTFlags", ".", "bytewidth", ",", "(", "len", "(", "x", ")", "+", "1", ")", "*", "N", ".", "Uint8Flags", ".", "bytewidth", ")", "self", ".", "Place", "(", "0", ",", "N", ".", "Uint8Flags", ")", "l", "=", "UOffsetTFlags", ".", "py_type", "(", "len", "(", "s", ")", ")", "## @cond FLATBUFFERS_INTERNAL", "self", ".", "head", "=", "UOffsetTFlags", ".", "py_type", "(", "self", ".", "Head", "(", ")", "-", "l", ")", "## @endcond", "self", ".", "Bytes", "[", "self", ".", "Head", "(", ")", ":", "self", ".", "Head", "(", ")", "+", "l", "]", "=", "x", "return", "self", ".", "EndVector", "(", "len", "(", "x", ")", ")" ]
CreateString writes a null-terminated byte string as a vector.
[ "CreateString", "writes", "a", "null", "-", "terminated", "byte", "string", "as", "a", "vector", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L398-L422
24,703
google/flatbuffers
python/flatbuffers/builder.py
Builder.CreateByteVector
def CreateByteVector(self, x): """CreateString writes a byte vector.""" self.assertNotNested() ## @cond FLATBUFFERS_INTERNAL self.nested = True ## @endcond if not isinstance(x, compat.binary_types): raise TypeError("non-byte vector passed to CreateByteVector") self.Prep(N.UOffsetTFlags.bytewidth, len(x)*N.Uint8Flags.bytewidth) l = UOffsetTFlags.py_type(len(x)) ## @cond FLATBUFFERS_INTERNAL self.head = UOffsetTFlags.py_type(self.Head() - l) ## @endcond self.Bytes[self.Head():self.Head()+l] = x return self.EndVector(len(x))
python
def CreateByteVector(self, x): """CreateString writes a byte vector.""" self.assertNotNested() ## @cond FLATBUFFERS_INTERNAL self.nested = True ## @endcond if not isinstance(x, compat.binary_types): raise TypeError("non-byte vector passed to CreateByteVector") self.Prep(N.UOffsetTFlags.bytewidth, len(x)*N.Uint8Flags.bytewidth) l = UOffsetTFlags.py_type(len(x)) ## @cond FLATBUFFERS_INTERNAL self.head = UOffsetTFlags.py_type(self.Head() - l) ## @endcond self.Bytes[self.Head():self.Head()+l] = x return self.EndVector(len(x))
[ "def", "CreateByteVector", "(", "self", ",", "x", ")", ":", "self", ".", "assertNotNested", "(", ")", "## @cond FLATBUFFERS_INTERNAL", "self", ".", "nested", "=", "True", "## @endcond", "if", "not", "isinstance", "(", "x", ",", "compat", ".", "binary_types", ")", ":", "raise", "TypeError", "(", "\"non-byte vector passed to CreateByteVector\"", ")", "self", ".", "Prep", "(", "N", ".", "UOffsetTFlags", ".", "bytewidth", ",", "len", "(", "x", ")", "*", "N", ".", "Uint8Flags", ".", "bytewidth", ")", "l", "=", "UOffsetTFlags", ".", "py_type", "(", "len", "(", "x", ")", ")", "## @cond FLATBUFFERS_INTERNAL", "self", ".", "head", "=", "UOffsetTFlags", ".", "py_type", "(", "self", ".", "Head", "(", ")", "-", "l", ")", "## @endcond", "self", ".", "Bytes", "[", "self", ".", "Head", "(", ")", ":", "self", ".", "Head", "(", ")", "+", "l", "]", "=", "x", "return", "self", ".", "EndVector", "(", "len", "(", "x", ")", ")" ]
CreateString writes a byte vector.
[ "CreateString", "writes", "a", "byte", "vector", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L424-L443
24,704
google/flatbuffers
python/flatbuffers/builder.py
Builder.CreateNumpyVector
def CreateNumpyVector(self, x): """CreateNumpyVector writes a numpy array into the buffer.""" if np is None: # Numpy is required for this feature raise NumpyRequiredForThisFeature("Numpy was not found.") if not isinstance(x, np.ndarray): raise TypeError("non-numpy-ndarray passed to CreateNumpyVector") if x.dtype.kind not in ['b', 'i', 'u', 'f']: raise TypeError("numpy-ndarray holds elements of unsupported datatype") if x.ndim > 1: raise TypeError("multidimensional-ndarray passed to CreateNumpyVector") self.StartVector(x.itemsize, x.size, x.dtype.alignment) # Ensure little endian byte ordering if x.dtype.str[0] == "<": x_lend = x else: x_lend = x.byteswap(inplace=False) # Calculate total length l = UOffsetTFlags.py_type(x_lend.itemsize * x_lend.size) ## @cond FLATBUFFERS_INTERNAL self.head = UOffsetTFlags.py_type(self.Head() - l) ## @endcond # tobytes ensures c_contiguous ordering self.Bytes[self.Head():self.Head()+l] = x_lend.tobytes(order='C') return self.EndVector(x.size)
python
def CreateNumpyVector(self, x): """CreateNumpyVector writes a numpy array into the buffer.""" if np is None: # Numpy is required for this feature raise NumpyRequiredForThisFeature("Numpy was not found.") if not isinstance(x, np.ndarray): raise TypeError("non-numpy-ndarray passed to CreateNumpyVector") if x.dtype.kind not in ['b', 'i', 'u', 'f']: raise TypeError("numpy-ndarray holds elements of unsupported datatype") if x.ndim > 1: raise TypeError("multidimensional-ndarray passed to CreateNumpyVector") self.StartVector(x.itemsize, x.size, x.dtype.alignment) # Ensure little endian byte ordering if x.dtype.str[0] == "<": x_lend = x else: x_lend = x.byteswap(inplace=False) # Calculate total length l = UOffsetTFlags.py_type(x_lend.itemsize * x_lend.size) ## @cond FLATBUFFERS_INTERNAL self.head = UOffsetTFlags.py_type(self.Head() - l) ## @endcond # tobytes ensures c_contiguous ordering self.Bytes[self.Head():self.Head()+l] = x_lend.tobytes(order='C') return self.EndVector(x.size)
[ "def", "CreateNumpyVector", "(", "self", ",", "x", ")", ":", "if", "np", "is", "None", ":", "# Numpy is required for this feature", "raise", "NumpyRequiredForThisFeature", "(", "\"Numpy was not found.\"", ")", "if", "not", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"non-numpy-ndarray passed to CreateNumpyVector\"", ")", "if", "x", ".", "dtype", ".", "kind", "not", "in", "[", "'b'", ",", "'i'", ",", "'u'", ",", "'f'", "]", ":", "raise", "TypeError", "(", "\"numpy-ndarray holds elements of unsupported datatype\"", ")", "if", "x", ".", "ndim", ">", "1", ":", "raise", "TypeError", "(", "\"multidimensional-ndarray passed to CreateNumpyVector\"", ")", "self", ".", "StartVector", "(", "x", ".", "itemsize", ",", "x", ".", "size", ",", "x", ".", "dtype", ".", "alignment", ")", "# Ensure little endian byte ordering", "if", "x", ".", "dtype", ".", "str", "[", "0", "]", "==", "\"<\"", ":", "x_lend", "=", "x", "else", ":", "x_lend", "=", "x", ".", "byteswap", "(", "inplace", "=", "False", ")", "# Calculate total length", "l", "=", "UOffsetTFlags", ".", "py_type", "(", "x_lend", ".", "itemsize", "*", "x_lend", ".", "size", ")", "## @cond FLATBUFFERS_INTERNAL", "self", ".", "head", "=", "UOffsetTFlags", ".", "py_type", "(", "self", ".", "Head", "(", ")", "-", "l", ")", "## @endcond", "# tobytes ensures c_contiguous ordering", "self", ".", "Bytes", "[", "self", ".", "Head", "(", ")", ":", "self", ".", "Head", "(", ")", "+", "l", "]", "=", "x_lend", ".", "tobytes", "(", "order", "=", "'C'", ")", "return", "self", ".", "EndVector", "(", "x", ".", "size", ")" ]
CreateNumpyVector writes a numpy array into the buffer.
[ "CreateNumpyVector", "writes", "a", "numpy", "array", "into", "the", "buffer", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L445-L478
24,705
google/flatbuffers
python/flatbuffers/builder.py
Builder.assertStructIsInline
def assertStructIsInline(self, obj): """ Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere. """ N.enforce_number(obj, N.UOffsetTFlags) if obj != self.Offset(): msg = ("flatbuffers: Tried to write a Struct at an Offset that " "is different from the current Offset of the Builder.") raise StructIsNotInlineError(msg)
python
def assertStructIsInline(self, obj): """ Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere. """ N.enforce_number(obj, N.UOffsetTFlags) if obj != self.Offset(): msg = ("flatbuffers: Tried to write a Struct at an Offset that " "is different from the current Offset of the Builder.") raise StructIsNotInlineError(msg)
[ "def", "assertStructIsInline", "(", "self", ",", "obj", ")", ":", "N", ".", "enforce_number", "(", "obj", ",", "N", ".", "UOffsetTFlags", ")", "if", "obj", "!=", "self", ".", "Offset", "(", ")", ":", "msg", "=", "(", "\"flatbuffers: Tried to write a Struct at an Offset that \"", "\"is different from the current Offset of the Builder.\"", ")", "raise", "StructIsNotInlineError", "(", "msg", ")" ]
Structs are always stored inline, so need to be created right where they are used. You'll get this error if you created it elsewhere.
[ "Structs", "are", "always", "stored", "inline", "so", "need", "to", "be", "created", "right", "where", "they", "are", "used", ".", "You", "ll", "get", "this", "error", "if", "you", "created", "it", "elsewhere", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L498-L509
24,706
google/flatbuffers
python/flatbuffers/builder.py
Builder.Slot
def Slot(self, slotnum): """ Slot sets the vtable key `voffset` to the current location in the buffer. """ self.assertNested() self.current_vtable[slotnum] = self.Offset()
python
def Slot(self, slotnum): """ Slot sets the vtable key `voffset` to the current location in the buffer. """ self.assertNested() self.current_vtable[slotnum] = self.Offset()
[ "def", "Slot", "(", "self", ",", "slotnum", ")", ":", "self", ".", "assertNested", "(", ")", "self", ".", "current_vtable", "[", "slotnum", "]", "=", "self", ".", "Offset", "(", ")" ]
Slot sets the vtable key `voffset` to the current location in the buffer.
[ "Slot", "sets", "the", "vtable", "key", "voffset", "to", "the", "current", "location", "in", "the", "buffer", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L511-L518
24,707
google/flatbuffers
python/flatbuffers/builder.py
Builder.__Finish
def __Finish(self, rootTable, sizePrefix): """Finish finalizes a buffer, pointing to the given `rootTable`.""" N.enforce_number(rootTable, N.UOffsetTFlags) prepSize = N.UOffsetTFlags.bytewidth if sizePrefix: prepSize += N.Int32Flags.bytewidth self.Prep(self.minalign, prepSize) self.PrependUOffsetTRelative(rootTable) if sizePrefix: size = len(self.Bytes) - self.Head() N.enforce_number(size, N.Int32Flags) self.PrependInt32(size) self.finished = True return self.Head()
python
def __Finish(self, rootTable, sizePrefix): """Finish finalizes a buffer, pointing to the given `rootTable`.""" N.enforce_number(rootTable, N.UOffsetTFlags) prepSize = N.UOffsetTFlags.bytewidth if sizePrefix: prepSize += N.Int32Flags.bytewidth self.Prep(self.minalign, prepSize) self.PrependUOffsetTRelative(rootTable) if sizePrefix: size = len(self.Bytes) - self.Head() N.enforce_number(size, N.Int32Flags) self.PrependInt32(size) self.finished = True return self.Head()
[ "def", "__Finish", "(", "self", ",", "rootTable", ",", "sizePrefix", ")", ":", "N", ".", "enforce_number", "(", "rootTable", ",", "N", ".", "UOffsetTFlags", ")", "prepSize", "=", "N", ".", "UOffsetTFlags", ".", "bytewidth", "if", "sizePrefix", ":", "prepSize", "+=", "N", ".", "Int32Flags", ".", "bytewidth", "self", ".", "Prep", "(", "self", ".", "minalign", ",", "prepSize", ")", "self", ".", "PrependUOffsetTRelative", "(", "rootTable", ")", "if", "sizePrefix", ":", "size", "=", "len", "(", "self", ".", "Bytes", ")", "-", "self", ".", "Head", "(", ")", "N", ".", "enforce_number", "(", "size", ",", "N", ".", "Int32Flags", ")", "self", ".", "PrependInt32", "(", "size", ")", "self", ".", "finished", "=", "True", "return", "self", ".", "Head", "(", ")" ]
Finish finalizes a buffer, pointing to the given `rootTable`.
[ "Finish", "finalizes", "a", "buffer", "pointing", "to", "the", "given", "rootTable", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L521-L534
24,708
google/flatbuffers
python/flatbuffers/builder.py
Builder.PrependUOffsetTRelativeSlot
def PrependUOffsetTRelativeSlot(self, o, x, d): """ PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at vtable slot `o`. If value `x` equals default `d`, then the slot will be set to zero and no other data will be written. """ if x != d: self.PrependUOffsetTRelative(x) self.Slot(o)
python
def PrependUOffsetTRelativeSlot(self, o, x, d): """ PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at vtable slot `o`. If value `x` equals default `d`, then the slot will be set to zero and no other data will be written. """ if x != d: self.PrependUOffsetTRelative(x) self.Slot(o)
[ "def", "PrependUOffsetTRelativeSlot", "(", "self", ",", "o", ",", "x", ",", "d", ")", ":", "if", "x", "!=", "d", ":", "self", ".", "PrependUOffsetTRelative", "(", "x", ")", "self", ".", "Slot", "(", "o", ")" ]
PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at vtable slot `o`. If value `x` equals default `d`, then the slot will be set to zero and no other data will be written.
[ "PrependUOffsetTRelativeSlot", "prepends", "an", "UOffsetT", "onto", "the", "object", "at", "vtable", "slot", "o", ".", "If", "value", "x", "equals", "default", "d", "then", "the", "slot", "will", "be", "set", "to", "zero", "and", "no", "other", "data", "will", "be", "written", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L585-L594
24,709
google/flatbuffers
python/flatbuffers/builder.py
Builder.PrependStructSlot
def PrependStructSlot(self, v, x, d): """ PrependStructSlot prepends a struct onto the object at vtable slot `o`. Structs are stored inline, so nothing additional is being added. In generated code, `d` is always 0. """ N.enforce_number(d, N.UOffsetTFlags) if x != d: self.assertStructIsInline(x) self.Slot(v)
python
def PrependStructSlot(self, v, x, d): """ PrependStructSlot prepends a struct onto the object at vtable slot `o`. Structs are stored inline, so nothing additional is being added. In generated code, `d` is always 0. """ N.enforce_number(d, N.UOffsetTFlags) if x != d: self.assertStructIsInline(x) self.Slot(v)
[ "def", "PrependStructSlot", "(", "self", ",", "v", ",", "x", ",", "d", ")", ":", "N", ".", "enforce_number", "(", "d", ",", "N", ".", "UOffsetTFlags", ")", "if", "x", "!=", "d", ":", "self", ".", "assertStructIsInline", "(", "x", ")", "self", ".", "Slot", "(", "v", ")" ]
PrependStructSlot prepends a struct onto the object at vtable slot `o`. Structs are stored inline, so nothing additional is being added. In generated code, `d` is always 0.
[ "PrependStructSlot", "prepends", "a", "struct", "onto", "the", "object", "at", "vtable", "slot", "o", ".", "Structs", "are", "stored", "inline", "so", "nothing", "additional", "is", "being", "added", ".", "In", "generated", "code", "d", "is", "always", "0", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L596-L606
24,710
google/flatbuffers
python/flatbuffers/builder.py
Builder.Place
def Place(self, x, flags): """ Place prepends a value specified by `flags` to the Builder, without checking for available space. """ N.enforce_number(x, flags) self.head = self.head - flags.bytewidth encode.Write(flags.packer_type, self.Bytes, self.Head(), x)
python
def Place(self, x, flags): """ Place prepends a value specified by `flags` to the Builder, without checking for available space. """ N.enforce_number(x, flags) self.head = self.head - flags.bytewidth encode.Write(flags.packer_type, self.Bytes, self.Head(), x)
[ "def", "Place", "(", "self", ",", "x", ",", "flags", ")", ":", "N", ".", "enforce_number", "(", "x", ",", "flags", ")", "self", ".", "head", "=", "self", ".", "head", "-", "flags", ".", "bytewidth", "encode", ".", "Write", "(", "flags", ".", "packer_type", ",", "self", ".", "Bytes", ",", "self", ".", "Head", "(", ")", ",", "x", ")" ]
Place prepends a value specified by `flags` to the Builder, without checking for available space.
[ "Place", "prepends", "a", "value", "specified", "by", "flags", "to", "the", "Builder", "without", "checking", "for", "available", "space", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L699-L707
24,711
google/flatbuffers
python/flatbuffers/builder.py
Builder.PlaceVOffsetT
def PlaceVOffsetT(self, x): """PlaceVOffsetT prepends a VOffsetT to the Builder, without checking for space. """ N.enforce_number(x, N.VOffsetTFlags) self.head = self.head - N.VOffsetTFlags.bytewidth encode.Write(packer.voffset, self.Bytes, self.Head(), x)
python
def PlaceVOffsetT(self, x): """PlaceVOffsetT prepends a VOffsetT to the Builder, without checking for space. """ N.enforce_number(x, N.VOffsetTFlags) self.head = self.head - N.VOffsetTFlags.bytewidth encode.Write(packer.voffset, self.Bytes, self.Head(), x)
[ "def", "PlaceVOffsetT", "(", "self", ",", "x", ")", ":", "N", ".", "enforce_number", "(", "x", ",", "N", ".", "VOffsetTFlags", ")", "self", ".", "head", "=", "self", ".", "head", "-", "N", ".", "VOffsetTFlags", ".", "bytewidth", "encode", ".", "Write", "(", "packer", ".", "voffset", ",", "self", ".", "Bytes", ",", "self", ".", "Head", "(", ")", ",", "x", ")" ]
PlaceVOffsetT prepends a VOffsetT to the Builder, without checking for space.
[ "PlaceVOffsetT", "prepends", "a", "VOffsetT", "to", "the", "Builder", "without", "checking", "for", "space", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L709-L715
24,712
google/flatbuffers
python/flatbuffers/builder.py
Builder.PlaceSOffsetT
def PlaceSOffsetT(self, x): """PlaceSOffsetT prepends a SOffsetT to the Builder, without checking for space. """ N.enforce_number(x, N.SOffsetTFlags) self.head = self.head - N.SOffsetTFlags.bytewidth encode.Write(packer.soffset, self.Bytes, self.Head(), x)
python
def PlaceSOffsetT(self, x): """PlaceSOffsetT prepends a SOffsetT to the Builder, without checking for space. """ N.enforce_number(x, N.SOffsetTFlags) self.head = self.head - N.SOffsetTFlags.bytewidth encode.Write(packer.soffset, self.Bytes, self.Head(), x)
[ "def", "PlaceSOffsetT", "(", "self", ",", "x", ")", ":", "N", ".", "enforce_number", "(", "x", ",", "N", ".", "SOffsetTFlags", ")", "self", ".", "head", "=", "self", ".", "head", "-", "N", ".", "SOffsetTFlags", ".", "bytewidth", "encode", ".", "Write", "(", "packer", ".", "soffset", ",", "self", ".", "Bytes", ",", "self", ".", "Head", "(", ")", ",", "x", ")" ]
PlaceSOffsetT prepends a SOffsetT to the Builder, without checking for space.
[ "PlaceSOffsetT", "prepends", "a", "SOffsetT", "to", "the", "Builder", "without", "checking", "for", "space", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L717-L723
24,713
google/flatbuffers
python/flatbuffers/builder.py
Builder.PlaceUOffsetT
def PlaceUOffsetT(self, x): """PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space. """ N.enforce_number(x, N.UOffsetTFlags) self.head = self.head - N.UOffsetTFlags.bytewidth encode.Write(packer.uoffset, self.Bytes, self.Head(), x)
python
def PlaceUOffsetT(self, x): """PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space. """ N.enforce_number(x, N.UOffsetTFlags) self.head = self.head - N.UOffsetTFlags.bytewidth encode.Write(packer.uoffset, self.Bytes, self.Head(), x)
[ "def", "PlaceUOffsetT", "(", "self", ",", "x", ")", ":", "N", ".", "enforce_number", "(", "x", ",", "N", ".", "UOffsetTFlags", ")", "self", ".", "head", "=", "self", ".", "head", "-", "N", ".", "UOffsetTFlags", ".", "bytewidth", "encode", ".", "Write", "(", "packer", ".", "uoffset", ",", "self", ".", "Bytes", ",", "self", ".", "Head", "(", ")", ",", "x", ")" ]
PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space.
[ "PlaceUOffsetT", "prepends", "a", "UOffsetT", "to", "the", "Builder", "without", "checking", "for", "space", "." ]
6cc30b3272d79c85db7d4871ac0aa69541dc89de
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L725-L731
24,714
pypa/pipenv
pipenv/vendor/appdirs.py
site_data_dir
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical site data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('/Library/Application Support') if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv('XDG_DATA_DIRS', os.pathsep.join(['/usr/local/share', '/usr/share'])) pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path if appname and version: path = os.path.join(path, version) return path
python
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical site data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) elif system == 'darwin': path = os.path.expanduser('/Library/Application Support') if appname: path = os.path.join(path, appname) else: # XDG default for $XDG_DATA_DIRS # only first, if multipath is False path = os.getenv('XDG_DATA_DIRS', os.pathsep.join(['/usr/local/share', '/usr/share'])) pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)] if appname: if version: appname = os.path.join(appname, version) pathlist = [os.sep.join([x, appname]) for x in pathlist] if multipath: path = os.pathsep.join(pathlist) else: path = pathlist[0] return path if appname and version: path = os.path.join(path, version) return path
[ "def", "site_data_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "multipath", "=", "False", ")", ":", "if", "system", "==", "\"win32\"", ":", "if", "appauthor", "is", "None", ":", "appauthor", "=", "appname", "path", "=", "os", ".", "path", ".", "normpath", "(", "_get_win_folder", "(", "\"CSIDL_COMMON_APPDATA\"", ")", ")", "if", "appname", ":", "if", "appauthor", "is", "not", "False", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appauthor", ",", "appname", ")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "elif", "system", "==", "'darwin'", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "'/Library/Application Support'", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "else", ":", "# XDG default for $XDG_DATA_DIRS", "# only first, if multipath is False", "path", "=", "os", ".", "getenv", "(", "'XDG_DATA_DIRS'", ",", "os", ".", "pathsep", ".", "join", "(", "[", "'/usr/local/share'", ",", "'/usr/share'", "]", ")", ")", "pathlist", "=", "[", "os", ".", "path", ".", "expanduser", "(", "x", ".", "rstrip", "(", "os", ".", "sep", ")", ")", "for", "x", "in", "path", ".", "split", "(", "os", ".", "pathsep", ")", "]", "if", "appname", ":", "if", "version", ":", "appname", "=", "os", ".", "path", ".", "join", "(", "appname", ",", "version", ")", "pathlist", "=", "[", "os", ".", "sep", ".", "join", "(", "[", "x", ",", "appname", "]", ")", "for", "x", "in", "pathlist", "]", "if", "multipath", ":", "path", "=", "os", ".", "pathsep", ".", "join", "(", "pathlist", ")", "else", ":", "path", "=", "pathlist", "[", "0", "]", "return", "path", "if", "appname", "and", "version", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "version", ")", "return", "path" ]
r"""Return full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/<AppName>', if XDG_DATA_DIRS is not set Typical site data directories are: Mac OS X: /Library/Application Support/<AppName> Unix: /usr/local/share/<AppName> or /usr/share/<AppName> Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName> Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
[ "r", "Return", "full", "path", "to", "the", "user", "-", "shared", "data", "dir", "for", "this", "application", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/appdirs.py#L100-L163
24,715
pypa/pipenv
pipenv/vendor/appdirs.py
user_config_dir
def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user config directories are: Mac OS X: same as user_data_dir Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path
python
def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user config directories are: Mac OS X: same as user_data_dir Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/<AppName>". """ if system in ["win32", "darwin"]: path = user_data_dir(appname, appauthor, None, roaming) else: path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path
[ "def", "user_config_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "roaming", "=", "False", ")", ":", "if", "system", "in", "[", "\"win32\"", ",", "\"darwin\"", "]", ":", "path", "=", "user_data_dir", "(", "appname", ",", "appauthor", ",", "None", ",", "roaming", ")", "else", ":", "path", "=", "os", ".", "getenv", "(", "'XDG_CONFIG_HOME'", ",", "os", ".", "path", ".", "expanduser", "(", "\"~/.config\"", ")", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "if", "appname", "and", "version", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "version", ")", "return", "path" ]
r"""Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx> for a discussion of issues. Typical user config directories are: Mac OS X: same as user_data_dir Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/<AppName>".
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "config", "dir", "for", "this", "application", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/appdirs.py#L166-L203
24,716
pypa/pipenv
pipenv/vendor/requests/api.py
get
def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return request('get', url, params=params, **kwargs)
python
def get(url, params=None, **kwargs): r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return request('get', url, params=params, **kwargs)
[ "def", "get", "(", "url", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "request", "(", "'get'", ",", "url", ",", "params", "=", "params", ",", "*", "*", "kwargs", ")" ]
r"""Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
[ "r", "Sends", "a", "GET", "request", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/api.py#L63-L75
24,717
pypa/pipenv
pipenv/vendor/toml/encoder.py
dump
def dump(o, f): """Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is passed """ if not f.write: raise TypeError("You can only dump an object to a file descriptor") d = dumps(o) f.write(d) return d
python
def dump(o, f): """Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is passed """ if not f.write: raise TypeError("You can only dump an object to a file descriptor") d = dumps(o) f.write(d) return d
[ "def", "dump", "(", "o", ",", "f", ")", ":", "if", "not", "f", ".", "write", ":", "raise", "TypeError", "(", "\"You can only dump an object to a file descriptor\"", ")", "d", "=", "dumps", "(", "o", ")", "f", ".", "write", "(", "d", ")", "return", "d" ]
Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is passed
[ "Writes", "out", "dict", "as", "toml", "to", "a", "file" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/toml/encoder.py#L11-L29
24,718
pypa/pipenv
pipenv/environments.py
is_in_virtualenv
def is_in_virtualenv(): """ Check virtualenv membership dynamically :return: True or false depending on whether we are in a regular virtualenv or not :rtype: bool """ pipenv_active = os.environ.get("PIPENV_ACTIVE", False) virtual_env = None use_system = False ignore_virtualenvs = bool(os.environ.get("PIPENV_IGNORE_VIRTUALENVS", False)) if not pipenv_active and not ignore_virtualenvs: virtual_env = os.environ.get("VIRTUAL_ENV") use_system = bool(virtual_env) return (use_system or virtual_env) and not (pipenv_active or ignore_virtualenvs)
python
def is_in_virtualenv(): """ Check virtualenv membership dynamically :return: True or false depending on whether we are in a regular virtualenv or not :rtype: bool """ pipenv_active = os.environ.get("PIPENV_ACTIVE", False) virtual_env = None use_system = False ignore_virtualenvs = bool(os.environ.get("PIPENV_IGNORE_VIRTUALENVS", False)) if not pipenv_active and not ignore_virtualenvs: virtual_env = os.environ.get("VIRTUAL_ENV") use_system = bool(virtual_env) return (use_system or virtual_env) and not (pipenv_active or ignore_virtualenvs)
[ "def", "is_in_virtualenv", "(", ")", ":", "pipenv_active", "=", "os", ".", "environ", ".", "get", "(", "\"PIPENV_ACTIVE\"", ",", "False", ")", "virtual_env", "=", "None", "use_system", "=", "False", "ignore_virtualenvs", "=", "bool", "(", "os", ".", "environ", ".", "get", "(", "\"PIPENV_IGNORE_VIRTUALENVS\"", ",", "False", ")", ")", "if", "not", "pipenv_active", "and", "not", "ignore_virtualenvs", ":", "virtual_env", "=", "os", ".", "environ", ".", "get", "(", "\"VIRTUAL_ENV\"", ")", "use_system", "=", "bool", "(", "virtual_env", ")", "return", "(", "use_system", "or", "virtual_env", ")", "and", "not", "(", "pipenv_active", "or", "ignore_virtualenvs", ")" ]
Check virtualenv membership dynamically :return: True or false depending on whether we are in a regular virtualenv or not :rtype: bool
[ "Check", "virtualenv", "membership", "dynamically" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/environments.py#L293-L309
24,719
pypa/pipenv
pipenv/patched/notpip/_vendor/msgpack/fallback.py
unpackb
def unpackb(packed, **kwargs): """ Unpack an object from `packed`. Raises `ExtraData` when `packed` contains extra bytes. See :class:`Unpacker` for options. """ unpacker = Unpacker(None, **kwargs) unpacker.feed(packed) try: ret = unpacker._unpack() except OutOfData: raise UnpackValueError("Data is not enough.") if unpacker._got_extradata(): raise ExtraData(ret, unpacker._get_extradata()) return ret
python
def unpackb(packed, **kwargs): """ Unpack an object from `packed`. Raises `ExtraData` when `packed` contains extra bytes. See :class:`Unpacker` for options. """ unpacker = Unpacker(None, **kwargs) unpacker.feed(packed) try: ret = unpacker._unpack() except OutOfData: raise UnpackValueError("Data is not enough.") if unpacker._got_extradata(): raise ExtraData(ret, unpacker._get_extradata()) return ret
[ "def", "unpackb", "(", "packed", ",", "*", "*", "kwargs", ")", ":", "unpacker", "=", "Unpacker", "(", "None", ",", "*", "*", "kwargs", ")", "unpacker", ".", "feed", "(", "packed", ")", "try", ":", "ret", "=", "unpacker", ".", "_unpack", "(", ")", "except", "OutOfData", ":", "raise", "UnpackValueError", "(", "\"Data is not enough.\"", ")", "if", "unpacker", ".", "_got_extradata", "(", ")", ":", "raise", "ExtraData", "(", "ret", ",", "unpacker", ".", "_get_extradata", "(", ")", ")", "return", "ret" ]
Unpack an object from `packed`. Raises `ExtraData` when `packed` contains extra bytes. See :class:`Unpacker` for options.
[ "Unpack", "an", "object", "from", "packed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/msgpack/fallback.py#L111-L126
24,720
pypa/pipenv
pipenv/patched/notpip/_vendor/msgpack/fallback.py
Unpacker._consume
def _consume(self): """ Gets rid of the used parts of the buffer. """ self._stream_offset += self._buff_i - self._buf_checkpoint self._buf_checkpoint = self._buff_i
python
def _consume(self): """ Gets rid of the used parts of the buffer. """ self._stream_offset += self._buff_i - self._buf_checkpoint self._buf_checkpoint = self._buff_i
[ "def", "_consume", "(", "self", ")", ":", "self", ".", "_stream_offset", "+=", "self", ".", "_buff_i", "-", "self", ".", "_buf_checkpoint", "self", ".", "_buf_checkpoint", "=", "self", ".", "_buff_i" ]
Gets rid of the used parts of the buffer.
[ "Gets", "rid", "of", "the", "used", "parts", "of", "the", "buffer", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/msgpack/fallback.py#L300-L303
24,721
pypa/pipenv
pipenv/vendor/urllib3/connection.py
HTTPConnection._new_conn
def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except SocketError as e: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn
python
def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except SocketError as e: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn
[ "def", "_new_conn", "(", "self", ")", ":", "extra_kw", "=", "{", "}", "if", "self", ".", "source_address", ":", "extra_kw", "[", "'source_address'", "]", "=", "self", ".", "source_address", "if", "self", ".", "socket_options", ":", "extra_kw", "[", "'socket_options'", "]", "=", "self", ".", "socket_options", "try", ":", "conn", "=", "connection", ".", "create_connection", "(", "(", "self", ".", "_dns_host", ",", "self", ".", "port", ")", ",", "self", ".", "timeout", ",", "*", "*", "extra_kw", ")", "except", "SocketTimeout", "as", "e", ":", "raise", "ConnectTimeoutError", "(", "self", ",", "\"Connection to %s timed out. (connect timeout=%s)\"", "%", "(", "self", ".", "host", ",", "self", ".", "timeout", ")", ")", "except", "SocketError", "as", "e", ":", "raise", "NewConnectionError", "(", "self", ",", "\"Failed to establish a new connection: %s\"", "%", "e", ")", "return", "conn" ]
Establish a socket connection and set nodelay settings on it. :return: New socket connection.
[ "Establish", "a", "socket", "connection", "and", "set", "nodelay", "settings", "on", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L145-L170
24,722
pypa/pipenv
pipenv/vendor/urllib3/connection.py
HTTPConnection.request_chunked
def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = 'accept-encoding' in headers skip_host = 'host' in headers self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) for header, value in headers.items(): self.putheader(header, value) if 'transfer-encoding' not in headers: self.putheader('Transfer-Encoding', 'chunked') self.endheaders() if body is not None: stringish_types = six.string_types + (bytes,) if isinstance(body, stringish_types): body = (body,) for chunk in body: if not chunk: continue if not isinstance(chunk, bytes): chunk = chunk.encode('utf8') len_str = hex(len(chunk))[2:] self.send(len_str.encode('utf-8')) self.send(b'\r\n') self.send(chunk) self.send(b'\r\n') # After the if clause, to always have a closed body self.send(b'0\r\n\r\n')
python
def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = 'accept-encoding' in headers skip_host = 'host' in headers self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) for header, value in headers.items(): self.putheader(header, value) if 'transfer-encoding' not in headers: self.putheader('Transfer-Encoding', 'chunked') self.endheaders() if body is not None: stringish_types = six.string_types + (bytes,) if isinstance(body, stringish_types): body = (body,) for chunk in body: if not chunk: continue if not isinstance(chunk, bytes): chunk = chunk.encode('utf8') len_str = hex(len(chunk))[2:] self.send(len_str.encode('utf-8')) self.send(b'\r\n') self.send(chunk) self.send(b'\r\n') # After the if clause, to always have a closed body self.send(b'0\r\n\r\n')
[ "def", "request_chunked", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "headers", "=", "HTTPHeaderDict", "(", "headers", "if", "headers", "is", "not", "None", "else", "{", "}", ")", "skip_accept_encoding", "=", "'accept-encoding'", "in", "headers", "skip_host", "=", "'host'", "in", "headers", "self", ".", "putrequest", "(", "method", ",", "url", ",", "skip_accept_encoding", "=", "skip_accept_encoding", ",", "skip_host", "=", "skip_host", ")", "for", "header", ",", "value", "in", "headers", ".", "items", "(", ")", ":", "self", ".", "putheader", "(", "header", ",", "value", ")", "if", "'transfer-encoding'", "not", "in", "headers", ":", "self", ".", "putheader", "(", "'Transfer-Encoding'", ",", "'chunked'", ")", "self", ".", "endheaders", "(", ")", "if", "body", "is", "not", "None", ":", "stringish_types", "=", "six", ".", "string_types", "+", "(", "bytes", ",", ")", "if", "isinstance", "(", "body", ",", "stringish_types", ")", ":", "body", "=", "(", "body", ",", ")", "for", "chunk", "in", "body", ":", "if", "not", "chunk", ":", "continue", "if", "not", "isinstance", "(", "chunk", ",", "bytes", ")", ":", "chunk", "=", "chunk", ".", "encode", "(", "'utf8'", ")", "len_str", "=", "hex", "(", "len", "(", "chunk", ")", ")", "[", "2", ":", "]", "self", ".", "send", "(", "len_str", ".", "encode", "(", "'utf-8'", ")", ")", "self", ".", "send", "(", "b'\\r\\n'", ")", "self", ".", "send", "(", "chunk", ")", "self", ".", "send", "(", "b'\\r\\n'", ")", "# After the if clause, to always have a closed body", "self", ".", "send", "(", "b'0\\r\\n\\r\\n'", ")" ]
Alternative to the common request method, which sends the body with chunked encoding and not as one block
[ "Alternative", "to", "the", "common", "request", "method", "which", "sends", "the", "body", "with", "chunked", "encoding", "and", "not", "as", "one", "block" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L184-L220
24,723
pypa/pipenv
pipenv/vendor/urllib3/connection.py
VerifiedHTTPSConnection.set_cert
def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None): """ This method should only be called once, before the connection is used. """ # If cert_reqs is not provided, we can try to guess. If the user gave # us a cert database, we assume they want to use it: otherwise, if # they gave us an SSL Context object we should use whatever is set for # it. if cert_reqs is None: if ca_certs or ca_cert_dir: cert_reqs = 'CERT_REQUIRED' elif self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
python
def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None): """ This method should only be called once, before the connection is used. """ # If cert_reqs is not provided, we can try to guess. If the user gave # us a cert database, we assume they want to use it: otherwise, if # they gave us an SSL Context object we should use whatever is set for # it. if cert_reqs is None: if ca_certs or ca_cert_dir: cert_reqs = 'CERT_REQUIRED' elif self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
[ "def", "set_cert", "(", "self", ",", "key_file", "=", "None", ",", "cert_file", "=", "None", ",", "cert_reqs", "=", "None", ",", "ca_certs", "=", "None", ",", "assert_hostname", "=", "None", ",", "assert_fingerprint", "=", "None", ",", "ca_cert_dir", "=", "None", ")", ":", "# If cert_reqs is not provided, we can try to guess. If the user gave", "# us a cert database, we assume they want to use it: otherwise, if", "# they gave us an SSL Context object we should use whatever is set for", "# it.", "if", "cert_reqs", "is", "None", ":", "if", "ca_certs", "or", "ca_cert_dir", ":", "cert_reqs", "=", "'CERT_REQUIRED'", "elif", "self", ".", "ssl_context", "is", "not", "None", ":", "cert_reqs", "=", "self", ".", "ssl_context", ".", "verify_mode", "self", ".", "key_file", "=", "key_file", "self", ".", "cert_file", "=", "cert_file", "self", ".", "cert_reqs", "=", "cert_reqs", "self", ".", "assert_hostname", "=", "assert_hostname", "self", ".", "assert_fingerprint", "=", "assert_fingerprint", "self", ".", "ca_certs", "=", "ca_certs", "and", "os", ".", "path", ".", "expanduser", "(", "ca_certs", ")", "self", ".", "ca_cert_dir", "=", "ca_cert_dir", "and", "os", ".", "path", ".", "expanduser", "(", "ca_cert_dir", ")" ]
This method should only be called once, before the connection is used.
[ "This", "method", "should", "only", "be", "called", "once", "before", "the", "connection", "is", "used", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/connection.py#L274-L297
24,724
pypa/pipenv
pipenv/exceptions.py
prettify_exc
def prettify_exc(error): """Catch known errors and prettify them instead of showing the entire traceback, for better UX""" matched_exceptions = [k for k in KNOWN_EXCEPTIONS.keys() if k in error] if not matched_exceptions: return "{}".format(vistir.misc.decode_for_output(error)) errors = [] for match in matched_exceptions: _, error, info = error.rpartition(KNOWN_EXCEPTIONS[match]) errors.append("{} {}".format(error, info)) return "\n".join(errors)
python
def prettify_exc(error): """Catch known errors and prettify them instead of showing the entire traceback, for better UX""" matched_exceptions = [k for k in KNOWN_EXCEPTIONS.keys() if k in error] if not matched_exceptions: return "{}".format(vistir.misc.decode_for_output(error)) errors = [] for match in matched_exceptions: _, error, info = error.rpartition(KNOWN_EXCEPTIONS[match]) errors.append("{} {}".format(error, info)) return "\n".join(errors)
[ "def", "prettify_exc", "(", "error", ")", ":", "matched_exceptions", "=", "[", "k", "for", "k", "in", "KNOWN_EXCEPTIONS", ".", "keys", "(", ")", "if", "k", "in", "error", "]", "if", "not", "matched_exceptions", ":", "return", "\"{}\"", ".", "format", "(", "vistir", ".", "misc", ".", "decode_for_output", "(", "error", ")", ")", "errors", "=", "[", "]", "for", "match", "in", "matched_exceptions", ":", "_", ",", "error", ",", "info", "=", "error", ".", "rpartition", "(", "KNOWN_EXCEPTIONS", "[", "match", "]", ")", "errors", ".", "append", "(", "\"{} {}\"", ".", "format", "(", "error", ",", "info", ")", ")", "return", "\"\\n\"", ".", "join", "(", "errors", ")" ]
Catch known errors and prettify them instead of showing the entire traceback, for better UX
[ "Catch", "known", "errors", "and", "prettify", "them", "instead", "of", "showing", "the", "entire", "traceback", "for", "better", "UX" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/exceptions.py#L412-L423
24,725
pypa/pipenv
pipenv/vendor/click_completion/patch.py
choice_complete
def choice_complete(self, ctx, incomplete): """Returns the completion results for click.core.Choice Parameters ---------- ctx : click.core.Context The current context incomplete : The string to complete Returns ------- [(str, str)] A list of completion results """ return [ (c, None) for c in self.choices if completion_configuration.match_incomplete(c, incomplete) ]
python
def choice_complete(self, ctx, incomplete): """Returns the completion results for click.core.Choice Parameters ---------- ctx : click.core.Context The current context incomplete : The string to complete Returns ------- [(str, str)] A list of completion results """ return [ (c, None) for c in self.choices if completion_configuration.match_incomplete(c, incomplete) ]
[ "def", "choice_complete", "(", "self", ",", "ctx", ",", "incomplete", ")", ":", "return", "[", "(", "c", ",", "None", ")", "for", "c", "in", "self", ".", "choices", "if", "completion_configuration", ".", "match_incomplete", "(", "c", ",", "incomplete", ")", "]" ]
Returns the completion results for click.core.Choice Parameters ---------- ctx : click.core.Context The current context incomplete : The string to complete Returns ------- [(str, str)] A list of completion results
[ "Returns", "the", "completion", "results", "for", "click", ".", "core", ".", "Choice" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click_completion/patch.py#L39-L57
24,726
pypa/pipenv
pipenv/vendor/docopt.py
parse_argv
def parse_argv(tokens, options, options_first=False): """Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; """ parsed = [] while tokens.current() is not None: if tokens.current() == '--': return parsed + [Argument(None, v) for v in tokens] elif tokens.current().startswith('--'): parsed += parse_long(tokens, options) elif tokens.current().startswith('-') and tokens.current() != '-': parsed += parse_shorts(tokens, options) elif options_first: return parsed + [Argument(None, v) for v in tokens] else: parsed.append(Argument(None, tokens.move())) return parsed
python
def parse_argv(tokens, options, options_first=False): """Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; """ parsed = [] while tokens.current() is not None: if tokens.current() == '--': return parsed + [Argument(None, v) for v in tokens] elif tokens.current().startswith('--'): parsed += parse_long(tokens, options) elif tokens.current().startswith('-') and tokens.current() != '-': parsed += parse_shorts(tokens, options) elif options_first: return parsed + [Argument(None, v) for v in tokens] else: parsed.append(Argument(None, tokens.move())) return parsed
[ "def", "parse_argv", "(", "tokens", ",", "options", ",", "options_first", "=", "False", ")", ":", "parsed", "=", "[", "]", "while", "tokens", ".", "current", "(", ")", "is", "not", "None", ":", "if", "tokens", ".", "current", "(", ")", "==", "'--'", ":", "return", "parsed", "+", "[", "Argument", "(", "None", ",", "v", ")", "for", "v", "in", "tokens", "]", "elif", "tokens", ".", "current", "(", ")", ".", "startswith", "(", "'--'", ")", ":", "parsed", "+=", "parse_long", "(", "tokens", ",", "options", ")", "elif", "tokens", ".", "current", "(", ")", ".", "startswith", "(", "'-'", ")", "and", "tokens", ".", "current", "(", ")", "!=", "'-'", ":", "parsed", "+=", "parse_shorts", "(", "tokens", ",", "options", ")", "elif", "options_first", ":", "return", "parsed", "+", "[", "Argument", "(", "None", ",", "v", ")", "for", "v", "in", "tokens", "]", "else", ":", "parsed", ".", "append", "(", "Argument", "(", "None", ",", "tokens", ".", "move", "(", ")", ")", ")", "return", "parsed" ]
Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
[ "Parse", "command", "-", "line", "argument", "vector", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/docopt.py#L430-L451
24,727
pypa/pipenv
pipenv/vendor/vistir/misc.py
unnest
def unnest(elem): """Flatten an arbitrarily nested iterable :param elem: An iterable to flatten :type elem: :class:`~collections.Iterable` >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599))))) >>> list(vistir.misc.unnest(nested_iterable)) [1234, 3456, 4398345, 234234, 2396, 23895750, 9283798, 29384, 289375983275, 293759, 2347, 2098, 7987, 27599] """ if isinstance(elem, Iterable) and not isinstance(elem, six.string_types): elem, target = tee(elem, 2) else: target = elem for el in target: if isinstance(el, Iterable) and not isinstance(el, six.string_types): el, el_copy = tee(el, 2) for sub in unnest(el_copy): yield sub else: yield el
python
def unnest(elem): """Flatten an arbitrarily nested iterable :param elem: An iterable to flatten :type elem: :class:`~collections.Iterable` >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599))))) >>> list(vistir.misc.unnest(nested_iterable)) [1234, 3456, 4398345, 234234, 2396, 23895750, 9283798, 29384, 289375983275, 293759, 2347, 2098, 7987, 27599] """ if isinstance(elem, Iterable) and not isinstance(elem, six.string_types): elem, target = tee(elem, 2) else: target = elem for el in target: if isinstance(el, Iterable) and not isinstance(el, six.string_types): el, el_copy = tee(el, 2) for sub in unnest(el_copy): yield sub else: yield el
[ "def", "unnest", "(", "elem", ")", ":", "if", "isinstance", "(", "elem", ",", "Iterable", ")", "and", "not", "isinstance", "(", "elem", ",", "six", ".", "string_types", ")", ":", "elem", ",", "target", "=", "tee", "(", "elem", ",", "2", ")", "else", ":", "target", "=", "elem", "for", "el", "in", "target", ":", "if", "isinstance", "(", "el", ",", "Iterable", ")", "and", "not", "isinstance", "(", "el", ",", "six", ".", "string_types", ")", ":", "el", ",", "el_copy", "=", "tee", "(", "el", ",", "2", ")", "for", "sub", "in", "unnest", "(", "el_copy", ")", ":", "yield", "sub", "else", ":", "yield", "el" ]
Flatten an arbitrarily nested iterable :param elem: An iterable to flatten :type elem: :class:`~collections.Iterable` >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599))))) >>> list(vistir.misc.unnest(nested_iterable)) [1234, 3456, 4398345, 234234, 2396, 23895750, 9283798, 29384, 289375983275, 293759, 2347, 2098, 7987, 27599]
[ "Flatten", "an", "arbitrarily", "nested", "iterable" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L74-L95
24,728
pypa/pipenv
pipenv/vendor/vistir/misc.py
run
def run( cmd, env=None, return_object=False, block=True, cwd=None, verbose=False, nospin=False, spinner_name=None, combine_stderr=True, display_limit=200, write_to_stdout=True, ): """Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param bool block: When False, returns a potentially still-running :class:`subprocess.Popen` instance :param str cwd: Current working directory contect to use for spawning the subprocess. :param bool verbose: Whether to print stdout in real time when non-blocking. :param bool nospin: Whether to disable the cli spinner. :param str spinner_name: The name of the spinner to use if enabled, defaults to bouncingBar :param bool combine_stderr: Optionally merge stdout and stderr in the subprocess, false if nonblocking. :param int dispay_limit: The max width of output lines to display when using a spinner. :param bool write_to_stdout: Whether to write to stdout when using a spinner, default True. :returns: A 2-tuple of (output, error) or a :class:`subprocess.Popen` object. .. Warning:: Merging standard out and standarad error in a nonblocking subprocess can cause errors in some cases and may not be ideal. Consider disabling this functionality. """ _env = os.environ.copy() if env: _env.update(env) if six.PY2: fs_encode = partial(to_bytes, encoding=locale_encoding) _env = {fs_encode(k): fs_encode(v) for k, v in _env.items()} else: _env = {k: fs_str(v) for k, v in _env.items()} if not spinner_name: spinner_name = "bouncingBar" if six.PY2: if isinstance(cmd, six.string_types): cmd = cmd.encode("utf-8") elif isinstance(cmd, (list, tuple)): cmd = [c.encode("utf-8") for c in cmd] if not isinstance(cmd, Script): cmd = Script.parse(cmd) if block or not return_object: combine_stderr = False start_text = "" with spinner( spinner_name=spinner_name, start_text=start_text, nospin=nospin, write_to_stdout=write_to_stdout, ) as sp: return _create_subprocess( cmd, env=_env, return_object=return_object, block=block, cwd=cwd, verbose=verbose, spinner=sp, combine_stderr=combine_stderr, start_text=start_text, write_to_stdout=True, )
python
def run( cmd, env=None, return_object=False, block=True, cwd=None, verbose=False, nospin=False, spinner_name=None, combine_stderr=True, display_limit=200, write_to_stdout=True, ): """Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param bool block: When False, returns a potentially still-running :class:`subprocess.Popen` instance :param str cwd: Current working directory contect to use for spawning the subprocess. :param bool verbose: Whether to print stdout in real time when non-blocking. :param bool nospin: Whether to disable the cli spinner. :param str spinner_name: The name of the spinner to use if enabled, defaults to bouncingBar :param bool combine_stderr: Optionally merge stdout and stderr in the subprocess, false if nonblocking. :param int dispay_limit: The max width of output lines to display when using a spinner. :param bool write_to_stdout: Whether to write to stdout when using a spinner, default True. :returns: A 2-tuple of (output, error) or a :class:`subprocess.Popen` object. .. Warning:: Merging standard out and standarad error in a nonblocking subprocess can cause errors in some cases and may not be ideal. Consider disabling this functionality. """ _env = os.environ.copy() if env: _env.update(env) if six.PY2: fs_encode = partial(to_bytes, encoding=locale_encoding) _env = {fs_encode(k): fs_encode(v) for k, v in _env.items()} else: _env = {k: fs_str(v) for k, v in _env.items()} if not spinner_name: spinner_name = "bouncingBar" if six.PY2: if isinstance(cmd, six.string_types): cmd = cmd.encode("utf-8") elif isinstance(cmd, (list, tuple)): cmd = [c.encode("utf-8") for c in cmd] if not isinstance(cmd, Script): cmd = Script.parse(cmd) if block or not return_object: combine_stderr = False start_text = "" with spinner( spinner_name=spinner_name, start_text=start_text, nospin=nospin, write_to_stdout=write_to_stdout, ) as sp: return _create_subprocess( cmd, env=_env, return_object=return_object, block=block, cwd=cwd, verbose=verbose, spinner=sp, combine_stderr=combine_stderr, start_text=start_text, write_to_stdout=True, )
[ "def", "run", "(", "cmd", ",", "env", "=", "None", ",", "return_object", "=", "False", ",", "block", "=", "True", ",", "cwd", "=", "None", ",", "verbose", "=", "False", ",", "nospin", "=", "False", ",", "spinner_name", "=", "None", ",", "combine_stderr", "=", "True", ",", "display_limit", "=", "200", ",", "write_to_stdout", "=", "True", ",", ")", ":", "_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "env", ":", "_env", ".", "update", "(", "env", ")", "if", "six", ".", "PY2", ":", "fs_encode", "=", "partial", "(", "to_bytes", ",", "encoding", "=", "locale_encoding", ")", "_env", "=", "{", "fs_encode", "(", "k", ")", ":", "fs_encode", "(", "v", ")", "for", "k", ",", "v", "in", "_env", ".", "items", "(", ")", "}", "else", ":", "_env", "=", "{", "k", ":", "fs_str", "(", "v", ")", "for", "k", ",", "v", "in", "_env", ".", "items", "(", ")", "}", "if", "not", "spinner_name", ":", "spinner_name", "=", "\"bouncingBar\"", "if", "six", ".", "PY2", ":", "if", "isinstance", "(", "cmd", ",", "six", ".", "string_types", ")", ":", "cmd", "=", "cmd", ".", "encode", "(", "\"utf-8\"", ")", "elif", "isinstance", "(", "cmd", ",", "(", "list", ",", "tuple", ")", ")", ":", "cmd", "=", "[", "c", ".", "encode", "(", "\"utf-8\"", ")", "for", "c", "in", "cmd", "]", "if", "not", "isinstance", "(", "cmd", ",", "Script", ")", ":", "cmd", "=", "Script", ".", "parse", "(", "cmd", ")", "if", "block", "or", "not", "return_object", ":", "combine_stderr", "=", "False", "start_text", "=", "\"\"", "with", "spinner", "(", "spinner_name", "=", "spinner_name", ",", "start_text", "=", "start_text", ",", "nospin", "=", "nospin", ",", "write_to_stdout", "=", "write_to_stdout", ",", ")", "as", "sp", ":", "return", "_create_subprocess", "(", "cmd", ",", "env", "=", "_env", ",", "return_object", "=", "return_object", ",", "block", "=", "block", ",", "cwd", "=", "cwd", ",", "verbose", "=", "verbose", ",", "spinner", "=", "sp", ",", "combine_stderr", "=", "combine_stderr", ",", "start_text", "=", "start_text", ",", "write_to_stdout", "=", "True", ",", ")" ]
Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param bool block: When False, returns a potentially still-running :class:`subprocess.Popen` instance :param str cwd: Current working directory contect to use for spawning the subprocess. :param bool verbose: Whether to print stdout in real time when non-blocking. :param bool nospin: Whether to disable the cli spinner. :param str spinner_name: The name of the spinner to use if enabled, defaults to bouncingBar :param bool combine_stderr: Optionally merge stdout and stderr in the subprocess, false if nonblocking. :param int dispay_limit: The max width of output lines to display when using a spinner. :param bool write_to_stdout: Whether to write to stdout when using a spinner, default True. :returns: A 2-tuple of (output, error) or a :class:`subprocess.Popen` object. .. Warning:: Merging standard out and standarad error in a nonblocking subprocess can cause errors in some cases and may not be ideal. Consider disabling this functionality.
[ "Use", "subprocess", ".", "Popen", "to", "get", "the", "output", "of", "a", "command", "and", "decode", "it", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L265-L335
24,729
pypa/pipenv
pipenv/vendor/vistir/misc.py
getpreferredencoding
def getpreferredencoding(): """Determine the proper output encoding for terminal rendering""" # Borrowed from Invoke # (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881) _encoding = locale.getpreferredencoding(False) if six.PY2 and not sys.platform == "win32": _default_encoding = locale.getdefaultlocale()[1] if _default_encoding is not None: _encoding = _default_encoding return _encoding
python
def getpreferredencoding(): """Determine the proper output encoding for terminal rendering""" # Borrowed from Invoke # (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881) _encoding = locale.getpreferredencoding(False) if six.PY2 and not sys.platform == "win32": _default_encoding = locale.getdefaultlocale()[1] if _default_encoding is not None: _encoding = _default_encoding return _encoding
[ "def", "getpreferredencoding", "(", ")", ":", "# Borrowed from Invoke", "# (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881)", "_encoding", "=", "locale", ".", "getpreferredencoding", "(", "False", ")", "if", "six", ".", "PY2", "and", "not", "sys", ".", "platform", "==", "\"win32\"", ":", "_default_encoding", "=", "locale", ".", "getdefaultlocale", "(", ")", "[", "1", "]", "if", "_default_encoding", "is", "not", "None", ":", "_encoding", "=", "_default_encoding", "return", "_encoding" ]
Determine the proper output encoding for terminal rendering
[ "Determine", "the", "proper", "output", "encoding", "for", "terminal", "rendering" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L522-L532
24,730
pypa/pipenv
pipenv/vendor/vistir/misc.py
decode_for_output
def decode_for_output(output, target_stream=None, translation_map=None): """Given a string, decode it for output to a terminal :param str output: A string to print to a terminal :param target_stream: A stream to write to, we will encode to target this stream if possible. :param dict translation_map: A mapping of unicode character ordinals to replacement strings. :return: A re-encoded string using the preferred encoding :rtype: str """ if not isinstance(output, six.string_types): return output encoding = None if target_stream is not None: encoding = getattr(target_stream, "encoding", None) encoding = get_output_encoding(encoding) try: output = _encode(output, encoding=encoding, translation_map=translation_map) except (UnicodeDecodeError, UnicodeEncodeError): output = to_native_string(output) output = _encode( output, encoding=encoding, errors="replace", translation_map=translation_map ) return to_text(output, encoding=encoding, errors="replace")
python
def decode_for_output(output, target_stream=None, translation_map=None): """Given a string, decode it for output to a terminal :param str output: A string to print to a terminal :param target_stream: A stream to write to, we will encode to target this stream if possible. :param dict translation_map: A mapping of unicode character ordinals to replacement strings. :return: A re-encoded string using the preferred encoding :rtype: str """ if not isinstance(output, six.string_types): return output encoding = None if target_stream is not None: encoding = getattr(target_stream, "encoding", None) encoding = get_output_encoding(encoding) try: output = _encode(output, encoding=encoding, translation_map=translation_map) except (UnicodeDecodeError, UnicodeEncodeError): output = to_native_string(output) output = _encode( output, encoding=encoding, errors="replace", translation_map=translation_map ) return to_text(output, encoding=encoding, errors="replace")
[ "def", "decode_for_output", "(", "output", ",", "target_stream", "=", "None", ",", "translation_map", "=", "None", ")", ":", "if", "not", "isinstance", "(", "output", ",", "six", ".", "string_types", ")", ":", "return", "output", "encoding", "=", "None", "if", "target_stream", "is", "not", "None", ":", "encoding", "=", "getattr", "(", "target_stream", ",", "\"encoding\"", ",", "None", ")", "encoding", "=", "get_output_encoding", "(", "encoding", ")", "try", ":", "output", "=", "_encode", "(", "output", ",", "encoding", "=", "encoding", ",", "translation_map", "=", "translation_map", ")", "except", "(", "UnicodeDecodeError", ",", "UnicodeEncodeError", ")", ":", "output", "=", "to_native_string", "(", "output", ")", "output", "=", "_encode", "(", "output", ",", "encoding", "=", "encoding", ",", "errors", "=", "\"replace\"", ",", "translation_map", "=", "translation_map", ")", "return", "to_text", "(", "output", ",", "encoding", "=", "encoding", ",", "errors", "=", "\"replace\"", ")" ]
Given a string, decode it for output to a terminal :param str output: A string to print to a terminal :param target_stream: A stream to write to, we will encode to target this stream if possible. :param dict translation_map: A mapping of unicode character ordinals to replacement strings. :return: A re-encoded string using the preferred encoding :rtype: str
[ "Given", "a", "string", "decode", "it", "for", "output", "to", "a", "terminal" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L574-L597
24,731
pypa/pipenv
pipenv/vendor/vistir/misc.py
get_canonical_encoding_name
def get_canonical_encoding_name(name): # type: (str) -> str """ Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str """ import codecs try: codec = codecs.lookup(name) except LookupError: return name else: return codec.name
python
def get_canonical_encoding_name(name): # type: (str) -> str """ Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str """ import codecs try: codec = codecs.lookup(name) except LookupError: return name else: return codec.name
[ "def", "get_canonical_encoding_name", "(", "name", ")", ":", "# type: (str) -> str", "import", "codecs", "try", ":", "codec", "=", "codecs", ".", "lookup", "(", "name", ")", "except", "LookupError", ":", "return", "name", "else", ":", "return", "codec", ".", "name" ]
Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str
[ "Given", "an", "encoding", "name", "get", "the", "canonical", "name", "from", "a", "codec", "lookup", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L600-L617
24,732
pypa/pipenv
pipenv/vendor/urllib3/util/connection.py
_has_ipv6
def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/shazow/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6
python
def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/shazow/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6
[ "def", "_has_ipv6", "(", "host", ")", ":", "sock", "=", "None", "has_ipv6", "=", "False", "# App Engine doesn't support IPV6 sockets and actually has a quota on the", "# number of sockets that can be used, so just early out here instead of", "# creating a socket needlessly.", "# See https://github.com/urllib3/urllib3/issues/1446", "if", "_appengine_environ", ".", "is_appengine_sandbox", "(", ")", ":", "return", "False", "if", "socket", ".", "has_ipv6", ":", "# has_ipv6 returns true if cPython was compiled with IPv6 support.", "# It does not tell us if the system has IPv6 support enabled. To", "# determine that we must bind to an IPv6 address.", "# https://github.com/shazow/urllib3/pull/611", "# https://bugs.python.org/issue658327", "try", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET6", ")", "sock", ".", "bind", "(", "(", "host", ",", "0", ")", ")", "has_ipv6", "=", "True", "except", "Exception", ":", "pass", "if", "sock", ":", "sock", ".", "close", "(", ")", "return", "has_ipv6" ]
Returns True if the system can bind an IPv6 address.
[ "Returns", "True", "if", "the", "system", "can", "bind", "an", "IPv6", "address", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/util/connection.py#L104-L131
24,733
pypa/pipenv
pipenv/vendor/requests/_internal_utils.py
unicode_is_ascii
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
python
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return True except UnicodeEncodeError: return False
[ "def", "unicode_is_ascii", "(", "u_string", ")", ":", "assert", "isinstance", "(", "u_string", ",", "str", ")", "try", ":", "u_string", ".", "encode", "(", "'ascii'", ")", "return", "True", "except", "UnicodeEncodeError", ":", "return", "False" ]
Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool
[ "Determine", "if", "unicode", "string", "only", "contains", "ASCII", "characters", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/_internal_utils.py#L30-L42
24,734
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
check_install_build_global
def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2, )
python
def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2, )
[ "def", "check_install_build_global", "(", "options", ",", "check_options", "=", "None", ")", ":", "# type: (Values, Optional[Values]) -> None", "if", "check_options", "is", "None", ":", "check_options", "=", "options", "def", "getname", "(", "n", ")", ":", "return", "getattr", "(", "check_options", ",", "n", ",", "None", ")", "names", "=", "[", "\"build_options\"", ",", "\"global_options\"", ",", "\"install_options\"", "]", "if", "any", "(", "map", "(", "getname", ",", "names", ")", ")", ":", "control", "=", "options", ".", "format_control", "control", ".", "disallow_binaries", "(", ")", "warnings", ".", "warn", "(", "'Disabling all use of wheels due to the use of --build-options '", "'/ --global-options / --install-options.'", ",", "stacklevel", "=", "2", ",", ")" ]
Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options.
[ "Disable", "wheels", "if", "per", "-", "setup", ".", "py", "call", "options", "are", "set", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L59-L79
24,735
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
check_dist_restriction
def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # gauranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
python
def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any([ options.python_version, options.platform, options.abi, options.implementation, ]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies ) # Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # gauranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." ) if check_target: if dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target'" )
[ "def", "check_dist_restriction", "(", "options", ",", "check_target", "=", "False", ")", ":", "# type: (Values, bool) -> None", "dist_restriction_set", "=", "any", "(", "[", "options", ".", "python_version", ",", "options", ".", "platform", ",", "options", ".", "abi", ",", "options", ".", "implementation", ",", "]", ")", "binary_only", "=", "FormatControl", "(", "set", "(", ")", ",", "{", "':all:'", "}", ")", "sdist_dependencies_allowed", "=", "(", "options", ".", "format_control", "!=", "binary_only", "and", "not", "options", ".", "ignore_dependencies", ")", "# Installations or downloads using dist restrictions must not combine", "# source distributions and dist-specific wheels, as they are not", "# gauranteed to be locally compatible.", "if", "dist_restriction_set", "and", "sdist_dependencies_allowed", ":", "raise", "CommandError", "(", "\"When restricting platform and interpreter constraints using \"", "\"--python-version, --platform, --abi, or --implementation, \"", "\"either --no-deps must be set, or --only-binary=:all: must be \"", "\"set and --no-binary must not be set (or must be set to \"", "\":none:).\"", ")", "if", "check_target", ":", "if", "dist_restriction_set", "and", "not", "options", ".", "target_dir", ":", "raise", "CommandError", "(", "\"Can not use any platform or abi specific options unless \"", "\"installing via '--target'\"", ")" ]
Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used.
[ "Function", "for", "determining", "if", "custom", "platform", "options", "are", "allowed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L82-L119
24,736
pypa/pipenv
pipenv/vendor/requirementslib/models/pipfile.py
PipfileLoader.populate_source
def populate_source(cls, source): """Derive missing values of source from the existing fields.""" # Only URL pararemter is mandatory, let the KeyError be thrown. if "name" not in source: source["name"] = get_url_name(source["url"]) if "verify_ssl" not in source: source["verify_ssl"] = "https://" in source["url"] if not isinstance(source["verify_ssl"], bool): source["verify_ssl"] = source["verify_ssl"].lower() == "true" return source
python
def populate_source(cls, source): """Derive missing values of source from the existing fields.""" # Only URL pararemter is mandatory, let the KeyError be thrown. if "name" not in source: source["name"] = get_url_name(source["url"]) if "verify_ssl" not in source: source["verify_ssl"] = "https://" in source["url"] if not isinstance(source["verify_ssl"], bool): source["verify_ssl"] = source["verify_ssl"].lower() == "true" return source
[ "def", "populate_source", "(", "cls", ",", "source", ")", ":", "# Only URL pararemter is mandatory, let the KeyError be thrown.", "if", "\"name\"", "not", "in", "source", ":", "source", "[", "\"name\"", "]", "=", "get_url_name", "(", "source", "[", "\"url\"", "]", ")", "if", "\"verify_ssl\"", "not", "in", "source", ":", "source", "[", "\"verify_ssl\"", "]", "=", "\"https://\"", "in", "source", "[", "\"url\"", "]", "if", "not", "isinstance", "(", "source", "[", "\"verify_ssl\"", "]", ",", "bool", ")", ":", "source", "[", "\"verify_ssl\"", "]", "=", "source", "[", "\"verify_ssl\"", "]", ".", "lower", "(", ")", "==", "\"true\"", "return", "source" ]
Derive missing values of source from the existing fields.
[ "Derive", "missing", "values", "of", "source", "from", "the", "existing", "fields", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requirementslib/models/pipfile.py#L111-L120
24,737
pypa/pipenv
pipenv/vendor/passa/internals/utils.py
get_pinned_version
def get_pinned_version(ireq): """Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned. """ try: specifier = ireq.specifier except AttributeError: raise TypeError("Expected InstallRequirement, not {}".format( type(ireq).__name__, )) if ireq.editable: raise ValueError("InstallRequirement is editable") if not specifier: raise ValueError("InstallRequirement has no version specification") if len(specifier._specs) != 1: raise ValueError("InstallRequirement has multiple specifications") op, version = next(iter(specifier._specs))._spec if op not in ('==', '===') or version.endswith('.*'): raise ValueError("InstallRequirement not pinned (is {0!r})".format( op + version, )) return version
python
def get_pinned_version(ireq): """Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned. """ try: specifier = ireq.specifier except AttributeError: raise TypeError("Expected InstallRequirement, not {}".format( type(ireq).__name__, )) if ireq.editable: raise ValueError("InstallRequirement is editable") if not specifier: raise ValueError("InstallRequirement has no version specification") if len(specifier._specs) != 1: raise ValueError("InstallRequirement has multiple specifications") op, version = next(iter(specifier._specs))._spec if op not in ('==', '===') or version.endswith('.*'): raise ValueError("InstallRequirement not pinned (is {0!r})".format( op + version, )) return version
[ "def", "get_pinned_version", "(", "ireq", ")", ":", "try", ":", "specifier", "=", "ireq", ".", "specifier", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Expected InstallRequirement, not {}\"", ".", "format", "(", "type", "(", "ireq", ")", ".", "__name__", ",", ")", ")", "if", "ireq", ".", "editable", ":", "raise", "ValueError", "(", "\"InstallRequirement is editable\"", ")", "if", "not", "specifier", ":", "raise", "ValueError", "(", "\"InstallRequirement has no version specification\"", ")", "if", "len", "(", "specifier", ".", "_specs", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"InstallRequirement has multiple specifications\"", ")", "op", ",", "version", "=", "next", "(", "iter", "(", "specifier", ".", "_specs", ")", ")", ".", "_spec", "if", "op", "not", "in", "(", "'=='", ",", "'==='", ")", "or", "version", ".", "endswith", "(", "'.*'", ")", ":", "raise", "ValueError", "(", "\"InstallRequirement not pinned (is {0!r})\"", ".", "format", "(", "op", "+", "version", ",", ")", ")", "return", "version" ]
Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned django~=1.8 # NOT pinned django==1.* # NOT pinned Raises `TypeError` if the input is not a valid InstallRequirement, or `ValueError` if the InstallRequirement is not pinned.
[ "Get", "the", "pinned", "version", "of", "an", "InstallRequirement", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/utils.py#L20-L59
24,738
pypa/pipenv
pipenv/vendor/passa/internals/utils.py
strip_extras
def strip_extras(requirement): """Returns a new requirement object with extras removed. """ line = requirement.as_line() new = type(requirement).from_line(line) new.extras = None return new
python
def strip_extras(requirement): """Returns a new requirement object with extras removed. """ line = requirement.as_line() new = type(requirement).from_line(line) new.extras = None return new
[ "def", "strip_extras", "(", "requirement", ")", ":", "line", "=", "requirement", ".", "as_line", "(", ")", "new", "=", "type", "(", "requirement", ")", ".", "from_line", "(", "line", ")", "new", ".", "extras", "=", "None", "return", "new" ]
Returns a new requirement object with extras removed.
[ "Returns", "a", "new", "requirement", "object", "with", "extras", "removed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/passa/internals/utils.py#L112-L118
24,739
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_makefile_filename
def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") if hasattr(sys, 'abiflags'): config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags) else: config_dir_name = 'config' return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
python
def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") if hasattr(sys, 'abiflags'): config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags) else: config_dir_name = 'config' return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
[ "def", "get_makefile_filename", "(", ")", ":", "if", "_PYTHON_BUILD", ":", "return", "os", ".", "path", ".", "join", "(", "_PROJECT_BASE", ",", "\"Makefile\"", ")", "if", "hasattr", "(", "sys", ",", "'abiflags'", ")", ":", "config_dir_name", "=", "'config-%s%s'", "%", "(", "_PY_VERSION_SHORT", ",", "sys", ".", "abiflags", ")", "else", ":", "config_dir_name", "=", "'config'", "return", "os", ".", "path", ".", "join", "(", "get_path", "(", "'stdlib'", ")", ",", "config_dir_name", ",", "'Makefile'", ")" ]
Return the path of the Makefile.
[ "Return", "the", "path", "of", "the", "Makefile", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L333-L341
24,740
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
_init_posix
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED']
python
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED']
[ "def", "_init_posix", "(", "vars", ")", ":", "# load the installed Makefile:", "makefile", "=", "get_makefile_filename", "(", ")", "try", ":", "_parse_makefile", "(", "makefile", ",", "vars", ")", "except", "IOError", "as", "e", ":", "msg", "=", "\"invalid Python installation: unable to open %s\"", "%", "makefile", "if", "hasattr", "(", "e", ",", "\"strerror\"", ")", ":", "msg", "=", "msg", "+", "\" (%s)\"", "%", "e", ".", "strerror", "raise", "IOError", "(", "msg", ")", "# load the installed pyconfig.h:", "config_h", "=", "get_config_h_filename", "(", ")", "try", ":", "with", "open", "(", "config_h", ")", "as", "f", ":", "parse_config_h", "(", "f", ",", "vars", ")", "except", "IOError", "as", "e", ":", "msg", "=", "\"invalid Python installation: unable to open %s\"", "%", "config_h", "if", "hasattr", "(", "e", ",", "\"strerror\"", ")", ":", "msg", "=", "msg", "+", "\" (%s)\"", "%", "e", ".", "strerror", "raise", "IOError", "(", "msg", ")", "# On AIX, there are wrong paths to the linker scripts in the Makefile", "# -- these paths are relative to the Python source, but when installed", "# the scripts are in another directory.", "if", "_PYTHON_BUILD", ":", "vars", "[", "'LDSHARED'", "]", "=", "vars", "[", "'BLDSHARED'", "]" ]
Initialize the module as appropriate for POSIX systems.
[ "Initialize", "the", "module", "as", "appropriate", "for", "POSIX", "systems", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L344-L369
24,741
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
_init_non_posix
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
python
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
[ "def", "_init_non_posix", "(", "vars", ")", ":", "# set basic install directories", "vars", "[", "'LIBDEST'", "]", "=", "get_path", "(", "'stdlib'", ")", "vars", "[", "'BINLIBDEST'", "]", "=", "get_path", "(", "'platstdlib'", ")", "vars", "[", "'INCLUDEPY'", "]", "=", "get_path", "(", "'include'", ")", "vars", "[", "'SO'", "]", "=", "'.pyd'", "vars", "[", "'EXE'", "]", "=", "'.exe'", "vars", "[", "'VERSION'", "]", "=", "_PY_VERSION_SHORT_NO_DOT", "vars", "[", "'BINDIR'", "]", "=", "os", ".", "path", ".", "dirname", "(", "_safe_realpath", "(", "sys", ".", "executable", ")", ")" ]
Initialize the module as appropriate for NT
[ "Initialize", "the", "module", "as", "appropriate", "for", "NT" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L372-L381
24,742
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
parse_config_h
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars
python
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars
[ "def", "parse_config_h", "(", "fp", ",", "vars", "=", "None", ")", ":", "if", "vars", "is", "None", ":", "vars", "=", "{", "}", "define_rx", "=", "re", ".", "compile", "(", "\"#define ([A-Z][A-Za-z0-9_]+) (.*)\\n\"", ")", "undef_rx", "=", "re", ".", "compile", "(", "\"/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\\n\"", ")", "while", "True", ":", "line", "=", "fp", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "m", "=", "define_rx", ".", "match", "(", "line", ")", "if", "m", ":", "n", ",", "v", "=", "m", ".", "group", "(", "1", ",", "2", ")", "try", ":", "v", "=", "int", "(", "v", ")", "except", "ValueError", ":", "pass", "vars", "[", "n", "]", "=", "v", "else", ":", "m", "=", "undef_rx", ".", "match", "(", "line", ")", "if", "m", ":", "vars", "[", "m", ".", "group", "(", "1", ")", "]", "=", "0", "return", "vars" ]
Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
[ "Parse", "a", "config", ".", "h", "-", "style", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L388-L416
24,743
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_config_h_filename
def get_config_h_filename(): """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") else: inc_dir = _PROJECT_BASE else: inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h')
python
def get_config_h_filename(): """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") else: inc_dir = _PROJECT_BASE else: inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h')
[ "def", "get_config_h_filename", "(", ")", ":", "if", "_PYTHON_BUILD", ":", "if", "os", ".", "name", "==", "\"nt\"", ":", "inc_dir", "=", "os", ".", "path", ".", "join", "(", "_PROJECT_BASE", ",", "\"PC\"", ")", "else", ":", "inc_dir", "=", "_PROJECT_BASE", "else", ":", "inc_dir", "=", "get_path", "(", "'platinclude'", ")", "return", "os", ".", "path", ".", "join", "(", "inc_dir", ",", "'pyconfig.h'", ")" ]
Return the path of pyconfig.h.
[ "Return", "the", "path", "of", "pyconfig", ".", "h", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L419-L428
24,744
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_paths
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ _ensure_cfg_read() if expand: return _expand_vars(scheme, vars) else: return dict(_SCHEMES.items(scheme))
python
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ _ensure_cfg_read() if expand: return _expand_vars(scheme, vars) else: return dict(_SCHEMES.items(scheme))
[ "def", "get_paths", "(", "scheme", "=", "_get_default_scheme", "(", ")", ",", "vars", "=", "None", ",", "expand", "=", "True", ")", ":", "_ensure_cfg_read", "(", ")", "if", "expand", ":", "return", "_expand_vars", "(", "scheme", ",", "vars", ")", "else", ":", "return", "dict", "(", "_SCHEMES", ".", "items", "(", "scheme", ")", ")" ]
Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform.
[ "Return", "a", "mapping", "containing", "an", "install", "scheme", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L442-L452
24,745
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
get_path
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
python
def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
[ "def", "get_path", "(", "name", ",", "scheme", "=", "_get_default_scheme", "(", ")", ",", "vars", "=", "None", ",", "expand", "=", "True", ")", ":", "return", "get_paths", "(", "scheme", ",", "vars", ",", "expand", ")", "[", "name", "]" ]
Return a path corresponding to the scheme. ``scheme`` is the install scheme name.
[ "Return", "a", "path", "corresponding", "to", "the", "scheme", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L455-L460
24,746
pypa/pipenv
pipenv/vendor/distlib/_backport/sysconfig.py
_main
def _main(): """Display all information sysconfig detains.""" print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars())
python
def _main(): """Display all information sysconfig detains.""" print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', get_paths()) print() _print_dict('Variables', get_config_vars())
[ "def", "_main", "(", ")", ":", "print", "(", "'Platform: \"%s\"'", "%", "get_platform", "(", ")", ")", "print", "(", "'Python version: \"%s\"'", "%", "get_python_version", "(", ")", ")", "print", "(", "'Current installation scheme: \"%s\"'", "%", "_get_default_scheme", "(", ")", ")", "print", "(", ")", "_print_dict", "(", "'Paths'", ",", "get_paths", "(", ")", ")", "print", "(", ")", "_print_dict", "(", "'Variables'", ",", "get_config_vars", "(", ")", ")" ]
Display all information sysconfig detains.
[ "Display", "all", "information", "sysconfig", "detains", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/sysconfig.py#L776-L784
24,747
pypa/pipenv
pipenv/vendor/tomlkit/source.py
Source.inc
def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) return True except StopIteration: self._idx = len(self) self._current = self.EOF if exception: raise self.parse_error(exception) return False
python
def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) return True except StopIteration: self._idx = len(self) self._current = self.EOF if exception: raise self.parse_error(exception) return False
[ "def", "inc", "(", "self", ",", "exception", "=", "None", ")", ":", "# type: (Optional[ParseError.__class__]) -> bool", "try", ":", "self", ".", "_idx", ",", "self", ".", "_current", "=", "next", "(", "self", ".", "_chars", ")", "return", "True", "except", "StopIteration", ":", "self", ".", "_idx", "=", "len", "(", "self", ")", "self", ".", "_current", "=", "self", ".", "EOF", "if", "exception", ":", "raise", "self", ".", "parse_error", "(", "exception", ")", "return", "False" ]
Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance.
[ "Increments", "the", "parser", "if", "the", "end", "of", "the", "input", "has", "not", "been", "reached", ".", "Returns", "whether", "or", "not", "it", "was", "able", "to", "advance", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/tomlkit/source.py#L117-L132
24,748
pypa/pipenv
pipenv/patched/notpip/_internal/commands/__init__.py
get_similar_commands
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
python
def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
[ "def", "get_similar_commands", "(", "name", ")", ":", "from", "difflib", "import", "get_close_matches", "name", "=", "name", ".", "lower", "(", ")", "close_commands", "=", "get_close_matches", "(", "name", ",", "commands_dict", ".", "keys", "(", ")", ")", "if", "close_commands", ":", "return", "close_commands", "[", "0", "]", "else", ":", "return", "False" ]
Command name auto-correct.
[ "Command", "name", "auto", "-", "correct", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/commands/__init__.py#L57-L68
24,749
pypa/pipenv
pipenv/vendor/jinja2/ext.py
Extension.bind
def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
python
def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
[ "def", "bind", "(", "self", ",", "environment", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "environment", "=", "environment", "return", "rv" ]
Create a copy of this extension bound to another environment.
[ "Create", "a", "copy", "of", "this", "extension", "bound", "to", "another", "environment", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L75-L80
24,750
pypa/pipenv
pipenv/vendor/jinja2/ext.py
Extension.attr
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
python
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
[ "def", "attr", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "nodes", ".", "ExtensionAttribute", "(", "self", ".", "identifier", ",", "name", ",", "lineno", "=", "lineno", ")" ]
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno)
[ "Return", "an", "attribute", "node", "for", "the", "current", "extension", ".", "This", "is", "useful", "to", "pass", "constants", "on", "extensions", "to", "generated", "template", "code", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L109-L117
24,751
pypa/pipenv
pipenv/vendor/jinja2/ext.py
InternationalizationExtension._parse_block
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif parser.stream.current.type == 'variable_begin': next(parser.stream) name = parser.stream.expect('name').value referenced.append(name) buf.append('%%(%s)s' % name) parser.stream.expect('variable_end') elif parser.stream.current.type == 'block_begin': next(parser.stream) if parser.stream.current.test('name:endtrans'): break elif parser.stream.current.test('name:pluralize'): if allow_pluralize: break parser.fail('a translatable section can have only one ' 'pluralize section') parser.fail('control structures in translatable sections are ' 'not allowed') elif parser.stream.eos: parser.fail('unclosed translation block') else: assert False, 'internal parser error' return referenced, concat(buf)
python
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif parser.stream.current.type == 'variable_begin': next(parser.stream) name = parser.stream.expect('name').value referenced.append(name) buf.append('%%(%s)s' % name) parser.stream.expect('variable_end') elif parser.stream.current.type == 'block_begin': next(parser.stream) if parser.stream.current.test('name:endtrans'): break elif parser.stream.current.test('name:pluralize'): if allow_pluralize: break parser.fail('a translatable section can have only one ' 'pluralize section') parser.fail('control structures in translatable sections are ' 'not allowed') elif parser.stream.eos: parser.fail('unclosed translation block') else: assert False, 'internal parser error' return referenced, concat(buf)
[ "def", "_parse_block", "(", "self", ",", "parser", ",", "allow_pluralize", ")", ":", "referenced", "=", "[", "]", "buf", "=", "[", "]", "while", "1", ":", "if", "parser", ".", "stream", ".", "current", ".", "type", "==", "'data'", ":", "buf", ".", "append", "(", "parser", ".", "stream", ".", "current", ".", "value", ".", "replace", "(", "'%'", ",", "'%%'", ")", ")", "next", "(", "parser", ".", "stream", ")", "elif", "parser", ".", "stream", ".", "current", ".", "type", "==", "'variable_begin'", ":", "next", "(", "parser", ".", "stream", ")", "name", "=", "parser", ".", "stream", ".", "expect", "(", "'name'", ")", ".", "value", "referenced", ".", "append", "(", "name", ")", "buf", ".", "append", "(", "'%%(%s)s'", "%", "name", ")", "parser", ".", "stream", ".", "expect", "(", "'variable_end'", ")", "elif", "parser", ".", "stream", ".", "current", ".", "type", "==", "'block_begin'", ":", "next", "(", "parser", ".", "stream", ")", "if", "parser", ".", "stream", ".", "current", ".", "test", "(", "'name:endtrans'", ")", ":", "break", "elif", "parser", ".", "stream", ".", "current", ".", "test", "(", "'name:pluralize'", ")", ":", "if", "allow_pluralize", ":", "break", "parser", ".", "fail", "(", "'a translatable section can have only one '", "'pluralize section'", ")", "parser", ".", "fail", "(", "'control structures in translatable sections are '", "'not allowed'", ")", "elif", "parser", ".", "stream", ".", "eos", ":", "parser", ".", "fail", "(", "'unclosed translation block'", ")", "else", ":", "assert", "False", ",", "'internal parser error'", "return", "referenced", ",", "concat", "(", "buf", ")" ]
Parse until the next block tag with a given name.
[ "Parse", "until", "the", "next", "block", "tag", "with", "a", "given", "name", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/ext.py#L325-L355
24,752
pypa/pipenv
pipenv/vendor/dotenv/__init__.py
get_cli_string
def get_cli_string(path=None, action=None, key=None, value=None, quote=None): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. """ command = ['dotenv'] if quote: command.append('-q %s' % quote) if path: command.append('-f %s' % path) if action: command.append(action) if key: command.append(key) if value: if ' ' in value: command.append('"%s"' % value) else: command.append(value) return ' '.join(command).strip()
python
def get_cli_string(path=None, action=None, key=None, value=None, quote=None): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. """ command = ['dotenv'] if quote: command.append('-q %s' % quote) if path: command.append('-f %s' % path) if action: command.append(action) if key: command.append(key) if value: if ' ' in value: command.append('"%s"' % value) else: command.append(value) return ' '.join(command).strip()
[ "def", "get_cli_string", "(", "path", "=", "None", ",", "action", "=", "None", ",", "key", "=", "None", ",", "value", "=", "None", ",", "quote", "=", "None", ")", ":", "command", "=", "[", "'dotenv'", "]", "if", "quote", ":", "command", ".", "append", "(", "'-q %s'", "%", "quote", ")", "if", "path", ":", "command", ".", "append", "(", "'-f %s'", "%", "path", ")", "if", "action", ":", "command", ".", "append", "(", "action", ")", "if", "key", ":", "command", ".", "append", "(", "key", ")", "if", "value", ":", "if", "' '", "in", "value", ":", "command", ".", "append", "(", "'\"%s\"'", "%", "value", ")", "else", ":", "command", ".", "append", "(", "value", ")", "return", "' '", ".", "join", "(", "command", ")", ".", "strip", "(", ")" ]
Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command.
[ "Returns", "a", "string", "suitable", "for", "running", "as", "a", "shell", "script", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/__init__.py#L9-L30
24,753
pypa/pipenv
pipenv/vendor/requests/sessions.py
merge_hooks
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
python
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
[ "def", "merge_hooks", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_hooks", "is", "None", "or", "session_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "request_hooks", "if", "request_hooks", "is", "None", "or", "request_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "session_hooks", "return", "merge_setting", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", ")" ]
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely.
[ "Properly", "merges", "both", "requests", "and", "session", "hooks", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L80-L92
24,754
pypa/pipenv
pipenv/vendor/requests/sessions.py
SessionRedirectMixin.get_redirect_target
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
python
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
[ "def", "get_redirect_target", "(", "self", ",", "resp", ")", ":", "# Due to the nature of how requests processes redirects this method will", "# be called at least once upon the original response and at least twice", "# on each subsequent redirect response (if any).", "# If a custom mixin is used to handle this logic, it may be advantageous", "# to cache the redirect location onto the response object as a private", "# attribute.", "if", "resp", ".", "is_redirect", ":", "location", "=", "resp", ".", "headers", "[", "'location'", "]", "# Currently the underlying http module on py3 decode headers", "# in latin1, but empirical evidence suggests that latin1 is very", "# rarely used with non-ASCII characters in HTTP headers.", "# It is more likely to get UTF8 header rather than latin1.", "# This causes incorrect handling of UTF8 encoded location headers.", "# To solve this, we re-encode the location in latin1.", "if", "is_py3", ":", "location", "=", "location", ".", "encode", "(", "'latin1'", ")", "return", "to_native_string", "(", "location", ",", "'utf8'", ")", "return", "None" ]
Receives a Response. Returns a redirect URI or ``None``
[ "Receives", "a", "Response", ".", "Returns", "a", "redirect", "URI", "or", "None" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L97-L116
24,755
pypa/pipenv
pipenv/vendor/requests/sessions.py
SessionRedirectMixin.should_strip_auth
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme
python
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme
[ "def", "should_strip_auth", "(", "self", ",", "old_url", ",", "new_url", ")", ":", "old_parsed", "=", "urlparse", "(", "old_url", ")", "new_parsed", "=", "urlparse", "(", "new_url", ")", "if", "old_parsed", ".", "hostname", "!=", "new_parsed", ".", "hostname", ":", "return", "True", "# Special case: allow http -> https redirect when using the standard", "# ports. This isn't specified by RFC 7235, but is kept to avoid", "# breaking backwards compatibility with older versions of requests", "# that allowed any redirects on the same host.", "if", "(", "old_parsed", ".", "scheme", "==", "'http'", "and", "old_parsed", ".", "port", "in", "(", "80", ",", "None", ")", "and", "new_parsed", ".", "scheme", "==", "'https'", "and", "new_parsed", ".", "port", "in", "(", "443", ",", "None", ")", ")", ":", "return", "False", "# Handle default port usage corresponding to scheme.", "changed_port", "=", "old_parsed", ".", "port", "!=", "new_parsed", ".", "port", "changed_scheme", "=", "old_parsed", ".", "scheme", "!=", "new_parsed", ".", "scheme", "default_port", "=", "(", "DEFAULT_PORTS", ".", "get", "(", "old_parsed", ".", "scheme", ",", "None", ")", ",", "None", ")", "if", "(", "not", "changed_scheme", "and", "old_parsed", ".", "port", "in", "default_port", "and", "new_parsed", ".", "port", "in", "default_port", ")", ":", "return", "False", "# Standard case: root URI must match", "return", "changed_port", "or", "changed_scheme" ]
Decide whether Authorization header should be removed when redirecting
[ "Decide", "whether", "Authorization", "header", "should", "be", "removed", "when", "redirecting" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L118-L141
24,756
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.merge_environment_settings
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert}
python
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert}
[ "def", "merge_environment_settings", "(", "self", ",", "url", ",", "proxies", ",", "stream", ",", "verify", ",", "cert", ")", ":", "# Gather clues from the surrounding environment.", "if", "self", ".", "trust_env", ":", "# Set environment's proxies.", "no_proxy", "=", "proxies", ".", "get", "(", "'no_proxy'", ")", "if", "proxies", "is", "not", "None", "else", "None", "env_proxies", "=", "get_environ_proxies", "(", "url", ",", "no_proxy", "=", "no_proxy", ")", "for", "(", "k", ",", "v", ")", "in", "env_proxies", ".", "items", "(", ")", ":", "proxies", ".", "setdefault", "(", "k", ",", "v", ")", "# Look for requests environment configuration and be compatible", "# with cURL.", "if", "verify", "is", "True", "or", "verify", "is", "None", ":", "verify", "=", "(", "os", ".", "environ", ".", "get", "(", "'REQUESTS_CA_BUNDLE'", ")", "or", "os", ".", "environ", ".", "get", "(", "'CURL_CA_BUNDLE'", ")", ")", "# Merge all the kwargs.", "proxies", "=", "merge_setting", "(", "proxies", ",", "self", ".", "proxies", ")", "stream", "=", "merge_setting", "(", "stream", ",", "self", ".", "stream", ")", "verify", "=", "merge_setting", "(", "verify", ",", "self", ".", "verify", ")", "cert", "=", "merge_setting", "(", "cert", ",", "self", ".", "cert", ")", "return", "{", "'verify'", ":", "verify", ",", "'proxies'", ":", "proxies", ",", "'stream'", ":", "stream", ",", "'cert'", ":", "cert", "}" ]
Check the environment and merge it with some settings. :rtype: dict
[ "Check", "the", "environment", "and", "merge", "it", "with", "some", "settings", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L690-L717
24,757
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.get_adapter
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for '%s'" % url)
python
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for '%s'" % url)
[ "def", "get_adapter", "(", "self", ",", "url", ")", ":", "for", "(", "prefix", ",", "adapter", ")", "in", "self", ".", "adapters", ".", "items", "(", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "prefix", ".", "lower", "(", ")", ")", ":", "return", "adapter", "# Nothing matches :-/", "raise", "InvalidSchema", "(", "\"No connection adapters were found for '%s'\"", "%", "url", ")" ]
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
[ "Returns", "the", "appropriate", "connection", "adapter", "for", "the", "given", "URL", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L719-L731
24,758
pypa/pipenv
pipenv/vendor/requests/sessions.py
Session.mount
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
python
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
[ "def", "mount", "(", "self", ",", "prefix", ",", "adapter", ")", ":", "self", ".", "adapters", "[", "prefix", "]", "=", "adapter", "keys_to_move", "=", "[", "k", "for", "k", "in", "self", ".", "adapters", "if", "len", "(", "k", ")", "<", "len", "(", "prefix", ")", "]", "for", "key", "in", "keys_to_move", ":", "self", ".", "adapters", "[", "key", "]", "=", "self", ".", "adapters", ".", "pop", "(", "key", ")" ]
Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length.
[ "Registers", "a", "connection", "adapter", "to", "a", "prefix", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/sessions.py#L738-L747
24,759
pypa/pipenv
pipenv/patched/notpip/_internal/utils/compat.py
console_to_str
def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ # First, get the encoding we assume. This is the preferred # encoding for the locale, unless that is not found, or # it is ASCII, in which case assume UTF-8 encoding = locale.getpreferredencoding() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: logger.warning( "Subprocess output does not appear to be encoded as %s", encoding, ) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data
python
def console_to_str(data): # type: (bytes) -> Text """Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. """ # First, get the encoding we assume. This is the preferred # encoding for the locale, unless that is not found, or # it is ASCII, in which case assume UTF-8 encoding = locale.getpreferredencoding() if (not encoding) or codecs.lookup(encoding).name == "ascii": encoding = "utf-8" # Now try to decode the data - if we fail, warn the user and # decode with replacement. try: decoded_data = data.decode(encoding) except UnicodeDecodeError: logger.warning( "Subprocess output does not appear to be encoded as %s", encoding, ) decoded_data = data.decode(encoding, errors=backslashreplace_decode) # Make sure we can print the output, by encoding it to the output # encoding with replacement of unencodable characters, and then # decoding again. # We use stderr's encoding because it's less likely to be # redirected and if we don't find an encoding we skip this # step (on the assumption that output is wrapped by something # that won't fail). # The double getattr is to deal with the possibility that we're # being called in a situation where sys.__stderr__ doesn't exist, # or doesn't have an encoding attribute. Neither of these cases # should occur in normal pip use, but there's no harm in checking # in case people use pip in (unsupported) unusual situations. output_encoding = getattr(getattr(sys, "__stderr__", None), "encoding", None) if output_encoding: output_encoded = decoded_data.encode( output_encoding, errors="backslashreplace" ) decoded_data = output_encoded.decode(output_encoding) return decoded_data
[ "def", "console_to_str", "(", "data", ")", ":", "# type: (bytes) -> Text", "# First, get the encoding we assume. This is the preferred", "# encoding for the locale, unless that is not found, or", "# it is ASCII, in which case assume UTF-8", "encoding", "=", "locale", ".", "getpreferredencoding", "(", ")", "if", "(", "not", "encoding", ")", "or", "codecs", ".", "lookup", "(", "encoding", ")", ".", "name", "==", "\"ascii\"", ":", "encoding", "=", "\"utf-8\"", "# Now try to decode the data - if we fail, warn the user and", "# decode with replacement.", "try", ":", "decoded_data", "=", "data", ".", "decode", "(", "encoding", ")", "except", "UnicodeDecodeError", ":", "logger", ".", "warning", "(", "\"Subprocess output does not appear to be encoded as %s\"", ",", "encoding", ",", ")", "decoded_data", "=", "data", ".", "decode", "(", "encoding", ",", "errors", "=", "backslashreplace_decode", ")", "# Make sure we can print the output, by encoding it to the output", "# encoding with replacement of unencodable characters, and then", "# decoding again.", "# We use stderr's encoding because it's less likely to be", "# redirected and if we don't find an encoding we skip this", "# step (on the assumption that output is wrapped by something", "# that won't fail).", "# The double getattr is to deal with the possibility that we're", "# being called in a situation where sys.__stderr__ doesn't exist,", "# or doesn't have an encoding attribute. Neither of these cases", "# should occur in normal pip use, but there's no harm in checking", "# in case people use pip in (unsupported) unusual situations.", "output_encoding", "=", "getattr", "(", "getattr", "(", "sys", ",", "\"__stderr__\"", ",", "None", ")", ",", "\"encoding\"", ",", "None", ")", "if", "output_encoding", ":", "output_encoded", "=", "decoded_data", ".", "encode", "(", "output_encoding", ",", "errors", "=", "\"backslashreplace\"", ")", "decoded_data", "=", "output_encoded", ".", "decode", "(", "output_encoding", ")", "return", "decoded_data" ]
Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors.
[ "Return", "a", "string", "safe", "for", "output", "of", "subprocess", "output", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L75-L127
24,760
pypa/pipenv
pipenv/patched/notpip/_internal/utils/compat.py
get_path_uid
def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ if hasattr(os, 'O_NOFOLLOW'): fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) file_uid = os.fstat(fd).st_uid os.close(fd) else: # AIX and Jython # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid
python
def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ if hasattr(os, 'O_NOFOLLOW'): fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) file_uid = os.fstat(fd).st_uid os.close(fd) else: # AIX and Jython # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid
[ "def", "get_path_uid", "(", "path", ")", ":", "# type: (str) -> int", "if", "hasattr", "(", "os", ",", "'O_NOFOLLOW'", ")", ":", "fd", "=", "os", ".", "open", "(", "path", ",", "os", ".", "O_RDONLY", "|", "os", ".", "O_NOFOLLOW", ")", "file_uid", "=", "os", ".", "fstat", "(", "fd", ")", ".", "st_uid", "os", ".", "close", "(", "fd", ")", "else", ":", "# AIX and Jython", "# WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW", "if", "not", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "# older versions of Jython don't have `os.fstat`", "file_uid", "=", "os", ".", "stat", "(", "path", ")", ".", "st_uid", "else", ":", "# raise OSError for parity with os.O_NOFOLLOW above", "raise", "OSError", "(", "\"%s is a symlink; Will not return uid for symlinks\"", "%", "path", ")", "return", "file_uid" ]
Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read.
[ "Return", "path", "s", "uid", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L146-L173
24,761
pypa/pipenv
pipenv/patched/notpip/_internal/utils/compat.py
expanduser
def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded
python
def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded
[ "def", "expanduser", "(", "path", ")", ":", "# type: (str) -> str", "expanded", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "path", ".", "startswith", "(", "'~/'", ")", "and", "expanded", ".", "startswith", "(", "'//'", ")", ":", "expanded", "=", "expanded", "[", "1", ":", "]", "return", "expanded" ]
Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768
[ "Expand", "~", "and", "~user", "constructions", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/compat.py#L188-L198
24,762
pypa/pipenv
pipenv/resolver.py
Entry.get_constraints
def get_constraints(self): """ Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set """ constraints = { c for c in self.resolver.parsed_constraints if c and c.name == self.entry.name } pipfile_constraint = self.get_pipfile_constraint() if pipfile_constraint: constraints.add(pipfile_constraint) return constraints
python
def get_constraints(self): """ Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set """ constraints = { c for c in self.resolver.parsed_constraints if c and c.name == self.entry.name } pipfile_constraint = self.get_pipfile_constraint() if pipfile_constraint: constraints.add(pipfile_constraint) return constraints
[ "def", "get_constraints", "(", "self", ")", ":", "constraints", "=", "{", "c", "for", "c", "in", "self", ".", "resolver", ".", "parsed_constraints", "if", "c", "and", "c", ".", "name", "==", "self", ".", "entry", ".", "name", "}", "pipfile_constraint", "=", "self", ".", "get_pipfile_constraint", "(", ")", "if", "pipfile_constraint", ":", "constraints", ".", "add", "(", "pipfile_constraint", ")", "return", "constraints" ]
Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set
[ "Retrieve", "all", "of", "the", "relevant", "constraints", "aggregated", "from", "the", "pipfile", "resolver", "and", "parent", "dependencies", "and", "their", "respective", "conflict", "resolution", "where", "possible", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L363-L378
24,763
pypa/pipenv
pipenv/resolver.py
Entry.constraint_from_parent_conflicts
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible """ # ensure that we satisfy the parent dependencies of this dep from pipenv.vendor.packaging.specifiers import Specifier parent_dependencies = set() has_mismatch = False can_use_original = True for p in self.parent_deps: # updated dependencies should be satisfied since they were resolved already if p.is_updated: continue # parents with no requirements can't conflict if not p.requirements: continue needed = p.requirements.get("dependencies", []) entry_ref = p.get_dependency(self.name) required = entry_ref.get("required_version", "*") required = self.clean_specifier(required) parent_requires = self.make_requirement(self.name, required) parent_dependencies.add("{0} => {1} ({2})".format(p.name, self.name, required)) if not parent_requires.requirement.specifier.contains(self.original_version): can_use_original = False if not parent_requires.requirement.specifier.contains(self.updated_version): has_mismatch = True if has_mismatch and not can_use_original: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve {0} ({1}) due to conflicting parent dependencies: " "\n\t{2}".format( self.name, self.updated_version, "\n\t".join(parent_dependencies) ) ) raise DependencyConflict(msg) elif can_use_original: return self.lockfile_entry.as_ireq() return self.entry.as_ireq()
python
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible """ # ensure that we satisfy the parent dependencies of this dep from pipenv.vendor.packaging.specifiers import Specifier parent_dependencies = set() has_mismatch = False can_use_original = True for p in self.parent_deps: # updated dependencies should be satisfied since they were resolved already if p.is_updated: continue # parents with no requirements can't conflict if not p.requirements: continue needed = p.requirements.get("dependencies", []) entry_ref = p.get_dependency(self.name) required = entry_ref.get("required_version", "*") required = self.clean_specifier(required) parent_requires = self.make_requirement(self.name, required) parent_dependencies.add("{0} => {1} ({2})".format(p.name, self.name, required)) if not parent_requires.requirement.specifier.contains(self.original_version): can_use_original = False if not parent_requires.requirement.specifier.contains(self.updated_version): has_mismatch = True if has_mismatch and not can_use_original: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve {0} ({1}) due to conflicting parent dependencies: " "\n\t{2}".format( self.name, self.updated_version, "\n\t".join(parent_dependencies) ) ) raise DependencyConflict(msg) elif can_use_original: return self.lockfile_entry.as_ireq() return self.entry.as_ireq()
[ "def", "constraint_from_parent_conflicts", "(", "self", ")", ":", "# ensure that we satisfy the parent dependencies of this dep", "from", "pipenv", ".", "vendor", ".", "packaging", ".", "specifiers", "import", "Specifier", "parent_dependencies", "=", "set", "(", ")", "has_mismatch", "=", "False", "can_use_original", "=", "True", "for", "p", "in", "self", ".", "parent_deps", ":", "# updated dependencies should be satisfied since they were resolved already", "if", "p", ".", "is_updated", ":", "continue", "# parents with no requirements can't conflict", "if", "not", "p", ".", "requirements", ":", "continue", "needed", "=", "p", ".", "requirements", ".", "get", "(", "\"dependencies\"", ",", "[", "]", ")", "entry_ref", "=", "p", ".", "get_dependency", "(", "self", ".", "name", ")", "required", "=", "entry_ref", ".", "get", "(", "\"required_version\"", ",", "\"*\"", ")", "required", "=", "self", ".", "clean_specifier", "(", "required", ")", "parent_requires", "=", "self", ".", "make_requirement", "(", "self", ".", "name", ",", "required", ")", "parent_dependencies", ".", "add", "(", "\"{0} => {1} ({2})\"", ".", "format", "(", "p", ".", "name", ",", "self", ".", "name", ",", "required", ")", ")", "if", "not", "parent_requires", ".", "requirement", ".", "specifier", ".", "contains", "(", "self", ".", "original_version", ")", ":", "can_use_original", "=", "False", "if", "not", "parent_requires", ".", "requirement", ".", "specifier", ".", "contains", "(", "self", ".", "updated_version", ")", ":", "has_mismatch", "=", "True", "if", "has_mismatch", "and", "not", "can_use_original", ":", "from", "pipenv", ".", "exceptions", "import", "DependencyConflict", "msg", "=", "(", "\"Cannot resolve {0} ({1}) due to conflicting parent dependencies: \"", "\"\\n\\t{2}\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "updated_version", ",", "\"\\n\\t\"", ".", "join", "(", "parent_dependencies", ")", ")", ")", "raise", "DependencyConflict", "(", "msg", ")", "elif", "can_use_original", ":", "return", "self", ".", "lockfile_entry", ".", "as_ireq", "(", ")", "return", "self", ".", "entry", ".", "as_ireq", "(", ")" ]
Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if resolution is impossible
[ "Given", "a", "resolved", "entry", "with", "multiple", "parent", "dependencies", "with", "different", "constraints", "searches", "for", "the", "resolution", "that", "satisfies", "all", "of", "the", "parent", "constraints", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L391-L433
24,764
pypa/pipenv
pipenv/resolver.py
Entry.validate_constraints
def validate_constraints(self): """ Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist """ constraints = self.get_constraints() for constraint in constraints: try: constraint.check_if_exists(False) except Exception: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve conflicting version {0}{1} while {1}{2} is " "locked.".format( self.name, self.updated_specifier, self.old_name, self.old_specifiers ) ) raise DependencyConflict(msg) return True
python
def validate_constraints(self): """ Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist """ constraints = self.get_constraints() for constraint in constraints: try: constraint.check_if_exists(False) except Exception: from pipenv.exceptions import DependencyConflict msg = ( "Cannot resolve conflicting version {0}{1} while {1}{2} is " "locked.".format( self.name, self.updated_specifier, self.old_name, self.old_specifiers ) ) raise DependencyConflict(msg) return True
[ "def", "validate_constraints", "(", "self", ")", ":", "constraints", "=", "self", ".", "get_constraints", "(", ")", "for", "constraint", "in", "constraints", ":", "try", ":", "constraint", ".", "check_if_exists", "(", "False", ")", "except", "Exception", ":", "from", "pipenv", ".", "exceptions", "import", "DependencyConflict", "msg", "=", "(", "\"Cannot resolve conflicting version {0}{1} while {1}{2} is \"", "\"locked.\"", ".", "format", "(", "self", ".", "name", ",", "self", ".", "updated_specifier", ",", "self", ".", "old_name", ",", "self", ".", "old_specifiers", ")", ")", "raise", "DependencyConflict", "(", "msg", ")", "return", "True" ]
Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constraints dont exist
[ "Retrieves", "the", "full", "set", "of", "available", "constraints", "and", "iterate", "over", "them", "validating", "that", "they", "exist", "and", "that", "they", "are", "not", "causing", "unresolvable", "conflicts", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/resolver.py#L435-L456
24,765
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
inject_into_urllib3
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
python
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
[ "def", "inject_into_urllib3", "(", ")", ":", "util", ".", "ssl_", ".", "SSLContext", "=", "SecureTransportContext", "util", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "IS_SECURETRANSPORT", "=", "True", "util", ".", "ssl_", ".", "IS_SECURETRANSPORT", "=", "True" ]
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
[ "Monkey", "-", "patch", "urllib3", "with", "SecureTransport", "-", "backed", "SSL", "-", "support", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L154-L162
24,766
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
_read_callback
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
python
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
[ "def", "_read_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "wrapped_socket", "=", "None", "try", ":", "wrapped_socket", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "wrapped_socket", "is", "None", ":", "return", "SecurityConst", ".", "errSSLInternal", "base_socket", "=", "wrapped_socket", ".", "socket", "requested_length", "=", "data_length_pointer", "[", "0", "]", "timeout", "=", "wrapped_socket", ".", "gettimeout", "(", ")", "error", "=", "None", "read_count", "=", "0", "try", ":", "while", "read_count", "<", "requested_length", ":", "if", "timeout", "is", "None", "or", "timeout", ">=", "0", ":", "if", "not", "util", ".", "wait_for_read", "(", "base_socket", ",", "timeout", ")", ":", "raise", "socket", ".", "error", "(", "errno", ".", "EAGAIN", ",", "'timed out'", ")", "remaining", "=", "requested_length", "-", "read_count", "buffer", "=", "(", "ctypes", ".", "c_char", "*", "remaining", ")", ".", "from_address", "(", "data_buffer", "+", "read_count", ")", "chunk_size", "=", "base_socket", ".", "recv_into", "(", "buffer", ",", "remaining", ")", "read_count", "+=", "chunk_size", "if", "not", "chunk_size", ":", "if", "not", "read_count", ":", "return", "SecurityConst", ".", "errSSLClosedGraceful", "break", "except", "(", "socket", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "data_length_pointer", "[", "0", "]", "=", "read_count", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedAbort", "raise", "data_length_pointer", "[", "0", "]", "=", "read_count", "if", "read_count", "!=", "requested_length", ":", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "Exception", "as", "e", ":", "if", "wrapped_socket", "is", "not", "None", ":", "wrapped_socket", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLInternal" ]
SecureTransport read callback. This is called by ST to request that data be returned from the socket.
[ "SecureTransport", "read", "callback", ".", "This", "is", "called", "by", "ST", "to", "request", "that", "data", "be", "returned", "from", "the", "socket", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L176-L228
24,767
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
_write_callback
def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
python
def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
[ "def", "_write_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "wrapped_socket", "=", "None", "try", ":", "wrapped_socket", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "wrapped_socket", "is", "None", ":", "return", "SecurityConst", ".", "errSSLInternal", "base_socket", "=", "wrapped_socket", ".", "socket", "bytes_to_write", "=", "data_length_pointer", "[", "0", "]", "data", "=", "ctypes", ".", "string_at", "(", "data_buffer", ",", "bytes_to_write", ")", "timeout", "=", "wrapped_socket", ".", "gettimeout", "(", ")", "error", "=", "None", "sent", "=", "0", "try", ":", "while", "sent", "<", "bytes_to_write", ":", "if", "timeout", "is", "None", "or", "timeout", ">=", "0", ":", "if", "not", "util", ".", "wait_for_write", "(", "base_socket", ",", "timeout", ")", ":", "raise", "socket", ".", "error", "(", "errno", ".", "EAGAIN", ",", "'timed out'", ")", "chunk_sent", "=", "base_socket", ".", "send", "(", "data", ")", "sent", "+=", "chunk_sent", "# This has some needless copying here, but I'm not sure there's", "# much value in optimising this data path.", "data", "=", "data", "[", "chunk_sent", ":", "]", "except", "(", "socket", ".", "error", ")", "as", "e", ":", "error", "=", "e", ".", "errno", "if", "error", "is", "not", "None", "and", "error", "!=", "errno", ".", "EAGAIN", ":", "data_length_pointer", "[", "0", "]", "=", "sent", "if", "error", "==", "errno", ".", "ECONNRESET", "or", "error", "==", "errno", ".", "EPIPE", ":", "return", "SecurityConst", ".", "errSSLClosedAbort", "raise", "data_length_pointer", "[", "0", "]", "=", "sent", "if", "sent", "!=", "bytes_to_write", ":", "return", "SecurityConst", ".", "errSSLWouldBlock", "return", "0", "except", "Exception", "as", "e", ":", "if", "wrapped_socket", "is", "not", "None", ":", "wrapped_socket", ".", "_exception", "=", "e", "return", "SecurityConst", ".", "errSSLInternal" ]
SecureTransport write callback. This is called by ST to request that data actually be sent on the network.
[ "SecureTransport", "write", "callback", ".", "This", "is", "called", "by", "ST", "to", "request", "that", "data", "actually", "be", "sent", "on", "the", "network", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L231-L279
24,768
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
WrappedSocket._set_ciphers
def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result)
python
def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result)
[ "def", "_set_ciphers", "(", "self", ")", ":", "ciphers", "=", "(", "Security", ".", "SSLCipherSuite", "*", "len", "(", "CIPHER_SUITES", ")", ")", "(", "*", "CIPHER_SUITES", ")", "result", "=", "Security", ".", "SSLSetEnabledCiphers", "(", "self", ".", "context", ",", "ciphers", ",", "len", "(", "CIPHER_SUITES", ")", ")", "_assert_no_error", "(", "result", ")" ]
Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare.
[ "Sets", "up", "the", "allowed", "ciphers", ".", "By", "default", "this", "matches", "the", "set", "in", "util", ".", "ssl_", ".", "DEFAULT_CIPHERS", "at", "least", "as", "supported", "by", "macOS", ".", "This", "is", "done", "custom", "and", "doesn", "t", "allow", "changing", "at", "this", "time", "mostly", "because", "parsing", "OpenSSL", "cipher", "strings", "is", "going", "to", "be", "a", "freaking", "nightmare", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L335-L346
24,769
pypa/pipenv
pipenv/vendor/urllib3/contrib/securetransport.py
WrappedSocket.handshake
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate( self.context, self._client_cert_chain ) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break
python
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate( self.context, self._client_cert_chain ) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break
[ "def", "handshake", "(", "self", ",", "server_hostname", ",", "verify", ",", "trust_bundle", ",", "min_version", ",", "max_version", ",", "client_cert", ",", "client_key", ",", "client_key_passphrase", ")", ":", "# First, we do the initial bits of connection setup. We need to create", "# a context, set its I/O funcs, and set the connection reference.", "self", ".", "context", "=", "Security", ".", "SSLCreateContext", "(", "None", ",", "SecurityConst", ".", "kSSLClientSide", ",", "SecurityConst", ".", "kSSLStreamType", ")", "result", "=", "Security", ".", "SSLSetIOFuncs", "(", "self", ".", "context", ",", "_read_callback_pointer", ",", "_write_callback_pointer", ")", "_assert_no_error", "(", "result", ")", "# Here we need to compute the handle to use. We do this by taking the", "# id of self modulo 2**31 - 1. If this is already in the dictionary, we", "# just keep incrementing by one until we find a free space.", "with", "_connection_ref_lock", ":", "handle", "=", "id", "(", "self", ")", "%", "2147483647", "while", "handle", "in", "_connection_refs", ":", "handle", "=", "(", "handle", "+", "1", ")", "%", "2147483647", "_connection_refs", "[", "handle", "]", "=", "self", "result", "=", "Security", ".", "SSLSetConnection", "(", "self", ".", "context", ",", "handle", ")", "_assert_no_error", "(", "result", ")", "# If we have a server hostname, we should set that too.", "if", "server_hostname", ":", "if", "not", "isinstance", "(", "server_hostname", ",", "bytes", ")", ":", "server_hostname", "=", "server_hostname", ".", "encode", "(", "'utf-8'", ")", "result", "=", "Security", ".", "SSLSetPeerDomainName", "(", "self", ".", "context", ",", "server_hostname", ",", "len", "(", "server_hostname", ")", ")", "_assert_no_error", "(", "result", ")", "# Setup the ciphers.", "self", ".", "_set_ciphers", "(", ")", "# Set the minimum and maximum TLS versions.", "result", "=", "Security", ".", "SSLSetProtocolVersionMin", "(", "self", ".", "context", ",", "min_version", ")", "_assert_no_error", "(", "result", ")", "result", "=", "Security", ".", "SSLSetProtocolVersionMax", "(", "self", ".", "context", ",", "max_version", ")", "_assert_no_error", "(", "result", ")", "# If there's a trust DB, we need to use it. We do that by telling", "# SecureTransport to break on server auth. We also do that if we don't", "# want to validate the certs at all: we just won't actually do any", "# authing in that case.", "if", "not", "verify", "or", "trust_bundle", "is", "not", "None", ":", "result", "=", "Security", ".", "SSLSetSessionOption", "(", "self", ".", "context", ",", "SecurityConst", ".", "kSSLSessionOptionBreakOnServerAuth", ",", "True", ")", "_assert_no_error", "(", "result", ")", "# If there's a client cert, we need to use it.", "if", "client_cert", ":", "self", ".", "_keychain", ",", "self", ".", "_keychain_dir", "=", "_temporary_keychain", "(", ")", "self", ".", "_client_cert_chain", "=", "_load_client_cert_chain", "(", "self", ".", "_keychain", ",", "client_cert", ",", "client_key", ")", "result", "=", "Security", ".", "SSLSetCertificate", "(", "self", ".", "context", ",", "self", ".", "_client_cert_chain", ")", "_assert_no_error", "(", "result", ")", "while", "True", ":", "with", "self", ".", "_raise_on_error", "(", ")", ":", "result", "=", "Security", ".", "SSLHandshake", "(", "self", ".", "context", ")", "if", "result", "==", "SecurityConst", ".", "errSSLWouldBlock", ":", "raise", "socket", ".", "timeout", "(", "\"handshake timed out\"", ")", "elif", "result", "==", "SecurityConst", ".", "errSSLServerAuthCompleted", ":", "self", ".", "_custom_validate", "(", "verify", ",", "trust_bundle", ")", "continue", "else", ":", "_assert_no_error", "(", "result", ")", "break" ]
Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code.
[ "Actually", "performs", "the", "TLS", "handshake", ".", "This", "is", "run", "automatically", "by", "wrapped", "socket", "and", "shouldn", "t", "be", "needed", "in", "user", "code", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/securetransport.py#L410-L498
24,770
pypa/pipenv
pipenv/vendor/jinja2/bccache.py
BytecodeCache.get_cache_key
def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_type): filename = filename.encode('utf-8') hash.update(filename) return hash.hexdigest()
python
def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_type): filename = filename.encode('utf-8') hash.update(filename) return hash.hexdigest()
[ "def", "get_cache_key", "(", "self", ",", "name", ",", "filename", "=", "None", ")", ":", "hash", "=", "sha1", "(", "name", ".", "encode", "(", "'utf-8'", ")", ")", "if", "filename", "is", "not", "None", ":", "filename", "=", "'|'", "+", "filename", "if", "isinstance", "(", "filename", ",", "text_type", ")", ":", "filename", "=", "filename", ".", "encode", "(", "'utf-8'", ")", "hash", ".", "update", "(", "filename", ")", "return", "hash", ".", "hexdigest", "(", ")" ]
Returns the unique hash key for this template name.
[ "Returns", "the", "unique", "hash", "key", "for", "this", "template", "name", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L166-L174
24,771
pypa/pipenv
pipenv/vendor/jinja2/bccache.py
BytecodeCache.get_bucket
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(environment, key, checksum) self.load_bytecode(bucket) return bucket
python
def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = self.get_cache_key(name, filename) checksum = self.get_source_checksum(source) bucket = Bucket(environment, key, checksum) self.load_bytecode(bucket) return bucket
[ "def", "get_bucket", "(", "self", ",", "environment", ",", "name", ",", "filename", ",", "source", ")", ":", "key", "=", "self", ".", "get_cache_key", "(", "name", ",", "filename", ")", "checksum", "=", "self", ".", "get_source_checksum", "(", "source", ")", "bucket", "=", "Bucket", "(", "environment", ",", "key", ",", "checksum", ")", "self", ".", "load_bytecode", "(", "bucket", ")", "return", "bucket" ]
Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`.
[ "Return", "a", "cache", "bucket", "for", "the", "given", "template", ".", "All", "arguments", "are", "mandatory", "but", "filename", "may", "be", "None", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/bccache.py#L180-L188
24,772
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
_get_encoding
def _get_encoding(encoding_or_label): """ Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label. """ if hasattr(encoding_or_label, 'codec_info'): return encoding_or_label encoding = lookup(encoding_or_label) if encoding is None: raise LookupError('Unknown encoding label: %r' % encoding_or_label) return encoding
python
def _get_encoding(encoding_or_label): """ Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label. """ if hasattr(encoding_or_label, 'codec_info'): return encoding_or_label encoding = lookup(encoding_or_label) if encoding is None: raise LookupError('Unknown encoding label: %r' % encoding_or_label) return encoding
[ "def", "_get_encoding", "(", "encoding_or_label", ")", ":", "if", "hasattr", "(", "encoding_or_label", ",", "'codec_info'", ")", ":", "return", "encoding_or_label", "encoding", "=", "lookup", "(", "encoding_or_label", ")", "if", "encoding", "is", "None", ":", "raise", "LookupError", "(", "'Unknown encoding label: %r'", "%", "encoding_or_label", ")", "return", "encoding" ]
Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label.
[ "Accept", "either", "an", "encoding", "object", "or", "label", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L91-L106
24,773
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
decode
def decode(input, fallback_encoding, errors='replace'): """ Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`. """ # Fail early if `encoding` is an invalid label. fallback_encoding = _get_encoding(fallback_encoding) bom_encoding, input = _detect_bom(input) encoding = bom_encoding or fallback_encoding return encoding.codec_info.decode(input, errors)[0], encoding
python
def decode(input, fallback_encoding, errors='replace'): """ Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`. """ # Fail early if `encoding` is an invalid label. fallback_encoding = _get_encoding(fallback_encoding) bom_encoding, input = _detect_bom(input) encoding = bom_encoding or fallback_encoding return encoding.codec_info.decode(input, errors)[0], encoding
[ "def", "decode", "(", "input", ",", "fallback_encoding", ",", "errors", "=", "'replace'", ")", ":", "# Fail early if `encoding` is an invalid label.", "fallback_encoding", "=", "_get_encoding", "(", "fallback_encoding", ")", "bom_encoding", ",", "input", "=", "_detect_bom", "(", "input", ")", "encoding", "=", "bom_encoding", "or", "fallback_encoding", "return", "encoding", ".", "codec_info", ".", "decode", "(", "input", ",", "errors", ")", "[", "0", "]", ",", "encoding" ]
Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A ``(output, encoding)`` tuple of an Unicode string and an :obj:`Encoding`.
[ "Decode", "a", "single", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L139-L158
24,774
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
encode
def encode(input, encoding=UTF8, errors='strict'): """ Encode a single string. :param input: An Unicode string. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A byte string. """ return _get_encoding(encoding).codec_info.encode(input, errors)[0]
python
def encode(input, encoding=UTF8, errors='strict'): """ Encode a single string. :param input: An Unicode string. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A byte string. """ return _get_encoding(encoding).codec_info.encode(input, errors)[0]
[ "def", "encode", "(", "input", ",", "encoding", "=", "UTF8", ",", "errors", "=", "'strict'", ")", ":", "return", "_get_encoding", "(", "encoding", ")", ".", "codec_info", ".", "encode", "(", "input", ",", "errors", ")", "[", "0", "]" ]
Encode a single string. :param input: An Unicode string. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A byte string.
[ "Encode", "a", "single", "string", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L172-L183
24,775
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
iter_decode
def iter_decode(input, fallback_encoding, errors='replace'): """ "Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used. """ decoder = IncrementalDecoder(fallback_encoding, errors) generator = _iter_decode_generator(input, decoder) encoding = next(generator) return generator, encoding
python
def iter_decode(input, fallback_encoding, errors='replace'): """ "Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used. """ decoder = IncrementalDecoder(fallback_encoding, errors) generator = _iter_decode_generator(input, decoder) encoding = next(generator) return generator, encoding
[ "def", "iter_decode", "(", "input", ",", "fallback_encoding", ",", "errors", "=", "'replace'", ")", ":", "decoder", "=", "IncrementalDecoder", "(", "fallback_encoding", ",", "errors", ")", "generator", "=", "_iter_decode_generator", "(", "input", ",", "decoder", ")", "encoding", "=", "next", "(", "generator", ")", "return", "generator", ",", "encoding" ]
"Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :returns: An ``(output, encoding)`` tuple. :obj:`output` is an iterable of Unicode strings, :obj:`encoding` is the :obj:`Encoding` that is being used.
[ "Pull", "-", "based", "decoder", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L186-L211
24,776
pypa/pipenv
pipenv/patched/notpip/_vendor/webencodings/__init__.py
IncrementalDecoder.decode
def decode(self, input, final=False): """Decode one chunk of the input. :param input: A byte string. :param final: Indicate that no more input is available. Must be :obj:`True` if this is the last call. :returns: An Unicode string. """ decoder = self._decoder if decoder is not None: return decoder(input, final) input = self._buffer + input encoding, input = _detect_bom(input) if encoding is None: if len(input) < 3 and not final: # Not enough data yet. self._buffer = input return '' else: # No BOM encoding = self._fallback_encoding decoder = encoding.codec_info.incrementaldecoder(self._errors).decode self._decoder = decoder self.encoding = encoding return decoder(input, final)
python
def decode(self, input, final=False): """Decode one chunk of the input. :param input: A byte string. :param final: Indicate that no more input is available. Must be :obj:`True` if this is the last call. :returns: An Unicode string. """ decoder = self._decoder if decoder is not None: return decoder(input, final) input = self._buffer + input encoding, input = _detect_bom(input) if encoding is None: if len(input) < 3 and not final: # Not enough data yet. self._buffer = input return '' else: # No BOM encoding = self._fallback_encoding decoder = encoding.codec_info.incrementaldecoder(self._errors).decode self._decoder = decoder self.encoding = encoding return decoder(input, final)
[ "def", "decode", "(", "self", ",", "input", ",", "final", "=", "False", ")", ":", "decoder", "=", "self", ".", "_decoder", "if", "decoder", "is", "not", "None", ":", "return", "decoder", "(", "input", ",", "final", ")", "input", "=", "self", ".", "_buffer", "+", "input", "encoding", ",", "input", "=", "_detect_bom", "(", "input", ")", "if", "encoding", "is", "None", ":", "if", "len", "(", "input", ")", "<", "3", "and", "not", "final", ":", "# Not enough data yet.", "self", ".", "_buffer", "=", "input", "return", "''", "else", ":", "# No BOM", "encoding", "=", "self", ".", "_fallback_encoding", "decoder", "=", "encoding", ".", "codec_info", ".", "incrementaldecoder", "(", "self", ".", "_errors", ")", ".", "decode", "self", ".", "_decoder", "=", "decoder", "self", ".", "encoding", "=", "encoding", "return", "decoder", "(", "input", ",", "final", ")" ]
Decode one chunk of the input. :param input: A byte string. :param final: Indicate that no more input is available. Must be :obj:`True` if this is the last call. :returns: An Unicode string.
[ "Decode", "one", "chunk", "of", "the", "input", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L295-L320
24,777
pypa/pipenv
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
_cf_dictionary_from_tuples
def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ dictionary_size = len(tuples) # We need to get the dictionary keys and values out in the same order. keys = (t[0] for t in tuples) values = (t[1] for t in tuples) cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, )
python
def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ dictionary_size = len(tuples) # We need to get the dictionary keys and values out in the same order. keys = (t[0] for t in tuples) values = (t[1] for t in tuples) cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, )
[ "def", "_cf_dictionary_from_tuples", "(", "tuples", ")", ":", "dictionary_size", "=", "len", "(", "tuples", ")", "# We need to get the dictionary keys and values out in the same order.", "keys", "=", "(", "t", "[", "0", "]", "for", "t", "in", "tuples", ")", "values", "=", "(", "t", "[", "1", "]", "for", "t", "in", "tuples", ")", "cf_keys", "=", "(", "CoreFoundation", ".", "CFTypeRef", "*", "dictionary_size", ")", "(", "*", "keys", ")", "cf_values", "=", "(", "CoreFoundation", ".", "CFTypeRef", "*", "dictionary_size", ")", "(", "*", "values", ")", "return", "CoreFoundation", ".", "CFDictionaryCreate", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "cf_keys", ",", "cf_values", ",", "dictionary_size", ",", "CoreFoundation", ".", "kCFTypeDictionaryKeyCallBacks", ",", "CoreFoundation", ".", "kCFTypeDictionaryValueCallBacks", ",", ")" ]
Given a list of Python tuples, create an associated CFDictionary.
[ "Given", "a", "list", "of", "Python", "tuples", "create", "an", "associated", "CFDictionary", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L37-L56
24,778
pypa/pipenv
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
_cf_string_to_unicode
def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = buffer.value if string is not None: string = string.decode('utf-8') return string
python
def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = buffer.value if string is not None: string = string.decode('utf-8') return string
[ "def", "_cf_string_to_unicode", "(", "value", ")", ":", "value_as_void_p", "=", "ctypes", ".", "cast", "(", "value", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_void_p", ")", ")", "string", "=", "CoreFoundation", ".", "CFStringGetCStringPtr", "(", "value_as_void_p", ",", "CFConst", ".", "kCFStringEncodingUTF8", ")", "if", "string", "is", "None", ":", "buffer", "=", "ctypes", ".", "create_string_buffer", "(", "1024", ")", "result", "=", "CoreFoundation", ".", "CFStringGetCString", "(", "value_as_void_p", ",", "buffer", ",", "1024", ",", "CFConst", ".", "kCFStringEncodingUTF8", ")", "if", "not", "result", ":", "raise", "OSError", "(", "'Error copying C string from CFStringRef'", ")", "string", "=", "buffer", ".", "value", "if", "string", "is", "not", "None", ":", "string", "=", "string", ".", "decode", "(", "'utf-8'", ")", "return", "string" ]
Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex.
[ "Creates", "a", "Unicode", "string", "from", "a", "CFString", "object", ".", "Used", "entirely", "for", "error", "reporting", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L59-L85
24,779
pypa/pipenv
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
_assert_no_error
def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if output is None or output == u'': output = u'OSStatus %s' % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output)
python
def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if output is None or output == u'': output = u'OSStatus %s' % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output)
[ "def", "_assert_no_error", "(", "error", ",", "exception_class", "=", "None", ")", ":", "if", "error", "==", "0", ":", "return", "cf_error_string", "=", "Security", ".", "SecCopyErrorMessageString", "(", "error", ",", "None", ")", "output", "=", "_cf_string_to_unicode", "(", "cf_error_string", ")", "CoreFoundation", ".", "CFRelease", "(", "cf_error_string", ")", "if", "output", "is", "None", "or", "output", "==", "u''", ":", "output", "=", "u'OSStatus %s'", "%", "error", "if", "exception_class", "is", "None", ":", "exception_class", "=", "ssl", ".", "SSLError", "raise", "exception_class", "(", "output", ")" ]
Checks the return code and throws an exception if there is an error to report
[ "Checks", "the", "return", "code", "and", "throws", "an", "exception", "if", "there", "is", "an", "error", "to", "report" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L88-L106
24,780
pypa/pipenv
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
_cert_array_from_pem
def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # Normalize the PEM bundle's line endings. pem_bundle = pem_bundle.replace(b"\r\n", b"\n") der_certs = [ base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle) ] if not der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks) ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) return cert_array
python
def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # Normalize the PEM bundle's line endings. pem_bundle = pem_bundle.replace(b"\r\n", b"\n") der_certs = [ base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle) ] if not der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks) ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) return cert_array
[ "def", "_cert_array_from_pem", "(", "pem_bundle", ")", ":", "# Normalize the PEM bundle's line endings.", "pem_bundle", "=", "pem_bundle", ".", "replace", "(", "b\"\\r\\n\"", ",", "b\"\\n\"", ")", "der_certs", "=", "[", "base64", ".", "b64decode", "(", "match", ".", "group", "(", "1", ")", ")", "for", "match", "in", "_PEM_CERTS_RE", ".", "finditer", "(", "pem_bundle", ")", "]", "if", "not", "der_certs", ":", "raise", "ssl", ".", "SSLError", "(", "\"No root certificates specified\"", ")", "cert_array", "=", "CoreFoundation", ".", "CFArrayCreateMutable", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "0", ",", "ctypes", ".", "byref", "(", "CoreFoundation", ".", "kCFTypeArrayCallBacks", ")", ")", "if", "not", "cert_array", ":", "raise", "ssl", ".", "SSLError", "(", "\"Unable to allocate memory!\"", ")", "try", ":", "for", "der_bytes", "in", "der_certs", ":", "certdata", "=", "_cf_data_from_bytes", "(", "der_bytes", ")", "if", "not", "certdata", ":", "raise", "ssl", ".", "SSLError", "(", "\"Unable to allocate memory!\"", ")", "cert", "=", "Security", ".", "SecCertificateCreateWithData", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "certdata", ")", "CoreFoundation", ".", "CFRelease", "(", "certdata", ")", "if", "not", "cert", ":", "raise", "ssl", ".", "SSLError", "(", "\"Unable to build cert object!\"", ")", "CoreFoundation", ".", "CFArrayAppendValue", "(", "cert_array", ",", "cert", ")", "CoreFoundation", ".", "CFRelease", "(", "cert", ")", "except", "Exception", ":", "# We need to free the array before the exception bubbles further.", "# We only want to do that if an error occurs: otherwise, the caller", "# should free.", "CoreFoundation", ".", "CFRelease", "(", "cert_array", ")", "return", "cert_array" ]
Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain.
[ "Given", "a", "bundle", "of", "certs", "in", "PEM", "format", "turns", "them", "into", "a", "CFArray", "of", "certs", "that", "can", "be", "used", "to", "validate", "a", "cert", "chain", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L109-L152
24,781
pypa/pipenv
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
_temporary_keychain
def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # Unfortunately, SecKeychainCreate requires a path to a keychain. This # means we cannot use mkstemp to use a generic temporary file. Instead, # we're going to create a temporary directory and a filename to use there. # This filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b16encode(random_bytes[:8]).decode('utf-8') password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode('utf-8') # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory
python
def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # Unfortunately, SecKeychainCreate requires a path to a keychain. This # means we cannot use mkstemp to use a generic temporary file. Instead, # we're going to create a temporary directory and a filename to use there. # This filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b16encode(random_bytes[:8]).decode('utf-8') password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode('utf-8') # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory
[ "def", "_temporary_keychain", "(", ")", ":", "# Unfortunately, SecKeychainCreate requires a path to a keychain. This", "# means we cannot use mkstemp to use a generic temporary file. Instead,", "# we're going to create a temporary directory and a filename to use there.", "# This filename will be 8 random bytes expanded into base64. We also need", "# some random bytes to password-protect the keychain we're creating, so we", "# ask for 40 random bytes.", "random_bytes", "=", "os", ".", "urandom", "(", "40", ")", "filename", "=", "base64", ".", "b16encode", "(", "random_bytes", "[", ":", "8", "]", ")", ".", "decode", "(", "'utf-8'", ")", "password", "=", "base64", ".", "b16encode", "(", "random_bytes", "[", "8", ":", "]", ")", "# Must be valid UTF-8", "tempdirectory", "=", "tempfile", ".", "mkdtemp", "(", ")", "keychain_path", "=", "os", ".", "path", ".", "join", "(", "tempdirectory", ",", "filename", ")", ".", "encode", "(", "'utf-8'", ")", "# We now want to create the keychain itself.", "keychain", "=", "Security", ".", "SecKeychainRef", "(", ")", "status", "=", "Security", ".", "SecKeychainCreate", "(", "keychain_path", ",", "len", "(", "password", ")", ",", "password", ",", "False", ",", "None", ",", "ctypes", ".", "byref", "(", "keychain", ")", ")", "_assert_no_error", "(", "status", ")", "# Having created the keychain, we want to pass it off to the caller.", "return", "keychain", ",", "tempdirectory" ]
This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it.
[ "This", "function", "creates", "a", "temporary", "Mac", "keychain", "that", "we", "can", "use", "to", "work", "with", "credentials", ".", "This", "keychain", "uses", "a", "one", "-", "time", "password", "and", "a", "temporary", "file", "to", "store", "the", "data", ".", "We", "expect", "to", "have", "one", "keychain", "per", "socket", ".", "The", "returned", "SecKeychainRef", "must", "be", "freed", "by", "the", "caller", "including", "calling", "SecKeychainDelete", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L171-L208
24,782
pypa/pipenv
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
_load_client_cert_chain
def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # Ok, the strategy. # # This relies on knowing that macOS will not give you a SecIdentityRef # unless you have imported a key into a keychain. This is a somewhat # artificial limitation of macOS (for example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file( keychain, file_path ) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj)
python
def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # Ok, the strategy. # # This relies on knowing that macOS will not give you a SecIdentityRef # unless you have imported a key into a keychain. This is a somewhat # artificial limitation of macOS (for example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file( keychain, file_path ) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj)
[ "def", "_load_client_cert_chain", "(", "keychain", ",", "*", "paths", ")", ":", "# Ok, the strategy.", "#", "# This relies on knowing that macOS will not give you a SecIdentityRef", "# unless you have imported a key into a keychain. This is a somewhat", "# artificial limitation of macOS (for example, it doesn't necessarily", "# affect iOS), but there is nothing inside Security.framework that lets you", "# get a SecIdentityRef without having a key in a keychain.", "#", "# So the policy here is we take all the files and iterate them in order.", "# Each one will use SecItemImport to have one or more objects loaded from", "# it. We will also point at a keychain that macOS can use to work with the", "# private key.", "#", "# Once we have all the objects, we'll check what we actually have. If we", "# already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,", "# we'll take the first certificate (which we assume to be our leaf) and", "# ask the keychain to give us a SecIdentityRef with that cert's associated", "# key.", "#", "# We'll then return a CFArray containing the trust chain: one", "# SecIdentityRef and then zero-or-more SecCertificateRef objects. The", "# responsibility for freeing this CFArray will be with the caller. This", "# CFArray must remain alive for the entire connection, so in practice it", "# will be stored with a single SSLSocket, along with the reference to the", "# keychain.", "certificates", "=", "[", "]", "identities", "=", "[", "]", "# Filter out bad paths.", "paths", "=", "(", "path", "for", "path", "in", "paths", "if", "path", ")", "try", ":", "for", "file_path", "in", "paths", ":", "new_identities", ",", "new_certs", "=", "_load_items_from_file", "(", "keychain", ",", "file_path", ")", "identities", ".", "extend", "(", "new_identities", ")", "certificates", ".", "extend", "(", "new_certs", ")", "# Ok, we have everything. The question is: do we have an identity? If", "# not, we want to grab one from the first cert we have.", "if", "not", "identities", ":", "new_identity", "=", "Security", ".", "SecIdentityRef", "(", ")", "status", "=", "Security", ".", "SecIdentityCreateWithCertificate", "(", "keychain", ",", "certificates", "[", "0", "]", ",", "ctypes", ".", "byref", "(", "new_identity", ")", ")", "_assert_no_error", "(", "status", ")", "identities", ".", "append", "(", "new_identity", ")", "# We now want to release the original certificate, as we no longer", "# need it.", "CoreFoundation", ".", "CFRelease", "(", "certificates", ".", "pop", "(", "0", ")", ")", "# We now need to build a new CFArray that holds the trust chain.", "trust_chain", "=", "CoreFoundation", ".", "CFArrayCreateMutable", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "0", ",", "ctypes", ".", "byref", "(", "CoreFoundation", ".", "kCFTypeArrayCallBacks", ")", ",", ")", "for", "item", "in", "itertools", ".", "chain", "(", "identities", ",", "certificates", ")", ":", "# ArrayAppendValue does a CFRetain on the item. That's fine,", "# because the finally block will release our other refs to them.", "CoreFoundation", ".", "CFArrayAppendValue", "(", "trust_chain", ",", "item", ")", "return", "trust_chain", "finally", ":", "for", "obj", "in", "itertools", ".", "chain", "(", "identities", ",", "certificates", ")", ":", "CoreFoundation", ".", "CFRelease", "(", "obj", ")" ]
Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain.
[ "Load", "certificates", "and", "maybe", "keys", "from", "a", "number", "of", "files", ".", "Has", "the", "end", "goal", "of", "returning", "a", "CFArray", "containing", "one", "SecIdentityRef", "and", "then", "zero", "or", "more", "SecCertificateRef", "objects", "suitable", "for", "use", "as", "a", "client", "certificate", "trust", "chain", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L270-L346
24,783
pypa/pipenv
pipenv/vendor/urllib3/response.py
HTTPResponse.get_redirect_location
def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False
python
def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False
[ "def", "get_redirect_location", "(", "self", ")", ":", "if", "self", ".", "status", "in", "self", ".", "REDIRECT_STATUSES", ":", "return", "self", ".", "headers", ".", "get", "(", "'location'", ")", "return", "False" ]
Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code.
[ "Should", "we", "redirect", "and", "where", "to?" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L211-L222
24,784
pypa/pipenv
pipenv/vendor/urllib3/response.py
HTTPResponse._init_length
def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get('content-length') if length is not None: if self.chunked: # This Response will fail with an IncompleteRead if it can't be # received as chunked. This method falls back to attempt reading # the response before raising an exception. log.warning("Received response with both Content-Length and " "Transfer-Encoding set. This is expressly forbidden " "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " "attempting to process response as Transfer-Encoding: " "chunked.") return None try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = set([int(val) for val in length.split(',')]) if len(lengths) > 1: raise InvalidHeader("Content-Length contained multiple " "unmatching values (%s)" % length) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None # Convert status to int for comparison # In some cases, httplib returns a status of "_UNKNOWN" try: status = int(self.status) except ValueError: status = 0 # Check for responses that shouldn't include a body if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD': length = 0 return length
python
def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get('content-length') if length is not None: if self.chunked: # This Response will fail with an IncompleteRead if it can't be # received as chunked. This method falls back to attempt reading # the response before raising an exception. log.warning("Received response with both Content-Length and " "Transfer-Encoding set. This is expressly forbidden " "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " "attempting to process response as Transfer-Encoding: " "chunked.") return None try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = set([int(val) for val in length.split(',')]) if len(lengths) > 1: raise InvalidHeader("Content-Length contained multiple " "unmatching values (%s)" % length) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None # Convert status to int for comparison # In some cases, httplib returns a status of "_UNKNOWN" try: status = int(self.status) except ValueError: status = 0 # Check for responses that shouldn't include a body if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD': length = 0 return length
[ "def", "_init_length", "(", "self", ",", "request_method", ")", ":", "length", "=", "self", ".", "headers", ".", "get", "(", "'content-length'", ")", "if", "length", "is", "not", "None", ":", "if", "self", ".", "chunked", ":", "# This Response will fail with an IncompleteRead if it can't be", "# received as chunked. This method falls back to attempt reading", "# the response before raising an exception.", "log", ".", "warning", "(", "\"Received response with both Content-Length and \"", "\"Transfer-Encoding set. This is expressly forbidden \"", "\"by RFC 7230 sec 3.3.2. Ignoring Content-Length and \"", "\"attempting to process response as Transfer-Encoding: \"", "\"chunked.\"", ")", "return", "None", "try", ":", "# RFC 7230 section 3.3.2 specifies multiple content lengths can", "# be sent in a single Content-Length header", "# (e.g. Content-Length: 42, 42). This line ensures the values", "# are all valid ints and that as long as the `set` length is 1,", "# all values are the same. Otherwise, the header is invalid.", "lengths", "=", "set", "(", "[", "int", "(", "val", ")", "for", "val", "in", "length", ".", "split", "(", "','", ")", "]", ")", "if", "len", "(", "lengths", ")", ">", "1", ":", "raise", "InvalidHeader", "(", "\"Content-Length contained multiple \"", "\"unmatching values (%s)\"", "%", "length", ")", "length", "=", "lengths", ".", "pop", "(", ")", "except", "ValueError", ":", "length", "=", "None", "else", ":", "if", "length", "<", "0", ":", "length", "=", "None", "# Convert status to int for comparison", "# In some cases, httplib returns a status of \"_UNKNOWN\"", "try", ":", "status", "=", "int", "(", "self", ".", "status", ")", "except", "ValueError", ":", "status", "=", "0", "# Check for responses that shouldn't include a body", "if", "status", "in", "(", "204", ",", "304", ")", "or", "100", "<=", "status", "<", "200", "or", "request_method", "==", "'HEAD'", ":", "length", "=", "0", "return", "length" ]
Set initial length value for Response content if available.
[ "Set", "initial", "length", "value", "for", "Response", "content", "if", "available", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L255-L301
24,785
pypa/pipenv
pipenv/vendor/urllib3/response.py
HTTPResponse._flush_decoder
def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b'') return buf + self._decoder.flush() return b''
python
def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b'') return buf + self._decoder.flush() return b''
[ "def", "_flush_decoder", "(", "self", ")", ":", "if", "self", ".", "_decoder", ":", "buf", "=", "self", ".", "_decoder", ".", "decompress", "(", "b''", ")", "return", "buf", "+", "self", ".", "_decoder", ".", "flush", "(", ")", "return", "b''" ]
Flushes the decoder. Should only be called if the decoder is actually being used.
[ "Flushes", "the", "decoder", ".", "Should", "only", "be", "called", "if", "the", "decoder", "is", "actually", "being", "used", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L336-L345
24,786
pypa/pipenv
pipenv/vendor/urllib3/response.py
HTTPResponse._error_catcher
def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ clean_exit = False try: try: yield except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except (HTTPException, SocketError) as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now to ensure that the connection is # released back to the pool. if self._original_response: self._original_response.close() # Closing the response may not actually be sufficient to close # everything, so if we have a hold of the connection close that # too. if self._connection: self._connection.close() # If we hold the original response but it's closed now, we should # return the connection back to the pool. if self._original_response and self._original_response.isclosed(): self.release_conn()
python
def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ clean_exit = False try: try: yield except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except (HTTPException, SocketError) as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now to ensure that the connection is # released back to the pool. if self._original_response: self._original_response.close() # Closing the response may not actually be sufficient to close # everything, so if we have a hold of the connection close that # too. if self._connection: self._connection.close() # If we hold the original response but it's closed now, we should # return the connection back to the pool. if self._original_response and self._original_response.isclosed(): self.release_conn()
[ "def", "_error_catcher", "(", "self", ")", ":", "clean_exit", "=", "False", "try", ":", "try", ":", "yield", "except", "SocketTimeout", ":", "# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but", "# there is yet no clean way to get at it from this context.", "raise", "ReadTimeoutError", "(", "self", ".", "_pool", ",", "None", ",", "'Read timed out.'", ")", "except", "BaseSSLError", "as", "e", ":", "# FIXME: Is there a better way to differentiate between SSLErrors?", "if", "'read operation timed out'", "not", "in", "str", "(", "e", ")", ":", "# Defensive:", "# This shouldn't happen but just in case we're missing an edge", "# case, let's avoid swallowing SSL errors.", "raise", "raise", "ReadTimeoutError", "(", "self", ".", "_pool", ",", "None", ",", "'Read timed out.'", ")", "except", "(", "HTTPException", ",", "SocketError", ")", "as", "e", ":", "# This includes IncompleteRead.", "raise", "ProtocolError", "(", "'Connection broken: %r'", "%", "e", ",", "e", ")", "# If no exception is thrown, we should avoid cleaning up", "# unnecessarily.", "clean_exit", "=", "True", "finally", ":", "# If we didn't terminate cleanly, we need to throw away our", "# connection.", "if", "not", "clean_exit", ":", "# The response may not be closed but we're not going to use it", "# anymore so close it now to ensure that the connection is", "# released back to the pool.", "if", "self", ".", "_original_response", ":", "self", ".", "_original_response", ".", "close", "(", ")", "# Closing the response may not actually be sufficient to close", "# everything, so if we have a hold of the connection close that", "# too.", "if", "self", ".", "_connection", ":", "self", ".", "_connection", ".", "close", "(", ")", "# If we hold the original response but it's closed now, we should", "# return the connection back to the pool.", "if", "self", ".", "_original_response", "and", "self", ".", "_original_response", ".", "isclosed", "(", ")", ":", "self", ".", "release_conn", "(", ")" ]
Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool.
[ "Catch", "low", "-", "level", "python", "exceptions", "instead", "re", "-", "raising", "urllib3", "variants", "so", "that", "low", "-", "level", "exceptions", "are", "not", "leaked", "in", "the", "high", "-", "level", "api", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L348-L402
24,787
pypa/pipenv
pipenv/vendor/urllib3/response.py
HTTPResponse.geturl
def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. """ if self.retries is not None and len(self.retries.history): return self.retries.history[-1].redirect_location else: return self._request_url
python
def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. """ if self.retries is not None and len(self.retries.history): return self.retries.history[-1].redirect_location else: return self._request_url
[ "def", "geturl", "(", "self", ")", ":", "if", "self", ".", "retries", "is", "not", "None", "and", "len", "(", "self", ".", "retries", ".", "history", ")", ":", "return", "self", ".", "retries", ".", "history", "[", "-", "1", "]", ".", "redirect_location", "else", ":", "return", "self", ".", "_request_url" ]
Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location.
[ "Returns", "the", "URL", "that", "was", "the", "source", "of", "this", "response", ".", "If", "the", "request", "that", "generated", "this", "response", "redirected", "this", "method", "will", "return", "the", "final", "redirect", "location", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/urllib3/response.py#L696-L705
24,788
pypa/pipenv
pipenv/vendor/vistir/spin.py
VistirSpinner.fail
def fail(self, text=u"FAIL", err=False): """Set fail finalizer to a spinner.""" # Do not display spin text for fail state self._text = None _text = text if text else u"FAIL" err = err or not self.write_to_stdout self._freeze(_text, err=err)
python
def fail(self, text=u"FAIL", err=False): """Set fail finalizer to a spinner.""" # Do not display spin text for fail state self._text = None _text = text if text else u"FAIL" err = err or not self.write_to_stdout self._freeze(_text, err=err)
[ "def", "fail", "(", "self", ",", "text", "=", "u\"FAIL\"", ",", "err", "=", "False", ")", ":", "# Do not display spin text for fail state", "self", ".", "_text", "=", "None", "_text", "=", "text", "if", "text", "else", "u\"FAIL\"", "err", "=", "err", "or", "not", "self", ".", "write_to_stdout", "self", ".", "_freeze", "(", "_text", ",", "err", "=", "err", ")" ]
Set fail finalizer to a spinner.
[ "Set", "fail", "finalizer", "to", "a", "spinner", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L236-L243
24,789
pypa/pipenv
pipenv/vendor/vistir/spin.py
VistirSpinner.write_err
def write_err(self, text): """Write error text in the terminal without breaking the spinner.""" stderr = self.stderr if self.stderr.closed: stderr = sys.stderr stderr.write(decode_output(u"\r", target_stream=stderr)) stderr.write(decode_output(CLEAR_LINE, target_stream=stderr)) if text is None: text = "" text = decode_output(u"{0}\n".format(text), target_stream=stderr) self.stderr.write(text) self.out_buff.write(decode_output(text, target_stream=self.out_buff))
python
def write_err(self, text): """Write error text in the terminal without breaking the spinner.""" stderr = self.stderr if self.stderr.closed: stderr = sys.stderr stderr.write(decode_output(u"\r", target_stream=stderr)) stderr.write(decode_output(CLEAR_LINE, target_stream=stderr)) if text is None: text = "" text = decode_output(u"{0}\n".format(text), target_stream=stderr) self.stderr.write(text) self.out_buff.write(decode_output(text, target_stream=self.out_buff))
[ "def", "write_err", "(", "self", ",", "text", ")", ":", "stderr", "=", "self", ".", "stderr", "if", "self", ".", "stderr", ".", "closed", ":", "stderr", "=", "sys", ".", "stderr", "stderr", ".", "write", "(", "decode_output", "(", "u\"\\r\"", ",", "target_stream", "=", "stderr", ")", ")", "stderr", ".", "write", "(", "decode_output", "(", "CLEAR_LINE", ",", "target_stream", "=", "stderr", ")", ")", "if", "text", "is", "None", ":", "text", "=", "\"\"", "text", "=", "decode_output", "(", "u\"{0}\\n\"", ".", "format", "(", "text", ")", ",", "target_stream", "=", "stderr", ")", "self", ".", "stderr", ".", "write", "(", "text", ")", "self", ".", "out_buff", ".", "write", "(", "decode_output", "(", "text", ",", "target_stream", "=", "self", ".", "out_buff", ")", ")" ]
Write error text in the terminal without breaking the spinner.
[ "Write", "error", "text", "in", "the", "terminal", "without", "breaking", "the", "spinner", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L270-L281
24,790
pypa/pipenv
pipenv/vendor/jinja2/lexer.py
describe_token_expr
def describe_token_expr(expr): """Like `describe_token` but for token expressions.""" if ':' in expr: type, value = expr.split(':', 1) if type == 'name': return value else: type = expr return _describe_token_type(type)
python
def describe_token_expr(expr): """Like `describe_token` but for token expressions.""" if ':' in expr: type, value = expr.split(':', 1) if type == 'name': return value else: type = expr return _describe_token_type(type)
[ "def", "describe_token_expr", "(", "expr", ")", ":", "if", "':'", "in", "expr", ":", "type", ",", "value", "=", "expr", ".", "split", "(", "':'", ",", "1", ")", "if", "type", "==", "'name'", ":", "return", "value", "else", ":", "type", "=", "expr", "return", "_describe_token_type", "(", "type", ")" ]
Like `describe_token` but for token expressions.
[ "Like", "describe_token", "but", "for", "token", "expressions", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L178-L186
24,791
pypa/pipenv
pipenv/vendor/jinja2/lexer.py
get_lexer
def get_lexer(environment): """Return a lexer which is probably cached.""" key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_blocks, environment.lstrip_blocks, environment.newline_sequence, environment.keep_trailing_newline) lexer = _lexer_cache.get(key) if lexer is None: lexer = Lexer(environment) _lexer_cache[key] = lexer return lexer
python
def get_lexer(environment): """Return a lexer which is probably cached.""" key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_blocks, environment.lstrip_blocks, environment.newline_sequence, environment.keep_trailing_newline) lexer = _lexer_cache.get(key) if lexer is None: lexer = Lexer(environment) _lexer_cache[key] = lexer return lexer
[ "def", "get_lexer", "(", "environment", ")", ":", "key", "=", "(", "environment", ".", "block_start_string", ",", "environment", ".", "block_end_string", ",", "environment", ".", "variable_start_string", ",", "environment", ".", "variable_end_string", ",", "environment", ".", "comment_start_string", ",", "environment", ".", "comment_end_string", ",", "environment", ".", "line_statement_prefix", ",", "environment", ".", "line_comment_prefix", ",", "environment", ".", "trim_blocks", ",", "environment", ".", "lstrip_blocks", ",", "environment", ".", "newline_sequence", ",", "environment", ".", "keep_trailing_newline", ")", "lexer", "=", "_lexer_cache", ".", "get", "(", "key", ")", "if", "lexer", "is", "None", ":", "lexer", "=", "Lexer", "(", "environment", ")", "_lexer_cache", "[", "key", "]", "=", "lexer", "return", "lexer" ]
Return a lexer which is probably cached.
[ "Return", "a", "lexer", "which", "is", "probably", "cached", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L391-L409
24,792
pypa/pipenv
pipenv/vendor/jinja2/lexer.py
Lexer.tokenize
def tokenize(self, source, name=None, filename=None, state=None): """Calls tokeniter + tokenize and wraps it in a token stream. """ stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name, filename), name, filename)
python
def tokenize(self, source, name=None, filename=None, state=None): """Calls tokeniter + tokenize and wraps it in a token stream. """ stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name, filename), name, filename)
[ "def", "tokenize", "(", "self", ",", "source", ",", "name", "=", "None", ",", "filename", "=", "None", ",", "state", "=", "None", ")", ":", "stream", "=", "self", ".", "tokeniter", "(", "source", ",", "name", ",", "filename", ",", "state", ")", "return", "TokenStream", "(", "self", ".", "wrap", "(", "stream", ",", "name", ",", "filename", ")", ",", "name", ",", "filename", ")" ]
Calls tokeniter + tokenize and wraps it in a token stream.
[ "Calls", "tokeniter", "+", "tokenize", "and", "wraps", "it", "in", "a", "token", "stream", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/lexer.py#L552-L556
24,793
pypa/pipenv
pipenv/pyenv.py
Runner.iter_installable_versions
def iter_installable_versions(self): """Iterate through CPython versions available for Pipenv to install. """ for name in self._pyenv('install', '--list').out.splitlines(): try: version = Version.parse(name.strip()) except ValueError: continue yield version
python
def iter_installable_versions(self): """Iterate through CPython versions available for Pipenv to install. """ for name in self._pyenv('install', '--list').out.splitlines(): try: version = Version.parse(name.strip()) except ValueError: continue yield version
[ "def", "iter_installable_versions", "(", "self", ")", ":", "for", "name", "in", "self", ".", "_pyenv", "(", "'install'", ",", "'--list'", ")", ".", "out", ".", "splitlines", "(", ")", ":", "try", ":", "version", "=", "Version", ".", "parse", "(", "name", ".", "strip", "(", ")", ")", "except", "ValueError", ":", "continue", "yield", "version" ]
Iterate through CPython versions available for Pipenv to install.
[ "Iterate", "through", "CPython", "versions", "available", "for", "Pipenv", "to", "install", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/pyenv.py#L75-L83
24,794
pypa/pipenv
pipenv/pyenv.py
Runner.find_version_to_install
def find_version_to_install(self, name): """Find a version in pyenv from the version supplied. A ValueError is raised if a matching version cannot be found. """ version = Version.parse(name) if version.patch is not None: return name try: best_match = max(( inst_version for inst_version in self.iter_installable_versions() if inst_version.matches_minor(version) ), key=operator.attrgetter('cmpkey')) except ValueError: raise ValueError( 'no installable version found for {0!r}'.format(name), ) return best_match
python
def find_version_to_install(self, name): """Find a version in pyenv from the version supplied. A ValueError is raised if a matching version cannot be found. """ version = Version.parse(name) if version.patch is not None: return name try: best_match = max(( inst_version for inst_version in self.iter_installable_versions() if inst_version.matches_minor(version) ), key=operator.attrgetter('cmpkey')) except ValueError: raise ValueError( 'no installable version found for {0!r}'.format(name), ) return best_match
[ "def", "find_version_to_install", "(", "self", ",", "name", ")", ":", "version", "=", "Version", ".", "parse", "(", "name", ")", "if", "version", ".", "patch", "is", "not", "None", ":", "return", "name", "try", ":", "best_match", "=", "max", "(", "(", "inst_version", "for", "inst_version", "in", "self", ".", "iter_installable_versions", "(", ")", "if", "inst_version", ".", "matches_minor", "(", "version", ")", ")", ",", "key", "=", "operator", ".", "attrgetter", "(", "'cmpkey'", ")", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'no installable version found for {0!r}'", ".", "format", "(", "name", ")", ",", ")", "return", "best_match" ]
Find a version in pyenv from the version supplied. A ValueError is raised if a matching version cannot be found.
[ "Find", "a", "version", "in", "pyenv", "from", "the", "version", "supplied", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/pyenv.py#L85-L103
24,795
pypa/pipenv
pipenv/pyenv.py
Runner.install
def install(self, version): """Install the given version with pyenv. The version must be a ``Version`` instance representing a version found in pyenv. A ValueError is raised if the given version does not have a match in pyenv. A PyenvError is raised if the pyenv command fails. """ c = self._pyenv( 'install', '-s', str(version), timeout=PIPENV_INSTALL_TIMEOUT, ) return c
python
def install(self, version): """Install the given version with pyenv. The version must be a ``Version`` instance representing a version found in pyenv. A ValueError is raised if the given version does not have a match in pyenv. A PyenvError is raised if the pyenv command fails. """ c = self._pyenv( 'install', '-s', str(version), timeout=PIPENV_INSTALL_TIMEOUT, ) return c
[ "def", "install", "(", "self", ",", "version", ")", ":", "c", "=", "self", ".", "_pyenv", "(", "'install'", ",", "'-s'", ",", "str", "(", "version", ")", ",", "timeout", "=", "PIPENV_INSTALL_TIMEOUT", ",", ")", "return", "c" ]
Install the given version with pyenv. The version must be a ``Version`` instance representing a version found in pyenv. A ValueError is raised if the given version does not have a match in pyenv. A PyenvError is raised if the pyenv command fails.
[ "Install", "the", "given", "version", "with", "pyenv", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/pyenv.py#L105-L118
24,796
pypa/pipenv
pipenv/patched/notpip/_internal/req/constructors.py
deduce_helpful_msg
def deduce_helpful_msg(req): # type: (str) -> str """Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path """ msg = "" if os.path.exists(req): msg = " It does exist." # Try to parse and check if it is a requirements file. try: with open(req, 'r') as fp: # parse first line only next(parse_requirements(fp.read())) msg += " The argument you provided " + \ "(%s) appears to be a" % (req) + \ " requirements file. If that is the" + \ " case, use the '-r' flag to install" + \ " the packages specified within it." except RequirementParseError: logger.debug("Cannot parse '%s' as requirements \ file" % (req), exc_info=True) else: msg += " File '%s' does not exist." % (req) return msg
python
def deduce_helpful_msg(req): # type: (str) -> str """Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path """ msg = "" if os.path.exists(req): msg = " It does exist." # Try to parse and check if it is a requirements file. try: with open(req, 'r') as fp: # parse first line only next(parse_requirements(fp.read())) msg += " The argument you provided " + \ "(%s) appears to be a" % (req) + \ " requirements file. If that is the" + \ " case, use the '-r' flag to install" + \ " the packages specified within it." except RequirementParseError: logger.debug("Cannot parse '%s' as requirements \ file" % (req), exc_info=True) else: msg += " File '%s' does not exist." % (req) return msg
[ "def", "deduce_helpful_msg", "(", "req", ")", ":", "# type: (str) -> str", "msg", "=", "\"\"", "if", "os", ".", "path", ".", "exists", "(", "req", ")", ":", "msg", "=", "\" It does exist.\"", "# Try to parse and check if it is a requirements file.", "try", ":", "with", "open", "(", "req", ",", "'r'", ")", "as", "fp", ":", "# parse first line only", "next", "(", "parse_requirements", "(", "fp", ".", "read", "(", ")", ")", ")", "msg", "+=", "\" The argument you provided \"", "+", "\"(%s) appears to be a\"", "%", "(", "req", ")", "+", "\" requirements file. If that is the\"", "+", "\" case, use the '-r' flag to install\"", "+", "\" the packages specified within it.\"", "except", "RequirementParseError", ":", "logger", ".", "debug", "(", "\"Cannot parse '%s' as requirements \\\n file\"", "%", "(", "req", ")", ",", "exc_info", "=", "True", ")", "else", ":", "msg", "+=", "\" File '%s' does not exist.\"", "%", "(", "req", ")", "return", "msg" ]
Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path
[ "Returns", "helpful", "msg", "in", "case", "requirements", "file", "does", "not", "exist", "or", "cannot", "be", "parsed", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/req/constructors.py#L136-L161
24,797
pypa/pipenv
pipenv/patched/notpip/_vendor/cachecontrol/caches/file_cache.py
url_to_file_path
def url_to_file_path(url, filecache): """Return the file cache path based on the URL. This does not ensure the file exists! """ key = CacheController.cache_url(url) return filecache._fn(key)
python
def url_to_file_path(url, filecache): """Return the file cache path based on the URL. This does not ensure the file exists! """ key = CacheController.cache_url(url) return filecache._fn(key)
[ "def", "url_to_file_path", "(", "url", ",", "filecache", ")", ":", "key", "=", "CacheController", ".", "cache_url", "(", "url", ")", "return", "filecache", ".", "_fn", "(", "key", ")" ]
Return the file cache path based on the URL. This does not ensure the file exists!
[ "Return", "the", "file", "cache", "path", "based", "on", "the", "URL", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/cachecontrol/caches/file_cache.py#L140-L146
24,798
pypa/pipenv
pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py
write_pid_to_pidfile
def write_pid_to_pidfile(pidfile_path): """ Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. """ open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY) open_mode = 0o644 pidfile_fd = os.open(pidfile_path, open_flags, open_mode) pidfile = os.fdopen(pidfile_fd, 'w') # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. For # example, if crond was process number 25, /var/run/crond.pid # would contain three characters: two, five, and newline. pid = os.getpid() pidfile.write("%s\n" % pid) pidfile.close()
python
def write_pid_to_pidfile(pidfile_path): """ Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. """ open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY) open_mode = 0o644 pidfile_fd = os.open(pidfile_path, open_flags, open_mode) pidfile = os.fdopen(pidfile_fd, 'w') # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. For # example, if crond was process number 25, /var/run/crond.pid # would contain three characters: two, five, and newline. pid = os.getpid() pidfile.write("%s\n" % pid) pidfile.close()
[ "def", "write_pid_to_pidfile", "(", "pidfile_path", ")", ":", "open_flags", "=", "(", "os", ".", "O_CREAT", "|", "os", ".", "O_EXCL", "|", "os", ".", "O_WRONLY", ")", "open_mode", "=", "0o644", "pidfile_fd", "=", "os", ".", "open", "(", "pidfile_path", ",", "open_flags", ",", "open_mode", ")", "pidfile", "=", "os", ".", "fdopen", "(", "pidfile_fd", ",", "'w'", ")", "# According to the FHS 2.3 section on PID files in /var/run:", "#", "# The file must consist of the process identifier in", "# ASCII-encoded decimal, followed by a newline character. For", "# example, if crond was process number 25, /var/run/crond.pid", "# would contain three characters: two, five, and newline.", "pid", "=", "os", ".", "getpid", "(", ")", "pidfile", ".", "write", "(", "\"%s\\n\"", "%", "pid", ")", "pidfile", ".", "close", "(", ")" ]
Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text.
[ "Write", "the", "PID", "in", "the", "named", "PID", "file", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py#L152-L173
24,799
pypa/pipenv
pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py
remove_existing_pidfile
def remove_existing_pidfile(pidfile_path): """ Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist. """ try: os.remove(pidfile_path) except OSError as exc: if exc.errno == errno.ENOENT: pass else: raise
python
def remove_existing_pidfile(pidfile_path): """ Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist. """ try: os.remove(pidfile_path) except OSError as exc: if exc.errno == errno.ENOENT: pass else: raise
[ "def", "remove_existing_pidfile", "(", "pidfile_path", ")", ":", "try", ":", "os", ".", "remove", "(", "pidfile_path", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "ENOENT", ":", "pass", "else", ":", "raise" ]
Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist.
[ "Remove", "the", "named", "PID", "file", "if", "it", "exists", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/lockfile/pidlockfile.py#L176-L190