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
catalyst-team__catalyst
examples/detection/models/yolo_x.py
{ "start": 508, "end": 1258 }
class ____(nn.Module): """A Conv2d -> Batchnorm -> silu/leaky relu block""" def __init__( self, in_channels, out_channels, ksize, stride, groups=1, bias=False, act="silu" ): super().__init__() # same padding pad = (ksize - 1) // 2 self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=ksize, stride=stride, padding=pad, groups=groups, bias=bias, ) self.bn = nn.BatchNorm2d(out_channels) self.act = get_activation(act, inplace=True) def forward(self, x): return self.act(self.bn(self.conv(x))) def fuseforward(self, x): return self.act(self.conv(x))
BaseConv
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 54442, "end": 54818 }
class ____(BaseModel): """ Response of updating a Human-in-the-loop detail. """ responded_by: HITLUser responded_at: Annotated[datetime, Field(title="Responded At")] chosen_options: Annotated[list[str], Field(min_length=1, title="Chosen Options")] params_input: Annotated[dict[str, Any] | None, Field(title="Params Input")] = None
HITLDetailResponse
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/sagemaker.py
{ "start": 4880, "end": 7946 }
class ____(BaseTrigger): """Trigger to wait for a sagemaker pipeline execution to finish.""" class Type(IntEnum): """Type of waiter to use.""" COMPLETE = 1 STOPPED = 2 def __init__( self, waiter_type: Type, pipeline_execution_arn: str, waiter_delay: int, waiter_max_attempts: int, aws_conn_id: str | None, ): self.waiter_type = waiter_type self.pipeline_execution_arn = pipeline_execution_arn self.waiter_delay = waiter_delay self.waiter_max_attempts = waiter_max_attempts self.aws_conn_id = aws_conn_id def serialize(self) -> tuple[str, dict[str, Any]]: return ( self.__class__.__module__ + "." + self.__class__.__qualname__, { "waiter_type": self.waiter_type.value, # saving the int value here "pipeline_execution_arn": self.pipeline_execution_arn, "waiter_delay": self.waiter_delay, "waiter_max_attempts": self.waiter_max_attempts, "aws_conn_id": self.aws_conn_id, }, ) _waiter_name = { Type.COMPLETE: "PipelineExecutionComplete", Type.STOPPED: "PipelineExecutionStopped", } async def run(self) -> AsyncIterator[TriggerEvent]: hook = SageMakerHook(aws_conn_id=self.aws_conn_id) async with await hook.get_async_conn() as conn: waiter = hook.get_waiter(self._waiter_name[self.waiter_type], deferrable=True, client=conn) for _ in range(self.waiter_max_attempts): try: await waiter.wait( PipelineExecutionArn=self.pipeline_execution_arn, WaiterConfig={"MaxAttempts": 1} ) # we reach this point only if the waiter met a success criteria yield TriggerEvent({"status": "success", "value": self.pipeline_execution_arn}) return except WaiterError as error: if "terminal failure" in str(error): raise self.log.info( "Status of the pipeline execution: %s", error.last_response["PipelineExecutionStatus"] ) res = await conn.list_pipeline_execution_steps( PipelineExecutionArn=self.pipeline_execution_arn ) count_by_state = Counter(s["StepStatus"] for s in res["PipelineExecutionSteps"]) running_steps = [ s["StepName"] for s in res["PipelineExecutionSteps"] if s["StepStatus"] == "Executing" ] self.log.info("State of the pipeline steps: %s", count_by_state) self.log.info("Steps currently in progress: %s", running_steps) await asyncio.sleep(int(self.waiter_delay)) raise AirflowException("Waiter error: max attempts reached")
SageMakerPipelineTrigger
python
ApeWorX__ape
src/ape/contracts/base.py
{ "start": 10429, "end": 12904 }
class ____(ContractMethodHandler): def __call__(self, *args, **kwargs) -> Any: self._validate_is_contract() selected_abi = _select_method_abi(self.abis, args) arguments = self.conversion_manager.convert_method_args(selected_abi, args) return ContractCall( abi=selected_abi, address=self.contract.address, )(*arguments, **kwargs) def as_transaction(self, *args, **kwargs): """ Convert the call to a transaction. This is useful for checking coverage or checking gas costs. Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: :class:`~ape.api.transactions.TransactionAPI` """ return self.transact.as_transaction(*args, **kwargs) def as_transaction_bytes(self, *args, **txn_kwargs) -> HexBytes: """ Get a signed serialized transaction. Returns: HexBytes: The serialized transaction """ return self.transact.as_transaction_bytes(**txn_kwargs) @property def transact(self) -> "ContractTransactionHandler": """ Send the call as a transaction. """ return ContractTransactionHandler(self.contract, self.abis) def estimate_gas_cost(self, *args, **kwargs) -> int: """ Get the estimated gas cost (according to the provider) for the contract method call (as if it were a transaction). Args: *args: The contract method invocation arguments. **kwargs: Transaction kwargs, such as value or sender. Returns: int: The estimated cost of gas to execute the transaction reported in the fee-currency's smallest unit, e.g. Wei. """ selected_abi = _select_method_abi(self.abis, args) arguments = self.conversion_manager.convert_method_args(selected_abi, args) return self.transact.estimate_gas_cost(*arguments, **kwargs) def _select_method_abi(abis: list["MethodABI"], args: Union[tuple, list]) -> "MethodABI": args = args or [] selected_abi = None for abi in abis: inputs = abi.inputs or [] if len(args) == len(inputs): selected_abi = abi if not selected_abi: raise ArgumentsLengthError(len(args), inputs=abis) return selected_abi
ContractCallHandler
python
realpython__materials
arcade-platformer/arcade_platformer/arcade_platformer.py
{ "start": 5607, "end": 7462 }
class ____(arcade.View): """Shown when the game is paused""" def __init__(self, game_view: arcade.View) -> None: """Create the pause screen""" # Initialize the parent super().__init__() # Store a reference to the underlying view self.game_view = game_view # Store a semi-transparent color to use as an overlay self.fill_color = arcade.make_transparent_color( arcade.color.WHITE, transparency=150 ) def on_draw(self) -> None: """Draw the underlying screen, blurred, then the Paused text""" # First, draw the underlying view # This also calls start_render(), so no need to do it again self.game_view.on_draw() # Now create a filled rect that covers the current viewport # We get the viewport size from the game view arcade.draw_lrtb_rectangle_filled( left=self.game_view.view_left, right=self.game_view.view_left + game.SCREEN_WIDTH, top=self.game_view.view_bottom + game.SCREEN_HEIGHT, bottom=self.game_view.view_bottom, color=self.fill_color, ) # Now show the Pause text arcade.draw_text( "PAUSED - ESC TO CONTINUE", start_x=self.game_view.view_left + 180, start_y=self.game_view.view_bottom + 300, color=arcade.color.INDIGO, font_size=40, ) def on_key_press(self, key: int, modifiers: int) -> None: """Resume the game when the user presses ESC again Arguments: key -- Which key was pressed modifiers -- What modifiers were active """ if key == arcade.key.ESCAPE: self.window.show_view(self.game_view) # Victory View, shown when the player completes a level successfully
PauseView
python
joke2k__faker
faker/providers/phone_number/zh_CN/__init__.py
{ "start": 49, "end": 681 }
class ____(PhoneNumberProvider): phonenumber_prefixes = [ 134, 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 182, 187, 188, 130, 131, 132, 145, 155, 156, 185, 186, 145, 133, 153, 180, 181, 189, ] formats = [str(i) + "########" for i in phonenumber_prefixes] def phonenumber_prefix(self) -> int: return self.random_element(self.phonenumber_prefixes)
Provider
python
numba__numba
numba/core/caching.py
{ "start": 5891, "end": 6278 }
class ____(InTreeCacheLocator): """ A locator for functions backed by a regular Python module with a writable __pycache__ directory. This version is agnostic to filesystem differences, e.g. timestamp precision with milliseconds. """ def get_source_stamp(self): st = super().get_source_stamp() return floor(st[0]), st[1]
InTreeCacheLocatorFsAgnostic
python
wntrblm__nox
nox/logger.py
{ "start": 2511, "end": 5364 }
class ____(logging.getLoggerClass()): # type: ignore[misc] def __init__(self, name: str, level: int = logging.NOTSET): super().__init__(name, level) logging.addLevelName(SESSION_INFO, "SESSION_INFO") logging.addLevelName(SUCCESS, "SUCCESS") logging.addLevelName(OUTPUT, "OUTPUT") def session_info(self, msg: str, *args: Any, **kwargs: Any) -> None: if self.isEnabledFor(SESSION_INFO): # pragma: no cover self._log(SESSION_INFO, msg, args, **kwargs) def success(self, msg: str, *args: Any, **kwargs: Any) -> None: if self.isEnabledFor(SUCCESS): # pragma: no cover self._log(SUCCESS, msg, args, **kwargs) def output(self, msg: str, *args: Any, **kwargs: Any) -> None: if self.isEnabledFor(OUTPUT): # pragma: no cover self._log(OUTPUT, msg, args, **kwargs) logging.setLoggerClass(LoggerWithSuccessAndOutput) logger = cast("LoggerWithSuccessAndOutput", logging.getLogger("nox")) def _get_formatter(*, color: bool, add_timestamp: bool) -> logging.Formatter: if color: return NoxColoredFormatter( reset=True, log_colors={ "DEBUG": "cyan", "INFO": "blue", "SESSION_INFO": "purple", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "red,bg_white", "SUCCESS": "green", }, style="%", secondary_log_colors=None, add_timestamp=add_timestamp, ) return NoxFormatter(add_timestamp=add_timestamp) def setup_logging( *, color: bool, verbose: bool = False, add_timestamp: bool = False ) -> None: # pragma: no cover """Setup logging. Args: color (bool): If true, the output will be colored using colorlog. Otherwise, it will be plaintext. """ root_logger = logging.getLogger() if verbose: root_logger.setLevel(OUTPUT) else: root_logger.setLevel(logging.DEBUG) active_handlers = [ handler for handler in root_logger.handlers if handler.get_name() == "nox-stream-handler" ] for handler in active_handlers: # Avoid duplicate handlers by removing all we've previously created # this causes trouble in tests where setup_logging is called multiple # times root_logger.removeHandler(handler) handler = logging.StreamHandler() handler.set_name("nox-stream-handler") handler.setFormatter(_get_formatter(color=color, add_timestamp=add_timestamp)) root_logger.addHandler(handler) # Silence noisy loggers logging.getLogger("sh").setLevel(logging.WARNING) logging.getLogger("httpx").setLevel(logging.WARNING) logging.getLogger("httpcore").setLevel(logging.WARNING)
LoggerWithSuccessAndOutput
python
kubernetes-client__python
kubernetes/client/models/v1_storage_class_list.py
{ "start": 383, "end": 6951 }
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 = { 'api_version': 'str', 'items': 'list[V1StorageClass]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 """V1StorageClassList - 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._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1StorageClassList. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1StorageClassList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1StorageClassList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1StorageClassList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1StorageClassList. # noqa: E501 items is the list of StorageClasses # noqa: E501 :return: The items of this V1StorageClassList. # noqa: E501 :rtype: list[V1StorageClass] """ return self._items @items.setter def items(self, items): """Sets the items of this V1StorageClassList. items is the list of StorageClasses # noqa: E501 :param items: The items of this V1StorageClassList. # noqa: E501 :type: list[V1StorageClass] """ if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1StorageClassList. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1StorageClassList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1StorageClassList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1StorageClassList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1StorageClassList. # noqa: E501 :return: The metadata of this V1StorageClassList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1StorageClassList. :param metadata: The metadata of this V1StorageClassList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata 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, V1StorageClassList): 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, V1StorageClassList): return True return self.to_dict() != other.to_dict()
V1StorageClassList
python
davidhalter__jedi
test/completion/classes.py
{ "start": 6736, "end": 6883 }
class ____: class __getattr__(): pass #? [] WeirdGetattr().something # ----------------- # private vars # -----------------
WeirdGetattr
python
apache__airflow
providers/yandex/src/airflow/providers/yandex/hooks/yq.py
{ "start": 1123, "end": 3503 }
class ____(YandexCloudBaseHook): """A hook for Yandex Query.""" def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) config = YQHttpClientConfig( token=self._get_iam_token(), project=self.default_folder_id, user_agent=provider_user_agent() ) self.client: YQHttpClient = YQHttpClient(config=config) def close(self): """Release all resources.""" self.client.close() def create_query(self, query_text: str | None, name: str | None = None) -> str: """ Create and run query. :param query_text: SQL text. :param name: name for the query """ return self.client.create_query( name=name, query_text=query_text, ) def wait_results(self, query_id: str, execution_timeout: timedelta = timedelta(minutes=30)) -> Any: """ Wait for query complete and get results. :param query_id: ID of query. :param execution_timeout: how long to wait for the query to complete. """ result_set_count = self.client.wait_query_to_succeed( query_id, execution_timeout=execution_timeout, stop_on_timeout=True ) return self.client.get_query_all_result_sets(query_id=query_id, result_set_count=result_set_count) def stop_query(self, query_id: str) -> None: """ Stop the query. :param query_id: ID of the query. """ self.client.stop_query(query_id) def get_query(self, query_id: str) -> Any: """ Get query info. :param query_id: ID of the query. """ return self.client.get_query(query_id) def get_query_status(self, query_id: str) -> str: """ Get status of the query. :param query_id: ID of query. """ return self.client.get_query_status(query_id) def compose_query_web_link(self, query_id: str): """ Compose web link to query in Yandex Query UI. :param query_id: ID of query. """ return self.client.compose_query_web_link(query_id) def _get_iam_token(self) -> str: if "token" in self.credentials: return self.credentials["token"] return yc_auth.get_auth_token(service_account_key=self.credentials.get("service_account_key"))
YQHook
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass11.py
{ "start": 666, "end": 902 }
class ____(metaclass=MetaB): var0: int # This should generate an error ClassB.var0 = "" ClassB.var1 = "" ClassB().var0 = 1 # This should generate an error ClassB().var0 = "" # This should generate an error ClassB().var1 = ""
ClassB
python
openai__openai-python
src/openai/types/beta/threads/runs/tool_call_delta_object.py
{ "start": 275, "end": 615 }
class ____(BaseModel): type: Literal["tool_calls"] """Always `tool_calls`.""" tool_calls: Optional[List[ToolCallDelta]] = None """An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`. """
ToolCallDeltaObject
python
django__django
tests/admin_views/models.py
{ "start": 18589, "end": 18698 }
class ____(models.Model): start_date = models.DateTimeField() price = models.IntegerField()
Reservation
python
pandas-dev__pandas
pandas/io/formats/info.py
{ "start": 29668, "end": 30487 }
class ____(_TableBuilderAbstract): """ Abstract builder for series info table. Parameters ---------- info : SeriesInfo. Instance of SeriesInfo. """ def __init__(self, *, info: SeriesInfo) -> None: self.info: SeriesInfo = info def get_lines(self) -> list[str]: self._lines = [] self._fill_non_empty_info() return self._lines @property def data(self) -> Series: """Series.""" return self.info.data def add_memory_usage_line(self) -> None: """Add line containing memory usage.""" self._lines.append(f"memory usage: {self.memory_usage_string}") @abstractmethod def _fill_non_empty_info(self) -> None: """Add lines to the info table, pertaining to non-empty series."""
_SeriesTableBuilder
python
xlwings__xlwings
xlwings/pro/reports/markdown.py
{ "start": 1007, "end": 1380 }
class ____(Style): def __init__( self, display_name=None, color=None, size=None, bold=None, italic=None, name=None, ): super().__init__(display_name=display_name) self.color = color self.size = size self.bold = bold self.italic = italic self.name = name
FontStyle
python
astropy__astropy
astropy/visualization/wcsaxes/frame.py
{ "start": 448, "end": 4139 }
class ____: """ A single side of an axes. This does not need to be a straight line, but represents a 'side' when determining which part of the frame to put labels and ticks on. Parameters ---------- parent_axes : `~astropy.visualization.wcsaxes.WCSAxes` The parent axes transform : `~matplotlib.transforms.Transform` The transform from data to world data_func : callable If not ``None``, it should be a function that returns the appropriate spine data when called with this object as the sole argument. If ``None``, the spine data must be manually updated in ``update_spines()``. """ def __init__(self, parent_axes, transform, *, data_func=None): self.parent_axes = parent_axes self.transform = transform self.data_func = data_func self._data = None self._world = None @property def data(self): if self._data is None and self.data_func: self.data = self.data_func(self) return self._data @data.setter def data(self, value): self._data = value if value is None: self._world = None else: with np.errstate(invalid="ignore"): self._world = self.transform.transform(self._data) self._update_normal() def _get_pixel(self): return self.parent_axes.transData.transform(self._data) @property def pixel(self): warnings.warn( "Pixel coordinates cannot be accurately calculated unless " "Matplotlib is currently drawing a figure, so the .pixel " "attribute is deprecated and will be removed in a future " "astropy release.", AstropyDeprecationWarning, ) return self._get_pixel() @pixel.setter def pixel(self, value): warnings.warn( "Manually setting pixel values of a Spine can lead to incorrect results " "as these can only be accurately calculated when Matplotlib is drawing " "a figure. As such the .pixel setter now does nothing, is deprecated, " "and will be removed in a future astropy release.", AstropyDeprecationWarning, ) @property def world(self): return self._world @world.setter def world(self, value): self._world = value if value is None: self._data = None self._pixel = None else: self._data = self.transform.transform(value) self._pixel = self.parent_axes.transData.transform(self._data) self._update_normal() def _update_normal(self): pixel = self._get_pixel() # Find angle normal to border and inwards, in display coordinate dx = pixel[1:, 0] - pixel[:-1, 0] dy = pixel[1:, 1] - pixel[:-1, 1] self.normal_angle = np.degrees(np.arctan2(dx, -dy)) def _halfway_x_y_angle(self): """ Return the x, y, normal_angle values halfway along the spine. """ pixel = self._get_pixel() x_disp, y_disp = pixel[:, 0], pixel[:, 1] # Get distance along the path d = np.hstack( [0.0, np.cumsum(np.sqrt(np.diff(x_disp) ** 2 + np.diff(y_disp) ** 2))] ) xcen = np.interp(d[-1] / 2.0, d, x_disp) ycen = np.interp(d[-1] / 2.0, d, y_disp) # Find segment along which the mid-point lies imin = np.searchsorted(d, d[-1] / 2.0) - 1 # Find normal of the axis label facing outwards on that segment normal_angle = self.normal_angle[imin] + 180.0 return xcen, ycen, normal_angle
Spine
python
huggingface__transformers
src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py
{ "start": 2876, "end": 3235 }
class ____: """Fake command line arguments needed by mask2former/detectron implementation""" config_file: str def setup_cfg(args: Args): # load config from file and command-line arguments cfg = get_cfg() add_deeplab_config(cfg) add_maskformer2_config(cfg) cfg.merge_from_file(args.config_file) cfg.freeze() return cfg
Args
python
pyqtgraph__pyqtgraph
pyqtgraph/flowchart/library/Operators.py
{ "start": 55, "end": 438 }
class ____(Node): """Generic node for performing any operation like Out = In.fn()""" def __init__(self, name, fn): self.fn = fn Node.__init__(self, name, terminals={ 'In': {'io': 'in'}, 'Out': {'io': 'out', 'bypass': 'In'} }) def process(self, **args): return {'Out': getattr(args['In'], self.fn)()}
UniOpNode
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 213532, "end": 214210 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("BypassPullRequestAllowanceEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field( sgqlc.types.list_of("BypassPullRequestAllowance"), graphql_name="nodes" ) page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
BypassPullRequestAllowanceConnection
python
MongoEngine__mongoengine
mongoengine/base/metaclasses.py
{ "start": 17656, "end": 18014 }
class ____(dict): """Custom dictionary for meta classes. Handles the merging of set indexes """ _merge_options = ("indexes",) def merge(self, new_options): for k, v in new_options.items(): if k in self._merge_options: self[k] = self.get(k, []) + v else: self[k] = v
MetaDict
python
ray-project__ray
rllib/models/torch/misc.py
{ "start": 6998, "end": 9323 }
class ____(nn.Module): """Simple mock of tf.slim Conv2d""" def __init__( self, in_channels: int, out_channels: int, kernel: Union[int, Tuple[int, int]], stride: Union[int, Tuple[int, int]], padding: Union[int, Tuple[int, int]], # Defaulting these to nn.[..] will break soft torch import. initializer: Any = "default", activation_fn: Any = "default", bias_init: float = 0, ): """Creates a standard Conv2d layer, similar to torch.nn.Conv2d Args: in_channels: Number of input channels out_channels: Number of output channels kernel: If int, the kernel is a tuple(x,x). Elsewise, the tuple can be specified stride: Controls the stride for the cross-correlation. If int, the stride is a tuple(x,x). Elsewise, the tuple can be specified padding: Controls the amount of implicit zero-paddings during the conv operation initializer: Initializer function for kernel weights activation_fn: Activation function at the end of layer bias_init: Initalize bias weights to bias_init const """ super(SlimConv2d, self).__init__() layers = [] # Padding layer. if padding: layers.append(nn.ZeroPad2d(padding)) # Actual Conv2D layer (including correct initialization logic). conv = nn.Conv2d(in_channels, out_channels, kernel, stride) if initializer: if initializer == "default": initializer = nn.init.xavier_uniform_ initializer(conv.weight) nn.init.constant_(conv.bias, bias_init) layers.append(conv) # Activation function (if any; default=ReLu). if isinstance(activation_fn, str): if activation_fn == "default": activation_fn = nn.ReLU else: activation_fn = get_activation_fn(activation_fn, "torch") if activation_fn is not None: layers.append(activation_fn()) # Put everything in sequence. self._model = nn.Sequential(*layers) def forward(self, x: TensorType) -> TensorType: return self._model(x) @DeveloperAPI
SlimConv2d
python
explosion__spaCy
spacy/lang/zh/__init__.py
{ "start": 11154, "end": 11387 }
class ____(BaseDefaults): config = load_config_from_str(DEFAULT_CONFIG) lex_attr_getters = LEX_ATTRS stop_words = STOP_WORDS writing_system = {"direction": "ltr", "has_case": False, "has_letters": False}
ChineseDefaults
python
sympy__sympy
sympy/functions/special/zeta_functions.py
{ "start": 18389, "end": 21000 }
class ____(DefinedFunction): r""" Dirichlet eta function. Explanation =========== For $\operatorname{Re}(s) > 0$ and $0 < x \le 1$, this function is defined as .. math:: \eta(s, a) = \sum_{n=0}^\infty \frac{(-1)^n}{(n+a)^s}. It admits a unique analytic continuation to all of $\mathbb{C}$ for any fixed $a$ not a nonpositive integer. It is an entire, unbranched function. It can be expressed using the Hurwitz zeta function as .. math:: \eta(s, a) = \zeta(s,a) - 2^{1-s} \zeta\left(s, \frac{a+1}{2}\right) and using the generalized Genocchi function as .. math:: \eta(s, a) = \frac{G(1-s, a)}{2(s-1)}. In both cases the limiting value of $\log2 - \psi(a) + \psi\left(\frac{a+1}{2}\right)$ is used when $s = 1$. Examples ======== >>> from sympy import dirichlet_eta, zeta >>> from sympy.abc import s >>> dirichlet_eta(s).rewrite(zeta) Piecewise((log(2), Eq(s, 1)), ((1 - 2**(1 - s))*zeta(s), True)) See Also ======== zeta References ========== .. [1] https://en.wikipedia.org/wiki/Dirichlet_eta_function .. [2] Peter Luschny, "An introduction to the Bernoulli function", https://arxiv.org/abs/2009.06743 """ @classmethod def eval(cls, s, a=None): if a is S.One: return cls(s) if a is None: if s == 1: return log(2) z = zeta(s) if not z.has(zeta): return (1 - 2**(1-s)) * z return elif s == 1: from sympy.functions.special.gamma_functions import digamma return log(2) - digamma(a) + digamma((a+1)/2) z1 = zeta(s, a) z2 = zeta(s, (a+1)/2) if not z1.has(zeta) and not z2.has(zeta): return z1 - 2**(1-s) * z2 def _eval_rewrite_as_zeta(self, s, a=1, **kwargs): from sympy.functions.special.gamma_functions import digamma if a == 1: return Piecewise((log(2), Eq(s, 1)), ((1 - 2**(1-s)) * zeta(s), True)) return Piecewise((log(2) - digamma(a) + digamma((a+1)/2), Eq(s, 1)), (zeta(s, a) - 2**(1-s) * zeta(s, (a+1)/2), True)) def _eval_rewrite_as_genocchi(self, s, a=S.One, **kwargs): from sympy.functions.special.gamma_functions import digamma return Piecewise((log(2) - digamma(a) + digamma((a+1)/2), Eq(s, 1)), (genocchi(1-s, a) / (2 * (s-1)), True)) def _eval_evalf(self, prec): if all(i.is_number for i in self.args): return self.rewrite(zeta)._eval_evalf(prec)
dirichlet_eta
python
jina-ai__jina
tests/integration/streaming/test_clients_streaming.py
{ "start": 1356, "end": 1730 }
class ____(Executor): """Fast Executor""" @requests def foo(self, docs: DocumentArray, **kwargs): for doc in docs: doc.tags['executor'] = time.time() print( f'in FastExecutor: {doc.id}, time: {readable_time_from(doc.tags["executor"])}, {doc.tags["executor"]}', flush=True, )
FastExecutor
python
django__django
tests/migrations/test_migrations_squashed_replaced_order/app1/0002_squashed_initial.py
{ "start": 35, "end": 286 }
class ____(migrations.Migration): initial = True replaces = [ ("app1", "0001_initial"), ] dependencies = [ ("app1", "0001_squashed_initial"), ("app2", "0001_squashed_initial"), ] operations = []
Migration
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 164899, "end": 166070 }
class ____(TestCase): def test_basic(self): for iterable, expected in [ ([], True), ([1, 2, 3], True), ([1, 1], False), ([1, 2, 3, 1], False), ([1, 2, 3, '1'], True), ]: with self.subTest(args=(iterable,)): self.assertEqual(mi.all_unique(iterable), expected) def test_non_hashable(self): self.assertEqual(mi.all_unique([[1, 2], [3, 4]]), True) self.assertEqual(mi.all_unique([[1, 2], [3, 4], [1, 2]]), False) def test_partially_hashable(self): self.assertEqual(mi.all_unique([[1, 2], [3, 4], (5, 6)]), True) self.assertEqual( mi.all_unique([[1, 2], [3, 4], (5, 6), [1, 2]]), False ) self.assertEqual( mi.all_unique([[1, 2], [3, 4], (5, 6), (5, 6)]), False ) def test_key(self): iterable = ['A', 'B', 'C', 'b'] self.assertEqual(mi.all_unique(iterable, lambda x: x), True) self.assertEqual(mi.all_unique(iterable, str.lower), False) def test_infinite(self): self.assertEqual(mi.all_unique(mi.prepend(3, count())), False)
AllUniqueTests
python
huggingface__transformers
src/transformers/data/processors/glue.py
{ "start": 11832, "end": 13532 }
class ____(DataProcessor): """Processor for the STS-B data set (GLUE version).""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) warnings.warn(DEPRECATION_WARNING.format("processor"), FutureWarning) def get_example_from_tensor_dict(self, tensor_dict): """See base class.""" return InputExample( tensor_dict["idx"].numpy(), tensor_dict["sentence1"].numpy().decode("utf-8"), tensor_dict["sentence2"].numpy().decode("utf-8"), str(tensor_dict["label"].numpy()), ) def get_train_examples(self, data_dir): """See base class.""" return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return [None] def _create_examples(self, lines, set_type): """Creates examples for the training, dev and test sets.""" examples = [] for i, line in enumerate(lines): if i == 0: continue guid = f"{set_type}-{line[0]}" text_a = line[7] text_b = line[8] label = None if set_type == "test" else line[-1] examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples
StsbProcessor
python
kamyu104__LeetCode-Solutions
Python/alice-and-bob-playing-flower-game.py
{ "start": 45, "end": 211 }
class ____(object): def flowerGame(self, n, m): """ :type n: int :type m: int :rtype: int """ return (n*m)//2
Solution
python
PyCQA__pylint
tests/functional/a/attribute_defined_outside_init.py
{ "start": 1084, "end": 1289 }
class ____: def __init__(self, param): self.prop = param @property def prop(self): return self.__prop @prop.setter def prop(self, value): self.__prop = value
Mine
python
numba__numba
numba/tests/test_dataflow.py
{ "start": 1194, "end": 4848 }
class ____(TestCase): def test_assignments(self, flags=force_pyobj_jit_opt): pyfunc = assignments cfunc = jit((types.int32,), **flags)(pyfunc) for x in [-1, 0, 1]: self.assertPreciseEqual(pyfunc(x), cfunc(x)) def test_assignments2(self, flags=force_pyobj_jit_opt): pyfunc = assignments2 cfunc = jit((types.int32,), **flags)(pyfunc) for x in [-1, 0, 1]: self.assertPreciseEqual(pyfunc(x), cfunc(x)) if flags is force_pyobj_jit_opt: cfunc("a") # The dataflow analysis must be good enough for native mode # compilation to succeed, hence the use of njit in the following tests. def run_propagate_func(self, func, args): self.assertPreciseEqual(func(*args), func.py_func(*args)) def test_var_propagate1(self): cfunc = njit((types.intp, types.intp))(var_propagate1) self.run_propagate_func(cfunc, (2, 3)) self.run_propagate_func(cfunc, (3, 2)) def test_var_propagate2(self): cfunc = njit((types.intp, types.intp))(var_propagate2) self.run_propagate_func(cfunc, (2, 3)) self.run_propagate_func(cfunc, (3, 2)) def test_var_propagate3(self): cfunc = njit((types.intp, types.intp))(var_propagate3) self.run_propagate_func(cfunc, (2, 3)) self.run_propagate_func(cfunc, (3, 2)) self.run_propagate_func(cfunc, (2, 0)) self.run_propagate_func(cfunc, (-1, 0)) self.run_propagate_func(cfunc, (0, 2)) self.run_propagate_func(cfunc, (0, -1)) def test_var_propagate4(self): cfunc = njit((types.intp, types.intp))(var_propagate4) self.run_propagate_func(cfunc, (1, 1)) self.run_propagate_func(cfunc, (1, 0)) self.run_propagate_func(cfunc, (1, -1)) self.run_propagate_func(cfunc, (0, 1)) self.run_propagate_func(cfunc, (0, 0)) self.run_propagate_func(cfunc, (0, -1)) self.run_propagate_func(cfunc, (-1, 1)) self.run_propagate_func(cfunc, (-1, 0)) self.run_propagate_func(cfunc, (-1, -1)) def test_chained_compare(self, flags=force_pyobj_jit_opt): pyfunc = chained_compare cfunc = jit((types.int32,), **flags)(pyfunc) for x in [0, 1, 2, 3, 4]: self.assertPreciseEqual(pyfunc(x), cfunc(x)) def test_chained_compare_npm(self): self.test_chained_compare(no_pyobj_jit_opt) def test_stack_effect_error(self, flags=force_pyobj_jit_opt): # Issue #591: POP_BLOCK must undo all stack pushes done inside # the block. pyfunc = stack_effect_error cfunc = jit((types.int32,), **flags)(pyfunc) for x in (0, 1, 2, 3): self.assertPreciseEqual(pyfunc(x), cfunc(x)) def test_stack_effect_error_npm(self): self.test_stack_effect_error(no_pyobj_jit_opt) def test_var_swapping(self, flags=force_pyobj_jit_opt): pyfunc = var_swapping cfunc = jit((types.int32,) * 5, **flags)(pyfunc) args = tuple(range(0, 10, 2)) self.assertPreciseEqual(pyfunc(*args), cfunc(*args)) def test_var_swapping_npm(self): self.test_var_swapping(no_pyobj_jit_opt) def test_for_break(self, flags=force_pyobj_jit_opt): # BREAK_LOOP must unwind the current inner syntax block. pyfunc = for_break cfunc = jit((types.intp, types.intp), **flags)(pyfunc) for (n, x) in [(4, 2), (4, 6)]: self.assertPreciseEqual(pyfunc(n, x), cfunc(n, x)) def test_for_break_npm(self): self.test_for_break(no_pyobj_jit_opt) if __name__ == '__main__': unittest.main()
TestDataFlow
python
keras-team__keras
keras/src/layers/pooling/global_max_pooling2d.py
{ "start": 261, "end": 2451 }
class ____(BaseGlobalPooling): """Global max pooling operation for 2D data. Args: data_format: string, either `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, height, width, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, features, height, weight)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be `"channels_last"`. keepdims: A boolean, whether to keep the temporal dimension or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the spatial dimension are retained with length 1. The behavior is the same as for `tf.reduce_mean` or `np.mean`. Input shape: - If `data_format='channels_last'`: 4D tensor with shape: `(batch_size, height, width, channels)` - If `data_format='channels_first'`: 4D tensor with shape: `(batch_size, channels, height, width)` Output shape: - If `keepdims=False`: 2D tensor with shape `(batch_size, channels)`. - If `keepdims=True`: - If `data_format="channels_last"`: 4D tensor with shape `(batch_size, 1, 1, channels)` - If `data_format="channels_first"`: 4D tensor with shape `(batch_size, channels, 1, 1)` Example: >>> x = np.random.rand(2, 4, 5, 3) >>> y = keras.layers.GlobalMaxPooling2D()(x) >>> y.shape (2, 3) """ def __init__(self, data_format=None, keepdims=False, **kwargs): super().__init__( pool_dimensions=2, data_format=data_format, keepdims=keepdims, **kwargs, ) def call(self, inputs): if self.data_format == "channels_last": return ops.max(inputs, axis=[1, 2], keepdims=self.keepdims) return ops.max(inputs, axis=[2, 3], keepdims=self.keepdims)
GlobalMaxPooling2D
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride1.py
{ "start": 12417, "end": 12468 }
class ____(TypedDict): values: list[str]
MyObject
python
plotly__plotly.py
plotly/graph_objs/scatterpolargl/marker/_colorbar.py
{ "start": 233, "end": 61796 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolargl.marker" _path_str = "scatterpolargl.marker.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent", "nticks", "orientation", "outlinecolor", "outlinewidth", "separatethousands", "showexponent", "showticklabels", "showtickprefix", "showticksuffix", "thickness", "thicknessmode", "tick0", "tickangle", "tickcolor", "tickfont", "tickformat", "tickformatstopdefaults", "tickformatstops", "ticklabeloverflow", "ticklabelposition", "ticklabelstep", "ticklen", "tickmode", "tickprefix", "ticks", "ticksuffix", "ticktext", "ticktextsrc", "tickvals", "tickvalssrc", "tickwidth", "title", "x", "xanchor", "xpad", "xref", "y", "yanchor", "ypad", "yref", } @property def bgcolor(self): """ Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val @property def bordercolor(self): """ Sets the axis line color. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val @property def borderwidth(self): """ Sets the width (in px) or the border enclosing this color bar. The 'borderwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["borderwidth"] @borderwidth.setter def borderwidth(self, val): self["borderwidth"] = val @property def dtick(self): """ Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" The 'dtick' property accepts values of any type Returns ------- Any """ return self["dtick"] @dtick.setter def dtick(self, val): self["dtick"] = val @property def exponentformat(self): """ Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. The 'exponentformat' property is an enumeration that may be specified as: - One of the following enumeration values: ['none', 'e', 'E', 'power', 'SI', 'B', 'SI extended'] Returns ------- Any """ return self["exponentformat"] @exponentformat.setter def exponentformat(self, val): self["exponentformat"] = val @property def labelalias(self): """ Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html- like tags or MathJax. The 'labelalias' property accepts values of any type Returns ------- Any """ return self["labelalias"] @labelalias.setter def labelalias(self, val): self["labelalias"] = val @property def len(self): """ Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. The 'len' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["len"] @len.setter def len(self, val): self["len"] = val @property def lenmode(self): """ Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. The 'lenmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["lenmode"] @lenmode.setter def lenmode(self, val): self["lenmode"] = val @property def minexponent(self): """ Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". The 'minexponent' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["minexponent"] @minexponent.setter def minexponent(self, val): self["minexponent"] = val @property def nticks(self): """ Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". The 'nticks' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["nticks"] @nticks.setter def nticks(self, val): self["nticks"] = val @property def orientation(self): """ Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v'] Returns ------- Any """ return self["orientation"] @orientation.setter def orientation(self, val): self["orientation"] = val @property def outlinecolor(self): """ Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["outlinecolor"] @outlinecolor.setter def outlinecolor(self, val): self["outlinecolor"] = val @property def outlinewidth(self): """ Sets the width (in px) of the axis line. The 'outlinewidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["outlinewidth"] @outlinewidth.setter def outlinewidth(self, val): self["outlinewidth"] = val @property def separatethousands(self): """ If "true", even 4-digit integers are separated The 'separatethousands' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["separatethousands"] @separatethousands.setter def separatethousands(self, val): self["separatethousands"] = val @property def showexponent(self): """ If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. The 'showexponent' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showexponent"] @showexponent.setter def showexponent(self, val): self["showexponent"] = val @property def showticklabels(self): """ Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showticklabels"] @showticklabels.setter def showticklabels(self, val): self["showticklabels"] = val @property def showtickprefix(self): """ If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. The 'showtickprefix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showtickprefix"] @showtickprefix.setter def showtickprefix(self, val): self["showtickprefix"] = val @property def showticksuffix(self): """ Same as `showtickprefix` but for tick suffixes. The 'showticksuffix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showticksuffix"] @showticksuffix.setter def showticksuffix(self, val): self["showticksuffix"] = val @property def thickness(self): """ Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["thickness"] @thickness.setter def thickness(self, val): self["thickness"] = val @property def thicknessmode(self): """ Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. The 'thicknessmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["thicknessmode"] @thicknessmode.setter def thicknessmode(self, val): self["thicknessmode"] = val @property def tick0(self): """ Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. The 'tick0' property accepts values of any type Returns ------- Any """ return self["tick0"] @tick0.setter def tick0(self, val): self["tick0"] = val @property def tickangle(self): """ Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. The 'tickangle' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["tickangle"] @tickangle.setter def tickangle(self, val): self["tickangle"] = val @property def tickcolor(self): """ Sets the tick color. The 'tickcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["tickcolor"] @tickcolor.setter def tickcolor(self, val): self["tickcolor"] = val @property def tickfont(self): """ Sets the color bar's tick label font The 'tickfont' property is an instance of Tickfont that may be specified as: - An instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.Tickfont` - A dict of string/value properties that will be passed to the Tickfont constructor Returns ------- plotly.graph_objs.scatterpolargl.marker.colorbar.Tickfont """ return self["tickfont"] @tickfont.setter def tickfont(self, val): self["tickfont"] = val @property def tickformat(self): """ Sets the tick label formatting rule using d3 formatting mini- languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" The 'tickformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickformat"] @tickformat.setter def tickformat(self, val): self["tickformat"] = val @property def tickformatstops(self): """ The 'tickformatstops' property is a tuple of instances of Tickformatstop that may be specified as: - A list or tuple of instances of plotly.graph_objs.scatterpolargl.marker.colorbar.Tickformatstop - A list or tuple of dicts of string/value properties that will be passed to the Tickformatstop constructor Returns ------- tuple[plotly.graph_objs.scatterpolargl.marker.colorbar.Tickformatstop] """ return self["tickformatstops"] @tickformatstops.setter def tickformatstops(self, val): self["tickformatstops"] = val @property def tickformatstopdefaults(self): """ When used in a template (as layout.template.data.scatterpolargl .marker.colorbar.tickformatstopdefaults), sets the default property values to use for elements of scatterpolargl.marker.colorbar.tickformatstops The 'tickformatstopdefaults' property is an instance of Tickformatstop that may be specified as: - An instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.Tickformatstop` - A dict of string/value properties that will be passed to the Tickformatstop constructor Returns ------- plotly.graph_objs.scatterpolargl.marker.colorbar.Tickformatstop """ return self["tickformatstopdefaults"] @tickformatstopdefaults.setter def tickformatstopdefaults(self, val): self["tickformatstopdefaults"] = val @property def ticklabeloverflow(self): """ Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabeloverflow' property is an enumeration that may be specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain'] Returns ------- Any """ return self["ticklabeloverflow"] @ticklabeloverflow.setter def ticklabeloverflow(self, val): self["ticklabeloverflow"] = val @property def ticklabelposition(self): """ Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". The 'ticklabelposition' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', 'outside top', 'inside top', 'outside left', 'inside left', 'outside right', 'inside right', 'outside bottom', 'inside bottom'] Returns ------- Any """ return self["ticklabelposition"] @ticklabelposition.setter def ticklabelposition(self, val): self["ticklabelposition"] = val @property def ticklabelstep(self): """ Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". The 'ticklabelstep' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["ticklabelstep"] @ticklabelstep.setter def ticklabelstep(self, val): self["ticklabelstep"] = val @property def ticklen(self): """ Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ticklen"] @ticklen.setter def ticklen(self, val): self["ticklen"] = val @property def tickmode(self): """ Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). The 'tickmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'linear', 'array'] Returns ------- Any """ return self["tickmode"] @tickmode.setter def tickmode(self, val): self["tickmode"] = val @property def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"] @tickprefix.setter def tickprefix(self, val): self["tickprefix"] = val @property def ticks(self): """ Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any """ return self["ticks"] @ticks.setter def ticks(self, val): self["ticks"] = val @property def ticksuffix(self): """ Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["ticksuffix"] @ticksuffix.setter def ticksuffix(self, val): self["ticksuffix"] = val @property def ticktext(self): """ Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"] @ticktext.setter def ticktext(self, val): self["ticktext"] = val @property def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for `ticktext`. The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"] @ticktextsrc.setter def ticktextsrc(self, val): self["ticktextsrc"] = val @property def tickvals(self): """ Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["tickvals"] @tickvals.setter def tickvals(self, val): self["tickvals"] = val @property def tickvalssrc(self): """ Sets the source reference on Chart Studio Cloud for `tickvals`. The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tickvalssrc"] @tickvalssrc.setter def tickvalssrc(self, val): self["tickvalssrc"] = val @property def tickwidth(self): """ Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["tickwidth"] @tickwidth.setter def tickwidth(self, val): self["tickwidth"] = val @property def title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.scatterpolargl.marker.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Returns ------- plotly.graph_objs.scatterpolargl.marker.colorbar.Title """ return self["title"] @title.setter def title(self, val): self["title"] = val @property def x(self): """ Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". The 'x' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val @property def xanchor(self): """ Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any """ return self["xanchor"] @xanchor.setter def xanchor(self, val): self["xanchor"] = val @property def xpad(self): """ Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["xpad"] @xpad.setter def xpad(self, val): self["xpad"] = val @property def xref(self): """ Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. The 'xref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["xref"] @xref.setter def xref(self, val): self["xref"] = val @property def y(self): """ Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". The 'y' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val @property def yanchor(self): """ Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"] @yanchor.setter def yanchor(self, val): self["yanchor"] = val @property def ypad(self): """ Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ypad"] @ypad.setter def ypad(self, val): self["ypad"] = val @property def yref(self): """ Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. The 'yref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["yref"] @yref.setter def yref(self, val): self["yref"] = val @property def _prop_descriptions(self): return """\ bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.scatterpolargl. marker.colorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.scatte rpolargl.marker.colorbar.tickformatstopdefaults), sets the default property values to use for elements of scatterpolargl.marker.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.scatterpolargl.marker.colo rbar.Title` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. """ def __init__( self, arg=None, bgcolor=None, bordercolor=None, borderwidth=None, dtick=None, exponentformat=None, labelalias=None, len=None, lenmode=None, minexponent=None, nticks=None, orientation=None, outlinecolor=None, outlinewidth=None, separatethousands=None, showexponent=None, showticklabels=None, showtickprefix=None, showticksuffix=None, thickness=None, thicknessmode=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklabeloverflow=None, ticklabelposition=None, ticklabelstep=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, x=None, xanchor=None, xpad=None, xref=None, y=None, yanchor=None, ypad=None, yref=None, **kwargs, ): """ Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatterpolargl .marker.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.scatterpolargl. marker.colorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.scatte rpolargl.marker.colorbar.tickformatstopdefaults), sets the default property values to use for elements of scatterpolargl.marker.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.scatterpolargl.marker.colo rbar.Title` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. Returns ------- ColorBar """ super().__init__("colorbar") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.scatterpolargl.marker.ColorBar constructor must be a dict or an instance of :class:`plotly.graph_objs.scatterpolargl.marker.ColorBar`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("bgcolor", arg, bgcolor) self._set_property("bordercolor", arg, bordercolor) self._set_property("borderwidth", arg, borderwidth) self._set_property("dtick", arg, dtick) self._set_property("exponentformat", arg, exponentformat) self._set_property("labelalias", arg, labelalias) self._set_property("len", arg, len) self._set_property("lenmode", arg, lenmode) self._set_property("minexponent", arg, minexponent) self._set_property("nticks", arg, nticks) self._set_property("orientation", arg, orientation) self._set_property("outlinecolor", arg, outlinecolor) self._set_property("outlinewidth", arg, outlinewidth) self._set_property("separatethousands", arg, separatethousands) self._set_property("showexponent", arg, showexponent) self._set_property("showticklabels", arg, showticklabels) self._set_property("showtickprefix", arg, showtickprefix) self._set_property("showticksuffix", arg, showticksuffix) self._set_property("thickness", arg, thickness) self._set_property("thicknessmode", arg, thicknessmode) self._set_property("tick0", arg, tick0) self._set_property("tickangle", arg, tickangle) self._set_property("tickcolor", arg, tickcolor) self._set_property("tickfont", arg, tickfont) self._set_property("tickformat", arg, tickformat) self._set_property("tickformatstops", arg, tickformatstops) self._set_property("tickformatstopdefaults", arg, tickformatstopdefaults) self._set_property("ticklabeloverflow", arg, ticklabeloverflow) self._set_property("ticklabelposition", arg, ticklabelposition) self._set_property("ticklabelstep", arg, ticklabelstep) self._set_property("ticklen", arg, ticklen) self._set_property("tickmode", arg, tickmode) self._set_property("tickprefix", arg, tickprefix) self._set_property("ticks", arg, ticks) self._set_property("ticksuffix", arg, ticksuffix) self._set_property("ticktext", arg, ticktext) self._set_property("ticktextsrc", arg, ticktextsrc) self._set_property("tickvals", arg, tickvals) self._set_property("tickvalssrc", arg, tickvalssrc) self._set_property("tickwidth", arg, tickwidth) self._set_property("title", arg, title) self._set_property("x", arg, x) self._set_property("xanchor", arg, xanchor) self._set_property("xpad", arg, xpad) self._set_property("xref", arg, xref) self._set_property("y", arg, y) self._set_property("yanchor", arg, yanchor) self._set_property("ypad", arg, ypad) self._set_property("yref", arg, yref) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
ColorBar
python
sympy__sympy
sympy/matrices/repmatrix.py
{ "start": 18762, "end": 33049 }
class ____(RepMatrix): """Mutable matrix based on DomainMatrix as the internal representation""" # # MutableRepMatrix is a subclass of RepMatrix that adds/overrides methods # to make the instances mutable. MutableRepMatrix is a superclass for both # MutableDenseMatrix and MutableSparseMatrix. # is_zero = False def __new__(cls, *args, **kwargs): return cls._new(*args, **kwargs) @classmethod def _new(cls, *args, copy=True, **kwargs): if copy is False: # The input was rows, cols, [list]. # It should be used directly without creating a copy. if len(args) != 3: raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]") rows, cols, flat_list = args else: rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) flat_list = list(flat_list) # create a shallow copy rep = cls._flat_list_to_DomainMatrix(rows, cols, flat_list) return cls._fromrep(rep) @classmethod def _fromrep(cls, rep): obj = super().__new__(cls) obj.rows, obj.cols = rep.shape # type: ignore obj._rep = rep return obj def copy(self): return self._fromrep(self._rep.copy()) def as_mutable(self): return self.copy() def __setitem__(self, key, value): """ Examples ======== >>> from sympy import Matrix, I, zeros, ones >>> m = Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m[1, 0] = 9 >>> m Matrix([ [1, 2 + I], [9, 4]]) >>> m[1, 0] = [[0, 1]] To replace row r you assign to position r*m where m is the number of columns: >>> M = zeros(4) >>> m = M.cols >>> M[3*m] = ones(1, m)*2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]]) And to replace column c you can assign to position c: >>> M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]]) """ rv = self._setitem(key, value) if rv is not None: i, j, value = rv self._rep, value = self._unify_element_sympy(self._rep, value) self._rep.rep.setitem(i, j, value) def _setitem(self, key, value): """Helper to set value at location given by key. Examples ======== >>> from sympy import Matrix, I, zeros, ones >>> m = Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m[1, 0] = 9 >>> m Matrix([ [1, 2 + I], [9, 4]]) >>> m[1, 0] = [[0, 1]] To replace row r you assign to position r*m where m is the number of columns: >>> M = zeros(4) >>> m = M.cols >>> M[3*m] = ones(1, m)*2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]]) And to replace column c you can assign to position c: >>> M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]]) """ is_slice = isinstance(key, slice) i, j = key = self.key2ij(key) is_mat = isinstance(value, MatrixBase) if isinstance(i, slice) or isinstance(j, slice): if isinstance(value, MatrixBase): self.copyin_matrix(key, value) return if not isinstance(value, Expr) and is_sequence(value): self.copyin_list(key, value) return raise ValueError('unexpected value: %s' % value) else: if (not is_mat and not isinstance(value, Basic) and is_sequence(value)): value = self._new(value) is_mat = True if isinstance(value, MatrixBase): if is_slice: key = (slice(*divmod(i, self.cols)), slice(*divmod(j, self.cols))) else: key = (slice(i, i + value.rows), slice(j, j + value.cols)) self.copyin_matrix(key, value) else: return i, j, self._sympify(value) # type: ignore return def _eval_col_del(self, col): # type: ignore self._rep = DomainMatrix.hstack(self._rep[:,:col], self._rep[:,col+1:]) self.cols -= 1 # type: ignore def _eval_row_del(self, row): # type: ignore self._rep = DomainMatrix.vstack(self._rep[:row,:], self._rep[row+1:, :]) self.rows -= 1 # type: ignore def _eval_col_insert(self, col, other): other = self._new(other) return self.hstack(self[:,:col], other, self[:,col:]) def _eval_row_insert(self, row, other): other = self._new(other) return self.vstack(self[:row,:], other, self[row:,:]) def col_op(self, j, f): """In-place operation on col j using two-arg functor whose args are interpreted as (self[i, j], i). Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M Matrix([ [1, 2, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== col row_op """ for i in range(self.rows): self[i, j] = f(self[i, j], i) def col_swap(self, i, j): """Swap the two given columns of the matrix in-place. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 0], [1, 0]]) >>> M Matrix([ [1, 0], [1, 0]]) >>> M.col_swap(0, 1) >>> M Matrix([ [0, 1], [0, 1]]) See Also ======== col row_swap """ for k in range(0, self.rows): self[k, i], self[k, j] = self[k, j], self[k, i] def row_op(self, i, f): """In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], j)``. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) See Also ======== row zip_row_op col_op """ for j in range(self.cols): self[i, j] = f(self[i, j], j) #The next three methods give direct support for the most common row operations inplace. def row_mult(self,i,factor): """Multiply the given row by the given factor in-place. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.row_mult(1,7); M Matrix([ [1, 0, 0], [0, 7, 0], [0, 0, 1]]) """ for j in range(self.cols): self[i,j] *= factor def row_add(self,s,t,k): """Add k times row s (source) to row t (target) in place. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.row_add(0, 2,3); M Matrix([ [1, 0, 0], [0, 1, 0], [3, 0, 1]]) """ for j in range(self.cols): self[t,j] += k*self[s,j] def row_swap(self, i, j): """Swap the two given rows of the matrix in-place. Examples ======== >>> from sympy import Matrix >>> M = Matrix([[0, 1], [1, 0]]) >>> M Matrix([ [0, 1], [1, 0]]) >>> M.row_swap(0, 1) >>> M Matrix([ [1, 0], [0, 1]]) See Also ======== row col_swap """ for k in range(0, self.cols): self[i, k], self[j, k] = self[j, k], self[i, k] def zip_row_op(self, i, k, f): """In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], self[k, j])``. Examples ======== >>> from sympy import eye >>> M = eye(3) >>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) See Also ======== row row_op col_op """ for j in range(self.cols): self[i, j] = f(self[i, j], self[k, j]) def copyin_list(self, key, value): """Copy in elements from a list. Parameters ========== key : slice The section of this matrix to replace. value : iterable The iterable to copy values from. Examples ======== >>> from sympy import eye >>> I = eye(3) >>> I[:2, 0] = [1, 2] # col >>> I Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) >>> I[1, :2] = [[3, 4]] >>> I Matrix([ [1, 0, 0], [3, 4, 0], [0, 0, 1]]) See Also ======== copyin_matrix """ if not is_sequence(value): raise TypeError("`value` must be an ordered iterable, not %s." % type(value)) return self.copyin_matrix(key, type(self)(value)) def copyin_matrix(self, key, value): """Copy in values from a matrix into the given bounds. Parameters ========== key : slice The section of this matrix to replace. value : Matrix The matrix to copy values from. Examples ======== >>> from sympy import Matrix, eye >>> M = Matrix([[0, 1], [2, 3], [4, 5]]) >>> I = eye(3) >>> I[:3, :2] = M >>> I Matrix([ [0, 1, 0], [2, 3, 0], [4, 5, 1]]) >>> I[0, 1] = M >>> I Matrix([ [0, 0, 1], [2, 2, 3], [4, 4, 5]]) See Also ======== copyin_list """ rlo, rhi, clo, chi = self.key2bounds(key) shape = value.shape dr, dc = rhi - rlo, chi - clo if shape != (dr, dc): raise ShapeError(filldedent("The Matrix `value` doesn't have the " "same dimensions " "as the in sub-Matrix given by `key`.")) for i in range(value.rows): for j in range(value.cols): self[i + rlo, j + clo] = value[i, j] def fill(self, value): """Fill self with the given value. Notes ===== Unless many values are going to be deleted (i.e. set to zero) this will create a matrix that is slower than a dense matrix in operations. Examples ======== >>> from sympy import SparseMatrix >>> M = SparseMatrix.zeros(3); M Matrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> M.fill(1); M Matrix([ [1, 1, 1], [1, 1, 1], [1, 1, 1]]) See Also ======== zeros ones """ value = _sympify(value) if not value: self._rep = DomainMatrix.zeros(self.shape, EXRAW) else: elements_dod = {i: dict.fromkeys(range(self.cols), value) for i in range(self.rows)} self._rep = DomainMatrix(elements_dod, self.shape, EXRAW) def _getitem_RepMatrix(self, key): """Return portion of self defined by key. If the key involves a slice then a list will be returned (if key is a single slice) or a matrix (if key was a tuple involving a slice). Examples ======== >>> from sympy import Matrix, I >>> m = Matrix([ ... [1, 2 + I], ... [3, 4 ]]) If the key is a tuple that does not involve a slice then that element is returned: >>> m[1, 0] 3 When a tuple key involves a slice, a matrix is returned. Here, the first column is selected (all rows, column 0): >>> m[:, 0] Matrix([ [1], [3]]) If the slice is not a tuple then it selects from the underlying list of elements that are arranged in row order and a list is returned if a slice is involved: >>> m[0] 1 >>> m[::2] [1, 3] """ if isinstance(key, tuple): i, j = key try: return self._rep.getitem_sympy(index_(i), index_(j)) except (TypeError, IndexError): if (isinstance(i, Expr) and not i.is_number) or (isinstance(j, Expr) and not j.is_number): if ((j < 0) is True) or ((j >= self.shape[1]) is True) or\ ((i < 0) is True) or ((i >= self.shape[0]) is True): raise ValueError("index out of boundary") from sympy.matrices.expressions.matexpr import MatrixElement return MatrixElement(self, i, j) if isinstance(i, slice): i = range(self.rows)[i] elif is_sequence(i): pass else: i = [i] if isinstance(j, slice): j = range(self.cols)[j] elif is_sequence(j): pass else: j = [j] return self.extract(i, j) else: # Index/slice like a flattened list rows, cols = self.shape # Raise the appropriate exception: if not rows * cols: return [][key] rep = self._rep.rep domain = rep.domain is_slice = isinstance(key, slice) if is_slice: values = [rep.getitem(*divmod(n, cols)) for n in range(rows * cols)[key]] else: values = [rep.getitem(*divmod(index_(key), cols))] if domain != EXRAW: to_sympy = domain.to_sympy values = [to_sympy(val) for val in values] if is_slice: return values else: return values[0]
MutableRepMatrix
python
django__django
tests/auth_tests/test_models.py
{ "start": 805, "end": 1727 }
class ____(TestCase): def test_user_natural_key(self): staff_user = User.objects.create_user(username="staff") self.assertEqual(User.objects.get_by_natural_key("staff"), staff_user) self.assertEqual(staff_user.natural_key(), ("staff",)) async def test_auser_natural_key(self): staff_user = await User.objects.acreate_user(username="staff") self.assertEqual(await User.objects.aget_by_natural_key("staff"), staff_user) self.assertEqual(staff_user.natural_key(), ("staff",)) def test_group_natural_key(self): users_group = Group.objects.create(name="users") self.assertEqual(Group.objects.get_by_natural_key("users"), users_group) async def test_agroup_natural_key(self): users_group = await Group.objects.acreate(name="users") self.assertEqual(await Group.objects.aget_by_natural_key("users"), users_group)
NaturalKeysTestCase
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
{ "start": 1294, "end": 1490 }
class ____(WhooshMockSearchIndex): def prepare_text(self, obj): if obj.author == "daniel3": raise SkipDocument return obj.author
WhooshMockSearchIndexWithSkipDocument
python
jina-ai__jina
jina/orchestrate/pods/__init__.py
{ "start": 9852, "end": 13173 }
class ____(BasePod): """ :class:`Pod` is a thread/process- container of :class:`BaseRuntime`. It leverages :class:`multiprocessing.Process` to manage the lifecycle of a :class:`BaseRuntime` object in a robust way. A :class:`Pod` must be equipped with a proper :class:`Runtime` class to work. """ def __init__(self, args: 'argparse.Namespace'): super().__init__(args) self.runtime_cls = self._get_runtime_cls() cargs = None self.raft_worker = None if self.args.stateful and self.args.pod_role == PodRoleType.WORKER: cargs_stateful = copy.deepcopy(args) self.raft_worker = multiprocessing.Process( target=run_raft, kwargs={ 'args': cargs_stateful, 'is_ready': self.is_ready, }, name=self.name, daemon=True, ) cargs = copy.deepcopy(cargs_stateful) if isinstance(cargs.port, int): cargs.port += RAFT_TO_EXECUTOR_PORT elif isinstance(cargs.port, list): cargs.port = [port + RAFT_TO_EXECUTOR_PORT for port in cargs.port] # if stateful, have a raft_worker self.worker = multiprocessing.Process( target=run, kwargs={ 'args': cargs or args, 'name': self.name, 'envs': self._envs, 'is_started': self.is_started, 'is_signal_handlers_installed': self.is_signal_handlers_installed, 'is_shutdown': self.is_shutdown, 'is_ready': self.is_ready, 'runtime_cls': self.runtime_cls, 'jaml_classes': JAML.registered_classes(), }, name=self.name, daemon=False, ) def start(self): """Start the Pod. This method calls :meth:`start` in :class:`multiprocesssing.Process`. .. #noqa: DAR201 """ self.worker.start() if self.raft_worker is not None: self.raft_worker.start() if not self.args.noblock_on_start: self.wait_start_success() return self def join(self, *args, **kwargs): """Joins the Pod. This method calls :meth:`join` in :class:`multiprocesssing.Process`. :param args: extra positional arguments to pass to join :param kwargs: extra keyword arguments to pass to join """ self.logger.debug(f'joining the process') self.worker.join(*args, **kwargs) if self.raft_worker is not None: self.raft_worker.join(*args, **kwargs) self.logger.debug(f'successfully joined the process') def _terminate(self): """Terminate the Pod. This method calls :meth:`terminate` in :class:`multiprocesssing.Process`. """ self.logger.debug(f'terminating the runtime process') self.worker.terminate() if self.raft_worker is not None: self.raft_worker.terminate() self.logger.debug(f'runtime process properly terminated') def _get_runtime_cls(self): from jina.orchestrate.pods.helper import update_runtime_cls update_runtime_cls(self.args) return self.args.runtime_cls
Pod
python
pyqtgraph__pyqtgraph
pyqtgraph/parametertree/parameterTypes/slider.py
{ "start": 144, "end": 3914 }
class ____(WidgetParameterItem): slider: QtWidgets.QSlider span: np.ndarray charSpan: np.ndarray def __init__(self, param, depth): # Bind emitter to self to avoid garbage collection self.emitter = Emitter() self.sigChanging = self.emitter.sigChanging self._suffix = None super().__init__(param, depth) def updateDisplayLabel(self, value=None): if value is None: value = self.param.value() self.sliderLabel.setText(self.prettyTextValue(self.slider.value())) value = str(value) if self._suffix is None: suffixTxt = '' else: suffixTxt = f' {self._suffix}' self.displayLabel.setText(value + suffixTxt) def setSuffix(self, suffix): self._suffix = suffix # This may be called during widget construction in which case there is no # displayLabel yet if hasattr(self, 'displayLabel'): self.updateDisplayLabel(self.slider.value()) def makeWidget(self): param = self.param opts = param.opts opts.setdefault('limits', [0, 0]) self._suffix = opts.get('suffix') self.slider = QtWidgets.QSlider() self.slider.setOrientation(QtCore.Qt.Orientation.Horizontal) lbl = self.sliderLabel = QtWidgets.QLabel() lbl.setAlignment(QtCore.Qt.AlignmentFlag.AlignLeft) w = QtWidgets.QWidget() layout = QtWidgets.QHBoxLayout() w.setLayout(layout) layout.addWidget(lbl) layout.addWidget(self.slider) def setValue(v): self.slider.setValue(self.spanToSliderValue(v)) def getValue(): return self.span[self.slider.value()].item() self.slider.valueChanged.connect(self.updateDisplayLabel) def onMove(pos): self.sigChanging.emit(self, self.span[pos].item()) self.slider.sliderMoved.connect(onMove) w.setValue = setValue w.value = getValue w.sigChanged = self.slider.valueChanged w.sigChanging = self.sigChanging self.optsChanged(param, opts) return w def spanToSliderValue(self, v): return int(np.argmin(np.abs(self.span - v))) def prettyTextValue(self, v): if self._suffix is None: suffixTxt = '' else: suffixTxt = f' {self._suffix}' format_ = self.param.opts.get('format', None) cspan = self.charSpan if format_ is None: format_ = f'{{0:>{cspan.dtype.itemsize}}}{suffixTxt}' return format_.format(cspan[v].decode()) def optsChanged(self, param, opts): try: super().optsChanged(param, opts) except AttributeError: # This may trigger while building the parameter before the widget is fully constructed. # This is fine, since errors are from the parent scope which will stabilize after the widget is # constructed anyway pass span = opts.get('span', None) if span is None: step = opts.get('step', 1) start, stop = opts.get('limits', param.opts['limits']) # Add a bit to 'stop' since python slicing excludes the last value span = np.arange(start, stop + step, step) precision = opts.get('precision', 2) if precision is not None: span = span.round(precision) self.span = span self.charSpan = np.char.array(span) w = self.slider w.setMinimum(0) w.setMaximum(len(span) - 1) if 'suffix' in opts: self.setSuffix(opts['suffix']) def limitsChanged(self, param, limits): self.optsChanged(param, dict(limits=limits))
SliderParameterItem
python
matplotlib__matplotlib
lib/matplotlib/animation.py
{ "start": 27377, "end": 31881 }
class ____(FileMovieWriter): """Writer for JavaScript-based HTML movies.""" supported_formats = ['png', 'jpeg', 'tiff', 'svg'] @classmethod def isAvailable(cls): return True def __init__(self, fps=30, codec=None, bitrate=None, extra_args=None, metadata=None, embed_frames=False, default_mode='loop', embed_limit=None): if extra_args: _log.warning("HTMLWriter ignores 'extra_args'") extra_args = () # Don't lookup nonexistent rcParam[args_key]. self.embed_frames = embed_frames self.default_mode = default_mode.lower() _api.check_in_list(['loop', 'once', 'reflect'], default_mode=self.default_mode) # Save embed limit, which is given in MB self._bytes_limit = mpl._val_or_rc(embed_limit, 'animation.embed_limit') # Convert from MB to bytes self._bytes_limit *= 1024 * 1024 super().__init__(fps, codec, bitrate, extra_args, metadata) def setup(self, fig, outfile, dpi=None, frame_dir=None): outfile = Path(outfile) _api.check_in_list(['.html', '.htm'], outfile_extension=outfile.suffix) self._saved_frames = [] self._total_bytes = 0 self._hit_limit = False if not self.embed_frames: if frame_dir is None: frame_dir = outfile.with_name(outfile.stem + '_frames') frame_dir.mkdir(parents=True, exist_ok=True) frame_prefix = frame_dir / 'frame' else: frame_prefix = None super().setup(fig, outfile, dpi, frame_prefix) self._clear_temp = False def grab_frame(self, **savefig_kwargs): _validate_grabframe_kwargs(savefig_kwargs) if self.embed_frames: # Just stop processing if we hit the limit if self._hit_limit: return f = BytesIO() self.fig.savefig(f, format=self.frame_format, dpi=self.dpi, **savefig_kwargs) imgdata64 = base64.encodebytes(f.getvalue()).decode('ascii') self._total_bytes += len(imgdata64) if self._total_bytes >= self._bytes_limit: _log.warning( "Animation size has reached %s bytes, exceeding the limit " "of %s. If you're sure you want a larger animation " "embedded, set the animation.embed_limit rc parameter to " "a larger value (in MB). This and further frames will be " "dropped.", self._total_bytes, self._bytes_limit) self._hit_limit = True else: self._saved_frames.append(imgdata64) else: return super().grab_frame(**savefig_kwargs) def finish(self): # save the frames to an html file if self.embed_frames: fill_frames = _embedded_frames(self._saved_frames, self.frame_format) frame_count = len(self._saved_frames) else: # temp names is filled by FileMovieWriter frame_count = len(self._temp_paths) fill_frames = _included_frames( frame_count, self.frame_format, self._temp_paths[0].parent.relative_to(self.outfile.parent)) mode_dict = dict(once_checked='', loop_checked='', reflect_checked='') mode_dict[self.default_mode + '_checked'] = 'checked' interval = 1000 // self.fps with open(self.outfile, 'w') as of: of.write(JS_INCLUDE + STYLE_INCLUDE) of.write(DISPLAY_TEMPLATE.format(id=uuid.uuid4().hex, Nframes=frame_count, fill_frames=fill_frames, interval=interval, **mode_dict)) # Duplicate the temporary file clean up logic from # FileMovieWriter.finish. We cannot call the inherited version of # finish because it assumes that there is a subprocess that we either # need to call to merge many frames together or that there is a # subprocess call that we need to clean up. if self._tmpdir: _log.debug('MovieWriter: clearing temporary path=%s', self._tmpdir) self._tmpdir.cleanup()
HTMLWriter
python
ray-project__ray
rllib/connectors/common/module_to_agent_unmapping.py
{ "start": 431, "end": 1636 }
class ____(ConnectorV2): """Performs flipping of `data` from ModuleID- to AgentID based mapping. Before mapping: data[module1] -> [col, e.g. ACTIONS] -> [dict mapping episode-identifying tuples to lists of data] data[module2] -> ... After mapping: data[ACTIONS]: [dict mapping episode-identifying tuples to lists of data] Note that episode-identifying tuples have the form of: (episode_id,) in the single-agent case and (ma_episode_id, agent_id, module_id) in the multi-agent case. """ @override(ConnectorV2) def __call__( self, *, rl_module: RLModule, batch: Dict[str, Any], episodes: List[EpisodeType], explore: Optional[bool] = None, shared_data: Optional[dict] = None, **kwargs, ) -> Any: # This Connector should only be used in a multi-agent setting. assert isinstance(episodes[0], MultiAgentEpisode) agent_data = defaultdict(dict) for module_id, module_data in batch.items(): for column, values_dict in module_data.items(): agent_data[column].update(values_dict) return dict(agent_data)
ModuleToAgentUnmapping
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/select_rebuild.py
{ "start": 150, "end": 594 }
class ____(App[None]): def compose(self) -> ComposeResult: yield Select[int]((("1", 1), ("2", 2))) yield Button("Rebuild") def on_button_pressed(self): self.query_one(Select).set_options(( ("This", 0), ("Should", 1), ("Be", 2), ("What", 3), ("Goes", 4), ("Into",5), ("The", 6), ("Snapshit", 7) )) if __name__ == "__main__": SelectRebuildApp().run()
SelectRebuildApp
python
astropy__astropy
astropy/utils/data_info.py
{ "start": 26329, "end": 27584 }
class ____(BaseColumnInfo): @property def name(self): return self._attrs.get("name") @name.setter def name(self, name: str | None): if name is None: new_name = None elif isinstance(name, str): new_name = str(name) else: raise TypeError( f"Expected a str value, got {name} with type {type(name).__name__}" ) # For mixin columns that live within a table, rename the column in the # table when setting the name attribute. This mirrors the same # functionality in the BaseColumn class. if self.parent_table is not None: self.parent_table.columns._rename_column(self.name, new_name) self._attrs["name"] = new_name @property def groups(self): # This implementation for mixin columns essentially matches the Column # property definition. `groups` is a read-only property here and # depends on the parent table of the column having `groups`. This will # allow aggregating mixins as long as they support those operations. from astropy.table import groups return self._attrs.setdefault("groups", groups.ColumnGroups(self._parent))
MixinInfo
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-make-array-equalindromic.py
{ "start": 93, "end": 2001 }
class ____(object): def minimumCost(self, nums): """ :type nums: List[int] :rtype: int """ def nth_element(nums, n, compare=lambda a, b: a < b): def tri_partition(nums, left, right, target, compare): mid = left while mid <= right: if nums[mid] == target: mid += 1 elif compare(nums[mid], target): nums[left], nums[mid] = nums[mid], nums[left] left += 1 mid += 1 else: nums[mid], nums[right] = nums[right], nums[mid] right -= 1 return left, right left, right = 0, len(nums)-1 while left <= right: pivot_idx = random.randint(left, right) pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare) if pivot_left <= n <= pivot_right: return elif pivot_left > n: right = pivot_left-1 else: # pivot_right < n. left = pivot_right+1 def nearest_palindromic(x): n = str(x) l = len(n) result = {10**l+1, 10**(l-1)-1} prefix = int(n[:(l+1)/2]) for i in map(str, (prefix-1, prefix, prefix+1)): result.add(int(i+[i, i[:-1]][l%2][::-1])) return result nth_element(nums, len(nums)//2) median = nums[len(nums)//2] if len(nums)%2 == 0: nth_element(nums, len(nums)//2-1) median = (median+nums[len(nums)//2-1])//2 return min(sum(abs(x-p) for x in nums) for p in nearest_palindromic(median)) # Time: O(nlogn + logr) # Space: O(logr) # lc0564 # sort, math, string
Solution
python
sanic-org__sanic
sanic/response/types.py
{ "start": 8646, "end": 16230 }
class ____(HTTPResponse): """Convenience class for JSON responses HTTP response to be sent back to the client, when the response is of json type. Offers several utilities to manipulate common json data types. Args: body (Optional[Any], optional): The body content to be returned. Defaults to `None`. status (int, optional): HTTP response number. Defaults to `200`. headers (Optional[Union[Header, Dict[str, str]]], optional): Headers to be returned. Defaults to `None`. content_type (str, optional): Content type to be returned (as a header). Defaults to `"application/json"`. dumps (Optional[Callable[..., AnyStr]], optional): The function to use for json encoding. Defaults to `None`. **kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to `{}`. """ # noqa: E501 __slots__ = ( "_body", "_body_manually_set", "_initialized", "_raw_body", "_use_dumps", "_use_dumps_kwargs", ) def __init__( self, body: Optional[Any] = None, status: int = 200, headers: Optional[Union[Header, dict[str, str]]] = None, content_type: str = "application/json", dumps: Optional[Callable[..., AnyStr]] = None, **kwargs: Any, ): self._initialized = False self._body_manually_set = False self._use_dumps: Callable[..., str | bytes] = ( dumps or BaseHTTPResponse._dumps ) self._use_dumps_kwargs = kwargs self._raw_body = body super().__init__( self._encode_body(self._use_dumps(body, **self._use_dumps_kwargs)), headers=headers, status=status, content_type=content_type, ) self._initialized = True def _check_body_not_manually_set(self): if self._body_manually_set: raise SanicException( "Cannot use raw_body after body has been manually set." ) @property def raw_body(self) -> Optional[Any]: """Returns the raw body, as long as body has not been manually set previously. NOTE: This object should not be mutated, as it will not be reflected in the response body. If you need to mutate the response body, consider using one of the provided methods in this class or alternatively call set_body() with the mutated object afterwards or set the raw_body property to it. Returns: Optional[Any]: The raw body """ # noqa: E501 self._check_body_not_manually_set() return self._raw_body @raw_body.setter def raw_body(self, value: Any): self._body_manually_set = False self._body = self._encode_body( self._use_dumps(value, **self._use_dumps_kwargs) ) self._raw_body = value @property # type: ignore def body(self) -> Optional[bytes]: # type: ignore """Returns the response body. Returns: Optional[bytes]: The response body """ return self._body @body.setter def body(self, value: Optional[bytes]): self._body = value if not self._initialized: return self._body_manually_set = True def set_body( self, body: Any, dumps: Optional[Callable[..., AnyStr]] = None, **dumps_kwargs: Any, ) -> None: """Set the response body to the given value, using the given dumps function Sets a new response body using the given dumps function and kwargs, or falling back to the defaults given when creating the object if none are specified. Args: body (Any): The body to set dumps (Optional[Callable[..., AnyStr]], optional): The function to use for json encoding. Defaults to `None`. **dumps_kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to `{}`. Examples: ```python response = JSONResponse({"foo": "bar"}) response.set_body({"bar": "baz"}) assert response.body == b'{"bar": "baz"}' ``` """ # noqa: E501 self._body_manually_set = False self._raw_body = body use_dumps = dumps or self._use_dumps use_dumps_kwargs = dumps_kwargs if dumps else self._use_dumps_kwargs self._body = self._encode_body(use_dumps(body, **use_dumps_kwargs)) def append(self, value: Any) -> None: """Appends a value to the response raw_body, ensuring that body is kept up to date. This can only be used if raw_body is a list. Args: value (Any): The value to append Raises: SanicException: If the body is not a list """ # noqa: E501 self._check_body_not_manually_set() if not isinstance(self._raw_body, list): raise SanicException("Cannot append to a non-list object.") self._raw_body.append(value) self.raw_body = self._raw_body def extend(self, value: Any) -> None: """Extends the response's raw_body with the given values, ensuring that body is kept up to date. This can only be used if raw_body is a list. Args: value (Any): The values to extend with Raises: SanicException: If the body is not a list """ # noqa: E501 self._check_body_not_manually_set() if not isinstance(self._raw_body, list): raise SanicException("Cannot extend a non-list object.") self._raw_body.extend(value) self.raw_body = self._raw_body def update(self, *args, **kwargs) -> None: """Updates the response's raw_body with the given values, ensuring that body is kept up to date. This can only be used if raw_body is a dict. Args: *args: The args to update with **kwargs: The kwargs to update with Raises: SanicException: If the body is not a dict """ # noqa: E501 self._check_body_not_manually_set() if not isinstance(self._raw_body, dict): raise SanicException("Cannot update a non-dict object.") self._raw_body.update(*args, **kwargs) self.raw_body = self._raw_body def pop(self, key: Any, default: Any = _default) -> Any: """Pops a key from the response's raw_body, ensuring that body is kept up to date. This can only be used if raw_body is a dict or a list. Args: key (Any): The key to pop default (Any, optional): The default value to return if the key is not found. Defaults to `_default`. Raises: SanicException: If the body is not a dict or a list TypeError: If the body is a list and a default value is provided Returns: Any: The value that was popped """ # noqa: E501 self._check_body_not_manually_set() if not isinstance(self._raw_body, (list, dict)): raise SanicException( "Cannot pop from a non-list and non-dict object." ) if isinstance(default, Default): value = self._raw_body.pop(key) elif isinstance(self._raw_body, list): raise TypeError("pop doesn't accept a default argument for lists") else: value = self._raw_body.pop(key, default) self.raw_body = self._raw_body return value
JSONResponse
python
nedbat__coveragepy
coverage/sysmon.py
{ "start": 6675, "end": 19814 }
class ____(Tracer): """Python implementation of the raw data tracer for PEP669 implementations.""" # One of these will be used across threads. Be careful. def __init__(self, tool_id: int) -> None: # Attributes set from the collector: self.data: TTraceData self.trace_arcs = False self.should_trace: TShouldTraceFn self.should_trace_cache: dict[str, TFileDisposition | None] # TODO: should_start_context and switch_context are unused! # Change tests/testenv.py:DYN_CONTEXTS when this is updated. self.should_start_context: TShouldStartContextFn | None = None self.switch_context: Callable[[str | None], None] | None = None self.lock_data: Callable[[], None] self.unlock_data: Callable[[], None] # TODO: warn is unused. self.warn: TWarnFn self.myid = tool_id # Map id(code_object) -> CodeInfo self.code_infos: dict[int, CodeInfo] = {} # A list of code_objects, just to keep them alive so that id's are # useful as identity. self.code_objects: list[CodeType] = [] # Map filename:__name__ -> set(id(code_object)) self.filename_code_ids: dict[str, set[int]] = collections.defaultdict(set) self.sysmon_on = False self.lock = threading.Lock() self.stats: dict[str, int] | None = None if COLLECT_STATS: self.stats = dict.fromkeys( "starts start_tracing returns line_lines line_arcs branches branch_trails".split(), 0, ) self._activity = False def __repr__(self) -> str: points = sum(len(v) for v in self.data.values()) files = len(self.data) return f"<SysMonitor at {id(self):#x}: {points} data points in {files} files>" @panopticon() def start(self) -> None: """Start this Tracer.""" with self.lock: assert sys_monitoring is not None sys_monitoring.use_tool_id(self.myid, "coverage.py") register = functools.partial(sys_monitoring.register_callback, self.myid) events = sys.monitoring.events sys_monitoring.set_events(self.myid, events.PY_START) register(events.PY_START, self.sysmon_py_start) if self.trace_arcs: register(events.PY_RETURN, self.sysmon_py_return) register(events.LINE, self.sysmon_line_arcs) if env.PYBEHAVIOR.branch_right_left: register( events.BRANCH_RIGHT, # type:ignore[attr-defined] self.sysmon_branch_either, ) register( events.BRANCH_LEFT, self.sysmon_branch_either, ) else: register(events.LINE, self.sysmon_line_lines) sys_monitoring.restart_events() self.sysmon_on = True @panopticon() def stop(self) -> None: """Stop this Tracer.""" with self.lock: if not self.sysmon_on: # In forking situations, we might try to stop when we are not # started. Do nothing in that case. return assert sys_monitoring is not None sys_monitoring.set_events(self.myid, 0) self.sysmon_on = False sys_monitoring.free_tool_id(self.myid) if LOG: # pragma: debugging items = sorted( self.filename_code_ids.items(), key=lambda item: len(item[1]), reverse=True, ) code_objs = sum(len(code_ids) for _, code_ids in items) dupes = code_objs - len(items) if dupes: log(f"==== Duplicate code objects: {dupes} duplicates, {code_objs} total") for filename, code_ids in items: if len(code_ids) > 1: log(f"{len(code_ids):>5} objects: {filename}") else: log("==== Duplicate code objects: none") @panopticon() def post_fork(self) -> None: """The process has forked, clean up as needed.""" self.stop() def activity(self) -> bool: """Has there been any activity?""" return self._activity def reset_activity(self) -> None: """Reset the activity() flag.""" self._activity = False def get_stats(self) -> dict[str, int] | None: """Return a dictionary of statistics, or None.""" return self.stats @panopticon("code", "@") def sysmon_py_start(self, code: CodeType, instruction_offset: TOffset) -> MonitorReturn: """Handle sys.monitoring.events.PY_START events.""" self._activity = True if self.stats is not None: self.stats["starts"] += 1 if code.co_name == "__annotate__": # Type annotation code objects don't execute, ignore them. return DISABLE # Entering a new frame. Decide if we should trace in this file. code_info = self.code_infos.get(id(code)) tracing_code: bool | None = None file_data: TTraceFileData | None = None if code_info is not None: tracing_code = code_info.tracing file_data = code_info.file_data if tracing_code is None: filename = code.co_filename disp = self.should_trace_cache.get(filename) if disp is None: frame = inspect.currentframe() if frame is not None: frame = inspect.currentframe().f_back # type: ignore[union-attr] if LOG: # pragma: debugging # @panopticon adds a frame. frame = frame.f_back # type: ignore[union-attr] disp = self.should_trace(filename, frame) # type: ignore[arg-type] self.should_trace_cache[filename] = disp tracing_code = disp.trace if tracing_code: tracename = disp.source_filename assert tracename is not None self.lock_data() try: if tracename not in self.data: self.data[tracename] = set() finally: self.unlock_data() file_data = self.data[tracename] b2l = bytes_to_lines(code) else: file_data = None b2l = None code_info = CodeInfo( tracing=tracing_code, file_data=file_data, byte_to_line=b2l, branch_trails={}, always_jumps={}, ) self.code_infos[id(code)] = code_info self.code_objects.append(code) if tracing_code: if self.stats is not None: self.stats["start_tracing"] += 1 events = sys.monitoring.events with self.lock: if self.sysmon_on: assert sys_monitoring is not None local_events = events.PY_RETURN | events.PY_RESUME | events.LINE if self.trace_arcs: assert env.PYBEHAVIOR.branch_right_left local_events |= ( events.BRANCH_RIGHT # type:ignore[attr-defined] | events.BRANCH_LEFT ) sys_monitoring.set_local_events(self.myid, code, local_events) if LOG: # pragma: debugging if code.co_filename not in {"<string>"}: self.filename_code_ids[f"{code.co_filename}:{code.co_name}"].add( id(code) ) return DISABLE @panopticon("code", "@", None) def sysmon_py_return( self, code: CodeType, instruction_offset: TOffset, retval: object, ) -> MonitorReturn: """Handle sys.monitoring.events.PY_RETURN events for branch coverage.""" if self.stats is not None: self.stats["returns"] += 1 code_info = self.code_infos.get(id(code)) # code_info is not None and code_info.file_data is not None, since we # wouldn't have enabled this event if they were. last_line = code_info.byte_to_line.get(instruction_offset) # type: ignore if last_line is not None: arc = (last_line, -code.co_firstlineno) code_info.file_data.add(arc) # type: ignore # log(f"adding {arc=}") return DISABLE @panopticon("code", "line") def sysmon_line_lines(self, code: CodeType, line_number: TLineNo) -> MonitorReturn: """Handle sys.monitoring.events.LINE events for line coverage.""" if self.stats is not None: self.stats["line_lines"] += 1 code_info = self.code_infos.get(id(code)) # It should be true that code_info is not None and code_info.file_data # is not None, since we wouldn't have enabled this event if they were. # But somehow code_info can be None here, so we have to check. if code_info is not None and code_info.file_data is not None: code_info.file_data.add(line_number) # type: ignore # log(f"adding {line_number=}") return DISABLE @panopticon("code", "line") def sysmon_line_arcs(self, code: CodeType, line_number: TLineNo) -> MonitorReturn: """Handle sys.monitoring.events.LINE events for branch coverage.""" if self.stats is not None: self.stats["line_arcs"] += 1 code_info = self.code_infos[id(code)] # code_info is not None and code_info.file_data is not None, since we # wouldn't have enabled this event if they were. arc = (line_number, line_number) code_info.file_data.add(arc) # type: ignore # log(f"adding {arc=}") return DISABLE @panopticon("code", "@", "@") def sysmon_branch_either( self, code: CodeType, instruction_offset: TOffset, destination_offset: TOffset ) -> MonitorReturn: """Handle BRANCH_RIGHT and BRANCH_LEFT events.""" if self.stats is not None: self.stats["branches"] += 1 code_info = self.code_infos[id(code)] # code_info is not None and code_info.file_data is not None, since we # wouldn't have enabled this event if they were. if not code_info.branch_trails: if self.stats is not None: self.stats["branch_trails"] += 1 multiline_map = get_multiline_map(code.co_filename) code_info.branch_trails = branch_trails(code, multiline_map=multiline_map) code_info.always_jumps = always_jumps(code) # log(f"branch_trails for {code}:\n{ppformat(code_info.branch_trails)}") added_arc = False dest_info = code_info.branch_trails.get(instruction_offset) # Re-map the destination offset through always-jumps to deal with NOP etc. dests = {destination_offset} while (dest := code_info.always_jumps.get(destination_offset)) is not None: destination_offset = dest dests.add(destination_offset) # log(f"dest_info = {ppformat(dest_info)}") if dest_info is not None: for arc, offsets in dest_info.items(): if arc is None: continue if dests & offsets: code_info.file_data.add(arc) # type: ignore # log(f"adding {arc=}") added_arc = True break if not added_arc: # This could be an exception jumping from line to line. assert code_info.byte_to_line is not None l1 = code_info.byte_to_line.get(instruction_offset) if l1 is not None: l2 = code_info.byte_to_line.get(destination_offset) if l2 is not None and l1 != l2: arc = (l1, l2) code_info.file_data.add(arc) # type: ignore # log(f"adding unforeseen {arc=}") return DISABLE @functools.lru_cache(maxsize=20) def get_multiline_map(filename: str) -> dict[TLineNo, TLineNo]: """Get a PythonParser for the given filename, cached.""" try: parser = PythonParser(filename=filename) parser.parse_source() except NotPython: # The file was not Python. This can happen when the code object refers # to an original non-Python source file, like a Jinja template. # In that case, just return an empty map, which might lead to slightly # wrong branch coverage, but we don't have any better option. return {} except NoSource: # This can happen if open() in python.py fails. return {} return parser.multiline_map
SysMonitor
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 4570, "end": 4723 }
class ____(BaseIntType): @classmethod def validate(cls, value: Any) -> None: cls.validate_int_in_range(value, 0, 4294967295)
XsdUnsignedInt
python
ansible__ansible
lib/ansible/modules/group.py
{ "start": 4022, "end": 9009 }
class ____(object): """ This is a generic Group manipulation class that is subclassed based on platform. A subclass may wish to override the following action methods:- - group_del() - group_add() - group_mod() All subclasses MUST define platform and distribution (which may be None). """ platform = 'Generic' distribution = None # type: str | None GROUPFILE = '/etc/group' def __new__(cls, *args, **kwargs): new_cls = get_platform_subclass(Group) return super(cls, new_cls).__new__(new_cls) def __init__(self, module): self.module = module self.state = module.params['state'] self.name = module.params['name'] self.force = module.params['force'] self.gid = module.params['gid'] self.system = module.params['system'] self.local = module.params['local'] self.non_unique = module.params['non_unique'] self.gid_min = module.params['gid_min'] self.gid_max = module.params['gid_max'] if self.local: if self.gid_min is not None: module.fail_json(msg="'gid_min' can not be used with 'local'") if self.gid_max is not None: module.fail_json(msg="'gid_max' can not be used with 'local'") def execute_command(self, cmd): return self.module.run_command(cmd) def group_del(self): if self.local: command_name = 'lgroupdel' else: command_name = 'groupdel' cmd = [self.module.get_bin_path(command_name, True), self.name] return self.execute_command(cmd) def _local_check_gid_exists(self): if self.gid: for gr in grp.getgrall(): if self.gid == gr.gr_gid and self.name != gr.gr_name: self.module.fail_json(msg="GID '{0}' already exists with group '{1}'".format(self.gid, gr.gr_name)) def group_add(self, **kwargs): if self.local: command_name = 'lgroupadd' self._local_check_gid_exists() else: command_name = 'groupadd' cmd = [self.module.get_bin_path(command_name, True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') elif key == 'system' and kwargs[key] is True: cmd.append('-r') if self.gid_min is not None: cmd.append('-K') cmd.append('GID_MIN=' + str(self.gid_min)) if self.gid_max is not None: cmd.append('-K') cmd.append('GID_MAX=' + str(self.gid_max)) cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): if self.local: command_name = 'lgroupmod' self._local_check_gid_exists() else: command_name = 'groupmod' cmd = [self.module.get_bin_path(command_name, True)] info = self.group_info() for key in kwargs: if key == 'gid': if kwargs[key] is not None and info[2] != int(kwargs[key]): cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) def group_exists(self): # The grp module does not distinguish between local and directory accounts. # It's output cannot be used to determine whether or not a group exists locally. # It returns True if the group exists locally or in the directory, so instead # look in the local GROUP file for an existing account. if self.local: if not os.path.exists(self.GROUPFILE): self.module.fail_json(msg="'local: true' specified but unable to find local group file {0} to parse.".format(self.GROUPFILE)) exists = False name_test = '{0}:'.format(self.name) with open(self.GROUPFILE, 'rb') as f: reversed_lines = f.readlines()[::-1] for line in reversed_lines: if line.startswith(to_bytes(name_test)): exists = True break return exists else: try: if grp.getgrnam(self.name): return True except KeyError: return False def group_info(self): if not self.group_exists(): return False try: info = list(grp.getgrnam(self.name)) except KeyError: return False return info # ===========================================
Group
python
joke2k__faker
faker/providers/person/de_LU/__init__.py
{ "start": 81, "end": 29592 }
class ____(PersonProvider): # Source for last names: https://nachnamen.net/luxemburg last_names = OrderedDict( ( ("Schmit", 6799), ("Muller", 5784), ("Weber", 4858), ("Wagner", 4837), ("Hoffmann", 4628), ("Thill", 3304), ("Schmitz", 3135), ("Schroeder", 2839), ("Becker", 2549), ("Klein", 2413), ("Faber", 2159), ("Da silva", 2007), ("Kieffer", 1949), ("Reuter", 1944), ("Schiltz", 1891), ("Dos santos", 1867), ("Welter", 1788), ("Simon", 1785), ("Schneider", 1721), ("Hansen", 1657), ("Meyer", 1614), ("Kremer", 1605), ("Pereira", 1580), ("Weis", 1446), ("Braun", 1381), ("Fernandes", 1368), ("Kayser", 1352), ("Kirsch", 1351), ("Steffen", 1350), ("Krier", 1311), ("Theisen", 1301), ("Majerus", 1239), ("Ries", 1203), ("Ferreira", 1153), ("Gonçalves", 1151), ("Meyers", 1148), ("Engel", 1135), ("Schumacher", 1119), ("Diederich", 1090), ("Rodrigues", 1074), ("Martin", 1065), ("Marx", 1062), ("Gomes", 1043), ("Molitor", 1030), ("Theis", 1021), ("Wolff", 961), ("Martins", 952), ("Heinen", 914), ("Weydert", 891), ("Zimmer", 889), ("Goergen", 867), ("Fischer", 863), ("Wagener", 854), ("Reding", 837), ("Lentz", 830), ("Flammang", 828), ("Bernard", 827), ("Scholtes", 809), ("Adrovic", 800), ("Koch", 775), ("Goedert", 763), ("Arend", 753), ("Winandy", 753), ("Jacoby", 740), ("Nilles", 703), ("Gengler", 690), ("Peters", 690), ("Berg", 685), ("Lanners", 684), ("Pinto", 676), ("Sabotic", 673), ("Back", 672), ("Lopes", 663), ("Marques", 658), ("Lux", 655), ("Bertemes", 652), ("Putz", 649), ("Jung", 648), ("Haas", 633), ("Erpelding", 630), ("Schmitt", 620), ("Weiler", 613), ("Mangen", 607), ("Pauly", 602), ("Weyland", 601), ("Dostert", 599), ("Biver", 598), ("Alves", 597), ("Huberty", 594), ("Schreiner", 590), ("Decker", 590), ("Backes", 589), ("Schaus", 589), ("Olinger", 576), ("Rastoder", 562), ("Schaack", 561), ("Grethen", 554), ("Steichen", 542), ("Mendes", 541), ("Monteiro", 539), ("Oliveira", 536), ("Lucas", 536), ("Poos", 536), ("Ney", 535), ("Teixeira", 528), ("Michels", 527), ("Wirtz", 515), ("Mathieu", 511), ("Schintgen", 510), ("Scheer", 493), ("Peiffer", 486), ("Hilbert", 485), ("Thein", 478), ("Steinmetz", 470), ("Stoffel", 470), ("Da costa", 469), ("Arendt", 468), ("Clement", 468), ("Hermes", 465), ("Dumont", 463), ("Kohn", 459), ("Wies", 459), ("Feller", 454), ("Soares", 454), ("Kneip", 453), ("Kohl", 448), ("De sousa", 441), ("Thinnes", 439), ("Almeida", 437), ("Elsen", 436), ("Glod", 433), ("Mergen", 432), ("Trausch", 432), ("Mertens", 430), ("Schaeffer", 425), ("Mousel", 424), ("Heck", 419), ("Thiel", 418), ("Duarte", 418), ("Lang", 416), ("Mersch", 414), ("Linden", 414), ("Thiry", 413), ("Muhovic", 411), ("Bausch", 411), ("Georges", 410), ("Lambert", 403), ("Hengen", 403), ("Konsbruck", 397), ("Trierweiler", 395), ("Ewen", 393), ("Kohnen", 391), ("Berchem", 388), ("Schmidt", 387), ("Thoma", 384), ("Heiderscheid", 383), ("May", 382), ("Wantz", 381), ("Clemens", 380), ("Conter", 379), ("Felten", 377), ("Gerard", 377), ("Garcia", 376), ("Ribeiro", 372), ("Skrijelj", 370), ("Wolter", 369), ("Lorang", 361), ("Nickels", 360), ("Barthel", 359), ("Huss", 358), ("Jeitz", 358), ("Moes", 357), ("Werner", 357), ("Kerschen", 354), ("Sinner", 352), ("Bertrand", 350), ("Kemp", 350), ("Lutgen", 349), ("Gillen", 348), ("Baustert", 346), ("Stoltz", 346), ("Lamesch", 345), ("Carvalho", 344), ("Reinert", 341), ("Schummer", 337), ("Hilger", 337), ("Michel", 333), ("Reiter", 330), ("Hubert", 329), ("Neu", 328), ("Dias", 326), ("Frisch", 322), ("Nosbusch", 322), ("Silva", 320), ("Weyrich", 320), ("Wilmes", 318), ("Brandenburger", 314), ("Manderscheid", 314), ("Pedersen", 313), ("Rollinger", 313), ("Eischen", 312), ("Kraus", 312), ("Paulus", 312), ("Kauffmann", 311), ("Colling", 310), ("Correia", 305), ("Koenig", 305), ("Glodt", 303), ("Antony", 301), ("Cardoso", 300), ("Oberweis", 298), ("Quintus", 297), ("Jost", 297), ("Agovic", 296), ("Machado", 295), ("Beffort", 293), ("Wiltzius", 292), ("Francois", 292), ("Maas", 291), ("Vitali", 291), ("Fischbach", 290), ("Reckinger", 289), ("Bauer", 288), ("Fisch", 288), ("Beck", 286), ("Andersen", 285), ("Delvaux", 284), ("Gloden", 281), ("Hames", 280), ("Ramdedovic", 280), ("Friederich", 279), ("Richard", 279), ("Melchior", 279), ("Zeimet", 278), ("Demuth", 276), ("Muratovic", 273), ("Ruppert", 273), ("Hurt", 269), ("Kass", 268), ("Hoss", 267), ("Rausch", 267), ("Thielen", 266), ("Andre", 265), ("Wampach", 265), ("Linster", 264), ("Dupont", 263), ("Dahm", 263), ("Willems", 263), ("Schartz", 260), ("Clees", 260), ("Fonck", 259), ("Wilhelm", 258), ("Jensen", 258), ("Petit", 258), ("Schank", 257), ("Kerger", 257), ("Franzen", 257), ("Gaspar", 256), ("Gilson", 256), ("Biwer", 255), ("Wolf", 254), ("Tavares", 253), ("Reiser", 253), ("De jesus", 252), ("Heintz", 250), ("Robert", 248), ("Goetzinger", 246), ("Schon", 246), ("Claude", 244), ("Halsdorf", 244), ("Moreira", 243), ("Schuler", 241), ("Schlesser", 241), ("Colbach", 241), ("Haupert", 240), ("Cikotic", 239), ("Rossi", 239), ("Siebenaler", 238), ("Daleiden", 238), ("Gaasch", 237), ("Lemmer", 237), ("Kasel", 236), ("Breuer", 235), ("Skenderovic", 234), ("Godart", 234), ("Bettendorff", 234), ("Karier", 233), ("Graf", 233), ("Louis", 233), ("Feinen", 233), ("Risch", 232), ("Weisgerber", 232), ("Beissel", 231), ("Mores", 230), ("Juncker", 229), ("Buchler", 229), ("Santos", 229), ("Feltz", 229), ("Pletschette", 228), ("Entringer", 228), ("Brosius", 227), ("Bintner", 227), ("Heirens", 226), ("Urbany", 226), ("Marnach", 226), ("Neumann", 225), ("Sauber", 225), ("Pundel", 225), ("Feyder", 225), ("Thomas", 224), ("Meisch", 224), ("Greisch", 224), ("Bruck", 224), ("Turmes", 224), ("Hemmen", 224), ("Hemmer", 222), ("Krecke", 221), ("Bintz", 220), ("Baum", 220), ("Gregoire", 219), ("Kinsch", 219), ("Gatti", 218), ("Schilling", 218), ("Schwartz", 217), ("Kaiser", 217), ("Zenner", 217), ("Thilmany", 217), ("Mathias", 215), ("Mayer", 214), ("Fuchs", 214), ("Kocan", 213), ("Staudt", 213), ("Franck", 213), ("Berscheid", 213), ("Hahn", 213), ("Strasser", 213), ("Frank", 212), ("Feltgen", 212), ("Goerens", 210), ("Ley", 209), ("Zeimes", 208), ("Lima", 208), ("Beckius", 207), ("Heuertz", 207), ("Feiereisen", 206), ("Krack", 206), ("Guillaume", 206), ("Pires", 206), ("Seil", 206), ("Kintziger", 205), ) ) # Source for first names: https://github.com/MatthiasWinkelmann/firstname-database first_names_female = OrderedDict( ( ("Ada", 0.00390625), ("Adeline", 0.015625), ("Adrienne", 0.015625), ("Agnès", 0.0625), ("Albertine", 0.0625), ("Alice", 0.25), ("Aline", 0.0625), ("Aloyse", 0.5), ("Aly", 0.125), ("Amandine", 0.00390625), ("Amélie", 0.03125), ("Andréa", 0.0625), ("Andrée", 0.125), ("Angèle", 0.0625), ("Angélique", 0.015625), ("Anita", 0.03125), ("Anna", 0.25), ("Anne", 1.0), ("Annette", 0.125), ("Annick", 0.125), ("Annie", 0.03125), ("Anouk", 0.0625), ("Antoinette", 0.125), ("Ariane", 0.015625), ("Arlette", 0.0625), ("Armande", 0.00390625), ("Armelle", 0.0078125), ("Astrid", 0.125), ("Astride", 0.015625), ("Audrey", 0.03125), ("Aurélie", 0.015625), ("Barbara", 0.0625), ("Béatrice", 0.0625), ("Béatrix", 0.00390625), ("Bénédicte", 0.015625), ("Bernadette", 0.03125), ("Berthe", 0.03125), ("Betty", 0.0625), ("Bianca", 0.03125), ("Birgit", 0.015625), ("Blanche", 0.0625), ("Blandine", 0.00390625), ("Brigitte", 0.125), ("Camille", 0.5), ("Carine", 0.125), ("Carol", 0.015625), ("Carole", 0.25), ("Caroline", 0.125), ("Catherine", 0.5), ("Cécile", 0.25), ("Cecilia", 0.0078125), ("Cecille", 0.00390625), ("Céline", 0.125), ("Chantal", 0.25), ("Chloe", 0.00390625), ("Christelle", 0.03125), ("Christiane", 0.5), ("Christine", 0.125), ("Cindy", 0.0625), ("Claire", 0.125), ("Clarisse", 0.00390625), ("Claudette", 0.0078125), ("Claudia", 0.0625), ("Claudie", 0.00390625), ("Claudine", 0.25), ("Clémentine", 0.00390625), ("Clothilde", 0.0078125), ("Clotilde", 0.00390625), ("Colette", 0.125), ("Constance", 0.0078125), ("Corinne", 0.0625), ("Cornelia", 0.015625), ("Cynthia", 0.03125), ("Damienne", 0.00390625), ("Daniela", 0.0625), ("Danièle", 0.125), ("Danielle", 0.25), ("Dany", 0.0625), ("Deborah", 0.03125), ("Delphine", 0.03125), ("Denise", 0.25), ("Désirée", 0.015625), ("Diane", 0.125), ("Doris", 0.0625), ("Dorothée", 0.0078125), ("Eléonore", 0.0078125), ("Eliane", 0.03125), ("Eliette", 0.0078125), ("Elisabeth", 0.25), ("Elise", 0.125), ("Elodie", 0.00390625), ("Elvira", 0.03125), ("Elvire", 0.03125), ("Emilie", 0.0625), ("Emma", 0.015625), ("Emmanuelle", 0.03125), ("Ernestine", 0.015625), ("Erny", 0.25), ("Estelle", 0.03125), ("Esther", 0.03125), ("Eugénie", 0.0625), ("Eunice", 0.0078125), ("Eva", 0.03125), ("Fabienne", 0.125), ("Fanny", 0.015625), ("Félicie", 0.0625), ("Fernande", 0.125), ("Ferny", 0.0078125), ("Flore", 0.00390625), ("Florence", 0.0625), ("Florentine", 0.0078125), ("France", 0.125), ("Francine", 0.125), ("Françoise", 0.25), ("Frédérique", 0.03125), ("Gabrielle", 0.0625), ("Gaby", 0.0625), ("Gaëlle", 0.0078125), ("Geneviève", 0.03125), ("Georgette", 0.125), ("Géraldine", 0.03125), ("Germaine", 0.125), ("Gertrude", 0.015625), ("Ghislaine", 0.015625), ("Gilberte", 0.03125), ("Ginette", 0.125), ("Gisèle", 0.0625), ("Hélène", 0.25), ("Heloise", 0.00390625), ("Henriette", 0.25), ("Hilda", 0.03125), ("Huguette", 0.015625), ("Ida", 0.03125), ("Inès", 0.015625), ("Ingrid", 0.03125), ("Irène", 0.25), ("Irma", 0.0625), ("Isabel", 0.125), ("Isabelle", 0.5), ("Jacqueline", 0.25), ("Janine", 0.015625), ("Jasmine", 0.015625), ("Jeanette", 0.0078125), ("Jeanine", 0.015625), ("Jeanne", 0.5), ("Jeannette", 0.03125), ("Jeannie", 0.00390625), ("Jeannine", 0.0625), ("Jeanny", 0.125), ("Jennifer", 0.03125), ("Jessica", 0.125), ("Jocelyne", 0.015625), ("Joëlle", 0.25), ("Josée", 0.5), ("Joséphine", 0.125), ("Josette", 0.25), ("Josiane", 0.125), ("Josy", 0.5), ("Judith", 0.03125), ("Julia", 0.03125), ("Julie", 0.125), ("Julienne", 0.0078125), ("Juliette", 0.0625), ("Justine", 0.015625), ("Karin", 0.125), ("Karine", 0.03125), ("Katia", 0.0078125), ("Kim", 0.0625), ("Laetitia", 0.015625), ("Laura", 0.0078125), ("Laure", 0.0625), ("Laurence", 0.125), ("Laurette", 0.00390625), ("Léa", 0.0625), ("Léone", 0.00390625), ("Léonie", 0.125), ("Léontine", 0.015625), ("Liliane", 0.25), ("Lily", 0.03125), ("Lina", 0.0625), ("Linda", 0.125), ("Louise", 0.25), ("Lucette", 0.0078125), ("Lucie", 0.125), ("Lucienne", 0.0625), ("Ludivine", 0.00390625), ("Lydia", 0.03125), ("Lydiane", 0.00390625), ("Lydianne", 0.00390625), ("Lydie", 0.0625), ("Lysiane", 0.00390625), ("Madeleine", 0.125), ("Magali", 0.015625), ("Magalie", 0.00390625), ("Maggy", 0.125), ("Maisy", 0.125), ("Malou", 0.0625), ("Manuela", 0.03125), ("Manuelle", 0.00390625), ("Marceline", 0.015625), ("Marcelle", 0.125), ("Margot", 0.25), ("Marguerite", 0.25), ("Maria", 2.0), ("Marianne", 0.25), ("Marie", 4.0), ("Marielle", 0.015625), ("Mariette", 0.25), ("Marine", 0.00390625), ("Marion", 0.0625), ("Marise", 0.00390625), ("Marlène", 0.03125), ("Marlyse", 0.00390625), ("Marthe", 0.125), ("Martine", 0.5), ("Marylène", 0.0078125), ("Maryline", 0.0078125), ("Maryse", 0.0625), ("Maryvonne", 0.00390625), ("Mathilde", 0.03125), ("Mauricette", 0.00390625), ("Mélanie", 0.0625), ("Michèle", 0.5), ("Micheline", 0.0625), ("Michelle", 0.03125), ("Mimy", 0.00390625), ("Mireille", 0.125), ("Monika", 0.03125), ("Monique", 0.5), ("Morgane", 0.00390625), ("Muriel", 0.0625), ("Murielle", 0.03125), ("Mylène", 0.015625), ("Myriam", 0.125), ("Nadège", 0.0078125), ("Nadia", 0.03125), ("Nadine", 0.25), ("Nancy", 0.0625), ("Natacha", 0.015625), ("Nathalie", 0.5), ("Nelly", 0.125), ("Nicole", 0.5), ("Nina", 0.03125), ("Noëlle", 0.015625), ("Noémie", 0.0078125), ("Nora", 0.015625), ("Octavie", 0.0078125), ("Odette", 0.0625), ("Odile", 0.0625), ("Olga", 0.03125), ("Pascale", 0.0625), ("Patricia", 0.25), ("Paule", 0.125), ("Paulette", 0.0625), ("Pauline", 0.0625), ("Peggy", 0.0625), ("Petra", 0.03125), ("Pierette", 0.00390625), ("Pierrette", 0.0625), ("Rachel", 0.03125), ("Rachèle", 0.00390625), ("Raphaëlle", 0.0078125), ("Raymonde", 0.0625), ("Regina", 0.015625), ("Régine", 0.0625), ("Reine", 0.00390625), ("Rejane", 0.0078125), ("Renée", 0.25), ("Rita", 0.125), ("Rolande", 0.0078125), ("Rollande", 0.00390625), ("Romaine", 0.0625), ("Rosa", 0.015625), ("Rosalie", 0.015625), ("Rose", 0.125), ("Rosy", 0.015625), ("Roxane", 0.00390625), ("Roxanne", 0.00390625), ("Ruth", 0.015625), ("Sabine", 0.03125), ("Sandra", 0.5), ("Sandrine", 0.0625), ("Sandy", 0.0625), ("Sarah", 0.0625), ("Scarlette", 0.00390625), ("Severine", 0.03125), ("Simone", 0.125), ("Simonne", 0.00390625), ("Solange", 0.03125), ("Sonia", 0.03125), ("Sophie", 0.125), ("Stéphanie", 0.125), ("Susanne", 0.03125), ("Suzanne", 0.125), ("Suzette", 0.125), ("Sylvaine", 0.00390625), ("Sylvia", 0.015625), ("Sylviane", 0.015625), ("Sylvie", 0.5), ("Thérèse", 0.25), ("Tina", 0.0625), ("Ursula", 0.03125), ("Valérie", 0.125), ("Vera", 0.03125), ("Véronique", 0.25), ("Vicky", 0.03125), ("Victorine", 0.015625), ("Vinciane", 0.015625), ("Violette", 0.00390625), ("Virginie", 0.0625), ("Viviane", 0.25), ("Vivienne", 0.00390625), ("Yolande", 0.0625), ("Yvette", 0.125), ("Yvonne", 0.25), ) ) first_names_male = OrderedDict( ( ("Achille", 0.00390625), ("Adolphe", 0.015625), ("Adrien", 0.0625), ("Aimable", 0.00390625), ("Alain", 0.5), ("Albert", 0.5), ("Alex", 0.25), ("Alexandre", 0.0625), ("Alexis", 0.0078125), ("Alfred", 0.0625), ("Aloïs", 0.00390625), ("Alphonse", 0.25), ("André", 1.0), ("Andreas", 0.015625), ("Ange", 0.00390625), ("Anicet", 0.00390625), ("Anthony", 0.015625), ("Antoine", 0.5), ("Aristide", 0.00390625), ("Armand", 0.5), ("Arnaud", 0.015625), ("Arnold", 0.03125), ("Arthur", 0.125), ("Auguste", 0.03125), ("Aurelien", 0.00390625), ("Axel", 0.0078125), ("Baptiste", 0.015625), ("Bastien", 0.00390625), ("Benoît", 0.0625), ("Bernard", 0.5), ("Bernd", 0.015625), ("Bertrand", 0.03125), ("Bruno", 0.0625), ("Carlo", 0.125), ("Cédric", 0.03125), ("Célestin", 0.0078125), ("Charles", 0.5), ("Charly", 0.00390625), ("Christian", 0.25), ("Christophe", 0.125), ("Claude", 1.0), ("Clement", 0.015625), ("Constant", 0.03125), ("Corneille", 0.015625), ("Cornel", 0.00390625), ("Cyril", 0.0078125), ("Damien", 0.015625), ("Dan", 0.03125), ("Daniel", 0.25), ("David", 0.125), ("Denis", 0.0625), ("Désiré", 0.0078125), ("Didier", 0.125), ("Dieter", 0.015625), ("Dimitri", 0.00390625), ("Edgar", 0.015625), ("Edgard", 0.0078125), ("Edmond", 0.125), ("Edouard", 0.125), ("Elie", 0.00390625), ("Eloi", 0.0078125), ("Emile", 0.5), ("Emmanuel", 0.03125), ("Eric", 0.125), ("Erik", 0.015625), ("Ernest", 0.25), ("Erwin", 0.015625), ("Etienne", 0.0625), ("Eugène", 0.25), ("Fabien", 0.03125), ("Fabrice", 0.5), ("Felicien", 0.00390625), ("Félix", 0.125), ("Ferdinand", 0.03125), ("Fernand", 1.0), ("Firmin", 0.00390625), ("Florent", 0.03125), ("Francis", 0.125), ("Franck", 0.03125), ("François", 1.0), ("Frank", 0.25), ("Franky", 0.0078125), ("Franz", 0.015625), ("Freddy", 0.0078125), ("Frédéric", 0.125), ("Frederick", 0.00390625), ("Gabriel", 0.015625), ("Gaël", 0.00390625), ("Gaston", 0.25), ("Georges", 0.5), ("Gérald", 0.0078125), ("Gérard", 0.25), ("Geraud", 0.00390625), ("Gery", 0.00390625), ("Ghislain", 0.0078125), ("Gilbert", 0.25), ("Gilles", 0.125), ("Grégoire", 0.015625), ("Grégory", 0.015625), ("Guillaume", 0.125), ("Guy", 1.0), ("Gwenael", 0.00390625), ("Hans", 0.0625), ("Heinz", 0.03125), ("Helmut", 0.015625), ("Henri", 0.5), ("Henrique", 0.015625), ("Henry", 0.03125), ("Herbert", 0.015625), ("Hermann", 0.015625), ("Hervé", 0.03125), ("Hugo", 0.015625), ("Hugues", 0.0078125), ("Ignace", 0.0078125), ("Jacky", 0.0078125), ("Jacques", 0.5), ("James", 0.015625), ("Jean", 4.0), ("Jean-Claude", 0.25), ("Jean-Luc", 0.0625), ("Jeannot", 0.25), ("Jean-Paul", 0.25), ("Jean-Pierre", 0.25), ("Jeff", 0.0625), ("Jeremie", 0.00390625), ("Jérôme", 0.0625), ("Jim", 0.03125), ("Joachim", 0.015625), ("Joé", 0.0625), ("Joël", 0.125), ("John", 0.25), ("Johnny", 0.015625), ("Johny", 0.125), ("Jonathan", 0.015625), ("Jorge", 0.0625), ("Joseph", 0.5), ("Jules", 0.125), ("Julien", 0.0625), ("Jürgen", 0.015625), ("Justin", 0.015625), ("Karl", 0.015625), ("Kevin", 0.0078125), ("Klaus", 0.03125), ("Kurt", 0.015625), ("Lambert", 0.015625), ("Laurent", 0.25), ("Léandre", 0.0078125), ("Léo", 0.03125), ("Léon", 0.5), ("Léonard", 0.0078125), ("Léonce", 0.00390625), ("Léopold", 0.015625), ("Lionel", 0.015625), ("Loïc", 0.0078125), ("Louis", 0.25), ("Luc", 0.25), ("Lucien", 0.5), ("Ludovic", 0.0078125), ("Manfred", 0.015625), ("Manuel", 0.125), ("Marc", 1.0), ("Marcel", 1.0), ("Marco", 0.25), ("Marguy", 0.0078125), ("Marius", 0.0078125), ("Martial", 0.0078125), ("Martin", 0.0625), ("Mathias", 0.125), ("Mathieu", 0.0078125), ("Matthieu", 0.00390625), ("Maurice", 0.0625), ("Max", 0.015625), ("Maxime", 0.015625), ("Maximilien", 0.00390625), ("Michael", 0.0625), ("Michaël", 0.0078125), ("Michel", 1.0), ("Mickael", 0.00390625), ("Mike", 0.125), ("Narcisse", 0.0078125), ("Nicolas", 0.5), ("Noël", 0.015625), ("Norbert", 0.25), ("Olivier", 0.125), ("Oswald", 0.00390625), ("Pascal", 0.125), ("Patrice", 0.0625), ("Patrick", 0.5), ("Paul", 0.5), ("Peter", 0.0625), ("Philippe", 0.25), ("Pierre", 2.0), ("Ralph", 0.0625), ("Raoul", 0.015625), ("Raphaël", 0.03125), ("Raymond", 0.5), ("Réginald", 0.00390625), ("Régis", 0.0078125), ("Rémi", 0.0078125), ("Rémy", 0.0625), ("Renaud", 0.0078125), ("René", 1.0), ("Richard", 0.125), ("Robert", 0.5), ("Rodolphe", 0.015625), ("Roger", 1.0), ("Roland", 0.25), ("Romain", 0.5), ("Ronald", 0.03125), ("Rudy", 0.0625), ("Samuel", 0.0078125), ("Sébastien", 0.03125), ("Serge", 0.25), ("Severin", 0.00390625), ("Séverin", 0.00390625), ("Simon", 0.0078125), ("Stefan", 0.015625), ("Stephan", 0.03125), ("Stéphane", 0.0625), ("Steven", 0.0078125), ("Sylvain", 0.0625), ("Sylvère", 0.0078125), ("Tanguy", 0.00390625), ("Teddy", 0.00390625), ("Théo", 0.25), ("Théodore", 0.03125), ("Théophile", 0.015625), ("Thibaud", 0.00390625), ("Thibaut", 0.00390625), ("Thierry", 0.125), ("Thomas", 0.0625), ("Tommy", 0.0078125), ("Valéry", 0.00390625), ("Victor", 0.25), ("Vincent", 0.0625), ("Vivien", 0.00390625), ("Werner", 0.03125), ("William", 0.015625), ("Willy", 0.0625), ("Wolfgang", 0.03125), ("Xavier", 0.03125), ("Yann", 0.015625), ("Yannick", 0.015625), ("Yvan", 0.015625), ("Yves", 0.25), ("Yvon", 0.03125), ) ) first_names_nonbinary = OrderedDict( [("Claudy", 0.00390625), ("Cyrille", 0.0078125), ("Dominique", 0.125)] + list(first_names_female.items()) + list(first_names_male.items()) )
Provider
python
django__django
tests/model_forms/tests.py
{ "start": 2384, "end": 2483 }
class ____(forms.ModelForm): class Meta: model = Book fields = "__all__"
BookForm
python
mitmproxy__pdoc
test/testdata/misc_py314.py
{ "start": 0, "end": 69 }
class ____(RuntimeError): """custom exception type"""
CustomException
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 28144, "end": 32795 }
class ____: def test_password_change_email(self, pyramid_request, pyramid_config, monkeypatch): stub_user = pretend.stub( id="id", username="username", name="", email="email@example.com", primary_email=pretend.stub(email="email@example.com", verified=True), ) subject_renderer = pyramid_config.testing_add_renderer( "email/password-change/subject.txt" ) subject_renderer.string_response = "Email Subject" body_renderer = pyramid_config.testing_add_renderer( "email/password-change/body.txt" ) body_renderer.string_response = "Email Body" html_renderer = pyramid_config.testing_add_renderer( "email/password-change/body.html" ) html_renderer.string_response = "Email HTML Body" send_email = pretend.stub( delay=pretend.call_recorder(lambda *args, **kwargs: None) ) pyramid_request.task = pretend.call_recorder(lambda *args, **kwargs: send_email) monkeypatch.setattr(email, "send_email", send_email) pyramid_request.db = pretend.stub( query=lambda a: pretend.stub( filter=lambda *a: pretend.stub( one=lambda: pretend.stub(user_id=stub_user.id) ) ), ) pyramid_request.user = stub_user pyramid_request.registry.settings = {"mail.sender": "noreply@example.com"} result = email.send_password_change_email(pyramid_request, stub_user) assert result == {"username": stub_user.username} subject_renderer.assert_() body_renderer.assert_(username=stub_user.username) html_renderer.assert_(username=stub_user.username) assert pyramid_request.task.calls == [pretend.call(send_email)] assert send_email.delay.calls == [ pretend.call( f"{stub_user.username} <{stub_user.email}>", { "sender": None, "subject": "Email Subject", "body_text": "Email Body", "body_html": ( "<html>\n<head></head>\n" "<body><p>Email HTML Body</p></body>\n</html>\n" ), }, { "tag": "account:email:sent", "user_id": stub_user.id, "additional": { "from_": "noreply@example.com", "to": stub_user.email, "subject": "Email Subject", "redact_ip": False, }, }, ) ] def test_password_change_email_unverified( self, pyramid_request, pyramid_config, monkeypatch ): stub_user = pretend.stub( username="username", name="", email="email@example.com", primary_email=pretend.stub(email="email@example.com", verified=False), ) subject_renderer = pyramid_config.testing_add_renderer( "email/password-change/subject.txt" ) subject_renderer.string_response = "Email Subject" body_renderer = pyramid_config.testing_add_renderer( "email/password-change/body.txt" ) body_renderer.string_response = "Email Body" html_renderer = pyramid_config.testing_add_renderer( "email/password-change/body.html" ) html_renderer.string_response = "Email HTML Body" send_email = pretend.stub( delay=pretend.call_recorder(lambda *args, **kwargs: None) ) pyramid_request.task = pretend.call_recorder(lambda *args, **kwargs: send_email) monkeypatch.setattr(email, "send_email", send_email) pyramid_request.db = pretend.stub( query=lambda a: pretend.stub( filter=lambda *a: pretend.stub( one=lambda: pretend.stub(user_id=stub_user.id) ) ), ) pyramid_request.user = stub_user pyramid_request.registry.settings = {"mail.sender": "noreply@example.com"} result = email.send_password_change_email(pyramid_request, stub_user) assert result == {"username": stub_user.username} subject_renderer.assert_() body_renderer.assert_(username=stub_user.username) html_renderer.assert_(username=stub_user.username) assert pyramid_request.task.calls == [] assert send_email.delay.calls == []
TestPasswordChangeEmail
python
django__django
tests/template_tests/syntax_tests/test_cache.py
{ "start": 188, "end": 5649 }
class ____(SimpleTestCase): libraries = { "cache": "django.templatetags.cache", "custom": "template_tests.templatetags.custom", } def tearDown(self): cache.clear() @setup({"cache03": "{% load cache %}{% cache 2 test %}cache03{% endcache %}"}) def test_cache03(self): output = self.engine.render_to_string("cache03") self.assertEqual(output, "cache03") @setup( { "cache03": "{% load cache %}{% cache 2 test %}cache03{% endcache %}", "cache04": "{% load cache %}{% cache 2 test %}cache04{% endcache %}", } ) def test_cache04(self): self.engine.render_to_string("cache03") output = self.engine.render_to_string("cache04") self.assertEqual(output, "cache03") @setup({"cache05": "{% load cache %}{% cache 2 test foo %}cache05{% endcache %}"}) def test_cache05(self): output = self.engine.render_to_string("cache05", {"foo": 1}) self.assertEqual(output, "cache05") @setup({"cache06": "{% load cache %}{% cache 2 test foo %}cache06{% endcache %}"}) def test_cache06(self): output = self.engine.render_to_string("cache06", {"foo": 2}) self.assertEqual(output, "cache06") @setup( { "cache05": "{% load cache %}{% cache 2 test foo %}cache05{% endcache %}", "cache07": "{% load cache %}{% cache 2 test foo %}cache07{% endcache %}", } ) def test_cache07(self): context = {"foo": 1} self.engine.render_to_string("cache05", context) output = self.engine.render_to_string("cache07", context) self.assertEqual(output, "cache05") @setup( { "cache06": "{% load cache %}{% cache 2 test foo %}cache06{% endcache %}", "cache08": "{% load cache %}{% cache time test foo %}cache08{% endcache %}", } ) def test_cache08(self): """ Allow first argument to be a variable. """ context = {"foo": 2, "time": 2} self.engine.render_to_string("cache06", context) output = self.engine.render_to_string("cache08", context) self.assertEqual(output, "cache06") # Raise exception if we don't have at least 2 args, first one integer. @setup({"cache11": "{% load cache %}{% cache %}{% endcache %}"}) def test_cache11(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("cache11") @setup({"cache12": "{% load cache %}{% cache 1 %}{% endcache %}"}) def test_cache12(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template("cache12") @setup({"cache13": "{% load cache %}{% cache foo bar %}{% endcache %}"}) def test_cache13(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string("cache13") @setup({"cache14": "{% load cache %}{% cache foo bar %}{% endcache %}"}) def test_cache14(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string("cache14", {"foo": "fail"}) @setup({"cache15": "{% load cache %}{% cache foo bar %}{% endcache %}"}) def test_cache15(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string("cache15", {"foo": []}) @setup({"cache16": "{% load cache %}{% cache 1 foo bar %}{% endcache %}"}) def test_cache16(self): """ Regression test for #7460. """ output = self.engine.render_to_string( "cache16", {"foo": "foo", "bar": "with spaces"} ) self.assertEqual(output, "") @setup( { "cache17": ( "{% load cache %}{% cache 10 long_cache_key poem %}Some Content" "{% endcache %}" ) } ) def test_cache17(self): """ Regression test for #11270. """ output = self.engine.render_to_string( "cache17", { "poem": ( "Oh freddled gruntbuggly/Thy micturations are to me/" "As plurdled gabbleblotchits/On a lurgid bee/" "That mordiously hath bitled out/Its earted jurtles/" "Into a rancid festering/Or else I shall rend thee in the " "gobberwarts with my blurglecruncheon/See if I don't." ), }, ) self.assertEqual(output, "Some Content") @setup( { "cache18": ( '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18' "{% endcache %}" ) } ) def test_cache18(self): """ Test whitespace in filter arguments """ output = self.engine.render_to_string("cache18") self.assertEqual(output, "cache18") @setup( { "first": "{% load cache %}{% cache None fragment19 %}content{% endcache %}", "second": ( "{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}" ), } ) def test_none_timeout(self): """A timeout of None means "cache forever".""" output = self.engine.render_to_string("first") self.assertEqual(output, "content") output = self.engine.render_to_string("second") self.assertEqual(output, "content")
CacheTagTests
python
encode__starlette
starlette/authentication.py
{ "start": 3637, "end": 3823 }
class ____: async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None: raise NotImplementedError() # pragma: no cover
AuthenticationBackend
python
milvus-io__pymilvus
pymilvus/client/types.py
{ "start": 737, "end": 1122 }
class ____(dict): def omit_zero_len(self): return len({k: v for k, v in self.items() if v or k in ALWAYS_KEEP_ZERO_KEYS}) # keep zero for specific keys, omit other zero values def __str__(self): return str({k: v for k, v in self.items() if v or k in ALWAYS_KEEP_ZERO_KEYS}) # no filter def __repr__(self): return str(dict(self))
OmitZeroDict
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/unit_tests/integration/test_rest_stream.py
{ "start": 2727, "end": 3670 }
class ____(TestCase): def setUp(self) -> None: self._config = ConfigBuilder().client_id(_CLIENT_ID).client_secret(_CLIENT_SECRET).refresh_token(_REFRESH_TOKEN) @HttpMocker() def test_given_error_on_fetch_chunk_of_properties_when_read_then_retry(self, http_mocker: HttpMocker) -> None: given_authentication(http_mocker, _CLIENT_ID, _CLIENT_SECRET, _REFRESH_TOKEN, _INSTANCE_URL) given_stream(http_mocker, _BASE_URL, _STREAM_NAME, SalesforceDescribeResponseBuilder().field(_A_FIELD_NAME)) http_mocker.get( create_http_request(_STREAM_NAME, [_A_FIELD_NAME]), [ HttpResponse("", status_code=406), create_http_response([_A_FIELD_NAME], record_count=1), ], ) output = read(_STREAM_NAME, SyncMode.full_refresh, self._config) assert len(output.records) == 1 @freezegun.freeze_time(_NOW.isoformat())
FullRefreshTest
python
rapidsai__cudf
python/cudf/cudf/core/window/ewm.py
{ "start": 397, "end": 7922 }
class ____(_RollingBase): r""" Provide exponential weighted (EW) functions. Available EW functions: ``mean()`` Exactly one parameter: ``com``, ``span``, ``halflife``, or ``alpha`` must be provided. Parameters ---------- com : float, optional Specify decay in terms of center of mass, :math:`\alpha = 1 / (1 + com)`, for :math:`com \geq 0`. span : float, optional Specify decay in terms of span, :math:`\alpha = 2 / (span + 1)`, for :math:`span \geq 1`. halflife : float, str, timedelta, optional Specify decay in terms of half-life, :math:`\alpha = 1 - \exp\left(-\ln(2) / halflife\right)`, for :math:`halflife > 0`. alpha : float, optional Specify smoothing factor :math:`\alpha` directly, :math:`0 < \alpha \leq 1`. min_periods : int, default 0 Not Supported adjust : bool, default True Controls assumptions about the first value in the sequence. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ewm.html for details. ignore_na : bool, default False Not Supported axis : {0, 1}, default 0 Not Supported times : str, np.ndarray, Series, default None Not Supported Returns ------- ``ExponentialMovingWindow`` object Notes ----- cuDF input data may contain both nulls and nan values. For the purposes of this method, they are taken to have the same meaning, meaning nulls in cuDF will affect the result the same way that nan values would using the equivalent pandas method. .. pandas-compat:: :meth:`pandas.DataFrame.ewm` The parameters ``min_periods``, ``ignore_na``, ``axis``, and ``times`` are not yet supported. Behavior is defined only for data that begins with a valid (non-null) element. Currently, only ``mean`` is a supported method. Examples -------- >>> df = cudf.DataFrame({'B': [0, 1, 2, cudf.NA, 4]}) >>> df B 0 0 1 1 2 2 3 <NA> 4 4 >>> df.ewm(com=0.5).mean() B 0 0.000000 1 0.750000 2 1.615385 3 1.615385 4 3.670213 >>> df.ewm(com=0.5, adjust=False).mean() B 0 0.000000 1 0.666667 2 1.555556 3 1.555556 4 3.650794 """ def __init__( self, obj, com: float | None = None, span: float | None = None, halflife: float | None = None, alpha: float | None = None, min_periods: int | None = 0, adjust: bool = True, ignore_na: bool = False, axis: int = 0, times: str | np.ndarray | None = None, method: Literal["single", "table"] = "single", ): if min_periods != 0: raise NotImplementedError( "min_periods is currently not supported." ) if ignore_na is not False: raise NotImplementedError("ignore_na is currently not supported.") if axis != 0: warnings.warn( "axis is deprecated with will be removed in a future version. " "Transpose the DataFrame first instead." ) raise NotImplementedError("axis is currently not supported.") if times is not None: raise NotImplementedError("times is currently not supported.") if method != "single": raise NotImplementedError("method is currently not supported.") self.obj = obj self.adjust = adjust self.com = get_center_of_mass(com, span, halflife, alpha) def online(self, engine: str = "numba", engine_kwargs=None): """ Return an ``OnlineExponentialMovingWindow`` object to calculate exponentially moving window aggregations in an online method. Currently not supported. """ raise NotImplementedError("online is currently not supported.") def mean( self, numeric_only: bool = False, engine=None, engine_kwargs=None ): """ Calculate the ewm (exponential weighted moment) mean. """ if numeric_only is not False: raise NotImplementedError( "numeric_only is currently not supported." ) if engine is not None: raise NotImplementedError( "engine is non-functional and added for compatibility with pandas." ) if engine_kwargs is not None: raise NotImplementedError( "engine_kwargs is non-functional and added for compatibility with pandas." ) return self._apply_agg("ewma") def sum(self, numeric_only: bool = False, engine=None, engine_kwargs=None): raise NotImplementedError("sum not yet supported.") def var(self, bias: bool = False, numeric_only: bool = False): raise NotImplementedError("var not yet supported.") def std(self, bias: bool = False, numeric_only: bool = False): raise NotImplementedError("std not yet supported.") def corr( self, other, pairwise: bool | None = None, numeric_only: bool = False ): raise NotImplementedError("corr not yet supported.") def cov( self, other, pairwise: bool | None = None, bias: bool = False, numeric_only: bool = False, ): raise NotImplementedError("cov not yet supported.") def _apply_agg_column( self, source_column: ColumnBase, agg_name: str ) -> ColumnBase: if not is_dtype_obj_numeric(source_column.dtype): raise TypeError("No numeric types to aggregate") # libcudf ewm has special casing for nulls only # and come what may with nans. It treats those nulls like # pandas does nans in the same positions mathematically. # as such we need to convert the nans to nulls before # passing them in. to_libcudf_column = source_column.astype( np.dtype(np.float64) ).nans_to_nulls() return to_libcudf_column.scan( agg_name, True, com=self.com, adjust=self.adjust ) def get_center_of_mass( comass: float | None, span: float | None, halflife: float | None, alpha: float | None, ) -> float: valid_count = count_not_none(comass, span, halflife, alpha) if valid_count > 1: raise ValueError( "comass, span, halflife, and alpha are mutually exclusive" ) # Convert to center of mass; domain checks ensure 0 < alpha <= 1 if comass is not None: if comass < 0: raise ValueError("comass must satisfy: comass >= 0") elif span is not None: if span < 1: raise ValueError("span must satisfy: span >= 1") comass = (span - 1) / 2 elif halflife is not None: if halflife <= 0: raise ValueError("halflife must satisfy: halflife > 0") decay = 1 - np.exp(np.log(0.5) / halflife) comass = 1 / decay - 1 elif alpha is not None: if alpha <= 0 or alpha > 1: raise ValueError("alpha must satisfy: 0 < alpha <= 1") comass = (1 - alpha) / alpha else: raise ValueError("Must pass one of comass, span, halflife, or alpha") return float(comass) def count_not_none(*args) -> int: """ Returns the count of arguments that are not None. """ return sum(x is not None for x in args)
ExponentialMovingWindow
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_ec2.py
{ "start": 1184, "end": 4023 }
class ____: def test_ec2_state_sensor_trigger_serialize(self): test_ec2_state_sensor = EC2StateSensorTrigger( instance_id=TEST_INSTANCE_ID, target_state=TEST_TARGET_STATE, aws_conn_id=TEST_CONN_ID, region_name=TEST_REGION_NAME, poll_interval=TEST_POLL_INTERVAL, ) class_path, args = test_ec2_state_sensor.serialize() assert class_path == "airflow.providers.amazon.aws.triggers.ec2.EC2StateSensorTrigger" assert args["instance_id"] == TEST_INSTANCE_ID assert args["target_state"] == TEST_TARGET_STATE assert args["aws_conn_id"] == TEST_CONN_ID assert args["region_name"] == TEST_REGION_NAME assert args["poll_interval"] == TEST_POLL_INTERVAL @pytest.mark.asyncio @mock.patch("airflow.providers.amazon.aws.hooks.ec2.EC2Hook.get_instance_state_async") @mock.patch("airflow.providers.amazon.aws.hooks.ec2.EC2Hook.get_async_conn") async def test_ec2_state_sensor_run(self, mock_async_conn, mock_get_instance_state_async): mock = AsyncMock() mock_async_conn.return_value.__aenter__.return_value = mock mock_get_instance_state_async.return_value = TEST_TARGET_STATE test_ec2_state_sensor = EC2StateSensorTrigger( instance_id=TEST_INSTANCE_ID, target_state=TEST_TARGET_STATE, aws_conn_id=TEST_CONN_ID, region_name=TEST_REGION_NAME, poll_interval=TEST_POLL_INTERVAL, ) generator = test_ec2_state_sensor.run() response = await generator.asend(None) assert response == TriggerEvent({"status": "success", "message": "target state met"}) @pytest.mark.asyncio @mock.patch("asyncio.sleep") @mock.patch("airflow.providers.amazon.aws.hooks.ec2.EC2Hook.get_instance_state_async") @mock.patch("airflow.providers.amazon.aws.hooks.ec2.EC2Hook.get_async_conn") async def test_ec2_state_sensor_run_multiple( self, mock_async_conn, mock_get_instance_state_async, mock_sleep ): mock = AsyncMock() mock_async_conn.return_value.__aenter__.return_value = mock mock_get_instance_state_async.side_effect = ["test-state", TEST_TARGET_STATE] mock_sleep.return_value = True test_ec2_state_sensor = EC2StateSensorTrigger( instance_id=TEST_INSTANCE_ID, target_state=TEST_TARGET_STATE, aws_conn_id=TEST_CONN_ID, region_name=TEST_REGION_NAME, poll_interval=TEST_POLL_INTERVAL, ) generator = test_ec2_state_sensor.run() response = await generator.asend(None) assert mock_get_instance_state_async.call_count == 2 assert response == TriggerEvent({"status": "success", "message": "target state met"})
TestEC2StateSensorTrigger
python
gevent__gevent
src/gevent/tests/test__threading_2.py
{ "start": 22881, "end": 23116 }
class ____(lock_tests.RLockTests): # See comments at the top of the file for the difference # between this and RLockTests, and why they both matter locktype = staticmethod(threading.NativeRLock) @skipDueToHang
NativeRLockTests
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/components/reward_providers/gail_reward_provider.py
{ "start": 945, "end": 2655 }
class ____(BaseRewardProvider): def __init__(self, specs: BehaviorSpec, settings: GAILSettings) -> None: super().__init__(specs, settings) self._ignore_done = False self._discriminator_network = DiscriminatorNetwork(specs, settings) self._discriminator_network.to(default_device()) _, self._demo_buffer = demo_to_buffer( settings.demo_path, 1, specs ) # This is supposed to be the sequence length but we do not have access here params = list(self._discriminator_network.parameters()) self.optimizer = torch.optim.Adam(params, lr=settings.learning_rate) def evaluate(self, mini_batch: AgentBuffer) -> np.ndarray: with torch.no_grad(): estimates, _ = self._discriminator_network.compute_estimate( mini_batch, use_vail_noise=False ) return ModelUtils.to_numpy( -torch.log( 1.0 - estimates.squeeze(dim=1) * (1.0 - self._discriminator_network.EPSILON) ) ) def update(self, mini_batch: AgentBuffer) -> Dict[str, np.ndarray]: expert_batch = self._demo_buffer.sample_mini_batch( mini_batch.num_experiences, 1 ) self._discriminator_network.encoder.update_normalization(expert_batch) loss, stats_dict = self._discriminator_network.compute_loss( mini_batch, expert_batch ) self.optimizer.zero_grad() loss.backward() self.optimizer.step() return stats_dict def get_modules(self): return {f"Module:{self.name}": self._discriminator_network}
GAILRewardProvider
python
aimacode__aima-python
text.py
{ "start": 4745, "end": 7882 }
class ____: """A very simple Information Retrieval System, as discussed in Sect. 23.2. The constructor s = IRSystem('the a') builds an empty system with two stopwords. Next, index several documents with s.index_document(text, url). Then ask queries with s.query('query words', n) to retrieve the top n matching documents. Queries are literal words from the document, except that stopwords are ignored, and there is one special syntax: The query "learn: man cat", for example, runs "man cat" and indexes it.""" def __init__(self, stopwords='the a of'): """Create an IR System. Optionally specify stopwords.""" # index is a map of {word: {docid: count}}, where docid is an int, # indicating the index into the documents list. self.index = defaultdict(lambda: defaultdict(int)) self.stopwords = set(words(stopwords)) self.documents = [] def index_collection(self, filenames): """Index a whole collection of files.""" prefix = os.path.dirname(__file__) for filename in filenames: self.index_document(open(filename).read(), os.path.relpath(filename, prefix)) def index_document(self, text, url): """Index the text of a document.""" # For now, use first line for title title = text[:text.index('\n')].strip() docwords = words(text) docid = len(self.documents) self.documents.append(Document(title, url, len(docwords))) for word in docwords: if word not in self.stopwords: self.index[word][docid] += 1 def query(self, query_text, n=10): """Return a list of n (score, docid) pairs for the best matches. Also handle the special syntax for 'learn: command'.""" if query_text.startswith("learn:"): doctext = os.popen(query_text[len("learn:"):], 'r').read() self.index_document(doctext, query_text) return [] qwords = [w for w in words(query_text) if w not in self.stopwords] shortest = min(qwords, key=lambda w: len(self.index[w])) docids = self.index[shortest] return heapq.nlargest(n, ((self.total_score(qwords, docid), docid) for docid in docids)) def score(self, word, docid): """Compute a score for this word on the document with this docid.""" # There are many options; here we take a very simple approach return np.log(1 + self.index[word][docid]) / np.log(1 + self.documents[docid].nwords) def total_score(self, words, docid): """Compute the sum of the scores of these words on the document with this docid.""" return sum(self.score(word, docid) for word in words) def present(self, results): """Present the results as a list.""" for (score, docid) in results: doc = self.documents[docid] print("{:5.2}|{:25} | {}".format(100 * score, doc.url, doc.title[:45].expandtabs())) def present_results(self, query_text, n=10): """Get results for the query and present them.""" self.present(self.query(query_text, n))
IRSystem
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/api.py
{ "start": 697, "end": 6910 }
class ____(FacebookAdsApi): """Custom Facebook API class to intercept all API calls and handle call rate limits""" MAX_RATE, MAX_PAUSE_INTERVAL = (95, timedelta(minutes=10)) MIN_RATE, MIN_PAUSE_INTERVAL = (85, timedelta(minutes=2)) # see `_should_restore_page_size` method docstring for more info. # attribute to handle the reduced request limit request_record_limit_is_reduced: bool = False # attribute to save the status of the last successful call last_api_call_is_successful: bool = False @dataclass class Throttle: """Utilization of call rate in %, from 0 to 100""" per_application: float per_account: float # Insights async jobs throttle _ads_insights_throttle: Throttle @property def ads_insights_throttle(self) -> Throttle: return self._ads_insights_throttle @staticmethod def _parse_call_rate_header(headers): usage = 0 pause_interval = timedelta() usage_header_business = headers.get("x-business-use-case-usage") usage_header_app = headers.get("x-app-usage") usage_header_ad_account = headers.get("x-ad-account-usage") if usage_header_ad_account: usage_header_ad_account_loaded = json.loads(usage_header_ad_account) usage = max(usage, usage_header_ad_account_loaded.get("acc_id_util_pct")) if usage_header_app: usage_header_app_loaded = json.loads(usage_header_app) usage = max( usage, usage_header_app_loaded.get("call_count"), usage_header_app_loaded.get("total_time"), usage_header_app_loaded.get("total_cputime"), ) if usage_header_business: usage_header_business_loaded = json.loads(usage_header_business) for business_object_id in usage_header_business_loaded: usage_limits = usage_header_business_loaded.get(business_object_id)[0] usage = max( usage, usage_limits.get("call_count"), usage_limits.get("total_cputime"), usage_limits.get("total_time"), ) pause_interval = max( pause_interval, timedelta(minutes=usage_limits.get("estimated_time_to_regain_access", 0)), ) return usage, pause_interval def _compute_pause_interval(self, usage, pause_interval): """The sleep time will be calculated based on usage consumed.""" if usage >= self.MAX_RATE: return max(self.MAX_PAUSE_INTERVAL, pause_interval) return max(self.MIN_PAUSE_INTERVAL, pause_interval) def _get_max_usage_pause_interval_from_batch(self, records): usage = 0 pause_interval = self.MIN_PAUSE_INTERVAL for record in records: # there are two types of failures: # 1. no response (we execute batch until all inner requests has response) # 2. response with error (we crash loudly) # in case it is failed inner request the headers might not be present if "headers" not in record: continue headers = {header["name"].lower(): header["value"] for header in record["headers"]} ( usage_from_response, pause_interval_from_response, ) = self._parse_call_rate_header(headers) usage = max(usage, usage_from_response) pause_interval = max(pause_interval_from_response, pause_interval) return usage, pause_interval def _handle_call_rate_limit(self, response, params): if "batch" in params: records = response.json() usage, pause_interval = self._get_max_usage_pause_interval_from_batch(records) else: headers = response.headers() usage, pause_interval = self._parse_call_rate_header(headers) if usage >= self.MIN_RATE: sleep_time = self._compute_pause_interval(usage=usage, pause_interval=pause_interval) logger.warning(f"Facebook API Utilization is too high ({usage})%, pausing for {sleep_time}") sleep(sleep_time.total_seconds()) def _update_insights_throttle_limit(self, response: FacebookResponse): """ For /insights call every response contains x-fb-ads-insights-throttle header representing current throttle limit parameter for async insights jobs for current app/account. We need this information to adjust number of running async jobs for optimal performance. """ ads_insights_throttle = response.headers().get("x-fb-ads-insights-throttle") if ads_insights_throttle: ads_insights_throttle = json.loads(ads_insights_throttle) self._ads_insights_throttle = self.Throttle( per_application=ads_insights_throttle.get("app_id_util_pct", 0), per_account=ads_insights_throttle.get("acc_id_util_pct", 0), ) def _should_restore_default_page_size(self, params): """ Track the state of the `request_record_limit_is_reduced` and `last_api_call_is_successful`, based on the logic from `@backoff_policy` (common.py > `reduce_request_record_limit` and `revert_request_record_limit`) """ params = True if params else False return params and not self.request_record_limit_is_reduced and self.last_api_call_is_successful @backoff_policy def call( self, method, path, params=None, headers=None, files=None, url_override=None, api_version=None, ): """Makes an API call, delegate actual work to parent class and handles call rates""" if self._should_restore_default_page_size(params): params.update(**{"limit": self.default_page_size}) response = super().call(method, path, params, headers, files, url_override, api_version) self._update_insights_throttle_limit(response) self._handle_call_rate_limit(response, params) return response
MyFacebookAdsApi
python
django__django
tests/gis_tests/test_data.py
{ "start": 1790, "end": 2050 }
class ____: """ Each attribute of this object is a list of `TestGeom` instances. """ def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, [TestGeom(**strconvert(kw)) for kw in value])
TestGeomSet
python
readthedocs__readthedocs.org
readthedocs/organizations/tests/test_orgs.py
{ "start": 621, "end": 3880 }
class ____(RequestFactoryTestMixin, TestCase): def setUp(self): self.owner = fixture.get(User) self.tester = fixture.get(User, username="tester") self.project = fixture.get(Project, slug="pip") self.organization = fixture.get( Organization, name="Mozilla", slug="mozilla", projects=[self.project], owners=[self.owner], stripe_id="1234", ) self.client.force_login(user=self.owner) def add_owner(self, username="tester", test=True): data = {"username_or_email": username} resp = self.client.post( ("/organizations/mozilla/owners/add/".format(org=self.organization.slug)), data=data, ) if test: self.assertEqual(resp.status_code, 302) self.assertEqual( resp["location"], "/organizations/mozilla/owners/", ) return resp def add_member(self, username="tester"): """ Regression tests for removed functionality. Members are now a team only concept, where organization.members is now an aggregate function of all team members. Expect failures from form """ def add_team(self, team="foobar", access="readonly", test=True): data = { "name": team, "slug": team, "access": access, } resp = self.client.post( ("/organizations/{org}/teams/add/".format(org=self.organization.slug)), data=data, ) if test: self.assertEqual(resp.status_code, 302) self.assertEqual( resp["location"], "/organizations/mozilla/teams/{}/".format(team), ) return resp def add_project_to_team(self, team="foobar", projects=None, test=True): if projects is None: projects = [self.project.pk] elif isinstance(projects, list): projects = [project.pk for project in projects] data = { "projects": projects, } resp = self.client.post( ( "/organizations/{org}/teams/{team}/projects/".format( org=self.organization.slug, team=team ) ), data=data, ) if test: self.assertEqual(resp.status_code, 302) self.assertEqual( resp["location"], "/organizations/mozilla/teams/{}/".format(team), ) return resp def add_team_member(self, username="tester", team="foobar", test=True): """Add organization team member.""" data = {"member": username} resp = self.client.post( ( "/organizations/{org}/teams/{team}/members/invite/".format( org=self.organization.slug, team=team ) ), data=data, ) if test: self.assertEqual(resp.status_code, 302) self.assertEqual( resp["location"], "/organizations/mozilla/teams/{}/".format(team), ) return resp
OrganizationTestCase
python
giampaolo__psutil
psutil/test/memleak.py
{ "start": 4305, "end": 4540 }
class ____(UnclosedResourceError): """Raised when test detects HeapCreate() without a corresponding HeapDestroy() after calling function once. Windows only. """ resource_name = "HeapCreate() call"
UnclosedHeapCreateError
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 2801, "end": 3660 }
class ____(Operation): def call(self, x): return backend.nn.sparse_sigmoid(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["keras.ops.sparse_sigmoid", "keras.ops.nn.sparse_sigmoid"]) def sparse_sigmoid(x): """Sparse sigmoid activation function. It is defined as `f(x) = 0` for `x <= -1`, `f(x) = 0.5 * (x + 1)` for `-1 < x < 1`, `f(x) = 1` for `x >= 1`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = keras.ops.convert_to_tensor([-6.0, 1.0, 0.0, 1.0, 6.0]) >>> keras.ops.sparse_sigmoid(x) array([0. , 1. , 0.5, 1. , 1. ], dtype=float32) """ if any_symbolic_tensors((x,)): return SparseSigmoid().symbolic_call(x) return backend.nn.sparse_sigmoid(x)
SparseSigmoid
python
ansible__ansible
test/units/parsing/vault/test_vault.py
{ "start": 4918, "end": 6692 }
class ____(unittest.TestCase): def test_empty_prompt_formats(self): secret = vault.PromptVaultSecret(vault_id='test_id', prompt_formats=[]) secret.load() self.assertIsNone(secret._bytes) @patch('ansible.parsing.vault.display.prompt', return_value='the_password') def test_prompt_formats_none(self, mock_display_prompt): secret = vault.PromptVaultSecret(vault_id='test_id') secret.load() self.assertEqual(secret._bytes, b'the_password') @patch('ansible.parsing.vault.display.prompt', return_value='the_password') def test_custom_prompt(self, mock_display_prompt): secret = vault.PromptVaultSecret(vault_id='test_id', prompt_formats=['The cow flies at midnight: ']) secret.load() self.assertEqual(secret._bytes, b'the_password') @patch('ansible.parsing.vault.display.prompt', side_effect=EOFError) def test_prompt_eoferror(self, mock_display_prompt): secret = vault.PromptVaultSecret(vault_id='test_id') self.assertRaisesRegex(vault.AnsibleVaultError, 'EOFError.*test_id', secret.load) @patch('ansible.parsing.vault.display.prompt', side_effect=['first_password', 'second_password']) def test_prompt_passwords_dont_match(self, mock_display_prompt): secret = vault.PromptVaultSecret(vault_id='test_id', prompt_formats=['Vault password: ', 'Confirm Vault password: ']) self.assertRaisesRegex(errors.AnsibleError, 'Passwords do not match', secret.load)
TestPromptVaultSecret
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/styles/style_transformation.py
{ "start": 7838, "end": 8177 }
class ____(StyleTransformation): """ Don't transform anything at all. """ def transform_attrs(self, attrs: Attrs) -> Attrs: return attrs def invalidation_hash(self) -> Hashable: # Always return the same hash for these dummy instances. return "dummy-style-transformation"
DummyStyleTransformation
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc.py
{ "start": 76071, "end": 84777 }
class ____(GoogleCloudBaseOperator): """ Instantiate a WorkflowTemplate Inline on Google Cloud Dataproc. The operator will wait until the WorkflowTemplate is finished executing. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataprocInstantiateInlineWorkflowTemplateOperator` For more detail on about instantiate inline have a look at the reference: https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.workflowTemplates/instantiateInline :param template: The template contents. (templated) :param project_id: The ID of the google cloud project in which the template runs :param region: The specified region where the dataproc cluster is created. :param parameters: a map of parameters for Dataproc Template in key-value format: map (key: string, value: string) Example: { "date_from": "2019-08-01", "date_to": "2019-08-02"}. Values may not exceed 100 characters. Please refer to: https://cloud.google.com/dataproc/docs/concepts/workflows/workflow-parameters :param request_id: Optional. A unique id used to identify the request. If the server receives two ``SubmitJobRequest`` requests with the same id, then the second request will be ignored and the first ``Job`` created and stored in the backend is returned. It is recommended to always set this value to a UUID. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param deferrable: Run operator in the deferrable mode. :param polling_interval_seconds: Time (seconds) to wait between calls to check the run status. :param cancel_on_kill: Flag which indicates whether cancel the workflow, when on_kill is called """ template_fields: Sequence[str] = ("template", "gcp_conn_id", "impersonation_chain") template_fields_renderers = {"template": "json"} operator_extra_links = (DataprocWorkflowLink(),) def __init__( self, *, template: dict, region: str, project_id: str = PROVIDE_PROJECT_ID, request_id: str | None = None, retry: AsyncRetry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), polling_interval_seconds: int = 10, cancel_on_kill: bool = True, openlineage_inject_parent_job_info: bool = conf.getboolean( "openlineage", "spark_inject_parent_job_info", fallback=False ), openlineage_inject_transport_info: bool = conf.getboolean( "openlineage", "spark_inject_transport_info", fallback=False ), **kwargs, ) -> None: super().__init__(**kwargs) if deferrable and polling_interval_seconds <= 0: raise ValueError("Invalid value for polling_interval_seconds. Expected value greater than 0") self.template = template self.project_id = project_id self.region = region self.template = template self.request_id = request_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain self.deferrable = deferrable self.polling_interval_seconds = polling_interval_seconds self.cancel_on_kill = cancel_on_kill self.operation_name: str | None = None self.openlineage_inject_parent_job_info = openlineage_inject_parent_job_info self.openlineage_inject_transport_info = openlineage_inject_transport_info def execute(self, context: Context): self.log.info("Instantiating Inline Template") hook = DataprocHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) project_id = self.project_id or hook.project_id if self.openlineage_inject_parent_job_info or self.openlineage_inject_transport_info: self.log.info("Automatic injection of OpenLineage information into Spark properties is enabled.") self._inject_openlineage_properties_into_dataproc_workflow_template(context) operation = hook.instantiate_inline_workflow_template( template=self.template, project_id=project_id, region=self.region, request_id=self.request_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) operation_name = operation.operation.name self.operation_name = operation_name workflow_id = operation_name.split("/")[-1] if project_id: DataprocWorkflowLink.persist( context=context, workflow_id=workflow_id, region=self.region, project_id=project_id, ) if not self.deferrable: self.log.info("Template instantiated. Workflow Id : %s", workflow_id) hook.wait_for_operation(timeout=self.timeout, result_retry=self.retry, operation=operation) self.log.info("Workflow %s completed successfully", workflow_id) else: self.defer( trigger=DataprocOperationTrigger( name=operation_name, project_id=self.project_id or hook.project_id, region=self.region, gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, polling_interval_seconds=self.polling_interval_seconds, ), method_name="execute_complete", ) def execute_complete(self, context, event=None) -> None: """ Act as a callback for when the trigger fires. This returns immediately. It relies on trigger to throw an exception, otherwise it assumes execution was successful. """ if event["status"] in ("failed", "error"): self.log.exception("Unexpected error in the operation.") raise AirflowException(event["message"]) self.log.info("Workflow %s completed successfully", event["operation_name"]) def on_kill(self) -> None: if self.cancel_on_kill and self.operation_name: hook = DataprocHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) hook.get_operations_client(region=self.region).cancel_operation(name=self.operation_name) def _inject_openlineage_properties_into_dataproc_workflow_template(self, context: Context) -> None: try: from airflow.providers.google.cloud.openlineage.utils import ( inject_openlineage_properties_into_dataproc_workflow_template, ) self.template = inject_openlineage_properties_into_dataproc_workflow_template( template=self.template, context=context, inject_parent_job_info=self.openlineage_inject_parent_job_info, inject_transport_info=self.openlineage_inject_transport_info, ) except Exception as e: self.log.warning( "An error occurred while trying to inject OpenLineage information. " "Dataproc template has not been modified by OpenLineage.", exc_info=e, )
DataprocInstantiateInlineWorkflowTemplateOperator
python
getsentry__sentry
tests/sentry/api/test_base.py
{ "start": 2656, "end": 3112 }
class ____(Endpoint): permission_classes = () def get(self, request): values = [x for x in range(0, 100)] def data_fn(offset, limit): page_offset = offset * limit return values[page_offset : page_offset + limit] return self.paginate( request=request, paginator=GenericOffsetPaginator(data_fn), on_results=lambda results: results, )
DummyPaginationEndpoint
python
realpython__materials
python-dicts/number.py
{ "start": 0, "end": 101 }
class ____: def __init__(self, value): self.value = value print(Number(42).__dict__)
Number
python
tiangolo__fastapi
fastapi/openapi/models.py
{ "start": 11684, "end": 12265 }
class ____(BaseModelWithConfig): ref: Optional[str] = Field(default=None, alias="$ref") summary: Optional[str] = None description: Optional[str] = None get: Optional[Operation] = None put: Optional[Operation] = None post: Optional[Operation] = None delete: Optional[Operation] = None options: Optional[Operation] = None head: Optional[Operation] = None patch: Optional[Operation] = None trace: Optional[Operation] = None servers: Optional[List[Server]] = None parameters: Optional[List[Union[Parameter, Reference]]] = None
PathItem
python
chroma-core__chroma
chromadb/db/mixins/sysdb.py
{ "start": 1451, "end": 36955 }
class ____(SqlDB, SysDB): # Used only to delete log streams on collection deletion. # TODO: refactor to remove this dependency into a separate interface _producer: Producer def __init__(self, system: System): super().__init__(system) self._opentelemetry_client = system.require(OpenTelemetryClient) @trace_method("SqlSysDB.create_segment", OpenTelemetryGranularity.ALL) @override def start(self) -> None: super().start() self._producer = self._system.instance(Producer) @override def create_database( self, id: UUID, name: str, tenant: str = DEFAULT_TENANT ) -> None: with self.tx() as cur: # Get the tenant id for the tenant name and then insert the database with the id, name and tenant id databases = Table("databases") tenants = Table("tenants") insert_database = ( self.querybuilder() .into(databases) .columns(databases.id, databases.name, databases.tenant_id) .insert( ParameterValue(self.uuid_to_db(id)), ParameterValue(name), self.querybuilder() .select(tenants.id) .from_(tenants) .where(tenants.id == ParameterValue(tenant)), ) ) sql, params = get_sql(insert_database, self.parameter_format()) try: cur.execute(sql, params) except self.unique_constraint_error() as e: raise UniqueConstraintError( f"Database {name} already exists for tenant {tenant}" ) from e @override def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: with self.tx() as cur: databases = Table("databases") q = ( self.querybuilder() .from_(databases) .select(databases.id, databases.name) .where(databases.name == ParameterValue(name)) .where(databases.tenant_id == ParameterValue(tenant)) ) sql, params = get_sql(q, self.parameter_format()) row = cur.execute(sql, params).fetchone() if not row: raise NotFoundError( f"Database {name} not found for tenant {tenant}. Are you sure it exists?" ) if row[0] is None: raise NotFoundError( f"Database {name} not found for tenant {tenant}. Are you sure it exists?" ) id: UUID = cast(UUID, self.uuid_from_db(row[0])) return Database( id=id, name=row[1], tenant=tenant, ) @override def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: with self.tx() as cur: databases = Table("databases") q = ( self.querybuilder() .from_(databases) .where(databases.name == ParameterValue(name)) .where(databases.tenant_id == ParameterValue(tenant)) .delete() ) sql, params = get_sql(q, self.parameter_format()) sql = sql + " RETURNING id" result = cur.execute(sql, params).fetchone() if not result: raise NotFoundError(f"Database {name} not found for tenant {tenant}") # As of 01/09/2025, cascading deletes don't work because foreign keys are not enabled. # See https://github.com/chroma-core/chroma/issues/3456. collections = Table("collections") q = ( self.querybuilder() .from_(collections) .where(collections.database_id == ParameterValue(result[0])) .delete() ) sql, params = get_sql(q, self.parameter_format()) cur.execute(sql, params) @override def list_databases( self, limit: Optional[int] = None, offset: Optional[int] = None, tenant: str = DEFAULT_TENANT, ) -> Sequence[Database]: with self.tx() as cur: databases = Table("databases") q = ( self.querybuilder() .from_(databases) .select(databases.id, databases.name) .where(databases.tenant_id == ParameterValue(tenant)) .offset(offset) .limit( sys.maxsize if limit is None else limit ) # SQLite requires that a limit is provided to use offset .orderby(databases.created_at) ) sql, params = get_sql(q, self.parameter_format()) rows = cur.execute(sql, params).fetchall() return [ Database( id=cast(UUID, self.uuid_from_db(row[0])), name=row[1], tenant=tenant, ) for row in rows ] @override def create_tenant(self, name: str) -> None: with self.tx() as cur: tenants = Table("tenants") insert_tenant = ( self.querybuilder() .into(tenants) .columns(tenants.id) .insert(ParameterValue(name)) ) sql, params = get_sql(insert_tenant, self.parameter_format()) try: cur.execute(sql, params) except self.unique_constraint_error() as e: raise UniqueConstraintError(f"Tenant {name} already exists") from e @override def get_tenant(self, name: str) -> Tenant: with self.tx() as cur: tenants = Table("tenants") q = ( self.querybuilder() .from_(tenants) .select(tenants.id) .where(tenants.id == ParameterValue(name)) ) sql, params = get_sql(q, self.parameter_format()) row = cur.execute(sql, params).fetchone() if not row: raise NotFoundError(f"Tenant {name} not found") return Tenant(name=name) # Create a segment using the passed cursor, so that the other changes # can be in the same transaction. def create_segment_with_tx(self, cur: Cursor, segment: Segment) -> None: add_attributes_to_current_span( { "segment_id": str(segment["id"]), "segment_type": segment["type"], "segment_scope": segment["scope"].value, "collection": str(segment["collection"]), } ) segments = Table("segments") insert_segment = ( self.querybuilder() .into(segments) .columns( segments.id, segments.type, segments.scope, segments.collection, ) .insert( ParameterValue(self.uuid_to_db(segment["id"])), ParameterValue(segment["type"]), ParameterValue(segment["scope"].value), ParameterValue(self.uuid_to_db(segment["collection"])), ) ) sql, params = get_sql(insert_segment, self.parameter_format()) try: cur.execute(sql, params) except self.unique_constraint_error() as e: raise UniqueConstraintError( f"Segment {segment['id']} already exists" ) from e # Insert segment metadata if it exists metadata_t = Table("segment_metadata") if segment["metadata"]: try: self._insert_metadata( cur, metadata_t, metadata_t.segment_id, segment["id"], segment["metadata"], ) except Exception as e: logger.error(f"Error inserting segment metadata: {e}") raise # TODO(rohit): Investigate and remove this method completely. @trace_method("SqlSysDB.create_segment", OpenTelemetryGranularity.ALL) @override def create_segment(self, segment: Segment) -> None: with self.tx() as cur: self.create_segment_with_tx(cur, segment) @trace_method("SqlSysDB.create_collection", OpenTelemetryGranularity.ALL) @override def create_collection( self, id: UUID, name: str, schema: Optional[Schema], configuration: CreateCollectionConfiguration, segments: Sequence[Segment], metadata: Optional[Metadata] = None, dimension: Optional[int] = None, get_or_create: bool = False, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> Tuple[Collection, bool]: if id is None and not get_or_create: raise ValueError("id must be specified if get_or_create is False") add_attributes_to_current_span( { "collection_id": str(id), "collection_name": name, } ) existing = self.get_collections(name=name, tenant=tenant, database=database) if existing: if get_or_create: collection = existing[0] return ( self.get_collections( id=collection.id, tenant=tenant, database=database )[0], False, ) else: raise UniqueConstraintError(f"Collection {name} already exists") collection = Collection( id=id, name=name, configuration_json=create_collection_configuration_to_json( configuration, cast(CollectionMetadata, metadata) ), serialized_schema=None, metadata=metadata, dimension=dimension, tenant=tenant, database=database, version=0, ) with self.tx() as cur: collections = Table("collections") databases = Table("databases") insert_collection = ( self.querybuilder() .into(collections) .columns( collections.id, collections.name, collections.config_json_str, collections.dimension, collections.database_id, ) .insert( ParameterValue(self.uuid_to_db(collection["id"])), ParameterValue(collection["name"]), ParameterValue( create_collection_configuration_to_json_str( configuration, cast(CollectionMetadata, metadata) ) ), ParameterValue(collection["dimension"]), # Get the database id for the database with the given name and tenant self.querybuilder() .select(databases.id) .from_(databases) .where(databases.name == ParameterValue(database)) .where(databases.tenant_id == ParameterValue(tenant)), ) ) sql, params = get_sql(insert_collection, self.parameter_format()) try: cur.execute(sql, params) except self.unique_constraint_error() as e: raise UniqueConstraintError( f"Collection {collection['id']} already exists" ) from e metadata_t = Table("collection_metadata") if collection["metadata"]: self._insert_metadata( cur, metadata_t, metadata_t.collection_id, collection.id, collection["metadata"], ) for segment in segments: self.create_segment_with_tx(cur, segment) return collection, True @trace_method("SqlSysDB.get_segments", OpenTelemetryGranularity.ALL) @override def get_segments( self, collection: UUID, id: Optional[UUID] = None, type: Optional[str] = None, scope: Optional[SegmentScope] = None, ) -> Sequence[Segment]: add_attributes_to_current_span( { "segment_id": str(id), "segment_type": type if type else "", "segment_scope": scope.value if scope else "", "collection": str(collection), } ) segments_t = Table("segments") metadata_t = Table("segment_metadata") q = ( self.querybuilder() .from_(segments_t) .select( segments_t.id, segments_t.type, segments_t.scope, segments_t.collection, metadata_t.key, metadata_t.str_value, metadata_t.int_value, metadata_t.float_value, metadata_t.bool_value, ) .left_join(metadata_t) .on(segments_t.id == metadata_t.segment_id) .orderby(segments_t.id) ) if id: q = q.where(segments_t.id == ParameterValue(self.uuid_to_db(id))) if type: q = q.where(segments_t.type == ParameterValue(type)) if scope: q = q.where(segments_t.scope == ParameterValue(scope.value)) if collection: q = q.where( segments_t.collection == ParameterValue(self.uuid_to_db(collection)) ) with self.tx() as cur: sql, params = get_sql(q, self.parameter_format()) rows = cur.execute(sql, params).fetchall() by_segment = groupby(rows, lambda r: cast(object, r[0])) segments = [] for segment_id, segment_rows in by_segment: id = self.uuid_from_db(str(segment_id)) rows = list(segment_rows) type = str(rows[0][1]) scope = SegmentScope(str(rows[0][2])) collection = self.uuid_from_db(rows[0][3]) # type: ignore[assignment] metadata = self._metadata_from_rows(rows) segments.append( Segment( id=cast(UUID, id), type=type, scope=scope, collection=collection, metadata=metadata, file_paths={}, ) ) return segments @trace_method("SqlSysDB.get_collections", OpenTelemetryGranularity.ALL) @override def get_collections( self, id: Optional[UUID] = None, name: Optional[str] = None, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, limit: Optional[int] = None, offset: Optional[int] = None, ) -> Sequence[Collection]: """Get collections by name, embedding function and/or metadata""" if name is not None and (tenant is None or database is None): raise ValueError( "If name is specified, tenant and database must also be specified in order to uniquely identify the collection" ) add_attributes_to_current_span( { "collection_id": str(id), "collection_name": name if name else "", } ) collections_t = Table("collections") metadata_t = Table("collection_metadata") databases_t = Table("databases") q = ( self.querybuilder() .from_(collections_t) .select( collections_t.id, collections_t.name, collections_t.config_json_str, collections_t.dimension, databases_t.name, databases_t.tenant_id, metadata_t.key, metadata_t.str_value, metadata_t.int_value, metadata_t.float_value, metadata_t.bool_value, ) .left_join(metadata_t) .on(collections_t.id == metadata_t.collection_id) .left_join(databases_t) .on(collections_t.database_id == databases_t.id) .orderby(collections_t.id) ) if id: q = q.where(collections_t.id == ParameterValue(self.uuid_to_db(id))) if name: q = q.where(collections_t.name == ParameterValue(name)) # Only if we have a name, tenant and database do we need to filter databases # Given an id, we can uniquely identify the collection so we don't need to filter databases if id is None and tenant and database: databases_t = Table("databases") q = q.where( collections_t.database_id == self.querybuilder() .select(databases_t.id) .from_(databases_t) .where(databases_t.name == ParameterValue(database)) .where(databases_t.tenant_id == ParameterValue(tenant)) ) # cant set limit and offset here because this is metadata and we havent reduced yet with self.tx() as cur: sql, params = get_sql(q, self.parameter_format()) rows = cur.execute(sql, params).fetchall() by_collection = groupby(rows, lambda r: cast(object, r[0])) collections = [] for collection_id, collection_rows in by_collection: id = self.uuid_from_db(str(collection_id)) rows = list(collection_rows) name = str(rows[0][1]) metadata = self._metadata_from_rows(rows) dimension = int(rows[0][3]) if rows[0][3] else None if rows[0][2] is not None: configuration = load_collection_configuration_from_json_str( rows[0][2] ) else: # 07/2024: This is a legacy case where we don't have a collection # configuration stored in the database. This non-destructively migrates # the collection to have a configuration, and takes into account any # HNSW params that might be in the existing metadata. configuration = self._insert_config_from_legacy_params( collection_id, metadata ) collections.append( Collection( id=cast(UUID, id), name=name, configuration_json=collection_configuration_to_json( configuration ), serialized_schema=None, metadata=metadata, dimension=dimension, tenant=str(rows[0][5]), database=str(rows[0][4]), version=0, ) ) # apply limit and offset if limit is not None: if offset is None: offset = 0 collections = collections[offset : offset + limit] else: collections = collections[offset:] return collections @override def get_collection_with_segments( self, collection_id: UUID ) -> CollectionAndSegments: collections = self.get_collections(id=collection_id) if len(collections) == 0: raise NotFoundError(f"Collection {collection_id} does not exist.") return CollectionAndSegments( collection=collections[0], segments=self.get_segments(collection=collection_id), ) @trace_method("SqlSysDB.delete_segment", OpenTelemetryGranularity.ALL) @override def delete_segment(self, collection: UUID, id: UUID) -> None: """Delete a segment from the SysDB""" add_attributes_to_current_span( { "segment_id": str(id), } ) t = Table("segments") q = ( self.querybuilder() .from_(t) .where(t.id == ParameterValue(self.uuid_to_db(id))) .delete() ) with self.tx() as cur: # no need for explicit del from metadata table because of ON DELETE CASCADE sql, params = get_sql(q, self.parameter_format()) sql = sql + " RETURNING id" result = cur.execute(sql, params).fetchone() if not result: raise NotFoundError(f"Segment {id} not found") # Used by delete_collection to delete all segments for a collection along with # the collection itself in a single transaction. def delete_segments_for_collection(self, cur: Cursor, collection: UUID) -> None: segments_t = Table("segments") q = ( self.querybuilder() .from_(segments_t) .where(segments_t.collection == ParameterValue(self.uuid_to_db(collection))) .delete() ) sql, params = get_sql(q, self.parameter_format()) cur.execute(sql, params) @trace_method("SqlSysDB.delete_collection", OpenTelemetryGranularity.ALL) @override def delete_collection( self, id: UUID, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE, ) -> None: """Delete a collection and all associated segments from the SysDB. Deletes the log stream for this collection as well.""" add_attributes_to_current_span( { "collection_id": str(id), } ) t = Table("collections") databases_t = Table("databases") q = ( self.querybuilder() .from_(t) .where(t.id == ParameterValue(self.uuid_to_db(id))) .where( t.database_id == self.querybuilder() .select(databases_t.id) .from_(databases_t) .where(databases_t.name == ParameterValue(database)) .where(databases_t.tenant_id == ParameterValue(tenant)) ) .delete() ) with self.tx() as cur: # no need for explicit del from metadata table because of ON DELETE CASCADE sql, params = get_sql(q, self.parameter_format()) sql = sql + " RETURNING id" result = cur.execute(sql, params).fetchone() if not result: raise NotFoundError(f"Collection {id} not found") # Delete segments. self.delete_segments_for_collection(cur, id) self._producer.delete_log(result[0]) @trace_method("SqlSysDB.update_segment", OpenTelemetryGranularity.ALL) @override def update_segment( self, collection: UUID, id: UUID, metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(), ) -> None: add_attributes_to_current_span( { "segment_id": str(id), "collection": str(collection), } ) segments_t = Table("segments") metadata_t = Table("segment_metadata") q = ( self.querybuilder() .update(segments_t) .where(segments_t.id == ParameterValue(self.uuid_to_db(id))) .set(segments_t.collection, ParameterValue(self.uuid_to_db(collection))) ) with self.tx() as cur: sql, params = get_sql(q, self.parameter_format()) if sql: # pypika emits a blank string if nothing to do cur.execute(sql, params) if metadata is None: q = ( self.querybuilder() .from_(metadata_t) .where(metadata_t.segment_id == ParameterValue(self.uuid_to_db(id))) .delete() ) sql, params = get_sql(q, self.parameter_format()) cur.execute(sql, params) elif metadata != Unspecified(): metadata = cast(UpdateMetadata, metadata) metadata = cast(UpdateMetadata, metadata) self._insert_metadata( cur, metadata_t, metadata_t.segment_id, id, metadata, set(metadata.keys()), ) @trace_method("SqlSysDB.update_collection", OpenTelemetryGranularity.ALL) @override def update_collection( self, id: UUID, name: OptionalArgument[str] = Unspecified(), dimension: OptionalArgument[Optional[int]] = Unspecified(), metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(), configuration: OptionalArgument[ Optional[UpdateCollectionConfiguration] ] = Unspecified(), ) -> None: add_attributes_to_current_span( { "collection_id": str(id), } ) collections_t = Table("collections") metadata_t = Table("collection_metadata") q = ( self.querybuilder() .update(collections_t) .where(collections_t.id == ParameterValue(self.uuid_to_db(id))) ) if not name == Unspecified(): q = q.set(collections_t.name, ParameterValue(name)) if not dimension == Unspecified(): q = q.set(collections_t.dimension, ParameterValue(dimension)) with self.tx() as cur: sql, params = get_sql(q, self.parameter_format()) if sql: # pypika emits a blank string if nothing to do sql = sql + " RETURNING id" result = cur.execute(sql, params) if not result.fetchone(): raise NotFoundError(f"Collection {id} not found") # TODO: Update to use better semantics where it's possible to update # individual keys without wiping all the existing metadata. # For now, follow current legancy semantics where metadata is fully reset if metadata != Unspecified(): q = ( self.querybuilder() .from_(metadata_t) .where( metadata_t.collection_id == ParameterValue(self.uuid_to_db(id)) ) .delete() ) sql, params = get_sql(q, self.parameter_format()) cur.execute(sql, params) if metadata is not None: metadata = cast(UpdateMetadata, metadata) self._insert_metadata( cur, metadata_t, metadata_t.collection_id, id, metadata, set(metadata.keys()), ) if configuration != Unspecified(): update_configuration = cast( UpdateCollectionConfiguration, configuration ) self._update_config_json_str(cur, update_configuration, id) else: if metadata != Unspecified(): metadata = cast(UpdateMetadata, metadata) if metadata is not None: update_configuration = ( update_collection_configuration_from_legacy_update_metadata( metadata ) ) self._update_config_json_str(cur, update_configuration, id) def _update_config_json_str( self, cur: Cursor, update_configuration: UpdateCollectionConfiguration, id: UUID ) -> None: collections_t = Table("collections") q = ( self.querybuilder() .from_(collections_t) .select(collections_t.config_json_str) .where(collections_t.id == ParameterValue(self.uuid_to_db(id))) ) sql, params = get_sql(q, self.parameter_format()) row = cur.execute(sql, params).fetchone() if not row: raise NotFoundError(f"Collection {id} not found") config_json_str = row[0] existing_config = load_collection_configuration_from_json_str(config_json_str) new_config = overwrite_collection_configuration( existing_config, update_configuration ) q = ( self.querybuilder() .update(collections_t) .set( collections_t.config_json_str, ParameterValue(collection_configuration_to_json_str(new_config)), ) .where(collections_t.id == ParameterValue(self.uuid_to_db(id))) ) sql, params = get_sql(q, self.parameter_format()) cur.execute(sql, params) @trace_method("SqlSysDB._metadata_from_rows", OpenTelemetryGranularity.ALL) def _metadata_from_rows( self, rows: Sequence[Tuple[Any, ...]] ) -> Optional[Metadata]: """Given SQL rows, return a metadata map (assuming that the last four columns are the key, str_value, int_value & float_value)""" add_attributes_to_current_span( { "num_rows": len(rows), } ) metadata: Dict[str, Union[str, int, float, bool]] = {} for row in rows: key = str(row[-5]) if row[-4] is not None: metadata[key] = str(row[-4]) elif row[-3] is not None: metadata[key] = int(row[-3]) elif row[-2] is not None: metadata[key] = float(row[-2]) elif row[-1] is not None: metadata[key] = bool(row[-1]) return metadata or None @trace_method("SqlSysDB._insert_metadata", OpenTelemetryGranularity.ALL) def _insert_metadata( self, cur: Cursor, table: Table, id_col: Column, id: UUID, metadata: UpdateMetadata, clear_keys: Optional[Set[str]] = None, ) -> None: # It would be cleaner to use something like ON CONFLICT UPDATE here But that is # very difficult to do in a portable way (e.g sqlite and postgres have # completely different sytnax) add_attributes_to_current_span( { "num_keys": len(metadata), } ) if clear_keys: q = ( self.querybuilder() .from_(table) .where(id_col == ParameterValue(self.uuid_to_db(id))) .where(table.key.isin([ParameterValue(k) for k in clear_keys])) .delete() ) sql, params = get_sql(q, self.parameter_format()) cur.execute(sql, params) q = ( self.querybuilder() .into(table) .columns( id_col, table.key, table.str_value, table.int_value, table.float_value, table.bool_value, ) ) sql_id = self.uuid_to_db(id) for k, v in metadata.items(): # Note: The order is important here because isinstance(v, bool) # and isinstance(v, int) both are true for v of bool type. if isinstance(v, bool): q = q.insert( ParameterValue(sql_id), ParameterValue(k), None, None, None, ParameterValue(int(v)), ) elif isinstance(v, str): q = q.insert( ParameterValue(sql_id), ParameterValue(k), ParameterValue(v), None, None, None, ) elif isinstance(v, int): q = q.insert( ParameterValue(sql_id), ParameterValue(k), None, ParameterValue(v), None, None, ) elif isinstance(v, float): q = q.insert( ParameterValue(sql_id), ParameterValue(k), None, None, ParameterValue(v), None, ) elif v is None: continue sql, params = get_sql(q, self.parameter_format()) if sql: cur.execute(sql, params) def _insert_config_from_legacy_params( self, collection_id: Any, metadata: Optional[Metadata] ) -> CollectionConfiguration: """Insert the configuration from legacy metadata params into the collections table, and return the configuration object.""" # This is a legacy case where we don't have configuration stored in the database # This is non-destructive, we don't delete or overwrite any keys in the metadata collections_t = Table("collections") create_collection_config = CreateCollectionConfiguration() # Write the configuration into the database configuration_json_str = create_collection_configuration_to_json_str( create_collection_config, cast(CollectionMetadata, metadata) ) q = ( self.querybuilder() .update(collections_t) .set( collections_t.config_json_str, ParameterValue(configuration_json_str), ) .where(collections_t.id == ParameterValue(collection_id)) ) sql, params = get_sql(q, self.parameter_format()) with self.tx() as cur: cur.execute(sql, params) return load_collection_configuration_from_json_str(configuration_json_str) @override def get_collection_size(self, id: UUID) -> int: raise NotImplementedError @override def count_collections( self, tenant: str = DEFAULT_TENANT, database: Optional[str] = None, ) -> int: """Gets the number of collections for the (tenant, database) combination.""" # TODO(Sanket): Implement this efficiently using a count query. # Note, the underlying get_collections api always requires a database # to be specified. In the sysdb implementation in go code, it does not # filter on database if it is set to "". This is a bad API and # should be fixed. For now, we will replicate the behavior. request_database: str = "" if database is None or database == "" else database return len(self.get_collections(tenant=tenant, database=request_database))
SqlSysDB
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call.py
{ "start": 41316, "end": 44012 }
class ____: """Test async execution with wrap_model_call.""" async def test_async_model_with_middleware(self) -> None: """Test that wrap_model_call works with async model execution.""" log = [] class LoggingMiddleware(AgentMiddleware): async def awrap_model_call(self, request, handler): log.append("before") result = await handler(request) log.append("after") return result model = GenericFakeChatModel(messages=iter([AIMessage(content="Async response")])) agent = create_agent(model=model, middleware=[LoggingMiddleware()]) result = await agent.ainvoke({"messages": [HumanMessage("Test")]}) assert log == ["before", "after"] assert result["messages"][1].content == "Async response" async def test_async_retry(self) -> None: """Test retry logic with async execution.""" call_count = {"value": 0} class AsyncFailOnceThenSucceed(GenericFakeChatModel): async def _agenerate(self, messages, **kwargs): call_count["value"] += 1 if call_count["value"] == 1: raise ValueError("First async call fails") return await super()._agenerate(messages, **kwargs) class RetryMiddleware(AgentMiddleware): async def awrap_model_call(self, request, handler): try: return await handler(request) except Exception: return await handler(request) model = AsyncFailOnceThenSucceed(messages=iter([AIMessage(content="Async success")])) agent = create_agent(model=model, middleware=[RetryMiddleware()]) result = await agent.ainvoke({"messages": [HumanMessage("Test")]}) assert call_count["value"] == 2 assert result["messages"][1].content == "Async success" async def test_decorator_with_async_agent(self) -> None: """Test that decorated middleware works with async agent invocation.""" call_log = [] @wrap_model_call async def logging_middleware(request, handler): call_log.append("before") result = await handler(request) call_log.append("after") return result model = GenericFakeChatModel(messages=iter([AIMessage(content="Async response")])) agent = create_agent(model=model, middleware=[logging_middleware]) result = await agent.ainvoke({"messages": [HumanMessage("Test")]}) assert call_log == ["before", "after"] assert result["messages"][1].content == "Async response"
TestAsyncWrapModelCall
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels21.py
{ "start": 315, "end": 1880 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels21.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "pie"}) data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "values": "=Sheet1!$A$1:$A$5", "data_labels": { "value": True, "category": True, "series_name": True, "percentage": True, "separator": ";", "leader_lines": True, "position": "inside_end", "legend_key": True, "num_format": "#,##0.00", "font": { "name": "Consolas", "baseline": 1 * -1, "pitch_family": 49, "charset": 0, }, }, } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
numpy__numpy
doc/neps/nep-0016-benchmark.py
{ "start": 211, "end": 1053 }
class ____: pass ArrayBase.register(ABCArray2) not_array = NotArray() attr_array = AttrArray() abc_array_1 = ABCArray1() abc_array_2 = ABCArray2() # Make sure ABC cache is primed isinstance(not_array, ArrayBase) isinstance(abc_array_1, ArrayBase) isinstance(abc_array_2, ArrayBase) runner = perf.Runner() def t(name, statement): runner.timeit(name, statement, globals=globals()) t("np.asarray([])", "np.asarray([])") arrobj = np.array([]) t("np.asarray(arrobj)", "np.asarray(arrobj)") t("attr, False", "getattr(not_array, '__array_implementer__', False)") t("attr, True", "getattr(attr_array, '__array_implementer__', False)") t("ABC, False", "isinstance(not_array, ArrayBase)") t("ABC, True, via inheritance", "isinstance(abc_array_1, ArrayBase)") t("ABC, True, via register", "isinstance(abc_array_2, ArrayBase)")
ABCArray2
python
getsentry__sentry
src/sentry/api/endpoints/organization_profiling_functions.py
{ "start": 2407, "end": 12640 }
class ____(OrganizationEventsV2EndpointBase): owner = ApiOwner.PROFILING publish_status = { "GET": ApiPublishStatus.PRIVATE, } def has_feature(self, organization: Organization, request: Request): return features.has( "organizations:profiling-global-suspect-functions", organization, actor=request.user ) def get(self, request: Request, organization: Organization) -> Response: if not self.has_feature(organization, request): return Response(status=404) try: snuba_params = self.get_snuba_params(request, organization) except NoProjects: return Response({}) serializer = FunctionTrendsSerializer(data=request.GET) if not serializer.is_valid(): return Response(serializer.errors, status=400) data = serializer.validated_data with handle_query_errors(): top_functions = functions.query( selected_columns=[ "project.id", "fingerprint", "package", "function", "count()", ], query=data.get("query"), snuba_params=snuba_params, orderby=["-count()"], limit=TOP_FUNCTIONS_LIMIT, referrer=Referrer.API_PROFILING_FUNCTION_TRENDS_TOP_EVENTS.value, auto_aggregations=True, use_aggregate_conditions=True, transform_alias_to_input_format=True, ) def get_event_stats( _columns, query, snuba_params, _rollup, zerofill_results, _comparison_delta ): rollup = get_rollup_from_range(snuba_params.date_range) chunks = [ top_functions["data"][i : i + FUNCTIONS_PER_QUERY] for i in range(0, len(top_functions["data"]), FUNCTIONS_PER_QUERY) ] builders = [ ProfileTopFunctionsTimeseriesQueryBuilder( dataset=Dataset.Functions, params={}, snuba_params=snuba_params, interval=rollup, top_events=chunk, other=False, query=query, selected_columns=["project.id", "fingerprint"], # It's possible to override the columns via # the `yAxis` qs. So we explicitly ignore the # columns, and hard code in the columns we want. timeseries_columns=[data["function"], "examples()", "all_examples()"], config=QueryBuilderConfig( skip_tag_resolution=True, ), ) for chunk in chunks ] bulk_results = bulk_snuba_queries( [builder.get_snql_query() for builder in builders], Referrer.API_PROFILING_FUNCTION_TRENDS_STATS.value, ) results = {} for chunk, builder, result in zip(chunks, builders, bulk_results): formatted_results = functions.format_top_events_timeseries_results( result, builder, rollup=rollup, snuba_params=snuba_params, top_events={"data": chunk}, result_key_order=["project.id", "fingerprint"], ) results.update(formatted_results) return results def get_trends_data(stats_data) -> list[BreakpointData]: if not stats_data: return [] trends_request: BreakpointRequest = { "data": { k: { "data": v[data["function"]]["data"], "data_start": v[data["function"]]["start"], "data_end": v[data["function"]]["end"], # We want to use the first 20% of the data as historical data # to help filter out false positives. # This means if there is a change in the first 20%, it will # not be detected as a breakpoint. "request_start": v[data["function"]]["data"][ len(v[data["function"]]["data"]) // 5 ][0], "request_end": v[data["function"]]["end"], } for k, v in stats_data.items() if v[data["function"]]["data"] }, "sort": data["trend"].as_sort(), } return detect_breakpoints(trends_request)["data"] stats_data = self.get_event_stats_data( request, organization, get_event_stats, top_events=FUNCTIONS_PER_QUERY, query_column=data["function"], additional_query_columns=["examples()", "all_examples()"], snuba_params=snuba_params, query=data.get("query"), ) trending_functions = get_trends_data(stats_data) all_trending_functions_count = len(trending_functions) set_span_attribute("profiling.top_functions", all_trending_functions_count) # Profiling functions have a resolution of ~10ms. To increase the confidence # of the results, the caller can specify a min threshold for the trend difference. threshold = data.get("threshold") if threshold is not None: trending_functions = [ data for data in trending_functions if abs(data["trend_difference"]) >= threshold * 1e6 ] filtered_trending_functions_count = all_trending_functions_count - len(trending_functions) set_span_attribute( "profiling.top_functions.below_threshold", filtered_trending_functions_count ) # Make sure to sort the results so that it's in order of largest change # to smallest change (ASC/DESC depends on the trend type) trending_functions.sort( key=lambda function: function["trend_percentage"], reverse=data["trend"] is TrendType.REGRESSION, ) def paginate_trending_events(offset, limit): return {"data": trending_functions[offset : limit + offset]} def get_stats_data_for_trending_events(results): functions = { f"{function['project.id']},{function['fingerprint']}": function for function in top_functions.get("data", []) } formatted_results = [] for result in results["data"]: # The endpoint originally was meant for only transactions # hence the name of the key, but it can be adapted to work # for functions as well. key = f"{result['project']},{result['transaction']}" formatted_result = { "stats": stats_data[key][data["function"]], "worst": [ # deprecated, migrate to `examples` (ts, data[0]["count"][0]) for ts, data in stats_data[key]["examples()"]["data"] if data[0]["count"] # filter out entries without an example ], "examples": [ (ts, data[0]["count"][0]) for ts, data in stats_data[key]["all_examples()"]["data"] if data[0]["count"] # filter out entries without an example ], } formatted_result.update( { k: result[k] for k in [ "aggregate_range_1", "aggregate_range_2", "breakpoint", "change", "project", "trend_difference", "trend_percentage", "unweighted_p_value", # "unweighted_t_value", # unneeded, but also can error because of infs ] } ) formatted_result.update( { k: functions[key][k] for k in ["fingerprint", "package", "function", "count()"] } ) formatted_results.append(formatted_result) return formatted_results with handle_query_errors(): return self.paginate( request=request, paginator=GenericOffsetPaginator(data_fn=paginate_trending_events), on_results=get_stats_data_for_trending_events, default_per_page=5, max_per_page=5, ) def get_rollup_from_range(date_range: timedelta, top_functions=TOP_FUNCTIONS_LIMIT) -> int: interval = parse_stats_period(get_interval_from_range(date_range)) if interval is None: interval = timedelta(hours=1) validate_interval(interval, InvalidSearchQuery(), date_range, top_functions) return int(interval.total_seconds()) def get_interval_from_range(date_range: timedelta) -> str: """ This is a specialized variant of the generic `get_interval_from_range` function tailored for the function trends use case. We have a limit of 10,000 from snuba, and if we limit ourselves to 50 unique functions, this gives us room for 200 data points per function. The default `get_interval_from_range` is fairly close to this already so this implementation provides this additional guarantee. """ if date_range > timedelta(days=60): return "12h" if date_range > timedelta(days=30): return "8h" if date_range > timedelta(days=14): return "4h" if date_range > timedelta(days=7): return "2h" return "1h"
OrganizationProfilingFunctionTrendsEndpoint
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0033_dont_cascade_delete_builds.py
{ "start": 183, "end": 723 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0032_migrate_version_data_to_build"), ] operations = [ migrations.AlterField( model_name="build", name="version", field=models.ForeignKey( null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="builds", to="builds.Version", verbose_name="Version", ), ), ]
Migration
python
tensorflow__tensorflow
tensorflow/python/keras/saving/saved_model/serialized_attributes.py
{ "start": 10832, "end": 12096 }
class ____(SerializedAttributes.with_attributes( 'LayerAttributes', checkpointable_objects=['non_trainable_variables', 'layers', 'metrics', 'layer_regularization_losses', 'layer_metrics'], functions=['call_and_return_conditional_losses', 'activity_regularizer_fn'], copy_from=[CommonEndpoints] )): """Layer checkpointable objects + functions that are saved to the SavedModel. List of all attributes: All attributes from CommonEndpoints non_trainable_variables: List of non-trainable variables in the layer and its sublayers. layers: List of all sublayers. metrics: List of all metrics in the layer and its sublayers. call_and_return_conditional_losses: Function that takes inputs and returns a tuple of (outputs of the call function, list of input-dependent losses). The list of losses excludes the activity regularizer function, which is separate to allow the deserialized Layer object to define a different activity regularizer. activity_regularizer_fn: Callable that returns the activity regularizer loss layer_regularization_losses: List of losses owned only by this layer. layer_metrics: List of metrics owned by this layer. """
LayerAttributes
python
streamlit__streamlit
lib/streamlit/web/server/routes.py
{ "start": 8541, "end": 9799 }
class ____(_SpecialRequestHandler): def initialize(self) -> None: # Make a copy of the allowedOrigins list, since we might modify it later: self._allowed_origins = _DEFAULT_ALLOWED_MESSAGE_ORIGINS.copy() if ( config.get_option("global.developmentMode") and "http://localhost" not in self._allowed_origins ): # Allow messages from localhost in dev mode for testing of host <-> guest communication self._allowed_origins.append("http://localhost") async def get(self) -> None: self.write( { "allowedOrigins": self._allowed_origins, "useExternalAuthToken": False, # Default host configuration settings. "enableCustomParentMessages": False, "enforceDownloadInNewTab": False, "metricsUrl": "", "blockErrorDialogs": False, # Determines whether the crossOrigin attribute is set on some elements, e.g. img, video, audio, and if # so with which value. One of None, "anonymous", "use-credentials". "resourceCrossOriginMode": None, } ) self.set_status(200)
HostConfigHandler
python
huggingface__transformers
src/transformers/models/gpt_neo/configuration_gpt_neo.py
{ "start": 784, "end": 9150 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`GPTNeoModel`]. It is used to instantiate a GPT Neo model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the GPTNeo [EleutherAI/gpt-neo-1.3B](https://huggingface.co/EleutherAI/gpt-neo-1.3B) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 50257): Vocabulary size of the GPT Neo model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`GPTNeoModel`]. Vocabulary size of the model. Defines the different tokens that can be represented by the *inputs_ids* passed to the forward method of [`GPTNeoModel`]. max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). hidden_size (`int`, *optional*, defaults to 2048): Dimensionality of the encoder layers and the pooler layer. num_layers (`int`, *optional*, defaults to 24): Number of hidden layers in the Transformer encoder. attention_types (`List`, *optional*, defaults to `[[['global', 'local'], 12]]`): The type of attention for each layer in a `List` of the following format `[[["attention_type"], num_layerss]]` e.g. for a 24 layer model `[[["global"], 24]]` or `[[["global", "local"], 12]]` Choose the value of `attention_type` from `["global", "local"]` num_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer in the Transformer encoder. intermediate_size (`int`, *optional*, defaults to 8192): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. window_size (`int`, *optional*, defaults to 256): The size of the sliding window for local attention. activation_function (`str` or `function`, *optional*, defaults to `"gelu_new"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported. resid_dropout (`float`, *optional*, defaults to 0.0): Residual dropout used in the attention pattern. embed_dropout (`float`, *optional*, defaults to 0.0): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. classifier_dropout (`float`, *optional*, defaults to 0.1): Argument used when doing token classification, used in the model [`GPTNeoForTokenClassification`]. The dropout ratio for the hidden layer. layer_norm_epsilon (`float`, *optional*, defaults to 1e-05): The epsilon used by the layer normalization layers. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. bos_token_id (`int`, *optional*, defaults to 50256): The id of the beginning of sentence token in the vocabulary. eos_token_id (`int`, *optional*, defaults to 50256): The id of the end of sentence token in the vocabulary. Example: ```python >>> from transformers import GPTNeoConfig, GPTNeoModel >>> # Initializing a GPTNeo EleutherAI/gpt-neo-1.3B style configuration >>> configuration = GPTNeoConfig() >>> # Initializing a model (with random weights) from the EleutherAI/gpt-neo-1.3B style configuration >>> model = GPTNeoModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "gpt_neo" keys_to_ignore_at_inference = ["past_key_values"] attribute_map = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self, vocab_size=50257, max_position_embeddings=2048, hidden_size=2048, num_layers=24, attention_types=[[["global", "local"], 12]], num_heads=16, intermediate_size=None, window_size=256, activation_function="gelu_new", resid_dropout=0.0, embed_dropout=0.0, attention_dropout=0.0, classifier_dropout=0.1, layer_norm_epsilon=1e-5, initializer_range=0.02, use_cache=True, bos_token_id=50256, eos_token_id=50256, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.num_layers = num_layers self.num_heads = num_heads self.intermediate_size = intermediate_size self.window_size = window_size self.activation_function = activation_function self.resid_dropout = resid_dropout self.embed_dropout = embed_dropout self.attention_dropout = attention_dropout self.classifier_dropout = classifier_dropout self.layer_norm_epsilon = layer_norm_epsilon self.initializer_range = initializer_range self.use_cache = use_cache self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id self.attention_types = attention_types self.attention_layers = self.expand_attention_types_params(attention_types) if len(self.attention_layers) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f"but is `len(config.attention_layers) = {len(self.attention_layers)}`, " f"`config.num_layers = {self.num_layers}`. " "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) @staticmethod def expand_attention_types_params(attention_types): attentions = [] for item in attention_types: for _ in range(item[1]): attentions.extend(item[0]) return attentions def custom_unfold(input, dimension, size, step): """Custom torch.Tensor.unfold implementation to enable the export to ONNX.""" import torch shape = input.size() rank = len(shape) sizedim = shape[dimension] low_indices = torch.arange(0, sizedim, step) min_length = torch.div(sizedim - size, step, rounding_mode="floor") + 1 indices = torch.arange(size) + low_indices[:min_length][:, None] s = [slice(None)] * rank s[dimension] = indices sliced = input[s] perm = list(range(0, rank + 1)) perm.append(perm.pop(dimension + 1)) return sliced.permute(perm) def custom_get_block_length_and_num_blocks(seq_length, window_size): """ Custom implementation for GPTNeoAttentionMixin._get_block_length_and_num_blocks to enable the export to ONNX as original implementation uses Python variables and control flow. """ import torch candidates = torch.arange(1, window_size) remainders = torch.remainder(seq_length, candidates) divisor_indices = remainders == 0 divisors = candidates[divisor_indices] largest_divisor = torch.max(divisors) return largest_divisor, torch.div(seq_length, largest_divisor, rounding_mode="floor") __all__ = ["GPTNeoConfig"]
GPTNeoConfig
python
huggingface__transformers
src/transformers/models/arcee/modular_arcee.py
{ "start": 8221, "end": 8309 }
class ____(NemotronMLP): pass @auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
ArceeMLP
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 878866, "end": 879138 }
class ____( sgqlc.types.Type, ProjectV2ItemFieldValueCommon, Node ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("text",) text = sgqlc.types.Field(String, graphql_name="text")
ProjectV2ItemFieldTextValue
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 177097, "end": 179164 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateCheckRun""" __schema__ = github_schema __field_names__ = ( "repository_id", "name", "head_sha", "details_url", "external_id", "status", "started_at", "conclusion", "completed_at", "output", "actions", "client_mutation_id", ) repository_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="repositoryId") """The node ID of the repository.""" name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """The name of the check.""" head_sha = sgqlc.types.Field(sgqlc.types.non_null(GitObjectID), graphql_name="headSha") """The SHA of the head commit.""" details_url = sgqlc.types.Field(URI, graphql_name="detailsUrl") """The URL of the integrator's site that has the full details of the check. """ external_id = sgqlc.types.Field(String, graphql_name="externalId") """A reference for the run on the integrator's system.""" status = sgqlc.types.Field(RequestableCheckStatusState, graphql_name="status") """The current status.""" started_at = sgqlc.types.Field(DateTime, graphql_name="startedAt") """The time that the check run began.""" conclusion = sgqlc.types.Field(CheckConclusionState, graphql_name="conclusion") """The final conclusion of the check.""" completed_at = sgqlc.types.Field(DateTime, graphql_name="completedAt") """The time that the check run finished.""" output = sgqlc.types.Field(CheckRunOutput, graphql_name="output") """Descriptive details about the run.""" actions = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null(CheckRunAction)), graphql_name="actions") """Possible further actions the integrator can perform, which a user may trigger. """ client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
CreateCheckRunInput
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py
{ "start": 112791, "end": 116310 }
class ____(test.TestCase): def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, expected): """Verifies the output values of the convolution function. Args: tensor_in_sizes: Input tensor dimensions in [batch, input_rows, input_cols, input_depth]. filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, input_depth, depth_multiplier]. stride: Stride. padding: Padding type. expected: An array containing the expected operation outputs. """ total_size_1 = 1 total_size_2 = 1 for s in tensor_in_sizes: total_size_1 *= s for s in filter_in_sizes: total_size_2 *= s # Initializes the input tensor with array containing incrementing # numbers from 1. x1 = [f * 1.0 for f in range(1, total_size_1 + 1)] x2 = [f * 1.0 for f in range(1, total_size_2 + 1)] with self.cached_session(): t1 = constant_op.constant(x1, shape=tensor_in_sizes) t1.set_shape(tensor_in_sizes) t2 = constant_op.constant(x2, shape=filter_in_sizes) conv = nn_impl.depthwise_conv2d( t1, t2, strides=[1, stride, stride, 1], padding=padding) value = self.evaluate(conv) tf_logging.debug("value = %s", value) self.assertArrayNear(expected, np.ravel(value), 1e-5) self.assertShapeEqual(value, conv) def testConv2D2x2Filter(self): # The inputs look like this (it's a 3 x 2 matrix, each of depth 2): # # [ (1.0, 2.0), (3.0, 4.0), ( 5.0, 6.0) ] # [ (7.0, 8.0), (9.0, 10.0), (11.0, 12.0) ] # We can view this as two inputs # # input depth 0: # # [ 1.0, 3.0, 5.0 ] # [ 7.0, 9.0, 11.0 ] # # input depth 1: # # [ 2.0, 4.0, 6.0 ] # [ 8.0, 10.0, 12.0 ] # # The filter looks like this (it has two 2 x 2 patches, each generating 2 # depths): # # filter #0: # # [ (1.0, 3.0), ( 5.0, 7.0)] # [ (9.0, 11.0), (13.0, 15.0)] # # filter #1: # # [ ( 2.0, 4.0), ( 6.0, 8.0)] # [ (10.0, 12.0), (14.0, 16.0)] # # So the outputs are: # # (position 0, 0: in_depth 0, output_depth 0 -- using filter #0) # 1.0 * 1.0 + 7.0 * 9.0 + 3.0 * 5.0 + 9.0 * 13.0 = 196 # (position 0, 0: in_depth 0, output_depth 1 -- using filter #1) # 1.0 * 2.0 + 7.0 * 10.0 + 3.0 * 6.0 + 9.0 * 14.0 = 216 # (position 0, 0: in_depth 1, output_depth 2 -- using filter #0) # 2.0 * 3.0 + 8.0 * 11.0 + 4.0 * 7.0 + 10.0 * 15.0 = 272 # (position 0, 0: in_depth 1, output_depth 3 -- using filter #1) # 2.0 * 4.0 + 8.0 * 12.0 + 4.0 * 8.0 + 10.0 * 16.0 = 296 # # (position 1, 0: in_depth 0, output_depth 0 -- using filter #0) # 3.0 * 1.0 + 9.0 * 9.0 + 5.0 * 5.0 + 11.0 * 13.0 = 252 # (position 1, 0: in_depth 0, output_depth 1 -- using filter #1) # 3.0 * 2.0 + 9.0 * 10.0 + 5.0 * 6.0 + 11.0 * 14.0 = 280 # (position 1, 0: in_depth 1, output_depth 2 -- using filter #0) # 4.0 * 3.0 + 10.0 * 11.0 + 6.0 * 7.0 + 12.0 * 15.0 = 344 # (position 1, 0: in_depth 1, output_depth 3 -- using filter #1) # 4.0 * 4.0 + 10.0 * 12.0 + 6.0 * 8.0 + 12.0 * 16.0 = 376 expected_output = [196, 216, 272, 296, 252, 280, 344, 376] self._VerifyValues( tensor_in_sizes=[1, 2, 3, 2], filter_in_sizes=[2, 2, 2, 2], stride=1, padding="VALID", expected=expected_output) @test_util.run_all_without_tensor_float_32("Avoid TF32 conv on GPU")
DepthwiseConv2DTest
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-operations-to-satisfy-conditions.py
{ "start": 844, "end": 1463 }
class ____(object): def minimumOperations(self, grid): """ :type grid: List[List[int]] :rtype: int """ INF = float("inf") MAX_VALUE = 9 dp = [0]*(MAX_VALUE+1) for j in xrange(len(grid[0])): new_dp = [INF]*(MAX_VALUE+1) cnt = [0]*(MAX_VALUE+1) for i in xrange(len(grid)): cnt[grid[i][j]] += 1 for i in xrange(MAX_VALUE+1): new_dp[i] = min(new_dp[i], min(dp[k] for k in xrange(MAX_VALUE+1) if k != i)+(len(grid)-cnt[i])) dp = new_dp return min(dp)
Solution2
python
mlflow__mlflow
tests/tracing/test_fluent.py
{ "start": 3462, "end": 3699 }
class ____: @mlflow.trace() def predict(self, x, y): return self.some_operation_raise_error(x, y) @mlflow.trace() def some_operation_raise_error(self, x, y): raise ValueError("Some error")
ErroringTestModel
python
numpy__numpy
numpy/_core/tests/test_numeric.py
{ "start": 110433, "end": 113045 }
class ____: rtol = 1e-5 atol = 1e-8 def setup_method(self): self.olderr = np.seterr(invalid='ignore') def teardown_method(self): np.seterr(**self.olderr) def tst_allclose(self, x, y): assert_(np.allclose(x, y), f"{x} and {y} not close") def tst_not_allclose(self, x, y): assert_(not np.allclose(x, y), f"{x} and {y} shouldn't be close") def test_ip_allclose(self): # Parametric test factory. arr = np.array([100, 1000]) aran = np.arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([1, 0], [1, 0]), ([atol], [0]), ([1], [1 + rtol + atol]), (arr, arr + arr * rtol), (arr, arr + arr * rtol + atol * 2), (aran, aran + aran * rtol), (np.inf, np.inf), (np.inf, [np.inf])] for (x, y) in data: self.tst_allclose(x, y) def test_ip_not_allclose(self): # Parametric test factory. aran = np.arange(125).reshape((5, 5, 5)) atol = self.atol rtol = self.rtol data = [([np.inf, 0], [1, np.inf]), ([np.inf, 0], [1, 0]), ([np.inf, np.inf], [1, np.inf]), ([np.inf, np.inf], [1, 0]), ([-np.inf, 0], [np.inf, 0]), ([np.nan, 0], [np.nan, 0]), ([atol * 2], [0]), ([1], [1 + rtol + atol * 2]), (aran, aran + aran * atol + atol * 2), (np.array([np.inf, 1]), np.array([0, np.inf]))] for (x, y) in data: self.tst_not_allclose(x, y) def test_no_parameter_modification(self): x = np.array([np.inf, 1]) y = np.array([0, np.inf]) np.allclose(x, y) assert_array_equal(x, np.array([np.inf, 1])) assert_array_equal(y, np.array([0, np.inf])) def test_min_int(self): # Could make problems because of abs(min_int) == min_int min_int = np.iinfo(np.int_).min a = np.array([min_int], dtype=np.int_) assert_(np.allclose(a, a)) def test_equalnan(self): x = np.array([1.0, np.nan]) assert_(np.allclose(x, x, equal_nan=True)) def test_return_class_is_ndarray(self): # Issue gh-6475 # Check that allclose does not preserve subtypes class Foo(np.ndarray): def __new__(cls, *args, **kwargs): return np.array(*args, **kwargs).view(cls) a = Foo([1]) assert_(type(np.allclose(a, a)) is bool)
TestAllclose
python
doocs__leetcode
solution/1700-1799/1705.Maximum Number of Eaten Apples/Solution.py
{ "start": 0, "end": 537 }
class ____: def eatenApples(self, apples: List[int], days: List[int]) -> int: n = len(days) i = ans = 0 q = [] while i < n or q: if i < n and apples[i]: heappush(q, (i + days[i] - 1, apples[i])) while q and q[0][0] < i: heappop(q) if q: t, v = heappop(q) v -= 1 ans += 1 if v and t > i: heappush(q, (t, v)) i += 1 return ans
Solution
python
has2k1__plotnine
plotnine/stats/stat_qq_line.py
{ "start": 284, "end": 3646 }
class ____(stat): """ Calculate line through quantile-quantile plot {usage} Parameters ---------- {common_parameters} distribution : str, default="norm" Distribution or distribution function name. The default is *norm* for a normal probability plot. Objects that look enough like a stats.distributions instance (i.e. they have a ppf method) are also accepted. See [scipy stats ](`scipy.stats`) for available distributions. dparams : dict, default=None Distribution-specific shape parameters (shape parameters plus location and scale). quantiles : array_like, default=None Probability points at which to calculate the theoretical quantile values. If provided, must be the same number as as the sample data points. The default is to use calculated theoretical points, use to `alpha_beta` control how these points are generated. alpha_beta : tuple, default=(3/8, 3/8) Parameter values to use when calculating the quantiles. line_p : tuple, default=(0.25, 0.75) Quantiles to use when fitting a Q-Q line. Must be 2 values. fullrange : bool, default=False If `True`{.py} the fit will span the full range of the plot. See Also -------- plotnine.geom_qq_line : The default `geom` for this `stat`. scipy.stats.mstats.plotting_positions : Uses `alpha_beta` to calculate the quantiles. """ REQUIRED_AES = {"sample"} DEFAULT_PARAMS = { "geom": "qq_line", "position": "identity", "na_rm": False, "distribution": "norm", "dparams": {}, "quantiles": None, "alpha_beta": (3 / 8, 3 / 8), "line_p": (0.25, 0.75), "fullrange": False, } CREATES = {"x", "y"} def setup_params(self, data): if len(self.params["line_p"]) != 2: raise PlotnineError( "Cannot fit line quantiles. 'line_p' must be of length 2" ) def compute_group(self, data, scales): from scipy.stats.mstats import mquantiles from .distributions import get_continuous_distribution line_p = self.params["line_p"] dparams = self.params["dparams"] # Compute theoretical values sample = cast("FloatArray", data["sample"].sort_values().to_numpy()) theoretical = theoretical_qq( sample, self.params["distribution"], alpha=self.params["alpha_beta"][0], beta=self.params["alpha_beta"][1], quantiles=self.params["quantiles"], distribution_params=dparams, ) # Compute slope & intercept of the line through the quantiles cdist = get_continuous_distribution(self.params["distribution"]) x_coords = cdist.ppf(line_p, **dparams) y_coords = mquantiles(sample, line_p) slope = (np.diff(y_coords) / np.diff(x_coords))[0] intercept = y_coords[0] - slope * x_coords[0] # Get x,y points that describe the line if self.params["fullrange"] and scales.x: x = scales.x.dimension() else: x = theoretical.min(), theoretical.max() x = np.asarray(x) y = slope * x + intercept data = pd.DataFrame({"x": x, "y": y}) return data
stat_qq_line
python
tensorflow__tensorflow
tensorflow/python/training/experimental/loss_scale_test.py
{ "start": 3765, "end": 12004 }
class ____(test.TestCase, parameterized.TestCase): def _get_tensor(self, is_finite): tensor = cond.cond(is_finite, lambda: 1., lambda: float('NaN')) if not distribute_lib.has_strategy(): return tensor def get(): rep_id = ( distribute_lib.get_replica_context() .replica_id_in_sync_group) return cond.cond( math_ops.equal(rep_id, 0), lambda: tensor, lambda: 1.) distribution = distribute_lib.get_strategy() return distribution.extended.call_for_each_replica(get) def _test_helper(self, inputs, expected_outputs, initial_loss_scale=1., increment_period=2, multiplier=2): loss_scale = loss_scale_module.DynamicLossScale( initial_loss_scale=initial_loss_scale, increment_period=increment_period, multiplier=multiplier) itr = _get_example_iter(inputs) def update(): is_finite = itr.get_next() grad = self._get_tensor(is_finite) update_op, should_apply_gradients = loss_scale.update([grad]) assert_op = check_ops.assert_equal(should_apply_gradients, is_finite) if context.executing_eagerly(): return with ops.control_dependencies([assert_op]): return array_ops.identity(update_op) actual_outputs = [] if not context.executing_eagerly(): update_op = update() self.evaluate(variables.global_variables_initializer()) for _ in range(len(inputs)): if context.executing_eagerly(): update() else: self.evaluate(update_op) actual_outputs.append(self.evaluate(loss_scale())) self.assertEqual(actual_outputs, expected_outputs) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_increase(self, strategy_fn): with strategy_fn().scope(): inputs = [True] * 6 expected_outputs = [1, 2, 2, 4, 4, 8] self._test_helper(inputs, expected_outputs) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_keep_increasing_until_capped(self, strategy_fn): with strategy_fn().scope(): init_loss_scale = np.finfo(np.float32).max / 4 max_float = np.finfo(np.float32).max inputs = [True] * 6 # Output is capped the 2nd time it doubles. expected_outputs = [ init_loss_scale, init_loss_scale * 2, init_loss_scale * 2, max_float, max_float, max_float ] self._test_helper(inputs, expected_outputs, init_loss_scale) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_decrease_every_step(self, strategy_fn): with strategy_fn().scope(): inputs = [False] * 6 init_loss_scale = 1024 expected_outputs = [512, 256, 128, 64, 32, 16] self._test_helper(inputs, expected_outputs, init_loss_scale) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_keep_decreasing_until_one(self, strategy_fn): with strategy_fn().scope(): inputs = [False] * 6 init_loss_scale = 16 expected_outputs = [8, 4, 2, 1, 1, 1] self._test_helper(inputs, expected_outputs, init_loss_scale) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_nan_clear_good_step(self, strategy_fn): with strategy_fn().scope(): inputs = [True, True, True, False, True] expected_outputs = [1, 2, 2, 1, 1] self._test_helper(inputs, expected_outputs) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_trigger_loss_scale_update_each_step(self, strategy_fn): with strategy_fn().scope(): init_loss_scale = 1 increment_period = 1 inputs = [True] * 3 + [False, True, True] expected_outputs = [2, 4, 8, 4, 8, 16] self._test_helper(inputs, expected_outputs, init_loss_scale, increment_period) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_alternating_good_and_bad_gradients_trigger_each_step( self, strategy_fn): with strategy_fn().scope(): init_loss_scale = 1 increment_period = 1 inputs = [True, False] * 4 + [True] expected_outputs = [2, 1, 2, 1, 2, 1, 2, 1, 2] self._test_helper(inputs, expected_outputs, init_loss_scale, increment_period) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_alternating_good_and_bad_gradients_trigger_every_other_step( self, strategy_fn): with strategy_fn().scope(): init_loss_scale = 32 increment_period = 2 inputs = [True, False] * 3 + [True] expected_outputs = [32, 16, 16, 8, 8, 4, 4] self._test_helper(inputs, expected_outputs, init_loss_scale, increment_period) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_nondefault_multiplier(self, strategy_fn): with strategy_fn().scope(): init_loss_scale = 4 multiplier = 3 inputs = [True, True, False, True, True] expected_outputs = [4, 12, 4, 4, 12] self._test_helper( inputs, expected_outputs, init_loss_scale, multiplier=multiplier) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_random_mix_good_and_bad_gradients(self, strategy_fn): with strategy_fn().scope(): init_loss_scale = 4 inputs = [ False, True, True, True, False, True, False, True, True, True, False ] expected_outputs = [2, 2, 4, 4, 2, 2, 1, 1, 2, 2, 1] self._test_helper(inputs, expected_outputs, init_loss_scale) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_single_tensor_gradient(self, strategy_fn): with strategy_fn().scope(): loss_scale = loss_scale_module.DynamicLossScale() grad = constant_op.constant(4.0) _, should_apply = loss_scale.update(grad) self.assertTrue(self.evaluate(should_apply)) @test_util.run_in_graph_and_eager_modes def test_serialization(self): loss_scale = loss_scale_module.DynamicLossScale( initial_loss_scale=1, increment_period=2, multiplier=3) config = loss_scale.get_config() loss_scale = loss_scale_module.DynamicLossScale.from_config(config) self.evaluate(variables.global_variables_initializer()) self.assertEqual(self.evaluate(loss_scale()), 1) self.assertEqual(loss_scale.increment_period, 2) self.assertEqual(loss_scale.multiplier, 3) @test_util.run_in_graph_and_eager_modes def test_update_with_none_gradients(self): loss_scale = loss_scale_module.DynamicLossScale() loss_scale.update([None]) @test_util.run_in_graph_and_eager_modes def test_get(self): scalar = loss_scale_module.get('dynamic') scalar2 = loss_scale_module.DynamicLossScale() self.assertEqual(scalar.initial_loss_scale, scalar2.initial_loss_scale) self.assertEqual(scalar.increment_period, scalar2.increment_period) self.assertEqual(scalar.multiplier, scalar2.multiplier) @test_util.run_in_graph_and_eager_modes def test_call_type(self): scalar = loss_scale_module.DynamicLossScale() self.assertIsInstance(scalar(), tensor_lib.Tensor) @parameterized.named_parameters(*TESTCASES) @test_util.run_in_graph_and_eager_modes def test_repr(self, strategy_fn): with strategy_fn().scope(): loss_scale = loss_scale_module.DynamicLossScale( initial_loss_scale=1, increment_period=2, multiplier=3) if context.executing_eagerly(): self.assertEqual(repr(loss_scale), 'DynamicLossScale(current_loss_scale=1.0, ' 'num_good_steps=0, initial_loss_scale=1.0, ' 'increment_period=2, multiplier=3.0)') else: self.assertEqual(repr(loss_scale), 'DynamicLossScale(initial_loss_scale=1.0, ' 'increment_period=2, multiplier=3.0)') if __name__ == '__main__': test.main()
DynamicLossScaleTest
python
joke2k__faker
faker/factory.py
{ "start": 576, "end": 3939 }
class ____: @classmethod def create( cls, locale: Optional[str] = None, providers: Optional[List[str]] = None, generator: Optional[Generator] = None, includes: Optional[List[str]] = None, # Should we use weightings (more realistic) or weight every element equally (faster)? # By default, use weightings for backwards compatibility & realism use_weighting: bool = True, **config: Any, ) -> Generator: if includes is None: includes = [] # fix locale to package name locale = locale.replace("-", "_") if locale else DEFAULT_LOCALE locale = pylocale.normalize(locale).split(".")[0] if locale not in AVAILABLE_LOCALES: msg = f"Invalid configuration for faker locale `{locale}`" raise AttributeError(msg) config["locale"] = locale config["use_weighting"] = use_weighting providers = providers or PROVIDERS providers += includes faker = generator or Generator(**config) for prov_name in providers: if prov_name == "faker.providers": continue prov_cls, lang_found, _ = cls._find_provider_class(prov_name, locale) provider = prov_cls(faker) provider.__use_weighting__ = use_weighting provider.__provider__ = prov_name provider.__lang__ = lang_found faker.add_provider(provider) return faker @classmethod @functools.lru_cache(maxsize=None) def _find_provider_class( cls, provider_path: str, locale: Optional[str] = None, ) -> Tuple[Any, Optional[str], Optional[str]]: provider_module = import_module(provider_path) default_locale = getattr(provider_module, "default_locale", "") if getattr(provider_module, "localized", False): logger.debug( "Looking for locale `%s` in provider `%s`.", locale, provider_module.__name__, ) available_locales = list_module(provider_module) if not locale or locale not in available_locales: unavailable_locale = locale locale = default_locale or DEFAULT_LOCALE logger.debug( "Specified locale `%s` is not available for " "provider `%s`. Locale reset to `%s` for this " "provider.", unavailable_locale, provider_module.__name__, locale, ) else: logger.debug( "Provider `%s` has been localized to `%s`.", provider_module.__name__, locale, ) path = f"{provider_path}.{locale}" provider_module = import_module(path) else: if locale: logger.debug( "Provider `%s` does not feature localization. " "Specified locale `%s` is not used for this provider.", provider_module.__name__, locale, ) locale = default_locale = None return provider_module.Provider, locale, default_locale # type: ignore
Factory
python
Textualize__textual
src/textual/widget.py
{ "start": 8167, "end": 8300 }
class ____(Exception): """Raised when widget class names do not satisfy the required restrictions.""" @rich.repr.auto
BadWidgetName
python
django__django
tests/many_to_one/models.py
{ "start": 1984, "end": 2091 }
class ____(models.Model): name = models.CharField(primary_key=True, max_length=15)
ParentStringPrimaryKey
python
microsoft__ML-For-Beginners
8-Reinforcement/1-QLearning/rlboard.py
{ "start": 1011, "end": 7234 }
class ____: class Cell: empty = 0 water = 1 wolf = 2 tree = 3 apple = 4 def __init__(self,width,height,size=50): self.width = width self.height = height self.size = size+2 self.matrix = np.zeros((width,height)) self.grid_color = (0.6,0.6,0.6) self.background_color = (1.0,1.0,1.0) self.grid_thickness = 1 self.grid_line_type = cv2.LINE_AA self.pics = { "wolf" : imload('images/wolf.png',size-4), "apple" : imload('images/apple.png',size-4), "human" : imload('images/human.png',size-4) } self.human = (0,0) self.frame_no = 0 def randomize(self,water_size=5, num_water=3, num_wolves=1, num_trees=5, num_apples=3,seed=None): if seed: random.seed(seed) for _ in range(num_water): x = random.randint(0,self.width-1) y = random.randint(0,self.height-1) for _ in range(water_size): self.matrix[x,y] = Board.Cell.water x = clip(0,self.width-1,x+random.randint(-1,1)) y = clip(0,self.height-1,y+random.randint(-1,1)) for _ in range(num_trees): while True: x = random.randint(0,self.width-1) y = random.randint(0,self.height-1) if self.matrix[x,y]==Board.Cell.empty: self.matrix[x,y] = Board.Cell.tree # tree break for _ in range(num_wolves): while True: x = random.randint(0,self.width-1) y = random.randint(0,self.height-1) if self.matrix[x,y]==Board.Cell.empty: self.matrix[x,y] = Board.Cell.wolf # wolf break for _ in range(num_apples): while True: x = random.randint(0,self.width-1) y = random.randint(0,self.height-1) if self.matrix[x,y]==Board.Cell.empty: self.matrix[x,y] = Board.Cell.apple break def at(self,pos=None): if pos: return self.matrix[pos[0],pos[1]] else: return self.matrix[self.human[0],self.human[1]] def is_valid(self,pos): return pos[0]>=0 and pos[0]<self.width and pos[1]>=0 and pos[1] < self.height def move_pos(self, pos, dpos): return (pos[0] + dpos[0], pos[1] + dpos[1]) def move(self,dpos,check_correctness=True): new_pos = self.move_pos(self.human,dpos) if self.is_valid(new_pos) or not check_correctness: self.human = new_pos def random_pos(self): x = random.randint(0,self.width-1) y = random.randint(0,self.height-1) return (x,y) def random_start(self): while True: pos = self.random_pos() if self.at(pos) == Board.Cell.empty: self.human = pos break def image(self,Q=None): img = np.zeros((self.height*self.size+1,self.width*self.size+1,3)) img[:,:,:] = self.background_color # Draw water for x in range(self.width): for y in range(self.height): if (x,y) == self.human: ov = self.pics['human'] img[self.size*y+2:self.size*y+ov.shape[0]+2,self.size*x+2:self.size*x+2+ov.shape[1],:] = np.minimum(ov,1.0) continue if self.matrix[x,y] == Board.Cell.water: img[self.size*y:self.size*(y+1),self.size*x:self.size*(x+1),:] = (0,0,1.0) if self.matrix[x,y] == Board.Cell.wolf: ov = self.pics['wolf'] img[self.size*y+2:self.size*y+ov.shape[0]+2,self.size*x+2:self.size*x+2+ov.shape[1],:] = np.minimum(ov,1.0) if self.matrix[x,y] == Board.Cell.apple: # apple ov = self.pics['apple'] img[self.size*y+2:self.size*y+ov.shape[0]+2,self.size*x+2:self.size*x+2+ov.shape[1],:] = np.minimum(ov,1.0) if self.matrix[x,y] == Board.Cell.tree: # tree img[self.size*y:self.size*(y+1),self.size*x:self.size*(x+1),:] = (0,1.0,0) if self.matrix[x,y] == Board.Cell.empty and Q is not None: p = probs(Q[x,y]) dx,dy = 0,0 for i,(ddx,ddy) in enumerate([(-1,0),(1,0),(0,-1),(0,1)]): dx += ddx*p[i] dy += ddy*p[i] l = draw_line(dx,dy,self.size) img[self.size*y+2:self.size*y+l.shape[0]+2,self.size*x+2:self.size*x+2+l.shape[1],:] = l # Draw grid for i in range(self.height+1): img[:,i*self.size] = 0.3 #cv2.line(img,(0,i*self.size),(self.width*self.size,i*self.size), self.grid_color, self.grid_thickness,lineType=self.grid_line_type) for j in range(self.width+1): img[j*self.size,:] = 0.3 #cv2.line(img,(j*self.size,0),(j*self.size,self.height*self.size), self.grid_color, self.grid_thickness,lineType=self.grid_line_type) return img def plot(self,Q=None): plt.figure(figsize=(11,6)) plt.imshow(self.image(Q),interpolation='hanning') def saveimage(self,filename,Q=None): cv2.imwrite(filename,255*self.image(Q)[...,::-1]) def walk(self,policy,save_to=None,start=None): n = 0 if start: self.human = start else: self.random_start() while True: if save_to: self.saveimage(save_to.format(self.frame_no)) self.frame_no+=1 if self.at() == Board.Cell.apple: return n # success! if self.at() in [Board.Cell.wolf, Board.Cell.water]: return -1 # eaten by wolf or drowned while True: a = policy(self) new_pos = self.move_pos(self.human,a) if self.is_valid(new_pos) and self.at(new_pos)!=Board.Cell.water: self.move(a) # do the actual move break n+=1
Board
python
sphinx-doc__sphinx
sphinx/domains/std/__init__.py
{ "start": 2913, "end": 2994 }
class ____(GenericObject): indextemplate = _('environment variable; %s')
EnvVar
python
coleifer__peewee
tests/regressions.py
{ "start": 34351, "end": 34446 }
class ____(TestModel): data = IntegerField() class Meta: primary_key = False
NoPK
python
joke2k__faker
faker/providers/person/en_US/__init__.py
{ "start": 81, "end": 66194 }
class ____(PersonProvider): formats_female = OrderedDict( ( ("{{first_name_female}} {{last_name}}", 0.97), ("{{prefix_female}} {{first_name_female}} {{last_name}}", 0.015), ("{{first_name_female}} {{last_name}} {{suffix_female}}", 0.02), ( "{{prefix_female}} {{first_name_female}} {{last_name}} {{suffix_female}}", 0.005, ), ) ) formats_nonbinary = OrderedDict( ( ("{{first_name_nonbinary}} {{last_name}}", 0.97), ("{{prefix_nonbinary}} {{first_name_nonbinary}} {{last_name}}", 0.015), ("{{first_name_nonbinary}} {{last_name}} {{suffix_nonbinary}}", 0.02), ( "{{prefix_nonbinary}} {{first_name_nonbinary}} {{last_name}} {{suffix_nonbinary}}", 0.005, ), ) ) formats_male = OrderedDict( ( ("{{first_name_male}} {{last_name}}", 0.97), ("{{prefix_male}} {{first_name_male}} {{last_name}}", 0.015), ("{{first_name_male}} {{last_name}} {{suffix_male}}", 0.02), ( "{{prefix_male}} {{first_name_male}} {{last_name}} {{suffix_male}}", 0.005, ), ) ) # Using random_element's dictionary weighting means that the # formats = formats_male + formats_female # has to be replaced with something dict and python 2.x compatible formats = formats_male.copy() formats.update(formats_female) # Top 200 names of the decade from the 60's-90's from: # https://www.ssa.gov/OACT/babynames/decades/names1960s.html # Weightings derived from total number on each name first_names_female = OrderedDict( ( ("April", 0.004529083), ("Abigail", 0.002043839), ("Adriana", 0.000488767), ("Adrienne", 0.000622931), ("Aimee", 0.000424727), ("Alejandra", 0.000415754), ("Alexa", 0.000663005), ("Alexandra", 0.002835711), ("Alexandria", 0.000964993), ("Alexis", 0.003446735), ("Alice", 0.000589904), ("Alicia", 0.003766845), ("Alisha", 0.000475942), ("Alison", 0.001506047), ("Allison", 0.003740866), ("Alyssa", 0.00324341), ("Amanda", 0.015360768), ("Amber", 0.006928794), ("Amy", 0.012860314), ("Ana", 0.000853679), ("Andrea", 0.006747028), ("Angel", 0.001161117), ("Angela", 0.011954085), ("Angelica", 0.001102746), ("Angie", 0.00030166), ("Anita", 0.001383767), ("Ann", 0.002627483), ("Anna", 0.004691502), ("Anne", 0.002089582), ("Annette", 0.001487399), ("Ariana", 0.000412668), ("Ariel", 0.000615774), ("Ashlee", 0.000696534), ("Ashley", 0.014773009), ("Audrey", 0.001139165), ("Autumn", 0.000918594), ("Bailey", 0.000691916), ("Barbara", 0.004839169), ("Becky", 0.000960944), ("Belinda", 0.000502227), ("Beth", 0.002246113), ("Bethany", 0.001249385), ("Betty", 0.000840241), ("Beverly", 0.000990272), ("Bianca", 0.000624835), ("Bonnie", 0.001351901), ("Brandi", 0.002077216), ("Brandy", 0.002177499), ("Breanna", 0.000876003), ("Brenda", 0.005737124), ("Briana", 0.00093665), ("Brianna", 0.002543549), ("Bridget", 0.000787232), ("Brittany", 0.007258404), ("Brittney", 0.001566147), ("Brooke", 0.002410152), ("Caitlin", 0.001808319), ("Caitlyn", 0.000481194), ("Candace", 0.000550662), ("Candice", 0.000653199), ("Carla", 0.00195185), ("Carly", 0.000498725), ("Carmen", 0.000891783), ("Carol", 0.002972719), ("Caroline", 0.001198127), ("Carolyn", 0.002647225), ("Carrie", 0.002934659), ("Casey", 0.001177707), ("Cassandra", 0.002501243), ("Cassidy", 0.000452129), ("Cassie", 0.000344886), ("Catherine", 0.004460622), ("Cathy", 0.001413248), ("Charlene", 0.000538865), ("Charlotte", 0.000530417), ("Chelsea", 0.00280043), ("Chelsey", 0.000368501), ("Cheryl", 0.004166447), ("Cheyenne", 0.000696907), ("Chloe", 0.000565807), ("Christie", 0.000397873), ("Christina", 0.008735669), ("Christine", 0.007488758), ("Christy", 0.00141861), ("Cindy", 0.003360109), ("Claire", 0.000553835), ("Claudia", 0.00096055), ("Colleen", 0.001836203), ("Connie", 0.001821845), ("Courtney", 0.00484939), ("Cristina", 0.000328734), ("Crystal", 0.006365045), ("Cynthia", 0.007655379), ("Daisy", 0.000437443), ("Dana", 0.003395805), ("Danielle", 0.006671783), ("Darlene", 0.000952737), ("Dawn", 0.005014983), ("Deanna", 0.002049026), ("Debbie", 0.001842922), ("Deborah", 0.005386088), ("Debra", 0.004123572), ("Denise", 0.004592291), ("Desiree", 0.000991497), ("Destiny", 0.001055515), ("Diamond", 0.000331732), ("Diana", 0.003699348), ("Diane", 0.003058996), ("Dominique", 0.000847857), ("Donna", 0.00570819), ("Doris", 0.000398026), ("Dorothy", 0.000722426), ("Ebony", 0.000399624), ("Eileen", 0.000544271), ("Elaine", 0.000601175), ("Elizabeth", 0.014954075), ("Ellen", 0.000747267), ("Emily", 0.009100581), ("Emma", 0.001272059), ("Erica", 0.004344471), ("Erika", 0.002105537), ("Erin", 0.005450719), ("Evelyn", 0.000825095), ("Faith", 0.000427113), ("Felicia", 0.001717294), ("Frances", 0.000546897), ("Gabriela", 0.000526937), ("Gabriella", 0.00044123), ("Gabrielle", 0.001090096), ("Gail", 0.00071934), ("Gina", 0.002841095), ("Glenda", 0.000384982), ("Gloria", 0.001155623), ("Grace", 0.00087202), ("Gwendolyn", 0.000407831), ("Hailey", 0.000662917), ("Haley", 0.001557939), ("Hannah", 0.004189822), ("Hayley", 0.000478305), ("Heather", 0.010945254), ("Heidi", 0.002239941), ("Helen", 0.000636675), ("Holly", 0.003487028), ("Isabel", 0.000352305), ("Isabella", 0.000410282), ("Jackie", 0.000566748), ("Jaclyn", 0.00047708), ("Jacqueline", 0.004811242), ("Jade", 0.000446264), ("Jaime", 0.000853175), ("Jamie", 0.005067663), ("Jane", 0.0009486), ("Janet", 0.002489993), ("Janice", 0.001593308), ("Jasmin", 0.000333374), ("Jasmine", 0.003025422), ("Jean", 0.000815969), ("Jeanette", 0.000767293), ("Jeanne", 0.000515381), ("Jenna", 0.001804052), ("Jennifer", 0.029218839), ("Jenny", 0.000932667), ("Jessica", 0.020047608), ("Jill", 0.003253018), ("Jillian", 0.000988587), ("Jo", 0.000442083), ("Joan", 0.000802793), ("Joann", 0.000544336), ("Joanna", 0.001176284), ("Joanne", 0.000729824), ("Jocelyn", 0.000456878), ("Jodi", 0.001252405), ("Jody", 0.000741861), ("Jordan", 0.001653057), ("Joy", 0.000916515), ("Joyce", 0.001009488), ("Judith", 0.000870706), ("Judy", 0.001101586), ("Julia", 0.003301891), ("Julie", 0.008211731), ("Kaitlin", 0.000674473), ("Kaitlyn", 0.001478623), ("Kara", 0.001549119), ("Karen", 0.009643845), ("Kari", 0.000794323), ("Karina", 0.000494764), ("Karla", 0.000387696), ("Katelyn", 0.001476128), ("Katherine", 0.006581479), ("Kathleen", 0.00503549), ("Kathryn", 0.004177806), ("Kathy", 0.002710214), ("Katie", 0.003056216), ("Katrina", 0.001565446), ("Kayla", 0.004621465), ("Kaylee", 0.000551734), ("Kelli", 0.000932163), ("Kellie", 0.000299187), ("Kelly", 0.009342929), ("Kelsey", 0.002470383), ("Kendra", 0.001401079), ("Kerri", 0.000316215), ("Kerry", 0.000352984), ("Kiara", 0.000390037), ("Kim", 0.002518642), ("Kimberly", 0.015594077), ("Kirsten", 0.000369486), ("Krista", 0.001266872), ("Kristen", 0.004345587), ("Kristi", 0.001022926), ("Kristie", 0.000380189), ("Kristin", 0.003613728), ("Kristina", 0.002316281), ("Kristine", 0.000977709), ("Kristy", 0.001097734), ("Krystal", 0.001238113), ("Kylie", 0.00049739), ("Lacey", 0.00045469), ("Latasha", 0.00032904), ("Latoya", 0.000646371), ("Laura", 0.010815096), ("Lauren", 0.007015421), ("Laurie", 0.002200786), ("Leah", 0.001997571), ("Leslie", 0.003606134), ("Linda", 0.006437751), ("Lindsay", 0.002185466), ("Lindsey", 0.002646153), ("Lisa", 0.01872729), ("Loretta", 0.000482945), ("Lori", 0.006040316), ("Lorraine", 0.000486753), ("Lydia", 0.000370274), ("Lynn", 0.001522308), ("Mackenzie", 0.000761056), ("Madeline", 0.000808921), ("Madison", 0.002011184), ("Makayla", 0.000439391), ("Mallory", 0.000688633), ("Mandy", 0.000355566), ("Marcia", 0.000403213), ("Margaret", 0.003839968), ("Maria", 0.006593123), ("Mariah", 0.00097598), ("Marie", 0.001520229), ("Marilyn", 0.000590889), ("Marisa", 0.000339983), ("Marissa", 0.001582627), ("Martha", 0.001290028), ("Mary", 0.014288466), ("Maureen", 0.000753855), ("Mckenzie", 0.000334512), ("Meagan", 0.000729999), ("Megan", 0.007686786), ("Meghan", 0.001481578), ("Melanie", 0.003400117), ("Melinda", 0.002078113), ("Melissa", 0.014890692), ("Melody", 0.000404264), ("Mercedes", 0.000334643), ("Meredith", 0.000766987), ("Mia", 0.000319935), ("Michaela", 0.000506998), ("Michele", 0.003519551), ("Michelle", 0.01527423), ("Mikayla", 0.000410195), ("Mindy", 0.000306891), ("Miranda", 0.001421193), ("Misty", 0.001564614), ("Molly", 0.001710641), ("Monica", 0.004324095), ("Monique", 0.001272125), ("Morgan", 0.002527025), ("Nancy", 0.005023343), ("Natalie", 0.003658398), ("Natasha", 0.001739815), ("Nichole", 0.001001237), ("Nicole", 0.011156655), ("Nina", 0.000298115), ("Norma", 0.000470754), ("Olivia", 0.001967609), ("Paige", 0.001106313), ("Pam", 0.000374454), ("Pamela", 0.005816222), ("Patricia", 0.008349353), ("Patty", 0.000383493), ("Paula", 0.002478284), ("Peggy", 0.000810606), ("Penny", 0.000836564), ("Phyllis", 0.000562437), ("Priscilla", 0.000350226), ("Rachael", 0.001098128), ("Rachel", 0.00876108), ("Raven", 0.000404855), ("Rebecca", 0.010563161), ("Rebekah", 0.000858581), ("Regina", 0.001941739), ("Renee", 0.00257883), ("Rhonda", 0.002879221), ("Rita", 0.000719187), ("Roberta", 0.000461715), ("Robin", 0.00409199), ("Robyn", 0.00032138), ("Rose", 0.000697125), ("Ruth", 0.001041946), ("Sabrina", 0.001920969), ("Sally", 0.000532912), ("Samantha", 0.008186124), ("Sandra", 0.006473426), ("Sandy", 0.000497106), ("Sara", 0.005619879), ("Sarah", 0.014434273), ("Savannah", 0.000978344), ("Selena", 0.000329106), ("Shannon", 0.005952552), ("Shari", 0.000449043), ("Sharon", 0.004796469), ("Shawna", 0.000354209), ("Sheena", 0.000355763), ("Sheila", 0.00220129), ("Shelby", 0.001575601), ("Shelia", 0.000403673), ("Shelley", 0.000922227), ("Shelly", 0.001339469), ("Sheri", 0.000913166), ("Sherri", 0.001285038), ("Sherry", 0.002445235), ("Sheryl", 0.00057025), ("Shirley", 0.000833259), ("Sierra", 0.000954816), ("Sonia", 0.000332739), ("Sonya", 0.000914085), ("Sophia", 0.000535976), ("Stacey", 0.002836761), ("Stacie", 0.0003903), ("Stacy", 0.00311717), ("Stefanie", 0.00034644), ("Stephanie", 0.013595762), ("Sue", 0.000472877), ("Summer", 0.000411508), ("Susan", 0.0088973), ("Suzanne", 0.001943577), ("Sydney", 0.001220101), ("Sylvia", 0.000625798), ("Tabitha", 0.000428404), ("Tamara", 0.00212948), ("Tami", 0.000403651), ("Tammie", 0.00042337), ("Tammy", 0.006493584), ("Tanya", 0.002039024), ("Tara", 0.00316834), ("Tasha", 0.000355807), ("Taylor", 0.003996871), ("Teresa", 0.005060003), ("Terri", 0.001823903), ("Terry", 0.00060494), ("Theresa", 0.003492762), ("Tiffany", 0.006594283), ("Tina", 0.005186419), ("Toni", 0.000891695), ("Tonya", 0.002404133), ("Tracey", 0.001511146), ("Traci", 0.00086193), ("Tracie", 0.000301901), ("Tracy", 0.00498572), ("Tricia", 0.000449196), ("Valerie", 0.003218022), ("Vanessa", 0.003779189), ("Veronica", 0.003017805), ("Vicki", 0.00088653), ("Vickie", 0.000695199), ("Victoria", 0.005237677), ("Virginia", 0.001496482), ("Wanda", 0.001336186), ("Wendy", 0.004058263), ("Whitney", 0.001690768), ("Yesenia", 0.000331951), ("Yolanda", 0.001213819), ("Yvette", 0.000483427), ("Yvonne", 0.001005483), ("Zoe", 0.000367407), ) ) first_names_male = OrderedDict( ( ("Aaron", 0.006741589), ("Adam", 0.007124922), ("Adrian", 0.001521889), ("Alan", 0.002344657), ("Albert", 0.001316595), ("Alec", 0.000442958), ("Alejandro", 0.000862489), ("Alex", 0.002111833), ("Alexander", 0.005215733), ("Alexis", 0.000277915), ("Alfred", 0.000318919), ("Allen", 0.001679613), ("Alvin", 0.00024794), ("Andre", 0.001400621), ("Andres", 0.000335574), ("Andrew", 0.013475074), ("Angel", 0.000902262), ("Anthony", 0.013783357), ("Antonio", 0.002392535), ("Arthur", 0.001342637), ("Austin", 0.003785615), ("Barry", 0.001102751), ("Benjamin", 0.006535474), ("Bernard", 0.000298691), ("Bill", 0.000430013), ("Billy", 0.001749806), ("Blake", 0.001218155), ("Bob", 0.000235731), ("Bobby", 0.001666977), ("Brad", 0.000984544), ("Bradley", 0.003845018), ("Brady", 0.000277522), ("Brandon", 0.009518346), ("Brendan", 0.000736758), ("Brent", 0.001889131), ("Brett", 0.002248371), ("Brian", 0.01597677), ("Bruce", 0.001883335), ("Bryan", 0.00456454), ("Bryce", 0.000457406), ("Caleb", 0.001485861), ("Calvin", 0.001168738), ("Cameron", 0.00180755), ("Carl", 0.002011802), ("Carlos", 0.00266638), ("Casey", 0.001440035), ("Cesar", 0.000304898), ("Chad", 0.003858817), ("Charles", 0.010889881), ("Chase", 0.000971942), ("Chris", 0.001389507), ("Christian", 0.003097779), ("Christopher", 0.02783596), ("Clarence", 0.000299289), ("Clayton", 0.000662222), ("Clifford", 0.00053078), ("Clinton", 0.000579307), ("Cody", 0.00353482), ("Cole", 0.000578811), ("Colin", 0.00078508), ("Collin", 0.000406057), ("Colton", 0.000520845), ("Connor", 0.000981073), ("Corey", 0.002476612), ("Cory", 0.001813005), ("Craig", 0.00338161), ("Cristian", 0.000333847), ("Curtis", 0.002140235), ("Dakota", 0.000797614), ("Dale", 0.001171354), ("Dalton", 0.000615113), ("Damon", 0.00034308), ("Dan", 0.000388496), ("Daniel", 0.018881874), ("Danny", 0.001873879), ("Darin", 0.000234962), ("Darius", 0.000336189), ("Darrell", 0.001218582), ("Darren", 0.001253738), ("Darryl", 0.00067019), ("Daryl", 0.000260918), ("Dave", 0.000269673), ("David", 0.031073833), ("Dean", 0.000965375), ("Dennis", 0.003318992), ("Derek", 0.003095299), ("Derrick", 0.001955921), ("Devin", 0.001312474), ("Devon", 0.000485877), ("Dillon", 0.000558361), ("Dominic", 0.000438221), ("Don", 0.000378322), ("Donald", 0.005689572), ("Douglas", 0.004513687), ("Drew", 0.000596868), ("Duane", 0.00061855), ("Dustin", 0.003088938), ("Dwayne", 0.000711382), ("Dylan", 0.002329096), ("Earl", 0.000348347), ("Eddie", 0.0007944), ("Edgar", 0.000379536), ("Eduardo", 0.000465358), ("Edward", 0.005702242), ("Edwin", 0.001117833), ("Elijah", 0.000592183), ("Eric", 0.012024659), ("Erik", 0.001997096), ("Ernest", 0.000746556), ("Ethan", 0.001143978), ("Eugene", 0.000784243), ("Evan", 0.001570691), ("Fernando", 0.000557608), ("Francis", 0.000330837), ("Francisco", 0.001084335), ("Frank", 0.003276449), ("Franklin", 0.000237561), ("Fred", 0.000396618), ("Frederick", 0.001104188), ("Gabriel", 0.001906504), ("Garrett", 0.001124861), ("Gary", 0.005023109), ("Gavin", 0.000295373), ("Gene", 0.00023426), ("Geoffrey", 0.000425978), ("George", 0.004423984), ("Gerald", 0.00165841), ("Gilbert", 0.000246726), ("Glen", 0.000374338), ("Glenn", 0.001111421), ("Gordon", 0.00027075), ("Grant", 0.00068322), ("Greg", 0.000623492), ("Gregg", 0.000235885), ("Gregory", 0.007676443), ("Guy", 0.000262645), ("Harold", 0.000929467), ("Harry", 0.000586934), ("Hayden", 0.000279454), ("Hector", 0.000798691), ("Henry", 0.001856232), ("Herbert", 0.000234226), ("Howard", 0.000712921), ("Hunter", 0.001034679), ("Ian", 0.001863192), ("Isaac", 0.001001951), ("Isaiah", 0.000625441), ("Ivan", 0.000350433), ("Jack", 0.001839748), ("Jackson", 0.000403253), ("Jacob", 0.007845384), ("Jaime", 0.000421378), ("Jake", 0.000565782), ("James", 0.029601617), ("Jamie", 0.00093552), ("Jared", 0.002538802), ("Jason", 0.01520513), ("Javier", 0.000625202), ("Jay", 0.001411462), ("Jeff", 0.001271436), ("Jeffery", 0.002627873), ("Jeffrey", 0.01225709), ("Jeremiah", 0.001209605), ("Jeremy", 0.006336079), ("Jermaine", 0.000450156), ("Jerome", 0.000634299), ("Jerry", 0.003150273), ("Jesse", 0.003884552), ("Jesus", 0.001628965), ("Jim", 0.000567714), ("Jimmy", 0.001607489), ("Joe", 0.001621544), ("Joel", 0.002537742), ("John", 0.028683008), ("Johnathan", 0.000840448), ("Johnny", 0.002117065), ("Jon", 0.001561184), ("Jonathan", 0.009963971), ("Jonathon", 0.000701157), ("Jordan", 0.003451546), ("Jorge", 0.001180553), ("Jose", 0.005368207), ("Joseph", 0.018604763), ("Joshua", 0.014808101), ("Juan", 0.003233598), ("Julian", 0.000693736), ("Justin", 0.010197889), ("Karl", 0.000362437), ("Keith", 0.004622866), ("Kelly", 0.000775283), ("Kenneth", 0.008318145), ("Kent", 0.000329418), ("Kerry", 0.000261448), ("Kevin", 0.014324157), ("Kirk", 0.0003801), ("Kristopher", 0.000580692), ("Kurt", 0.000716375), ("Kyle", 0.006350049), ("Lance", 0.001048495), ("Larry", 0.003658807), ("Lawrence", 0.001670294), ("Lee", 0.001223883), ("Leon", 0.000236347), ("Leonard", 0.000756713), ("Leroy", 0.000260234), ("Leslie", 0.000234637), ("Levi", 0.000347184), ("Logan", 0.001325812), ("Lonnie", 0.000258576), ("Louis", 0.001212255), ("Lucas", 0.001098237), ("Luis", 0.002427777), ("Luke", 0.001221455), ("Malik", 0.000306813), ("Manuel", 0.001331369), ("Marc", 0.001431947), ("Marco", 0.000290586), ("Marcus", 0.002604122), ("Mario", 0.001229337), ("Mark", 0.014382277), ("Martin", 0.002085226), ("Marvin", 0.000732962), ("Mason", 0.000562037), ("Mathew", 0.000605555), ("Matthew", 0.020425018), ("Maurice", 0.000777078), ("Max", 0.000311276), ("Maxwell", 0.000357478), ("Melvin", 0.00061932), ("Michael", 0.045602241), ("Micheal", 0.001273847), ("Miguel", 0.001416267), ("Mike", 0.001221797), ("Mitchell", 0.001747788), ("Nathan", 0.005039405), ("Nathaniel", 0.001887558), ("Neil", 0.000240331), ("Nicholas", 0.010021219), ("Nicolas", 0.000362522), ("Noah", 0.000960947), ("Norman", 0.000389043), ("Omar", 0.000639052), ("Oscar", 0.000946583), ("Parker", 0.000277522), ("Patrick", 0.007153255), ("Paul", 0.009272953), ("Pedro", 0.000275726), ("Perry", 0.000258644), ("Peter", 0.004340385), ("Philip", 0.002262956), ("Phillip", 0.00280273), ("Preston", 0.000292022), ("Ralph", 0.000836891), ("Randall", 0.001614722), ("Randy", 0.003021926), ("Ray", 0.000379451), ("Raymond", 0.003493952), ("Reginald", 0.00095108), ("Ricardo", 0.001197276), ("Richard", 0.014131961), ("Rick", 0.000440016), ("Rickey", 0.00023833), ("Ricky", 0.001856882), ("Riley", 0.000322031), ("Robert", 0.026938092), ("Roberto", 0.000906024), ("Rodney", 0.002180555), ("Roger", 0.002038032), ("Ronald", 0.00576775), ("Ronnie", 0.000905938), ("Ross", 0.00026863), ("Roy", 0.001311346), ("Ruben", 0.000774821), ("Russell", 0.002096221), ("Ryan", 0.01128178), ("Samuel", 0.00498019), ("Scott", 0.010580999), ("Sean", 0.005593456), ("Sergio", 0.000568518), ("Seth", 0.001537416), ("Shane", 0.002530218), ("Shannon", 0.000421583), ("Shaun", 0.000748761), ("Shawn", 0.004474546), ("Spencer", 0.000912094), ("Stanley", 0.000739032), ("Stephen", 0.007675365), ("Steve", 0.001407564), ("Steven", 0.013292898), ("Stuart", 0.000238826), ("Tanner", 0.000639292), ("Taylor", 0.00133036), ("Terrance", 0.000203311), ("Terrence", 0.000203704), ("Terry", 0.002873624), ("Theodore", 0.000596561), ("Thomas", 0.0143364), ("Tim", 0.000711126), ("Timothy", 0.012632608), ("Todd", 0.00414612), ("Tom", 0.000499283), ("Tommy", 0.000778737), ("Tony", 0.002511563), ("Tracy", 0.000728259), ("Travis", 0.004022458), ("Trevor", 0.001692523), ("Tristan", 0.000408759), ("Troy", 0.002695415), ("Tyler", 0.005962323), ("Tyrone", 0.000587207), ("Vernon", 0.000246401), ("Victor", 0.002340621), ("Vincent", 0.002494515), ("Walter", 0.001525891), ("Warren", 0.000317414), ("Wayne", 0.00160966), ("Wesley", 0.001733835), ("William", 0.020025989), ("Willie", 0.001379247), ("Wyatt", 0.000306591), ("Xavier", 0.000415222), ("Zachary", 0.005918634), ) ) first_names = first_names_male.copy() first_names.update(first_names_female) first_names_nonbinary = first_names_male.copy() first_names_nonbinary.update(first_names_female) # Top 1000 US surnames from US Census data # Weighted by number of occurrences # By way of http://names.mongabay.com/data/1000.html on 2/10/2016 last_names = OrderedDict( ( ("Smith", 0.021712045), ("Johnson", 0.01696938), ("Williams", 0.014016962), ("Brown", 0.012610763), ("Jones", 0.012451866), ("Miller", 0.010305045), ("Davis", 0.009798219), ("Garcia", 0.007842422), ("Rodriguez", 0.007348561), ("Wilson", 0.007154951), ("Martinez", 0.007082045), ("Anderson", 0.006966203), ("Taylor", 0.006582218), ("Thomas", 0.006493824), ("Hernandez", 0.006454314), ("Moore", 0.006383948), ("Martin", 0.006146745), ("Jackson", 0.006086567), ("Thompson", 0.005887767), ("White", 0.005843424), ("Lopez", 0.005679145), ("Lee", 0.005535909), ("Gonzalez", 0.005461513), ("Harris", 0.005423356), ("Clark", 0.005010598), ("Lewis", 0.00465937), ("Robinson", 0.004596305), ("Walker", 0.004580579), ("Perez", 0.00446375), ("Hall", 0.004327121), ("Young", 0.004257495), ("Allen", 0.00423392), ("Sanchez", 0.004031749), ("Wright", 0.004023754), ("King", 0.004011135), ("Scott", 0.003838487), ("Green", 0.003778053), ("Baker", 0.003776901), ("Adams", 0.00377448), ("Nelson", 0.003766713), ("Hill", 0.003762455), ("Ramirez", 0.003554281), ("Campbell", 0.003398636), ("Mitchell", 0.003357336), ("Roberts", 0.003346207), ("Carter", 0.0033127), ("Phillips", 0.003214932), ("Evans", 0.003127113), ("Turner", 0.003067045), ("Torres", 0.002971158), ("Parker", 0.002962725), ("Collins", 0.002904264), ("Edwards", 0.002897155), ("Stewart", 0.002859044), ("Flores", 0.002856449), ("Morris", 0.002848582), ("Nguyen", 0.002833697), ("Murphy", 0.00274576), ("Rivera", 0.002736275), ("Cook", 0.002693623), ("Rogers", 0.002690041), ("Morgan", 0.002525543), ("Peterson", 0.002513125), ("Cooper", 0.00246795), ("Reed", 0.0024437), ("Bailey", 0.002429747), ("Bell", 0.002419112), ("Gomez", 0.002408494), ("Kelly", 0.002379209), ("Howard", 0.002327986), ("Ward", 0.002321973), ("Cox", 0.002318775), ("Diaz", 0.00230051), ("Richardson", 0.002280051), ("Wood", 0.002259639), ("Watson", 0.002215168), ("Brooks", 0.002199808), ("Bennett", 0.002184311), ("Gray", 0.002162912), ("James", 0.002131032), ("Reyes", 0.002124517), ("Cruz", 0.002111304), ("Hughes", 0.002095999), ("Price", 0.002090206), ("Myers", 0.002054278), ("Long", 0.002042126), ("Foster", 0.002019703), ("Sanders", 0.002018442), ("Ross", 0.002009844), ("Morales", 0.001988655), ("Powell", 0.001978704), ("Sullivan", 0.001970362), ("Russell", 0.001968461), ("Ortiz", 0.001961617), ("Jenkins", 0.001952974), ("Gutierrez", 0.001945371), ("Perry", 0.001942986), ("Butler", 0.001926859), ("Barnes", 0.00192272), ("Fisher", 0.001921377), ("Henderson", 0.001919686), ("Coleman", 0.001906255), ("Simmons", 0.001842531), ("Patterson", 0.00181427), ("Jordan", 0.00180198), ("Reynolds", 0.001787233), ("Hamilton", 0.001775656), ("Graham", 0.001773307), ("Kim", 0.001773243), ("Gonzales", 0.001772028), ("Alexander", 0.001767542), ("Ramos", 0.001764371), ("Wallace", 0.001743026), ("Griffin", 0.001741893), ("West", 0.001722047), ("Cole", 0.001715916), ("Hayes", 0.001712992), ("Chavez", 0.001698299), ("Gibson", 0.001685096), ("Bryant", 0.001679075), ("Ellis", 0.001662381), ("Stevens", 0.001657657), ("Murray", 0.001630218), ("Ford", 0.001630062), ("Marshall", 0.001619244), ("Owens", 0.001611212), ("Mcdonald", 0.001609019), ("Harrison", 0.001604295), ("Ruiz", 0.001602943), ("Kennedy", 0.001568285), ("Wells", 0.001559139), ("Alvarez", 0.001542527), ("Woods", 0.0015425), ("Mendoza", 0.001540243), ("Castillo", 0.001511972), ("Olson", 0.001493963), ("Webb", 0.001493771), ("Washington", 0.001489705), ("Tucker", 0.001488763), ("Freeman", 0.001486507), ("Burns", 0.001481636), ("Henry", 0.001474683), ("Vasquez", 0.001461863), ("Snyder", 0.001456143), ("Simpson", 0.001445891), ("Crawford", 0.001444795), ("Jimenez", 0.001438892), ("Porter", 0.001433163), ("Mason", 0.0014207), ("Shaw", 0.001417849), ("Gordon", 0.001415674), ("Wagner", 0.001411855), ("Hunter", 0.001410886), ("Romero", 0.001405057), ("Hicks", 0.00140365), ("Dixon", 0.001389003), ("Hunt", 0.001388738), ("Palmer", 0.00137431), ("Robertson", 0.001373323), ("Black", 0.001372291), ("Holmes", 0.001372108), ("Stone", 0.001368782), ("Meyer", 0.001367521), ("Boyd", 0.001365803), ("Mills", 0.001351485), ("Warren", 0.001351458), ("Fox", 0.001346441), ("Rose", 0.001342485), ("Rice", 0.001338062), ("Moreno", 0.001334846), ("Schmidt", 0.001330067), ("Patel", 0.001325508), ("Ferguson", 0.001299832), ("Nichols", 0.001296908), ("Herrera", 0.0012864), ("Medina", 0.001273307), ("Ryan", 0.001273142), ("Fernandez", 0.001272841), ("Weaver", 0.001268354), ("Daniels", 0.001268034), ("Stephens", 0.001267724), ("Gardner", 0.001266974), ("Payne", 0.0012612), ("Kelley", 0.001256878), ("Dunn", 0.001251395), ("Pierce", 0.001247393), ("Arnold", 0.001245547), ("Tran", 0.001243537), ("Spencer", 0.001228443), ("Peters", 0.001226505), ("Hawkins", 0.001224998), ("Grant", 0.001224705), ("Hansen", 0.001219589), ("Castro", 0.001217578), ("Hoffman", 0.001212014), ("Hart", 0.001210378), ("Elliott", 0.001210296), ("Cunningham", 0.00120517), ("Knight", 0.001204841), ("Bradley", 0.001199624), ("Carroll", 0.001197166), ("Hudson", 0.001195091), ("Duncan", 0.001191674), ("Armstrong", 0.001187681), ("Berry", 0.001182409), ("Andrews", 0.001181632), ("Johnston", 0.001178114), ("Ray", 0.001176826), ("Lane", 0.001176214), ("Riley", 0.001169206), ("Carpenter", 0.001161101), ("Perkins", 0.001159986), ("Aguilar", 0.001154942), ("Silva", 0.001152795), ("Richards", 0.001148126), ("Willis", 0.001147888), ("Matthews", 0.001140688), ("Chapman", 0.001138632), ("Lawrence", 0.001135955), ("Garza", 0.00113421), ("Vargas", 0.001132583), ("Watkins", 0.001118832), ("Wheeler", 0.00111186), ("Larson", 0.001106195), ("Carlson", 0.001097606), ("Harper", 0.001095267), ("George", 0.001094444), ("Greene", 0.001092855), ("Burke", 0.001088935), ("Guzman", 0.001081762), ("Morrison", 0.001077641), ("Munoz", 0.001076133), ("Jacobs", 0.001055721), ("Obrien", 0.001054304), ("Lawson", 0.001052486), ("Franklin", 0.001049498), ("Lynch", 0.001045743), ("Bishop", 0.00104196), ("Carr", 0.001040662), ("Salazar", 0.001036788), ("Austin", 0.001033974), ("Mendez", 0.0010301), ("Gilbert", 0.001027084), ("Jensen", 0.001026408), ("Williamson", 0.001025348), ("Montgomery", 0.00102469), ("Harvey", 0.001024617), ("Oliver", 0.001020094), ("Howell", 0.001001756), ("Dean", 0.000998064), ("Hanson", 0.000996685), ("Weber", 0.000985601), ("Garrett", 0.000984788), ("Sims", 0.000979918), ("Burton", 0.000979132), ("Fuller", 0.000974783), ("Soto", 0.000974317), ("Mccoy", 0.000972946), ("Welch", 0.00096676), ("Chen", 0.000964384), ("Schultz", 0.000959067), ("Walters", 0.000952844), ("Reid", 0.00095034), ("Fields", 0.00094335), ("Walsh", 0.000943113), ("Little", 0.000938563), ("Fowler", 0.000937667), ("Bowman", 0.000934186), ("Davidson", 0.000932404), ("May", 0.000929498), ("Day", 0.000929041), ("Schneider", 0.00091878), ("Newman", 0.000918214), ("Brewer", 0.000917976), ("Lucas", 0.000917538), ("Holland", 0.000912677), ("Wong", 0.000908172), ("Banks", 0.000907276), ("Santos", 0.000904526), ("Curtis", 0.000904206), ("Pearson", 0.000902105), ("Delgado", 0.000901621), ("Valdez", 0.000901027), ("Pena", 0.000898605), ("Rios", 0.000882377), ("Douglas", 0.000881062), ("Sandoval", 0.000879947), ("Barrett", 0.000876228), ("Hopkins", 0.000864414), ("Keller", 0.000861645), ("Guerrero", 0.000860293), ("Stanley", 0.000857232), ("Bates", 0.000856555), ("Alvarado", 0.000856373), ("Beck", 0.000851238), ("Ortega", 0.000850963), ("Wade", 0.00084825), ("Estrada", 0.000848222), ("Contreras", 0.00084666), ("Barnett", 0.000843252), ("Caldwell", 0.00083458), ("Santiago", 0.00083119), ("Lambert", 0.000828001), ("Powers", 0.000826019), ("Chambers", 0.000825324), ("Nunez", 0.000824255), ("Craig", 0.000818618), ("Leonard", 0.000815027), ("Lowe", 0.000814844), ("Rhodes", 0.000812459), ("Byrd", 0.00081149), ("Gregory", 0.000811481), ("Shelton", 0.000807059), ("Frazier", 0.00080705), ("Becker", 0.000805122), ("Maldonado", 0.000804226), ("Fleming", 0.000803614), ("Vega", 0.000801595), ("Sutton", 0.000798351), ("Cohen", 0.000797008), ("Jennings", 0.00079529), ("Parks", 0.000788967), ("Mcdaniel", 0.000788702), ("Watts", 0.000787889), ("Barker", 0.000778688), ("Norris", 0.000778605), ("Vaughn", 0.000777006), ("Vazquez", 0.000775992), ("Holt", 0.000774018), ("Schwartz", 0.000773918), ("Steele", 0.000770756), ("Benson", 0.00076966), ("Neal", 0.000766151), ("Dominguez", 0.000765073), ("Horton", 0.000763173), ("Terry", 0.000762387), ("Wolfe", 0.000759417), ("Hale", 0.000757983), ("Lyons", 0.000751614), ("Graves", 0.000750892), ("Haynes", 0.000749595), ("Miles", 0.000748644), ("Park", 0.000748251), ("Warner", 0.000747648), ("Padilla", 0.000747475), ("Bush", 0.000744907), ("Thornton", 0.000741864), ("Mccarthy", 0.000740439), ("Mann", 0.00074032), ("Zimmerman", 0.000739608), ("Erickson", 0.000739534), ("Fletcher", 0.000739498), ("Mckinney", 0.00073661), ("Page", 0.000735487), ("Dawson", 0.000732718), ("Joseph", 0.000731256), ("Marquez", 0.000730534), ("Reeves", 0.00072931), ("Klein", 0.000728104), ("Espinoza", 0.000724787), ("Baldwin", 0.000723224), ("Moran", 0.000717696), ("Love", 0.000715659), ("Robbins", 0.000713996), ("Higgins", 0.000713685), ("Ball", 0.000708696), ("Cortez", 0.000708066), ("Le", 0.000707709), ("Griffith", 0.00070749), ("Bowen", 0.000704283), ("Sharp", 0.000702364), ("Cummings", 0.000700893), ("Ramsey", 0.000700144), ("Hardy", 0.000699988), ("Swanson", 0.000699358), ("Barber", 0.000699038), ("Acosta", 0.000698791), ("Luna", 0.000695593), ("Chandler", 0.000695474), ("Daniel", 0.000686529), ("Blair", 0.000686529), ("Cross", 0.00068652), ("Simon", 0.000683824), ("Dennis", 0.000683322), ("Oconnor", 0.000683066), ("Quinn", 0.00068101), ("Gross", 0.000678762), ("Navarro", 0.000675884), ("Moss", 0.000673874), ("Fitzgerald", 0.000671791), ("Doyle", 0.000671754), ("Mclaughlin", 0.000668191), ("Rojas", 0.00066767), ("Rodgers", 0.000667213), ("Stevenson", 0.000666034), ("Singh", 0.00066375), ("Yang", 0.000663613), ("Figueroa", 0.000662754), ("Harmon", 0.000661667), ("Newton", 0.000660881), ("Paul", 0.00066015), ("Manning", 0.000658514), ("Garner", 0.000658359), ("Mcgee", 0.000657198), ("Reese", 0.000655636), ("Francis", 0.000655353), ("Burgess", 0.000654265), ("Adkins", 0.000653571), ("Goodman", 0.000653151), ("Curry", 0.00065189), ("Brady", 0.000650345), ("Christensen", 0.000650062), ("Potter", 0.000649688), ("Walton", 0.000648719), ("Goodwin", 0.000642652), ("Mullins", 0.000642222), ("Molina", 0.000641537), ("Webster", 0.000640733), ("Fischer", 0.000640477), ("Campos", 0.000639152), ("Avila", 0.000638175), ("Sherman", 0.000638147), ("Todd", 0.000637873), ("Chang", 0.00063738), ("Blake", 0.000633021), ("Malone", 0.00063282), ("Wolf", 0.000629604), ("Hodges", 0.000629266), ("Juarez", 0.000628507), ("Gill", 0.000627722), ("Farmer", 0.000624158), ("Hines", 0.00062266), ("Gallagher", 0.00062202), ("Duran", 0.000621755), ("Hubbard", 0.000621527), ("Cannon", 0.000620631), ("Miranda", 0.0006181), ("Wang", 0.000617406), ("Saunders", 0.000614116), ("Tate", 0.000614098), ("Mack", 0.000613604), ("Hammond", 0.000612773), ("Carrillo", 0.000612691), ("Townsend", 0.000610854), ("Wise", 0.000609803), ("Ingram", 0.000609136), ("Barton", 0.000608743), ("Mejia", 0.000607939), ("Ayala", 0.000607766), ("Schroeder", 0.000606825), ("Hampton", 0.000606514), ("Rowe", 0.000604933), ("Parsons", 0.000604915), ("Frank", 0.000602311), ("Waters", 0.000601388), ("Strickland", 0.000601361), ("Osborne", 0.000601251), ("Maxwell", 0.000601041), ("Chan", 0.000600493), ("Deleon", 0.000599387), ("Norman", 0.000596381), ("Harrington", 0.00059512), ("Casey", 0.000592232), ("Patton", 0.00059184), ("Logan", 0.000590049), ("Bowers", 0.000589318), ("Mueller", 0.000587572), ("Glover", 0.00058643), ("Floyd", 0.000586074), ("Hartman", 0.000583205), ("Buchanan", 0.000583187), ("Cobb", 0.000582401), ("French", 0.00057701), ("Kramer", 0.000575858), ("Mccormick", 0.000572569), ("Clarke", 0.0005715), ("Tyler", 0.00057139), ("Gibbs", 0.000571208), ("Moody", 0.000569654), ("Conner", 0.000569572), ("Sparks", 0.000568649), ("Mcguire", 0.000567571), ("Leon", 0.000566822), ("Bauer", 0.000566319), ("Norton", 0.000564729), ("Pope", 0.000564227), ("Flynn", 0.000564199), ("Hogan", 0.000563322), ("Robles", 0.00056303), ("Salinas", 0.000562692), ("Yates", 0.000561029), ("Lindsey", 0.000559192), ("Lloyd", 0.000558781), ("Marsh", 0.000557365), ("Mcbride", 0.000556222), ("Owen", 0.000552449), ("Solis", 0.000548648), ("Pham", 0.00054777), ("Lang", 0.000546802), ("Pratt", 0.000546418), ("Lara", 0.000545779), ("Brock", 0.000545331), ("Ballard", 0.00054513), ("Trujillo", 0.000544664), ("Shaffer", 0.000541173), ("Drake", 0.000539602), ("Roman", 0.000539282), ("Aguirre", 0.00053835), ("Morton", 0.000537162), ("Stokes", 0.000536239), ("Lamb", 0.000535033), ("Pacheco", 0.000534841), ("Patrick", 0.00053231), ("Cochran", 0.000532091), ("Shepherd", 0.000529368), ("Cain", 0.000528801), ("Burnett", 0.000528674), ("Hess", 0.000528335), ("Li", 0.000528007), ("Cervantes", 0.000527084), ("Olsen", 0.000524087), ("Briggs", 0.000523538), ("Ochoa", 0.000522743), ("Cabrera", 0.000522387), ("Velasquez", 0.000522314), ("Montoya", 0.00052151), ("Roth", 0.000521099), ("Meyers", 0.000518485), ("Cardenas", 0.000517334), ("Fuentes", 0.000515717), ("Weiss", 0.000513085), ("Wilkins", 0.000512309), ("Hoover", 0.000512309), ("Nicholson", 0.000511559), ("Underwood", 0.000511441), ("Short", 0.000510801), ("Carson", 0.000510052), ("Morrow", 0.000508617), ("Colon", 0.000507228), ("Holloway", 0.000506808), ("Summers", 0.000506123), ("Bryan", 0.000505008), ("Petersen", 0.00050424), ("Mckenzie", 0.000503318), ("Serrano", 0.000503071), ("Wilcox", 0.000502431), ("Carey", 0.000501856), ("Clayton", 0.000501408), ("Poole", 0.000499864), ("Calderon", 0.000499727), ("Gallegos", 0.000499553), ("Greer", 0.000498996), ("Rivas", 0.000498786), ("Guerra", 0.000498667), ("Decker", 0.000497525), ("Collier", 0.000497196), ("Wall", 0.000497077), ("Whitaker", 0.000496547), ("Bass", 0.000496117), ("Flowers", 0.000495944), ("Davenport", 0.000495295), ("Conley", 0.000495185), ("Houston", 0.00049365), ("Huff", 0.000492426), ("Copeland", 0.00049132), ("Hood", 0.00049101), ("Monroe", 0.000488616), ("Massey", 0.00048847), ("Roberson", 0.000486085), ("Combs", 0.00048592), ("Franco", 0.000485747), ("Larsen", 0.000483937), ("Pittman", 0.000481434), ("Randall", 0.000479661), ("Skinner", 0.000479616), ("Wilkinson", 0.000479552), ("Kirby", 0.00047946), ("Cameron", 0.00047915), ("Bridges", 0.000477514), ("Anthony", 0.000476472), ("Richard", 0.000476399), ("Kirk", 0.00047565), ("Bruce", 0.000475175), ("Singleton", 0.000473283), ("Mathis", 0.000473274), ("Bradford", 0.000472635), ("Boone", 0.000472205), ("Abbott", 0.000471666), ("Charles", 0.000470734), ("Allison", 0.000470606), ("Sweeney", 0.00047057), ("Atkinson", 0.000470469), ("Horn", 0.000469473), ("Jefferson", 0.0004693), ("Rosales", 0.000469071), ("York", 0.000469053), ("Christian", 0.000467618), ("Phelps", 0.000467408), ("Farrell", 0.000466869), ("Castaneda", 0.000466814), ("Nash", 0.000466193), ("Dickerson", 0.000466156), ("Bond", 0.000465818), ("Wyatt", 0.00046485), ("Foley", 0.000464649), ("Chase", 0.000463963), ("Gates", 0.000463698), ("Vincent", 0.000462602), ("Mathews", 0.000462419), ("Hodge", 0.000462136), ("Garrison", 0.000461268), ("Trevino", 0.000461012), ("Villarreal", 0.000460071), ("Heath", 0.000459669), ("Dalton", 0.00045838), ("Valencia", 0.000457101), ("Callahan", 0.000456178), ("Hensley", 0.000455566), ("Atkins", 0.000454616), ("Huffman", 0.000454461), ("Roy", 0.000454351), ("Boyer", 0.000453218), ("Shields", 0.000452807), ("Lin", 0.000451016), ("Hancock", 0.000450742), ("Grimes", 0.000449965), ("Glenn", 0.000449929), ("Cline", 0.000449252), ("Delacruz", 0.00044917), ("Camacho", 0.000447726), ("Dillon", 0.0004462), ("Parrish", 0.000446109), ("Oneill", 0.000444583), ("Melton", 0.000444017), ("Booth", 0.000443889), ("Kane", 0.000443404), ("Berg", 0.000442975), ("Harrell", 0.000442893), ("Pitts", 0.000442811), ("Savage", 0.000441943), ("Wiggins", 0.000441833), ("Brennan", 0.000441294), ("Salas", 0.000441166), ("Marks", 0.000441157), ("Russo", 0.00043974), ("Sawyer", 0.000438397), ("Baxter", 0.000437283), ("Golden", 0.000437118), ("Hutchinson", 0.000436844), ("Liu", 0.000435528), ("Walter", 0.000435071), ("Mcdowell", 0.000434258), ("Wiley", 0.000434048), ("Rich", 0.00043381), ("Humphrey", 0.000433746), ("Johns", 0.000432093), ("Koch", 0.000432065), ("Suarez", 0.000431599), ("Hobbs", 0.000431462), ("Beard", 0.000430621), ("Gilmore", 0.000429909), ("Ibarra", 0.000428492), ("Keith", 0.00042714), ("Macias", 0.000427067), ("Khan", 0.000426829), ("Andrade", 0.000426729), ("Ware", 0.000426546), ("Stephenson", 0.000426363), ("Henson", 0.000425879), ("Wilkerson", 0.000425843), ("Dyer", 0.000425559), ("Mcclure", 0.000424929), ("Blackwell", 0.000424838), ("Mercado", 0.000424308), ("Tanner", 0.000424079), ("Eaton", 0.000423997), ("Clay", 0.000422727), ("Barron", 0.000422106), ("Beasley", 0.00042195), ("Oneal", 0.000421786), ("Small", 0.000418944), ("Preston", 0.000418944), ("Wu", 0.000418624), ("Zamora", 0.000418542), ("Macdonald", 0.000418323), ("Vance", 0.000418149), ("Snow", 0.000417473), ("Mcclain", 0.000416294), ("Stafford", 0.000414366), ("Orozco", 0.000413818), ("Barry", 0.000411579), ("English", 0.00041147), ("Shannon", 0.000410282), ("Kline", 0.000410264), ("Jacobson", 0.000410026), ("Woodard", 0.000409624), ("Huang", 0.000408573), ("Kemp", 0.000408445), ("Mosley", 0.000408418), ("Prince", 0.000407888), ("Merritt", 0.00040776), ("Hurst", 0.000407404), ("Villanueva", 0.000407248), ("Roach", 0.000406188), ("Nolan", 0.000405887), ("Lam", 0.000405558), ("Yoder", 0.000404279), ("Mccullough", 0.000403164), ("Lester", 0.0004013), ("Santana", 0.000400898), ("Valenzuela", 0.000399938), ("Winters", 0.000399865), ("Barrera", 0.000399482), ("Orr", 0.000398988), ("Leach", 0.000398988), ("Berger", 0.000397983), ("Mckee", 0.000397974), ("Strong", 0.000396832), ("Conway", 0.000396512), ("Stein", 0.000395927), ("Whitehead", 0.000395735), ("Bullock", 0.000393095), ("Escobar", 0.000392492), ("Knox", 0.000392327), ("Meadows", 0.000391843), ("Solomon", 0.000391432), ("Velez", 0.000391258), ("Odonnell", 0.000391094), ("Kerr", 0.000390692), ("Stout", 0.000389878), ("Blankenship", 0.000389824), ("Browning", 0.000389632), ("Kent", 0.00038922), ("Lozano", 0.000388946), ("Bartlett", 0.000388444), ("Pruitt", 0.000387996), ("Buck", 0.000387795), ("Barr", 0.000387713), ("Gaines", 0.000387137), ("Durham", 0.000387101), ("Gentry", 0.000387028), ("Mcintyre", 0.000386826), ("Sloan", 0.000386333), ("Rocha", 0.000385036), ("Melendez", 0.000385036), ("Herman", 0.000384597), ("Sexton", 0.000384496), ("Moon", 0.000384332), ("Hendricks", 0.00038266), ("Rangel", 0.000382559), ("Stark", 0.000382514), ("Lowery", 0.00038075), ("Hardin", 0.000380695), ("Hull", 0.000380622), ("Sellers", 0.000379754), ("Ellison", 0.000378822), ("Calhoun", 0.000378758), ("Gillespie", 0.000378219), ("Mora", 0.000377808), ("Knapp", 0.000377068), ("Mccall", 0.000376739), ("Morse", 0.000375652), ("Dorsey", 0.000375579), ("Weeks", 0.000375113), ("Nielsen", 0.000374692), ("Livingston", 0.000374299), ("Leblanc", 0.000373925), ("Mclean", 0.00037345), ("Bradshaw", 0.000372746), ("Glass", 0.000372106), ("Middleton", 0.00037196), ("Buckley", 0.000371942), ("Schaefer", 0.000371549), ("Frost", 0.000370809), ("Howe", 0.000370562), ("House", 0.000369849), ("Mcintosh", 0.00036963), ("Ho", 0.000369265), ("Pennington", 0.000368588), ("Reilly", 0.000368324), ("Hebert", 0.000368077), ("Mcfarland", 0.00036772), ("Hickman", 0.000367538), ("Noble", 0.000367474), ("Spears", 0.000367346), ("Conrad", 0.000366423), ("Arias", 0.000366277), ("Galvan", 0.000365911), ("Velazquez", 0.000365765), ("Huynh", 0.000365591), ("Frederick", 0.000364659), ("Randolph", 0.000363134), ("Cantu", 0.000361845), ("Fitzpatrick", 0.000360931), ("Mahoney", 0.000360374), ("Peck", 0.000360301), ("Villa", 0.000360027), ("Michael", 0.000359725), ("Donovan", 0.000358821), ("Mcconnell", 0.000358209), ("Walls", 0.00035787), ("Boyle", 0.000357642), ("Mayer", 0.000357368), ("Zuniga", 0.000356875), ("Giles", 0.000356372), ("Pineda", 0.000356345), ("Pace", 0.000356125), ("Hurley", 0.000356089), ("Mays", 0.000355568), ("Mcmillan", 0.000355403), ("Crosby", 0.000354928), ("Ayers", 0.000354855), ("Case", 0.000354152), ("Bentley", 0.00035374), ("Shepard", 0.000353658), ("Everett", 0.000353631), ("Pugh", 0.00035353), ("David", 0.000353238), ("Mcmahon", 0.000352306), ("Dunlap", 0.000351931), ("Bender", 0.000351456), ("Hahn", 0.000350451), ("Harding", 0.000350323), ("Acevedo", 0.000349336), ("Raymond", 0.00034866), ("Blackburn", 0.000348468), ("Duffy", 0.000346869), ("Landry", 0.00034686), ("Dougherty", 0.00034633), ("Bautista", 0.000345818), ("Shah", 0.00034569), ("Potts", 0.000344356), ("Arroyo", 0.000344274), ("Valentine", 0.000344192), ("Meza", 0.000344128), ("Gould", 0.00034411), ("Vaughan", 0.000343479), ("Fry", 0.000343032), ("Rush", 0.000342374), ("Avery", 0.0003421), ("Herring", 0.000341305), ("Dodson", 0.000340802), ("Clements", 0.000340245), ("Sampson", 0.000340217), ("Tapia", 0.000339916), ("Bean", 0.000339404), ("Lynn", 0.000339221), ("Crane", 0.000339203), ("Farley", 0.000339139), ("Cisneros", 0.000338536), ("Benton", 0.000338372), ("Ashley", 0.000338271), ("Mckay", 0.000337604), ("Finley", 0.000336928), ("Best", 0.000336818), ("Blevins", 0.000336626), ("Friedman", 0.000336553), ("Moses", 0.00033638), ("Sosa", 0.00033637), ("Blanchard", 0.000335923), ("Huber", 0.000335603), ("Frye", 0.000335484), ("Krueger", 0.000335283), ("Bernard", 0.000333931), ("Rosario", 0.000333867), ("Rubio", 0.000333794), ("Mullen", 0.000332981), ("Benjamin", 0.000332953), ("Haley", 0.000332898), ("Chung", 0.000332798), ("Moyer", 0.000332789), ("Choi", 0.000332505), ("Horne", 0.000331573), ("Yu", 0.000331546), ("Woodward", 0.000331153), ("Ali", 0.000329664), ("Nixon", 0.00032928), ("Hayden", 0.000329161), ("Rivers", 0.000328759), ("Estes", 0.000327471), ("Mccarty", 0.000326365), ("Richmond", 0.000326338), ("Stuart", 0.00032621), ("Maynard", 0.000325726), ("Brandt", 0.000325433), ("Oconnell", 0.000325378), ("Hanna", 0.000325278), ("Sanford", 0.000324967), ("Sheppard", 0.000324867), ("Church", 0.00032473), ("Burch", 0.000324565), ("Levy", 0.000324044), ("Rasmussen", 0.000323944), ("Coffey", 0.000323843), ("Ponce", 0.000323459), ("Faulkner", 0.000323359), ("Donaldson", 0.000323341), ("Schmitt", 0.000322783), ("Novak", 0.000322381), ("Costa", 0.000321879), ("Montes", 0.000321595), ("Booker", 0.000320727), ("Cordova", 0.000320481), ("Waller", 0.000319814), ("Arellano", 0.000319795), ("Maddox", 0.00031953), ("Mata", 0.000318781), ("Bonilla", 0.000318196), ("Stanton", 0.000318087), ("Compton", 0.000317867), ("Kaufman", 0.000317849), ("Dudley", 0.000317703), ("Mcpherson", 0.000317639), ("Beltran", 0.000317392), ("Dickson", 0.000317045), ("Mccann", 0.00031699), ("Villegas", 0.000316917), ("Proctor", 0.000316899), ("Hester", 0.000316835), ("Cantrell", 0.000316826), ("Daugherty", 0.000316607), ("Cherry", 0.000316287), ("Bray", 0.000315921), ("Davila", 0.000315611), ("Rowland", 0.000315218), ("Madden", 0.00031498), ("Levine", 0.00031498), ("Spence", 0.000314642), ("Good", 0.000314596), ("Irwin", 0.000314085), ("Werner", 0.000313884), ("Krause", 0.00031382), ("Petty", 0.000313207), ("Whitney", 0.000312961), ("Baird", 0.000312796), ("Hooper", 0.000311435), ("Pollard", 0.000311389), ("Zavala", 0.000311289), ("Jarvis", 0.000311124), ("Holden", 0.000311042), ("Hendrix", 0.00031096), ("Haas", 0.00031096), ("Mcgrath", 0.000310951), ("Bird", 0.00031032), ("Lucero", 0.000309955), ("Terrell", 0.000309882), ("Riggs", 0.000309461), ("Joyce", 0.000309233), ("Rollins", 0.000308812), ("Mercer", 0.000308812), ("Galloway", 0.000308593), ("Duke", 0.000308337), ("Odom", 0.000308081), ("Andersen", 0.000306172), ("Downs", 0.000306044), ("Hatfield", 0.00030577), ("Benitez", 0.00030556), ("Archer", 0.000305285), ("Huerta", 0.00030471), ("Travis", 0.000304628), ("Mcneil", 0.000303714), ("Hinton", 0.00030344), ("Zhang", 0.000303376), ("Hays", 0.000303303), ("Mayo", 0.000302681), ("Fritz", 0.000302151), ("Branch", 0.000301896), ("Mooney", 0.000301101), ("Ewing", 0.000300845), ("Ritter", 0.000300287), ("Esparza", 0.000299447), ("Frey", 0.000299109), ("Braun", 0.00029857), ("Gay", 0.000298533), ("Riddle", 0.000298369), ("Haney", 0.000298277), ("Kaiser", 0.000297574), ("Holder", 0.000296651), ("Chaney", 0.000296349), ("Mcknight", 0.00029592), ("Gamble", 0.000295838), ("Vang", 0.000295435), ("Cooley", 0.000295015), ("Carney", 0.000294969), ("Cowan", 0.000294604), ("Forbes", 0.000294476), ("Ferrell", 0.000293983), ("Davies", 0.0002939), ("Barajas", 0.000293736), ("Shea", 0.000293023), ("Osborn", 0.000292795), ("Bright", 0.000292777), ("Cuevas", 0.00029253), ("Bolton", 0.000292347), ("Murillo", 0.000292064), ("Lutz", 0.000291845), ("Duarte", 0.000291442), ("Kidd", 0.000291351), ("Key", 0.000291315), ("Cooke", 0.000291114), ) ) prefixes_female = OrderedDict( ( ("Mrs.", 0.5), ("Ms.", 0.1), ("Miss", 0.1), ("Dr.", 0.3), ) ) prefixes_male = OrderedDict( ( ("Mr.", 0.7), ("Dr.", 0.3), ) ) # https://en.wikipedia.org/wiki/Gender-neutral_title prefixes_nonbinary = OrderedDict( ( ("Mx.", 0.5), ("Ind.", 0.1), ("Misc.", 0.1), ("Dr.", 0.3), ) ) suffixes_female = OrderedDict( ( ("MD", 0.5), ("DDS", 0.3), ("PhD", 0.1), ("DVM", 0.2), ) ) # Removed Sr and I as they'd almost never be part of legal names. suffixes_male = OrderedDict( ( ("Jr.", 0.2), ("II", 0.05), ("III", 0.03), ("IV", 0.015), ("V", 0.005), ("MD", 0.3), ("DDS", 0.2), ("PhD", 0.1), ("DVM", 0.1), ) ) suffixes_nonbinary = suffixes_male.copy()
Provider
python
pyqtgraph__pyqtgraph
pyqtgraph/widgets/VerticalLabel.py
{ "start": 702, "end": 3009 }
class ____(QtWidgets.QLabel): def __init__(self, text, orientation='vertical', forceWidth=True): QtWidgets.QLabel.__init__(self, text) self.forceWidth = forceWidth self.orientation = None self.setOrientation(orientation) def setOrientation(self, o): if self.orientation == o: return self.orientation = o self.update() self.updateGeometry() def paintEvent(self, ev): p = QtGui.QPainter(self) #p.setBrush(QtGui.QBrush(QtGui.QColor(100, 100, 200))) #p.setPen(QtGui.QPen(QtGui.QColor(50, 50, 100))) #p.drawRect(self.rect().adjusted(0, 0, -1, -1)) #p.setPen(QtGui.QPen(QtGui.QColor(255, 255, 255))) if self.orientation == 'vertical': p.rotate(-90) rgn = QtCore.QRect(-self.height(), 0, self.height(), self.width()) else: rgn = self.contentsRect() align = self.alignment() #align = QtCore.Qt.AlignmentFlag.AlignTop|QtCore.Qt.AlignmentFlag.AlignHCenter with warnings.catch_warnings(): warnings.simplefilter("ignore") self.hint = p.drawText(rgn, align, self.text()) p.end() if self.orientation == 'vertical': self.setMaximumWidth(self.hint.height()) self.setMinimumWidth(0) self.setMaximumHeight(16777215) if self.forceWidth: self.setMinimumHeight(self.hint.width()) else: self.setMinimumHeight(0) else: self.setMaximumHeight(self.hint.height()) self.setMinimumHeight(0) self.setMaximumWidth(16777215) if self.forceWidth: self.setMinimumWidth(self.hint.width()) else: self.setMinimumWidth(0) def sizeHint(self): if self.orientation == 'vertical': if hasattr(self, 'hint'): return QtCore.QSize(self.hint.height(), self.hint.width()) else: return QtCore.QSize(19, 50) else: if hasattr(self, 'hint'): return QtCore.QSize(self.hint.width(), self.hint.height()) else: return QtCore.QSize(50, 19)
VerticalLabel
python
getsentry__sentry
src/sentry/integrations/source_code_management/metrics.py
{ "start": 3697, "end": 4210 }
class ____(StrEnum): """ Reasons why a SourceCodeSearchEndpoint method (handle_search_issues, handle_search_repositories, or get) may halt without success/failure. """ NO_ISSUE_TRACKER = "no_issue_tracker" RATE_LIMITED = "rate_limited" MISSING_REPOSITORY_OR_NO_ACCESS = "missing_repository_or_no_access" MISSING_INTEGRATION = "missing_integration" SERIALIZER_ERRORS = "serializer_errors" MISSING_REPOSITORY_FIELD = "missing_repository_field"
SourceCodeSearchEndpointHaltReason