language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
python-attrs__attrs
tests/test_next_gen.py
{ "start": 10302, "end": 10595 }
class ____: def test_smoke(self): """ `attrs.asdict` only changes defaults, so we just call it and compare. """ inst = C("foo", {(1,): 42}) assert attrs.asdict(inst) == _attr.asdict( inst, retain_collection_types=True )
TestAsDict
python
kubernetes-client__python
kubernetes/client/models/v1_preferred_scheduling_term.py
{ "start": 383, "end": 4742 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'preference': 'V1NodeSelectorTerm', 'weight': 'int' } attribute_map = { 'preference': 'preference', 'weight': 'weight' } def __init__(self, preference=None, weight=None, local_vars_configuration=None): # noqa: E501 """V1PreferredSchedulingTerm - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._preference = None self._weight = None self.discriminator = None self.preference = preference self.weight = weight @property def preference(self): """Gets the preference of this V1PreferredSchedulingTerm. # noqa: E501 :return: The preference of this V1PreferredSchedulingTerm. # noqa: E501 :rtype: V1NodeSelectorTerm """ return self._preference @preference.setter def preference(self, preference): """Sets the preference of this V1PreferredSchedulingTerm. :param preference: The preference of this V1PreferredSchedulingTerm. # noqa: E501 :type: V1NodeSelectorTerm """ if self.local_vars_configuration.client_side_validation and preference is None: # noqa: E501 raise ValueError("Invalid value for `preference`, must not be `None`") # noqa: E501 self._preference = preference @property def weight(self): """Gets the weight of this V1PreferredSchedulingTerm. # noqa: E501 Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100. # noqa: E501 :return: The weight of this V1PreferredSchedulingTerm. # noqa: E501 :rtype: int """ return self._weight @weight.setter def weight(self, weight): """Sets the weight of this V1PreferredSchedulingTerm. Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100. # noqa: E501 :param weight: The weight of this V1PreferredSchedulingTerm. # noqa: E501 :type: int """ if self.local_vars_configuration.client_side_validation and weight is None: # noqa: E501 raise ValueError("Invalid value for `weight`, must not be `None`") # noqa: E501 self._weight = weight def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1PreferredSchedulingTerm): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1PreferredSchedulingTerm): return True return self.to_dict() != other.to_dict()
V1PreferredSchedulingTerm
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 69626, "end": 69760 }
class ____(_TestBinaryOpsMutating, __TestCase): constructor1 = SetSubclass constructor2 = set
TestBinaryOpsMutating_Subclass_Set
python
ray-project__ray
doc/source/serve/doc_code/intel_gaudi_inference_serve.py
{ "start": 361, "end": 4425 }
class ____: def __init__(self, model_id_or_path: str): from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig from optimum.habana.transformers.modeling_utils import ( adapt_transformers_to_gaudi, ) # Tweak transformers to optimize performance adapt_transformers_to_gaudi() self.device = torch.device("hpu") self.tokenizer = AutoTokenizer.from_pretrained( model_id_or_path, use_fast=False, use_auth_token="" ) hf_config = AutoConfig.from_pretrained( model_id_or_path, torchscript=True, use_auth_token="", trust_remote_code=False, ) # Load the model in Gaudi model = AutoModelForCausalLM.from_pretrained( model_id_or_path, config=hf_config, torch_dtype=torch.float32, low_cpu_mem_usage=True, use_auth_token="", ) model = model.eval().to(self.device) from habana_frameworks.torch.hpu import wrap_in_hpu_graph # Enable hpu graph runtime self.model = wrap_in_hpu_graph(model) # Set pad token, etc. self.tokenizer.pad_token_id = self.model.generation_config.pad_token_id self.tokenizer.padding_side = "left" # Use async loop in streaming self.loop = asyncio.get_running_loop() def tokenize(self, prompt: str): """Tokenize the input and move to HPU.""" input_tokens = self.tokenizer(prompt, return_tensors="pt", padding=True) return input_tokens.input_ids.to(device=self.device) def generate(self, prompt: str, **config: Dict[str, Any]): """Take a prompt and generate a response.""" input_ids = self.tokenize(prompt) gen_tokens = self.model.generate(input_ids, **config) return self.tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)[0] async def consume_streamer_async(self, streamer): """Consume the streamer asynchronously.""" while True: try: for token in streamer: yield token break except Empty: await asyncio.sleep(0.001) def streaming_generate(self, prompt: str, streamer, **config: Dict[str, Any]): """Generate a streamed response given an input.""" input_ids = self.tokenize(prompt) self.model.generate(input_ids, streamer=streamer, **config) async def __call__(self, http_request: Request): """Handle HTTP requests.""" # Load fields from the request json_request: str = await http_request.json() text = json_request["text"] # Config used in generation config = json_request.get("config", {}) streaming_response = json_request["stream"] # Prepare prompts prompts = [] if isinstance(text, list): prompts.extend(text) else: prompts.append(text) # Process config config.setdefault("max_new_tokens", 128) # Enable HPU graph runtime config["hpu_graphs"] = True # Lazy mode should be True when using HPU graphs config["lazy_mode"] = True # Non-streaming case if not streaming_response: return self.generate(prompts, **config) # Streaming case from transformers import TextIteratorStreamer streamer = TextIteratorStreamer( self.tokenizer, skip_prompt=True, timeout=0, skip_special_tokens=True ) # Convert the streamer into a generator self.loop.run_in_executor( None, partial(self.streaming_generate, prompts, streamer, **config) ) return StreamingResponse( self.consume_streamer_async(streamer), status_code=200, media_type="text/plain", ) # Replace the model ID with path if necessary entrypoint = LlamaModel.bind("meta-llama/Llama-2-7b-chat-hf") # __model_def_end__
LlamaModel
python
pyqtgraph__pyqtgraph
pyqtgraph/opengl/items/GLImageItem.py
{ "start": 324, "end": 6623 }
class ____(GLGraphicsItem): """ **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem.GLGraphicsItem>` Displays image data as a textured quad. """ _shaderProgram = None def __init__(self, data, smooth=False, glOptions='translucent', parentItem=None): """ ============== ======================================================================================= **Arguments:** data Volume data to be rendered. *Must* be 3D numpy array (x, y, RGBA) with dtype=ubyte. (See functions.makeRGBA) smooth (bool) If True, the volume slices are rendered with linear interpolation ============== ======================================================================================= """ super().__init__() self.setGLOptions(glOptions) self.smooth = smooth self._needUpdate = False self.texture = None self.m_vbo_position = QtOpenGL.QOpenGLBuffer(QtOpenGL.QOpenGLBuffer.Type.VertexBuffer) self.setParentItem(parentItem) self.setData(data) def setData(self, data): self.data = data self._needUpdate = True self.update() def _updateTexture(self): if self.texture is None: self.texture = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture) filt = GL.GL_LINEAR if self.smooth else GL.GL_NEAREST GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, filt) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, filt) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_BORDER) GL.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_BORDER) shape = self.data.shape context = QtGui.QOpenGLContext.currentContext() if not context.isOpenGLES(): ## Test texture dimensions first GL.glTexImage2D(GL.GL_PROXY_TEXTURE_2D, 0, GL.GL_RGBA, shape[0], shape[1], 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, None) if GL.glGetTexLevelParameteriv(GL.GL_PROXY_TEXTURE_2D, 0, GL.GL_TEXTURE_WIDTH) == 0: raise Exception("OpenGL failed to create 2D texture (%dx%d); too large for this hardware." % shape[:2]) data = np.ascontiguousarray(self.data.transpose((1,0,2))) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, shape[0], shape[1], 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, data) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) x, y = shape[:2] pos = np.array([ [0, 0, 0, 0], [x, 0, 1, 0], [0, y, 0, 1], [x, y, 1, 1], ], dtype=np.float32) vbo = self.m_vbo_position if not vbo.isCreated(): vbo.create() vbo.bind() vbo.allocate(pos, pos.nbytes) vbo.release() @staticmethod def getShaderProgram(): klass = GLImageItem if klass._shaderProgram is not None: return klass._shaderProgram ctx = QtGui.QOpenGLContext.currentContext() fmt = ctx.format() if ctx.isOpenGLES(): if fmt.version() >= (3, 0): glsl_version = "#version 300 es\n" sources = SHADER_CORE else: glsl_version = "" sources = SHADER_LEGACY else: if fmt.version() >= (3, 1): glsl_version = "#version 140\n" sources = SHADER_CORE else: glsl_version = "" sources = SHADER_LEGACY compiled = [shaders.compileShader([glsl_version, v], k) for k, v in sources.items()] program = shaders.compileProgram(*compiled) GL.glBindAttribLocation(program, 0, "a_position") GL.glBindAttribLocation(program, 1, "a_texcoord") GL.glLinkProgram(program) klass._shaderProgram = program return program def paint(self): if self._needUpdate: self._updateTexture() self._needUpdate = False self.setupGLState() mat_mvp = self.mvpMatrix() mat_mvp = np.array(mat_mvp.data(), dtype=np.float32) program = self.getShaderProgram() loc_pos, loc_tex = 0, 1 self.m_vbo_position.bind() GL.glVertexAttribPointer(loc_pos, 2, GL.GL_FLOAT, False, 4*4, None) GL.glVertexAttribPointer(loc_tex, 2, GL.GL_FLOAT, False, 4*4, GL.GLvoidp(2*4)) self.m_vbo_position.release() enabled_locs = [loc_pos, loc_tex] GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture) for loc in enabled_locs: GL.glEnableVertexAttribArray(loc) with program: loc = GL.glGetUniformLocation(program, "u_mvp") GL.glUniformMatrix4fv(loc, 1, False, mat_mvp) GL.glDrawArrays(GL.GL_TRIANGLE_STRIP, 0, 4) for loc in enabled_locs: GL.glDisableVertexAttribArray(loc) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) SHADER_LEGACY = { GL.GL_VERTEX_SHADER : """ uniform mat4 u_mvp; attribute vec4 a_position; attribute vec2 a_texcoord; varying vec2 v_texcoord; void main() { gl_Position = u_mvp * a_position; v_texcoord = a_texcoord; } """, GL.GL_FRAGMENT_SHADER : """ #ifdef GL_ES precision mediump float; #endif uniform sampler2D u_texture; varying vec2 v_texcoord; void main() { gl_FragColor = texture2D(u_texture, v_texcoord); } """, } SHADER_CORE = { GL.GL_VERTEX_SHADER : """ uniform mat4 u_mvp; in vec4 a_position; in vec2 a_texcoord; out vec2 v_texcoord; void main() { gl_Position = u_mvp * a_position; v_texcoord = a_texcoord; } """, GL.GL_FRAGMENT_SHADER : """ #ifdef GL_ES precision mediump float; #endif uniform sampler2D u_texture; in vec2 v_texcoord; out vec4 fragColor; void main() { fragColor = texture(u_texture, v_texcoord); } """, }
GLImageItem
python
django__django
tests/mail/test_deprecated.py
{ "start": 2574, "end": 4008 }
class ____(SimpleTestCase): """ These undocumented features were removed without going through deprecation. In case they were being used, they now raise errors. """ def test_undocumented_mixed_subtype(self): """ Trying to use the previously undocumented, now unsupported EmailMessage.mixed_subtype causes an error. """ msg = ( "EmailMessage no longer supports" " the undocumented `mixed_subtype` attribute" ) email = EmailMessage( attachments=[EmailAttachment(None, b"GIF89a...", "image/gif")] ) email.mixed_subtype = "related" with self.assertRaisesMessage(AttributeError, msg): email.message() def test_undocumented_alternative_subtype(self): """ Trying to use the previously undocumented, now unsupported EmailMultiAlternatives.alternative_subtype causes an error. """ msg = ( "EmailMultiAlternatives no longer supports" " the undocumented `alternative_subtype` attribute" ) email = EmailMultiAlternatives( alternatives=[EmailAlternative("", "text/plain")] ) email.alternative_subtype = "multilingual" with self.assertRaisesMessage(AttributeError, msg): email.message() @ignore_warnings(category=RemovedInDjango70Warning)
UndocumentedFeatureErrorTests
python
numpy__numpy
numpy/ctypeslib/_ctypeslib.py
{ "start": 5323, "end": 6180 }
class ____(_ndptr_base): @classmethod def from_param(cls, obj): if not isinstance(obj, np.ndarray): raise TypeError("argument must be an ndarray") if cls._dtype_ is not None \ and obj.dtype != cls._dtype_: raise TypeError(f"array must have data type {cls._dtype_}") if cls._ndim_ is not None \ and obj.ndim != cls._ndim_: raise TypeError("array must have %d dimension(s)" % cls._ndim_) if cls._shape_ is not None \ and obj.shape != cls._shape_: raise TypeError(f"array must have shape {str(cls._shape_)}") if cls._flags_ is not None \ and ((obj.flags.num & cls._flags_) != cls._flags_): raise TypeError(f"array must have flags {_flags_fromnum(cls._flags_)}") return obj.ctypes
_ndptr
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink39.py
{ "start": 315, "end": 906 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink39.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_image( "E9", self.image_dir + "red.png", {"url": r"external:c:\temp\foo.xlsx"} ) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/_typing.py
{ "start": 2397, "end": 2774 }
class ____(_CoreKnownExecutionOptions, total=False): populate_existing: bool autoflush: bool synchronize_session: SynchronizeSessionArgument dml_strategy: DMLStrategyArgument is_delete_using: bool is_update_from: bool render_nulls: bool OrmExecuteOptionsParameter = Union[ _OrmKnownExecutionOptions, Mapping[str, Any] ]
_OrmKnownExecutionOptions
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/typehints.py
{ "start": 471, "end": 1243 }
class ____: CONST1: int CONST2: int = 1 CONST3: pathlib.PurePosixPath = pathlib.PurePosixPath('/a/b/c') def __init__(self, s: str, o: Any = None) -> None: pass def incr(self, a: int, b: int = 1) -> int: return a + b def decr(self, a, b=1): # type: (int, int) -> int return a - b def nothing(self): # type: () -> None pass def horse( self, a, # type: str b, # type: int ): # type: (...) -> None return @property def prop(self) -> int: return 0 @property def path(self) -> pathlib.PurePosixPath: return pathlib.PurePosixPath('/a/b/c') def tuple_args(x: tuple[int, int | str]) -> tuple[int, int]: pass
Math
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-singlestoredb/llama_index/vector_stores/singlestoredb/base.py
{ "start": 491, "end": 11430 }
class ____(BasePydanticVectorStore): """ SingleStore vector store. This vector store stores embeddings within a SingleStore database table. During query time, the index uses SingleStore to query for the top k most similar nodes. Args: table_name (str, optional): Specifies the name of the table in use. Defaults to "embeddings". content_field (str, optional): Specifies the field to store the content. Defaults to "content". metadata_field (str, optional): Specifies the field to store metadata. Defaults to "metadata". vector_field (str, optional): Specifies the field to store the vector. Defaults to "vector". Following arguments pertain to the connection pool: pool_size (int, optional): Determines the number of active connections in the pool. Defaults to 5. max_overflow (int, optional): Determines the maximum number of connections allowed beyond the pool_size. Defaults to 10. timeout (float, optional): Specifies the maximum wait time in seconds for establishing a connection. Defaults to 30. Following arguments pertain to the connection: host (str, optional): Specifies the hostname, IP address, or URL for the database connection. The default scheme is "mysql". user (str, optional): Database username. password (str, optional): Database password. port (int, optional): Database port. Defaults to 3306 for non-HTTP connections, 80 for HTTP connections, and 443 for HTTPS connections. database (str, optional): Database name. Examples: `pip install llama-index-vector-stores-singlestoredb` ```python from llama_index.vector_stores.singlestoredb import SingleStoreVectorStore import os # can set the singlestore db url in env # or pass it in as an argument to the SingleStoreVectorStore constructor os.environ["SINGLESTOREDB_URL"] = "PLACEHOLDER URL" vector_store = SingleStoreVectorStore( table_name="embeddings", content_field="content", metadata_field="metadata", vector_field="vector", timeout=30, ) ``` """ stores_text: bool = True flat_metadata: bool = True table_name: str content_field: str metadata_field: str vector_field: str pool_size: int max_overflow: int timeout: float connection_kwargs: dict connection_pool: QueuePool def __init__( self, table_name: str = "embeddings", content_field: str = "content", metadata_field: str = "metadata", vector_field: str = "vector", pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any, ) -> None: """Init params.""" super().__init__( table_name=table_name, content_field=content_field, metadata_field=metadata_field, vector_field=vector_field, pool_size=pool_size, max_overflow=max_overflow, timeout=timeout, connection_kwargs=kwargs, connection_pool=QueuePool( self._get_connection, pool_size=pool_size, max_overflow=max_overflow, timeout=timeout, ), stores_text=True, ) self._create_table() @property def client(self) -> Any: """Return SingleStoreDB client.""" return self._get_connection() @classmethod def class_name(cls) -> str: return "SingleStoreVectorStore" def _get_connection(self) -> Any: return s2.connect(**self.connection_kwargs) def _create_table(self) -> None: VALID_NAME_PATTERN = re.compile(r"^[a-zA-Z0-9_]+$") if not VALID_NAME_PATTERN.match(self.table_name): raise ValueError( f"Invalid table name: {self.table_name}. Table names can only contain alphanumeric characters and underscores." ) if not VALID_NAME_PATTERN.match(self.content_field): raise ValueError( f"Invalid content_field: {self.content_field}. Field names can only contain alphanumeric characters and underscores." ) if not VALID_NAME_PATTERN.match(self.vector_field): raise ValueError( f"Invalid vector_field: {self.vector_field}. Field names can only contain alphanumeric characters and underscores." ) if not VALID_NAME_PATTERN.match(self.metadata_field): raise ValueError( f"Invalid metadata_field: {self.metadata_field}. Field names can only contain alphanumeric characters and underscores." ) conn = self.connection_pool.connect() try: cur = conn.cursor() try: cur.execute( f"""CREATE TABLE IF NOT EXISTS {self.table_name} ({self.content_field} TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci, {self.vector_field} BLOB, {self.metadata_field} JSON);""" ) finally: cur.close() finally: conn.close() def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]: """ Add nodes to index. Args: nodes: List[BaseNode]: list of nodes with embeddings """ insert_query = ( f"INSERT INTO {self.table_name} VALUES (%s, JSON_ARRAY_PACK(%s), %s)" ) conn = self.connection_pool.connect() try: cursor = conn.cursor() try: for node in nodes: embedding = node.get_embedding() metadata = node_to_metadata_dict( node, remove_text=True, flat_metadata=self.flat_metadata ) # Use parameterized query for all data values cursor.execute( insert_query, ( node.get_content(metadata_mode=MetadataMode.NONE) or "", "[{}]".format(",".join(map(str, embedding))), json.dumps(metadata), ), ) finally: cursor.close() finally: conn.close() return [node.node_id for node in nodes] def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: """ Delete nodes using with ref_doc_id. Args: ref_doc_id (str): The doc_id of the document to delete. """ delete_query = f"DELETE FROM {self.table_name} WHERE JSON_EXTRACT_JSON({self.metadata_field}, 'ref_doc_id') = %s" conn = self.connection_pool.connect() try: cursor = conn.cursor() try: cursor.execute(delete_query, (json.dumps(ref_doc_id),)) finally: cursor.close() finally: conn.close() def query( self, query: VectorStoreQuery, filter: Optional[dict] = None, **kwargs: Any ) -> VectorStoreQueryResult: """ Query index for top k most similar nodes. Args: query (VectorStoreQuery): Contains query_embedding and similarity_top_k attributes. filter (Optional[dict]): A dictionary of metadata fields and values to filter by. Defaults to None. Returns: VectorStoreQueryResult: Contains nodes, similarities, and ids attributes. """ query_embedding = query.query_embedding similarity_top_k = query.similarity_top_k if not isinstance(similarity_top_k, int) or similarity_top_k <= 0: raise ValueError( f"similarity_top_k must be a positive integer, got {similarity_top_k}" ) conn = self.connection_pool.connect() where_clause: str = "" where_clause_values: List[Any] = [] if filter: where_clause = "WHERE " arguments = [] def build_where_clause( where_clause_values: List[Any], sub_filter: dict, prefix_args: Optional[List[str]] = None, ) -> None: prefix_args = prefix_args or [] for key in sub_filter: if isinstance(sub_filter[key], dict): build_where_clause( where_clause_values, sub_filter[key], [*prefix_args, key] ) else: arguments.append( f"JSON_EXTRACT({self.metadata_field}, {', '.join(['%s'] * (len(prefix_args) + 1))}) = %s" ) where_clause_values += [*prefix_args, key] where_clause_values.append(json.dumps(sub_filter[key])) build_where_clause(where_clause_values, filter) where_clause += " AND ".join(arguments) results: Sequence[Any] = [] if query_embedding: try: cur = conn.cursor() formatted_vector = "[{}]".format(",".join(map(str, query_embedding))) try: logger.debug("vector field: %s", formatted_vector) logger.debug("similarity_top_k: %s", similarity_top_k) query = ( f"SELECT {self.content_field}, {self.metadata_field}, " f"DOT_PRODUCT({self.vector_field}, " "JSON_ARRAY_PACK(%s)) as similarity_score " f"FROM {self.table_name} {where_clause} " "ORDER BY similarity_score DESC LIMIT %s" ) cur.execute( query, ( formatted_vector, *tuple(where_clause_values), similarity_top_k, ), ) results = cur.fetchall() finally: cur.close() finally: conn.close() nodes = [] similarities = [] ids = [] for result in results: text, metadata, similarity_score = result node = metadata_dict_to_node(metadata) node.set_content(text) nodes.append(node) similarities.append(similarity_score) ids.append(node.node_id) return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids)
SingleStoreVectorStore
python
ApeWorX__ape
tests/functional/test_plugins.py
{ "start": 10147, "end": 11093 }
class ____: def test_str(self, plugin_metadata): representation = ApePluginsRepr(plugin_metadata) actual = str(representation) expected = f""" Installed Plugins installed {ape_version.base} Third-party Plugins thirdparty {ape_version.base} """ assert actual == expected.strip() def test_str_all_types(self, plugin_metadata): representation = ApePluginsRepr(plugin_metadata, include=list(PluginType)) actual = str(representation) expected = f""" Core Plugins run Installed Plugins installed {ape_version.base} Third-party Plugins thirdparty {ape_version.base} Available Plugins available """ assert actual == expected.strip() def test_str_no_plugins(self): plugins = PluginMetadataList.from_package_names([]) representation = ApePluginsRepr(plugins) assert str(representation) == ""
TestApePluginsRepr
python
mwaskom__seaborn
seaborn/_core/scales.py
{ "start": 13123, "end": 16928 }
class ____(Scale): values: tuple | str | None = None norm: tuple | None = None def _setup( self, data: Series, prop: Property, axis: Axis | None = None, ) -> Scale: new = copy(self) if new._tick_params is None: new = new.tick() if new._label_params is None: new = new.label() forward, inverse = new._get_transform() mpl_scale = new._get_scale(str(data.name), forward, inverse) if axis is None: axis = PseudoAxis(mpl_scale) axis.update_units(data) mpl_scale.set_default_locators_and_formatters(axis) new._matplotlib_scale = mpl_scale normalize: Optional[Callable[[ArrayLike], ArrayLike]] if prop.normed: if new.norm is None: vmin, vmax = data.min(), data.max() else: vmin, vmax = new.norm vmin, vmax = map(float, axis.convert_units((vmin, vmax))) a = forward(vmin) b = forward(vmax) - forward(vmin) def normalize(x): return (x - a) / b else: normalize = vmin = vmax = None new._pipeline = [ axis.convert_units, forward, normalize, prop.get_mapping(new, data) ] def spacer(x): x = x.dropna().unique() if len(x) < 2: return np.nan return np.min(np.diff(np.sort(x))) new._spacer = spacer # TODO How to allow disabling of legend for all uses of property? # Could add a Scale parameter, or perhaps Scale.suppress()? # Are there other useful parameters that would be in Scale.legend() # besides allowing Scale.legend(False)? if prop.legend: axis.set_view_interval(vmin, vmax) locs = axis.major.locator() locs = locs[(vmin <= locs) & (locs <= vmax)] # Avoid having an offset / scientific notation in a legend # as we don't represent that anywhere so it ends up incorrect. # This could become an option (e.g. Continuous.label(offset=True)) # in which case we would need to figure out how to show it. if hasattr(axis.major.formatter, "set_useOffset"): axis.major.formatter.set_useOffset(False) if hasattr(axis.major.formatter, "set_scientific"): axis.major.formatter.set_scientific(False) labels = axis.major.formatter.format_ticks(locs) new._legend = list(locs), list(labels) return new def _get_transform(self): arg = self.trans def get_param(method, default): if arg == method: return default return float(arg[len(method):]) if arg is None: return _make_identity_transforms() elif isinstance(arg, tuple): return arg elif isinstance(arg, str): if arg == "ln": return _make_log_transforms() elif arg == "logit": base = get_param("logit", 10) return _make_logit_transforms(base) elif arg.startswith("log"): base = get_param("log", 10) return _make_log_transforms(base) elif arg.startswith("symlog"): c = get_param("symlog", 1) return _make_symlog_transforms(c) elif arg.startswith("pow"): exp = get_param("pow", 2) return _make_power_transforms(exp) elif arg == "sqrt": return _make_sqrt_transforms() else: raise ValueError(f"Unknown value provided for trans: {arg!r}") @dataclass
ContinuousBase
python
PrefectHQ__prefect
src/prefect/server/database/query_components.py
{ "start": 1369, "end": 1874 }
class ____(NamedTuple): kind: Literal["flow-run", "task-run"] id: UUID label: str state_type: StateType start_time: DateTime end_time: Optional[DateTime] parent_ids: Optional[list[UUID]] child_ids: Optional[list[UUID]] encapsulating_ids: Optional[list[UUID]] ONE_HOUR = 60 * 60 jinja_env: Environment = Environment( loader=PackageLoader("prefect.server.database", package_path="sql"), autoescape=select_autoescape(), trim_blocks=True, )
FlowRunGraphV2Node
python
realpython__materials
python-range/float_range.py
{ "start": 3036, "end": 3733 }
class ____: """Non-public iterator. Should only be initialized by FloatRange.""" start: float | int stop: float | int step: float | int _num_steps: int = field(default=0, init=False) def __iter__(self): """Initialize the iterator.""" return self def __next__(self): """Calculate the next element in the iteration.""" element = self.start + self._num_steps * self.step if any( [ self.step > 0 and element >= self.stop, self.step < 0 and element <= self.stop, ] ): raise StopIteration self._num_steps += 1 return element
_FloatRangeIterator
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 11350, "end": 11765 }
class ____: def setup_method(self): class TestSerializer(serializers.Serializer): labeled = serializers.IntegerField(label='My label') self.serializer = TestSerializer() def test_label(self): """ A field's label may be set with the `label` argument. """ fields = self.serializer.fields assert fields['labeled'].label == 'My label'
TestLabel
python
doocs__leetcode
solution/2900-2999/2931.Maximum Spending After Buying Items/Solution.py
{ "start": 0, "end": 401 }
class ____: def maxSpending(self, values: List[List[int]]) -> int: n = len(values[0]) pq = [(row[-1], i, n - 1) for i, row in enumerate(values)] heapify(pq) ans = d = 0 while pq: d += 1 v, i, j = heappop(pq) ans += v * d if j: heappush(pq, (values[i][j - 1], i, j - 1)) return ans
Solution
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/assets/registry_entry.py
{ "start": 2210, "end": 30621 }
class ____(Exception): pass # HELPERS @sentry_sdk.trace def apply_spec_to_registry_entry(registry_entry: dict, spec_cache: SpecCache, registry_name: str) -> dict: cached_spec = spec_cache.find_spec_cache_with_fallback( registry_entry["dockerRepository"], registry_entry["dockerImageTag"], registry_name ) if cached_spec is None: raise MissingCachedSpecError(f"No cached spec found for {registry_entry['dockerRepository']}:{registry_entry['dockerImageTag']}") entry_with_spec = copy.deepcopy(registry_entry) entry_with_spec["spec"] = spec_cache.download_spec(cached_spec) return entry_with_spec def calculate_migration_documentation_url(releases_or_breaking_change: dict, documentation_url: str, version: Optional[str] = None) -> str: """Calculate the migration documentation url for the connector releases. Args: metadata_releases (dict): The connector releases. Returns: str: The migration documentation url. """ base_url = f"{documentation_url}-migrations" default_migration_documentation_url = f"{base_url}#{version}" if version is not None else base_url return releases_or_breaking_change.get("migrationDocumentationUrl", None) or default_migration_documentation_url @deep_copy_params def apply_connector_releases(metadata: dict) -> Optional[pd.DataFrame]: documentation_url = metadata.get("documentationUrl") final_registry_releases = {} releases = metadata.get("releases") if releases is not None and releases.get("breakingChanges"): # apply defaults for connector releases final_registry_releases["migrationDocumentationUrl"] = calculate_migration_documentation_url( metadata["releases"], documentation_url ) # releases has a dictionary field called breakingChanges, where the key is the version and the value is the data for the breaking change # each breaking change has a migrationDocumentationUrl field that is optional, so we need to apply defaults to it breaking_changes = metadata["releases"]["breakingChanges"] if breaking_changes is not None: for version, breaking_change in breaking_changes.items(): breaking_change["migrationDocumentationUrl"] = calculate_migration_documentation_url( breaking_change, documentation_url, version ) final_registry_releases["breakingChanges"] = breaking_changes if releases is not None and releases.get("rolloutConfiguration"): final_registry_releases["rolloutConfiguration"] = metadata["releases"]["rolloutConfiguration"] return final_registry_releases @deep_copy_params def apply_overrides_from_registry(metadata_data: dict, override_registry_key: str) -> dict: """Apply the overrides from the registry to the metadata data. Args: metadata_data (dict): The metadata data field. override_registry_key (str): The key of the registry to override the metadata with. Returns: dict: The metadata data field with the overrides applied. """ override_registry = metadata_data["registryOverrides"][override_registry_key] del override_registry["enabled"] # remove any None values from the override registry override_registry = {k: v for k, v in override_registry.items() if v is not None} metadata_data.update(override_registry) return metadata_data @deep_copy_params def apply_ab_internal_defaults(metadata_data: dict) -> dict: """Apply ab_internal defaults to the metadata data field. Args: metadata_data (dict): The metadata data field. Returns: dict: The metadata data field with the ab_internal defaults applied. """ default_ab_internal_values = { "sl": 100, "ql": 100, } existing_ab_internal_values = metadata_data.get("ab_internal") or {} ab_internal_values = {**default_ab_internal_values, **existing_ab_internal_values} metadata_data["ab_internal"] = ab_internal_values return metadata_data @deep_copy_params def apply_generated_fields(metadata_data: dict, metadata_entry: LatestMetadataEntry) -> dict: """Apply generated fields to the metadata data field. Args: metadata_data (dict): The metadata data field. metadata_entry (LatestMetadataEntry): The metadata entry. Returns: dict: The metadata data field with the generated fields applied. """ generated_fields = metadata_data.get("generated") or {} # Add the source file metadata generated_fields = set_with(generated_fields, "source_file_info.metadata_etag", metadata_entry.etag, default_none_to_dict) generated_fields = set_with(generated_fields, "source_file_info.metadata_file_path", metadata_entry.file_path, default_none_to_dict) generated_fields = set_with(generated_fields, "source_file_info.metadata_bucket_name", metadata_entry.bucket_name, default_none_to_dict) generated_fields = set_with( generated_fields, "source_file_info.metadata_last_modified", metadata_entry.last_modified, default_none_to_dict ) # Add the registry entry generation timestamp generated_fields = set_with( generated_fields, "source_file_info.registry_entry_generated_at", datetime.now().isoformat(), default_none_to_dict ) return generated_fields @deep_copy_params def apply_package_info_fields(metadata_data: dict, metadata_entry: LatestMetadataEntry) -> dict: """Apply package info fields to the metadata data field. Args: metadata_data (dict): The metadata data field. Returns: dict: The metadata data field with the package info fields applied. """ package_info_fields = metadata_data.get("packageInfo") or {} package_info_fields = set_with(package_info_fields, "cdk_version", get_cdk_version(metadata_entry), default_none_to_dict) return package_info_fields @deep_copy_params def apply_language_field(metadata_data: dict) -> dict: """Transform the language tag into a top-level field, if it is not already present. Args: metadata_data (dict): The metadata data field. Returns: dict: The metadata data field with the language field applied. """ if metadata_data.get("language"): return metadata_data tags = metadata_data.get("tags", []) languages = [tag.replace("language:", "") for tag in tags if tag.startswith("language:")] metadata_data["language"] = languages[0] if languages else None return metadata_data @deep_copy_params @sentry_sdk.trace def metadata_to_registry_entry(metadata_entry: LatestMetadataEntry, override_registry_key: str) -> dict: """Convert the metadata definition to a registry entry. Args: metadata_entry (LatestMetadataEntry): The metadata definition. override_registry_key (str): The key of the registry to override the metadata with. Returns: dict: The registry equivalent of the metadata definition. """ metadata_definition = metadata_entry.metadata_definition.dict() metadata_data = metadata_definition["data"] connector_type = metadata_data["connectorType"] # apply overrides from the registry overridden_metadata_data = apply_overrides_from_registry(metadata_data, override_registry_key) # remove fields that are not needed in the registry del overridden_metadata_data["registryOverrides"] del overridden_metadata_data["connectorType"] # rename field connectorSubtype to sourceType connector_subtype = overridden_metadata_data.get("connectorSubtype") if connector_subtype: overridden_metadata_data["sourceType"] = overridden_metadata_data["connectorSubtype"] del overridden_metadata_data["connectorSubtype"] # rename definitionId field to sourceDefinitionId or destinationDefinitionId id_field = "sourceDefinitionId" if connector_type == "source" else "destinationDefinitionId" overridden_metadata_data[id_field] = overridden_metadata_data["definitionId"] del overridden_metadata_data["definitionId"] # add in useless fields that are currently required for porting to the actor definition spec overridden_metadata_data["tombstone"] = False overridden_metadata_data["custom"] = False overridden_metadata_data["public"] = True # Add generated fields for source file metadata and git overridden_metadata_data["generated"] = apply_generated_fields(overridden_metadata_data, metadata_entry) # Add Dependency information overridden_metadata_data["packageInfo"] = apply_package_info_fields(overridden_metadata_data, metadata_entry) # Add language field overridden_metadata_data = apply_language_field(overridden_metadata_data) # if there is no supportLevel, set it to "community" if not overridden_metadata_data.get("supportLevel"): overridden_metadata_data["supportLevel"] = "community" # apply ab_internal defaults overridden_metadata_data = apply_ab_internal_defaults(overridden_metadata_data) # apply generated fields overridden_metadata_data["iconUrl"] = metadata_entry.icon_url overridden_metadata_data["releases"] = apply_connector_releases(overridden_metadata_data) return overridden_metadata_data def apply_entry_schema_migrations(registry_entry: dict) -> dict: """Apply schema migrations to the registry entry. Args: registry_entry (dict): The registry entry. Returns: dict: The registry entry with the schema migrations applied. """ # Remove the isReleaseCandidate field from the registry entry if registry_entry.get("releases", {}).get("isReleaseCandidate") is not None: registry_entry["releases"].pop("isReleaseCandidate") # Remove the releases field if it is empty if registry_entry.get("releases") == dict(): registry_entry.pop("releases") return registry_entry @sentry_sdk.trace def read_registry_entry_blob(registry_entry_blob: storage.Blob) -> TaggedRegistryEntry: json_string = registry_entry_blob.download_as_string().decode("utf-8") registry_entry_dict = json.loads(json_string) connector_type, ConnectorModel = get_connector_type_from_registry_entry(registry_entry_dict) registry_entry_dict = apply_entry_schema_migrations(registry_entry_dict) registry_entry = ConnectorModel.parse_obj(registry_entry_dict) return connector_type, registry_entry def get_connector_type_from_registry_entry(registry_entry: dict) -> TaggedRegistryEntry: if registry_entry.get(ConnectorTypePrimaryKey.SOURCE.value): return (ConnectorTypes.SOURCE, ConnectorRegistrySourceDefinition) elif registry_entry.get(ConnectorTypePrimaryKey.DESTINATION.value): return (ConnectorTypes.DESTINATION, ConnectorRegistryDestinationDefinition) else: raise Exception("Could not determine connector type from registry entry") def _get_directory_write_path(metadata_path: Optional[str], registry_name: str) -> str: """Get the write path for the registry entry, assuming the metadata entry is the latest version.""" if metadata_path is None: raise Exception(f"Metadata entry {metadata_entry} does not have a file path") metadata_folder = os.path.dirname(metadata_path) return os.path.join(metadata_folder, registry_name) def get_registry_entry_write_path( registry_entry: Optional[PolymorphicRegistryEntry], metadata_entry: LatestMetadataEntry, registry_name: str ) -> str: """Get the write path for the registry entry.""" if metadata_entry.is_latest_version_path or metadata_entry.is_release_candidate_version_path: # if the metadata entry is the latest or RC version, write the registry entry to the same path as the metadata entry return _get_directory_write_path(metadata_entry.file_path, registry_name) else: if registry_entry is None: raise Exception(f"Could not determine write path for registry entry {registry_entry} because it is None") # if the metadata entry is not the latest version, write the registry entry to its own version specific path # this is handle the case when a dockerImageTag is overridden return HACKS.construct_registry_entry_write_path(registry_entry, registry_name) @sentry_sdk.trace def persist_registry_entry_to_json( registry_entry: PolymorphicRegistryEntry, registry_name: str, metadata_entry: LatestMetadataEntry, registry_directory_manager: GCSFileManager, ) -> GCSFileHandle: """Persist the registry_entry to a json file on GCS bucket Args: registry_entry (ConnectorRegistryV0): The registry_entry. registry_name (str): The name of the registry_entry. One of "cloud" or "oss". metadata_entry (LatestMetadataEntry): The related Metadata Entry. registry_directory_manager (GCSFileHandle): The registry_entry directory manager. Returns: GCSFileHandle: The registry_entry directory manager. """ registry_entry_write_path = get_registry_entry_write_path(registry_entry, metadata_entry, registry_name) registry_entry_json = registry_entry.json(exclude_none=True) file_handle = registry_directory_manager.write_data(registry_entry_json.encode("utf-8"), ext="json", key=registry_entry_write_path) return file_handle def generate_registry_entry( metadata_entry: LatestMetadataEntry, spec_cache: SpecCache, registry_name: str, ) -> PolymorphicRegistryEntry: """Generate a registry entry given a metadata entry. Enriches the metadata entry with spec and release candidate information. Args: metadata_entry (LatestMetadataEntry): The metadata entry. spec_cache (SpecCache): The spec cache. registry_name (str): The name of the registry_entry. One of "cloud" or "oss". Returns: PolymorphicRegistryEntry: The registry entry (could be a source or destination entry). """ raw_entry_dict = metadata_to_registry_entry(metadata_entry, registry_name) registry_entry_with_spec = apply_spec_to_registry_entry(raw_entry_dict, spec_cache, registry_name) _, ConnectorModel = get_connector_type_from_registry_entry(registry_entry_with_spec) return ConnectorModel.parse_obj(registry_entry_with_spec) @sentry_sdk.trace def generate_and_persist_registry_entry( metadata_entry: LatestMetadataEntry, spec_cache: SpecCache, metadata_directory_manager: GCSFileManager, registry_name: str, ) -> str: """Generate the selected registry from the metadata files, and persist it to GCS. Args: metadata_entry (List[LatestMetadataEntry]): The metadata entry. spec_cache (SpecCache): The spec cache. metadata_directory_manager (GCSFileManager): The metadata directory manager. registry_name (str): The name of the registry_entry. One of "cloud" or "oss". Returns: str: The public url of the registry entry. """ registry_model = generate_registry_entry(metadata_entry, spec_cache, registry_name) file_handle = persist_registry_entry_to_json(registry_model, registry_name, metadata_entry, metadata_directory_manager) return file_handle.public_url def get_registry_status_lists(registry_entry: LatestMetadataEntry) -> Tuple[List[str], List[str]]: """Get the enabled registries for the given metadata entry. Args: registry_entry (LatestMetadataEntry): The metadata entry. Returns: Tuple[List[str], List[str]]: The enabled and disabled registries. """ metadata_data_dict = registry_entry.metadata_definition.dict() # get data.registryOverrides fiield, handling the case where it is not present or none registries_field = get(metadata_data_dict, "data.registryOverrides") or {} # registries is a dict of registry_name -> {enabled: bool} all_enabled_registries = [ registry_name for registry_name, registry_data in registries_field.items() if registry_data and registry_data.get("enabled") ] valid_enabled_registries = [registry_name for registry_name in all_enabled_registries if registry_name in VALID_REGISTRIES] valid_disabled_registries = [registry_name for registry_name in VALID_REGISTRIES if registry_name not in all_enabled_registries] return valid_enabled_registries, valid_disabled_registries def delete_registry_entry(registry_name, metadata_entry: LatestMetadataEntry, metadata_directory_manager: GCSFileManager) -> str: """Delete the given registry entry from GCS. Args: metadata_entry (LatestMetadataEntry): The registry entry. metadata_directory_manager (GCSFileManager): The metadata directory manager. """ registry_entry_write_path = get_registry_entry_write_path(None, metadata_entry, registry_name) file_handle = metadata_directory_manager.delete_by_key(key=registry_entry_write_path, ext="json") return file_handle.public_url if file_handle else None @sentry_sdk.trace def safe_parse_metadata_definition(file_name: str, metadata_dict: dict) -> Optional[MetadataDefinition]: """ Safely parse the metadata definition from the given metadata entry. Handles the case where the metadata definition is invalid for in old versions of the metadata. """ try: return MetadataDefinition.parse_obj(metadata_dict) except ValidationError as e: # only raise the error if "latest" is in the path if "latest" in file_name: raise e else: print(f"WARNING: Could not parse metadata definition for {file_name}. Error: {e}") return None def safe_get_slack_user_identifier(airbyte_slack_users: pd.DataFrame, metadata_dict: Union[dict, BaseModel]) -> Optional[str]: """ Safely get the slack user identifier from the given git info in the metadata file. """ if isinstance(metadata_dict, BaseModel): metadata_dict = to_json_sanitized_dict(metadata_dict) # if the slack users is empty or none, return none if airbyte_slack_users is None or airbyte_slack_users.empty: return None commit_author = get(metadata_dict, "data.generated.git.commit_author") commit_author_email = get(metadata_dict, "data.generated.git.commit_author_email") # if the commit author email is not present, return author name or none if not commit_author_email: return commit_author # if the commit author email is present, try to find the user in the slack users dataframe # if the user is not found, return the author name or none slack_user = airbyte_slack_users[airbyte_slack_users["email"] == commit_author_email] if slack_user.empty: slack_user = airbyte_slack_users[airbyte_slack_users["real_name"] == commit_author] if slack_user.empty: return commit_author # if the user is found, return the slack real_name and id e.g. "John Doe (U12345678)" slack_id = slack_user["id"].iloc[0] slack_real_name = slack_user["real_name"].iloc[0] return f"{slack_real_name} (<@{slack_id}>)" def safe_get_commit_sha(metadata_dict: Union[dict, BaseModel]) -> Optional[str]: """ Safely get the git commit sha from the given git info in the metadata file. """ if isinstance(metadata_dict, BaseModel): metadata_dict = to_json_sanitized_dict(metadata_dict) # if the git commit sha is not present, return none commit_sha = get(metadata_dict, "data.generated.git.commit_sha") if not commit_sha: return None # if the git commit sha is present, return the commit sha return commit_sha # ASSETS @asset( required_resource_keys={"slack", "all_metadata_file_blobs"}, group_name=GROUP_NAME, partitions_def=metadata_partitions_def, output_required=False, auto_materialize_policy=AutoMaterializePolicy.eager(max_materializations_per_minute=MAX_METADATA_PARTITION_RUN_REQUEST), ) @sentry.instrument_asset_op def metadata_entry(context: OpExecutionContext) -> Output[Optional[LatestMetadataEntry]]: """Parse and compute the LatestMetadataEntry for the given metadata file.""" etag = context.partition_key context.log.info(f"Processing metadata file with etag {etag}") all_metadata_file_blobs = context.resources.all_metadata_file_blobs # find the blob with the matching etag matching_blob = next((blob for blob in all_metadata_file_blobs if blob.etag == etag), None) if not matching_blob: raise Exception(f"Could not find blob with etag {etag}") airbyte_slack_users = HACKS.get_airbyte_slack_users_from_graph(context) metadata_dict = yaml_blob_to_dict(matching_blob) user_identifier = safe_get_slack_user_identifier(airbyte_slack_users, metadata_dict) commit_sha = safe_get_commit_sha(metadata_dict) metadata_file_path = matching_blob.name PublishConnectorLifecycle.log( context, PublishConnectorLifecycleStage.METADATA_VALIDATION, StageStatus.IN_PROGRESS, f"Found metadata file with path {metadata_file_path} for etag {etag}", user_identifier=user_identifier, commit_sha=commit_sha, ) # read the matching_blob into a metadata definition metadata_def = safe_parse_metadata_definition(matching_blob.name, metadata_dict) dagster_metadata = { "bucket_name": matching_blob.bucket.name, "file_path": metadata_file_path, "partition_key": etag, "invalid_metadata": metadata_def is None, } # return only if the metadata definition is valid if not metadata_def: PublishConnectorLifecycle.log( context, PublishConnectorLifecycleStage.METADATA_VALIDATION, StageStatus.FAILED, f"Could not parse metadata definition for {metadata_file_path}, dont panic, this can be expected for old metadata files", user_identifier=user_identifier, commit_sha=commit_sha, ) return Output(value=None, metadata=dagster_metadata) icon_file_path = metadata_file_path.replace(METADATA_FILE_NAME, ICON_FILE_NAME) icon_blob = matching_blob.bucket.blob(icon_file_path) icon_url = ( get_public_url_for_gcs_file(icon_blob.bucket.name, icon_blob.name, os.getenv("METADATA_CDN_BASE_URL")) if icon_blob.exists() else None ) metadata_entry = LatestMetadataEntry( metadata_definition=metadata_def, icon_url=icon_url, bucket_name=matching_blob.bucket.name, file_path=metadata_file_path, etag=etag, last_modified=matching_blob.time_created.isoformat(), ) PublishConnectorLifecycle.log( context, PublishConnectorLifecycleStage.METADATA_VALIDATION, StageStatus.SUCCESS, f"Successfully parsed metadata definition for {metadata_file_path}", user_identifier=user_identifier, commit_sha=commit_sha, ) return Output(value=metadata_entry, metadata=dagster_metadata) @asset( required_resource_keys={"slack", "root_metadata_directory_manager"}, group_name=GROUP_NAME, partitions_def=metadata_partitions_def, auto_materialize_policy=AutoMaterializePolicy.eager(max_materializations_per_minute=MAX_METADATA_PARTITION_RUN_REQUEST), ) @sentry.instrument_asset_op def registry_entry( context: OpExecutionContext, metadata_entry: Optional[LatestMetadataEntry], ) -> Output[Optional[dict]]: """ Generate the registry entry files from the given metadata file, and persist it to GCS. """ if not metadata_entry: # if the metadata entry is invalid, return an empty dict return Output(metadata={"empty_metadata": True}, value=None) airbyte_slack_users = HACKS.get_airbyte_slack_users_from_graph(context) user_identifier = safe_get_slack_user_identifier(airbyte_slack_users, metadata_entry.metadata_definition) commit_sha = safe_get_commit_sha(metadata_entry.metadata_definition) PublishConnectorLifecycle.log( context, PublishConnectorLifecycleStage.REGISTRY_ENTRY_GENERATION, StageStatus.IN_PROGRESS, f"Generating registry entry for {metadata_entry.file_path}", user_identifier=user_identifier, commit_sha=commit_sha, ) spec_cache = SpecCache() root_metadata_directory_manager = context.resources.root_metadata_directory_manager enabled_registries, disabled_registries = get_registry_status_lists(metadata_entry) persisted_registry_entries = { registry_name: generate_and_persist_registry_entry( metadata_entry, spec_cache, root_metadata_directory_manager, registry_name, ) for registry_name in enabled_registries } # Only delete the registry entry if it is the latest version # This is to preserve any registry specific overrides even if they were removed deleted_registry_entries = {} if metadata_entry.is_latest_version_path: context.log.debug(f"Deleting previous registry entries enabled {metadata_entry.file_path}") deleted_registry_entries = { registry_name: delete_registry_entry(registry_name, metadata_entry, root_metadata_directory_manager) for registry_name in disabled_registries } dagster_metadata_persist = { f"create_{registry_name}": MetadataValue.url(registry_url) for registry_name, registry_url in persisted_registry_entries.items() } dagster_metadata_delete = { f"delete_{registry_name}": MetadataValue.url(registry_url) for registry_name, registry_url in deleted_registry_entries.items() } dagster_metadata = { **dagster_metadata_persist, **dagster_metadata_delete, } # Log the registry entries that were created for registry_name, registry_url in persisted_registry_entries.items(): PublishConnectorLifecycle.log( context, PublishConnectorLifecycleStage.REGISTRY_ENTRY_GENERATION, StageStatus.SUCCESS, f"Successfully generated {registry_name} registry entry for {metadata_entry.file_path} at {registry_url}.\n\n*This new Connector will be available for use in the platform on the next release (1-3 min)*", user_identifier=user_identifier, commit_sha=commit_sha, ) # Log the registry entries that were deleted for registry_name, registry_url in deleted_registry_entries.items(): PublishConnectorLifecycle.log( context, PublishConnectorLifecycleStage.REGISTRY_ENTRY_GENERATION, StageStatus.SUCCESS, f"Successfully deleted {registry_name} registry entry for {metadata_entry.file_path}", user_identifier=user_identifier, commit_sha=commit_sha, ) return Output(metadata=dagster_metadata, value=persisted_registry_entries) def get_registry_entries(blob_resource) -> Output[List]: registry_entries = [] for blob in blob_resource: _, registry_entry = read_registry_entry_blob(blob) registry_entries.append(registry_entry) return Output(registry_entries) @asset(required_resource_keys={"latest_cloud_registry_entries_file_blobs"}, group_name=GROUP_NAME) @sentry.instrument_asset_op def latest_cloud_registry_entries(context: OpExecutionContext) -> Output[List]: return get_registry_entries(context.resources.latest_cloud_registry_entries_file_blobs) @asset(required_resource_keys={"latest_oss_registry_entries_file_blobs"}, group_name=GROUP_NAME) @sentry.instrument_asset_op def latest_oss_registry_entries(context: OpExecutionContext) -> Output[List]: return get_registry_entries(context.resources.latest_oss_registry_entries_file_blobs) @asset(required_resource_keys={"release_candidate_cloud_registry_entries_file_blobs"}, group_name=GROUP_NAME) @sentry.instrument_asset_op def release_candidate_cloud_registry_entries(context: OpExecutionContext) -> Output[List]: return get_registry_entries(context.resources.release_candidate_cloud_registry_entries_file_blobs) @asset(required_resource_keys={"release_candidate_oss_registry_entries_file_blobs"}, group_name=GROUP_NAME) @sentry.instrument_asset_op def release_candidate_oss_registry_entries(context: OpExecutionContext) -> Output[List]: return get_registry_entries(context.resources.release_candidate_oss_registry_entries_file_blobs)
MissingCachedSpecError
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/utils/task_log_fetcher.py
{ "start": 1187, "end": 5364 }
class ____(Thread): """Fetch Cloudwatch log events with specific interval and send the log events to the logger.info.""" def __init__( self, *, log_group: str, log_stream_name: str, fetch_interval: timedelta, logger: Logger, aws_conn_id: str | None = "aws_default", region_name: str | None = None, ): super().__init__() self._event = Event() self.fetch_interval = fetch_interval self.logger = logger self.log_group = log_group self.log_stream_name = log_stream_name self.hook = AwsLogsHook(aws_conn_id=aws_conn_id, region_name=region_name) def run(self) -> None: continuation_token = AwsLogsHook.ContinuationToken() while not self.is_stopped(): time.sleep(self.fetch_interval.total_seconds()) log_events = self._get_log_events(continuation_token) prev_timestamp_event = None for log_event in log_events: current_timestamp_event = datetime.fromtimestamp( log_event["timestamp"] / 1000.0, tz=timezone.utc ) if current_timestamp_event == prev_timestamp_event: # When multiple events have the same timestamp, somehow, only one event is logged # As a consequence, some logs are missed in the log group (in case they have the same # timestamp) # When a slight delay is added before logging the event, that solves the issue # See https://github.com/apache/airflow/issues/40875 time.sleep(0.001) self.logger.info(self.event_to_str(log_event)) prev_timestamp_event = current_timestamp_event def _get_log_events(self, skip_token: AwsLogsHook.ContinuationToken | None = None) -> Generator: if skip_token is None: skip_token = AwsLogsHook.ContinuationToken() try: yield from self.hook.get_log_events( self.log_group, self.log_stream_name, continuation_token=skip_token ) except ClientError as error: if error.response["Error"]["Code"] != "ResourceNotFoundException": self.logger.warning("Error on retrieving Cloudwatch log events", error) else: self.logger.info( "Cannot find log stream yet, it can take a couple of seconds to show up. " "If this error persists, check that the log group and stream are correct: " "group: %s\tstream: %s", self.log_group, self.log_stream_name, ) yield from () except ConnectionClosedError as error: self.logger.warning("ConnectionClosedError on retrieving Cloudwatch log events", error) yield from () @staticmethod def event_to_str(event: dict) -> str: event_dt = datetime.fromtimestamp(event["timestamp"] / 1000.0, tz=timezone.utc) formatted_event_dt = event_dt.strftime("%Y-%m-%d %H:%M:%S,%f")[:-3] message = event["message"] return f"[{formatted_event_dt}] {message}" def get_last_log_messages(self, number_messages) -> list: """ Get the last logs messages in one single request. NOTE: some restrictions apply: - if logs are too old, the response will be empty - the max number of messages we can retrieve is constrained by cloudwatch limits (10,000). """ response = self.hook.conn.get_log_events( logGroupName=self.log_group, logStreamName=self.log_stream_name, startFromHead=False, limit=number_messages, ) return [log["message"] for log in response["events"]] def get_last_log_message(self) -> str | None: try: return self.get_last_log_messages(1)[0] except IndexError: return None def is_stopped(self) -> bool: return self._event.is_set() def stop(self): self._event.set()
AwsTaskLogFetcher
python
getsentry__sentry
src/sentry/monitors/endpoints/base_monitor_environment_details.py
{ "start": 436, "end": 2678 }
class ____(BaseEndpointMixin): def update_monitor_environment( self, request: Request, project, monitor, monitor_environment ) -> Response: """ Update a monitor environment. """ # Only support muting/unmuting monitor environments is_muted = request.data.get("isMuted") if type(is_muted) is bool: monitor_environment.update(is_muted=is_muted) self.create_audit_entry( request=request, organization=project.organization, target_object=monitor_environment.id, event=audit_log.get_event_id("MONITOR_ENVIRONMENT_EDIT"), data=monitor_environment.get_audit_log_data(), ) return self.respond(serialize(monitor, request.user)) def delete_monitor_environment( self, request: Request, project, monitor, monitor_environment ) -> Response: """ Delete a monitor environment. """ active_monitor_environment = ( MonitorEnvironment.objects.filter(id=monitor_environment.id) .exclude( monitor__status__in=[ ObjectStatus.PENDING_DELETION, ObjectStatus.DELETION_IN_PROGRESS, ] ) .exclude( status__in=[ MonitorStatus.PENDING_DELETION, MonitorStatus.DELETION_IN_PROGRESS, ] ) .first() ) if not active_monitor_environment or not active_monitor_environment.update( status=MonitorStatus.PENDING_DELETION ): return self.respond(status=404) schedule = RegionScheduledDeletion.schedule( active_monitor_environment, days=0, actor=request.user ) self.create_audit_entry( request=request, organization=project.organization, target_object=active_monitor_environment.id, event=audit_log.get_event_id("MONITOR_ENVIRONMENT_EDIT"), data=active_monitor_environment.get_audit_log_data(), transaction_id=schedule.guid, ) return self.respond(status=202)
MonitorEnvironmentDetailsMixin
python
jazzband__django-oauth-toolkit
tests/test_scopes.py
{ "start": 952, "end": 1148 }
class ____(ScopedProtectedResourceView): required_scopes = ["scope1", "scope2"] def get(self, request, *args, **kwargs): return "This is a protected resource"
MultiScopeResourceView
python
spyder-ide__spyder
spyder/api/asyncdispatcher.py
{ "start": 17447, "end": 17655 }
class ____(QEvent): """Event to execute a callback in the main Qt loop.""" def __init__(self, func: typing.Callable): super().__init__(QEvent.Type.User) self.func = func
_QCallbackEvent
python
huggingface__transformers
src/transformers/models/table_transformer/modeling_table_transformer.py
{ "start": 15435, "end": 17140 }
class ____(nn.Module): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, embedding_dim=256): super().__init__() self.row_embeddings = nn.Embedding(50, embedding_dim) self.column_embeddings = nn.Embedding(50, embedding_dim) def forward(self, pixel_values, pixel_mask=None): height, width = pixel_values.shape[-2:] width_values = torch.arange(width, device=pixel_values.device) height_values = torch.arange(height, device=pixel_values.device) x_emb = self.column_embeddings(width_values) y_emb = self.row_embeddings(height_values) pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1) pos = pos.permute(2, 0, 1) pos = pos.unsqueeze(0) pos = pos.repeat(pixel_values.shape[0], 1, 1, 1) return pos # Copied from transformers.models.detr.modeling_detr.build_position_encoding with Detr->TableTransformer def build_position_encoding(config): n_steps = config.d_model // 2 if config.position_embedding_type == "sine": # TODO find a better way of exposing other arguments position_embedding = TableTransformerSinePositionEmbedding(n_steps, normalize=True) elif config.position_embedding_type == "learned": position_embedding = TableTransformerLearnedPositionEmbedding(n_steps) else: raise ValueError(f"Not supported {config.position_embedding_type}") return position_embedding # Copied from transformers.models.detr.modeling_detr.DetrAttention with DETR->TABLE_TRANSFORMER,Detr->TableTransformer
TableTransformerLearnedPositionEmbedding
python
getsentry__sentry
src/sentry/api/endpoints/relay/__init__.py
{ "start": 41, "end": 925 }
class ____(serializers.Serializer): relay_id = serializers.RegexField( r"^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$", required=True ) from .details import RelayDetailsEndpoint from .health_check import RelayHealthCheck from .index import RelayIndexEndpoint from .project_configs import RelayProjectConfigsEndpoint from .project_ids import RelayProjectIdsEndpoint from .public_keys import RelayPublicKeysEndpoint from .register_challenge import RelayRegisterChallengeEndpoint from .register_response import RelayRegisterResponseEndpoint __all__ = ( "RelayDetailsEndpoint", "RelayHealthCheck", "RelayIdSerializer", "RelayIndexEndpoint", "RelayProjectConfigsEndpoint", "RelayProjectIdsEndpoint", "RelayPublicKeysEndpoint", "RelayRegisterChallengeEndpoint", "RelayRegisterResponseEndpoint", )
RelayIdSerializer
python
apache__airflow
providers/elasticsearch/src/airflow/providers/elasticsearch/hooks/elasticsearch.py
{ "start": 3440, "end": 4678 }
class ____: """wrapper class for elasticsearch.Elasticsearch.""" def __init__( self, host: str = "localhost", port: int = 9200, user: str | None = None, password: str | None = None, scheme: str = "http", **kwargs: Any, ): self.host = host self.port = port self.user = user self.password = password self.scheme = scheme self.kwargs = deepcopy(kwargs) kwargs.pop("fetch_size", None) kwargs.pop("field_multi_value_leniency", None) netloc = f"{host}:{port}" self.url = parse.urlunparse((scheme, netloc, "/", None, None, None)) if user and password: self.es = Elasticsearch(self.url, http_auth=(user, password), **kwargs) else: self.es = Elasticsearch(self.url, **kwargs) def cursor(self) -> ElasticsearchSQLCursor: return ElasticsearchSQLCursor(self.es, **self.kwargs) def close(self): self.es.close() def commit(self): pass def execute_sql( self, query: str, params: Iterable | Mapping[str, Any] | None = None ) -> ObjectApiResponse: return self.cursor().execute(query, params)
ESConnection
python
mlflow__mlflow
mlflow/types/llm.py
{ "start": 6526, "end": 8169 }
class ____(_BaseDataclass): """ A message in a chat request or response. Args: role (str): The role of the entity that sent the message (e.g. ``"user"``, ``"system"``, ``"assistant"``, ``"tool"``). content (str): The content of the message. **Optional** Can be ``None`` if refusal or tool_calls are provided. refusal (str): The refusal message content. **Optional** Supplied if a refusal response is provided. name (str): The name of the entity that sent the message. **Optional**. tool_calls (List[:py:class:`ToolCall`]): A list of tool calls made by the model. **Optional** defaults to ``None`` tool_call_id (str): The ID of the tool call that this message is a response to. **Optional** defaults to ``None`` """ role: str content: str | None = None refusal: str | None = None name: str | None = None tool_calls: list[ToolCall] | None = None tool_call_id: str | None = None def __post_init__(self): self._validate_field("role", str, True) if self.refusal: self._validate_field("refusal", str, True) if self.content: raise ValueError("Both `content` and `refusal` cannot be set") elif self.tool_calls: self._validate_field("content", str, False) else: self._validate_field("content", str, True) self._validate_field("name", str, False) self._convert_dataclass_list("tool_calls", ToolCall, False) self._validate_field("tool_call_id", str, False) @dataclass
ChatMessage
python
walkccc__LeetCode
solutions/1260. Shift 2D Grid/1260.py
{ "start": 0, "end": 365 }
class ____: def shiftGrid(self, grid: list[list[int]], k: int) -> list[list[int]]: m = len(grid) n = len(grid[0]) ans = [[0] * n for _ in range(m)] k %= m * n for i in range(m): for j in range(n): index = (i * n + j + k) % (m * n) x = index // n y = index % n ans[x][y] = grid[i][j] return ans
Solution
python
numpy__numpy
tools/swig/test/testSuperTensor.py
{ "start": 12356, "end": 12673 }
class ____(SuperTensorTestCase): def __init__(self, methodName="runTest"): SuperTensorTestCase.__init__(self, methodName) self.typeStr = "uchar" self.typeCode = "B" #self.result = int(self.result) ######################################################################
ucharTestCase
python
apache__airflow
airflow-core/src/airflow/executors/workloads.py
{ "start": 4603, "end": 5659 }
class ____(BaseDagBundleWorkload): """Execute the given Callback.""" callback: Callback type: Literal["ExecuteCallback"] = Field(init=False, default="ExecuteCallback") @classmethod def make( cls, callback: CallbackModel, dag_run: DagRun, dag_rel_path: Path | None = None, generator: JWTGenerator | None = None, bundle_info: BundleInfo | None = None, ) -> ExecuteCallback: if not bundle_info: bundle_info = BundleInfo( name=dag_run.dag_model.bundle_name, version=dag_run.bundle_version, ) fname = f"executor_callbacks/{callback.id}" # TODO: better log file template return cls( callback=Callback.model_validate(callback, from_attributes=True), dag_rel_path=dag_rel_path or Path(dag_run.dag_model.relative_fileloc or ""), token=cls.generate_token(str(callback.id), generator), log_path=fname, bundle_info=bundle_info, )
ExecuteCallback
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_legacy_tests.py
{ "start": 15294, "end": 19813 }
class ____(TestCase): class Schema: repo_url = c.URL() repo_name = c.RepoName('repo_url') edit_uri_template = c.EditURITemplate('edit_uri') edit_uri = c.EditURI('repo_url') def test_repo_name_github(self): conf = self.get_config( self.Schema, {'repo_url': "https://github.com/mkdocs/mkdocs"}, ) self.assertEqual(conf['repo_name'], "GitHub") def test_repo_name_bitbucket(self): conf = self.get_config( self.Schema, {'repo_url': "https://bitbucket.org/gutworth/six/"}, ) self.assertEqual(conf['repo_name'], "Bitbucket") def test_repo_name_gitlab(self): conf = self.get_config( self.Schema, {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"}, ) self.assertEqual(conf['repo_name'], "GitLab") def test_repo_name_custom(self): conf = self.get_config( self.Schema, {'repo_url': "https://launchpad.net/python-tuskarclient"}, ) self.assertEqual(conf['repo_name'], "Launchpad") def test_edit_uri_github(self): conf = self.get_config( self.Schema, {'repo_url': "https://github.com/mkdocs/mkdocs"}, ) self.assertEqual(conf['edit_uri'], 'edit/master/docs/') self.assertEqual(conf['repo_url'], "https://github.com/mkdocs/mkdocs") def test_edit_uri_bitbucket(self): conf = self.get_config( self.Schema, {'repo_url': "https://bitbucket.org/gutworth/six/"}, ) self.assertEqual(conf['edit_uri'], 'src/default/docs/') self.assertEqual(conf['repo_url'], "https://bitbucket.org/gutworth/six/") def test_edit_uri_gitlab(self): conf = self.get_config( self.Schema, {'repo_url': "https://gitlab.com/gitlab-org/gitlab-ce/"}, ) self.assertEqual(conf['edit_uri'], 'edit/master/docs/') def test_edit_uri_custom(self): conf = self.get_config( self.Schema, {'repo_url': "https://launchpad.net/python-tuskarclient"}, ) self.assertEqual(conf['edit_uri'], None) self.assertEqual(conf['repo_url'], "https://launchpad.net/python-tuskarclient") def test_repo_name_custom_and_empty_edit_uri(self): conf = self.get_config( self.Schema, {'repo_url': "https://github.com/mkdocs/mkdocs", 'repo_name': 'mkdocs'}, ) self.assertEqual(conf['edit_uri'], 'edit/master/docs/') def test_edit_uri_template_ok(self): conf = self.get_config( self.Schema, { 'repo_url': "https://github.com/mkdocs/mkdocs", 'edit_uri_template': 'edit/foo/docs/{path}', }, ) self.assertEqual(conf['edit_uri_template'], 'edit/foo/docs/{path}') def test_edit_uri_template_errors(self): with self.expect_error( edit_uri_template=re.compile(r'.*[{}].*') # Complains about unclosed '{' or missing '}' ): self.get_config( self.Schema, { 'repo_url': "https://github.com/mkdocs/mkdocs", 'edit_uri_template': 'edit/master/{path', }, ) with self.expect_error(edit_uri_template=re.compile(r'.*\bz\b.*')): self.get_config( self.Schema, { 'repo_url': "https://github.com/mkdocs/mkdocs", 'edit_uri_template': 'edit/master/{path!z}', }, ) with self.expect_error(edit_uri_template="Unknown template substitute: 'foo'"): self.get_config( self.Schema, { 'repo_url': "https://github.com/mkdocs/mkdocs", 'edit_uri_template': 'edit/master/{foo}', }, ) def test_edit_uri_template_warning(self): conf = self.get_config( self.Schema, { 'repo_url': "https://github.com/mkdocs/mkdocs", 'edit_uri': 'edit', 'edit_uri_template': 'edit/master/{path}', }, warnings=dict( edit_uri_template="The option 'edit_uri' has no effect when 'edit_uri_template' is set." ), ) self.assertEqual(conf['edit_uri_template'], 'edit/master/{path}')
EditURITest
python
pytorch__pytorch
torch/_refs/fft.py
{ "start": 7669, "end": 13042 }
class ____(NamedTuple): shape: tuple[int, ...] dims: tuple[int, ...] def _canonicalize_fft_shape_and_dim_args( input: TensorLikeType, shape: Optional[ShapeType], dim: Optional[DimsType] ) -> _ShapeAndDims: """Convert the shape and dim arguments into a canonical form where neither are optional""" input_dim = input.ndim input_sizes = input.shape if dim is not None: if not isinstance(dim, Sequence): dim = (dim,) ret_dims = utils.canonicalize_dims(input_dim, dim, wrap_scalar=False) # Check dims are unique torch._check( len(set(ret_dims)) == len(ret_dims), lambda: "FFT dims must be unique" ) if shape is not None: if not isinstance(shape, Sequence): shape = (shape,) # Has shape, might have dim torch._check( dim is None or len(dim) == len(shape), lambda: "When given, dim and shape arguments must have the same length", ) transform_ndim = len(shape) torch._check( transform_ndim <= input_dim, lambda: f"Got shape with {transform_ndim} values but input tensor " f"only has {input_dim} dimensions.", ) # If shape is given, dims defaults to the last len(shape) dimensions if dim is None: ret_dims = tuple(range(input_dim - transform_ndim, input_dim)) # Translate any -1 values in shape to the default length ret_shape = tuple( s if s != -1 else input_sizes[d] for (s, d) in zip(shape, ret_dims) # type: ignore[possibly-undefined] ) elif dim is None: # No shape, no dim ret_dims = tuple(range(input_dim)) ret_shape = tuple(input_sizes) else: # No shape, has dim ret_shape = tuple(input_sizes[d] for d in ret_dims) # type: ignore[possibly-undefined] for n in ret_shape: torch._check(n > 0, lambda: f"Invalid number of data points ({n}) specified") return _ShapeAndDims(shape=ret_shape, dims=ret_dims) # type: ignore[possibly-undefined] def _prod(xs: Iterable[int]) -> int: """Compute product of a list""" prod = 1 for x in xs: prod *= x return prod def _fftn_c2c( function_name: str, input: TensorLikeType, shape: tuple[int, ...], dim: tuple[int, ...], norm: NormType, forward: bool, ) -> TensorLikeType: """Common code for n-dimensional complex to complex FFTs (fftn or ifftn)""" torch._check( input.dtype.is_complex, lambda: f"{function_name} expects a complex input tensor, " f"but got {input.dtype}", ) x = _resize_fft_input(input, dim, shape) output = prims.fft_c2c(x, dim=dim, forward=forward) return _apply_norm(output, norm=norm, signal_numel=_prod(shape), forward=forward) @register_decomposition(aten.fft_fftn) @out_wrapper() def fftn( input: TensorLikeType, s: Optional[ShapeType] = None, dim: Optional[DimsType] = None, norm: NormType = None, ) -> TensorLikeType: (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim) x = _maybe_promote_tensor_fft(input, require_complex=True) return _fftn_c2c("fftn", x, shape, dim, norm, forward=True) @register_decomposition(aten.fft_ifftn) @out_wrapper() def ifftn( input: TensorLikeType, s: Optional[ShapeType] = None, dim: Optional[DimsType] = None, norm: NormType = None, ) -> TensorLikeType: (shape, dim) = _canonicalize_fft_shape_and_dim_args(input, s, dim) x = _maybe_promote_tensor_fft(input, require_complex=True) return _fftn_c2c("ifftn", x, shape, dim, norm, forward=False) @register_decomposition(aten.fft_rfftn) @out_wrapper() def rfftn( input: TensorLikeType, s: Optional[ShapeType] = None, dim: Optional[DimsType] = None, norm: NormType = None, ) -> TensorLikeType: torch._check( not input.dtype.is_complex, lambda: f"rfftn expects a real-valued input tensor, but got {input.dtype}", ) shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim) input = _maybe_promote_tensor_fft(input, require_complex=False) input = _resize_fft_input(input, dim, shape) out = prims.fft_r2c(input, dim=dim, onesided=True) return _apply_norm(out, norm=norm, signal_numel=_prod(shape), forward=True) @register_decomposition(aten.fft_ihfftn) @out_wrapper() def ihfftn( input: TensorLikeType, s: Optional[ShapeType] = None, dim: Optional[DimsType] = None, norm: NormType = None, ) -> TensorLikeType: torch._check( not input.dtype.is_complex, lambda: f"ihfftn expects a real-valued input tensor, but got {input.dtype}", ) shape, dim = _canonicalize_fft_shape_and_dim_args(input, s, dim) torch._check(len(shape) > 0, lambda: "ihfftn must transform at least one axis") input = _maybe_promote_tensor_fft(input, require_complex=False) input = _resize_fft_input(input, dim, shape) tmp = prims.fft_r2c(input, dim=dim[-1:], onesided=True) if len(dim) == 1: tmp = _apply_norm(tmp, norm=norm, signal_numel=shape[0], forward=False) return prims.conj(tmp) tmp = prims.conj_physical(tmp) tmp = prims.fft_c2c(tmp, dim=dim[:-1], forward=False) return _apply_norm(tmp, norm=norm, signal_numel=_prod(shape), forward=False)
_ShapeAndDims
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1133541, "end": 1134982 }
class ____(sgqlc.types.Type, Node): """Describes the status of a given deployment attempt.""" __schema__ = github_schema __field_names__ = ("created_at", "creator", "deployment", "description", "environment_url", "log_url", "state", "updated_at") created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt") """Identifies the date and time when the object was created.""" creator = sgqlc.types.Field(sgqlc.types.non_null(Actor), graphql_name="creator") """Identifies the actor who triggered the deployment.""" deployment = sgqlc.types.Field(sgqlc.types.non_null(Deployment), graphql_name="deployment") """Identifies the deployment associated with status.""" description = sgqlc.types.Field(String, graphql_name="description") """Identifies the description of the deployment.""" environment_url = sgqlc.types.Field(URI, graphql_name="environmentUrl") """Identifies the environment URL of the deployment.""" log_url = sgqlc.types.Field(URI, graphql_name="logUrl") """Identifies the log URL of the deployment.""" state = sgqlc.types.Field(sgqlc.types.non_null(DeploymentStatusState), graphql_name="state") """Identifies the current state of the deployment.""" updated_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="updatedAt") """Identifies the date and time when the object was last updated."""
DeploymentStatus
python
getsentry__sentry
src/sentry/notifications/notification_action/metric_alert_registry/handlers/msteams_metric_alert_handler.py
{ "start": 871, "end": 2578 }
class ____(BaseMetricAlertHandler): @classmethod def send_alert( cls, notification_context: NotificationContext, alert_context: AlertContext, metric_issue_context: MetricIssueContext, open_period_context: OpenPeriodContext, trigger_status: TriggerStatus, notification_uuid: str, organization: Organization, project: Project, ) -> None: from sentry.integrations.msteams.utils import send_incident_alert_notification detector = Detector.objects.get(id=alert_context.action_identifier_id) if not detector: raise ValueError("Detector not found") open_period = GroupOpenPeriod.objects.get(id=open_period_context.id) if not open_period: raise ValueError("Open period not found") alert_rule_serialized_response = get_alert_rule_serializer(detector) incident_serialized_response = get_detailed_incident_serializer(open_period) logger.info( "notification_action.execute_via_metric_alert_handler.msteams", extra={ "action_id": alert_context.action_identifier_id, }, ) send_incident_alert_notification( notification_context=notification_context, alert_context=alert_context, metric_issue_context=metric_issue_context, open_period_context=open_period_context, organization=organization, notification_uuid=notification_uuid, alert_rule_serialized_response=alert_rule_serialized_response, incident_serialized_response=incident_serialized_response, )
MSTeamsMetricAlertHandler
python
pandas-dev__pandas
pandas/core/computation/ops.py
{ "start": 7816, "end": 12338 }
class ____(Op): """ Hold a binary operator and its operands. Parameters ---------- op : str lhs : Term or Op rhs : Term or Op """ def __init__(self, op: str, lhs, rhs) -> None: super().__init__(op, (lhs, rhs)) self.lhs = lhs self.rhs = rhs self._disallow_scalar_only_bool_ops() self.convert_values() try: self.func = _binary_ops_dict[op] except KeyError as err: # has to be made a list for python3 keys = list(_binary_ops_dict.keys()) raise ValueError( f"Invalid binary operator {op!r}, valid operators are {keys}" ) from err def __call__(self, env): """ Recursively evaluate an expression in Python space. Parameters ---------- env : Scope Returns ------- object The result of an evaluated expression. """ # recurse over the left/right nodes left = self.lhs(env) right = self.rhs(env) return self.func(left, right) def evaluate(self, env, engine: str, parser, term_type, eval_in_python): """ Evaluate a binary operation *before* being passed to the engine. Parameters ---------- env : Scope engine : str parser : str term_type : type eval_in_python : list Returns ------- term_type The "pre-evaluated" expression as an instance of ``term_type`` """ if engine == "python": res = self(env) else: # recurse over the left/right nodes left = self.lhs.evaluate( env, engine=engine, parser=parser, term_type=term_type, eval_in_python=eval_in_python, ) right = self.rhs.evaluate( env, engine=engine, parser=parser, term_type=term_type, eval_in_python=eval_in_python, ) # base cases if self.op in eval_in_python: res = self.func(left.value, right.value) else: from pandas.core.computation.eval import eval res = eval(self, local_dict=env, engine=engine, parser=parser) name = env.add_tmp(res) return term_type(name, env=env) def convert_values(self) -> None: """ Convert datetimes to a comparable value in an expression. """ def stringify(value): encoder: Callable if self.encoding is not None: encoder = partial(pprint_thing_encoded, encoding=self.encoding) else: encoder = pprint_thing return encoder(value) lhs, rhs = self.lhs, self.rhs if is_term(lhs) and lhs.is_datetime and is_term(rhs) and rhs.is_scalar: v = rhs.value if isinstance(v, (int, float)): v = stringify(v) v = Timestamp(ensure_decoded(v)) if v.tz is not None: v = v.tz_convert("UTC") self.rhs.update(v) if is_term(rhs) and rhs.is_datetime and is_term(lhs) and lhs.is_scalar: v = lhs.value if isinstance(v, (int, float)): v = stringify(v) v = Timestamp(ensure_decoded(v)) if v.tz is not None: v = v.tz_convert("UTC") self.lhs.update(v) def _disallow_scalar_only_bool_ops(self) -> None: rhs = self.rhs lhs = self.lhs # GH#24883 unwrap dtype if necessary to ensure we have a type object rhs_rt = rhs.return_type rhs_rt = getattr(rhs_rt, "type", rhs_rt) lhs_rt = lhs.return_type lhs_rt = getattr(lhs_rt, "type", lhs_rt) if ( (lhs.is_scalar or rhs.is_scalar) and self.op in _bool_ops_dict and ( not ( issubclass(rhs_rt, (bool, np.bool_)) and issubclass(lhs_rt, (bool, np.bool_)) ) ) ): raise NotImplementedError("cannot evaluate scalar only bool ops") UNARY_OPS_SYMS = ("+", "-", "~", "not") _unary_ops_funcs = (operator.pos, operator.neg, operator.invert, operator.invert) _unary_ops_dict = dict(zip(UNARY_OPS_SYMS, _unary_ops_funcs, strict=True))
BinOp
python
scipy__scipy
scipy/optimize/tests/test_linprog.py
{ "start": 104925, "end": 104988 }
class ____(RRTests): options = {"rr_method": "SVD"}
TestRRSVD
python
ansible__ansible
lib/ansible/modules/hostname.py
{ "start": 23372, "end": 23493 }
class ____(Hostname): platform = 'Linux' distribution = 'Alinux' strategy_class = RedHatStrategy
AlinuxHostname
python
scipy__scipy
scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
{ "start": 18754, "end": 27642 }
class ____(TestCase): # From Example 16.2 Nocedal/Wright "Numerical # Optimization" p.452. def test_nocedal_example(self): H = csc_array([[6, 2, 1], [2, 5, 2], [1, 2, 4]]) A = csc_array([[1, 0, 1], [0, 1, 1]]) c = np.array([-8, -3, -3]) b = -np.array([3, 0]) Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b) assert_equal(info["stop_cond"], 4) assert_equal(info["hits_boundary"], False) assert_array_almost_equal(x, [2, -1, 1]) def test_compare_with_direct_fact(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b, tol=0) x_kkt, _ = eqp_kktfact(H, c, A, b) assert_equal(info["stop_cond"], 1) assert_equal(info["hits_boundary"], False) assert_array_almost_equal(x, x_kkt) def test_trust_region_infeasible(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) trust_radius = 1 Z, _, Y = projections(A) with pytest.raises(ValueError): projected_cg(H, c, Z, Y, b, trust_radius=trust_radius) def test_trust_region_barely_feasible(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) trust_radius = 2.32379000772445021283 Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b, tol=0, trust_radius=trust_radius) assert_equal(info["stop_cond"], 2) assert_equal(info["hits_boundary"], True) assert_array_almost_equal(np.linalg.norm(x), trust_radius) assert_array_almost_equal(x, -Y.dot(b)) def test_hits_boundary(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) trust_radius = 3 Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b, tol=0, trust_radius=trust_radius) assert_equal(info["stop_cond"], 2) assert_equal(info["hits_boundary"], True) assert_array_almost_equal(np.linalg.norm(x), trust_radius) def test_negative_curvature_unconstrained(self): H = csc_array([[1, 2, 1, 3], [2, 0, 2, 4], [1, 2, 0, 2], [3, 4, 2, 0]]) A = csc_array([[1, 0, 1, 0], [0, 1, 0, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) Z, _, Y = projections(A) with pytest.raises(ValueError): projected_cg(H, c, Z, Y, b, tol=0) def test_negative_curvature(self): H = csc_array([[1, 2, 1, 3], [2, 0, 2, 4], [1, 2, 0, 2], [3, 4, 2, 0]]) A = csc_array([[1, 0, 1, 0], [0, 1, 0, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) Z, _, Y = projections(A) trust_radius = 1000 x, info = projected_cg(H, c, Z, Y, b, tol=0, trust_radius=trust_radius) assert_equal(info["stop_cond"], 3) assert_equal(info["hits_boundary"], True) assert_array_almost_equal(np.linalg.norm(x), trust_radius) # The box constraints are inactive at the solution but # are active during the iterations. def test_inactive_box_constraints(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b, tol=0, lb=[0.5, -np.inf, -np.inf, -np.inf], return_all=True) x_kkt, _ = eqp_kktfact(H, c, A, b) assert_equal(info["stop_cond"], 1) assert_equal(info["hits_boundary"], False) assert_array_almost_equal(x, x_kkt) # The box constraints active and the termination is # by maximum iterations (infeasible interaction). def test_active_box_constraints_maximum_iterations_reached(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b, tol=0, lb=[0.8, -np.inf, -np.inf, -np.inf], return_all=True) assert_equal(info["stop_cond"], 1) assert_equal(info["hits_boundary"], True) assert_array_almost_equal(A.dot(x), -b) assert_array_almost_equal(x[0], 0.8) # The box constraints are active and the termination is # because it hits boundary (without infeasible interaction). def test_active_box_constraints_hits_boundaries(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) trust_radius = 3 Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b, tol=0, ub=[np.inf, np.inf, 1.6, np.inf], trust_radius=trust_radius, return_all=True) assert_equal(info["stop_cond"], 2) assert_equal(info["hits_boundary"], True) assert_array_almost_equal(x[2], 1.6) # The box constraints are active and the termination is # because it hits boundary (infeasible interaction). def test_active_box_constraints_hits_boundaries_infeasible_iter(self): H = csc_array([[6, 2, 1, 3], [2, 5, 2, 4], [1, 2, 4, 5], [3, 4, 5, 7]]) A = csc_array([[1, 0, 1, 0], [0, 1, 1, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) trust_radius = 4 Z, _, Y = projections(A) x, info = projected_cg(H, c, Z, Y, b, tol=0, ub=[np.inf, 0.1, np.inf, np.inf], trust_radius=trust_radius, return_all=True) assert_equal(info["stop_cond"], 2) assert_equal(info["hits_boundary"], True) assert_array_almost_equal(x[1], 0.1) # The box constraints are active and the termination is # because it hits boundary (no infeasible interaction). def test_active_box_constraints_negative_curvature(self): H = csc_array([[1, 2, 1, 3], [2, 0, 2, 4], [1, 2, 0, 2], [3, 4, 2, 0]]) A = csc_array([[1, 0, 1, 0], [0, 1, 0, 1]]) c = np.array([-2, -3, -3, 1]) b = -np.array([3, 0]) Z, _, Y = projections(A) trust_radius = 1000 x, info = projected_cg(H, c, Z, Y, b, tol=0, ub=[np.inf, np.inf, 100, np.inf], trust_radius=trust_radius) assert_equal(info["stop_cond"], 3) assert_equal(info["hits_boundary"], True) assert_array_almost_equal(x[2], 100)
TestProjectCG
python
google__pytype
pytype/tests/test_typing_annotated.py
{ "start": 122, "end": 3488 }
class ____(test_base.BaseTest): """Tests for typing.Annotated types.""" def test_basic(self): ty = self.Infer(""" from typing_extensions import Annotated i = ... # type: Annotated[int, "foo"] s: Annotated[str, "foo", "bar"] = "baz" """) self.assertTypesMatchPytd( ty, """ i: int s: str """, ) def test_nested(self): ty = self.Infer(""" from typing import List from typing_extensions import Annotated i = ... # type: Annotated[Annotated[int, "foo"], "bar"] strings = ... # type: Annotated[List[str], "bar"] """) self.assertTypesMatchPytd( ty, """ from typing import List i: int strings: List[str] """, ) def test_func(self): ty = self.Infer(""" from typing_extensions import Annotated def id(x: Annotated[int, "foo"]): return x """) self.assertTypesMatchPytd( ty, """ def id(x: int) -> int: ... """, ) def test_invalid_type(self): errors = self.CheckWithErrors(""" from typing_extensions import Annotated x: Annotated[0, int] = 0 # invalid-annotation[err] """) self.assertErrorRegexes(errors, {"err": r"Not a type"}) def test_missing_type(self): errors = self.CheckWithErrors(""" from typing_extensions import Annotated x: Annotated = 0 # invalid-annotation[err] """) self.assertErrorRegexes(errors, {"err": r"Not a type"}) def test_missing_annotation(self): errors = self.CheckWithErrors(""" from typing_extensions import Annotated x: Annotated[int] # invalid-annotation[err] """) self.assertErrorRegexes(errors, {"err": r"must have at least 1 annotation"}) def test_annotated_in_pyi(self): with test_utils.Tempdir() as d: d.create_file( "a.pyi", """ from typing import Annotated class A: x: Annotated[int, 'tag'] = ... """, ) ty = self.Infer( """ import a x = a.A().x """, pythonpath=[d.path], ) self.assertTypesMatchPytd( ty, """ import a x: int """, ) def test_annotated_type_in_pyi(self): with test_utils.Tempdir() as d: d.create_file( "a.pyi", """ from typing import Annotated class Foo: w: int class A: x: Annotated[Foo, 'tag'] = ... """, ) ty = self.Infer( """ import a x = a.A().x.w """, pythonpath=[d.path], ) self.assertTypesMatchPytd( ty, """ import a x: int """, ) def test_subclass_annotated_in_pyi(self): with test_utils.Tempdir() as d: d.create_file( "a.pyi", """ from typing import Annotated class A: x: Annotated[int, 'tag1', 'tag2'] = ... """, ) ty = self.Infer( """ import a class B(a.A): pass x = B().x """, pythonpath=[d.path], ) self.assertTypesMatchPytd( ty, """ import a class B(a.A): ... x: int """, ) if __name__ == "__main__": test_base.main()
AnnotatedTest
python
django__django
tests/migration_test_data_persistence/migrations/0002_add_book.py
{ "start": 240, "end": 441 }
class ____(migrations.Migration): dependencies = [("migration_test_data_persistence", "0001_initial")] operations = [ migrations.RunPython( add_book, ), ]
Migration
python
realpython__materials
dwitter-part-3/source_code_final/dwitter/migrations/0002_dweet.py
{ "start": 158, "end": 856 }
class ____(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('dwitter', '0001_initial'), ] operations = [ migrations.CreateModel( name='Dweet', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('body', models.CharField(max_length=140)), ('created_at', models.DateTimeField(auto_now_add=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='dweets', to=settings.AUTH_USER_MODEL)), ], ), ]
Migration
python
coleifer__peewee
tests/base_models.py
{ "start": 483, "end": 641 }
class ____(TestModel): from_person = ForeignKeyField(Person, backref='relations') to_person = ForeignKeyField(Person, backref='related_to')
Relationship
python
walkccc__LeetCode
solutions/2709. Greatest Common Divisor Traversal/2709.py
{ "start": 0, "end": 550 }
class ____: def __init__(self, n: int): self.id = list(range(n)) self.sz = [1] * n def unionBySize(self, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.sz[i] < self.sz[j]: self.sz[j] += self.sz[i] self.id[i] = j else: self.sz[i] += self.sz[j] self.id[j] = i def getSize(self, i: int) -> int: return self.sz[i] def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u]
UnionFind
python
huggingface__transformers
tests/models/hubert/test_modeling_hubert.py
{ "start": 22199, "end": 33335 }
class ____(unittest.TestCase): def _load_datasamples(self, num_samples): from datasets import load_dataset ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") # automatic decoding with librispeech speech_samples = ds.sort("id").filter( lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def _load_superb(self, task, num_samples): from datasets import load_dataset ds = load_dataset("anton-l/superb_dummy", task, split="test") return ds[:num_samples] def test_inference_ctc_batched(self): model = HubertForCTC.from_pretrained("facebook/hubert-large-ls960-ft", dtype=torch.float16).to(torch_device) processor = Wav2Vec2Processor.from_pretrained("facebook/hubert-large-ls960-ft", do_lower_case=True) input_speech = self._load_datasamples(2) inputs = processor(input_speech, return_tensors="pt", padding=True) input_values = inputs.input_values.half().to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): logits = model(input_values, attention_mask=attention_mask).logits predicted_ids = torch.argmax(logits, dim=-1) predicted_trans = processor.batch_decode(predicted_ids) EXPECTED_TRANSCRIPTIONS = [ "a man said to the universe sir i exist", "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore", ] self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) def test_inference_keyword_spotting(self): model = HubertForSequenceClassification.from_pretrained( "superb/hubert-base-superb-ks", dtype=torch.float16 ).to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/hubert-base-superb-ks") input_data = self._load_superb("ks", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True) input_values = inputs.input_values.half().to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): outputs = model(input_values, attention_mask=attention_mask) predicted_logits, predicted_ids = torch.max(outputs.logits, dim=-1) expected_labels = [2, 6, 10, 9] # s3prl logits for the same batch expected_logits = torch.tensor([7.6692, 17.7795, 11.1562, 11.8232], dtype=torch.float16, device=torch_device) self.assertListEqual(predicted_ids.tolist(), expected_labels) torch.testing.assert_close(predicted_logits, expected_logits, rtol=3e-2, atol=3e-2) def test_inference_intent_classification(self): model = HubertForSequenceClassification.from_pretrained( "superb/hubert-base-superb-ic", dtype=torch.float16 ).to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/hubert-base-superb-ic") input_data = self._load_superb("ic", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True) input_values = inputs.input_values.half().to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): outputs = model(input_values, attention_mask=attention_mask) predicted_logits_action, predicted_ids_action = torch.max(outputs.logits[:, :6], dim=-1) predicted_logits_object, predicted_ids_object = torch.max(outputs.logits[:, 6:20], dim=-1) predicted_logits_location, predicted_ids_location = torch.max(outputs.logits[:, 20:24], dim=-1) expected_labels_action = [1, 0, 4, 3] expected_logits_action = torch.tensor( [5.9052, 12.5865, 4.4840, 10.0240], dtype=torch.float16, device=torch_device ) expected_labels_object = [1, 10, 3, 4] expected_logits_object = torch.tensor( [5.5316, 11.7946, 8.1672, 23.2415], dtype=torch.float16, device=torch_device ) expected_labels_location = [0, 0, 0, 1] expected_logits_location = torch.tensor( [5.2053, 8.9577, 10.0447, 8.1481], dtype=torch.float16, device=torch_device ) self.assertListEqual(predicted_ids_action.tolist(), expected_labels_action) self.assertListEqual(predicted_ids_object.tolist(), expected_labels_object) self.assertListEqual(predicted_ids_location.tolist(), expected_labels_location) # TODO: lower the tolerance after merging the padding fix https://github.com/pytorch/fairseq/pull/3572 torch.testing.assert_close(predicted_logits_action, expected_logits_action, rtol=3e-1, atol=3e-1) torch.testing.assert_close(predicted_logits_object, expected_logits_object, rtol=3e-1, atol=3e-1) torch.testing.assert_close(predicted_logits_location, expected_logits_location, rtol=3e-1, atol=3e-1) def test_inference_speaker_identification(self): model = HubertForSequenceClassification.from_pretrained( "superb/hubert-base-superb-sid", dtype=torch.float16 ).to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/hubert-base-superb-sid") input_data = self._load_superb("si", 4) output_logits = [] with torch.no_grad(): for example in input_data["speech"]: input = processor(example, return_tensors="pt", padding=True) output = model(input.input_values.half().to(torch_device), attention_mask=None) output_logits.append(output.logits[0]) output_logits = torch.stack(output_logits) predicted_logits, predicted_ids = torch.max(output_logits, dim=-1) expected_labels = [5, 1, 1, 3] # s3prl logits for the same batch expected_logits = torch.tensor( [78231.5547, 123166.6094, 122785.4141, 84851.2969], dtype=torch.float16, device=torch_device ) self.assertListEqual(predicted_ids.tolist(), expected_labels) # TODO: lower the tolerance after merging the padding fix https://github.com/pytorch/fairseq/pull/3572 torch.testing.assert_close(predicted_logits, expected_logits, rtol=10, atol=10) def test_inference_emotion_recognition(self): model = HubertForSequenceClassification.from_pretrained( "superb/hubert-base-superb-er", dtype=torch.float16 ).to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("superb/hubert-base-superb-er") input_data = self._load_superb("er", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True) input_values = inputs.input_values.half().to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): outputs = model(input_values, attention_mask=attention_mask) predicted_logits, predicted_ids = torch.max(outputs.logits, dim=-1) expected_labels = [1, 1, 2, 2] # s3prl logits for the same batch expected_logits = torch.tensor([2.8384, 2.3389, 3.8564, 4.5558], dtype=torch.float16, device=torch_device) self.assertListEqual(predicted_ids.tolist(), expected_labels) # TODO: lower the tolerance after merging the padding fix https://github.com/pytorch/fairseq/pull/3572 torch.testing.assert_close(predicted_logits, expected_logits, rtol=1e-1, atol=1e-1) def test_inference_distilhubert(self): model = HubertModel.from_pretrained("ntu-spml/distilhubert").to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("ntu-spml/distilhubert") # TODO: can't test on batched inputs due to incompatible padding https://github.com/pytorch/fairseq/pull/3572 input_speech = self._load_datasamples(1) inputs = processor(input_speech, return_tensors="pt", padding=True) input_values = inputs.input_values.to(torch_device) with torch.no_grad(): outputs = model(input_values).last_hidden_state # expected outputs taken from the original SEW implementation expected_outputs_first = torch.tensor( [ [ [-0.3505, 0.1167, 0.0608, 0.1294], [-0.3085, 0.0481, 0.1106, 0.0955], [-0.3107, -0.0391, 0.0739, 0.1360], [-0.2385, -0.1795, -0.0928, 0.2389], ] ], device=torch_device, ) expected_outputs_last = torch.tensor( [ [ [-0.0732, 0.0255, 0.0529, -0.1372], [-0.0812, 0.1259, 0.0564, -0.0438], [-0.0054, 0.0758, -0.0002, -0.1617], [0.0133, -0.0320, -0.0687, 0.0062], ] ], device=torch_device, ) expected_output_sum = -3776.0730 torch.testing.assert_close(outputs[:, :4, :4], expected_outputs_first, rtol=5e-3, atol=5e-3) torch.testing.assert_close(outputs[:, -4:, -4:], expected_outputs_last, rtol=5e-3, atol=5e-3) self.assertTrue(abs(outputs.sum() - expected_output_sum) < 0.1) def test_inference_hubert_25hz(self): model = HubertModel.from_pretrained("slprl/mhubert-base-25hz").to(torch_device) sample = self._load_datasamples(1) input_speech = torch.tensor(sample[0], dtype=torch.float, device=torch_device).unsqueeze(0) with torch.no_grad(): outputs = model(input_speech, output_hidden_states=True).hidden_states[11] # expected outputs taken from the original textlesslib implementation by: # model = SpeechEncoder.by_name(dense_model_name='mhubert-base-25hz', quantizer_model_name='kmeans', # vocab_size=500, deduplicate=False, need_f0=False) # model(wav)['dense'] expected_outputs_first = torch.tensor( [ [ [0.0267, 0.1776, -0.1706, -0.4559], [-0.2430, -0.2943, -0.1864, -0.1187], [-0.1812, -0.4239, -0.1916, -0.0858], [-0.1495, -0.4758, -0.4036, 0.0302], ] ], device=torch_device, ) expected_outputs_last = torch.tensor( [ [ [0.3366, -0.2734, -0.1415, -0.3055], [0.2329, -0.3580, -0.1421, -0.3197], [0.1631, -0.4301, -0.1965, -0.2956], [0.3342, -0.2185, -0.2253, -0.2363], ] ], device=torch_device, ) expected_output_sum = 1681.7603 torch.testing.assert_close(outputs[:, :4, :4], expected_outputs_first, rtol=5e-3, atol=5e-3) torch.testing.assert_close(outputs[:, -4:, -4:], expected_outputs_last, rtol=5e-3, atol=5e-3) self.assertTrue(abs(outputs.sum() - expected_output_sum) < 0.1)
HubertModelIntegrationTest
python
great-expectations__great_expectations
tests/data_context/test_data_context.py
{ "start": 24149, "end": 24825 }
class ____(BatchExpectation): metric_dependencies = ("table.color",) success_keys = ("color",) args_keys = ("color",) color: str @classmethod @renderer(renderer_type=".".join([AtomicRendererType.PRESCRIPTIVE, "custom_renderer_type"])) def _prescriptive_renderer_custom( cls, **kwargs: dict, ) -> None: raise ValueError("This renderer is broken!") def _validate( # type: ignore[override,explicit-override] # FIXME self, **kwargs: dict, ) -> Dict[str, Union[bool, dict]]: return { "success": True, "result": {"observed_value": "blue"}, }
ExpectSkyToBeColor
python
apache__airflow
providers/google/tests/unit/google/cloud/transfers/test_local_to_gcs.py
{ "start": 1167, "end": 9424 }
class ____: _config = { "bucket": "dummy", "mime_type": "application/octet-stream", "gzip": False, "chunk_size": 262144, } @pytest.fixture(autouse=True) def setup_method_fixture(self, tmp_path): args = {"owner": "airflow", "start_date": datetime.datetime(2017, 1, 1)} self.dag = DAG("test_dag_id", schedule=None, default_args=args) tmp_dir = tmp_path / "tmp" tmp_dir.mkdir(exist_ok=True, parents=True) self.tmpdir_posix = tmp_dir.as_posix() self.testfile1 = f"{self.tmpdir_posix}/fake1.csv" with open(self.testfile1, "wb") as f: f.write(b"x" * 393216) self.testfile2 = f"{self.tmpdir_posix}/fake2.csv" with open(self.testfile2, "wb") as f: f.write(b"x" * 393216) self.testfiles = [self.testfile1, self.testfile2] yield shutil.rmtree(tmp_dir, ignore_errors=True) def test_init(self): operator = LocalFilesystemToGCSOperator( task_id="file_to_gcs_operator", dag=self.dag, src=self.testfile1, dst="test/test1.csv", **self._config, ) assert operator.src == self.testfile1 assert operator.dst == "test/test1.csv" assert operator.bucket == self._config["bucket"] assert operator.mime_type == self._config["mime_type"] assert operator.gzip == self._config["gzip"] assert operator.chunk_size == self._config["chunk_size"] @mock.patch("airflow.providers.google.cloud.transfers.local_to_gcs.GCSHook", autospec=True) def test_execute(self, mock_hook): mock_instance = mock_hook.return_value operator = LocalFilesystemToGCSOperator( task_id="file_to_gcs_operator", dag=self.dag, src=self.testfile1, dst="test/test1.csv", **self._config, ) operator.execute(None) mock_instance.upload.assert_called_once_with( bucket_name=self._config["bucket"], filename=self.testfile1, gzip=self._config["gzip"], mime_type=self._config["mime_type"], object_name="test/test1.csv", chunk_size=self._config["chunk_size"], ) @pytest.mark.db_test def test_execute_with_empty_src(self): operator = LocalFilesystemToGCSOperator( task_id="file_to_gcs_operator", dag=self.dag, src="no_file.txt", dst="test/no_file.txt", **self._config, ) with pytest.raises(FileNotFoundError): operator.execute(None) @mock.patch("airflow.providers.google.cloud.transfers.local_to_gcs.GCSHook", autospec=True) def test_execute_multiple(self, mock_hook): mock_instance = mock_hook.return_value operator = LocalFilesystemToGCSOperator( task_id="file_to_gcs_operator", dag=self.dag, src=self.testfiles, dst="test/", **self._config ) operator.execute(None) files_objects = zip( self.testfiles, ["test/" + os.path.basename(testfile) for testfile in self.testfiles] ) calls = [ mock.call( bucket_name=self._config["bucket"], filename=filepath, gzip=self._config["gzip"], mime_type=self._config["mime_type"], object_name=object_name, chunk_size=self._config["chunk_size"], ) for filepath, object_name in files_objects ] mock_instance.upload.assert_has_calls(calls) @mock.patch("airflow.providers.google.cloud.transfers.local_to_gcs.GCSHook", autospec=True) def test_execute_wildcard(self, mock_hook): mock_instance = mock_hook.return_value operator = LocalFilesystemToGCSOperator( task_id="file_to_gcs_operator", dag=self.dag, src=f"{self.tmpdir_posix}/fake*.csv", dst="test/", **self._config, ) operator.execute(None) object_names = ["test/" + os.path.basename(fp) for fp in glob(f"{self.tmpdir_posix}/fake*.csv")] files_objects = zip(glob(f"{self.tmpdir_posix}/fake*.csv"), object_names) calls = [ mock.call( bucket_name=self._config["bucket"], filename=filepath, gzip=self._config["gzip"], mime_type=self._config["mime_type"], object_name=object_name, chunk_size=self._config["chunk_size"], ) for filepath, object_name in files_objects ] mock_instance.upload.assert_has_calls(calls) @pytest.mark.parametrize( ("src", "dst"), [ ("fake*.csv", "test/test1.csv"), ("fake*.csv", "test"), ("fake*.csv", "test/dir"), ], ) @mock.patch("airflow.providers.google.cloud.transfers.local_to_gcs.GCSHook", autospec=True) def test_execute_negative(self, mock_hook, src, dst): mock_instance = mock_hook.return_value operator = LocalFilesystemToGCSOperator( task_id="file_to_gcs_operator", dag=self.dag, src=f"{self.tmpdir_posix}/{src}", dst=dst, **self._config, ) with pytest.raises(ValueError, match="'dst' parameter references filepath."): operator.execute(None) mock_instance.assert_not_called() @pytest.mark.parametrize( ("src", "dst", "expected_input", "expected_output", "symlink"), [ ("fake*.csv", "test/", "", "test", True), ("../tmp/fake*.csv", "test/", "", "test", True), ("fake1.csv", "test/test1.csv", "fake1.csv", "test/test1.csv", False), ("fake1.csv", "test/pre", "fake1.csv", "test/pre", False), ], ) def test_get_openlineage_facets_on_start_with_string_src( self, src, dst, expected_input, expected_output, symlink ): operator = LocalFilesystemToGCSOperator( task_id="gcs_to_file_sensor", dag=self.dag, src=f"{self.tmpdir_posix}/{src}", dst=dst, **self._config, ) result = operator.get_openlineage_facets_on_start() expected_input = self.tmpdir_posix + ("/" + expected_input if expected_input else "") assert not result.job_facets assert not result.run_facets assert len(result.outputs) == 1 assert len(result.inputs) == 1 assert result.outputs[0].namespace == "gs://dummy" assert result.outputs[0].name == expected_output assert result.inputs[0].namespace == "file" assert result.inputs[0].name == expected_input if symlink: assert result.inputs[0].facets["symlink"] == SymlinksDatasetFacet( identifiers=[Identifier(namespace="file", name=f"{self.tmpdir_posix}/{src}", type="file")] ) @pytest.mark.parametrize( ("src", "dst", "expected_inputs", "expected_output"), [ (["fake1.csv", "fake2.csv"], "test/", ["fake1.csv", "fake2.csv"], "test"), (["fake1.csv", "fake2.csv"], "", ["fake1.csv", "fake2.csv"], "/"), ], ) def test_get_openlineage_facets_on_start_with_list_src(self, src, dst, expected_inputs, expected_output): expected_inputs = [f"{self.tmpdir_posix}/{item}" for item in expected_inputs] operator = LocalFilesystemToGCSOperator( task_id="gcs_to_file_sensor", dag=self.dag, src=[f"{self.tmpdir_posix}/{src_item}" for src_item in src], dst=dst, **self._config, ) result = operator.get_openlineage_facets_on_start() assert not result.job_facets assert not result.run_facets assert len(result.outputs) == 1 assert len(result.inputs) == len(expected_inputs) assert result.outputs[0].name == expected_output assert result.outputs[0].namespace == "gs://dummy" assert all(inp.name in expected_inputs for inp in result.inputs) assert all(inp.namespace == "file" for inp in result.inputs)
TestFileToGcsOperator
python
yaml__pyyaml
lib/yaml/tokens.py
{ "start": 1720, "end": 1915 }
class ____(Token): id = '<alias>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark
AliasToken
python
realpython__materials
mandelbrot-set-python/mandelbrot_03.py
{ "start": 145, "end": 879 }
class ____: max_iterations: int escape_radius: float = 2.0 def __contains__(self, c: complex) -> bool: return self.stability(c) == 1 def stability(self, c: complex, smooth=False, clamp=True) -> float: value = self.escape_count(c, smooth) / self.max_iterations return max(0.0, min(value, 1.0)) if clamp else value def escape_count(self, c: complex, smooth=False) -> int | float: z = 0 for iteration in range(self.max_iterations): z = z**2 + c if abs(z) > self.escape_radius: if smooth: return iteration + 1 - log(log(abs(z))) / log(2) return iteration return self.max_iterations
MandelbrotSet
python
openai__openai-python
src/openai/types/responses/response_text_config_param.py
{ "start": 319, "end": 1381 }
class ____(TypedDict, total=False): format: ResponseFormatTextConfigParam """An object specifying the format that the model must output. Configuring `{ "type": "json_schema" }` enables Structured Outputs, which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). The default format is `{ "type": "text" }` with no additional options. **Not recommended for gpt-4o and newer models:** Setting to `{ "type": "json_object" }` enables the older JSON mode, which ensures the message the model generates is valid JSON. Using `json_schema` is preferred for models that support it. """ verbosity: Optional[Literal["low", "medium", "high"]] """Constrains the verbosity of the model's response. Lower values will result in more concise responses, while higher values will result in more verbose responses. Currently supported values are `low`, `medium`, and `high`. """
ResponseTextConfigParam
python
lepture__authlib
authlib/oauth2/rfc8628/errors.py
{ "start": 320, "end": 600 }
class ____(OAuth2Error): """A variant of "authorization_pending", the authorization request is still pending and polling should continue, but the interval MUST be increased by 5 seconds for this and all subsequent requests. """ error = "slow_down"
SlowDownError
python
Textualize__textual
docs/examples/widgets/footer.py
{ "start": 116, "end": 680 }
class ____(App): BINDINGS = [ Binding(key="q", action="quit", description="Quit the app"), Binding( key="question_mark", action="help", description="Show help screen", key_display="?", ), Binding(key="delete", action="delete", description="Delete the thing"), Binding(key="j", action="down", description="Scroll down", show=False), ] def compose(self) -> ComposeResult: yield Footer() if __name__ == "__main__": app = FooterApp() app.run()
FooterApp
python
google__pytype
pytype/overlays/typing_overlay.py
{ "start": 12804, "end": 13782 }
class ____(_TypeVariable): """Representation of typing.TypeVar, as a function.""" _ABSTRACT_CLASS = abstract.TypeParameter @classmethod def make(cls, ctx, module): # We always want to use typing as the module, since pytype's typing.pytd # contains a _typevar_new helper. del module return super().make("TypeVar", ctx, "typing", pyval_name="_typevar_new") def _get_namedarg(self, node, args, name, default_value): if name not in args.namedargs: return default_value if name == "bound": return self._get_annotation(node, args.namedargs[name], name) else: if name == "default": ret = self._get_annotation(node, args.namedargs[name], name) else: ret = self._get_constant(args.namedargs[name], name, bool) # This error is logged only if _get_constant succeeds. self.ctx.errorlog.not_supported_yet( self.ctx.vm.frames, f'argument "{name}" to TypeVar' ) return ret
TypeVar
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 911245, "end": 913147 }
class ____( sgqlc.types.Type, Node, Comment, Deletable, Minimizable, Updatable, UpdatableComment, Reactable, RepositoryNode, ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "commit", "diff_hunk", "drafted_at", "original_commit", "original_position", "outdated", "path", "position", "pull_request", "pull_request_review", "reply_to", "resource_path", "state", "url", ) commit = sgqlc.types.Field(Commit, graphql_name="commit") diff_hunk = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="diffHunk") drafted_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="draftedAt" ) original_commit = sgqlc.types.Field(Commit, graphql_name="originalCommit") original_position = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="originalPosition" ) outdated = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="outdated") path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path") position = sgqlc.types.Field(Int, graphql_name="position") pull_request = sgqlc.types.Field( sgqlc.types.non_null(PullRequest), graphql_name="pullRequest" ) pull_request_review = sgqlc.types.Field( PullRequestReview, graphql_name="pullRequestReview" ) reply_to = sgqlc.types.Field("PullRequestReviewComment", graphql_name="replyTo") resource_path = sgqlc.types.Field( sgqlc.types.non_null(URI), graphql_name="resourcePath" ) state = sgqlc.types.Field( sgqlc.types.non_null(PullRequestReviewCommentState), graphql_name="state" ) url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="url")
PullRequestReviewComment
python
facebookresearch__faiss
benchs/bench_fw/benchmark.py
{ "start": 6896, "end": 9511 }
class ____(IndexOperator): codec_descs: List[CodecDescriptor] = field(default_factory=lambda: []) assemble_opaque: bool = True def get_desc(self, name: str) -> Optional[CodecDescriptor]: for desc in self.codec_descs: if desc.get_name() == name: return desc elif desc.factory == name: return desc return None def get_flat_desc(self, name=None) -> Optional[CodecDescriptor]: for desc in self.codec_descs: desc_name = desc.get_name() if desc_name == name: return desc if desc_name.startswith("Flat"): return desc return None def build_index_wrapper(self, codec_desc: CodecDescriptor): if hasattr(codec_desc, "index"): return if codec_desc.factory is not None: assert ( codec_desc.factory == "Flat" or codec_desc.training_vectors is not None ) index = IndexFromFactory( num_threads=self.num_threads, d=codec_desc.d, metric=self.distance_metric, construction_params=codec_desc.construction_params, factory=codec_desc.factory, training_vectors=codec_desc.training_vectors, codec_name=codec_desc.get_name(), assemble_opaque=self.assemble_opaque, ) index.set_io(self.io) codec_desc.index = index else: assert codec_desc.is_trained() def train_one( self, codec_desc: CodecDescriptor, results: Dict[str, Any], dry_run=False ): faiss.omp_set_num_threads(codec_desc.num_threads) self.build_index_wrapper(codec_desc) if codec_desc.is_trained(): return results, None if dry_run: meta, requires = codec_desc.index.fetch_meta(dry_run=dry_run) else: codec_desc.index.get_codec() meta, requires = codec_desc.index.fetch_meta(dry_run=dry_run) assert requires is None if requires is None: results["indices"][codec_desc.get_name()] = meta return results, requires def train(self, results, dry_run=False): for desc in self.codec_descs: results, requires = self.train_one(desc, results, dry_run=dry_run) if dry_run: if requires is None: continue return results, requires assert requires is None return results, None @dataclass
TrainOperator
python
Netflix__metaflow
metaflow/plugins/argo/exit_hooks.py
{ "start": 249, "end": 699 }
class ____(JsonSerializable): # https://argoproj.github.io/argo-workflows/fields/#lifecyclehook def __init__(self, name): tree = lambda: defaultdict(tree) self.name = name self.payload = tree() def expression(self, expression): self.payload["expression"] = str(expression) return self def template(self, template): self.payload["template"] = template return self
_LifecycleHook
python
marshmallow-code__marshmallow
src/marshmallow/schema.py
{ "start": 6962, "end": 8072 }
class ____: """Defines defaults for `marshmallow.Schema.Meta`.""" def __init__(self, meta: type): self.fields = getattr(meta, "fields", ()) if not isinstance(self.fields, (list, tuple)): raise ValueError("`fields` option must be a list or tuple.") self.exclude = getattr(meta, "exclude", ()) if not isinstance(self.exclude, (list, tuple)): raise ValueError("`exclude` must be a list or tuple.") self.dateformat = getattr(meta, "dateformat", None) self.datetimeformat = getattr(meta, "datetimeformat", None) self.timeformat = getattr(meta, "timeformat", None) self.render_module = getattr(meta, "render_module", json) self.index_errors = getattr(meta, "index_errors", True) self.include = getattr(meta, "include", {}) self.load_only = getattr(meta, "load_only", ()) self.dump_only = getattr(meta, "dump_only", ()) self.unknown = getattr(meta, "unknown", RAISE) self.register = getattr(meta, "register", True) self.many = getattr(meta, "many", False)
SchemaOpts
python
joke2k__faker
faker/providers/ssn/dk_DK/__init__.py
{ "start": 42, "end": 344 }
class ____(BaseProvider): """ A Faker provider for the Danish VAT IDs """ vat_id_formats = ("DK########",) def vat_id(self) -> str: """ Returns a random generated Danish Tax ID """ return self.bothify(self.random_element(self.vat_id_formats))
Provider
python
getsentry__sentry-python
sentry_sdk/integrations/huggingface_hub.py
{ "start": 699, "end": 14952 }
class ____(Integration): identifier = "huggingface_hub" origin = f"auto.ai.{identifier}" def __init__(self, include_prompts=True): # type: (HuggingfaceHubIntegration, bool) -> None self.include_prompts = include_prompts @staticmethod def setup_once(): # type: () -> None # Other tasks that can be called: https://huggingface.co/docs/huggingface_hub/guides/inference#supported-providers-and-tasks huggingface_hub.inference._client.InferenceClient.text_generation = ( _wrap_huggingface_task( huggingface_hub.inference._client.InferenceClient.text_generation, OP.GEN_AI_GENERATE_TEXT, ) ) huggingface_hub.inference._client.InferenceClient.chat_completion = ( _wrap_huggingface_task( huggingface_hub.inference._client.InferenceClient.chat_completion, OP.GEN_AI_CHAT, ) ) def _capture_exception(exc): # type: (Any) -> None set_span_errored() event, hint = event_from_exception( exc, client_options=sentry_sdk.get_client().options, mechanism={"type": "huggingface_hub", "handled": False}, ) sentry_sdk.capture_event(event, hint=hint) def _wrap_huggingface_task(f, op): # type: (Callable[..., Any], str) -> Callable[..., Any] @wraps(f) def new_huggingface_task(*args, **kwargs): # type: (*Any, **Any) -> Any integration = sentry_sdk.get_client().get_integration(HuggingfaceHubIntegration) if integration is None: return f(*args, **kwargs) prompt = None if "prompt" in kwargs: prompt = kwargs["prompt"] elif "messages" in kwargs: prompt = kwargs["messages"] elif len(args) >= 2: if isinstance(args[1], str) or isinstance(args[1], list): prompt = args[1] if prompt is None: # invalid call, dont instrument, let it return error return f(*args, **kwargs) client = args[0] model = client.model or kwargs.get("model") or "" operation_name = op.split(".")[-1] span = sentry_sdk.start_span( op=op, name=f"{operation_name} {model}", origin=HuggingfaceHubIntegration.origin, ) span.__enter__() span.set_data(SPANDATA.GEN_AI_OPERATION_NAME, operation_name) if model: span.set_data(SPANDATA.GEN_AI_REQUEST_MODEL, model) # Input attributes if should_send_default_pii() and integration.include_prompts: set_data_normalized( span, SPANDATA.GEN_AI_REQUEST_MESSAGES, prompt, unpack=False ) attribute_mapping = { "tools": SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS, "frequency_penalty": SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY, "max_tokens": SPANDATA.GEN_AI_REQUEST_MAX_TOKENS, "presence_penalty": SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY, "temperature": SPANDATA.GEN_AI_REQUEST_TEMPERATURE, "top_p": SPANDATA.GEN_AI_REQUEST_TOP_P, "top_k": SPANDATA.GEN_AI_REQUEST_TOP_K, "stream": SPANDATA.GEN_AI_RESPONSE_STREAMING, } for attribute, span_attribute in attribute_mapping.items(): value = kwargs.get(attribute, None) if value is not None: if isinstance(value, (int, float, bool, str)): span.set_data(span_attribute, value) else: set_data_normalized(span, span_attribute, value, unpack=False) # LLM Execution try: res = f(*args, **kwargs) except Exception as e: _capture_exception(e) span.__exit__(None, None, None) raise e from None # Output attributes finish_reason = None response_model = None response_text_buffer: list[str] = [] tokens_used = 0 tool_calls = None usage = None with capture_internal_exceptions(): if isinstance(res, str) and res is not None: response_text_buffer.append(res) if hasattr(res, "generated_text") and res.generated_text is not None: response_text_buffer.append(res.generated_text) if hasattr(res, "model") and res.model is not None: response_model = res.model if hasattr(res, "details") and hasattr(res.details, "finish_reason"): finish_reason = res.details.finish_reason if ( hasattr(res, "details") and hasattr(res.details, "generated_tokens") and res.details.generated_tokens is not None ): tokens_used = res.details.generated_tokens if hasattr(res, "usage") and res.usage is not None: usage = res.usage if hasattr(res, "choices") and res.choices is not None: for choice in res.choices: if hasattr(choice, "finish_reason"): finish_reason = choice.finish_reason if hasattr(choice, "message") and hasattr( choice.message, "tool_calls" ): tool_calls = choice.message.tool_calls if ( hasattr(choice, "message") and hasattr(choice.message, "content") and choice.message.content is not None ): response_text_buffer.append(choice.message.content) if response_model is not None: span.set_data(SPANDATA.GEN_AI_RESPONSE_MODEL, response_model) if finish_reason is not None: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS, finish_reason, ) if should_send_default_pii() and integration.include_prompts: if tool_calls is not None and len(tool_calls) > 0: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, tool_calls, unpack=False, ) if len(response_text_buffer) > 0: text_response = "".join(response_text_buffer) if text_response: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TEXT, text_response, ) if usage is not None: record_token_usage( span, input_tokens=usage.prompt_tokens, output_tokens=usage.completion_tokens, total_tokens=usage.total_tokens, ) elif tokens_used > 0: record_token_usage( span, total_tokens=tokens_used, ) # If the response is not a generator (meaning a streaming response) # we are done and can return the response if not inspect.isgenerator(res): span.__exit__(None, None, None) return res if kwargs.get("details", False): # text-generation stream output def new_details_iterator(): # type: () -> Iterable[Any] finish_reason = None response_text_buffer: list[str] = [] tokens_used = 0 with capture_internal_exceptions(): for chunk in res: if ( hasattr(chunk, "token") and hasattr(chunk.token, "text") and chunk.token.text is not None ): response_text_buffer.append(chunk.token.text) if hasattr(chunk, "details") and hasattr( chunk.details, "finish_reason" ): finish_reason = chunk.details.finish_reason if ( hasattr(chunk, "details") and hasattr(chunk.details, "generated_tokens") and chunk.details.generated_tokens is not None ): tokens_used = chunk.details.generated_tokens yield chunk if finish_reason is not None: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS, finish_reason, ) if should_send_default_pii() and integration.include_prompts: if len(response_text_buffer) > 0: text_response = "".join(response_text_buffer) if text_response: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TEXT, text_response, ) if tokens_used > 0: record_token_usage( span, total_tokens=tokens_used, ) span.__exit__(None, None, None) return new_details_iterator() else: # chat-completion stream output def new_iterator(): # type: () -> Iterable[str] finish_reason = None response_model = None response_text_buffer: list[str] = [] tool_calls = None usage = None with capture_internal_exceptions(): for chunk in res: if hasattr(chunk, "model") and chunk.model is not None: response_model = chunk.model if hasattr(chunk, "usage") and chunk.usage is not None: usage = chunk.usage if isinstance(chunk, str): if chunk is not None: response_text_buffer.append(chunk) if hasattr(chunk, "choices") and chunk.choices is not None: for choice in chunk.choices: if ( hasattr(choice, "delta") and hasattr(choice.delta, "content") and choice.delta.content is not None ): response_text_buffer.append( choice.delta.content ) if ( hasattr(choice, "finish_reason") and choice.finish_reason is not None ): finish_reason = choice.finish_reason if ( hasattr(choice, "delta") and hasattr(choice.delta, "tool_calls") and choice.delta.tool_calls is not None ): tool_calls = choice.delta.tool_calls yield chunk if response_model is not None: span.set_data( SPANDATA.GEN_AI_RESPONSE_MODEL, response_model ) if finish_reason is not None: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS, finish_reason, ) if should_send_default_pii() and integration.include_prompts: if tool_calls is not None and len(tool_calls) > 0: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS, tool_calls, unpack=False, ) if len(response_text_buffer) > 0: text_response = "".join(response_text_buffer) if text_response: set_data_normalized( span, SPANDATA.GEN_AI_RESPONSE_TEXT, text_response, ) if usage is not None: record_token_usage( span, input_tokens=usage.prompt_tokens, output_tokens=usage.completion_tokens, total_tokens=usage.total_tokens, ) span.__exit__(None, None, None) return new_iterator() return new_huggingface_task
HuggingfaceHubIntegration
python
bokeh__bokeh
src/bokeh/models/map_plots.py
{ "start": 4771, "end": 7567 }
class ____(MapPlot): ''' A Bokeh Plot with a `Google Map`_ displayed underneath. Data placed on this plot should be specified in decimal lat/lon coordinates e.g. ``(37.123, -122.404)``. It will be automatically converted into the web mercator projection to display properly over google maps tiles. The ``api_key`` property must be configured with a Google API Key in order for ``GMapPlot`` to function. The key will be stored in the Bokeh Document JSON. Note that Google Maps exert explicit control over aspect ratios at all times, which imposes some limitations on ``GMapPlot``: * Only ``Range1d`` ranges are supported. Attempting to use other range types will result in an error. * Usage of ``BoxZoomTool`` is incompatible with ``GMapPlot``. Adding a ``BoxZoomTool`` will have no effect. .. _Google Map: https://www.google.com/maps/ ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) # TODO (bev) map plot might not have these @error(REQUIRED_RANGE) def _check_required_range(self): pass @warning(MISSING_RENDERERS) def _check_missing_renderers(self): pass @error(MISSING_GOOGLE_API_KEY) def _check_missing_google_api_key(self): if self.api_key is None: return str(self) map_options = Instance(GMapOptions, help=""" Options for displaying the plot. """) border_fill_color = Override(default="#ffffff") background_fill_alpha = Override(default=0.0) api_key = Required(Bytes, help=""" Google Maps API requires an API key. See https://developers.google.com/maps/documentation/javascript/get-api-key for more information on how to obtain your own. """).accepts(String, lambda val: val.encode("utf-8")) api_version = String(default="weekly", help=""" The version of Google Maps API to use. See https://developers.google.com/maps/documentation/javascript/versions for more information. .. note:: Changing this value may result in broken map rendering. """) x_range = Override(default=InstanceDefault(Range1d)) y_range = Override(default=InstanceDefault(Range1d)) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
GMapPlot
python
eth-brownie__brownie
brownie/_gui/opcodes.py
{ "start": 6017, "end": 7501 }
class ____(ToggleButton): def __init__(self, parent): super().__init__(parent, "Scope", "s") self.oplist = self.root.main.oplist def toggle_on(self): try: op = self.oplist.selection()[0] except IndexError: return False if self.oplist.item(op, "tags")[0] == "NoSource": return False pc = self.root.pcMap[op] for key, value in sorted(self.root.pcMap.items(), key=lambda k: int(k[0])): if ( "path" not in value or value["path"] != pc["path"] or not is_inside_offset(value["offset"], pc["offset"]) ): self.oplist.detach(key) else: self.oplist.move(key, "", key) self.oplist.see(op) self.root.main.note.apply_scope(*pc["offset"]) return True def toggle_off(self): self.root.main.note.clear_scope() for i in sorted(self.root.pcMap, key=lambda k: int(k)): self.oplist.move(i, "", i) if self.oplist.selection(): self.oplist.see(self.oplist.selection()[0]) def _get_targets(pc_map, pc): targets = [] for key, value in pc_map.items(): if int(value.get("value", "0"), 16) != int(pc): continue next_pc = str(int(key) + int(value["op"][4:]) + 1) if pc_map[next_pc]["op"] in ("JUMP", "JUMPI"): targets.append(next_pc) return targets
ScopingButton
python
getsentry__sentry
src/sentry/api/serializers/models/project_key.py
{ "start": 558, "end": 802 }
class ____(TypedDict): secret: str public: str csp: str security: str minidump: str nel: str unreal: str crons: str cdn: str playstation: str integration: str otlp_traces: str otlp_logs: str
DSN
python
vyperlang__vyper
vyper/exceptions.py
{ "start": 8162, "end": 8261 }
class ____(VyperException): """Reference to an attribute that does not exist."""
UnknownAttribute
python
astropy__astropy
astropy/coordinates/representation/spherical.py
{ "start": 47175, "end": 51892 }
class ____(BaseSphericalCosLatDifferential): """Differential(s) of points on a unit sphere. Parameters ---------- d_lon_coslat, d_lat : `~astropy.units.Quantity` The longitude and latitude of the differentials. copy : bool, optional If `True` (default), arrays will be copied. If `False`, arrays will be references, though possibly broadcast to ensure matching shapes. """ base_representation = UnitSphericalRepresentation attr_classes = {"d_lon_coslat": u.Quantity, "d_lat": u.Quantity} @classproperty def _dimensional_differential(cls): return SphericalCosLatDifferential def __init__(self, d_lon_coslat, d_lat=None, copy=True): super().__init__(d_lon_coslat, d_lat, copy=copy) if not self._d_lon_coslat.unit.is_equivalent(self._d_lat.unit): raise u.UnitsError("d_lon_coslat and d_lat should have equivalent units.") @classmethod def from_cartesian(cls, other, base): # Go via the dimensional equivalent, so that the longitude and latitude # differentials correctly take into account the norm of the base. dimensional = cls._dimensional_differential.from_cartesian(other, base) return dimensional.represent_as(cls) def to_cartesian(self, base): if isinstance(base, SphericalRepresentation): scale = base.distance elif isinstance(base, PhysicsSphericalRepresentation): scale = base.r else: return super().to_cartesian(base) base = base.represent_as(UnitSphericalRepresentation) return scale * super().to_cartesian(base) def represent_as(self, other_class, base=None): # Only have enough information to represent other unit-spherical. if issubclass(other_class, UnitSphericalDifferential): return other_class(self._d_lon(base), self.d_lat) return super().represent_as(other_class, base) @classmethod def from_representation(cls, representation, base=None): # All spherical differentials can be done without going to Cartesian, # though w/o CosLat needs base for the latitude. if isinstance(representation, SphericalCosLatDifferential): return cls(representation.d_lon_coslat, representation.d_lat) elif isinstance( representation, (SphericalDifferential, UnitSphericalDifferential) ): d_lon_coslat = cls._get_d_lon_coslat(representation.d_lon, base) return cls(d_lon_coslat, representation.d_lat) elif isinstance(representation, PhysicsSphericalDifferential): d_lon_coslat = cls._get_d_lon_coslat(representation.d_phi, base) return cls(d_lon_coslat, -representation.d_theta) return super().from_representation(representation, base) def transform(self, matrix, base, transformed_base): """Transform differential using a 3x3 matrix in a Cartesian basis. This returns a new differential and does not modify the original one. Parameters ---------- matrix : (3,3) array-like A 3x3 (or stack thereof) matrix, such as a rotation matrix. base : instance of ``cls.base_representation`` Base relative to which the differentials are defined. If the other class is a differential representation, the base will be converted to its ``base_representation``. transformed_base : instance of ``cls.base_representation`` Base relative to which the transformed differentials are defined. If the other class is a differential representation, the base will be converted to its ``base_representation``. """ # the transformation matrix does not need to be a rotation matrix, # so the unit-distance is not guaranteed. For speed, we check if the # matrix is in O(3) and preserves lengths. if np.all(is_rotation_or_reflection(matrix)): # remain in unit-rep # TODO! implement without Cartesian intermediate step. diff = super().transform(matrix, base, transformed_base) else: # switch to dimensional representation du = self.d_lat.unit / base.lat.unit # derivative unit diff = self._dimensional_differential( d_lon_coslat=self.d_lon_coslat, d_lat=self.d_lat, d_distance=0 * du ).transform(matrix, base, transformed_base) return diff def _scale_operation(self, op, *args, scaled_base=False): if scaled_base: return self.copy() else: return super()._scale_operation(op, *args)
UnitSphericalCosLatDifferential
python
pytorch__pytorch
torch/nn/modules/loss.py
{ "start": 4565, "end": 10950 }
class ____(_WeightedLoss): r"""The negative log likelihood loss. It is useful to train a classification problem with `C` classes. If provided, the optional argument :attr:`weight` should be a 1D Tensor assigning weight to each of the classes. This is particularly useful when you have an unbalanced training set. The `input` given through a forward call is expected to contain log-probabilities of each class. `input` has to be a Tensor of size either :math:`(minibatch, C)` or :math:`(minibatch, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1` for the `K`-dimensional case. The latter is useful for higher dimension inputs, such as computing NLL loss per-pixel for 2D images. Obtaining log-probabilities in a neural network is easily achieved by adding a `LogSoftmax` layer in the last layer of your network. You may use `CrossEntropyLoss` instead, if you prefer not to add an extra layer. The `target` that this loss expects should be a class index in the range :math:`[0, C-1]` where `C = number of classes`; if `ignore_index` is specified, this loss also accepts this class index (this index may not necessarily be in the class range). The unreduced (i.e. with :attr:`reduction` set to ``'none'``) loss can be described as: .. math:: \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \\ l_n = - w_{y_n} x_{n,y_n}, \\ w_{c} = \text{weight}[c] \cdot \mathbb{1}\{c \not= \text{ignore\_index}\}, where :math:`x` is the input, :math:`y` is the target, :math:`w` is the weight, and :math:`N` is the batch size. If :attr:`reduction` is not ``'none'`` (default ``'mean'``), then .. math:: \ell(x, y) = \begin{cases} \sum_{n=1}^N \frac{1}{\sum_{n=1}^N w_{y_n}} l_n, & \text{if reduction} = \text{`mean';}\\ \sum_{n=1}^N l_n, & \text{if reduction} = \text{`sum'.} \end{cases} Args: weight (Tensor, optional): a manual rescaling weight given to each class. If given, it has to be a Tensor of size `C`. Otherwise, it is treated as if having all ones. size_average (bool, optional): Deprecated (see :attr:`reduction`). By default, the losses are averaged over each loss element in the batch. Note that for some losses, there are multiple elements per sample. If the field :attr:`size_average` is set to ``False``, the losses are instead summed for each minibatch. Ignored when :attr:`reduce` is ``False``. Default: ``None`` ignore_index (int, optional): Specifies a target value that is ignored and does not contribute to the input gradient. When :attr:`size_average` is ``True``, the loss is averaged over non-ignored targets. reduce (bool, optional): Deprecated (see :attr:`reduction`). By default, the losses are averaged or summed over observations for each minibatch depending on :attr:`size_average`. When :attr:`reduce` is ``False``, returns a loss per batch element instead and ignores :attr:`size_average`. Default: ``None`` reduction (str, optional): Specifies the reduction to apply to the output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied, ``'mean'``: the weighted mean of the output is taken, ``'sum'``: the output will be summed. Note: :attr:`size_average` and :attr:`reduce` are in the process of being deprecated, and in the meantime, specifying either of those two args will override :attr:`reduction`. Default: ``'mean'`` Shape:: - Input: :math:`(N, C)` or :math:`(C)`, where `C = number of classes`, `N = batch size`, or :math:`(N, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of `K`-dimensional loss. - Target: :math:`(N)` or :math:`()`, where each value is :math:`0 \leq \text{targets}[i] \leq C-1`, or :math:`(N, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of K-dimensional loss. - Output: If :attr:`reduction` is ``'none'``, shape :math:`(N)` or :math:`(N, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of K-dimensional loss. Otherwise, scalar. Examples: >>> log_softmax = nn.LogSoftmax(dim=1) >>> loss_fn = nn.NLLLoss() >>> # input to NLLLoss is of size N x C = 3 x 5 >>> input = torch.randn(3, 5, requires_grad=True) >>> # each element in target must have 0 <= value < C >>> target = torch.tensor([1, 0, 4]) >>> loss = loss_fn(log_softmax(input), target) >>> loss.backward() >>> >>> >>> # 2D loss example (used, for example, with image inputs) >>> N, C = 5, 4 >>> loss_fn = nn.NLLLoss() >>> data = torch.randn(N, 16, 10, 10) >>> conv = nn.Conv2d(16, C, (3, 3)) >>> log_softmax = nn.LogSoftmax(dim=1) >>> # output of conv forward is of shape [N, C, 8, 8] >>> output = log_softmax(conv(data)) >>> # each element in target must have 0 <= value < C >>> target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C) >>> # input to NLLLoss is of size N x C x height (8) x width (8) >>> loss = loss_fn(output, target) >>> loss.backward() """ __constants__ = ["ignore_index", "reduction"] ignore_index: int def __init__( self, weight: Optional[Tensor] = None, size_average=None, ignore_index: int = -100, reduce=None, reduction: str = "mean", ) -> None: super().__init__(weight, size_average, reduce, reduction) self.ignore_index = ignore_index def forward(self, input: Tensor, target: Tensor) -> Tensor: """ Runs the forward pass. """ return F.nll_loss( input, target, weight=self.weight, ignore_index=self.ignore_index, reduction=self.reduction, ) @deprecated( "`NLLLoss2d` has been deprecated. " "Please use `NLLLoss` instead as a drop-in replacement and see " "https://pytorch.org/docs/main/nn.html#torch.nn.NLLLoss for more details.", category=FutureWarning, )
NLLLoss
python
huggingface__transformers
src/transformers/models/lxmert/modeling_lxmert.py
{ "start": 27207, "end": 27747 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.transform_act_fn = ACT2FN[config.hidden_act] self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=1e-12) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states
LxmertPredictionHeadTransform
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/vector/vectorize_observation.py
{ "start": 603, "end": 4700 }
class ____(VectorObservationWrapper): """Transforms an observation via a function provided to the wrapper. This function allows the manual specification of the vector-observation function as well as the single-observation function. This is desirable when, for example, it is possible to process vector observations in parallel or via other more optimized methods. Otherwise, the ``VectorizeTransformObservation`` should be used instead, where only ``single_func`` needs to be defined. Example - Without observation transformation: >>> import gymnasium as gym >>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync") >>> obs, info = envs.reset(seed=123) >>> obs array([[ 0.01823519, -0.0446179 , -0.02796401, -0.03156282], [ 0.02852531, 0.02858594, 0.0469136 , 0.02480598], [ 0.03517495, -0.000635 , -0.01098382, -0.03203924]], dtype=float32) >>> envs.close() Example - With observation transformation: >>> import gymnasium as gym >>> from gymnasium.spaces import Box >>> def scale_and_shift(obs): ... return (obs - 1.0) * 2.0 ... >>> import gymnasium as gym >>> envs = gym.make_vec("CartPole-v1", num_envs=3, vectorization_mode="sync") >>> new_obs_space = Box(low=envs.observation_space.low, high=envs.observation_space.high) >>> envs = TransformObservation(envs, func=scale_and_shift, observation_space=new_obs_space) >>> obs, info = envs.reset(seed=123) >>> obs array([[-1.9635296, -2.0892358, -2.055928 , -2.0631256], [-1.9429494, -1.9428282, -1.9061728, -1.9503881], [-1.9296501, -2.00127 , -2.0219676, -2.0640786]], dtype=float32) >>> envs.close() """ def __init__( self, env: VectorEnv, func: Callable[[ObsType], Any], observation_space: Space | None = None, single_observation_space: Space | None = None, ): """Constructor for the transform observation wrapper. Args: env: The vector environment to wrap func: A function that will transform the vector observation. If this transformed observation is outside the observation space of ``env.observation_space`` then provide an ``observation_space``. observation_space: The observation spaces of the wrapper. If None, then it is computed from ``single_observation_space``. If ``single_observation_space`` is not provided either, then it is assumed to be the same as ``env.observation_space``. single_observation_space: The observation space of the non-vectorized environment. If None, then it is assumed the same as ``env.single_observation_space``. """ super().__init__(env) if observation_space is None: if single_observation_space is not None: self.single_observation_space = single_observation_space self.observation_space = batch_space( single_observation_space, self.num_envs ) else: self.observation_space = observation_space if single_observation_space is not None: self._single_observation_space = single_observation_space # TODO: We could compute single_observation_space from the observation_space if only the latter is provided and avoid the warning below. if self.observation_space != batch_space( self.single_observation_space, self.num_envs ): warn( f"For {env}, the observation space and the batched single observation space don't match as expected, observation_space={env.observation_space}, batched single_observation_space={batch_space(self.single_observation_space, self.num_envs)}" ) self.func = func def observations(self, observations: ObsType) -> ObsType: """Apply function to the vector observation.""" return self.func(observations)
TransformObservation
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/contrib/regular_languages/regex_parser.py
{ "start": 2974, "end": 7732 }
class ____(Node): def __init__( self, childnode: Node, min_repeat: int = 0, max_repeat: int | None = None, greedy: bool = True, ) -> None: self.childnode = childnode self.min_repeat = min_repeat self.max_repeat = max_repeat self.greedy = greedy def __repr__(self) -> str: return f"{self.__class__.__name__}(childnode={self.childnode!r})" def tokenize_regex(input: str) -> list[str]: """ Takes a string, representing a regular expression as input, and tokenizes it. :param input: string, representing a regular expression. :returns: List of tokens. """ # Regular expression for tokenizing other regular expressions. p = re.compile( r"""^( \(\?P\<[a-zA-Z0-9_-]+\> | # Start of named group. \(\?#[^)]*\) | # Comment \(\?= | # Start of lookahead assertion \(\?! | # Start of negative lookahead assertion \(\?<= | # If preceded by. \(\?< | # If not preceded by. \(?: | # Start of group. (non capturing.) \( | # Start of group. \(?[iLmsux] | # Flags. \(?P=[a-zA-Z]+\) | # Back reference to named group \) | # End of group. \{[^{}]*\} | # Repetition \*\? | \+\? | \?\?\ | # Non greedy repetition. \* | \+ | \? | # Repetition \#.*\n | # Comment \\. | # Character group. \[ ( [^\]\\] | \\.)* \] | [^(){}] | . )""", re.VERBOSE, ) tokens = [] while input: m = p.match(input) if m: token, input = input[: m.end()], input[m.end() :] if not token.isspace(): tokens.append(token) else: raise Exception("Could not tokenize input regex.") return tokens def parse_regex(regex_tokens: list[str]) -> Node: """ Takes a list of tokens from the tokenizer, and returns a parse tree. """ # We add a closing brace because that represents the final pop of the stack. tokens: list[str] = [")"] + regex_tokens[::-1] def wrap(lst: list[Node]) -> Node: """Turn list into sequence when it contains several items.""" if len(lst) == 1: return lst[0] else: return NodeSequence(lst) def _parse() -> Node: or_list: list[list[Node]] = [] result: list[Node] = [] def wrapped_result() -> Node: if or_list == []: return wrap(result) else: or_list.append(result) return AnyNode([wrap(i) for i in or_list]) while tokens: t = tokens.pop() if t.startswith("(?P<"): variable = Variable(_parse(), varname=t[4:-1]) result.append(variable) elif t in ("*", "*?"): greedy = t == "*" result[-1] = Repeat(result[-1], greedy=greedy) elif t in ("+", "+?"): greedy = t == "+" result[-1] = Repeat(result[-1], min_repeat=1, greedy=greedy) elif t in ("?", "??"): if result == []: raise Exception("Nothing to repeat." + repr(tokens)) else: greedy = t == "?" result[-1] = Repeat( result[-1], min_repeat=0, max_repeat=1, greedy=greedy ) elif t == "|": or_list.append(result) result = [] elif t in ("(", "(?:"): result.append(_parse()) elif t == "(?!": result.append(Lookahead(_parse(), negative=True)) elif t == "(?=": result.append(Lookahead(_parse(), negative=False)) elif t == ")": return wrapped_result() elif t.startswith("#"): pass elif t.startswith("{"): # TODO: implement! raise Exception(f"{t}-style repetition not yet supported") elif t.startswith("(?"): raise Exception(f"{t!r} not supported") elif t.isspace(): pass else: result.append(Regex(t)) raise Exception("Expecting ')' token") result = _parse() if len(tokens) != 0: raise Exception("Unmatched parentheses.") else: return result
Repeat
python
marshmallow-code__marshmallow
tests/base.py
{ "start": 544, "end": 1934 }
class ____(Enum): date_1 = dt.date(2004, 2, 29) date_2 = dt.date(2008, 2, 29) date_3 = dt.date(2012, 2, 29) ALL_FIELDS = [ fields.String, fields.Integer, fields.Boolean, fields.Float, fields.DateTime, fields.Time, fields.Date, fields.TimeDelta, fields.Dict, fields.Url, fields.Email, fields.UUID, fields.Decimal, fields.IP, fields.IPv4, fields.IPv6, fields.IPInterface, fields.IPv4Interface, fields.IPv6Interface, functools.partial(fields.Enum, GenderEnum), functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), ] ##### Custom asserts ##### def assert_date_equal(d1: dt.date, d2: dt.date) -> None: assert d1.year == d2.year assert d1.month == d2.month assert d1.day == d2.day def assert_time_equal(t1: dt.time, t2: dt.time) -> None: assert t1.hour == t2.hour assert t1.minute == t2.minute assert t1.second == t2.second assert t1.microsecond == t2.microsecond ##### Validation ##### def predicate( func: typing.Callable[[typing.Any], bool], ) -> typing.Callable[[typing.Any], None]: def validate(value: typing.Any) -> None: if func(value) is False: raise ValidationError("Invalid value.") return validate ##### Models #####
DateEnum
python
pypa__pip
src/pip/_internal/index/package_finder.py
{ "start": 21639, "end": 39158 }
class ____: """This finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. """ def __init__( self, link_collector: LinkCollector, target_python: TargetPython, allow_yanked: bool, format_control: FormatControl | None = None, candidate_prefs: CandidatePreferences | None = None, ignore_requires_python: bool | None = None, ) -> None: """ This constructor is primarily meant to be used by the create() class method and from tests. :param format_control: A FormatControl object, used to control the selection of source packages / binary packages when consulting the index and links. :param candidate_prefs: Options to use when creating a CandidateEvaluator object. """ if candidate_prefs is None: candidate_prefs = CandidatePreferences() format_control = format_control or FormatControl(set(), set()) self._allow_yanked = allow_yanked self._candidate_prefs = candidate_prefs self._ignore_requires_python = ignore_requires_python self._link_collector = link_collector self._target_python = target_python self.format_control = format_control # These are boring links that have already been logged somehow. self._logged_links: set[tuple[Link, LinkType, str]] = set() # Cache of the result of finding candidates self._all_candidates: dict[str, list[InstallationCandidate]] = {} self._best_candidates: dict[ tuple[str, specifiers.BaseSpecifier | None, Hashes | None], BestCandidateResult, ] = {} # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. @classmethod def create( cls, link_collector: LinkCollector, selection_prefs: SelectionPreferences, target_python: TargetPython | None = None, ) -> PackageFinder: """Create a PackageFinder. :param selection_prefs: The candidate selection preferences, as a SelectionPreferences object. :param target_python: The target Python interpreter to use when checking compatibility. If None (the default), a TargetPython object will be constructed from the running Python. """ if target_python is None: target_python = TargetPython() candidate_prefs = CandidatePreferences( prefer_binary=selection_prefs.prefer_binary, allow_all_prereleases=selection_prefs.allow_all_prereleases, ) return cls( candidate_prefs=candidate_prefs, link_collector=link_collector, target_python=target_python, allow_yanked=selection_prefs.allow_yanked, format_control=selection_prefs.format_control, ignore_requires_python=selection_prefs.ignore_requires_python, ) @property def target_python(self) -> TargetPython: return self._target_python @property def search_scope(self) -> SearchScope: return self._link_collector.search_scope @search_scope.setter def search_scope(self, search_scope: SearchScope) -> None: self._link_collector.search_scope = search_scope @property def find_links(self) -> list[str]: return self._link_collector.find_links @property def index_urls(self) -> list[str]: return self.search_scope.index_urls @property def proxy(self) -> str | None: return self._link_collector.session.pip_proxy @property def trusted_hosts(self) -> Iterable[str]: for host_port in self._link_collector.session.pip_trusted_origins: yield build_netloc(*host_port) @property def custom_cert(self) -> str | None: # session.verify is either a boolean (use default bundle/no SSL # verification) or a string path to a custom CA bundle to use. We only # care about the latter. verify = self._link_collector.session.verify return verify if isinstance(verify, str) else None @property def client_cert(self) -> str | None: cert = self._link_collector.session.cert assert not isinstance(cert, tuple), "pip only supports PEM client certs" return cert @property def allow_all_prereleases(self) -> bool: return self._candidate_prefs.allow_all_prereleases def set_allow_all_prereleases(self) -> None: self._candidate_prefs.allow_all_prereleases = True @property def prefer_binary(self) -> bool: return self._candidate_prefs.prefer_binary def set_prefer_binary(self) -> None: self._candidate_prefs.prefer_binary = True def requires_python_skipped_reasons(self) -> list[str]: reasons = { detail for _, result, detail in self._logged_links if result == LinkType.requires_python_mismatch } return sorted(reasons) def make_link_evaluator(self, project_name: str) -> LinkEvaluator: canonical_name = canonicalize_name(project_name) formats = self.format_control.get_allowed_formats(canonical_name) return LinkEvaluator( project_name=project_name, canonical_name=canonical_name, formats=formats, target_python=self._target_python, allow_yanked=self._allow_yanked, ignore_requires_python=self._ignore_requires_python, ) def _sort_links(self, links: Iterable[Link]) -> list[Link]: """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen: set[Link] = set() for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None: entry = (link, result, detail) if entry not in self._logged_links: # Put the link at the end so the reason is more visible and because # the link string is usually very long. logger.debug("Skipping link: %s: %s", detail, link) self._logged_links.add(entry) def get_install_candidate( self, link_evaluator: LinkEvaluator, link: Link ) -> InstallationCandidate | None: """ If the link is a candidate for install, convert it to an InstallationCandidate and return it. Otherwise, return None. """ result, detail = link_evaluator.evaluate_link(link) if result != LinkType.candidate: self._log_skipped_link(link, result, detail) return None try: return InstallationCandidate( name=link_evaluator.project_name, link=link, version=detail, ) except InvalidVersion: return None def evaluate_links( self, link_evaluator: LinkEvaluator, links: Iterable[Link] ) -> list[InstallationCandidate]: """ Convert links that are candidates to InstallationCandidate objects. """ candidates = [] for link in self._sort_links(links): candidate = self.get_install_candidate(link_evaluator, link) if candidate is not None: candidates.append(candidate) return candidates def process_project_url( self, project_url: Link, link_evaluator: LinkEvaluator ) -> list[InstallationCandidate]: logger.debug( "Fetching project page and analyzing links: %s", project_url, ) index_response = self._link_collector.fetch_response(project_url) if index_response is None: return [] page_links = list(parse_links(index_response)) with indent_log(): package_links = self.evaluate_links( link_evaluator, links=page_links, ) return package_links def find_all_candidates(self, project_name: str) -> list[InstallationCandidate]: """Find all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See LinkEvaluator.evaluate_link() for details on which files are accepted. """ if project_name in self._all_candidates: return self._all_candidates[project_name] link_evaluator = self.make_link_evaluator(project_name) collected_sources = self._link_collector.collect_sources( project_name=project_name, candidates_from_page=functools.partial( self.process_project_url, link_evaluator=link_evaluator, ), ) page_candidates_it = itertools.chain.from_iterable( source.page_candidates() for sources in collected_sources for source in sources if source is not None ) page_candidates = list(page_candidates_it) file_links_it = itertools.chain.from_iterable( source.file_links() for sources in collected_sources for source in sources if source is not None ) file_candidates = self.evaluate_links( link_evaluator, sorted(file_links_it, reverse=True), ) if logger.isEnabledFor(logging.DEBUG) and file_candidates: paths = [] for candidate in file_candidates: assert candidate.link.url # we need to have a URL try: paths.append(candidate.link.file_path) except Exception: paths.append(candidate.link.url) # it's not a local file logger.debug("Local files found: %s", ", ".join(paths)) # This is an intentional priority ordering self._all_candidates[project_name] = file_candidates + page_candidates return self._all_candidates[project_name] def make_candidate_evaluator( self, project_name: str, specifier: specifiers.BaseSpecifier | None = None, hashes: Hashes | None = None, ) -> CandidateEvaluator: """Create a CandidateEvaluator object to use.""" candidate_prefs = self._candidate_prefs return CandidateEvaluator.create( project_name=project_name, target_python=self._target_python, prefer_binary=candidate_prefs.prefer_binary, allow_all_prereleases=candidate_prefs.allow_all_prereleases, specifier=specifier, hashes=hashes, ) def find_best_candidate( self, project_name: str, specifier: specifiers.BaseSpecifier | None = None, hashes: Hashes | None = None, ) -> BestCandidateResult: """Find matches for the given project and specifier. :param specifier: An optional object implementing `filter` (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable versions. :return: A `BestCandidateResult` instance. """ if (project_name, specifier, hashes) in self._best_candidates: return self._best_candidates[project_name, specifier, hashes] candidates = self.find_all_candidates(project_name) candidate_evaluator = self.make_candidate_evaluator( project_name=project_name, specifier=specifier, hashes=hashes, ) self._best_candidates[project_name, specifier, hashes] = ( candidate_evaluator.compute_best_candidate(candidates) ) return self._best_candidates[project_name, specifier, hashes] def find_requirement( self, req: InstallRequirement, upgrade: bool ) -> InstallationCandidate | None: """Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a InstallationCandidate if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise """ name = req.name assert name is not None, "find_requirement() called with no name" hashes = req.hashes(trust_internet=False) best_candidate_result = self.find_best_candidate( name, specifier=req.specifier, hashes=hashes, ) best_candidate = best_candidate_result.best_candidate installed_version: _BaseVersion | None = None if req.satisfied_by is not None: installed_version = req.satisfied_by.version def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str: # This repeated parse_version and str() conversion is needed to # handle different vendoring sources from pip and pkg_resources. # If we stop using the pkg_resources provided specifier and start # using our own, we can drop the cast to str(). return ( ", ".join( sorted( {str(c.version) for c in cand_iter}, key=parse_version, ) ) or "none" ) if installed_version is None and best_candidate is None: logger.critical( "Could not find a version that satisfies the requirement %s " "(from versions: %s)", req, _format_versions(best_candidate_result.all_candidates), ) raise DistributionNotFound(f"No matching distribution found for {req}") def _should_install_candidate( candidate: InstallationCandidate | None, ) -> TypeGuard[InstallationCandidate]: if installed_version is None: return True if best_candidate is None: return False return best_candidate.version > installed_version if not upgrade and installed_version is not None: if _should_install_candidate(best_candidate): logger.debug( "Existing installed version (%s) satisfies requirement " "(most up-to-date version is %s)", installed_version, best_candidate.version, ) else: logger.debug( "Existing installed version (%s) is most up-to-date and " "satisfies requirement", installed_version, ) return None if _should_install_candidate(best_candidate): logger.debug( "Using version %s (newest of versions: %s)", best_candidate.version, _format_versions(best_candidate_result.applicable_candidates), ) return best_candidate # We have an existing version, and its the best version logger.debug( "Installed version (%s) is most up-to-date (past versions: %s)", installed_version, _format_versions(best_candidate_result.applicable_candidates), ) raise BestVersionAlreadyInstalled def _find_name_version_sep(fragment: str, canonical_name: str) -> int: """Find the separator's index based on the package's canonical name. :param fragment: A <package>+<version> filename "fragment" (stem) or egg fragment. :param canonical_name: The package's canonical name. This function is needed since the canonicalized name does not necessarily have the same length as the egg info's name part. An example:: >>> fragment = 'foo__bar-1.0' >>> canonical_name = 'foo-bar' >>> _find_name_version_sep(fragment, canonical_name) 8 """ # Project name and version must be separated by one single dash. Find all # occurrences of dashes; if the string in front of it matches the canonical # name, this is the one separating the name and version parts. for i, c in enumerate(fragment): if c != "-": continue if canonicalize_name(fragment[:i]) == canonical_name: return i raise ValueError(f"{fragment} does not match {canonical_name}") def _extract_version_from_fragment(fragment: str, canonical_name: str) -> str | None: """Parse the version string from a <package>+<version> filename "fragment" (stem) or egg fragment. :param fragment: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. """ try: version_start = _find_name_version_sep(fragment, canonical_name) + 1 except ValueError: return None version = fragment[version_start:] if not version: return None return version
PackageFinder
python
getsentry__sentry
src/sentry/issue_detection/detectors/uncompressed_asset_detector.py
{ "start": 715, "end": 6567 }
class ____(PerformanceDetector): """ Checks for large assets that are affecting load time. """ __slots__ = ("any_compression",) settings_key = DetectorType.UNCOMPRESSED_ASSETS type = DetectorType.UNCOMPRESSED_ASSETS def __init__(self, settings: dict[DetectorType, Any], event: dict[str, Any]) -> None: super().__init__(settings, event) self.any_compression = False def visit_span(self, span: Span) -> None: op = span.get("op", None) description = span.get("description", "") if not op: return allowed_span_ops = self.settings.get("allowed_span_ops") if op not in allowed_span_ops: return data = span.get("data", None) # TODO(nar): The sentence-style keys can be removed once SDK adoption has increased and # we are receiving snake_case keys consistently, likely beyond October 2023 transfer_size = data and ( data.get("http.response_transfer_size", None) or data.get("Transfer Size", None) ) encoded_body_size = data and ( data.get("http.response_content_length", None) or data.get("Encoded Body Size", None) ) decoded_body_size = data and ( data.get("http.decoded_response_content_length", None) or data.get("Decoded Body Size", None) ) if not (encoded_body_size and decoded_body_size and transfer_size): return # Ignore assets from cache, either directly (nothing transferred) or via # a 304 Not Modified response (transfer is smaller than asset size). if transfer_size <= 0 or transfer_size < encoded_body_size: return # Ignore assets that are already compressed. if encoded_body_size != decoded_body_size: # Met criteria for a compressed span somewhere in the event. self.any_compression = True return # Ignore assets that aren't big enough to worry about. size_threshold_bytes = self.settings.get("size_threshold_bytes") if encoded_body_size < size_threshold_bytes: return # Ignore assets with certain file extensions normalized_description = description.strip().upper() extension = EXTENSION_REGEX.search(normalized_description) if extension and extension.group(1) not in FILE_EXTENSION_ALLOWLIST: return # Ignore assets under a certain duration threshold if get_span_duration(span).total_seconds() * 1000 <= self.settings.get( "duration_threshold" ): return fingerprint = self._fingerprint(span) span_id = span.get("span_id", None) if self.stored_problems.get(fingerprint): logging.info( "Multiple occurrences detected for fingerprint", extra={"detector": self.settings_key}, ) return if fingerprint and span_id: self.stored_problems[fingerprint] = PerformanceProblem( fingerprint=fingerprint, op=op, desc=description, parent_span_ids=[], type=PerformanceUncompressedAssetsGroupType, cause_span_ids=[], offender_span_ids=[span_id], evidence_data={ "op": op, "parent_span_ids": [], "cause_span_ids": [], "offender_span_ids": [span_id], "transaction_name": self._event.get("description", ""), "repeating_spans": get_span_evidence_value(span), "repeating_spans_compact": get_span_evidence_value(span, include_op=False), "num_repeating_spans": str(len(span_id)), }, evidence_display=[ IssueEvidence( name="Offending Spans", value=get_notification_attachment_body( op, description, ), # Has to be marked important to be displayed in the notifications important=True, ) ], ) def _fingerprint(self, span: Span) -> str: resource_span = fingerprint_resource_span(span) return f"1-{PerformanceUncompressedAssetsGroupType.type_id}-{resource_span}" def is_creation_allowed_for_organization(self, organization: Organization) -> bool: return True def is_creation_allowed_for_project(self, project: Project) -> bool: return self.settings["detection_enabled"] @classmethod def is_event_eligible(cls, event: dict[str, Any], project: Project | None = None) -> bool: tags = event.get("tags", []) browser_name = next( ( tag[1] for tag in tags if tag is not None and tag[0] == "browser.name" and len(tag) == 2 and tag[1] is not None ), "", ) if browser_name.lower() in [ "chrome", "firefox", "safari", "edge", ]: # Only use major browsers as some mobile browser may be responsible for not sending accept-content header, # which isn't fixable since you can't control what headers your users are sending. # This can be extended later. return True return False def on_complete(self) -> None: if not self.any_compression: # Must have a compressed asset in the event to emit this perf problem. self.stored_problems = {}
UncompressedAssetSpanDetector
python
celery__celery
t/unit/app/test_beat.py
{ "start": 32959, "end": 33558 }
class ____: def test_maybe_make_aware(self): x = schedule(10, app=self.app) x.utc_enabled = True d = x.maybe_make_aware(datetime.now(timezone.utc)) assert d.tzinfo x.utc_enabled = False d2 = x.maybe_make_aware(datetime.now(timezone.utc)) assert d2.tzinfo def test_to_local(self): x = schedule(10, app=self.app) x.utc_enabled = True d = x.to_local(datetime.now()) assert d.tzinfo is None x.utc_enabled = False d = x.to_local(datetime.now(timezone.utc)) assert d.tzinfo
test_schedule
python
pandas-dev__pandas
pandas/tests/series/test_arithmetic.py
{ "start": 30347, "end": 33110 }
class ____: @pytest.mark.parametrize("box", [list, tuple, np.array, Index, Series, pd.array]) @pytest.mark.parametrize("flex", [True, False]) def test_series_ops_name_retention(self, flex, box, names, all_binary_operators): # GH#33930 consistent name-retention op = all_binary_operators left = Series(range(10), name=names[0]) right = Series(range(10), name=names[1]) name = op.__name__.strip("_") is_logical = name in ["and", "rand", "xor", "rxor", "or", "ror"] msg = ( r"Logical ops \(and, or, xor\) between Pandas objects and " "dtype-less sequences" ) right = box(right) if flex: if is_logical: # Series doesn't have these as flex methods return result = getattr(left, name)(right) else: if is_logical and box in [list, tuple]: with pytest.raises(TypeError, match=msg): # GH#52264 logical ops with dtype-less sequences deprecated op(left, right) return result = op(left, right) assert isinstance(result, Series) if box in [Index, Series]: assert result.name is names[2] or result.name == names[2] else: assert result.name is names[0] or result.name == names[0] def test_binop_maybe_preserve_name(self, datetime_series): # names match, preserve result = datetime_series * datetime_series assert result.name == datetime_series.name result = datetime_series.mul(datetime_series) assert result.name == datetime_series.name result = datetime_series * datetime_series[:-2] assert result.name == datetime_series.name # names don't match, don't preserve cp = datetime_series.copy() cp.name = "something else" result = datetime_series + cp assert result.name is None result = datetime_series.add(cp) assert result.name is None ops = ["add", "sub", "mul", "div", "truediv", "floordiv", "mod", "pow"] ops = ops + ["r" + op for op in ops] for op in ops: # names match, preserve ser = datetime_series.copy() result = getattr(ser, op)(ser) assert result.name == datetime_series.name # names don't match, don't preserve cp = datetime_series.copy() cp.name = "changed" result = getattr(ser, op)(cp) assert result.name is None def test_scalarop_preserve_name(self, datetime_series): result = datetime_series * 2 assert result.name == datetime_series.name
TestNamePreservation
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/__init__.py
{ "start": 2250, "end": 2382 }
class ____(dict): # NoQA: FURB189 """Docstring.""" def function(foo, *args, **kwds): """Return spam.""" pass
CustomDict
python
django__django
tests/pagination/custom.py
{ "start": 79, "end": 389 }
class ____(Page): def next_page_number(self): if not self.has_next(): return None return super().next_page_number() def previous_page_number(self): if not self.has_previous(): return None return super().previous_page_number()
ValidAdjacentNumsPage
python
huggingface__transformers
src/transformers/models/superglue/image_processing_superglue.py
{ "start": 4810, "end": 5122 }
class ____(ImagesKwargs, total=False): r""" do_grayscale (`bool`, *optional*, defaults to `True`): Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method. """ do_grayscale: bool @requires(backends=("torch",))
SuperGlueImageProcessorKwargs
python
explosion__spaCy
spacy/lang/yo/__init__.py
{ "start": 216, "end": 309 }
class ____(Language): lang = "yo" Defaults = YorubaDefaults __all__ = ["Yoruba"]
Yoruba
python
pytorch__pytorch
torch/_functorch/_aot_autograd/descriptors.py
{ "start": 15103, "end": 15264 }
class ____(AOTInput): """A subclass that classifies AOTInput that can be wrapped by GradAOTOutput""" @dataclasses.dataclass(frozen=True)
DifferentiableAOTInput
python
pallets__itsdangerous
src/itsdangerous/exc.py
{ "start": 87, "end": 436 }
class ____(Exception): """Raised if bad data of any sort was encountered. This is the base for all exceptions that ItsDangerous defines. .. versionadded:: 0.15 """ def __init__(self, message: str): super().__init__(message) self.message = message def __str__(self) -> str: return self.message
BadData
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_with_skeleton.py
{ "start": 15625, "end": 15976 }
class ____ { exampleMethod() { console.log("line1"); } } """ text_node = TextNode( text=text, ) chunks: List[RelatedNodeInfo] = code_splitter.get_nodes_from_documents([text_node]) # Fstrings don't like forward slash double_forward_slash: str = "//" assert ( chunks[0].text == f"""\
Example
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/response_builder/__init__.py
{ "start": 124, "end": 229 }
class ____: @abc.abstractmethod def build(self) -> HttpResponse: pass
AbstractResponseBuilder
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/broadcast_to_ops_test.py
{ "start": 1139, "end": 8114 }
class ____(test_util.TensorFlowTestCase): def testBroadcastToBasic(self): for dtype in [ np.uint8, np.uint16, np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype, dtypes.float8_e5m2.as_numpy_dtype, dtypes.float8_e4m3fn.as_numpy_dtype, ]: with self.session(): x = np.array([1, 2, 3], dtype=dtype) v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3]) v_np = np.broadcast_to(x, [3, 3]) self.assertAllEqual(v_tf, v_np) def testBroadcastToString(self): with self.session(): x = np.array([b"1", b"2", b"3"]) v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3]) v_np = np.broadcast_to(x, [3, 3]) self.assertAllEqual(v_tf, v_np) def testBroadcastToBool(self): with self.session(): x = np.array([True, False, True], dtype=np.bool_) v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3]) v_np = np.broadcast_to(x, [3, 3]) self.assertAllEqual(v_tf, v_np) def testBroadcastToShape(self): for input_dim in range(1, 6): for output_dim in range(input_dim, 6): with self.cached_session(): input_shape = [2] * input_dim output_shape = [2] * output_dim x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32) v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape) v_np = np.broadcast_to(x, output_shape) self.assertAllEqual(v_tf, v_np) def testBroadcastToShapeInnerDim(self): input_shape = [2, 1, 3] output_shape = [2, 5, 3] with self.cached_session(): x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32) v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape) v_np = np.broadcast_to(x, output_shape) self.assertAllEqual(v_tf, v_np) def testBroadcastToShapeLargerDim(self): input_shape = [2, 1, 3, 2, 2, 2] output_shape = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 15, 3, 2, 2, 2] with self.cached_session(): x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32) v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape) v_np = np.broadcast_to(x, output_shape) self.assertAllEqual(v_tf, v_np) def testBroadcastToShapeLargerDim2(self): input_shape = [2, 1, 3, 2, 2, 2, 1, 1, 1] output_shape = [1, 1, 1, 2, 5, 3, 2, 2, 2, 3, 3, 3] with self.cached_session(): x = np.array(np.random.randint(5, size=input_shape), dtype=np.int32) v_tf = array_ops.broadcast_to(constant_op.constant(x), output_shape) v_np = np.broadcast_to(x, output_shape) self.assertAllEqual(v_tf, v_np) def testBroadcastToScalar(self): with self.session(): x = np.array(1, dtype=np.int32) v_tf = array_ops.broadcast_to(constant_op.constant(x), [3, 3]) v_np = np.broadcast_to(x, [3, 3]) self.assertAllEqual(v_tf, v_np) def testBroadcastScalarToNonScalar(self): with self.session(): x = np.array(1.0, dtype=np.float64) v_tf = array_ops.broadcast_to( constant_op.constant(1.0), [2, 3, 4, 1, 1, 1]) v_np = np.broadcast_to(x, [2, 3, 4, 1, 1, 1]) self.assertAllEqual(v_tf, v_np) def testBroadcastToShapeTypeAndInference(self): for dtype in [dtypes.int32, dtypes.int64]: with self.cached_session(): x = np.array([1, 2, 3]) v_tf = array_ops.broadcast_to( constant_op.constant(x), constant_op.constant([3, 3], dtype=dtype)) shape = v_tf.get_shape().as_list() v_np = np.broadcast_to(x, [3, 3]) self.assertAllEqual(v_tf, v_np) # check shape inference when shape input is constant self.assertAllEqual(shape, v_np.shape) def testBroadcastToBadOutputShape(self): with context.eager_mode(): with self.assertRaisesRegex(errors.InvalidArgumentError, "Unable to broadcast tensor of shape"): self.evaluate( array_ops.broadcast_to( constant_op.constant([0, 1]), constant_op.constant([2, 1]))) def testGradientForScalar(self): x = constant_op.constant(1, dtype=dtypes.float32) def func(x): v = array_ops.broadcast_to(x, [2, 4, 3]) return 2 * v with self.cached_session(): err = gradient_checker_v2.max_error( *gradient_checker_v2.compute_gradient(func, [x])) self.assertLess(err, 1e-4) def testGradientWithSameRank(self): x = constant_op.constant( np.reshape(np.arange(6), (2, 1, 3)), dtype=dtypes.float32) def func(x): v = array_ops.broadcast_to(x, [2, 5, 3]) return 2 * v with self.cached_session(): err = gradient_checker_v2.max_error( *gradient_checker_v2.compute_gradient(func, [x], delta=1e-2)) self.assertLess(err, 1e-4) def testGradientWithIncreasingRank(self): x = constant_op.constant([[1], [2]], dtype=dtypes.float32) def func(x): v = array_ops.broadcast_to(x, [5, 2, 3]) return 2 * v with self.cached_session(): err = gradient_checker_v2.max_error( *gradient_checker_v2.compute_gradient(func, [x])) self.assertLess(err, 1e-4) def testGradientWithBroadcastAllDimensions(self): x = constant_op.constant([1], dtype=dtypes.float32) def func(x): v = array_ops.broadcast_to(x, [5, 2, 3]) return 2 * v with self.cached_session(): err = gradient_checker_v2.max_error( *gradient_checker_v2.compute_gradient(func, [x])) self.assertLess(err, 1e-4) def testGradientWithLargeDim(self): input_shape = [2, 1, 3, 2, 2, 2, 1, 1, 1] output_shape = [1, 1, 1, 2, 5, 3, 2, 2, 2, 3, 3, 3] x = constant_op.constant( np.array(np.random.randn(*input_shape), dtype=np.float32)) def func(x): v = array_ops.broadcast_to(x, output_shape) return 2 * v with self.cached_session(): err = gradient_checker_v2.max_error( *gradient_checker_v2.compute_gradient(func, [x], delta=1e-2)) self.assertLess(err, 1e-4) def testBroadcastToInvalidShape(self): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "110,53,104,147,157,123,5,24,188,40,5,2"): output_shape = [110, 53, 104, 147, 157, 123, 5, 24, 188, 40, 5, 2] x = np.array([1, 2, 3], dtype=np.int32) v = array_ops.broadcast_to(constant_op.constant(x), output_shape) self.evaluate(v) def testBroadcastToInvalidShapeForEmpty(self): with self.assertRaisesIncompatibleShapesError( (ValueError, errors.InvalidArgumentError)): output_shape = [3, 0, 3] x = constant_op.constant(value=[], shape=(3, 0, 5), dtype=np.int32) v = array_ops.broadcast_to(x, output_shape) self.evaluate(v) if __name__ == "__main__": test_lib.main()
BroadcastToTest
python
PrefectHQ__prefect
tests/server/orchestration/api/test_workers.py
{ "start": 57284, "end": 60158 }
class ____: async def test_work_pool_status_with_online_worker(self, client, work_pool): """Work pools with an online work should have a status of READY.""" await client.post( f"/work_pools/{work_pool.name}/workers/heartbeat", json=dict(name="test-worker"), ) response = await client.get(f"/work_pools/{work_pool.name}") assert response.status_code == status.HTTP_200_OK, response.text result = parse_obj_as(WorkPool, response.json()) assert result.status == schemas.statuses.WorkPoolStatus.READY async def test_work_pool_status_with_offline_worker( self, client, work_pool, session, db ): """Work pools with only offline workers should have a status of NOT_READY.""" now = datetime.now(timezone.utc) insert_stmt = db.queries.insert(db.Worker).values( name="old-worker", work_pool_id=work_pool.id, last_heartbeat_time=now - timedelta(minutes=5), ) await session.execute(insert_stmt) await session.commit() response = await client.get(f"/work_pools/{work_pool.name}") result = parse_obj_as(WorkPool, response.json()) assert result.status == schemas.statuses.WorkPoolStatus.NOT_READY async def test_work_pool_status_with_no_workers(self, client, work_pool): """Work pools with no workers should have a status of NOT_READY.""" response = await client.get(f"/work_pools/{work_pool.name}") result = parse_obj_as(WorkPool, response.json()) assert result.status == schemas.statuses.WorkPoolStatus.NOT_READY async def test_work_pool_status_for_paused_work_pool(self, client, work_pool): """Work pools that are paused should have a status of PAUSED.""" # Pause work pool await client.patch(f"/work_pools/{work_pool.name}", json=dict(is_paused=True)) # Heartbeat worker await client.post( f"/work_pools/{work_pool.name}/workers/heartbeat", json=dict(name="test-worker"), ) response = await client.get(f"/work_pools/{work_pool.name}") assert response.status_code == status.HTTP_200_OK, response.text result = parse_obj_as(WorkPool, response.json()) assert result.is_paused assert result.status == schemas.statuses.WorkPoolStatus.PAUSED async def test_work_pool_status_for_prefect_agent_work_pool( self, client, prefect_agent_work_pool ): """Work pools that are Prefect Agent work pools should have `null` for status.""" response = await client.get(f"/work_pools/{prefect_agent_work_pool.name}") assert response.status_code == status.HTTP_200_OK, response.text result = parse_obj_as(WorkPool, response.json()) assert result.status is None
TestWorkPoolStatus
python
getsentry__sentry-python
tests/integrations/beam/test_beam.py
{ "start": 1293, "end": 1399 }
class ____(DoFn): def process(self, x): if x: 1 / 0 return [True]
SimpleFunc
python
xlwings__xlwings
xlwings/constants.py
{ "start": 101783, "end": 102012 }
class ____: xlRangeValueDefault = 10 # from enum XlRangeValueDataType xlRangeValueMSPersistXML = 12 # from enum XlRangeValueDataType xlRangeValueXMLSpreadsheet = 11 # from enum XlRangeValueDataType
RangeValueDataType
python
pypa__warehouse
warehouse/accounts/forms.py
{ "start": 3042, "end": 3512 }
class ____: totp_value = wtforms.StringField( validators=[ wtforms.validators.InputRequired(), PreventNullBytesValidator(), wtforms.validators.Regexp( rf"^ *([0-9] *){{{otp.TOTP_LENGTH}}}$", message=_( "TOTP code must be ${totp_length} digits.", mapping={"totp_length": otp.TOTP_LENGTH}, ), ), ] )
TOTPValueMixin
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 109348, "end": 111247 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, api_token: str, dimensions: list[str], ingest_start: str, metrics: list[str], additional_metrics: Optional[list[str]] = None, until_today: Optional[bool] = None, ): """Airbyte Source for Adjust. Documentation can be found at https://docs.airbyte.com/integrations/sources/adjust Args: name (str): The name of the destination. additional_metrics (Optional[List[str]]): Metrics names that are not pre-defined, such as cohort metrics or app specific metrics. api_token (str): Adjust API key, see https://help.adjust.com/en/article/report-service-api-authentication dimensions (List[str]): Dimensions allow a user to break down metrics into groups using one or several parameters. For example, the number of installs by date, country and network. See https://help.adjust.com/en/article/reports-endpoint#dimensions for more information about the dimensions. ingest_start (str): Data ingest start date. metrics (List[str]): Select at least one metric to query. until_today (Optional[bool]): Syncs data up until today. Useful when running daily incremental syncs, and duplicates are not desired. """ self.additional_metrics = check.opt_nullable_list_param( additional_metrics, "additional_metrics", str ) self.api_token = check.str_param(api_token, "api_token") self.dimensions = check.list_param(dimensions, "dimensions", str) self.ingest_start = check.str_param(ingest_start, "ingest_start") self.metrics = check.list_param(metrics, "metrics", str) self.until_today = check.opt_bool_param(until_today, "until_today") super().__init__("Adjust", name)
AdjustSource
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 13684, "end": 53049 }
class ____(Node): # subexprs [string] Class var holding names of subexpr node attrs # type PyrexType Type of the result # result_code string Code fragment # result_ctype string C type of result_code if different from type # is_temp boolean Result is in a temporary variable # is_sequence_constructor # boolean Is a list or tuple constructor expression # is_starred boolean Is a starred expression (e.g. '*a') # use_managed_ref boolean use ref-counted temps/assignments/etc. # result_is_used boolean indicates that the result will be dropped and the # result_code/temp_result can safely be set to None # is_numpy_attribute boolean Is a Numpy module attribute # annotation ExprNode or None PEP526 annotation for names or expressions # generator_arg_tag None or Node A tag to mark ExprNodes that potentially need to # be changed to a generator argument result_ctype = None type = None annotation = None temp_code = None old_temp = None # error checker for multiple frees etc. use_managed_ref = True # can be set by optimisation transforms result_is_used = True is_numpy_attribute = False generator_arg_tag = None in_parallel_block = False # The Analyse Expressions phase for expressions is split # into two sub-phases: # # Analyse Types # Determines the result type of the expression based # on the types of its sub-expressions, and inserts # coercion nodes into the expression tree where needed. # Marks nodes which will need to have temporary variables # allocated. # # Allocate Temps # Allocates temporary variables where needed, and fills # in the result_code field of each node. # # ExprNode provides some convenience routines which # perform both of the above phases. These should only # be called from statement nodes, and only when no # coercion nodes need to be added around the expression # being analysed. In that case, the above two phases # should be invoked separately. # # Framework code in ExprNode provides much of the common # processing for the various phases. It makes use of the # 'subexprs' class attribute of ExprNodes, which should # contain a list of the names of attributes which can # hold sub-nodes or sequences of sub-nodes. # # The framework makes use of a number of abstract methods. # Their responsibilities are as follows. # # Declaration Analysis phase # # analyse_target_declaration # Called during the Analyse Declarations phase to analyse # the LHS of an assignment or argument of a del statement. # Nodes which cannot be the LHS of an assignment need not # implement it. # # Expression Analysis phase # # analyse_types # - Call analyse_types on all sub-expressions. # - Check operand types, and wrap coercion nodes around # sub-expressions where needed. # - Set the type of this node. # - If a temporary variable will be required for the # result, set the is_temp flag of this node. # # analyse_target_types # Called during the Analyse Types phase to analyse # the LHS of an assignment or argument of a del # statement. Similar responsibilities to analyse_types. # # target_code # Called by the default implementation of allocate_target_temps. # Should return a C lvalue for assigning to the node. The default # implementation calls calculate_result_code. # # check_const # - Check that this node and its subnodes form a # legal constant expression. If so, do nothing, # otherwise call not_const. # # The default implementation of check_const # assumes that the expression is not constant. # # check_const_addr # - Same as check_const, except check that the # expression is a C lvalue whose address is # constant. Otherwise, call addr_not_const. # # The default implementation of calc_const_addr # assumes that the expression is not a constant # lvalue. # # Code Generation phase # # generate_evaluation_code # - Call generate_evaluation_code for sub-expressions. # - Perform the functions of generate_result_code # (see below). # - If result is temporary, call generate_disposal_code # on all sub-expressions. # # A default implementation of generate_evaluation_code # is provided which uses the following abstract methods: # # generate_result_code # - Generate any C statements necessary to calculate # the result of this node from the results of its # sub-expressions. # # calculate_result_code # - Should return a C code fragment evaluating to the # result. This is only called when the result is not # a temporary. # # generate_assignment_code # Called on the LHS of an assignment. # - Call generate_evaluation_code for sub-expressions. # - Generate code to perform the assignment. # - If the assignment absorbed a reference, call # generate_post_assignment_code on the RHS, # otherwise call generate_disposal_code on it. # # generate_deletion_code # Called on an argument of a del statement. # - Call generate_evaluation_code for sub-expressions. # - Generate code to perform the deletion. # - Call generate_disposal_code on all sub-expressions. # # is_sequence_constructor = False is_dict_literal = False is_set_literal = False is_string_literal = False is_attribute = False is_subscript = False is_slice = False is_buffer_access = False is_memview_index = False is_memview_slice = False is_memview_broadcast = False is_memview_copy_assignment = False is_temp = False has_temp_moved = False # if True then attempting to do anything but free the temp is invalid is_target = False is_starred = False is_annotation = False constant_result = constant_value_not_set if sys.implementation.name == "cpython": child_attrs = property(fget=operator.attrgetter('subexprs')) else: @property def child_attrs(self): return self.subexprs def analyse_annotations(self, env): pass def not_implemented(self, method_name): print_call_chain(method_name, "not implemented") raise InternalError( "%s.%s not implemented" % (self.__class__.__name__, method_name)) def is_lvalue(self): return 0 def is_addressable(self): return self.is_lvalue() and not self.type.is_memoryviewslice def is_ephemeral(self): # An ephemeral node is one whose result is in # a Python temporary and we suspect there are no # other references to it. Certain operations are # disallowed on such values, since they are # likely to result in a dangling pointer. return self.type.is_pyobject and self.is_temp def subexpr_nodes(self): # Extract a list of subexpression nodes based # on the contents of the subexprs class attribute. nodes = [] for name in self.subexprs: item = getattr(self, name) if item is not None: if type(item) is list: nodes.extend(item) else: nodes.append(item) return nodes def result(self): if self.is_temp: #if not self.temp_code: # pos = (os.path.basename(self.pos[0].get_description()),) + self.pos[1:] if self.pos else '(?)' # raise RuntimeError("temp result name not set in %s at %r" % ( # self.__class__.__name__, pos)) return self.temp_code else: return self.calculate_result_code() def _make_move_result_rhs(self, result, optional=False): if optional and not (self.is_temp and self.type.is_cpp_class and not self.type.is_reference): return result self.has_temp_moved = True return "{}({})".format("__PYX_STD_MOVE_IF_SUPPORTED" if optional else "std::move", result) def move_result_rhs(self): return self._make_move_result_rhs(self.result(), optional=True) def move_result_rhs_as(self, type): result = self.result_as(type) if not (type.is_reference or type.needs_refcounting): requires_move = type.is_rvalue_reference and self.is_temp result = self._make_move_result_rhs(result, optional=not requires_move) return result def pythran_result(self, type_=None): if is_pythran_supported_node_or_none(self): return to_pythran(self) assert type_ is not None return to_pythran(self, type_) def is_c_result_required(self): """ Subtypes may return False here if result temp allocation can be skipped. """ return True def result_as(self, type = None): # Return the result code cast to the specified C type. if (self.is_temp and self.type.is_pyobject and type != py_object_type): # Allocated temporaries are always PyObject *, which may not # reflect the actual type (e.g. an extension type) return typecast(type, py_object_type, self.result()) return typecast(type, self.ctype(), self.result()) def py_result(self): # Return the result code cast to PyObject *. return self.result_as(py_object_type) def ctype(self): # Return the native C type of the result (i.e. the # C type of the result_code expression). return self.result_ctype or self.type def get_constant_c_result_code(self): # Return the constant value of this node as a result code # string, or None if the node is not constant. This method # can be called when the constant result code is required # before the code generation phase. # # The return value is a string that can represent a simple C # value, a constant C name or a constant C expression. If the # node type depends on Python code, this must return None. return None def calculate_constant_result(self): # Calculate the constant compile time result value of this # expression and store it in ``self.constant_result``. Does # nothing by default, thus leaving ``self.constant_result`` # unknown. If valid, the result can be an arbitrary Python # value. # # This must only be called when it is assured that all # sub-expressions have a valid constant_result value. The # ConstantFolding transform will do this. pass def has_constant_result(self): return self.constant_result is not constant_value_not_set and \ self.constant_result is not not_a_constant def compile_time_value(self, denv): # Return value of compile-time expression, or report error. error(self.pos, "Invalid compile-time expression") def compile_time_value_error(self, e): error(self.pos, "Error in compile-time expression: %s: %s" % ( e.__class__.__name__, e)) def as_exception_value(self, env): """ Returns a PyrexTypes.CFuncType.ExceptionValue (or None) The python_value attribute of the result can be either a Python constant or a string for types that can't be represented by a Python constant (e.g. enums) """ c_result = self.get_constant_c_result_code() if c_result is None: error(self.pos, "Exception value must be constant") return None # Using the C result string isn't the preferred fallback because it can end up # hard to distinguish between identical types, e.g. -1.0 vs -1 # for floats. However, it lets things like NULL and typecasts work. py_result = self.constant_result if self.has_constant_result() else c_result return PyrexTypes.CFuncType.ExceptionValue(py_result, c_result, self.type) def may_be_unsafe_shared(self) -> str: # For some function-local variables we can optimize their usage because we # know that it's unique to this thread and can't be used from another thread. # Returns the name of a C enum. if self.in_parallel_block: return "__Pyx_ReferenceSharing_SharedReference" if self.is_temp: # If it's a refcounted variable, we hold a reference to it. Therefore, if # the reference count is 1, we trust that we're the unique owner. return "__Pyx_ReferenceSharing_OwnStrongReference" if not hasattr(self, "entry") or self.entry is None: return "__Pyx_ReferenceSharing_SharedReference" # Not sure if we can reason about it if self.entry.is_arg: # Arguments are a little hard to reason about so need an extra level of check return "__Pyx_ReferenceSharing_FunctionArgument" if (self.entry.scope.is_local_scope and # TODO - in principle a generator closure should be "non shared" because # only one thread can run the generator at once. not self.entry.in_closure and not self.entry.from_closure): return "__Pyx_ReferenceSharing_OwnStrongReference" # Most likely a global, or a class attribute return "__Pyx_ReferenceSharing_SharedReference" # ------------- Declaration Analysis ---------------- def analyse_target_declaration(self, env): error(self.pos, "Cannot assign to or delete this") def analyse_assignment_expression_target_declaration(self, env): error(self.pos, "Cannot use anything except a name in an assignment expression") # ------------- Expression Analysis ---------------- def analyse_const_expression(self, env): # Called during the analyse_declarations phase of a # constant expression. Analyses the expression's type, # checks whether it is a legal const expression, # and determines its value. node = self.analyse_types(env) node.check_const() return node def analyse_expressions(self, env): # Convenience routine performing both the Type # Analysis and Temp Allocation phases for a whole # expression. return self.analyse_types(env) def analyse_target_expression(self, env, rhs): # Convenience routine performing both the Type # Analysis and Temp Allocation phases for the LHS of # an assignment. return self.analyse_target_types(env) def analyse_boolean_expression(self, env): # Analyse expression and coerce to a boolean. node = self.analyse_types(env) bool = node.coerce_to_boolean(env) return bool def analyse_temp_boolean_expression(self, env): # Analyse boolean expression and coerce result into # a temporary. This is used when a branch is to be # performed on the result and we won't have an # opportunity to ensure disposal code is executed # afterwards. By forcing the result into a temporary, # we ensure that all disposal has been done by the # time we get the result. node = self.analyse_types(env) return node.coerce_to_boolean(env).coerce_to_simple(env) # --------------- Type Inference ----------------- def type_dependencies(self, env): # Returns the list of entries whose types must be determined # before the type of self can be inferred. if getattr(self, 'type', None) is not None: return () return sum([node.type_dependencies(env) for node in self.subexpr_nodes()], ()) def infer_type(self, env): # Attempt to deduce the type of self. # Differs from analyse_types as it avoids unnecessary # analysis of subexpressions, but can assume everything # in self.type_dependencies() has been resolved. type = getattr(self, 'type', None) if type is not None: return type entry = getattr(self, 'entry', None) if entry is not None: return entry.type self.not_implemented("infer_type") def nonlocally_immutable(self): # Returns whether this variable is a safe reference, i.e. # can't be modified as part of globals or closures. return self.is_literal or self.is_temp or self.type.is_array or self.type.is_cfunction def inferable_item_node(self, index=0): """ Return a node that represents the (type) result of an indexing operation, e.g. for tuple unpacking or iteration. """ return IndexNode(self.pos, base=self, index=IntNode.for_size(self.pos, index)) # --------------- Type Analysis ------------------ def analyse_as_module(self, env): # If this node can be interpreted as a reference to a # cimported module, return its scope, else None. return None def analyse_as_type(self, env): # If this node can be interpreted as a reference to a # type, return that type, else None. return None def analyse_as_specialized_type(self, env): type = self.analyse_as_type(env) if type and type.is_fused and env.fused_to_specific: # while it would be nice to test "if entry.type in env.fused_to_specific" # rather than try/catch this doesn't work reliably (mainly for nested fused types) try: return type.specialize(env.fused_to_specific) except KeyError: pass if type and type.is_fused: error(self.pos, "Type is not specific") return type def analyse_as_extension_type(self, env): # If this node can be interpreted as a reference to an # extension type or builtin type, return its type, else None. return None def analyse_types(self, env): self.not_implemented("analyse_types") def analyse_target_types(self, env): return self.analyse_types(env) def nogil_check(self, env): # By default, any expression based on Python objects is # prevented in nogil environments. Subtypes must override # this if they can work without the GIL. if self.type and self.type.is_pyobject: self.gil_error() def gil_assignment_check(self, env): if env.nogil and self.type.is_pyobject: error(self.pos, "Assignment of Python object not allowed without gil") def check_const(self): self.not_const() return False def not_const(self): error(self.pos, "Not allowed in a constant expression") def check_const_addr(self): self.addr_not_const() return False def addr_not_const(self): error(self.pos, "Address is not constant") # ----------------- Result Allocation ----------------- def result_in_temp(self): # Return true if result is in a temporary owned by # this node or one of its subexpressions. Overridden # by certain nodes which can share the result of # a subnode. # Temp-tests from outside of a node class should always # prefer this method over a plain "node.is_temp". return self.is_temp def target_code(self): # Return code fragment for use as LHS of a C assignment. return self.calculate_result_code() def calculate_result_code(self): self.not_implemented("calculate_result_code") # def release_target_temp(self, env): # # Release temporaries used by LHS of an assignment. # self.release_subexpr_temps(env) def allocate_temp_result(self, code): if self.temp_code: raise RuntimeError("Temp allocated multiple times in %r: %r" % (self.__class__.__name__, self.pos)) type = self.type if not type.is_void: if type.is_pyobject: type = PyrexTypes.py_object_type elif not (self.result_is_used or type.is_memoryviewslice or self.is_c_result_required()): self.temp_code = None return self.temp_code = code.funcstate.allocate_temp( type, manage_ref=self.use_managed_ref) else: self.temp_code = None def release_temp_result(self, code): if not self.temp_code: if not self.result_is_used: # not used anyway, so ignore if not set up return pos = (os.path.basename(self.pos[0].get_description()),) + self.pos[1:] if self.pos else '(?)' if self.old_temp: raise RuntimeError("temp %s released multiple times in %s at %r" % ( self.old_temp, self.__class__.__name__, pos)) else: raise RuntimeError("no temp, but release requested in %s at %r" % ( self.__class__.__name__, pos)) code.funcstate.release_temp(self.temp_code) self.old_temp = self.temp_code self.temp_code = None # ---------------- Code Generation ----------------- def make_owned_reference(self, code): """ Make sure we own a reference to result. If the result is in a temp, it is already a new reference. """ if not self.result_in_temp(): code.put_incref(self.result(), self.ctype()) def make_owned_memoryviewslice(self, code): """ Make sure we own the reference to this memoryview slice. """ # TODO ideally this would be shared with "make_owned_reference" if not self.result_in_temp(): code.put_incref_memoryviewslice(self.result(), self.type, have_gil=not self.in_nogil_context) def generate_evaluation_code(self, code): # Generate code to evaluate this node and # its sub-expressions, and dispose of any # temporary results of its sub-expressions. self.generate_subexpr_evaluation_code(code) code.mark_pos(self.pos) if self.is_temp: self.allocate_temp_result(code) self.generate_result_code(code) if self.is_temp and not (self.type.is_string or self.type.is_pyunicode_ptr): # If we are temp we do not need to wait until this node is disposed # before disposing children. self.generate_subexpr_disposal_code(code) self.free_subexpr_temps(code) def generate_subexpr_evaluation_code(self, code): for node in self.subexpr_nodes(): node.generate_evaluation_code(code) def generate_result_code(self, code): self.not_implemented("generate_result_code") def generate_disposal_code(self, code): if self.has_temp_moved: code.globalstate.use_utility_code( UtilityCode.load_cached("MoveIfSupported", "CppSupport.cpp")) if self.is_temp: if self.type.is_string or self.type.is_pyunicode_ptr: # postponed from self.generate_evaluation_code() self.generate_subexpr_disposal_code(code) self.free_subexpr_temps(code) if self.result(): code.put_decref_clear(self.result(), self.ctype(), have_gil=not self.in_nogil_context) else: # Already done if self.is_temp self.generate_subexpr_disposal_code(code) def generate_subexpr_disposal_code(self, code): # Generate code to dispose of temporary results # of all sub-expressions. for node in self.subexpr_nodes(): node.generate_disposal_code(code) def generate_post_assignment_code(self, code): if self.is_temp: if self.type.is_string or self.type.is_pyunicode_ptr: # postponed from self.generate_evaluation_code() self.generate_subexpr_disposal_code(code) self.free_subexpr_temps(code) elif self.type.is_pyobject: code.putln("%s = 0;" % self.result()) elif self.type.is_memoryviewslice: code.putln("%s.memview = NULL;" % self.result()) code.putln("%s.data = NULL;" % self.result()) if self.has_temp_moved: code.globalstate.use_utility_code( UtilityCode.load_cached("MoveIfSupported", "CppSupport.cpp")) else: self.generate_subexpr_disposal_code(code) def generate_assignment_code(self, rhs, code, overloaded_assignment=False, exception_check=None, exception_value=None): # Stub method for nodes which are not legal as # the LHS of an assignment. An error will have # been reported earlier. pass def generate_deletion_code(self, code, ignore_nonexisting=False): # Stub method for nodes that are not legal as # the argument of a del statement. An error # will have been reported earlier. pass def free_temps(self, code): if self.is_temp: if not self.type.is_void: self.release_temp_result(code) else: self.free_subexpr_temps(code) def free_subexpr_temps(self, code): for sub in self.subexpr_nodes(): sub.free_temps(code) def generate_function_definitions(self, env, code): pass # ----Generation of small bits of reference counting -- def generate_decref_set(self, code, rhs): code.put_decref_set(self.result(), self.ctype(), rhs) def generate_xdecref_set(self, code, rhs): code.put_xdecref_set(self.result(), self.ctype(), rhs) def generate_gotref(self, code, handle_null=False, maybe_null_extra_check=True): if not (handle_null and self.cf_is_null): if (handle_null and self.cf_maybe_null and maybe_null_extra_check): self.generate_xgotref(code) else: code.put_gotref(self.result(), self.ctype()) def generate_xgotref(self, code): code.put_xgotref(self.result(), self.ctype()) def generate_giveref(self, code): code.put_giveref(self.result(), self.ctype()) def generate_xgiveref(self, code): code.put_xgiveref(self.result(), self.ctype()) # ---------------- Annotation --------------------- def annotate(self, code): for node in self.subexpr_nodes(): node.annotate(code) # ----------------- Coercion ---------------------- def coerce_to(self, dst_type, env): # Coerce the result so that it can be assigned to # something of type dst_type. If processing is necessary, # wraps this node in a coercion node and returns that. # Otherwise, returns this node unchanged. # # This method is called during the analyse_expressions # phase of the src_node's processing. # # Note that subclasses that override this (especially # ConstNodes) must not (re-)set their own .type attribute # here. Since expression nodes may turn up in different # places in the tree (e.g. inside of CloneNodes in cascaded # assignments), this method must return a new node instance # if it changes the type. # src = self src_type = self.type if self.check_for_coercion_error(dst_type, env): return self used_as_reference = dst_type.is_reference if used_as_reference and not src_type.is_reference: dst_type = dst_type.ref_base_type if src_type.is_cv_qualified: src_type = src_type.cv_base_type if src_type.is_fused or dst_type.is_fused: # See if we are coercing a fused function to a pointer to a # specialized function if (src_type.is_cfunction and not dst_type.is_fused and dst_type.is_ptr and dst_type.base_type.is_cfunction): dst_type = dst_type.base_type for signature in src_type.get_all_specialized_function_types(): if signature.same_as(dst_type): src.type = signature src.entry = src.type.entry src.entry.used = True return self if src_type.is_fused: error(self.pos, "Type is not specialized") elif src_type.is_null_ptr and dst_type.is_ptr: # NULL can be implicitly cast to any pointer type return self else: error(self.pos, "Cannot coerce to a type that is not specialized") self.type = error_type return self if self.coercion_type is not None: # This is purely for error checking purposes! node = NameNode(self.pos, name='', type=self.coercion_type) node.coerce_to(dst_type, env) if dst_type.is_memoryviewslice: from . import MemoryView if not src.type.is_memoryviewslice: if src.type.is_pyobject: src = CoerceToMemViewSliceNode(src, dst_type, env) elif src.type.is_array: src = CythonArrayNode.from_carray(src, env).coerce_to(dst_type, env) elif not src_type.is_error: error(self.pos, "Cannot convert '%s' to memoryviewslice" % (src_type,)) else: if src.type.writable_needed: dst_type.writable_needed = True if not src.type.conforms_to(dst_type, broadcast=self.is_memview_broadcast, copying=self.is_memview_copy_assignment): if src.type.dtype.same_as(dst_type.dtype): msg = "Memoryview '%s' not conformable to memoryview '%s'." tup = src.type, dst_type else: msg = "Different base types for memoryviews (%s, %s)" tup = src.type.dtype, dst_type.dtype error(self.pos, msg % tup) elif dst_type.is_pyobject: # We never need a type check when assigning None to a Python object type. if src.is_none: pass elif src.constant_result is None: src = NoneNode(src.pos).coerce_to(dst_type, env) elif src.type.is_pyobject: if not src.type.subtype_of(dst_type): # Apply a type check on assignment. src = PyTypeTestNode(src, dst_type, env) else: if dst_type is bytes_type and src.type.is_int: src = CoerceIntToBytesNode(src, env) else: src = CoerceToPyTypeNode(src, env, type=dst_type) # FIXME: I would expect that CoerceToPyTypeNode(type=dst_type) returns a value of type dst_type # but it doesn't for ctuples. Thus, we add a PyTypeTestNode which then triggers the # Python conversion and becomes useless. That seems backwards and inefficient. # We should not need a PyTypeTestNode after a previous conversion above. if not src.type.subtype_of(dst_type): src = PyTypeTestNode(src, dst_type, env) elif is_pythran_expr(dst_type) and is_pythran_supported_type(src.type): # We let the compiler decide whether this is valid return src elif is_pythran_expr(src.type): if is_pythran_supported_type(dst_type): # Match the case were a pythran expr is assigned to a value, or vice versa. # We let the C++ compiler decide whether this is valid or not! return src # Else, we need to convert the Pythran expression to a Python object src = CoerceToPyTypeNode(src, env, type=dst_type) elif src.type.is_pyobject: if used_as_reference and dst_type.is_cpp_class: warning( self.pos, "Cannot pass Python object as C++ data structure reference (%s &), will pass by copy." % dst_type) src = CoerceFromPyTypeNode(dst_type, src, env) elif (dst_type.is_complex and src_type != dst_type and dst_type.assignable_from(src_type)): src = CoerceToComplexNode(src, dst_type, env) elif (src_type is PyrexTypes.soft_complex_type and src_type != dst_type and not dst_type.assignable_from(src_type)): src = coerce_from_soft_complex(src, dst_type, env) else: # neither src nor dst are py types # Added the string comparison, since for c types that # is enough, but Cython gets confused when the types are # in different pxi files. # TODO: Remove this hack and require shared declarations. if not (src.type == dst_type or str(src.type) == str(dst_type) or dst_type.assignable_from(src_type)): self.fail_assignment(dst_type) return src def fail_assignment(self, dst_type): src_name = self.entry.name if hasattr(self, "entry") else None src_resolved = f" (alias of '{self.type.resolve()}')" if self.type.is_typedef else "" dst_resolved = f" (alias of '{dst_type.resolve()}')" if dst_type.is_typedef else "" extra_diagnostics = dst_type.assignment_failure_extra_info(self.type, src_name) error(self.pos, f"Cannot assign type '{self.type}'{src_resolved}" f" to '{dst_type}'{dst_resolved}" f"{'.' if extra_diagnostics else ''}{extra_diagnostics}" ) def check_for_coercion_error(self, dst_type, env, fail=False, default=None): if fail and not default: default = "Cannot assign type '%(FROM)s' to '%(TO)s'" message = find_coercion_error((self.type, dst_type), default, env) if message is not None: error(self.pos, message % {'FROM': self.type, 'TO': dst_type}) return True if fail: self.fail_assignment(dst_type) return True return False def coerce_to_pyobject(self, env): return self.coerce_to(PyrexTypes.py_object_type, env) def coerce_to_boolean(self, env): # Coerce result to something acceptable as # a boolean value. # if it's constant, calculate the result now if self.has_constant_result(): bool_value = bool(self.constant_result) return BoolNode(self.pos, value=bool_value) type = self.type if type.is_enum or type.is_error: return self elif type is PyrexTypes.c_bint_type: return self elif type.is_pyobject or type.is_int or type.is_ptr or type.is_float: return CoerceToBooleanNode(self, env) elif type.is_cpp_class and type.scope and type.scope.lookup("operator bool"): return SimpleCallNode( self.pos, function=AttributeNode( self.pos, obj=self, attribute=StringEncoding.EncodedString('operator bool')), args=[]).analyse_types(env) elif type.is_ctuple: bool_value = len(type.components) == 0 return BoolNode(self.pos, value=bool_value) else: error(self.pos, "Type '%s' not acceptable as a boolean" % type) return self def coerce_to_index(self, env): # If not already some C integer type, coerce to Py_ssize_t. return self if self.type.is_int else self.coerce_to(PyrexTypes.c_py_ssize_t_type, env) def coerce_to_temp(self, env): # Ensure that the result is in a temporary. if self.result_in_temp(): return self else: return CoerceToTempNode(self, env) def coerce_to_simple(self, env): # Ensure that the result is simple (see is_simple). if self.is_simple(): return self else: return self.coerce_to_temp(env) def is_simple(self): # A node is simple if its result is something that can # be referred to without performing any operations, e.g. # a constant, local var, C global var, struct member # reference, or temporary. return self.result_in_temp() def try_is_simple(self): # Allow ".is_simple()" to fail (e.g. before type analysis) and assume it's not simple. try: return self.is_simple() except Exception: return False def may_be_none(self): if self.type and not (self.type.is_pyobject or self.type.is_memoryviewslice): return False if self.has_constant_result(): return self.constant_result is not None return True def as_cython_attribute(self): return None def as_none_safe_node(self, message, error="PyExc_TypeError", format_args=()): # Wraps the node in a NoneCheckNode if it is not known to be # not-None (e.g. because it is a Python literal). if self.may_be_none(): return NoneCheckNode(self, error, message, format_args) else: return self @classmethod def from_node(cls, node, **kwargs): """Instantiate this node class from another node, properly copying over all attributes that one would forget otherwise. """ attributes = "cf_state cf_maybe_null cf_is_null constant_result".split() for attr_name in attributes: if attr_name in kwargs: continue try: value = getattr(node, attr_name) except AttributeError: pass else: kwargs[attr_name] = value return cls(node.pos, **kwargs) def get_known_standard_library_import(self): """ Gets the module.path that this node was imported from. Many nodes do not have one, or it is ambiguous, in which case this function returns a false value. """ return None
ExprNode
python
sympy__sympy
sympy/assumptions/predicates/order.py
{ "start": 8907, "end": 9511 }
class ____(Predicate): """ Nonnegative extended real number predicate. Explanation =========== ``ask(Q.extended_nonnegative(x))`` is true iff ``x`` is extended real and ``x`` is not negative. Examples ======== >>> from sympy import ask, I, oo, Q >>> ask(Q.extended_nonnegative(-1)) False >>> ask(Q.extended_nonnegative(oo)) True >>> ask(Q.extended_nonnegative(0)) True >>> ask(Q.extended_nonnegative(I)) False """ name = 'extended_nonnegative' handler = Dispatcher("ExtendedNonNegativeHandler")
ExtendedNonNegativePredicate
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 128709, "end": 128999 }
class ____(TestCase): # Tests crash reported in https://github.com/pytorch/pytorch/issues/53565 def test_conv_after_fork(self): loader = DataLoader(ConvDataset(), num_workers=1) for x in loader: self.assertEqual(x.shape, (1, 1, 1, 23999))
TestConvAfterFork
python
huggingface__transformers
tests/models/vilt/test_modeling_vilt.py
{ "start": 1626, "end": 7942 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, image_size=30, patch_size=2, num_channels=3, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, scope=None, modality_type_vocab_size=2, add_multiple_images=False, num_images=-1, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.scope = scope self.modality_type_vocab_size = modality_type_vocab_size self.add_multiple_images = add_multiple_images self.num_images = num_images # we set the expected sequence length (which is used in several tests) # this is equal to the seq length of the text tokens + number of image patches + 1 for the CLS token self.expected_seq_len = self.seq_length + (self.image_size // self.patch_size) ** 2 + 1 def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) if self.add_multiple_images: pixel_values = floats_tensor([self.batch_size, 2, self.num_channels, self.image_size, self.image_size]) else: pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) if self.use_labels: token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) config = self.get_config() return (config, input_ids, token_type_ids, input_mask, pixel_values, token_labels) def get_config(self): return ViltConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=False, initializer_range=self.initializer_range, num_labels=self.num_labels, modality_type_vocab_size=self.modality_type_vocab_size, num_images=self.num_images, ) def create_and_check_model( self, config, input_ids, token_type_ids, input_mask, pixel_values, token_labels, ): model = ViltModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, pixel_values=pixel_values) result = model(input_ids, token_type_ids=token_type_ids, pixel_values=pixel_values) result = model(input_ids, pixel_values=pixel_values) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.expected_seq_len, self.hidden_size) ) def create_and_check_for_token_classification( self, config, input_ids, token_type_ids, input_mask, pixel_values, token_labels, ): model = ViltForTokenClassification(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, pixel_values=pixel_values) result = model(input_ids, token_type_ids=token_type_ids, pixel_values=pixel_values) result = model(input_ids, pixel_values=pixel_values) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, token_type_ids, input_mask, pixel_values, token_labels, ) = config_and_inputs inputs_dict = { "input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask, "pixel_values": pixel_values, } return config, inputs_dict def prepare_pixel_values(self): return floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) @require_torch
ViltModelTester
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/welcome_widget.py
{ "start": 80, "end": 225 }
class ____(App[None]): def compose(self) -> ComposeResult: yield Welcome() if __name__ == "__main__": WelcomeApp().run()
WelcomeApp
python
RaRe-Technologies__gensim
gensim/scripts/segment_wiki.py
{ "start": 9363, "end": 15638 }
class ____(WikiCorpus): """Treat a wikipedia articles dump (<LANG>wiki-<YYYYMMDD>-pages-articles.xml.bz2 or <LANG>wiki-latest-pages-articles.xml.bz2) as a (read-only) corpus. The documents are extracted on-the-fly, so that the whole (massive) dump can stay compressed on disk. """ def __init__(self, fileobj, min_article_character=200, processes=None, lemmatize=None, filter_namespaces=('0',), include_interlinks=False): """ Parameters ---------- fileobj : file File descriptor of MediaWiki dump. min_article_character : int, optional Minimal number of character for article (except titles and leading gaps). processes : int, optional Number of processes, max(1, multiprocessing.cpu_count() - 1) if None. filter_namespaces : tuple of int, optional Enumeration of namespaces that will be ignored. include_interlinks: bool Whether or not interlinks should be included in the output """ if lemmatize is not None: raise NotImplementedError( 'The lemmatize parameter is no longer supported since Gensim 4.0.0. ' 'If you need to lemmatize, use e.g. https://github.com/clips/pattern ' 'to preprocess your corpus before submitting it to Gensim.' ) self.fileobj = fileobj self.filter_namespaces = filter_namespaces self.metadata = False if processes is None: processes = max(1, multiprocessing.cpu_count() - 1) self.processes = processes self.min_article_character = min_article_character self.include_interlinks = include_interlinks def get_texts_with_sections(self): """Iterate over the dump, returning titles and text versions of all sections of articles. Notes ----- Only articles of sufficient length are returned (short articles & redirects etc are ignored). Note that this iterates over the **texts**; if you want vectors, just use the standard corpus interface instead of this function: .. sourcecode:: pycon >>> for vec in wiki_corpus: >>> print(vec) Yields ------ (str, list of (str, str), list of (str, str)) Structure contains (title, [(section_heading, section_content), ...], (Optionally)[(interlink_article, interlink_text), ...]). """ skipped_namespace, skipped_length, skipped_redirect = 0, 0, 0 total_articles, total_sections = 0, 0 page_xmls = extract_page_xmls(self.fileobj) pool = multiprocessing.Pool(self.processes) # process the corpus in smaller chunks of docs, because multiprocessing.Pool # is dumb and would load the entire input into RAM at once... for group in utils.chunkize(page_xmls, chunksize=10 * self.processes, maxsize=1): for article in pool.imap(partial(segment, include_interlinks=self.include_interlinks), group): # chunksize=10): partial(merge_names, b='Sons') article_title, sections = article[0], article[1] # article redirects are pruned here if any(article_title.startswith(ignore + ':') for ignore in IGNORED_NAMESPACES): # filter non-articles skipped_namespace += 1 continue if not sections or sections[0][1].lstrip().lower().startswith("#redirect"): # filter redirect skipped_redirect += 1 continue if sum(len(body.strip()) for (_, body) in sections) < self.min_article_character: # filter stubs (incomplete, very short articles) skipped_length += 1 continue total_articles += 1 total_sections += len(sections) if self.include_interlinks: interlinks = article[2] yield (article_title, sections, interlinks) else: yield (article_title, sections) logger.info( "finished processing %i articles with %i sections (skipped %i redirects, %i stubs, %i ignored namespaces)", total_articles, total_sections, skipped_redirect, skipped_length, skipped_namespace) pool.terminate() self.length = total_articles # cache corpus length if __name__ == "__main__": logging.basicConfig(format='%(asctime)s - %(module)s - %(levelname)s - %(message)s', level=logging.INFO) parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description=__doc__[:-136]) default_workers = max(1, multiprocessing.cpu_count() - 1) parser.add_argument('-f', '--file', help='Path to MediaWiki database dump (read-only).', required=True) parser.add_argument( '-o', '--output', help='Path to output file (stdout if not specified). If ends in .gz or .bz2, ' 'the output file will be automatically compressed (recommended!).') parser.add_argument( '-w', '--workers', help='Number of parallel workers for multi-core systems. Default: %(default)s.', type=int, default=default_workers ) parser.add_argument( '-m', '--min-article-character', help="Ignore articles with fewer characters than this (article stubs). Default: %(default)s.", type=int, default=200 ) parser.add_argument( '-i', '--include-interlinks', help='Include a mapping for interlinks to other articles in the dump. The mappings format is: ' '"interlinks": [("article_title_1", "interlink_text_1"), ("article_title_2", "interlink_text_2"), ...]', action='store_true' ) args = parser.parse_args() logger.info("running %s", " ".join(sys.argv)) segment_and_write_all_articles( args.file, args.output, min_article_character=args.min_article_character, workers=args.workers, include_interlinks=args.include_interlinks ) logger.info("finished running %s", sys.argv[0])
_WikiSectionsCorpus
python
jmcnamara__XlsxWriter
xlsxwriter/rich_value_types.py
{ "start": 325, "end": 3356 }
class ____(xmlwriter.XMLwriter): """ A class for writing the Excel XLSX rdRichValueTypes.xml file. """ ########################################################################### # # Private API. # ########################################################################### def _assemble_xml_file(self) -> None: # Assemble and write the XML file. # Write the XML declaration. self._xml_declaration() # Write the rvTypesInfo element. self._write_rv_types_info() # Write the global element. self._write_global() self._xml_end_tag("rvTypesInfo") # Close the file. self._xml_close() ########################################################################### # # XML methods. # ########################################################################### def _write_rv_types_info(self) -> None: # Write the <rvTypesInfo> element. xmlns = "http://schemas.microsoft.com/office/spreadsheetml/2017/richdata2" xmlns_x = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns_mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" mc_ignorable = "x" attributes = [ ("xmlns", xmlns), ("xmlns:mc", xmlns_mc), ("mc:Ignorable", mc_ignorable), ("xmlns:x", xmlns_x), ] self._xml_start_tag("rvTypesInfo", attributes) def _write_global(self) -> None: # Write the <global> element. key_flags = [ ["_Self", ["ExcludeFromFile", "ExcludeFromCalcComparison"]], ["_DisplayString", ["ExcludeFromCalcComparison"]], ["_Flags", ["ExcludeFromCalcComparison"]], ["_Format", ["ExcludeFromCalcComparison"]], ["_SubLabel", ["ExcludeFromCalcComparison"]], ["_Attribution", ["ExcludeFromCalcComparison"]], ["_Icon", ["ExcludeFromCalcComparison"]], ["_Display", ["ExcludeFromCalcComparison"]], ["_CanonicalPropertyNames", ["ExcludeFromCalcComparison"]], ["_ClassificationId", ["ExcludeFromCalcComparison"]], ] self._xml_start_tag("global") self._xml_start_tag("keyFlags") for key_flag in key_flags: # Write the key element. self._write_key(key_flag) self._xml_end_tag("keyFlags") self._xml_end_tag("global") def _write_key(self, key_flag) -> None: # Write the <key> element. name = key_flag[0] attributes = [("name", name)] self._xml_start_tag("key", attributes) # Write the flag element. for name in key_flag[1]: self._write_flag(name) self._xml_end_tag("key") def _write_flag(self, name) -> None: # Write the <flag> element. attributes = [ ("name", name), ("value", "1"), ] self._xml_empty_tag("flag", attributes)
RichValueTypes
python
pytorch__pytorch
test/nn/test_load_state_dict.py
{ "start": 20321, "end": 20630 }
class ____(torch.Tensor): @classmethod def __torch_function__(cls, func, types, args=(), kwargs=None): return load_torch_function_handler(cls, func, types, args, kwargs) # We use MyLoadTensor2 to test tensor subclass, wrapper tensor subclass # where neither inherits from each other
MyLoadTensor
python
numba__numba
numba/core/ir.py
{ "start": 683, "end": 7314 }
class ____(object): """Source location """ _defmatcher = re.compile(r'def\s+(\w+)') def __init__(self, filename, line, col=None, maybe_decorator=False): """ Arguments: filename - name of the file line - line in file col - column maybe_decorator - Set to True if location is likely a jit decorator """ self.filename = filename self.line = line self.col = col self.lines = None # the source lines from the linecache self.maybe_decorator = maybe_decorator def __eq__(self, other): # equivalence is solely based on filename, line and col if type(self) is not type(other): return False if self.filename != other.filename: return False if self.line != other.line: return False if self.col != other.col: return False return True def __ne__(self, other): return not self.__eq__(other) @classmethod def from_function_id(cls, func_id): return cls(func_id.filename, func_id.firstlineno, maybe_decorator=True) def __repr__(self): return "Loc(filename=%s, line=%s, col=%s)" % (self.filename, self.line, self.col) def __str__(self): if self.col is not None: return "%s (%s:%s)" % (self.filename, self.line, self.col) else: return "%s (%s)" % (self.filename, self.line) def _find_definition(self): # try and find a def, go backwards from error line fn_name = None lines = self.get_lines() for x in reversed(lines[:self.line - 1]): # the strip and startswith is to handle user code with commented out # 'def' or use of 'def' in a docstring. if x.strip().startswith('def '): fn_name = x break return fn_name def _raw_function_name(self): defn = self._find_definition() if defn: m = self._defmatcher.match(defn.strip()) if m: return m.groups()[0] # Probably exec(<string>) or REPL. return None def get_lines(self): if self.lines is None: path = self._get_path() # Avoid reading from dynamic string. They are most likely # overridden. Problem started with Python 3.13. "<string>" seems # to be something from multiprocessing. lns = [] if path == "<string>" else linecache.getlines(path) self.lines = lns return self.lines def _get_path(self): path = None try: # Try to get a relative path # ipython/jupyter input just returns as self.filename path = os.path.relpath(self.filename) except ValueError: # Fallback to absolute path if error occurred in getting the # relative path. # This may happen on windows if the drive is different path = os.path.abspath(self.filename) return path def strformat(self, nlines_up=2): lines = self.get_lines() use_line = self.line if self.maybe_decorator: # try and sort out a better `loc`, if it's suspected that this loc # points at a jit decorator by virtue of # `__code__.co_firstlineno` # get lines, add a dummy entry at the start as lines count from # 1 but list index counts from 0 tmplines = [''] + lines if lines and use_line and 'def ' not in tmplines[use_line]: # look forward 10 lines, unlikely anyone managed to stretch # a jit call declaration over >10 lines?! min_line = max(0, use_line) max_line = use_line + 10 selected = tmplines[min_line : max_line] index = 0 for idx, x in enumerate(selected): if 'def ' in x: index = idx break use_line = use_line + index ret = [] # accumulates output if lines and use_line > 0: def count_spaces(string): spaces = 0 for x in itertools.takewhile(str.isspace, str(string)): spaces += 1 return spaces # A few places in the code still use no `loc` or default to line 1 # this is often in places where exceptions are used for the purposes # of flow control. As a result max is in use to prevent slice from # `[negative: positive]` selected = lines[max(0, use_line - nlines_up):use_line] # see if selected contains a definition def_found = False for x in selected: if 'def ' in x: def_found = True # no definition found, try and find one if not def_found: # try and find a def, go backwards from error line fn_name = None for x in reversed(lines[:use_line - 1]): if 'def ' in x: fn_name = x break if fn_name: ret.append(fn_name) spaces = count_spaces(x) ret.append(' '*(4 + spaces) + '<source elided>\n') if selected: ret.extend(selected[:-1]) ret.append(_termcolor.highlight(selected[-1])) # point at the problem with a caret spaces = count_spaces(selected[-1]) ret.append(' '*(spaces) + _termcolor.indicate("^")) # if in the REPL source may not be available if not ret: if not lines: ret = "<source missing, REPL/exec in use?>" elif use_line <= 0: ret = "<source line number missing>" err = _termcolor.filename('\nFile "%s", line %d:')+'\n%s' tmp = err % (self._get_path(), use_line, _termcolor.code(''.join(ret))) return tmp def with_lineno(self, line, col=None): """ Return a new Loc with this line number. """ return type(self)(self.filename, line, col) def short(self): """ Returns a short string """ shortfilename = os.path.basename(self.filename) return "%s:%s" % (shortfilename, self.line) # Used for annotating errors when source location is unknown. unknown_loc = Loc("unknown location", 0, 0) @total_ordering
Loc
python
streamlit__streamlit
lib/streamlit/runtime/memory_media_file_storage.py
{ "start": 2723, "end": 6253 }
class ____(MediaFileStorage, CacheStatsProvider): def __init__(self, media_endpoint: str) -> None: """Create a new MemoryMediaFileStorage instance. Parameters ---------- media_endpoint The name of the local endpoint that media is served from. This endpoint should start with a forward-slash (e.g. "/media"). """ self._files_by_id: dict[str, MemoryFile] = {} self._media_endpoint = media_endpoint def load_and_get_id( self, path_or_data: str | bytes, mimetype: str, kind: MediaFileKind, filename: str | None = None, ) -> str: """Add a file to the manager and return its ID.""" file_data: bytes file_data = ( self._read_file(path_or_data) if isinstance(path_or_data, str) else path_or_data ) # Because our file_ids are stable, if we already have a file with the # given ID, we don't need to create a new one. file_id = _calculate_file_id(file_data, mimetype, filename) if file_id not in self._files_by_id: _LOGGER.debug("Adding media file %s", file_id) media_file = MemoryFile( content=file_data, mimetype=mimetype, kind=kind, filename=filename ) self._files_by_id[file_id] = media_file return file_id def get_file(self, filename: str) -> MemoryFile: """Return the MemoryFile with the given filename. Filenames are of the form "file_id.extension". (Note that this is *not* the optional user-specified filename for download files.). Raises a MediaFileStorageError if no such file exists. """ file_id = os.path.splitext(filename)[0] try: return self._files_by_id[file_id] except KeyError as e: raise MediaFileStorageError( f"Bad filename '{filename}'. (No media file with id '{file_id}')" ) from e def get_url(self, file_id: str) -> str: """Get a URL for a given media file. Raise a MediaFileStorageError if no such file exists. """ media_file = self.get_file(file_id) extension = get_extension_for_mimetype(media_file.mimetype) return f"{self._media_endpoint}/{file_id}{extension}" def delete_file(self, file_id: str) -> None: """Delete the file with the given ID.""" # We swallow KeyErrors here - it's not an error to delete a file # that doesn't exist. with contextlib.suppress(KeyError): del self._files_by_id[file_id] def _read_file(self, filename: str) -> bytes: """Read a file into memory. Raise MediaFileStorageError if we can't.""" try: with open(filename, "rb") as f: return f.read() except Exception as ex: raise MediaFileStorageError(f"Error opening '{filename}'") from ex def get_stats(self) -> list[CacheStat]: # We operate on a copy of our dict, to avoid race conditions # with other threads that may be manipulating the cache. files_by_id = self._files_by_id.copy() stats: list[CacheStat] = [ CacheStat( category_name="st_memory_media_file_storage", cache_name="", byte_length=len(file.content), ) for _, file in files_by_id.items() ] return group_stats(stats)
MemoryMediaFileStorage
python
streamlit__streamlit
lib/tests/streamlit/web/server/routes_test.py
{ "start": 10184, "end": 11709 }
class ____(tornado.testing.AsyncHTTPTestCase): def setUp(self): super().setUp() def get_app(self): return tornado.web.Application( [ ( rf"/{HOST_CONFIG_ENDPOINT}", HostConfigHandler, ) ] ) @patch_config_options({"global.developmentMode": False}) def test_allowed_message_origins(self): response = self.fetch("/_stcore/host-config") response_body = json.loads(response.body) assert response.code == 200 assert response_body == { "allowedOrigins": _DEFAULT_ALLOWED_MESSAGE_ORIGINS, "useExternalAuthToken": False, # Default host configuration settings: "enableCustomParentMessages": False, "enforceDownloadInNewTab": False, "metricsUrl": "", "blockErrorDialogs": False, "resourceCrossOriginMode": None, } # Check that localhost NOT appended/allowed outside dev mode assert "http://localhost" not in response_body["allowedOrigins"] @patch_config_options({"global.developmentMode": True}) def test_allowed_message_origins_dev_mode(self): response = self.fetch("/_stcore/host-config") assert response.code == 200 # Check that localhost has been appended/allowed in dev mode origins_list = json.loads(response.body)["allowedOrigins"] assert "http://localhost" in origins_list
HostConfigHandlerTest
python
PyCQA__pylint
tests/functional/e/enum_subclasses.py
{ "start": 95, "end": 258 }
class ____(IntEnum): """https://github.com/pylint-dev/pylint/issues/1932""" FOO = 1 def whats_my_name(self): return self.name.lower()
Issue1932
python
kamyu104__LeetCode-Solutions
Python/sum-of-number-and-its-reverse.py
{ "start": 1065, "end": 1496 }
class ____(object): def sumOfNumberAndReverse(self, num): """ :type num: int :rtype: bool """ def reverse(n): result = 0 while n: result = result*10 + n%10 n //= 10 return result return any(x+reverse(x) == num for x in xrange(num//2, num+1)) # Time: O(nlogn) # Space: O(logn) # brute force
Solution2
python
huggingface__transformers
tests/quantization/quanto_integration/test_quanto.py
{ "start": 16545, "end": 16770 }
class ____(QuantoQuantizationSerializationTest): EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I" weights = "int4" @require_torch_accelerator
QuantoQuantizationQBitsTensorSerializationTest
python
huggingface__transformers
src/transformers/models/idefics3/modeling_idefics3.py
{ "start": 14310, "end": 16055 }
class ____(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`Idefics3EncoderLayer`]. Args: config: Idefics3Config """ def __init__(self, config: Idefics3Config): super().__init__() self.config = config self.layers = nn.ModuleList([Idefics3EncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False # Ignore copy @auto_docstring def forward( self, inputs_embeds, attention_mask: Optional[torch.Tensor] = None, ) -> Union[tuple, BaseModelOutput]: hidden_states = inputs_embeds for encoder_layer in self.layers: layer_outputs = encoder_layer( hidden_states, attention_mask, ) hidden_states = layer_outputs return BaseModelOutput(last_hidden_state=hidden_states) # Copied from transformers.models.llama.modeling_llama.repeat_kv def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Idefics3
Idefics3Encoder