file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
feedbackStatusbarItem.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IStatusbarItem } from 'vs/workbench/browser/parts/statusbar/statusbar'; import { FeedbackDropdown, IFeedback, IFeedbackService } from './feedback'; import { IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import product from 'vs/platform/node/product'; import { Themable, STATUS_BAR_FOREGROUND, STATUS_BAR_NO_FOLDER_FOREGROUND } from 'vs/workbench/common/theme'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; class TwitterFeedbackService implements IFeedbackService { private static TWITTER_URL: string = 'https://twitter.com/intent/tweet'; private static VIA_NAME: string = 'code'; private static HASHTAGS: string[] = ['HappyCoding']; private combineHashTagsAsString(): string { return TwitterFeedbackService.HASHTAGS.join(','); } public submitFeedback(feedback: IFeedback): void { const queryString = `?${feedback.sentiment === 1 ? `hashtags=${this.combineHashTagsAsString()}&` : null}ref_src=twsrc%5Etfw&related=twitterapi%2Ctwitter&text=${feedback.feedback}&tw_p=tweetbutton&via=${TwitterFeedbackService.VIA_NAME}`; const url = TwitterFeedbackService.TWITTER_URL + queryString; window.open(url); } public getCharacterLimit(sentiment: number): number { let length: number = 0; if (sentiment === 1) { TwitterFeedbackService.HASHTAGS.forEach(element => { length += element.length + 2; }); } if (TwitterFeedbackService.VIA_NAME) { length += ` via @${TwitterFeedbackService.VIA_NAME}`.length; } return 140 - length; } } export class FeedbackStatusbarItem extends Themable implements IStatusbarItem { private dropdown: FeedbackDropdown; constructor( @IInstantiationService private instantiationService: IInstantiationService, @IContextViewService private contextViewService: IContextViewService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IThemeService themeService: IThemeService ) { super(themeService); this.registerListeners(); } private registerListeners(): void { this.toUnbind.push(this.contextService.onDidChangeWorkbenchState(() => this.updateStyles())); } protected updateStyles(): void { super.updateStyles(); if (this.dropdown) { this.dropdown.label.style('background-color', this.getColor(this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY ? STATUS_BAR_FOREGROUND : STATUS_BAR_NO_FOLDER_FOREGROUND)); } } public render(element: HTMLElement): IDisposable { if (product.sendASmile) { this.dropdown = this.instantiationService.createInstance(FeedbackDropdown, element, { contextViewProvider: this.contextViewService, feedbackService: this.instantiationService.createInstance(TwitterFeedbackService) }); this.updateStyles(); return this.dropdown; }
return null; } }
random_line_split
tree.controller.ts
import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common'; import {IOuterNode} from '../../../src/interfaces/IOuterNode'; import {TreeDataService} from './tree-data.service';
@Controller('tree') export class TreeController { public constructor(private treeData: TreeDataService) { } @Get() public getRoot(): IOuterNode[] { return this.treeData.getChildren(null); } @Get(':id') public getChildren(@Param('id') nodeId: string): IOuterNode[] { if (nodeId === 'null') { return this.getRoot(); } return this.treeData.getChildren(nodeId); } @Post() public add(@Body() node: Partial<IOuterNode>): IOuterNode { return this.treeData.add(node); } @Delete(':id') public remove(@Res() response: Response, @Param('id') nodeId: string): any { const result = this.treeData.remove(nodeId); if (result) { response.status(HttpStatus.NO_CONTENT).send(); } else { response.status(HttpStatus.BAD_REQUEST).send(); } } @Put(':id') public update(@Param('id') nodeId: string, @Body() node: IOuterNode): IOuterNode { return this.treeData.update(node); } }
random_line_split
tree.controller.ts
import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common'; import {IOuterNode} from '../../../src/interfaces/IOuterNode'; import {TreeDataService} from './tree-data.service'; @Controller('tree') export class TreeController { public constructor(private treeData: TreeDataService) { } @Get() public getRoot(): IOuterNode[] { return this.treeData.getChildren(null); } @Get(':id') public getChildren(@Param('id') nodeId: string): IOuterNode[]
@Post() public add(@Body() node: Partial<IOuterNode>): IOuterNode { return this.treeData.add(node); } @Delete(':id') public remove(@Res() response: Response, @Param('id') nodeId: string): any { const result = this.treeData.remove(nodeId); if (result) { response.status(HttpStatus.NO_CONTENT).send(); } else { response.status(HttpStatus.BAD_REQUEST).send(); } } @Put(':id') public update(@Param('id') nodeId: string, @Body() node: IOuterNode): IOuterNode { return this.treeData.update(node); } }
{ if (nodeId === 'null') { return this.getRoot(); } return this.treeData.getChildren(nodeId); }
identifier_body
tree.controller.ts
import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common'; import {IOuterNode} from '../../../src/interfaces/IOuterNode'; import {TreeDataService} from './tree-data.service'; @Controller('tree') export class TreeController { public constructor(private treeData: TreeDataService) { } @Get() public getRoot(): IOuterNode[] { return this.treeData.getChildren(null); } @Get(':id') public getChildren(@Param('id') nodeId: string): IOuterNode[] { if (nodeId === 'null')
return this.treeData.getChildren(nodeId); } @Post() public add(@Body() node: Partial<IOuterNode>): IOuterNode { return this.treeData.add(node); } @Delete(':id') public remove(@Res() response: Response, @Param('id') nodeId: string): any { const result = this.treeData.remove(nodeId); if (result) { response.status(HttpStatus.NO_CONTENT).send(); } else { response.status(HttpStatus.BAD_REQUEST).send(); } } @Put(':id') public update(@Param('id') nodeId: string, @Body() node: IOuterNode): IOuterNode { return this.treeData.update(node); } }
{ return this.getRoot(); }
conditional_block
tree.controller.ts
import {Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, Response} from '@nestjs/common'; import {IOuterNode} from '../../../src/interfaces/IOuterNode'; import {TreeDataService} from './tree-data.service'; @Controller('tree') export class
{ public constructor(private treeData: TreeDataService) { } @Get() public getRoot(): IOuterNode[] { return this.treeData.getChildren(null); } @Get(':id') public getChildren(@Param('id') nodeId: string): IOuterNode[] { if (nodeId === 'null') { return this.getRoot(); } return this.treeData.getChildren(nodeId); } @Post() public add(@Body() node: Partial<IOuterNode>): IOuterNode { return this.treeData.add(node); } @Delete(':id') public remove(@Res() response: Response, @Param('id') nodeId: string): any { const result = this.treeData.remove(nodeId); if (result) { response.status(HttpStatus.NO_CONTENT).send(); } else { response.status(HttpStatus.BAD_REQUEST).send(); } } @Put(':id') public update(@Param('id') nodeId: string, @Body() node: IOuterNode): IOuterNode { return this.treeData.update(node); } }
TreeController
identifier_name
cerberus_run.py
#!/usr/bin/env python import syslog from subprocess import call import urllib2 import json import re import docker_login from user_data import get_user_data # Starts a docker run for a given repo # This will effectively call `docker run <flags> <repo>:<tag>` # This service is monitored by Upstart # User Data # docker.repo: Repo to run # docker.tag: Tag of repo # docker.flags: Flags to send to `docker run` (e.g. -p 8888:8888) syslog.syslog(syslog.LOG_WARNING, 'Running docker container...') user_data = get_user_data() docker = user_data['docker'] repo = docker['repo'] tag = docker.get('tag', 'latest') repo_with_tag = "%s:%s" % (repo, tag) flags = docker.get('flags', []) # Allow flags to be a string or an array if isinstance(flags,basestring): flags = [flags] flags = map(lambda flag: re.sub('-(\w)\s', r'-\1=', flag), flags) # Change `-x ...` to `-x=...` # Call Python Login Script syslog.syslog(syslog.LOG_WARNING, 'Logging in to docker') docker_login.login() syslog.syslog(syslog.LOG_WARNING, 'Pulling %s docker image' % repo_with_tag) if call(['docker','pull',repo]) != 0:
syslog.syslog(syslog.LOG_WARNING, 'Booting %s with %s...' % (repo_with_tag, flags)) if call(['docker','run','--cidfile=/var/run/docker/container.cid'] + flags + [repo_with_tag]) != 0: raise Exception("Failed to run docker repo %s" % repo_with_tag)
raise Exception("Failed to pull docker repo %s" % repo_with_tag)
conditional_block
cerberus_run.py
#!/usr/bin/env python import syslog from subprocess import call import urllib2 import json import re import docker_login from user_data import get_user_data # Starts a docker run for a given repo # This will effectively call `docker run <flags> <repo>:<tag>` # This service is monitored by Upstart # User Data # docker.repo: Repo to run # docker.tag: Tag of repo # docker.flags: Flags to send to `docker run` (e.g. -p 8888:8888) syslog.syslog(syslog.LOG_WARNING, 'Running docker container...')
repo = docker['repo'] tag = docker.get('tag', 'latest') repo_with_tag = "%s:%s" % (repo, tag) flags = docker.get('flags', []) # Allow flags to be a string or an array if isinstance(flags,basestring): flags = [flags] flags = map(lambda flag: re.sub('-(\w)\s', r'-\1=', flag), flags) # Change `-x ...` to `-x=...` # Call Python Login Script syslog.syslog(syslog.LOG_WARNING, 'Logging in to docker') docker_login.login() syslog.syslog(syslog.LOG_WARNING, 'Pulling %s docker image' % repo_with_tag) if call(['docker','pull',repo]) != 0: raise Exception("Failed to pull docker repo %s" % repo_with_tag) syslog.syslog(syslog.LOG_WARNING, 'Booting %s with %s...' % (repo_with_tag, flags)) if call(['docker','run','--cidfile=/var/run/docker/container.cid'] + flags + [repo_with_tag]) != 0: raise Exception("Failed to run docker repo %s" % repo_with_tag)
user_data = get_user_data() docker = user_data['docker']
random_line_split
_operation_status_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class OperationStatusOperations(object): """OperationStatusOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.dataprotection.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer):
def get( self, location, # type: str operation_id, # type: str **kwargs # type: Any ): # type: (...) -> "_models.OperationResource" """Gets the operation status for a resource. Gets the operation status for a resource. :param location: :type location: str :param operation_id: :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationResource, or the result of cls(response) :rtype: ~azure.mgmt.dataprotection.models.OperationResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str'), 'operationId': self._serialize.url("operation_id", operation_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('OperationResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataProtection/locations/{location}/operationStatus/{operationId}'} # type: ignore
self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config
identifier_body
_operation_status_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class OperationStatusOperations(object): """OperationStatusOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.dataprotection.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def get( self, location, # type: str operation_id, # type: str **kwargs # type: Any ): # type: (...) -> "_models.OperationResource" """Gets the operation status for a resource. Gets the operation status for a resource. :param location: :type location: str :param operation_id: :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationResource, or the result of cls(response) :rtype: ~azure.mgmt.dataprotection.models.OperationResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError }
url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str'), 'operationId': self._serialize.url("operation_id", operation_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('OperationResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataProtection/locations/{location}/operationStatus/{operationId}'} # type: ignore
error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" # Construct URL
random_line_split
_operation_status_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class OperationStatusOperations(object): """OperationStatusOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.dataprotection.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def
(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def get( self, location, # type: str operation_id, # type: str **kwargs # type: Any ): # type: (...) -> "_models.OperationResource" """Gets the operation status for a resource. Gets the operation status for a resource. :param location: :type location: str :param operation_id: :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationResource, or the result of cls(response) :rtype: ~azure.mgmt.dataprotection.models.OperationResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str'), 'operationId': self._serialize.url("operation_id", operation_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('OperationResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataProtection/locations/{location}/operationStatus/{operationId}'} # type: ignore
__init__
identifier_name
_operation_status_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class OperationStatusOperations(object): """OperationStatusOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.dataprotection.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def get( self, location, # type: str operation_id, # type: str **kwargs # type: Any ): # type: (...) -> "_models.OperationResource" """Gets the operation status for a resource. Gets the operation status for a resource. :param location: :type location: str :param operation_id: :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: OperationResource, or the result of cls(response) :rtype: ~azure.mgmt.dataprotection.models.OperationResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str'), 'operationId': self._serialize.url("operation_id", operation_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('OperationResource', pipeline_response) if cls:
return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DataProtection/locations/{location}/operationStatus/{operationId}'} # type: ignore
return cls(pipeline_response, deserialized, {})
conditional_block
range_set.rs
#![allow(dead_code)] //! A set library to aid character set manipulation. //! //! `range_set` aims to make it easier to handle set manipulation for characters //! over ranges. For example, a unicode library may expose character ranges such //! as `('0', '9')` as a sequence of digits. If I was already later state I would //! like to add the sequence of digits: `('1', '3')`, it would consider them as //! distinct and store both. This is a nuisance. It should recognize that `1-3` //! is encased inside `0-9` and leave it as is. //! //! It provides the standard set operations: union, intersection, difference, //! and symmetric difference. use std::collections::BTreeSet; use std::fmt::{self, Display}; use parse::NextPrev; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] pub struct Range(pub char, pub char); impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } impl Range { fn contains(&self, c: char) -> bool { self.0 <= c && self.1 >= c } } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Set(BTreeSet<Range>); impl fmt::Display for Set { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Set(ref set) = *self; let len = BTreeSet::len(set); for (count, s) in set.iter().enumerate() { if count < len - 1 { try!(write!(f, "{}, ", s)) } else { return write!(f, "{}", s) } } Ok(()) } } impl Set { pub fn contains(&self, c: char) -> bool { for range in &self.0 { if range.contains(c) { return true } } false } pub fn new() -> Self { Set(BTreeSet::new()) } pub fn insert(&mut self, value: Range) { let mut ret = BTreeSet::new(); // value is a complete subset of one of the other ranges. let mut subset = false; // Borrowing self blocks later operation. Add a new scope. { let Set(ref set) = *self; let Range(mut min_val, mut max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set adding old disjoint pieces and supersets back. When partially // overlapped or disjoint without a gap, expand value to the union. At the // end, insert union after it has been fully expanded. // // It is important that each branch consider all cases which lead to a specific // modification. For example, expanding the low side isn't checking for only // partial overlap, it's checking all cases which result in *only* the left // side expanding. Previous attempts, for example, checked for partial overlap // as distinct from subsets/supersets. The result was missing many edge cases. for &Range(min, max) in &*set { // value overlaps at the beginning or disjoint w/o gap on the low side. if min_val < min && max_val >= min.prev() && max_val <= max { max_val = max } // value overlaps at the end or disjoin w/o gap on the high side. else if min_val >= min && min_val <= max.next() && max_val > max { min_val = min } // value is entirely contained between min and max. Insert original // into new array because new is a subset. else if min_val >= min && max_val <= max { ret.insert(Range(min, max)); subset = true; } // value is a superset to the current so don't add current. else if min_val < min && max_val > max {} // value is disjoint with current and has a gap. Add current. else
} // Insert value only when it's not a subset. if !subset { ret.insert(Range(min_val, max_val)); } } *self = Set(ret); } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn remove(&mut self, value: Range) { let mut ret = BTreeSet::new(); // Borrowing self blocks later modification. Make a new scope to contain it. { let Set(ref set) = *self; let Range(min_val, max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set inserting whatever doesn't intersect. for &Range(min, max) in &*set { // value overlaps at the beginning. if min_val <= min && max_val >= min && max_val < max { ret.insert(Range(max_val.next(), max)); } // value overlaps at the end. else if min_val > min && min_val <= max && max_val >= max { ret.insert(Range(min, min_val.prev())); } // value is entirely contained between min and max. Split set // into two pieces. else if min_val > min && max_val < max { ret.insert(Range(min, min_val.prev())); ret.insert(Range(max_val.next(), max)); // Current piece was a superset so value cannot be anywhere else. break; // value is a superset to the current so don't add current. } else if min_val <= min && max_val >= max {} // value is disjoint with current so add current. else { ret.insert(Range(min, max)); } } } *self = Set(ret) } // 123 + 345 = 12345. pub fn union(&self, value: &Self) -> Self { let mut ret = self.clone(); // Loop over the btreeset of Range(char, char). for &x in &value.0 { ret.insert(x) } ret } // Intersection of `A` & `B` is `A - (A - B)`: 123 & 345 = 3. pub fn intersection(&self, value: &Self) -> Self { let diff = self.difference(value); self.difference(&diff) } // 123 - 345 = 12. pub fn difference(&self, value: &Self) -> Self { let mut ret = self.clone(); for &x in &value.0 { ret.remove(x) } ret } // `A` ^ `B` is `(A + B) - (A & B)`: 123 ^ 345 = 1245. pub fn symmetric_difference(&self, value: &Self) -> Self { let union = self.union(value); let intersection = self.intersection(value); union.difference(&intersection) } }
{ ret.insert(Range(min, max)); }
conditional_block
range_set.rs
#![allow(dead_code)] //! A set library to aid character set manipulation. //! //! `range_set` aims to make it easier to handle set manipulation for characters //! over ranges. For example, a unicode library may expose character ranges such //! as `('0', '9')` as a sequence of digits. If I was already later state I would //! like to add the sequence of digits: `('1', '3')`, it would consider them as //! distinct and store both. This is a nuisance. It should recognize that `1-3` //! is encased inside `0-9` and leave it as is. //! //! It provides the standard set operations: union, intersection, difference, //! and symmetric difference. use std::collections::BTreeSet; use std::fmt::{self, Display}; use parse::NextPrev; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] pub struct Range(pub char, pub char); impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } impl Range { fn contains(&self, c: char) -> bool { self.0 <= c && self.1 >= c } } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Set(BTreeSet<Range>); impl fmt::Display for Set { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Set(ref set) = *self; let len = BTreeSet::len(set); for (count, s) in set.iter().enumerate() { if count < len - 1 { try!(write!(f, "{}, ", s)) } else { return write!(f, "{}", s) } } Ok(()) } } impl Set { pub fn contains(&self, c: char) -> bool { for range in &self.0 { if range.contains(c) { return true } } false } pub fn
() -> Self { Set(BTreeSet::new()) } pub fn insert(&mut self, value: Range) { let mut ret = BTreeSet::new(); // value is a complete subset of one of the other ranges. let mut subset = false; // Borrowing self blocks later operation. Add a new scope. { let Set(ref set) = *self; let Range(mut min_val, mut max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set adding old disjoint pieces and supersets back. When partially // overlapped or disjoint without a gap, expand value to the union. At the // end, insert union after it has been fully expanded. // // It is important that each branch consider all cases which lead to a specific // modification. For example, expanding the low side isn't checking for only // partial overlap, it's checking all cases which result in *only* the left // side expanding. Previous attempts, for example, checked for partial overlap // as distinct from subsets/supersets. The result was missing many edge cases. for &Range(min, max) in &*set { // value overlaps at the beginning or disjoint w/o gap on the low side. if min_val < min && max_val >= min.prev() && max_val <= max { max_val = max } // value overlaps at the end or disjoin w/o gap on the high side. else if min_val >= min && min_val <= max.next() && max_val > max { min_val = min } // value is entirely contained between min and max. Insert original // into new array because new is a subset. else if min_val >= min && max_val <= max { ret.insert(Range(min, max)); subset = true; } // value is a superset to the current so don't add current. else if min_val < min && max_val > max {} // value is disjoint with current and has a gap. Add current. else { ret.insert(Range(min, max)); } } // Insert value only when it's not a subset. if !subset { ret.insert(Range(min_val, max_val)); } } *self = Set(ret); } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn remove(&mut self, value: Range) { let mut ret = BTreeSet::new(); // Borrowing self blocks later modification. Make a new scope to contain it. { let Set(ref set) = *self; let Range(min_val, max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set inserting whatever doesn't intersect. for &Range(min, max) in &*set { // value overlaps at the beginning. if min_val <= min && max_val >= min && max_val < max { ret.insert(Range(max_val.next(), max)); } // value overlaps at the end. else if min_val > min && min_val <= max && max_val >= max { ret.insert(Range(min, min_val.prev())); } // value is entirely contained between min and max. Split set // into two pieces. else if min_val > min && max_val < max { ret.insert(Range(min, min_val.prev())); ret.insert(Range(max_val.next(), max)); // Current piece was a superset so value cannot be anywhere else. break; // value is a superset to the current so don't add current. } else if min_val <= min && max_val >= max {} // value is disjoint with current so add current. else { ret.insert(Range(min, max)); } } } *self = Set(ret) } // 123 + 345 = 12345. pub fn union(&self, value: &Self) -> Self { let mut ret = self.clone(); // Loop over the btreeset of Range(char, char). for &x in &value.0 { ret.insert(x) } ret } // Intersection of `A` & `B` is `A - (A - B)`: 123 & 345 = 3. pub fn intersection(&self, value: &Self) -> Self { let diff = self.difference(value); self.difference(&diff) } // 123 - 345 = 12. pub fn difference(&self, value: &Self) -> Self { let mut ret = self.clone(); for &x in &value.0 { ret.remove(x) } ret } // `A` ^ `B` is `(A + B) - (A & B)`: 123 ^ 345 = 1245. pub fn symmetric_difference(&self, value: &Self) -> Self { let union = self.union(value); let intersection = self.intersection(value); union.difference(&intersection) } }
new
identifier_name
range_set.rs
#![allow(dead_code)] //! A set library to aid character set manipulation. //! //! `range_set` aims to make it easier to handle set manipulation for characters //! over ranges. For example, a unicode library may expose character ranges such //! as `('0', '9')` as a sequence of digits. If I was already later state I would //! like to add the sequence of digits: `('1', '3')`, it would consider them as //! distinct and store both. This is a nuisance. It should recognize that `1-3` //! is encased inside `0-9` and leave it as is. //! //! It provides the standard set operations: union, intersection, difference, //! and symmetric difference. use std::collections::BTreeSet; use std::fmt::{self, Display}; use parse::NextPrev; #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] pub struct Range(pub char, pub char); impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } impl Range { fn contains(&self, c: char) -> bool { self.0 <= c && self.1 >= c } } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Set(BTreeSet<Range>); impl fmt::Display for Set { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Set(ref set) = *self; let len = BTreeSet::len(set); for (count, s) in set.iter().enumerate() { if count < len - 1 { try!(write!(f, "{}, ", s)) } else { return write!(f, "{}", s) } } Ok(()) } } impl Set { pub fn contains(&self, c: char) -> bool { for range in &self.0 { if range.contains(c) { return true } } false } pub fn new() -> Self { Set(BTreeSet::new()) } pub fn insert(&mut self, value: Range) { let mut ret = BTreeSet::new(); // value is a complete subset of one of the other ranges. let mut subset = false; // Borrowing self blocks later operation. Add a new scope. { let Set(ref set) = *self; let Range(mut min_val, mut max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set adding old disjoint pieces and supersets back. When partially // overlapped or disjoint without a gap, expand value to the union. At the // end, insert union after it has been fully expanded. // // It is important that each branch consider all cases which lead to a specific // modification. For example, expanding the low side isn't checking for only // partial overlap, it's checking all cases which result in *only* the left // side expanding. Previous attempts, for example, checked for partial overlap // as distinct from subsets/supersets. The result was missing many edge cases. for &Range(min, max) in &*set { // value overlaps at the beginning or disjoint w/o gap on the low side. if min_val < min && max_val >= min.prev() && max_val <= max { max_val = max } // value overlaps at the end or disjoin w/o gap on the high side. else if min_val >= min && min_val <= max.next() && max_val > max { min_val = min } // value is entirely contained between min and max. Insert original // into new array because new is a subset. else if min_val >= min && max_val <= max { ret.insert(Range(min, max)); subset = true; } // value is a superset to the current so don't add current. else if min_val < min && max_val > max {} // value is disjoint with current and has a gap. Add current. else { ret.insert(Range(min, max)); } } // Insert value only when it's not a subset. if !subset { ret.insert(Range(min_val, max_val)); } } *self = Set(ret); } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn remove(&mut self, value: Range) { let mut ret = BTreeSet::new(); // Borrowing self blocks later modification. Make a new scope to contain it. { let Set(ref set) = *self; let Range(min_val, max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set inserting whatever doesn't intersect. for &Range(min, max) in &*set { // value overlaps at the beginning. if min_val <= min && max_val >= min && max_val < max { ret.insert(Range(max_val.next(), max)); } // value overlaps at the end. else if min_val > min && min_val <= max && max_val >= max { ret.insert(Range(min, min_val.prev())); } // value is entirely contained between min and max. Split set // into two pieces. else if min_val > min && max_val < max { ret.insert(Range(min, min_val.prev())); ret.insert(Range(max_val.next(), max)); // Current piece was a superset so value cannot be anywhere else. break; // value is a superset to the current so don't add current. } else if min_val <= min && max_val >= max {} // value is disjoint with current so add current. else { ret.insert(Range(min, max)); } } } *self = Set(ret) } // 123 + 345 = 12345. pub fn union(&self, value: &Self) -> Self
// Intersection of `A` & `B` is `A - (A - B)`: 123 & 345 = 3. pub fn intersection(&self, value: &Self) -> Self { let diff = self.difference(value); self.difference(&diff) } // 123 - 345 = 12. pub fn difference(&self, value: &Self) -> Self { let mut ret = self.clone(); for &x in &value.0 { ret.remove(x) } ret } // `A` ^ `B` is `(A + B) - (A & B)`: 123 ^ 345 = 1245. pub fn symmetric_difference(&self, value: &Self) -> Self { let union = self.union(value); let intersection = self.intersection(value); union.difference(&intersection) } }
{ let mut ret = self.clone(); // Loop over the btreeset of Range(char, char). for &x in &value.0 { ret.insert(x) } ret }
identifier_body
range_set.rs
#![allow(dead_code)] //! A set library to aid character set manipulation. //! //! `range_set` aims to make it easier to handle set manipulation for characters //! over ranges. For example, a unicode library may expose character ranges such //! as `('0', '9')` as a sequence of digits. If I was already later state I would //! like to add the sequence of digits: `('1', '3')`, it would consider them as //! distinct and store both. This is a nuisance. It should recognize that `1-3` //! is encased inside `0-9` and leave it as is. //! //! It provides the standard set operations: union, intersection, difference, //! and symmetric difference.
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)] pub struct Range(pub char, pub char); impl fmt::Display for Range { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.0, self.1) } } impl Range { fn contains(&self, c: char) -> bool { self.0 <= c && self.1 >= c } } #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Set(BTreeSet<Range>); impl fmt::Display for Set { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Set(ref set) = *self; let len = BTreeSet::len(set); for (count, s) in set.iter().enumerate() { if count < len - 1 { try!(write!(f, "{}, ", s)) } else { return write!(f, "{}", s) } } Ok(()) } } impl Set { pub fn contains(&self, c: char) -> bool { for range in &self.0 { if range.contains(c) { return true } } false } pub fn new() -> Self { Set(BTreeSet::new()) } pub fn insert(&mut self, value: Range) { let mut ret = BTreeSet::new(); // value is a complete subset of one of the other ranges. let mut subset = false; // Borrowing self blocks later operation. Add a new scope. { let Set(ref set) = *self; let Range(mut min_val, mut max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set adding old disjoint pieces and supersets back. When partially // overlapped or disjoint without a gap, expand value to the union. At the // end, insert union after it has been fully expanded. // // It is important that each branch consider all cases which lead to a specific // modification. For example, expanding the low side isn't checking for only // partial overlap, it's checking all cases which result in *only* the left // side expanding. Previous attempts, for example, checked for partial overlap // as distinct from subsets/supersets. The result was missing many edge cases. for &Range(min, max) in &*set { // value overlaps at the beginning or disjoint w/o gap on the low side. if min_val < min && max_val >= min.prev() && max_val <= max { max_val = max } // value overlaps at the end or disjoin w/o gap on the high side. else if min_val >= min && min_val <= max.next() && max_val > max { min_val = min } // value is entirely contained between min and max. Insert original // into new array because new is a subset. else if min_val >= min && max_val <= max { ret.insert(Range(min, max)); subset = true; } // value is a superset to the current so don't add current. else if min_val < min && max_val > max {} // value is disjoint with current and has a gap. Add current. else { ret.insert(Range(min, max)); } } // Insert value only when it's not a subset. if !subset { ret.insert(Range(min_val, max_val)); } } *self = Set(ret); } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn remove(&mut self, value: Range) { let mut ret = BTreeSet::new(); // Borrowing self blocks later modification. Make a new scope to contain it. { let Set(ref set) = *self; let Range(min_val, max_val) = value; if min_val > max_val { panic!("First value cannot be greater than the second.") } // Loop over set inserting whatever doesn't intersect. for &Range(min, max) in &*set { // value overlaps at the beginning. if min_val <= min && max_val >= min && max_val < max { ret.insert(Range(max_val.next(), max)); } // value overlaps at the end. else if min_val > min && min_val <= max && max_val >= max { ret.insert(Range(min, min_val.prev())); } // value is entirely contained between min and max. Split set // into two pieces. else if min_val > min && max_val < max { ret.insert(Range(min, min_val.prev())); ret.insert(Range(max_val.next(), max)); // Current piece was a superset so value cannot be anywhere else. break; // value is a superset to the current so don't add current. } else if min_val <= min && max_val >= max {} // value is disjoint with current so add current. else { ret.insert(Range(min, max)); } } } *self = Set(ret) } // 123 + 345 = 12345. pub fn union(&self, value: &Self) -> Self { let mut ret = self.clone(); // Loop over the btreeset of Range(char, char). for &x in &value.0 { ret.insert(x) } ret } // Intersection of `A` & `B` is `A - (A - B)`: 123 & 345 = 3. pub fn intersection(&self, value: &Self) -> Self { let diff = self.difference(value); self.difference(&diff) } // 123 - 345 = 12. pub fn difference(&self, value: &Self) -> Self { let mut ret = self.clone(); for &x in &value.0 { ret.remove(x) } ret } // `A` ^ `B` is `(A + B) - (A & B)`: 123 ^ 345 = 1245. pub fn symmetric_difference(&self, value: &Self) -> Self { let union = self.union(value); let intersection = self.intersection(value); union.difference(&intersection) } }
use std::collections::BTreeSet; use std::fmt::{self, Display}; use parse::NextPrev;
random_line_split
dma.rs
use hardware::cpu; use hardware::cpu::MapperHolder; pub struct DmaController { running: bool, base: u16, cycles: usize, pub oam_ram: [u8; 160], } impl cpu::Handler for DmaController { fn read(&self, address: u16) -> u8 { match address { 0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00], // TODO: not sure what should happen here, so let's just crash 0xFF46 => panic!("Trying to read from DMA."), _ => unreachable!(), } } fn write(&mut self, address: u16, v: u8) { match address { 0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00] = v, 0xFF46 => { if v >= 0xE0 { // It's not really clear to me what happens when we try to // DMA to a high address so let's just crash unimplemented!(); } self.base = (v as u16) << 8; // TODO: what if it's already running? self.running = true; self.cycles = 0; } _ => unreachable!(), } } } impl DmaController { pub fn new() -> DmaController { DmaController { running: false, base: 0, cycles: 0, oam_ram: [0; 160], } } pub fn cpu_step(&mut self, mapper_holder: &dyn MapperHolder)
}
{ if !self.running { return; } match self.cycles { 0 => { // There's a 1 cycle wait after enabling DMA } 1..=160 => { let dma_step = self.cycles as u16 - 1; let from = self.base + dma_step; let v = mapper_holder.get_handler_read(from).read(from); self.oam_ram[dma_step as usize] = v; } 161 => { // DMA is done self.running = false; } _ => unreachable!(), } self.cycles += 1; }
identifier_body
dma.rs
use hardware::cpu; use hardware::cpu::MapperHolder; pub struct DmaController { running: bool, base: u16, cycles: usize, pub oam_ram: [u8; 160], } impl cpu::Handler for DmaController { fn
(&self, address: u16) -> u8 { match address { 0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00], // TODO: not sure what should happen here, so let's just crash 0xFF46 => panic!("Trying to read from DMA."), _ => unreachable!(), } } fn write(&mut self, address: u16, v: u8) { match address { 0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00] = v, 0xFF46 => { if v >= 0xE0 { // It's not really clear to me what happens when we try to // DMA to a high address so let's just crash unimplemented!(); } self.base = (v as u16) << 8; // TODO: what if it's already running? self.running = true; self.cycles = 0; } _ => unreachable!(), } } } impl DmaController { pub fn new() -> DmaController { DmaController { running: false, base: 0, cycles: 0, oam_ram: [0; 160], } } pub fn cpu_step(&mut self, mapper_holder: &dyn MapperHolder) { if !self.running { return; } match self.cycles { 0 => { // There's a 1 cycle wait after enabling DMA } 1..=160 => { let dma_step = self.cycles as u16 - 1; let from = self.base + dma_step; let v = mapper_holder.get_handler_read(from).read(from); self.oam_ram[dma_step as usize] = v; } 161 => { // DMA is done self.running = false; } _ => unreachable!(), } self.cycles += 1; } }
read
identifier_name
dma.rs
use hardware::cpu; use hardware::cpu::MapperHolder;
cycles: usize, pub oam_ram: [u8; 160], } impl cpu::Handler for DmaController { fn read(&self, address: u16) -> u8 { match address { 0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00], // TODO: not sure what should happen here, so let's just crash 0xFF46 => panic!("Trying to read from DMA."), _ => unreachable!(), } } fn write(&mut self, address: u16, v: u8) { match address { 0xFE00..=0xFE9F => self.oam_ram[address as usize - 0xFE00] = v, 0xFF46 => { if v >= 0xE0 { // It's not really clear to me what happens when we try to // DMA to a high address so let's just crash unimplemented!(); } self.base = (v as u16) << 8; // TODO: what if it's already running? self.running = true; self.cycles = 0; } _ => unreachable!(), } } } impl DmaController { pub fn new() -> DmaController { DmaController { running: false, base: 0, cycles: 0, oam_ram: [0; 160], } } pub fn cpu_step(&mut self, mapper_holder: &dyn MapperHolder) { if !self.running { return; } match self.cycles { 0 => { // There's a 1 cycle wait after enabling DMA } 1..=160 => { let dma_step = self.cycles as u16 - 1; let from = self.base + dma_step; let v = mapper_holder.get_handler_read(from).read(from); self.oam_ram[dma_step as usize] = v; } 161 => { // DMA is done self.running = false; } _ => unreachable!(), } self.cycles += 1; } }
pub struct DmaController { running: bool, base: u16,
random_line_split
live_audio_sample.py
import numpy as np import matplotlib.pyplot as plt #Used for graphing audio tests import pyaudio as pa import wave from time import sleep #Constants used for sampling audio CHUNK = 1024 FORMAT = pa.paInt16 CHANNELS = 1 RATE = 44100 # Must match rate at which mic actually samples sound RECORD_TIMEFRAME = 1.0 #Time in seconds OUTPUT_FILE = "sample.wav" #Flag for plotting sound input waves for debugging and implementation purposes TESTING_GRAPHS = True def sampleAudio(wav_name=OUTPUT_FILE): """Samples audio from the microphone for a given period of time. The output file is saved as [wav_name] Code here taken from the front page of: < https://people.csail.mit.edu/hubert/pyaudio/ > """ # Open the recording session rec_session = pa.PyAudio() stream = rec_session.open(format=FORMAT, channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK) print("Start recording") frames = [] # Sample audio frames for given time period for i in range(0, int(RATE/CHUNK*RECORD_TIMEFRAME)): data = stream.read(CHUNK) frames.append(data) # Close the recording session stream.stop_stream() stream.close() rec_session.terminate() #Create the wav file for analysis output_wav = wave.open(wav_name,"wb") output_wav.setnchannels(CHANNELS) output_wav.setsampwidth(rec_session.get_sample_size(FORMAT)) output_wav.setframerate(RATE) output_wav.writeframes(b''.join(frames)) output_wav.close() def
(wav_file=OUTPUT_FILE): """Analyzes the audio sample [wav_file] (must be a 16-bit WAV file with one channel) and returns maximum magnitude of the most prominent sound and the frequency thresholds it falls between. Basic procedure of processing audio taken from: < http://samcarcagno.altervista.org/blog/basic-sound-processing-python/ >""" #Open wav file for analysis sound_sample = wave.open(wav_file, "rb") #Get sampling frequency sample_freq = sound_sample.getframerate() #Extract audio frames to be analyzed # audio_frames = sound_sample.readframes(sound_sample.getnframes()) audio_frames = sound_sample.readframes(1024) converted_val = [] #COnvert byte objects into frequency values per frame for i in range(0,len(audio_frames),2): if ord(audio_frames[i+1])>127: converted_val.append(-(ord(audio_frames[i])+(256*(255-ord(audio_frames[i+1]))))) else: converted_val.append(ord(audio_frames[i])+(256*ord(audio_frames[i+1]))) #Fit into numpy array for FFT analysis freq_per_frame = np.array(converted_val) # Get amplitude of soundwave section freq = np.fft.fft(freq_per_frame) amplitude = np.abs(freq) amplitude = amplitude/float(len(freq_per_frame)) amplitude = amplitude**2 #Get bins/thresholds for frequencies freqbins = np.fft.fftfreq(CHUNK,1.0/sample_freq) x = np.linspace(0.0,1.0,1024) # Plot data if need visualization if(TESTING_GRAPHS): #Plot raw data plt.plot(converted_val) plt.title("Raw Data") plt.xlabel("Time (ms)") plt.ylabel("Frequency (Hz)") plt.show() #Plot frequency histogram plt.plot(freqbins[:16],amplitude[:16]) plt.title("Processed Data") plt.xlabel("Frequency Bins") plt.ylabel("Magnitude") plt.show() #Get the range that the max amplitude falls in. This represents the loudest noise magnitude = np.amax(amplitude) loudest = np.argmax(amplitude) lower_thres = freqbins[loudest] upper_thres = (freqbins[1]-freqbins[0])+lower_thres #Close wav file sound_sample.close() #Return the magnitude of the sound wave and its frequency threshold for analysis return magnitude, lower_thres, upper_thres #Use for testing microphone input if __name__ == "__main__": # print("Wait 3 seconds to start...") # sleep(3) print("Recording!") sampleAudio(OUTPUT_FILE) print("Stop recording!") print("Analyzing...") mag, lower, upper = getAvgFreq(OUTPUT_FILE) print("Magnitude is "+str(mag)) print("Lower bin threshold is "+str(lower)) print("Upper bin threshold is "+str(upper))
getAvgFreq
identifier_name
live_audio_sample.py
import numpy as np import matplotlib.pyplot as plt #Used for graphing audio tests import pyaudio as pa import wave from time import sleep #Constants used for sampling audio CHUNK = 1024 FORMAT = pa.paInt16 CHANNELS = 1 RATE = 44100 # Must match rate at which mic actually samples sound RECORD_TIMEFRAME = 1.0 #Time in seconds OUTPUT_FILE = "sample.wav" #Flag for plotting sound input waves for debugging and implementation purposes TESTING_GRAPHS = True def sampleAudio(wav_name=OUTPUT_FILE): """Samples audio from the microphone for a given period of time. The output file is saved as [wav_name] Code here taken from the front page of: < https://people.csail.mit.edu/hubert/pyaudio/ > """ # Open the recording session rec_session = pa.PyAudio() stream = rec_session.open(format=FORMAT, channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK) print("Start recording") frames = [] # Sample audio frames for given time period for i in range(0, int(RATE/CHUNK*RECORD_TIMEFRAME)): data = stream.read(CHUNK) frames.append(data) # Close the recording session stream.stop_stream() stream.close() rec_session.terminate() #Create the wav file for analysis output_wav = wave.open(wav_name,"wb") output_wav.setnchannels(CHANNELS) output_wav.setsampwidth(rec_session.get_sample_size(FORMAT)) output_wav.setframerate(RATE) output_wav.writeframes(b''.join(frames)) output_wav.close() def getAvgFreq(wav_file=OUTPUT_FILE): """Analyzes the audio sample [wav_file] (must be a 16-bit WAV file with one channel) and returns maximum magnitude of the most prominent sound and the frequency thresholds it falls between. Basic procedure of processing audio taken from: < http://samcarcagno.altervista.org/blog/basic-sound-processing-python/ >"""
#Get sampling frequency sample_freq = sound_sample.getframerate() #Extract audio frames to be analyzed # audio_frames = sound_sample.readframes(sound_sample.getnframes()) audio_frames = sound_sample.readframes(1024) converted_val = [] #COnvert byte objects into frequency values per frame for i in range(0,len(audio_frames),2): if ord(audio_frames[i+1])>127: converted_val.append(-(ord(audio_frames[i])+(256*(255-ord(audio_frames[i+1]))))) else: converted_val.append(ord(audio_frames[i])+(256*ord(audio_frames[i+1]))) #Fit into numpy array for FFT analysis freq_per_frame = np.array(converted_val) # Get amplitude of soundwave section freq = np.fft.fft(freq_per_frame) amplitude = np.abs(freq) amplitude = amplitude/float(len(freq_per_frame)) amplitude = amplitude**2 #Get bins/thresholds for frequencies freqbins = np.fft.fftfreq(CHUNK,1.0/sample_freq) x = np.linspace(0.0,1.0,1024) # Plot data if need visualization if(TESTING_GRAPHS): #Plot raw data plt.plot(converted_val) plt.title("Raw Data") plt.xlabel("Time (ms)") plt.ylabel("Frequency (Hz)") plt.show() #Plot frequency histogram plt.plot(freqbins[:16],amplitude[:16]) plt.title("Processed Data") plt.xlabel("Frequency Bins") plt.ylabel("Magnitude") plt.show() #Get the range that the max amplitude falls in. This represents the loudest noise magnitude = np.amax(amplitude) loudest = np.argmax(amplitude) lower_thres = freqbins[loudest] upper_thres = (freqbins[1]-freqbins[0])+lower_thres #Close wav file sound_sample.close() #Return the magnitude of the sound wave and its frequency threshold for analysis return magnitude, lower_thres, upper_thres #Use for testing microphone input if __name__ == "__main__": # print("Wait 3 seconds to start...") # sleep(3) print("Recording!") sampleAudio(OUTPUT_FILE) print("Stop recording!") print("Analyzing...") mag, lower, upper = getAvgFreq(OUTPUT_FILE) print("Magnitude is "+str(mag)) print("Lower bin threshold is "+str(lower)) print("Upper bin threshold is "+str(upper))
#Open wav file for analysis sound_sample = wave.open(wav_file, "rb")
random_line_split
live_audio_sample.py
import numpy as np import matplotlib.pyplot as plt #Used for graphing audio tests import pyaudio as pa import wave from time import sleep #Constants used for sampling audio CHUNK = 1024 FORMAT = pa.paInt16 CHANNELS = 1 RATE = 44100 # Must match rate at which mic actually samples sound RECORD_TIMEFRAME = 1.0 #Time in seconds OUTPUT_FILE = "sample.wav" #Flag for plotting sound input waves for debugging and implementation purposes TESTING_GRAPHS = True def sampleAudio(wav_name=OUTPUT_FILE): """Samples audio from the microphone for a given period of time. The output file is saved as [wav_name] Code here taken from the front page of: < https://people.csail.mit.edu/hubert/pyaudio/ > """ # Open the recording session rec_session = pa.PyAudio() stream = rec_session.open(format=FORMAT, channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK) print("Start recording") frames = [] # Sample audio frames for given time period for i in range(0, int(RATE/CHUNK*RECORD_TIMEFRAME)): data = stream.read(CHUNK) frames.append(data) # Close the recording session stream.stop_stream() stream.close() rec_session.terminate() #Create the wav file for analysis output_wav = wave.open(wav_name,"wb") output_wav.setnchannels(CHANNELS) output_wav.setsampwidth(rec_session.get_sample_size(FORMAT)) output_wav.setframerate(RATE) output_wav.writeframes(b''.join(frames)) output_wav.close() def getAvgFreq(wav_file=OUTPUT_FILE): """Analyzes the audio sample [wav_file] (must be a 16-bit WAV file with one channel) and returns maximum magnitude of the most prominent sound and the frequency thresholds it falls between. Basic procedure of processing audio taken from: < http://samcarcagno.altervista.org/blog/basic-sound-processing-python/ >""" #Open wav file for analysis sound_sample = wave.open(wav_file, "rb") #Get sampling frequency sample_freq = sound_sample.getframerate() #Extract audio frames to be analyzed # audio_frames = sound_sample.readframes(sound_sample.getnframes()) audio_frames = sound_sample.readframes(1024) converted_val = [] #COnvert byte objects into frequency values per frame for i in range(0,len(audio_frames),2): if ord(audio_frames[i+1])>127:
else: converted_val.append(ord(audio_frames[i])+(256*ord(audio_frames[i+1]))) #Fit into numpy array for FFT analysis freq_per_frame = np.array(converted_val) # Get amplitude of soundwave section freq = np.fft.fft(freq_per_frame) amplitude = np.abs(freq) amplitude = amplitude/float(len(freq_per_frame)) amplitude = amplitude**2 #Get bins/thresholds for frequencies freqbins = np.fft.fftfreq(CHUNK,1.0/sample_freq) x = np.linspace(0.0,1.0,1024) # Plot data if need visualization if(TESTING_GRAPHS): #Plot raw data plt.plot(converted_val) plt.title("Raw Data") plt.xlabel("Time (ms)") plt.ylabel("Frequency (Hz)") plt.show() #Plot frequency histogram plt.plot(freqbins[:16],amplitude[:16]) plt.title("Processed Data") plt.xlabel("Frequency Bins") plt.ylabel("Magnitude") plt.show() #Get the range that the max amplitude falls in. This represents the loudest noise magnitude = np.amax(amplitude) loudest = np.argmax(amplitude) lower_thres = freqbins[loudest] upper_thres = (freqbins[1]-freqbins[0])+lower_thres #Close wav file sound_sample.close() #Return the magnitude of the sound wave and its frequency threshold for analysis return magnitude, lower_thres, upper_thres #Use for testing microphone input if __name__ == "__main__": # print("Wait 3 seconds to start...") # sleep(3) print("Recording!") sampleAudio(OUTPUT_FILE) print("Stop recording!") print("Analyzing...") mag, lower, upper = getAvgFreq(OUTPUT_FILE) print("Magnitude is "+str(mag)) print("Lower bin threshold is "+str(lower)) print("Upper bin threshold is "+str(upper))
converted_val.append(-(ord(audio_frames[i])+(256*(255-ord(audio_frames[i+1])))))
conditional_block
live_audio_sample.py
import numpy as np import matplotlib.pyplot as plt #Used for graphing audio tests import pyaudio as pa import wave from time import sleep #Constants used for sampling audio CHUNK = 1024 FORMAT = pa.paInt16 CHANNELS = 1 RATE = 44100 # Must match rate at which mic actually samples sound RECORD_TIMEFRAME = 1.0 #Time in seconds OUTPUT_FILE = "sample.wav" #Flag for plotting sound input waves for debugging and implementation purposes TESTING_GRAPHS = True def sampleAudio(wav_name=OUTPUT_FILE): """Samples audio from the microphone for a given period of time. The output file is saved as [wav_name] Code here taken from the front page of: < https://people.csail.mit.edu/hubert/pyaudio/ > """ # Open the recording session rec_session = pa.PyAudio() stream = rec_session.open(format=FORMAT, channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK) print("Start recording") frames = [] # Sample audio frames for given time period for i in range(0, int(RATE/CHUNK*RECORD_TIMEFRAME)): data = stream.read(CHUNK) frames.append(data) # Close the recording session stream.stop_stream() stream.close() rec_session.terminate() #Create the wav file for analysis output_wav = wave.open(wav_name,"wb") output_wav.setnchannels(CHANNELS) output_wav.setsampwidth(rec_session.get_sample_size(FORMAT)) output_wav.setframerate(RATE) output_wav.writeframes(b''.join(frames)) output_wav.close() def getAvgFreq(wav_file=OUTPUT_FILE):
#Use for testing microphone input if __name__ == "__main__": # print("Wait 3 seconds to start...") # sleep(3) print("Recording!") sampleAudio(OUTPUT_FILE) print("Stop recording!") print("Analyzing...") mag, lower, upper = getAvgFreq(OUTPUT_FILE) print("Magnitude is "+str(mag)) print("Lower bin threshold is "+str(lower)) print("Upper bin threshold is "+str(upper))
"""Analyzes the audio sample [wav_file] (must be a 16-bit WAV file with one channel) and returns maximum magnitude of the most prominent sound and the frequency thresholds it falls between. Basic procedure of processing audio taken from: < http://samcarcagno.altervista.org/blog/basic-sound-processing-python/ >""" #Open wav file for analysis sound_sample = wave.open(wav_file, "rb") #Get sampling frequency sample_freq = sound_sample.getframerate() #Extract audio frames to be analyzed # audio_frames = sound_sample.readframes(sound_sample.getnframes()) audio_frames = sound_sample.readframes(1024) converted_val = [] #COnvert byte objects into frequency values per frame for i in range(0,len(audio_frames),2): if ord(audio_frames[i+1])>127: converted_val.append(-(ord(audio_frames[i])+(256*(255-ord(audio_frames[i+1]))))) else: converted_val.append(ord(audio_frames[i])+(256*ord(audio_frames[i+1]))) #Fit into numpy array for FFT analysis freq_per_frame = np.array(converted_val) # Get amplitude of soundwave section freq = np.fft.fft(freq_per_frame) amplitude = np.abs(freq) amplitude = amplitude/float(len(freq_per_frame)) amplitude = amplitude**2 #Get bins/thresholds for frequencies freqbins = np.fft.fftfreq(CHUNK,1.0/sample_freq) x = np.linspace(0.0,1.0,1024) # Plot data if need visualization if(TESTING_GRAPHS): #Plot raw data plt.plot(converted_val) plt.title("Raw Data") plt.xlabel("Time (ms)") plt.ylabel("Frequency (Hz)") plt.show() #Plot frequency histogram plt.plot(freqbins[:16],amplitude[:16]) plt.title("Processed Data") plt.xlabel("Frequency Bins") plt.ylabel("Magnitude") plt.show() #Get the range that the max amplitude falls in. This represents the loudest noise magnitude = np.amax(amplitude) loudest = np.argmax(amplitude) lower_thres = freqbins[loudest] upper_thres = (freqbins[1]-freqbins[0])+lower_thres #Close wav file sound_sample.close() #Return the magnitude of the sound wave and its frequency threshold for analysis return magnitude, lower_thres, upper_thres
identifier_body
index.ts
import { observable } from 'mobx'; import { generateId } from 'utils/generate-id'; import { TimelineVector } from 'core/primitives/timeline-vector'; import { Data } from 'core/models/graph/node'; export interface SnipParams { length: TimelineVector; data?: Data; } export const enum SnipType { container = 'container', envelope = 'envelope', notes = 'notes', trigger = 'trigger', } export class Snip {
length: TimelineVector; @observable data: Data = null; constructor(params: SnipParams) { const { data = null, length } = params; this.length = length || new TimelineVector(2); this.data = data; } end(position: TimelineVector): TimelineVector { return position.add(this.length); } static copy(clip: Snip) { return new Snip({ length: clip.length, }); } }
id = generateId(); @observable
random_line_split
index.ts
import { observable } from 'mobx'; import { generateId } from 'utils/generate-id'; import { TimelineVector } from 'core/primitives/timeline-vector'; import { Data } from 'core/models/graph/node'; export interface SnipParams { length: TimelineVector; data?: Data; } export const enum SnipType { container = 'container', envelope = 'envelope', notes = 'notes', trigger = 'trigger', } export class Snip { id = generateId(); @observable length: TimelineVector; @observable data: Data = null; constructor(params: SnipParams) { const { data = null, length } = params; this.length = length || new TimelineVector(2); this.data = data; } end(position: TimelineVector): TimelineVector { return position.add(this.length); } static
(clip: Snip) { return new Snip({ length: clip.length, }); } }
copy
identifier_name
index.ts
import { observable } from 'mobx'; import { generateId } from 'utils/generate-id'; import { TimelineVector } from 'core/primitives/timeline-vector'; import { Data } from 'core/models/graph/node'; export interface SnipParams { length: TimelineVector; data?: Data; } export const enum SnipType { container = 'container', envelope = 'envelope', notes = 'notes', trigger = 'trigger', } export class Snip { id = generateId(); @observable length: TimelineVector; @observable data: Data = null; constructor(params: SnipParams) { const { data = null, length } = params; this.length = length || new TimelineVector(2); this.data = data; } end(position: TimelineVector): TimelineVector { return position.add(this.length); } static copy(clip: Snip)
}
{ return new Snip({ length: clip.length, }); }
identifier_body
dsb.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number): number { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length, f = parseInt(n.toString().replace(/^[^.]*\.?/, ''), 10) || 0; if (v === 0 && i % 100 === 1 || f % 100 === 1) return 1; if (v === 0 && i % 100 === 2 || f % 100 === 2) return 2; if (v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 3 && i % 100 <= 4 || f % 100 === Math.floor(f % 100) && f % 100 >= 3 && f % 100 <= 4)
'dsb', [ ['dop.', 'wótp.'], ['dopołdnja', 'wótpołdnja'], ], [ ['dopołdnja', 'wótpołdnja'], , ], [ ['n', 'p', 'w', 's', 's', 'p', 's'], ['nje', 'pón', 'wał', 'srj', 'stw', 'pět', 'sob'], ['njeźela', 'pónjeźele', 'wałtora', 'srjoda', 'stwórtk', 'pětk', 'sobota'], ['nj', 'pó', 'wa', 'sr', 'st', 'pě', 'so'] ], , [ ['j', 'f', 'm', 'a', 'm', 'j', 'j', 'a', 's', 'o', 'n', 'd'], [ 'jan.', 'feb.', 'měr.', 'apr.', 'maj.', 'jun.', 'jul.', 'awg.', 'sep.', 'okt.', 'now.', 'dec.' ], [ 'januara', 'februara', 'měrca', 'apryla', 'maja', 'junija', 'julija', 'awgusta', 'septembra', 'oktobra', 'nowembra', 'decembra' ] ], [ ['j', 'f', 'm', 'a', 'm', 'j', 'j', 'a', 's', 'o', 'n', 'd'], ['jan', 'feb', 'měr', 'apr', 'maj', 'jun', 'jul', 'awg', 'sep', 'okt', 'now', 'dec'], [ 'januar', 'februar', 'měrc', 'apryl', 'maj', 'junij', 'julij', 'awgust', 'september', 'oktober', 'nowember', 'december' ] ], [['pś.Chr.n.', 'pó Chr.n.'], , ['pśed Kristusowym naroźenim', 'pó Kristusowem naroźenju']], 1, [6, 0], ['d.M.yy', 'd.M.y', 'd. MMMM y', 'EEEE, d. MMMM y'], ['H:mm', 'H:mm:ss', 'H:mm:ss z', 'H:mm:ss zzzz'], [ '{1} {0}', , , ], [',', '.', ';', '%', '+', '-', 'E', '·', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], '€', 'euro', plural ];
return 3; return 5; } export default [
random_line_split
dsb.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function
(n: number): number { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length, f = parseInt(n.toString().replace(/^[^.]*\.?/, ''), 10) || 0; if (v === 0 && i % 100 === 1 || f % 100 === 1) return 1; if (v === 0 && i % 100 === 2 || f % 100 === 2) return 2; if (v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 3 && i % 100 <= 4 || f % 100 === Math.floor(f % 100) && f % 100 >= 3 && f % 100 <= 4) return 3; return 5; } export default [ 'dsb', [ ['dop.', 'wótp.'], ['dopołdnja', 'wótpołdnja'], ], [ ['dopołdnja', 'wótpołdnja'], , ], [ ['n', 'p', 'w', 's', 's', 'p', 's'], ['nje', 'pón', 'wał', 'srj', 'stw', 'pět', 'sob'], ['njeźela', 'pónjeźele', 'wałtora', 'srjoda', 'stwórtk', 'pětk', 'sobota'], ['nj', 'pó', 'wa', 'sr', 'st', 'pě', 'so'] ], , [ ['j', 'f', 'm', 'a', 'm', 'j', 'j', 'a', 's', 'o', 'n', 'd'], [ 'jan.', 'feb.', 'měr.', 'apr.', 'maj.', 'jun.', 'jul.', 'awg.', 'sep.', 'okt.', 'now.', 'dec.' ], [ 'januara', 'februara', 'měrca', 'apryla', 'maja', 'junija', 'julija', 'awgusta', 'septembra', 'oktobra', 'nowembra', 'decembra' ] ], [ ['j', 'f', 'm', 'a', 'm', 'j', 'j', 'a', 's', 'o', 'n', 'd'], ['jan', 'feb', 'měr', 'apr', 'maj', 'jun', 'jul', 'awg', 'sep', 'okt', 'now', 'dec'], [ 'januar', 'februar', 'měrc', 'apryl', 'maj', 'junij', 'julij', 'awgust', 'september', 'oktober', 'nowember', 'december' ] ], [['pś.Chr.n.', 'pó Chr.n.'], , ['pśed Kristusowym naroźenim', 'pó Kristusowem naroźenju']], 1, [6, 0], ['d.M.yy', 'd.M.y', 'd. MMMM y', 'EEEE, d. MMMM y'], ['H:mm', 'H:mm:ss', 'H:mm:ss z', 'H:mm:ss zzzz'], [ '{1} {0}', , , ], [',', '.', ';', '%', '+', '-', 'E', '·', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], '€', 'euro', plural ];
plural
identifier_name
dsb.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number): number
export default [ 'dsb', [ ['dop.', 'wótp.'], ['dopołdnja', 'wótpołdnja'], ], [ ['dopołdnja', 'wótpołdnja'], , ], [ ['n', 'p', 'w', 's', 's', 'p', 's'], ['nje', 'pón', 'wał', 'srj', 'stw', 'pět', 'sob'], ['njeźela', 'pónjeźele', 'wałtora', 'srjoda', 'stwórtk', 'pětk', 'sobota'], ['nj', 'pó', 'wa', 'sr', 'st', 'pě', 'so'] ], , [ ['j', 'f', 'm', 'a', 'm', 'j', 'j', 'a', 's', 'o', 'n', 'd'], [ 'jan.', 'feb.', 'měr.', 'apr.', 'maj.', 'jun.', 'jul.', 'awg.', 'sep.', 'okt.', 'now.', 'dec.' ], [ 'januara', 'februara', 'měrca', 'apryla', 'maja', 'junija', 'julija', 'awgusta', 'septembra', 'oktobra', 'nowembra', 'decembra' ] ], [ ['j', 'f', 'm', 'a', 'm', 'j', 'j', 'a', 's', 'o', 'n', 'd'], ['jan', 'feb', 'měr', 'apr', 'maj', 'jun', 'jul', 'awg', 'sep', 'okt', 'now', 'dec'], [ 'januar', 'februar', 'měrc', 'apryl', 'maj', 'junij', 'julij', 'awgust', 'september', 'oktober', 'nowember', 'december' ] ], [['pś.Chr.n.', 'pó Chr.n.'], , ['pśed Kristusowym naroźenim', 'pó Kristusowem naroźenju']], 1, [6, 0], ['d.M.yy', 'd.M.y', 'd. MMMM y', 'EEEE, d. MMMM y'], ['H:mm', 'H:mm:ss', 'H:mm:ss z', 'H:mm:ss zzzz'], [ '{1} {0}', , , ], [',', '.', ';', '%', '+', '-', 'E', '·', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], '€', 'euro', plural ];
{ let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length, f = parseInt(n.toString().replace(/^[^.]*\.?/, ''), 10) || 0; if (v === 0 && i % 100 === 1 || f % 100 === 1) return 1; if (v === 0 && i % 100 === 2 || f % 100 === 2) return 2; if (v === 0 && i % 100 === Math.floor(i % 100) && i % 100 >= 3 && i % 100 <= 4 || f % 100 === Math.floor(f % 100) && f % 100 >= 3 && f % 100 <= 4) return 3; return 5; }
identifier_body
util_spec.js
/*************************GO-LICENSE-START********************************* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END**********************************/ describe("util", function () { beforeEach(function () { setFixtures("<input type=\"hidden\" value=\"1287652847\" name=\"server_time\" id=\"server_timestamp\"/>\n" + "<div class='under_test'>\n" + " <span id=\"clickable\">clickable</span>\n" + " <span title=\"1287651018131\" id=\"time_field\"></span>\n" + " <input type=\"hidden\" value=\"1287651018131\"> \n" + "\n" + " <div id=\"populatable\" class=\"\"></div>\n" + " <input type=\"hidden\" id=\"shilpa_needs_to_work_more\"/>\n" + " <button type=\"button\" id=\"btn\" name=\"button\">Push the button</button>\n" + "\n" + " <a href=\"#\" id=\"foo_link\">name_foo</a>\n" + " <input id=\"baz_input\" value=\"name_baz\"/>\n" + "\n" + " <textarea id=\"id_bar\">id bar text</textarea>\n" + " <textarea id=\"id_quux\">id quux text</textarea>\n" + " <div id=\"update_on_evt\">Original content</div>\n" + "</div>"); }); var populatable; var orignialAjax = jQuery.ajax; afterEach(function () { jQuery.ajax = orignialAjax; } ); beforeEach(function () { populatable = $('populatable'); populatable.update(""); }); afterEach(function () { populatable.update(""); }); it("test_executes_javascript_on_event", function () { Util.on_load(function () { populatable.update("foo bar"); }); window.load; assertEquals("foo bar", populatable.innerHTML); }); it("test_executes_javascript_if_event_has_been_fired", function () { window.load; Util.on_load(function () { populatable.update("foo bar1"); }); assertEquals("foo bar1", populatable.innerHTML); }); it("test_appends_child_with_given_text_to_the_given_id", function () { Util.refresh_child_text('populatable', "This text gets overridden", "success"); Util.refresh_child_text('populatable', "second text", "success"); assertEquals(1, populatable.getElementsBySelector("p").length); var p = populatable.down('p'); assertEquals("second text", p.innerHTML); assertTrue("Should have class name", p.hasClassName("success")); }); it("test_does_not_execute_handler_except_for_the_first_time_the_event_is_fired", function () { Util.on_load(function () { populatable.update("foo bar1"); }); window.load; Util.on_load(function () { populatable.update("foo bar2"); }); populatable.update("bar baz"); window.load; assertEquals("bar baz", populatable.innerHTML); }); it("test_set_value", function () { var call_back = Util.set_value('shilpa_needs_to_work_more', "foo"); call_back(); assertEquals("foo", $('shilpa_needs_to_work_more').value); }); it("test_enable_disable", function () { Util.disable("btn"); assertTrue($("btn").disabled);
Util.enable("btn"); assertFalse($("btn").disabled); assertFalse($("btn").hasClassName("disabled")); }); it("test_escapeDotsFromId", function () { assertEquals("#2\\.1\\.1\\.2", Util.escapeDotsFromId("2.1.1.2")); }); it("test_ajax_modal_success", function () { var ajax_options = null; var ajax_request = {}; jQuery.ajax = function (options) { ajax_options = options; return ajax_request; }; ajax_request.done = function (func) { func(); }; ajax_request.fail = function (func) { }; ajax_request.responseText = 'response_body'; var modal_box_options = null; var modal_box_content = null; Modalbox.show = function (data) { modal_box_content = data; }; Util.ajax_modal("some_url", {title: "some_title"}); assertEquals("some_url", ajax_options.url); assertContains('response_body', modal_box_content); }); it("test_ajax_modal_failure", function () { var ajax_options = null; var ajax_request = {}; jQuery.ajax = function (options) { ajax_options = options; return ajax_request; }; ajax_request.done = function (func) { }; ajax_request.fail = function (func) { func(); }; ajax_request.responseText = 'response_body'; var modal_box_options = null; var modal_box_content = null; Modalbox.show = function (data, options) { modal_box_content = data; modal_box_options = options; }; Util.ajax_modal("some_url", {title: "some_title"}); assertEquals("some_url", ajax_options.url); assertContains('response_body', jQuery(modal_box_content)[0].innerHTML); }); it("test_updates_dom_elements_on_callback", function () { var mapping = {name_foo: "id_bar", name_baz: "id_quux"}; jQuery('#foo_link').click(Util.domUpdatingCallback(mapping, jQuery('#update_on_evt'), function () { return this.innerHTML; })); jQuery('#baz_input').click(Util.domUpdatingCallback(mapping, jQuery('#update_on_evt'), function () { return this.value; })); assertEquals("Original content", jQuery('#update_on_evt').text()); fire_event($("foo_link"), 'click'); assertEquals("id bar text", jQuery('#update_on_evt').text()); fire_event($("baz_input"), 'click'); assertEquals("id quux text", jQuery('#update_on_evt').text()); }); }); describe("disable input fields", function () { beforeEach(function () { setFixtures("<div id='search_users_table' class='users_table'>\n" + "<input type='hidden'\n" + "id='foo'\n" + "name='foo'\n" + "value='foo'\n" + "/>\n" + "<input type='hidden'\n" + "id='bar'\n" + "name='bar'\n" + "value='bar'\n" + "/>\n" + "</div>"); }); it("should disable all hidden input fields", function () { assertFalse(jQuery("#foo")[0].disabled); assertFalse(jQuery("#bar")[0].disabled); Util.disable_all_hidden_fields("#search_users_table"); assertTrue(jQuery("#foo")[0].disabled); assertTrue(jQuery("#bar")[0].disabled); }); });
assertTrue($("btn").hasClassName("disabled"));
random_line_split
record-pat.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum t1 { a(int), b(uint), } struct T2 {x: t1, y: int} enum t3 { c(T2, uint), } fn m(input: t3) -> int { match input { c(T2 {x: a(m), ..}, _) => { return m; } c(T2 {x: b(m), y: y}, z) => { return ((m + z) as int) + y; } } } pub fn main() { assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); }
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
record-pat.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum t1 { a(int), b(uint), } struct T2 {x: t1, y: int} enum t3 { c(T2, uint), } fn m(input: t3) -> int { match input { c(T2 {x: a(m), ..}, _) => { return m; } c(T2 {x: b(m), y: y}, z) =>
} } pub fn main() { assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); }
{ return ((m + z) as int) + y; }
conditional_block
record-pat.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum t1 { a(int), b(uint), } struct T2 {x: t1, y: int} enum t3 { c(T2, uint), } fn m(input: t3) -> int { match input { c(T2 {x: a(m), ..}, _) => { return m; } c(T2 {x: b(m), y: y}, z) => { return ((m + z) as int) + y; } } } pub fn main()
{ assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); }
identifier_body
record-pat.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum t1 { a(int), b(uint), } struct
{x: t1, y: int} enum t3 { c(T2, uint), } fn m(input: t3) -> int { match input { c(T2 {x: a(m), ..}, _) => { return m; } c(T2 {x: b(m), y: y}, z) => { return ((m + z) as int) + y; } } } pub fn main() { assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); }
T2
identifier_name
Gruntfile.js
/* License: MIT. * Copyright (C) 2013, 2014, Uri Shaked. */ 'use strict'; module.exports = function (grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ karma: { unit: { configFile: 'karma.conf.js', singleRun: true } }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'angular-moment.js', 'tests.js' ] }, uglify: { dist: { files: { 'angular-moment.min.js': 'angular-moment.js' }
'jshint', 'karma' ]); grunt.registerTask('build', [ 'jshint', 'uglify' ]); grunt.registerTask('default', ['build']); };
} } }); grunt.registerTask('test', [
random_line_split
conf.py
# -*- coding: utf-8 -*- # # hdfs documentation build configuration file, created by # sphinx-quickstart on Thu Mar 6 16:04:56 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import mock MOCK_MODULES = ['numpy', 'pandas', 'requests_kerberos'] for mod_name in MOCK_MODULES:
# If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'HdfsCLI' copyright = u'2014' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # import hdfs # The short X.Y version. version = hdfs.__version__.rsplit('.', 1)[0] # The full version, including alpha/beta/rc tags. release = hdfs.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # Autodoc autoclass_content = 'both' # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] html_static_path = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'hdfsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'hdfs.tex', u'hdfs Documentation', u'Author', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'hdfs', u'hdfs documentation', [u'Author'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'hdfs', u'hdfs documentation', u'Author', 'hdfs', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'hdfs' epub_author = u'Author' epub_publisher = u'Author' epub_copyright = u'2014, Author' # The basename for the epub file. It defaults to the project name. #epub_basename = u'hdfs' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True
sys.modules[mod_name] = mock.Mock()
conditional_block
conf.py
# -*- coding: utf-8 -*- # # hdfs documentation build configuration file, created by # sphinx-quickstart on Thu Mar 6 16:04:56 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import mock MOCK_MODULES = ['numpy', 'pandas', 'requests_kerberos'] for mod_name in MOCK_MODULES: sys.modules[mod_name] = mock.Mock() # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'HdfsCLI' copyright = u'2014' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # import hdfs # The short X.Y version. version = hdfs.__version__.rsplit('.', 1)[0] # The full version, including alpha/beta/rc tags. release = hdfs.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # Autodoc autoclass_content = 'both' # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] html_static_path = [] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None
# -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'hdfs.tex', u'hdfs Documentation', u'Author', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'hdfs', u'hdfs documentation', [u'Author'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'hdfs', u'hdfs documentation', u'Author', 'hdfs', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'hdfs' epub_author = u'Author' epub_publisher = u'Author' epub_copyright = u'2014, Author' # The basename for the epub file. It defaults to the project name. #epub_basename = u'hdfs' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the PIL. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True
# Output file base name for HTML help builder. htmlhelp_basename = 'hdfsdoc'
random_line_split
sintesi-richiesta.model.ts
import {Tipologia} from './tipologia.model'; import {Sede} from './sede.model'; import {Localita} from './localita.model'; import {Richiedente} from './richiedente.model'; import {Fonogramma} from './fonogramma.model'; import {Complessita} from './complessita.model'; import { Partenza } from './partenza.model'; import { Operatore } from './operatore.model'; import {Evento} from './evento.model'; /** * Modella la sintesi della richiesta di assistenza, con tutti i dati necessari * ad alimentare il primo ed il secondo livello di zoom. Non include il dettaglio * degli eventi della richiesta. */ export class SintesiRichiesta { constructor( /** * id */ public id: string, /** * E' il codice della Richiesta di Assistenza */ public codice: string,
/** * ricezione della richiesta (via telefono, ecc.) */ public istanteRicezioneRichiesta: Date, /** * Indica lo stato della richiesa di soccorso */ public stato: string, /** * priorita della richiesta (da 0 a 4). 0 = Altissima, 1 = Alta, 2 = Media, * 3 = Bassa, 4 = Bassissima. */ public priorita: number, /** * descrizione delle tipologie */ public tipologie: Tipologia[], /** * descrizione della richiesta */ public descrizione: string, /** * descrizione del richiedente */ public richiedente: Richiedente, /** * descrizione della località dell'evento */ public localita: Localita, /** * descrizione delle sedi di prima, seconda e terza competenza */ public competenze: Sede[], /** * indice di complessità dell'intervento (per es. numero di eventi collegati alla richiesta) */ public complessita: Complessita, /** * eventuale istante di presa in carico della richiesta */ public istantePresaInCarico?: Date, /** * eventuale istante di prima assegnazione di risorse alla richiesta */ public istantePrimaAssegnazione?: Date, /** * Indica se la richiesta è rilevante */ public rilevanza?: Date, /** * codice della scheda NUE */ public codiceSchedaNue?: string, /** * descrizione delle zone di emergenza */ public zoneEmergenza?: string[], /** * codice dello stato di invio del fonogramma (0 = Non necessario, 1 = Da inviare, * 2 = Inviato). Utile a calcolare il colore della segnalazione. */ public fonogramma?: Fonogramma, /** * lista delle partenze */ public partenze?: Partenza[], /** * etichette associate all'intervento (per es. aPagamento, imp, ecc.) */ public etichette?: string[], ) { } }
/** * è l'operatore che inserisce la richiesta */ public operatore: Operatore,
random_line_split
sintesi-richiesta.model.ts
import {Tipologia} from './tipologia.model'; import {Sede} from './sede.model'; import {Localita} from './localita.model'; import {Richiedente} from './richiedente.model'; import {Fonogramma} from './fonogramma.model'; import {Complessita} from './complessita.model'; import { Partenza } from './partenza.model'; import { Operatore } from './operatore.model'; import {Evento} from './evento.model'; /** * Modella la sintesi della richiesta di assistenza, con tutti i dati necessari * ad alimentare il primo ed il secondo livello di zoom. Non include il dettaglio * degli eventi della richiesta. */ export class SintesiRichiesta {
( /** * id */ public id: string, /** * E' il codice della Richiesta di Assistenza */ public codice: string, /** * è l'operatore che inserisce la richiesta */ public operatore: Operatore, /** * ricezione della richiesta (via telefono, ecc.) */ public istanteRicezioneRichiesta: Date, /** * Indica lo stato della richiesa di soccorso */ public stato: string, /** * priorita della richiesta (da 0 a 4). 0 = Altissima, 1 = Alta, 2 = Media, * 3 = Bassa, 4 = Bassissima. */ public priorita: number, /** * descrizione delle tipologie */ public tipologie: Tipologia[], /** * descrizione della richiesta */ public descrizione: string, /** * descrizione del richiedente */ public richiedente: Richiedente, /** * descrizione della località dell'evento */ public localita: Localita, /** * descrizione delle sedi di prima, seconda e terza competenza */ public competenze: Sede[], /** * indice di complessità dell'intervento (per es. numero di eventi collegati alla richiesta) */ public complessita: Complessita, /** * eventuale istante di presa in carico della richiesta */ public istantePresaInCarico?: Date, /** * eventuale istante di prima assegnazione di risorse alla richiesta */ public istantePrimaAssegnazione?: Date, /** * Indica se la richiesta è rilevante */ public rilevanza?: Date, /** * codice della scheda NUE */ public codiceSchedaNue?: string, /** * descrizione delle zone di emergenza */ public zoneEmergenza?: string[], /** * codice dello stato di invio del fonogramma (0 = Non necessario, 1 = Da inviare, * 2 = Inviato). Utile a calcolare il colore della segnalazione. */ public fonogramma?: Fonogramma, /** * lista delle partenze */ public partenze?: Partenza[], /** * etichette associate all'intervento (per es. aPagamento, imp, ecc.) */ public etichette?: string[], ) { } }
constructor
identifier_name
UploadRosters.tsx
import * as React from "react"; import XLSX from 'xlsx' import request from 'request' export const UploadRosters = () => { const [schoolId, setSchoolId] = React.useState<Number>(); const [teachers, setTeachers] = React.useState<Array<any>>([]); const [students, setStudents] = React.useState<Array<any>>([]) function getAuthToken() { return document.getElementsByName('csrf-token')[0] ? document.getElementsByName('csrf-token')[0].content : 0; } function
(e) { setSchoolId(e.target.value) } function handleChangeFile(file) { const fileReader = new FileReader(); fileReader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array', }); const sheet1 = workbook.Sheets[workbook.SheetNames[0]] const sheet1Array = XLSX.utils.sheet_to_json(sheet1, {header:1}) const teachers = sheet1Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2]} }); const sheet2 = workbook.Sheets[workbook.SheetNames[1]] const sheet2Array = XLSX.utils.sheet_to_json(sheet2, {header:1}) const students = sheet2Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2], classroom: row[3], teacher_name: row[4], teacher_email: row[5]} }); setTeachers(teachers) setStudents(students) }; fileReader.readAsArrayBuffer(file); } function submitRosters() { request.post(`${process.env.DEFAULT_URL}/cms/rosters/upload_teachers_and_students`, { json: { authenticity_token: getAuthToken(), school_id: schoolId, teachers: teachers, students: students }}, (e, r, response) => { if (response.errors) { alert(response.errors) } else { alert("Rosters uploaded successfully!") } } ); } return ( <div> <h2>Upload Teacher and Student Rosters</h2> <div className="roster-input-container"> <label className="roster-school-id" htmlFor="school-id-input">School ID <p className="control" id="school-id-input"> <input aria-label="enter-school-id" className="input" defaultValue="" onChange={handleSchoolIdChange} type="text" /> </p> </label> </div> <p className="upload-paragraph">Please upload a spreadsheet following this template: <a href="https://docs.google.com/spreadsheets/d/1YSSrb1IQMd1X_dss6btt2OUKEDrgYTTY--A_Kqfsck4/edit#gid=783496308" rel="noopener noreferrer" target="_blank">Bulk Teachers and Student Roster Template</a></p> <p className="control"> <input accept=".xlsx" aria-label="upload-roster-csv" onChange={e => handleChangeFile(e.target.files[0])} type="file" /> </p> <button className="quill-button primary medium upload-rosters-button" onClick={submitRosters} type="button">Upload Rosters</button> </div> ) } export default UploadRosters
handleSchoolIdChange
identifier_name
UploadRosters.tsx
import * as React from "react"; import XLSX from 'xlsx' import request from 'request' export const UploadRosters = () => { const [schoolId, setSchoolId] = React.useState<Number>(); const [teachers, setTeachers] = React.useState<Array<any>>([]); const [students, setStudents] = React.useState<Array<any>>([]) function getAuthToken() { return document.getElementsByName('csrf-token')[0] ? document.getElementsByName('csrf-token')[0].content : 0; } function handleSchoolIdChange(e) { setSchoolId(e.target.value) } function handleChangeFile(file) { const fileReader = new FileReader(); fileReader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array', }); const sheet1 = workbook.Sheets[workbook.SheetNames[0]] const sheet1Array = XLSX.utils.sheet_to_json(sheet1, {header:1}) const teachers = sheet1Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2]} }); const sheet2 = workbook.Sheets[workbook.SheetNames[1]] const sheet2Array = XLSX.utils.sheet_to_json(sheet2, {header:1}) const students = sheet2Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2], classroom: row[3], teacher_name: row[4], teacher_email: row[5]} }); setTeachers(teachers) setStudents(students) }; fileReader.readAsArrayBuffer(file); } function submitRosters() { request.post(`${process.env.DEFAULT_URL}/cms/rosters/upload_teachers_and_students`, { json: { authenticity_token: getAuthToken(), school_id: schoolId, teachers: teachers, students: students }}, (e, r, response) => { if (response.errors)
else { alert("Rosters uploaded successfully!") } } ); } return ( <div> <h2>Upload Teacher and Student Rosters</h2> <div className="roster-input-container"> <label className="roster-school-id" htmlFor="school-id-input">School ID <p className="control" id="school-id-input"> <input aria-label="enter-school-id" className="input" defaultValue="" onChange={handleSchoolIdChange} type="text" /> </p> </label> </div> <p className="upload-paragraph">Please upload a spreadsheet following this template: <a href="https://docs.google.com/spreadsheets/d/1YSSrb1IQMd1X_dss6btt2OUKEDrgYTTY--A_Kqfsck4/edit#gid=783496308" rel="noopener noreferrer" target="_blank">Bulk Teachers and Student Roster Template</a></p> <p className="control"> <input accept=".xlsx" aria-label="upload-roster-csv" onChange={e => handleChangeFile(e.target.files[0])} type="file" /> </p> <button className="quill-button primary medium upload-rosters-button" onClick={submitRosters} type="button">Upload Rosters</button> </div> ) } export default UploadRosters
{ alert(response.errors) }
conditional_block
UploadRosters.tsx
import * as React from "react"; import XLSX from 'xlsx' import request from 'request' export const UploadRosters = () => { const [schoolId, setSchoolId] = React.useState<Number>(); const [teachers, setTeachers] = React.useState<Array<any>>([]); const [students, setStudents] = React.useState<Array<any>>([]) function getAuthToken() { return document.getElementsByName('csrf-token')[0] ? document.getElementsByName('csrf-token')[0].content : 0; } function handleSchoolIdChange(e) { setSchoolId(e.target.value) } function handleChangeFile(file)
function submitRosters() { request.post(`${process.env.DEFAULT_URL}/cms/rosters/upload_teachers_and_students`, { json: { authenticity_token: getAuthToken(), school_id: schoolId, teachers: teachers, students: students }}, (e, r, response) => { if (response.errors) { alert(response.errors) } else { alert("Rosters uploaded successfully!") } } ); } return ( <div> <h2>Upload Teacher and Student Rosters</h2> <div className="roster-input-container"> <label className="roster-school-id" htmlFor="school-id-input">School ID <p className="control" id="school-id-input"> <input aria-label="enter-school-id" className="input" defaultValue="" onChange={handleSchoolIdChange} type="text" /> </p> </label> </div> <p className="upload-paragraph">Please upload a spreadsheet following this template: <a href="https://docs.google.com/spreadsheets/d/1YSSrb1IQMd1X_dss6btt2OUKEDrgYTTY--A_Kqfsck4/edit#gid=783496308" rel="noopener noreferrer" target="_blank">Bulk Teachers and Student Roster Template</a></p> <p className="control"> <input accept=".xlsx" aria-label="upload-roster-csv" onChange={e => handleChangeFile(e.target.files[0])} type="file" /> </p> <button className="quill-button primary medium upload-rosters-button" onClick={submitRosters} type="button">Upload Rosters</button> </div> ) } export default UploadRosters
{ const fileReader = new FileReader(); fileReader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array', }); const sheet1 = workbook.Sheets[workbook.SheetNames[0]] const sheet1Array = XLSX.utils.sheet_to_json(sheet1, {header:1}) const teachers = sheet1Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2]} }); const sheet2 = workbook.Sheets[workbook.SheetNames[1]] const sheet2Array = XLSX.utils.sheet_to_json(sheet2, {header:1}) const students = sheet2Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2], classroom: row[3], teacher_name: row[4], teacher_email: row[5]} }); setTeachers(teachers) setStudents(students) }; fileReader.readAsArrayBuffer(file); }
identifier_body
UploadRosters.tsx
import * as React from "react"; import XLSX from 'xlsx' import request from 'request' export const UploadRosters = () => { const [schoolId, setSchoolId] = React.useState<Number>(); const [teachers, setTeachers] = React.useState<Array<any>>([]); const [students, setStudents] = React.useState<Array<any>>([]) function getAuthToken() { return document.getElementsByName('csrf-token')[0] ? document.getElementsByName('csrf-token')[0].content : 0; } function handleSchoolIdChange(e) { setSchoolId(e.target.value) } function handleChangeFile(file) { const fileReader = new FileReader(); fileReader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array', }); const sheet1 = workbook.Sheets[workbook.SheetNames[0]] const sheet1Array = XLSX.utils.sheet_to_json(sheet1, {header:1}) const teachers = sheet1Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2]} });
}); setTeachers(teachers) setStudents(students) }; fileReader.readAsArrayBuffer(file); } function submitRosters() { request.post(`${process.env.DEFAULT_URL}/cms/rosters/upload_teachers_and_students`, { json: { authenticity_token: getAuthToken(), school_id: schoolId, teachers: teachers, students: students }}, (e, r, response) => { if (response.errors) { alert(response.errors) } else { alert("Rosters uploaded successfully!") } } ); } return ( <div> <h2>Upload Teacher and Student Rosters</h2> <div className="roster-input-container"> <label className="roster-school-id" htmlFor="school-id-input">School ID <p className="control" id="school-id-input"> <input aria-label="enter-school-id" className="input" defaultValue="" onChange={handleSchoolIdChange} type="text" /> </p> </label> </div> <p className="upload-paragraph">Please upload a spreadsheet following this template: <a href="https://docs.google.com/spreadsheets/d/1YSSrb1IQMd1X_dss6btt2OUKEDrgYTTY--A_Kqfsck4/edit#gid=783496308" rel="noopener noreferrer" target="_blank">Bulk Teachers and Student Roster Template</a></p> <p className="control"> <input accept=".xlsx" aria-label="upload-roster-csv" onChange={e => handleChangeFile(e.target.files[0])} type="file" /> </p> <button className="quill-button primary medium upload-rosters-button" onClick={submitRosters} type="button">Upload Rosters</button> </div> ) } export default UploadRosters
const sheet2 = workbook.Sheets[workbook.SheetNames[1]] const sheet2Array = XLSX.utils.sheet_to_json(sheet2, {header:1}) const students = sheet2Array.slice(1).map((row: Array<String>) => { return { "name": row[0], "email": row[1], "password": row[2], classroom: row[3], teacher_name: row[4], teacher_email: row[5]}
random_line_split
setup.rs
use docopt_args::DocoptArgs; use ProtonConfig; use std::io::{self, BufRead, stdout, StdinLock, Write}; pub fn initial_setup(_args: DocoptArgs) { configure(ProtonConfig::default_config()) } pub fn configure(old_config: ProtonConfig)
// Gets a config value from user input. Uses default value if nothing is provided fn get_config_value<'a>(prompt: &'a str, default: String, handle: &'a mut StdinLock) -> String { print!("{} [{}]: ", prompt, default); let _ = stdout().flush(); let mut value = String::new(); handle.read_line(&mut value).expect("Failed to read line of user input"); value = value.trim().to_string(); if value == "" { value = default; } value }
{ // Setup IO stuff let stdin = io::stdin(); let mut handle = stdin.lock(); // Get config values let key_path = get_config_value("key_path", old_config.key, &mut handle); let vixen_folder = get_config_value("vixen_folder", old_config.vixen_folder, &mut handle); let vixen_converter_py = get_config_value("vixen_converter_py", old_config.vixen_converter_py, &mut handle); let default_dmx_channel = get_config_value("default_dmx_channel", old_config.default_dmx_channel.to_string(), &mut handle); // Create config file (overwrite if already there) let config = ProtonConfig::new( key_path.trim(), vixen_folder.trim(), vixen_converter_py.trim(), default_dmx_channel.parse::<u16>().expect("DMX channel not a valid u16") ); config.save() }
identifier_body
setup.rs
use docopt_args::DocoptArgs; use ProtonConfig; use std::io::{self, BufRead, stdout, StdinLock, Write}; pub fn initial_setup(_args: DocoptArgs) { configure(ProtonConfig::default_config()) } pub fn configure(old_config: ProtonConfig) { // Setup IO stuff let stdin = io::stdin(); let mut handle = stdin.lock();
// Get config values let key_path = get_config_value("key_path", old_config.key, &mut handle); let vixen_folder = get_config_value("vixen_folder", old_config.vixen_folder, &mut handle); let vixen_converter_py = get_config_value("vixen_converter_py", old_config.vixen_converter_py, &mut handle); let default_dmx_channel = get_config_value("default_dmx_channel", old_config.default_dmx_channel.to_string(), &mut handle); // Create config file (overwrite if already there) let config = ProtonConfig::new( key_path.trim(), vixen_folder.trim(), vixen_converter_py.trim(), default_dmx_channel.parse::<u16>().expect("DMX channel not a valid u16") ); config.save() } // Gets a config value from user input. Uses default value if nothing is provided fn get_config_value<'a>(prompt: &'a str, default: String, handle: &'a mut StdinLock) -> String { print!("{} [{}]: ", prompt, default); let _ = stdout().flush(); let mut value = String::new(); handle.read_line(&mut value).expect("Failed to read line of user input"); value = value.trim().to_string(); if value == "" { value = default; } value }
random_line_split
setup.rs
use docopt_args::DocoptArgs; use ProtonConfig; use std::io::{self, BufRead, stdout, StdinLock, Write}; pub fn initial_setup(_args: DocoptArgs) { configure(ProtonConfig::default_config()) } pub fn configure(old_config: ProtonConfig) { // Setup IO stuff let stdin = io::stdin(); let mut handle = stdin.lock(); // Get config values let key_path = get_config_value("key_path", old_config.key, &mut handle); let vixen_folder = get_config_value("vixen_folder", old_config.vixen_folder, &mut handle); let vixen_converter_py = get_config_value("vixen_converter_py", old_config.vixen_converter_py, &mut handle); let default_dmx_channel = get_config_value("default_dmx_channel", old_config.default_dmx_channel.to_string(), &mut handle); // Create config file (overwrite if already there) let config = ProtonConfig::new( key_path.trim(), vixen_folder.trim(), vixen_converter_py.trim(), default_dmx_channel.parse::<u16>().expect("DMX channel not a valid u16") ); config.save() } // Gets a config value from user input. Uses default value if nothing is provided fn
<'a>(prompt: &'a str, default: String, handle: &'a mut StdinLock) -> String { print!("{} [{}]: ", prompt, default); let _ = stdout().flush(); let mut value = String::new(); handle.read_line(&mut value).expect("Failed to read line of user input"); value = value.trim().to_string(); if value == "" { value = default; } value }
get_config_value
identifier_name
setup.rs
use docopt_args::DocoptArgs; use ProtonConfig; use std::io::{self, BufRead, stdout, StdinLock, Write}; pub fn initial_setup(_args: DocoptArgs) { configure(ProtonConfig::default_config()) } pub fn configure(old_config: ProtonConfig) { // Setup IO stuff let stdin = io::stdin(); let mut handle = stdin.lock(); // Get config values let key_path = get_config_value("key_path", old_config.key, &mut handle); let vixen_folder = get_config_value("vixen_folder", old_config.vixen_folder, &mut handle); let vixen_converter_py = get_config_value("vixen_converter_py", old_config.vixen_converter_py, &mut handle); let default_dmx_channel = get_config_value("default_dmx_channel", old_config.default_dmx_channel.to_string(), &mut handle); // Create config file (overwrite if already there) let config = ProtonConfig::new( key_path.trim(), vixen_folder.trim(), vixen_converter_py.trim(), default_dmx_channel.parse::<u16>().expect("DMX channel not a valid u16") ); config.save() } // Gets a config value from user input. Uses default value if nothing is provided fn get_config_value<'a>(prompt: &'a str, default: String, handle: &'a mut StdinLock) -> String { print!("{} [{}]: ", prompt, default); let _ = stdout().flush(); let mut value = String::new(); handle.read_line(&mut value).expect("Failed to read line of user input"); value = value.trim().to_string(); if value == ""
value }
{ value = default; }
conditional_block
main.ts
import WeCheat from '../src/WeCheat'; const qrcodeTerminal = require('qrcode-terminal'); (async () => { const wecheat: WeCheat = new WeCheat(); wecheat.on('qrcode', (qrcode, uuid) => { const loginUrl = qrcode.replace(/\/qrcode\//, '/l/'); console.log('qrcode', qrcode);
wecheat.on('login', (userInfo: UserInfo) => { console.log('login success', userInfo); }); wecheat.on('onReceiveMsg', (type, msg) => { console.log('onReceiveMsg', type, msg); }); wecheat.on('onModContactList', (modContactList) => { console.log('modContactList', modContactList); }); wecheat.on('disconnect', (reason, retry) => { console.log('disconnect by', reason, `Retry: ${retry}`); }); wecheat.on('reconnect', () => { console.log('reconnect'); }); await wecheat.login(); })().catch(e => console.error(e));
qrcodeTerminal.generate(loginUrl); });
random_line_split
GridFilters.js
/** * Ext.ux.grid.GridFilters v0.2.7 **/ Ext.namespace("Ext.ux.grid"); Ext.ux.grid.GridFilters = function(config){ this.filters = new Ext.util.MixedCollection(); this.filters.getKey = function(o){return o ? o.dataIndex : null}; for(var i=0, len=config.filters.length; i<len; i++) this.addFilter(config.filters[i]); this.deferredUpdate = new Ext.util.DelayedTask(this.reload, this); delete config.filters; Ext.apply(this, config); }; Ext.extend(Ext.ux.grid.GridFilters, Ext.util.Observable, { /** * @cfg {Integer} updateBuffer * Number of milisecond to defer store updates since the last filter change. */ updateBuffer: 500, /** * @cfg {String} paramPrefix * The url parameter prefix for the filters. */ paramPrefix: 'filter', /** * @cfg {String} fitlerCls * The css class to be applied to column headers that active filters. Defaults to 'ux-filterd-column' */ filterCls: 'ux-filtered-column', /** * @cfg {Boolean} local * True to use Ext.data.Store filter functions instead of server side filtering. */ local: false, /** * @cfg {Boolean} autoReload * True to automagicly reload the datasource when a filter change happens. */ autoReload: true, /** * @cfg {String} stateId * Name of the Ext.data.Store value to be used to store state information. */ stateId: undefined, /** * @cfg {Boolean} showMenu * True to show the filter menus */ showMenu: true, menuFilterText: 'Filters', init: function(grid){ if(grid instanceof Ext.grid.GridPanel){ this.grid = grid; this.store = this.grid.getStore(); if(this.local){ this.store.on('load', function(store){ store.filterBy(this.getRecordFilter()); }, this); } else { this.store.on('beforeload', this.onBeforeLoad, this); } this.grid.filters = this; this.grid.addEvents({"filterupdate": true}); grid.on("render", this.onRender, this); grid.on("beforestaterestore", this.applyState, this); grid.on("beforestatesave", this.saveState, this); } else if(grid instanceof Ext.PagingToolbar){ this.toolbar = grid; } }, /** private **/ applyState: function(grid, state){ this.suspendStateStore = true; this.clearFilters(); if(state.filters) for(var key in state.filters){ var filter = this.filters.get(key); if(filter){ filter.setValue(state.filters[key]); filter.setActive(true); } } this.deferredUpdate.cancel(); if(this.local) this.reload(); this.suspendStateStore = false; }, /** private **/ saveState: function(grid, state){ var filters = {}; this.filters.each(function(filter){ if(filter.active) filters[filter.dataIndex] = filter.getValue(); }); return state.filters = filters; }, /** private **/ onRender: function(){ var hmenu; if(this.showMenu){ hmenu = this.grid.getView().hmenu; this.sep = hmenu.addSeparator(); this.menu = hmenu.add(new Ext.menu.CheckItem({ text: this.menuFilterText, menu: new Ext.menu.Menu() })); this.menu.on('checkchange', this.onCheckChange, this); this.menu.on('beforecheckchange', this.onBeforeCheck, this); hmenu.on('beforeshow', this.onMenu, this); } this.grid.getView().on("refresh", this.onRefresh, this); this.updateColumnHeadings(this.grid.getView()); }, /** private **/ onMenu: function(filterMenu){ var filter = this.getMenuFilter(); if(filter){ this.menu.menu = filter.menu; this.menu.setChecked(filter.active, false); } this.menu.setVisible(filter !== undefined); this.sep.setVisible(filter !== undefined); }, /** private **/ onCheckChange: function(item, value){ this.getMenuFilter().setActive(value); }, /** private **/ onBeforeCheck: function(check, value){ return !value || this.getMenuFilter().isActivatable(); }, /** private **/ onStateChange: function(event, filter){ if(event == "serialize") return; if(filter == this.getMenuFilter()) this.menu.setChecked(filter.active, false); if(this.autoReload || this.local) this.deferredUpdate.delay(this.updateBuffer); var view = this.grid.getView(); this.updateColumnHeadings(view); this.grid.saveState(); this.grid.fireEvent('filterupdate', this, filter); }, /** private **/ onBeforeLoad: function(store, options){ options.params = options.params || {}; this.cleanParams(options.params); var params = this.buildQuery(this.getFilterData()); Ext.apply(options.params, params); }, /** private **/ onRefresh: function(view){ this.updateColumnHeadings(view); }, /** private **/ getMenuFilter: function(){ var view = this.grid.getView(); if(!view || view.hdCtxIndex === undefined) return null; return this.filters.get( view.cm.config[view.hdCtxIndex].dataIndex); }, /** private **/ updateColumnHeadings: function(view){ if(!view || !view.mainHd) return; var hds = view.mainHd.select('td').removeClass(this.filterCls); for(var i=0, len=view.cm.config.length; i<len; i++){ var filter = this.getFilter(view.cm.config[i].dataIndex); if(filter && filter.active) hds.item(i).addClass(this.filterCls); } }, /** private **/ reload: function(){ if(this.local){ this.grid.store.clearFilter(true); this.grid.store.filterBy(this.getRecordFilter()); } else { this.deferredUpdate.cancel(); var store = this.grid.store; if(this.toolbar){ var start = this.toolbar.paramNames.start; if(store.lastOptions && store.lastOptions.params && store.lastOptions.params[start]) store.lastOptions.params[start] = 0; } store.reload(); } }, /** * Method factory that generates a record validator for the filters active at the time * of invokation. * * @private */ getRecordFilter: function(){ var f = []; this.filters.each(function(filter){ if(filter.active) f.push(filter); }); var len = f.length; return function(record){ for(var i=0; i<len; i++) if(!f[i].validateRecord(record)) return false; return true; }; }, /** * Adds a filter to the collection. * * @param {Object/Ext.ux.grid.filter.Filter} config A filter configuration or a filter object. * * @return {Ext.ux.grid.filter.Filter} The existing or newly created filter object. */ addFilter: function(config){ var filter = config.menu ? config : new (this.getFilterClass(config.type))(config); this.filters.add(filter); Ext.util.Observable.capture(filter, this.onStateChange, this); return filter; }, /** * Returns a filter for the given dataIndex, if on exists. * * @param {String} dataIndex The dataIndex of the desired filter object. * * @return {Ext.ux.grid.filter.Filter} */ getFilter: function(dataIndex){ return this.filters.get(dataIndex); }, /** * Turns all filters off. This does not clear the configuration information. */ clearFilters: function(){ this.filters.each(function(filter){ filter.setActive(false); }); }, /** private **/ getFilterData: function(){ var filters = [], fields = this.grid.getStore().fields; this.filters.each(function(f){ if(f.active){ var d = [].concat(f.serialize()); for(var i=0, len=d.length; i<len; i++) filters.push({ field: f.dataIndex, data: d[i] }); } }); return filters; }, /** * Function to take structured filter data and 'flatten' it into query parameteres. The default function * will produce a query string of the form: * filters[0][field]=dataIndex&filters[0][data][param1]=param&filters[0][data][param2]=param... * * @param {Array} filters A collection of objects representing active filters and their configuration. * Each element will take the form of {field: dataIndex, data: filterConf}. dataIndex is not assured * to be unique as any one filter may be a composite of more basic filters for the same dataIndex. * * @return {Object} Query keys and values */ buildQuery: function(filters){ var p = {}; for(var i=0, len=filters.length; i<len; i++){ var f = filters[i]; var root = [this.paramPrefix, '[', i, ']'].join(''); p[root + '[field]'] = f.field;
for(var key in f.data) p[[dataPrefix, '[', key, ']'].join('')] = f.data[key]; } return p; }, /** * Removes filter related query parameters from the provided object. * * @param {Object} p Query parameters that may contain filter related fields. */ cleanParams: function(p){ var regex = new RegExp("^" + this.paramPrefix + "\[[0-9]+\]"); for(var key in p) if(regex.test(key)) delete p[key]; }, /** * Function for locating filter classes, overwrite this with your favorite * loader to provide dynamic filter loading. * * @param {String} type The type of filter to load. * * @return {Class} */ getFilterClass: function(type){ return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter']; } });
var dataPrefix = root + '[data]';
random_line_split
test-examples-server-pre-post-functions.js
/*jshint expr: true*/ "use strict"; var chai = require("chai"); var expect = chai.expect; chai.config.includeStack = true; var request = require("supertest"); var alexaAppServer = require("../index"); var fs = require("fs"); describe("Alexa App Server with Examples & Pre/Post functions", function() {
testServer = alexaAppServer.start({ port: 3000, server_root: 'examples', pre: function(appServer) { fired.pre = true; }, post: function(appServer) { fired.post = true; }, preRequest: function(json, request, response) { fired.preRequest = true; }, postRequest: function(json, request, response) { fired.postRequest = true; } }); sampleLaunchReq = JSON.parse(fs.readFileSync("test/sample-launch-req.json", 'utf8')); }); after(function() { testServer.stop(); }); it("mounts hello world app (GET)", function() { return request(testServer.express) .get('/alexa/hello_world') .expect(200).then(function(response) { expect(fired.pre).to.equal(true); expect(fired.post).to.equal(true); // only called for actual Alexa requests expect(fired.preRequest).to.equal(undefined); expect(fired.postRequest).to.equal(undefined); }); }); it("mounts hello world app (POST)", function() { return request(testServer.express) .post('/alexa/hello_world') .send(sampleLaunchReq) .expect(200).then(function(response) { expect(fired.pre).to.equal(true); expect(fired.post).to.equal(true); expect(fired.preRequest).to.equal(true); expect(fired.postRequest).to.equal(true); }); }); });
var testServer, fired; var sampleLaunchReq; before(function() { fired = {};
random_line_split
owrocanalysis.py
""" ROC Analysis Widget ------------------- """ import operator from functools import reduce, wraps from collections import namedtuple, deque import numpy import sklearn.metrics as skl_metrics from PyQt4 import QtGui from PyQt4.QtGui import QColor, QPen, QBrush from PyQt4.QtCore import Qt import pyqtgraph as pg import Orange from Orange.widgets import widget, gui, settings from Orange.widgets.utils import colorpalette, colorbrewer #: Points on a ROC curve ROCPoints = namedtuple( "ROCPoints", ["fpr", # (N,) array of false positive rate coordinates (ascending) "tpr", # (N,) array of true positive rate coordinates "thresholds" # (N,) array of thresholds (in descending order) ] ) ROCPoints.is_valid = property(lambda self: self.fpr.size > 0) #: ROC Curve and it's convex hull ROCCurve = namedtuple( "ROCCurve", ["points", # ROCPoints "hull" # ROCPoints of the convex hull ] ) ROCCurve.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged vertically ROCAveragedVert = namedtuple( "ROCAveragedVert", ["points", # ROCPoints sampled by fpr "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviation of tpr at each fpr point ] ) ROCAveragedVert.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged by thresholds ROCAveragedThresh = namedtuple( "ROCAveragedThresh", ["points", # ROCPoints sampled by threshold "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviations of tpr at each threshold "fpr_std" # array standard deviations of fpr at each threshold ] ) ROCAveragedThresh.is_valid = property(lambda self: self.points.is_valid) #: Combined data for a ROC curve of a single algorithm ROCData = namedtuple( "ROCData", ["merged", # ROCCurve merged over all folds "folds", # ROCCurve list, one for each fold "avg_vertical", # ROCAveragedVert "avg_threshold", # ROCAveragedThresh ] ) def ROCData_from_results(results, clf_index, target): """ Compute ROC Curve(s) from evaluation results. :param Orange.evaluation.Results results: Evaluation results. :param int clf_index: Learner index in the `results`. :param int target: Target class index (i.e. positive class). :rval ROCData: A instance holding the computed curves. """ merged = roc_curve_for_fold(results, slice(0, -1), clf_index, target) merged_curve = ROCCurve(ROCPoints(*merged), ROCPoints(*roc_curve_convex_hull(merged))) folds = results.folds if results.folds is not None else [slice(0, -1)] fold_curves = [] for fold in folds: # TODO: Check for no FP or no TP points = roc_curve_for_fold(results, fold, clf_index, target) hull = roc_curve_convex_hull(points) c = ROCCurve(ROCPoints(*points), ROCPoints(*hull)) fold_curves.append(c) curves = [fold.points for fold in fold_curves if fold.is_valid] fpr, tpr, std = roc_curve_vertical_average(curves) thresh = numpy.zeros_like(fpr) * numpy.nan hull = roc_curve_convex_hull((fpr, tpr, thresh)) v_avg = ROCAveragedVert( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), std ) all_thresh = numpy.hstack([t for _, _, t in curves]) all_thresh = numpy.clip(all_thresh, 0.0 - 1e-10, 1.0 + 1e-10) all_thresh = numpy.unique(all_thresh)[::-1] thresh = all_thresh[::max(all_thresh.size // 10, 1)] (fpr, fpr_std), (tpr, tpr_std) = \ roc_curve_threshold_average(curves, thresh) hull = roc_curve_convex_hull((fpr, tpr, thresh)) t_avg = ROCAveragedThresh( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), tpr_std, fpr_std ) return ROCData(merged_curve, fold_curves, v_avg, t_avg) ROCData.from_results = staticmethod(ROCData_from_results) #: A curve item to be displayed in a plot PlotCurve = namedtuple( "PlotCurve", ["curve", # ROCCurve source curve "curve_item", # pg.PlotDataItem main curve "hull_item" # pg.PlotDataItem curve's convex hull ] ) def plot_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=3, name=None):
PlotCurve.from_roc_curve = staticmethod(plot_curve) #: A curve displayed in a plot with error bars PlotAvgCurve = namedtuple( "PlotAvgCurve", ["curve", # ROCCurve "curve_item", # pg.PlotDataItem "hull_item", # pg.PlotDataItem "confint_item", # pg.ErrorBarItem ] ) def plot_avg_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=4, name=None): """ Construct a `PlotAvgCurve` for the given `curve`. :param curve: Source curve. :type curve: ROCAveragedVert or ROCAveragedThresh The other parameters are passed to pg.PlotDataItem :rtype: PlotAvgCurve """ pc = plot_curve(curve, pen=pen, shadow_pen=shadow_pen, symbol=symbol, symbol_size=symbol_size, name=name) points = curve.points if isinstance(curve, ROCAveragedVert): tpr_std = curve.tpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) elif isinstance(curve, ROCAveragedThresh): tpr_std, fpr_std = curve.tpr_std, curve.fpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], width=2 * fpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) return PlotAvgCurve(curve, pc.curve_item, pc.hull_item, error_item) PlotAvgCurve.from_roc_curve = staticmethod(plot_avg_curve) Some = namedtuple("Some", ["val"]) def once(f): """ Return a function that will be called only once, and it's result cached. """ cached = None @wraps(f) def wraped(): nonlocal cached if cached is None: cached = Some(f()) return cached.val return wraped plot_curves = namedtuple( "plot_curves", ["merge", # :: () -> PlotCurve "folds", # :: () -> [PlotCurve] "avg_vertical", # :: () -> PlotAvgCurve "avg_threshold", # :: () -> PlotAvgCurve ] ) class InfiniteLine(pg.InfiniteLine): """pyqtgraph.InfiniteLine extended to support antialiasing. """ def __init__(self, pos=None, angle=90, pen=None, movable=False, bounds=None, antialias=False): super().__init__(pos, angle, pen, movable, bounds) self.antialias = antialias def paint(self, painter, *args): if self.antialias: painter.setRenderHint(QtGui.QPainter.Antialiasing, True) super().paint(painter, *args) class OWROCAnalysis(widget.OWWidget): name = "ROC Analysis" description = ("Displays Receiver Operating Characteristics curve " + "based on evaluation of classifiers.") icon = "icons/ROCAnalysis.svg" priority = 1010 inputs = [ {"name": "Evaluation Results", "type": Orange.evaluation.Results, "handler": "set_results"} ] target_index = settings.Setting(0) selected_classifiers = [] display_perf_line = settings.Setting(True) display_def_threshold = settings.Setting(True) fp_cost = settings.Setting(500) fn_cost = settings.Setting(500) target_prior = settings.Setting(50.0) #: ROC Averaging Types Merge, Vertical, Threshold, NoAveraging = 0, 1, 2, 3 roc_averaging = settings.Setting(Merge) display_convex_hull = settings.Setting(False) display_convex_curve = settings.Setting(False) def __init__(self, parent=None): super().__init__(parent) self.results = None self.classifier_names = [] self.perf_line = None self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None box = gui.widgetBox(self.controlArea, "Plot") tbox = gui.widgetBox(box, "Target Class") tbox.setFlat(True) self.target_cb = gui.comboBox( tbox, self, "target_index", callback=self._on_target_changed) cbox = gui.widgetBox(box, "Classifiers") cbox.setFlat(True) self.classifiers_list_box = gui.listBox( cbox, self, "selected_classifiers", "classifier_names", selectionMode=QtGui.QListView.MultiSelection, callback=self._on_classifiers_changed) abox = gui.widgetBox(box, "Combine ROC Curves From Folds") abox.setFlat(True) gui.comboBox(abox, self, "roc_averaging", items=["Merge predictions from folds", "Mean TP rate", "Mean TP and FP at threshold", "Show individual curves"], callback=self._replot) hbox = gui.widgetBox(box, "ROC Convex Hull") hbox.setFlat(True) gui.checkBox(hbox, self, "display_convex_curve", "Show convex ROC curves", callback=self._replot) gui.checkBox(hbox, self, "display_convex_hull", "Show ROC convex hull", callback=self._replot) box = gui.widgetBox(self.controlArea, "Analysis") gui.checkBox(box, self, "display_def_threshold", "Default threshold (0.5) point", callback=self._on_display_def_threshold_changed) gui.checkBox(box, self, "display_perf_line", "Show performance line", callback=self._on_display_perf_line_changed) grid = QtGui.QGridLayout() ibox = gui.indentedBox(box, orientation=grid) sp = gui.spin(box, self, "fp_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FP Cost"), 0, 0) grid.addWidget(sp, 0, 1) sp = gui.spin(box, self, "fn_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FN Cost")) grid.addWidget(sp, 1, 1) sp = gui.spin(box, self, "target_prior", 1, 99, callback=self._on_display_perf_line_changed) sp.setSuffix("%") sp.addAction(QtGui.QAction("Auto", sp)) grid.addWidget(QtGui.QLabel("Prior target class probability")) grid.addWidget(sp, 2, 1) self.plotview = pg.GraphicsView(background="w") self.plotview.setFrameStyle(QtGui.QFrame.StyledPanel) self.plot = pg.PlotItem() self.plot.getViewBox().setMenuEnabled(False) self.plot.getViewBox().setMouseEnabled(False, False) pen = QPen(self.palette().color(QtGui.QPalette.Text)) tickfont = QtGui.QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("FP Rate (1-Specificity)") axis = self.plot.getAxis("left") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("TP Rate (Sensitivity)") self.plot.showGrid(True, True, alpha=0.1) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0)) self.plotview.setCentralItem(self.plot) self.mainArea.layout().addWidget(self.plotview) def set_results(self, results): """Set the input evaluation results.""" self.clear() self.error(0) if results is not None: if results.data is None: self.error(0, "Give me data!!") results = None elif not isinstance(results.data.domain.class_var, Orange.data.DiscreteVariable): self.error(0, "Need discrete class variable") results = None self.results = results if results is not None: self._initialize(results) self._setup_plot() def clear(self): """Clear the widget state.""" self.results = None self.plot.clear() self.classifier_names = [] self.selected_classifiers = [] self.target_cb.clear() self.target_index = 0 self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None def _initialize(self, results): names = getattr(results, "learner_names", None) if names is None: names = ["#{}".format(i + 1) for i in range(len(results.predicted))] self.colors = colorpalette.ColorPaletteGenerator( len(names), colorbrewer.colorSchemes["qualitative"]["Dark2"]) self.classifier_names = names self.selected_classifiers = list(range(len(names))) for i in range(len(names)): listitem = self.classifiers_list_box.item(i) listitem.setIcon(colorpalette.ColorPixmap(self.colors[i])) class_var = results.data.domain.class_var self.target_cb.addItems(class_var.values) def curve_data(self, target, clf_idx): """Return `ROCData' for the given target and classifier.""" if (target, clf_idx) not in self._curve_data: data = ROCData.from_results(self.results, clf_idx, target) self._curve_data[target, clf_idx] = data return self._curve_data[target, clf_idx] def plot_curves(self, target, clf_idx): """Return a set of functions `plot_curves` generating plot curves.""" def generate_pens(basecolor): pen = QPen(basecolor, 1) pen.setCosmetic(True) shadow_pen = QPen(pen.color().lighter(160), 2.5) shadow_pen.setCosmetic(True) return pen, shadow_pen data = self.curve_data(target, clf_idx) if (target, clf_idx) not in self._plot_curves: pen, shadow_pen = generate_pens(self.colors[clf_idx]) name = self.classifier_names[clf_idx] @once def merged(): return plot_curve( data.merged, pen=pen, shadow_pen=shadow_pen, name=name) @once def folds(): return [plot_curve(fold, pen=pen, shadow_pen=shadow_pen) for fold in data.folds] @once def avg_vert(): return plot_avg_curve(data.avg_vertical, pen=pen, shadow_pen=shadow_pen, name=name) @once def avg_thres(): return plot_avg_curve(data.avg_threshold, pen=pen, shadow_pen=shadow_pen, name=name) self._plot_curves[target, clf_idx] = plot_curves( merge=merged, folds=folds, avg_vertical=avg_vert, avg_threshold=avg_thres ) return self._plot_curves[target, clf_idx] def _setup_plot(self): target = self.target_index selected = self.selected_classifiers curves = [self.plot_curves(target, i) for i in selected] selected = [self.curve_data(target, i) for i in selected] if self.roc_averaging == OWROCAnalysis.Merge: for curve in curves: graphics = curve.merge() curve = graphics.curve self.plot.addItem(graphics.curve_item) if self.display_convex_curve: self.plot.addItem(graphics.hull_item) if self.display_def_threshold: points = curve.points ind = numpy.argmin(numpy.abs(points.thresholds - 0.5)) item = pg.TextItem( text="{:.3f}".format(points.thresholds[ind]), ) item.setPos(points.fpr[ind], points.tpr[ind]) self.plot.addItem(item) hull_curves = [curve.merged.hull for curve in selected] if hull_curves: self._rocch = convex_hull(hull_curves) iso_pen = QPen(QColor(Qt.black), 1) iso_pen.setCosmetic(True) self._perf_line = InfiniteLine(pen=iso_pen, antialias=True) self.plot.addItem(self._perf_line) elif self.roc_averaging == OWROCAnalysis.Vertical: for curve in curves: graphics = curve.avg_vertical() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_vertical.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.Threshold: for curve in curves: graphics = curve.avg_threshold() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_threshold.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.NoAveraging: for curve in curves: graphics = curve.folds() for fold in graphics: self.plot.addItem(fold.curve_item) if self.display_convex_curve: self.plot.addItem(fold.hull_item) hull_curves = [fold.hull for curve in selected for fold in curve.folds] if self.display_convex_hull and hull_curves: hull = convex_hull(hull_curves) hull_pen = QPen(QColor(200, 200, 200, 100), 2) hull_pen.setCosmetic(True) item = self.plot.plot( hull.fpr, hull.tpr, pen=hull_pen, brush=QBrush(QColor(200, 200, 200, 50)), fillLevel=0) item.setZValue(-10000) pen = QPen(QColor(100, 100, 100, 100), 1, Qt.DashLine) pen.setCosmetic(True) self.plot.plot([0, 1], [0, 1], pen=pen, antialias=True) if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() def _on_target_changed(self): self.plot.clear() self._setup_plot() def _on_classifiers_changed(self): self.plot.clear() if self.results is not None: self._setup_plot() def _on_display_perf_line_changed(self): if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() if self.perf_line is not None: self.perf_line.setVisible(self.display_perf_line) def _on_display_def_threshold_changed(self): self._replot() def _replot(self): self.plot.clear() if self.results is not None: self._setup_plot() def _update_perf_line(self): if self._perf_line is None: return self._perf_line.setVisible(self.display_perf_line) if self.display_perf_line: m = roc_iso_performance_slope( self.fp_cost, self.fn_cost, self.target_prior / 100.0) hull = self._rocch ind = roc_iso_performance_line(m, hull) angle = numpy.arctan2(m, 1) # in radians self._perf_line.setAngle(angle * 180 / numpy.pi) self._perf_line.setPos((hull.fpr[ind[0]], hull.tpr[ind[0]])) def onDeleteWidget(self): self.clear() def interp(x, xp, fp, left=None, right=None): """ Like numpy.interp except for handling of running sequences of same values in `xp`. """ x = numpy.asanyarray(x) xp = numpy.asanyarray(xp) fp = numpy.asanyarray(fp) if xp.shape != fp.shape: raise ValueError("xp and fp must have the same shape") ind = numpy.searchsorted(xp, x, side="right") fx = numpy.zeros(len(x)) under = ind == 0 over = ind == len(xp) between = ~under & ~over fx[under] = left if left is not None else fp[0] fx[over] = right if right is not None else fp[-1] if right is not None: # Fix points exactly on the right boundary. fx[x == xp[-1]] = fp[-1] ind = ind[between] df = (fp[ind] - fp[ind - 1]) / (xp[ind] - xp[ind - 1]) fx[between] = df * (x[between] - xp[ind]) + fp[ind] return fx def roc_curve_for_fold(res, fold, clf_idx, target): fold_actual = res.actual[fold] P = numpy.sum(fold_actual == target) N = fold_actual.size - P if P == 0 or N == 0: # Undefined TP and FP rate return numpy.array([]), numpy.array([]), numpy.array([]) fold_probs = res.probabilities[clf_idx][fold][:, target] return skl_metrics.roc_curve( fold_actual, fold_probs, pos_label=target ) def roc_curve_vertical_average(curves, samples=10): fpr_sample = numpy.linspace(0.0, 1.0, samples) tpr_samples = [] for fpr, tpr, _ in curves: tpr_samples.append(interp(fpr_sample, fpr, tpr, left=0, right=1)) tpr_samples = numpy.array(tpr_samples) return fpr_sample, tpr_samples.mean(axis=0), tpr_samples.std(axis=0) def roc_curve_threshold_average(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: ind = numpy.searchsorted(thresh[::-1], thresh_samples, side="left") ind = ind[::-1] ind = numpy.clip(ind, 0, len(thresh) - 1) fpr_samples.append(fpr[ind]) tpr_samples.append(tpr[ind]) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) def roc_curve_threshold_average_interp(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: thresh = thresh[::-1] fpr = interp(thresh_samples, thresh, fpr[::-1], left=1.0, right=0.0) tpr = interp(thresh_samples, thresh, tpr[::-1], left=1.0, right=0.0) fpr_samples.append(fpr) tpr_samples.append(tpr) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) roc_point = namedtuple("roc_point", ["fpr", "tpr", "threshold"]) def roc_curve_convex_hull(curve): def slope(p1, p2): x1, y1, _ = p1 x2, y2, _ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf fpr, _, _ = curve if len(fpr) <= 2: return curve points = map(roc_point._make, zip(*curve)) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point.fpr != last.fpr and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() fpr = numpy.array([p.fpr for p in hull]) tpr = numpy.array([p.tpr for p in hull]) thres = numpy.array([p.threshold for p in hull]) return (fpr, tpr, thres) def convex_hull(curves): def slope(p1, p2): x1, y1, *_ = p1 x2, y2, *_ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf curves = [list(map(roc_point._make, zip(*curve))) for curve in curves] merged_points = reduce(operator.iadd, curves, []) merged_points = sorted(merged_points) if len(merged_points) == 0: return ROCPoints(numpy.array([]), numpy.array([]), numpy.array([])) if len(merged_points) <= 2: return ROCPoints._make(map(numpy.array, zip(*merged_points))) points = iter(merged_points) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point[0] != last[0] and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() return ROCPoints._make(map(numpy.array, zip(*hull))) def roc_iso_performance_line(slope, hull, tol=1e-5): """ Return the indices where a line with `slope` touches the ROC convex hull. """ fpr, tpr, *_ = hull # Compute the distance of each point to a reference iso line # going through point (0, 1). The point(s) with the minimum # distance are our result # y = m * x + 1 # m * x - 1y + 1 = 0 a, b, c = slope, -1, 1 dist = distance_to_line(a, b, c, fpr, tpr) mindist = numpy.min(dist) return numpy.flatnonzero((dist - mindist) <= tol) def distance_to_line(a, b, c, x0, y0): """ Return the distance to a line ax + by + c = 0 """ assert a != 0 or b != 0 return numpy.abs(a * x0 + b * y0 + c) / numpy.sqrt(a ** 2 + b ** 2) def roc_iso_performance_slope(fp_cost, fn_cost, p): assert 0 <= p <= 1 if fn_cost * p == 0: return numpy.inf else: return (fp_cost * (1. - p)) / (fn_cost * p) def main(): import gc import sip from PyQt4.QtGui import QApplication from Orange.classification import (LogisticRegressionLearner, SVMLearner, NuSVMLearner) app = QApplication([]) w = OWROCAnalysis() w.show() w.raise_() # data = Orange.data.Table("iris") data = Orange.data.Table("ionosphere") results = Orange.evaluation.CrossValidation( data, [LogisticRegressionLearner(), LogisticRegressionLearner(penalty="l1"), SVMLearner(probability=True), NuSVMLearner(probability=True)], k=5, store_data=True, ) results.learner_names = ["Logistic", "Logistic (L1 reg.)", "SVM", "NuSVM"] w.set_results(results) rval = app.exec_() w.deleteLater() sip.delete(w) del w app.processEvents() sip.delete(app) del app gc.collect() return rval if __name__ == "__main__": import sys sys.exit(main())
""" Construct a `PlotCurve` for the given `ROCCurve`. :param ROCCurve curve: Source curve. The other parameters are passed to pg.PlotDataItem :rtype: PlotCurve """ def extend_to_origin(points): "Extend ROCPoints to include coordinate origin if not already present" if points.tpr.size and (points.tpr[0] > 0 or points.fpr[0] > 0): points = ROCPoints( numpy.r_[0, points.fpr], numpy.r_[0, points.tpr], numpy.r_[points.thresholds[0] + 1, points.thresholds] ) return points points = extend_to_origin(curve.points) item = pg.PlotCurveItem( points.fpr, points.tpr, pen=pen, shadowPen=shadow_pen, name=name, antialias=True ) sp = pg.ScatterPlotItem( curve.points.fpr, curve.points.tpr, symbol=symbol, size=symbol_size, pen=shadow_pen, name=name ) sp.setParentItem(item) hull = extend_to_origin(curve.hull) hull_item = pg.PlotDataItem( hull.fpr, hull.tpr, pen=pen, antialias=True ) return PlotCurve(curve, item, hull_item)
identifier_body
owrocanalysis.py
""" ROC Analysis Widget ------------------- """ import operator from functools import reduce, wraps from collections import namedtuple, deque import numpy import sklearn.metrics as skl_metrics from PyQt4 import QtGui from PyQt4.QtGui import QColor, QPen, QBrush from PyQt4.QtCore import Qt import pyqtgraph as pg import Orange from Orange.widgets import widget, gui, settings from Orange.widgets.utils import colorpalette, colorbrewer #: Points on a ROC curve ROCPoints = namedtuple( "ROCPoints", ["fpr", # (N,) array of false positive rate coordinates (ascending) "tpr", # (N,) array of true positive rate coordinates "thresholds" # (N,) array of thresholds (in descending order) ] ) ROCPoints.is_valid = property(lambda self: self.fpr.size > 0) #: ROC Curve and it's convex hull ROCCurve = namedtuple( "ROCCurve", ["points", # ROCPoints "hull" # ROCPoints of the convex hull ] ) ROCCurve.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged vertically ROCAveragedVert = namedtuple( "ROCAveragedVert", ["points", # ROCPoints sampled by fpr "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviation of tpr at each fpr point ] ) ROCAveragedVert.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged by thresholds ROCAveragedThresh = namedtuple( "ROCAveragedThresh", ["points", # ROCPoints sampled by threshold "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviations of tpr at each threshold "fpr_std" # array standard deviations of fpr at each threshold ] ) ROCAveragedThresh.is_valid = property(lambda self: self.points.is_valid) #: Combined data for a ROC curve of a single algorithm ROCData = namedtuple( "ROCData", ["merged", # ROCCurve merged over all folds "folds", # ROCCurve list, one for each fold "avg_vertical", # ROCAveragedVert "avg_threshold", # ROCAveragedThresh ] ) def ROCData_from_results(results, clf_index, target): """ Compute ROC Curve(s) from evaluation results. :param Orange.evaluation.Results results: Evaluation results. :param int clf_index: Learner index in the `results`. :param int target: Target class index (i.e. positive class). :rval ROCData: A instance holding the computed curves. """ merged = roc_curve_for_fold(results, slice(0, -1), clf_index, target) merged_curve = ROCCurve(ROCPoints(*merged), ROCPoints(*roc_curve_convex_hull(merged))) folds = results.folds if results.folds is not None else [slice(0, -1)] fold_curves = [] for fold in folds: # TODO: Check for no FP or no TP points = roc_curve_for_fold(results, fold, clf_index, target) hull = roc_curve_convex_hull(points) c = ROCCurve(ROCPoints(*points), ROCPoints(*hull)) fold_curves.append(c) curves = [fold.points for fold in fold_curves if fold.is_valid] fpr, tpr, std = roc_curve_vertical_average(curves) thresh = numpy.zeros_like(fpr) * numpy.nan hull = roc_curve_convex_hull((fpr, tpr, thresh)) v_avg = ROCAveragedVert( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), std ) all_thresh = numpy.hstack([t for _, _, t in curves]) all_thresh = numpy.clip(all_thresh, 0.0 - 1e-10, 1.0 + 1e-10) all_thresh = numpy.unique(all_thresh)[::-1] thresh = all_thresh[::max(all_thresh.size // 10, 1)] (fpr, fpr_std), (tpr, tpr_std) = \ roc_curve_threshold_average(curves, thresh) hull = roc_curve_convex_hull((fpr, tpr, thresh)) t_avg = ROCAveragedThresh( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), tpr_std, fpr_std ) return ROCData(merged_curve, fold_curves, v_avg, t_avg) ROCData.from_results = staticmethod(ROCData_from_results) #: A curve item to be displayed in a plot PlotCurve = namedtuple( "PlotCurve", ["curve", # ROCCurve source curve "curve_item", # pg.PlotDataItem main curve "hull_item" # pg.PlotDataItem curve's convex hull ] ) def plot_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=3, name=None): """ Construct a `PlotCurve` for the given `ROCCurve`. :param ROCCurve curve: Source curve. The other parameters are passed to pg.PlotDataItem :rtype: PlotCurve """ def extend_to_origin(points): "Extend ROCPoints to include coordinate origin if not already present" if points.tpr.size and (points.tpr[0] > 0 or points.fpr[0] > 0): points = ROCPoints( numpy.r_[0, points.fpr], numpy.r_[0, points.tpr], numpy.r_[points.thresholds[0] + 1, points.thresholds] ) return points points = extend_to_origin(curve.points) item = pg.PlotCurveItem( points.fpr, points.tpr, pen=pen, shadowPen=shadow_pen, name=name, antialias=True ) sp = pg.ScatterPlotItem( curve.points.fpr, curve.points.tpr, symbol=symbol, size=symbol_size, pen=shadow_pen, name=name ) sp.setParentItem(item) hull = extend_to_origin(curve.hull) hull_item = pg.PlotDataItem( hull.fpr, hull.tpr, pen=pen, antialias=True ) return PlotCurve(curve, item, hull_item) PlotCurve.from_roc_curve = staticmethod(plot_curve) #: A curve displayed in a plot with error bars PlotAvgCurve = namedtuple( "PlotAvgCurve", ["curve", # ROCCurve "curve_item", # pg.PlotDataItem "hull_item", # pg.PlotDataItem "confint_item", # pg.ErrorBarItem ] ) def plot_avg_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=4, name=None): """ Construct a `PlotAvgCurve` for the given `curve`. :param curve: Source curve. :type curve: ROCAveragedVert or ROCAveragedThresh The other parameters are passed to pg.PlotDataItem :rtype: PlotAvgCurve """ pc = plot_curve(curve, pen=pen, shadow_pen=shadow_pen, symbol=symbol, symbol_size=symbol_size, name=name) points = curve.points if isinstance(curve, ROCAveragedVert): tpr_std = curve.tpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) elif isinstance(curve, ROCAveragedThresh): tpr_std, fpr_std = curve.tpr_std, curve.fpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], width=2 * fpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) return PlotAvgCurve(curve, pc.curve_item, pc.hull_item, error_item) PlotAvgCurve.from_roc_curve = staticmethod(plot_avg_curve) Some = namedtuple("Some", ["val"]) def once(f): """ Return a function that will be called only once, and it's result cached. """ cached = None @wraps(f) def wraped(): nonlocal cached if cached is None: cached = Some(f()) return cached.val return wraped plot_curves = namedtuple( "plot_curves", ["merge", # :: () -> PlotCurve "folds", # :: () -> [PlotCurve] "avg_vertical", # :: () -> PlotAvgCurve "avg_threshold", # :: () -> PlotAvgCurve ] ) class InfiniteLine(pg.InfiniteLine): """pyqtgraph.InfiniteLine extended to support antialiasing. """ def __init__(self, pos=None, angle=90, pen=None, movable=False, bounds=None, antialias=False): super().__init__(pos, angle, pen, movable, bounds) self.antialias = antialias def paint(self, painter, *args): if self.antialias: painter.setRenderHint(QtGui.QPainter.Antialiasing, True) super().paint(painter, *args) class OWROCAnalysis(widget.OWWidget): name = "ROC Analysis" description = ("Displays Receiver Operating Characteristics curve " + "based on evaluation of classifiers.") icon = "icons/ROCAnalysis.svg" priority = 1010 inputs = [ {"name": "Evaluation Results", "type": Orange.evaluation.Results, "handler": "set_results"} ] target_index = settings.Setting(0) selected_classifiers = [] display_perf_line = settings.Setting(True) display_def_threshold = settings.Setting(True) fp_cost = settings.Setting(500) fn_cost = settings.Setting(500) target_prior = settings.Setting(50.0) #: ROC Averaging Types Merge, Vertical, Threshold, NoAveraging = 0, 1, 2, 3 roc_averaging = settings.Setting(Merge) display_convex_hull = settings.Setting(False) display_convex_curve = settings.Setting(False) def __init__(self, parent=None): super().__init__(parent) self.results = None self.classifier_names = [] self.perf_line = None self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None box = gui.widgetBox(self.controlArea, "Plot") tbox = gui.widgetBox(box, "Target Class") tbox.setFlat(True) self.target_cb = gui.comboBox( tbox, self, "target_index", callback=self._on_target_changed) cbox = gui.widgetBox(box, "Classifiers") cbox.setFlat(True) self.classifiers_list_box = gui.listBox( cbox, self, "selected_classifiers", "classifier_names", selectionMode=QtGui.QListView.MultiSelection, callback=self._on_classifiers_changed) abox = gui.widgetBox(box, "Combine ROC Curves From Folds") abox.setFlat(True) gui.comboBox(abox, self, "roc_averaging", items=["Merge predictions from folds", "Mean TP rate", "Mean TP and FP at threshold", "Show individual curves"], callback=self._replot) hbox = gui.widgetBox(box, "ROC Convex Hull") hbox.setFlat(True) gui.checkBox(hbox, self, "display_convex_curve", "Show convex ROC curves", callback=self._replot) gui.checkBox(hbox, self, "display_convex_hull", "Show ROC convex hull", callback=self._replot) box = gui.widgetBox(self.controlArea, "Analysis") gui.checkBox(box, self, "display_def_threshold", "Default threshold (0.5) point", callback=self._on_display_def_threshold_changed) gui.checkBox(box, self, "display_perf_line", "Show performance line", callback=self._on_display_perf_line_changed) grid = QtGui.QGridLayout() ibox = gui.indentedBox(box, orientation=grid) sp = gui.spin(box, self, "fp_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FP Cost"), 0, 0) grid.addWidget(sp, 0, 1) sp = gui.spin(box, self, "fn_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FN Cost")) grid.addWidget(sp, 1, 1) sp = gui.spin(box, self, "target_prior", 1, 99, callback=self._on_display_perf_line_changed) sp.setSuffix("%") sp.addAction(QtGui.QAction("Auto", sp)) grid.addWidget(QtGui.QLabel("Prior target class probability")) grid.addWidget(sp, 2, 1) self.plotview = pg.GraphicsView(background="w") self.plotview.setFrameStyle(QtGui.QFrame.StyledPanel) self.plot = pg.PlotItem() self.plot.getViewBox().setMenuEnabled(False) self.plot.getViewBox().setMouseEnabled(False, False) pen = QPen(self.palette().color(QtGui.QPalette.Text)) tickfont = QtGui.QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("FP Rate (1-Specificity)") axis = self.plot.getAxis("left") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("TP Rate (Sensitivity)") self.plot.showGrid(True, True, alpha=0.1) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0)) self.plotview.setCentralItem(self.plot) self.mainArea.layout().addWidget(self.plotview) def set_results(self, results): """Set the input evaluation results.""" self.clear() self.error(0) if results is not None: if results.data is None: self.error(0, "Give me data!!") results = None elif not isinstance(results.data.domain.class_var, Orange.data.DiscreteVariable): self.error(0, "Need discrete class variable") results = None self.results = results if results is not None: self._initialize(results) self._setup_plot() def clear(self): """Clear the widget state.""" self.results = None self.plot.clear() self.classifier_names = [] self.selected_classifiers = [] self.target_cb.clear() self.target_index = 0 self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None def _initialize(self, results): names = getattr(results, "learner_names", None) if names is None: names = ["#{}".format(i + 1) for i in range(len(results.predicted))] self.colors = colorpalette.ColorPaletteGenerator( len(names), colorbrewer.colorSchemes["qualitative"]["Dark2"]) self.classifier_names = names self.selected_classifiers = list(range(len(names))) for i in range(len(names)): listitem = self.classifiers_list_box.item(i) listitem.setIcon(colorpalette.ColorPixmap(self.colors[i])) class_var = results.data.domain.class_var self.target_cb.addItems(class_var.values) def curve_data(self, target, clf_idx): """Return `ROCData' for the given target and classifier.""" if (target, clf_idx) not in self._curve_data: data = ROCData.from_results(self.results, clf_idx, target) self._curve_data[target, clf_idx] = data return self._curve_data[target, clf_idx] def plot_curves(self, target, clf_idx): """Return a set of functions `plot_curves` generating plot curves.""" def generate_pens(basecolor): pen = QPen(basecolor, 1) pen.setCosmetic(True) shadow_pen = QPen(pen.color().lighter(160), 2.5) shadow_pen.setCosmetic(True) return pen, shadow_pen data = self.curve_data(target, clf_idx)
def merged(): return plot_curve( data.merged, pen=pen, shadow_pen=shadow_pen, name=name) @once def folds(): return [plot_curve(fold, pen=pen, shadow_pen=shadow_pen) for fold in data.folds] @once def avg_vert(): return plot_avg_curve(data.avg_vertical, pen=pen, shadow_pen=shadow_pen, name=name) @once def avg_thres(): return plot_avg_curve(data.avg_threshold, pen=pen, shadow_pen=shadow_pen, name=name) self._plot_curves[target, clf_idx] = plot_curves( merge=merged, folds=folds, avg_vertical=avg_vert, avg_threshold=avg_thres ) return self._plot_curves[target, clf_idx] def _setup_plot(self): target = self.target_index selected = self.selected_classifiers curves = [self.plot_curves(target, i) for i in selected] selected = [self.curve_data(target, i) for i in selected] if self.roc_averaging == OWROCAnalysis.Merge: for curve in curves: graphics = curve.merge() curve = graphics.curve self.plot.addItem(graphics.curve_item) if self.display_convex_curve: self.plot.addItem(graphics.hull_item) if self.display_def_threshold: points = curve.points ind = numpy.argmin(numpy.abs(points.thresholds - 0.5)) item = pg.TextItem( text="{:.3f}".format(points.thresholds[ind]), ) item.setPos(points.fpr[ind], points.tpr[ind]) self.plot.addItem(item) hull_curves = [curve.merged.hull for curve in selected] if hull_curves: self._rocch = convex_hull(hull_curves) iso_pen = QPen(QColor(Qt.black), 1) iso_pen.setCosmetic(True) self._perf_line = InfiniteLine(pen=iso_pen, antialias=True) self.plot.addItem(self._perf_line) elif self.roc_averaging == OWROCAnalysis.Vertical: for curve in curves: graphics = curve.avg_vertical() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_vertical.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.Threshold: for curve in curves: graphics = curve.avg_threshold() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_threshold.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.NoAveraging: for curve in curves: graphics = curve.folds() for fold in graphics: self.plot.addItem(fold.curve_item) if self.display_convex_curve: self.plot.addItem(fold.hull_item) hull_curves = [fold.hull for curve in selected for fold in curve.folds] if self.display_convex_hull and hull_curves: hull = convex_hull(hull_curves) hull_pen = QPen(QColor(200, 200, 200, 100), 2) hull_pen.setCosmetic(True) item = self.plot.plot( hull.fpr, hull.tpr, pen=hull_pen, brush=QBrush(QColor(200, 200, 200, 50)), fillLevel=0) item.setZValue(-10000) pen = QPen(QColor(100, 100, 100, 100), 1, Qt.DashLine) pen.setCosmetic(True) self.plot.plot([0, 1], [0, 1], pen=pen, antialias=True) if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() def _on_target_changed(self): self.plot.clear() self._setup_plot() def _on_classifiers_changed(self): self.plot.clear() if self.results is not None: self._setup_plot() def _on_display_perf_line_changed(self): if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() if self.perf_line is not None: self.perf_line.setVisible(self.display_perf_line) def _on_display_def_threshold_changed(self): self._replot() def _replot(self): self.plot.clear() if self.results is not None: self._setup_plot() def _update_perf_line(self): if self._perf_line is None: return self._perf_line.setVisible(self.display_perf_line) if self.display_perf_line: m = roc_iso_performance_slope( self.fp_cost, self.fn_cost, self.target_prior / 100.0) hull = self._rocch ind = roc_iso_performance_line(m, hull) angle = numpy.arctan2(m, 1) # in radians self._perf_line.setAngle(angle * 180 / numpy.pi) self._perf_line.setPos((hull.fpr[ind[0]], hull.tpr[ind[0]])) def onDeleteWidget(self): self.clear() def interp(x, xp, fp, left=None, right=None): """ Like numpy.interp except for handling of running sequences of same values in `xp`. """ x = numpy.asanyarray(x) xp = numpy.asanyarray(xp) fp = numpy.asanyarray(fp) if xp.shape != fp.shape: raise ValueError("xp and fp must have the same shape") ind = numpy.searchsorted(xp, x, side="right") fx = numpy.zeros(len(x)) under = ind == 0 over = ind == len(xp) between = ~under & ~over fx[under] = left if left is not None else fp[0] fx[over] = right if right is not None else fp[-1] if right is not None: # Fix points exactly on the right boundary. fx[x == xp[-1]] = fp[-1] ind = ind[between] df = (fp[ind] - fp[ind - 1]) / (xp[ind] - xp[ind - 1]) fx[between] = df * (x[between] - xp[ind]) + fp[ind] return fx def roc_curve_for_fold(res, fold, clf_idx, target): fold_actual = res.actual[fold] P = numpy.sum(fold_actual == target) N = fold_actual.size - P if P == 0 or N == 0: # Undefined TP and FP rate return numpy.array([]), numpy.array([]), numpy.array([]) fold_probs = res.probabilities[clf_idx][fold][:, target] return skl_metrics.roc_curve( fold_actual, fold_probs, pos_label=target ) def roc_curve_vertical_average(curves, samples=10): fpr_sample = numpy.linspace(0.0, 1.0, samples) tpr_samples = [] for fpr, tpr, _ in curves: tpr_samples.append(interp(fpr_sample, fpr, tpr, left=0, right=1)) tpr_samples = numpy.array(tpr_samples) return fpr_sample, tpr_samples.mean(axis=0), tpr_samples.std(axis=0) def roc_curve_threshold_average(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: ind = numpy.searchsorted(thresh[::-1], thresh_samples, side="left") ind = ind[::-1] ind = numpy.clip(ind, 0, len(thresh) - 1) fpr_samples.append(fpr[ind]) tpr_samples.append(tpr[ind]) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) def roc_curve_threshold_average_interp(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: thresh = thresh[::-1] fpr = interp(thresh_samples, thresh, fpr[::-1], left=1.0, right=0.0) tpr = interp(thresh_samples, thresh, tpr[::-1], left=1.0, right=0.0) fpr_samples.append(fpr) tpr_samples.append(tpr) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) roc_point = namedtuple("roc_point", ["fpr", "tpr", "threshold"]) def roc_curve_convex_hull(curve): def slope(p1, p2): x1, y1, _ = p1 x2, y2, _ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf fpr, _, _ = curve if len(fpr) <= 2: return curve points = map(roc_point._make, zip(*curve)) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point.fpr != last.fpr and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() fpr = numpy.array([p.fpr for p in hull]) tpr = numpy.array([p.tpr for p in hull]) thres = numpy.array([p.threshold for p in hull]) return (fpr, tpr, thres) def convex_hull(curves): def slope(p1, p2): x1, y1, *_ = p1 x2, y2, *_ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf curves = [list(map(roc_point._make, zip(*curve))) for curve in curves] merged_points = reduce(operator.iadd, curves, []) merged_points = sorted(merged_points) if len(merged_points) == 0: return ROCPoints(numpy.array([]), numpy.array([]), numpy.array([])) if len(merged_points) <= 2: return ROCPoints._make(map(numpy.array, zip(*merged_points))) points = iter(merged_points) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point[0] != last[0] and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() return ROCPoints._make(map(numpy.array, zip(*hull))) def roc_iso_performance_line(slope, hull, tol=1e-5): """ Return the indices where a line with `slope` touches the ROC convex hull. """ fpr, tpr, *_ = hull # Compute the distance of each point to a reference iso line # going through point (0, 1). The point(s) with the minimum # distance are our result # y = m * x + 1 # m * x - 1y + 1 = 0 a, b, c = slope, -1, 1 dist = distance_to_line(a, b, c, fpr, tpr) mindist = numpy.min(dist) return numpy.flatnonzero((dist - mindist) <= tol) def distance_to_line(a, b, c, x0, y0): """ Return the distance to a line ax + by + c = 0 """ assert a != 0 or b != 0 return numpy.abs(a * x0 + b * y0 + c) / numpy.sqrt(a ** 2 + b ** 2) def roc_iso_performance_slope(fp_cost, fn_cost, p): assert 0 <= p <= 1 if fn_cost * p == 0: return numpy.inf else: return (fp_cost * (1. - p)) / (fn_cost * p) def main(): import gc import sip from PyQt4.QtGui import QApplication from Orange.classification import (LogisticRegressionLearner, SVMLearner, NuSVMLearner) app = QApplication([]) w = OWROCAnalysis() w.show() w.raise_() # data = Orange.data.Table("iris") data = Orange.data.Table("ionosphere") results = Orange.evaluation.CrossValidation( data, [LogisticRegressionLearner(), LogisticRegressionLearner(penalty="l1"), SVMLearner(probability=True), NuSVMLearner(probability=True)], k=5, store_data=True, ) results.learner_names = ["Logistic", "Logistic (L1 reg.)", "SVM", "NuSVM"] w.set_results(results) rval = app.exec_() w.deleteLater() sip.delete(w) del w app.processEvents() sip.delete(app) del app gc.collect() return rval if __name__ == "__main__": import sys sys.exit(main())
if (target, clf_idx) not in self._plot_curves: pen, shadow_pen = generate_pens(self.colors[clf_idx]) name = self.classifier_names[clf_idx] @once
random_line_split
owrocanalysis.py
""" ROC Analysis Widget ------------------- """ import operator from functools import reduce, wraps from collections import namedtuple, deque import numpy import sklearn.metrics as skl_metrics from PyQt4 import QtGui from PyQt4.QtGui import QColor, QPen, QBrush from PyQt4.QtCore import Qt import pyqtgraph as pg import Orange from Orange.widgets import widget, gui, settings from Orange.widgets.utils import colorpalette, colorbrewer #: Points on a ROC curve ROCPoints = namedtuple( "ROCPoints", ["fpr", # (N,) array of false positive rate coordinates (ascending) "tpr", # (N,) array of true positive rate coordinates "thresholds" # (N,) array of thresholds (in descending order) ] ) ROCPoints.is_valid = property(lambda self: self.fpr.size > 0) #: ROC Curve and it's convex hull ROCCurve = namedtuple( "ROCCurve", ["points", # ROCPoints "hull" # ROCPoints of the convex hull ] ) ROCCurve.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged vertically ROCAveragedVert = namedtuple( "ROCAveragedVert", ["points", # ROCPoints sampled by fpr "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviation of tpr at each fpr point ] ) ROCAveragedVert.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged by thresholds ROCAveragedThresh = namedtuple( "ROCAveragedThresh", ["points", # ROCPoints sampled by threshold "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviations of tpr at each threshold "fpr_std" # array standard deviations of fpr at each threshold ] ) ROCAveragedThresh.is_valid = property(lambda self: self.points.is_valid) #: Combined data for a ROC curve of a single algorithm ROCData = namedtuple( "ROCData", ["merged", # ROCCurve merged over all folds "folds", # ROCCurve list, one for each fold "avg_vertical", # ROCAveragedVert "avg_threshold", # ROCAveragedThresh ] ) def ROCData_from_results(results, clf_index, target): """ Compute ROC Curve(s) from evaluation results. :param Orange.evaluation.Results results: Evaluation results. :param int clf_index: Learner index in the `results`. :param int target: Target class index (i.e. positive class). :rval ROCData: A instance holding the computed curves. """ merged = roc_curve_for_fold(results, slice(0, -1), clf_index, target) merged_curve = ROCCurve(ROCPoints(*merged), ROCPoints(*roc_curve_convex_hull(merged))) folds = results.folds if results.folds is not None else [slice(0, -1)] fold_curves = [] for fold in folds: # TODO: Check for no FP or no TP points = roc_curve_for_fold(results, fold, clf_index, target) hull = roc_curve_convex_hull(points) c = ROCCurve(ROCPoints(*points), ROCPoints(*hull)) fold_curves.append(c) curves = [fold.points for fold in fold_curves if fold.is_valid] fpr, tpr, std = roc_curve_vertical_average(curves) thresh = numpy.zeros_like(fpr) * numpy.nan hull = roc_curve_convex_hull((fpr, tpr, thresh)) v_avg = ROCAveragedVert( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), std ) all_thresh = numpy.hstack([t for _, _, t in curves]) all_thresh = numpy.clip(all_thresh, 0.0 - 1e-10, 1.0 + 1e-10) all_thresh = numpy.unique(all_thresh)[::-1] thresh = all_thresh[::max(all_thresh.size // 10, 1)] (fpr, fpr_std), (tpr, tpr_std) = \ roc_curve_threshold_average(curves, thresh) hull = roc_curve_convex_hull((fpr, tpr, thresh)) t_avg = ROCAveragedThresh( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), tpr_std, fpr_std ) return ROCData(merged_curve, fold_curves, v_avg, t_avg) ROCData.from_results = staticmethod(ROCData_from_results) #: A curve item to be displayed in a plot PlotCurve = namedtuple( "PlotCurve", ["curve", # ROCCurve source curve "curve_item", # pg.PlotDataItem main curve "hull_item" # pg.PlotDataItem curve's convex hull ] ) def plot_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=3, name=None): """ Construct a `PlotCurve` for the given `ROCCurve`. :param ROCCurve curve: Source curve. The other parameters are passed to pg.PlotDataItem :rtype: PlotCurve """ def extend_to_origin(points): "Extend ROCPoints to include coordinate origin if not already present" if points.tpr.size and (points.tpr[0] > 0 or points.fpr[0] > 0): points = ROCPoints( numpy.r_[0, points.fpr], numpy.r_[0, points.tpr], numpy.r_[points.thresholds[0] + 1, points.thresholds] ) return points points = extend_to_origin(curve.points) item = pg.PlotCurveItem( points.fpr, points.tpr, pen=pen, shadowPen=shadow_pen, name=name, antialias=True ) sp = pg.ScatterPlotItem( curve.points.fpr, curve.points.tpr, symbol=symbol, size=symbol_size, pen=shadow_pen, name=name ) sp.setParentItem(item) hull = extend_to_origin(curve.hull) hull_item = pg.PlotDataItem( hull.fpr, hull.tpr, pen=pen, antialias=True ) return PlotCurve(curve, item, hull_item) PlotCurve.from_roc_curve = staticmethod(plot_curve) #: A curve displayed in a plot with error bars PlotAvgCurve = namedtuple( "PlotAvgCurve", ["curve", # ROCCurve "curve_item", # pg.PlotDataItem "hull_item", # pg.PlotDataItem "confint_item", # pg.ErrorBarItem ] ) def plot_avg_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=4, name=None): """ Construct a `PlotAvgCurve` for the given `curve`. :param curve: Source curve. :type curve: ROCAveragedVert or ROCAveragedThresh The other parameters are passed to pg.PlotDataItem :rtype: PlotAvgCurve """ pc = plot_curve(curve, pen=pen, shadow_pen=shadow_pen, symbol=symbol, symbol_size=symbol_size, name=name) points = curve.points if isinstance(curve, ROCAveragedVert): tpr_std = curve.tpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) elif isinstance(curve, ROCAveragedThresh): tpr_std, fpr_std = curve.tpr_std, curve.fpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], width=2 * fpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) return PlotAvgCurve(curve, pc.curve_item, pc.hull_item, error_item) PlotAvgCurve.from_roc_curve = staticmethod(plot_avg_curve) Some = namedtuple("Some", ["val"]) def once(f): """ Return a function that will be called only once, and it's result cached. """ cached = None @wraps(f) def wraped(): nonlocal cached if cached is None: cached = Some(f()) return cached.val return wraped plot_curves = namedtuple( "plot_curves", ["merge", # :: () -> PlotCurve "folds", # :: () -> [PlotCurve] "avg_vertical", # :: () -> PlotAvgCurve "avg_threshold", # :: () -> PlotAvgCurve ] ) class InfiniteLine(pg.InfiniteLine): """pyqtgraph.InfiniteLine extended to support antialiasing. """ def __init__(self, pos=None, angle=90, pen=None, movable=False, bounds=None, antialias=False): super().__init__(pos, angle, pen, movable, bounds) self.antialias = antialias def paint(self, painter, *args): if self.antialias: painter.setRenderHint(QtGui.QPainter.Antialiasing, True) super().paint(painter, *args) class OWROCAnalysis(widget.OWWidget): name = "ROC Analysis" description = ("Displays Receiver Operating Characteristics curve " + "based on evaluation of classifiers.") icon = "icons/ROCAnalysis.svg" priority = 1010 inputs = [ {"name": "Evaluation Results", "type": Orange.evaluation.Results, "handler": "set_results"} ] target_index = settings.Setting(0) selected_classifiers = [] display_perf_line = settings.Setting(True) display_def_threshold = settings.Setting(True) fp_cost = settings.Setting(500) fn_cost = settings.Setting(500) target_prior = settings.Setting(50.0) #: ROC Averaging Types Merge, Vertical, Threshold, NoAveraging = 0, 1, 2, 3 roc_averaging = settings.Setting(Merge) display_convex_hull = settings.Setting(False) display_convex_curve = settings.Setting(False) def __init__(self, parent=None): super().__init__(parent) self.results = None self.classifier_names = [] self.perf_line = None self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None box = gui.widgetBox(self.controlArea, "Plot") tbox = gui.widgetBox(box, "Target Class") tbox.setFlat(True) self.target_cb = gui.comboBox( tbox, self, "target_index", callback=self._on_target_changed) cbox = gui.widgetBox(box, "Classifiers") cbox.setFlat(True) self.classifiers_list_box = gui.listBox( cbox, self, "selected_classifiers", "classifier_names", selectionMode=QtGui.QListView.MultiSelection, callback=self._on_classifiers_changed) abox = gui.widgetBox(box, "Combine ROC Curves From Folds") abox.setFlat(True) gui.comboBox(abox, self, "roc_averaging", items=["Merge predictions from folds", "Mean TP rate", "Mean TP and FP at threshold", "Show individual curves"], callback=self._replot) hbox = gui.widgetBox(box, "ROC Convex Hull") hbox.setFlat(True) gui.checkBox(hbox, self, "display_convex_curve", "Show convex ROC curves", callback=self._replot) gui.checkBox(hbox, self, "display_convex_hull", "Show ROC convex hull", callback=self._replot) box = gui.widgetBox(self.controlArea, "Analysis") gui.checkBox(box, self, "display_def_threshold", "Default threshold (0.5) point", callback=self._on_display_def_threshold_changed) gui.checkBox(box, self, "display_perf_line", "Show performance line", callback=self._on_display_perf_line_changed) grid = QtGui.QGridLayout() ibox = gui.indentedBox(box, orientation=grid) sp = gui.spin(box, self, "fp_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FP Cost"), 0, 0) grid.addWidget(sp, 0, 1) sp = gui.spin(box, self, "fn_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FN Cost")) grid.addWidget(sp, 1, 1) sp = gui.spin(box, self, "target_prior", 1, 99, callback=self._on_display_perf_line_changed) sp.setSuffix("%") sp.addAction(QtGui.QAction("Auto", sp)) grid.addWidget(QtGui.QLabel("Prior target class probability")) grid.addWidget(sp, 2, 1) self.plotview = pg.GraphicsView(background="w") self.plotview.setFrameStyle(QtGui.QFrame.StyledPanel) self.plot = pg.PlotItem() self.plot.getViewBox().setMenuEnabled(False) self.plot.getViewBox().setMouseEnabled(False, False) pen = QPen(self.palette().color(QtGui.QPalette.Text)) tickfont = QtGui.QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("FP Rate (1-Specificity)") axis = self.plot.getAxis("left") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("TP Rate (Sensitivity)") self.plot.showGrid(True, True, alpha=0.1) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0)) self.plotview.setCentralItem(self.plot) self.mainArea.layout().addWidget(self.plotview) def set_results(self, results): """Set the input evaluation results.""" self.clear() self.error(0) if results is not None: if results.data is None: self.error(0, "Give me data!!") results = None elif not isinstance(results.data.domain.class_var, Orange.data.DiscreteVariable): self.error(0, "Need discrete class variable") results = None self.results = results if results is not None: self._initialize(results) self._setup_plot() def clear(self): """Clear the widget state.""" self.results = None self.plot.clear() self.classifier_names = [] self.selected_classifiers = [] self.target_cb.clear() self.target_index = 0 self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None def _initialize(self, results): names = getattr(results, "learner_names", None) if names is None: names = ["#{}".format(i + 1) for i in range(len(results.predicted))] self.colors = colorpalette.ColorPaletteGenerator( len(names), colorbrewer.colorSchemes["qualitative"]["Dark2"]) self.classifier_names = names self.selected_classifiers = list(range(len(names))) for i in range(len(names)): listitem = self.classifiers_list_box.item(i) listitem.setIcon(colorpalette.ColorPixmap(self.colors[i])) class_var = results.data.domain.class_var self.target_cb.addItems(class_var.values) def curve_data(self, target, clf_idx): """Return `ROCData' for the given target and classifier.""" if (target, clf_idx) not in self._curve_data: data = ROCData.from_results(self.results, clf_idx, target) self._curve_data[target, clf_idx] = data return self._curve_data[target, clf_idx] def plot_curves(self, target, clf_idx): """Return a set of functions `plot_curves` generating plot curves.""" def generate_pens(basecolor): pen = QPen(basecolor, 1) pen.setCosmetic(True) shadow_pen = QPen(pen.color().lighter(160), 2.5) shadow_pen.setCosmetic(True) return pen, shadow_pen data = self.curve_data(target, clf_idx) if (target, clf_idx) not in self._plot_curves: pen, shadow_pen = generate_pens(self.colors[clf_idx]) name = self.classifier_names[clf_idx] @once def merged(): return plot_curve( data.merged, pen=pen, shadow_pen=shadow_pen, name=name) @once def folds(): return [plot_curve(fold, pen=pen, shadow_pen=shadow_pen) for fold in data.folds] @once def avg_vert(): return plot_avg_curve(data.avg_vertical, pen=pen, shadow_pen=shadow_pen, name=name) @once def avg_thres(): return plot_avg_curve(data.avg_threshold, pen=pen, shadow_pen=shadow_pen, name=name) self._plot_curves[target, clf_idx] = plot_curves( merge=merged, folds=folds, avg_vertical=avg_vert, avg_threshold=avg_thres ) return self._plot_curves[target, clf_idx] def _setup_plot(self): target = self.target_index selected = self.selected_classifiers curves = [self.plot_curves(target, i) for i in selected] selected = [self.curve_data(target, i) for i in selected] if self.roc_averaging == OWROCAnalysis.Merge: for curve in curves: graphics = curve.merge() curve = graphics.curve self.plot.addItem(graphics.curve_item) if self.display_convex_curve: self.plot.addItem(graphics.hull_item) if self.display_def_threshold: points = curve.points ind = numpy.argmin(numpy.abs(points.thresholds - 0.5)) item = pg.TextItem( text="{:.3f}".format(points.thresholds[ind]), ) item.setPos(points.fpr[ind], points.tpr[ind]) self.plot.addItem(item) hull_curves = [curve.merged.hull for curve in selected] if hull_curves: self._rocch = convex_hull(hull_curves) iso_pen = QPen(QColor(Qt.black), 1) iso_pen.setCosmetic(True) self._perf_line = InfiniteLine(pen=iso_pen, antialias=True) self.plot.addItem(self._perf_line) elif self.roc_averaging == OWROCAnalysis.Vertical: for curve in curves: graphics = curve.avg_vertical() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_vertical.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.Threshold: for curve in curves: graphics = curve.avg_threshold() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_threshold.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.NoAveraging: for curve in curves: graphics = curve.folds() for fold in graphics: self.plot.addItem(fold.curve_item) if self.display_convex_curve: self.plot.addItem(fold.hull_item) hull_curves = [fold.hull for curve in selected for fold in curve.folds] if self.display_convex_hull and hull_curves: hull = convex_hull(hull_curves) hull_pen = QPen(QColor(200, 200, 200, 100), 2) hull_pen.setCosmetic(True) item = self.plot.plot( hull.fpr, hull.tpr, pen=hull_pen, brush=QBrush(QColor(200, 200, 200, 50)), fillLevel=0) item.setZValue(-10000) pen = QPen(QColor(100, 100, 100, 100), 1, Qt.DashLine) pen.setCosmetic(True) self.plot.plot([0, 1], [0, 1], pen=pen, antialias=True) if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() def _on_target_changed(self): self.plot.clear() self._setup_plot() def _on_classifiers_changed(self): self.plot.clear() if self.results is not None: self._setup_plot() def _on_display_perf_line_changed(self): if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() if self.perf_line is not None: self.perf_line.setVisible(self.display_perf_line) def _on_display_def_threshold_changed(self): self._replot() def _replot(self): self.plot.clear() if self.results is not None: self._setup_plot() def _update_perf_line(self): if self._perf_line is None: return self._perf_line.setVisible(self.display_perf_line) if self.display_perf_line: m = roc_iso_performance_slope( self.fp_cost, self.fn_cost, self.target_prior / 100.0) hull = self._rocch ind = roc_iso_performance_line(m, hull) angle = numpy.arctan2(m, 1) # in radians self._perf_line.setAngle(angle * 180 / numpy.pi) self._perf_line.setPos((hull.fpr[ind[0]], hull.tpr[ind[0]])) def onDeleteWidget(self): self.clear() def interp(x, xp, fp, left=None, right=None): """ Like numpy.interp except for handling of running sequences of same values in `xp`. """ x = numpy.asanyarray(x) xp = numpy.asanyarray(xp) fp = numpy.asanyarray(fp) if xp.shape != fp.shape: raise ValueError("xp and fp must have the same shape") ind = numpy.searchsorted(xp, x, side="right") fx = numpy.zeros(len(x)) under = ind == 0 over = ind == len(xp) between = ~under & ~over fx[under] = left if left is not None else fp[0] fx[over] = right if right is not None else fp[-1] if right is not None: # Fix points exactly on the right boundary. fx[x == xp[-1]] = fp[-1] ind = ind[between] df = (fp[ind] - fp[ind - 1]) / (xp[ind] - xp[ind - 1]) fx[between] = df * (x[between] - xp[ind]) + fp[ind] return fx def roc_curve_for_fold(res, fold, clf_idx, target): fold_actual = res.actual[fold] P = numpy.sum(fold_actual == target) N = fold_actual.size - P if P == 0 or N == 0: # Undefined TP and FP rate return numpy.array([]), numpy.array([]), numpy.array([]) fold_probs = res.probabilities[clf_idx][fold][:, target] return skl_metrics.roc_curve( fold_actual, fold_probs, pos_label=target ) def roc_curve_vertical_average(curves, samples=10): fpr_sample = numpy.linspace(0.0, 1.0, samples) tpr_samples = [] for fpr, tpr, _ in curves: tpr_samples.append(interp(fpr_sample, fpr, tpr, left=0, right=1)) tpr_samples = numpy.array(tpr_samples) return fpr_sample, tpr_samples.mean(axis=0), tpr_samples.std(axis=0) def roc_curve_threshold_average(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: ind = numpy.searchsorted(thresh[::-1], thresh_samples, side="left") ind = ind[::-1] ind = numpy.clip(ind, 0, len(thresh) - 1) fpr_samples.append(fpr[ind]) tpr_samples.append(tpr[ind]) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) def roc_curve_threshold_average_interp(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: thresh = thresh[::-1] fpr = interp(thresh_samples, thresh, fpr[::-1], left=1.0, right=0.0) tpr = interp(thresh_samples, thresh, tpr[::-1], left=1.0, right=0.0) fpr_samples.append(fpr) tpr_samples.append(tpr) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) roc_point = namedtuple("roc_point", ["fpr", "tpr", "threshold"]) def roc_curve_convex_hull(curve): def slope(p1, p2): x1, y1, _ = p1 x2, y2, _ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf fpr, _, _ = curve if len(fpr) <= 2: return curve points = map(roc_point._make, zip(*curve)) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point.fpr != last.fpr and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() fpr = numpy.array([p.fpr for p in hull]) tpr = numpy.array([p.tpr for p in hull]) thres = numpy.array([p.threshold for p in hull]) return (fpr, tpr, thres) def convex_hull(curves): def
(p1, p2): x1, y1, *_ = p1 x2, y2, *_ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf curves = [list(map(roc_point._make, zip(*curve))) for curve in curves] merged_points = reduce(operator.iadd, curves, []) merged_points = sorted(merged_points) if len(merged_points) == 0: return ROCPoints(numpy.array([]), numpy.array([]), numpy.array([])) if len(merged_points) <= 2: return ROCPoints._make(map(numpy.array, zip(*merged_points))) points = iter(merged_points) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point[0] != last[0] and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() return ROCPoints._make(map(numpy.array, zip(*hull))) def roc_iso_performance_line(slope, hull, tol=1e-5): """ Return the indices where a line with `slope` touches the ROC convex hull. """ fpr, tpr, *_ = hull # Compute the distance of each point to a reference iso line # going through point (0, 1). The point(s) with the minimum # distance are our result # y = m * x + 1 # m * x - 1y + 1 = 0 a, b, c = slope, -1, 1 dist = distance_to_line(a, b, c, fpr, tpr) mindist = numpy.min(dist) return numpy.flatnonzero((dist - mindist) <= tol) def distance_to_line(a, b, c, x0, y0): """ Return the distance to a line ax + by + c = 0 """ assert a != 0 or b != 0 return numpy.abs(a * x0 + b * y0 + c) / numpy.sqrt(a ** 2 + b ** 2) def roc_iso_performance_slope(fp_cost, fn_cost, p): assert 0 <= p <= 1 if fn_cost * p == 0: return numpy.inf else: return (fp_cost * (1. - p)) / (fn_cost * p) def main(): import gc import sip from PyQt4.QtGui import QApplication from Orange.classification import (LogisticRegressionLearner, SVMLearner, NuSVMLearner) app = QApplication([]) w = OWROCAnalysis() w.show() w.raise_() # data = Orange.data.Table("iris") data = Orange.data.Table("ionosphere") results = Orange.evaluation.CrossValidation( data, [LogisticRegressionLearner(), LogisticRegressionLearner(penalty="l1"), SVMLearner(probability=True), NuSVMLearner(probability=True)], k=5, store_data=True, ) results.learner_names = ["Logistic", "Logistic (L1 reg.)", "SVM", "NuSVM"] w.set_results(results) rval = app.exec_() w.deleteLater() sip.delete(w) del w app.processEvents() sip.delete(app) del app gc.collect() return rval if __name__ == "__main__": import sys sys.exit(main())
slope
identifier_name
owrocanalysis.py
""" ROC Analysis Widget ------------------- """ import operator from functools import reduce, wraps from collections import namedtuple, deque import numpy import sklearn.metrics as skl_metrics from PyQt4 import QtGui from PyQt4.QtGui import QColor, QPen, QBrush from PyQt4.QtCore import Qt import pyqtgraph as pg import Orange from Orange.widgets import widget, gui, settings from Orange.widgets.utils import colorpalette, colorbrewer #: Points on a ROC curve ROCPoints = namedtuple( "ROCPoints", ["fpr", # (N,) array of false positive rate coordinates (ascending) "tpr", # (N,) array of true positive rate coordinates "thresholds" # (N,) array of thresholds (in descending order) ] ) ROCPoints.is_valid = property(lambda self: self.fpr.size > 0) #: ROC Curve and it's convex hull ROCCurve = namedtuple( "ROCCurve", ["points", # ROCPoints "hull" # ROCPoints of the convex hull ] ) ROCCurve.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged vertically ROCAveragedVert = namedtuple( "ROCAveragedVert", ["points", # ROCPoints sampled by fpr "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviation of tpr at each fpr point ] ) ROCAveragedVert.is_valid = property(lambda self: self.points.is_valid) #: A ROC Curve averaged by thresholds ROCAveragedThresh = namedtuple( "ROCAveragedThresh", ["points", # ROCPoints sampled by threshold "hull", # ROCPoints of the convex hull "tpr_std", # array standard deviations of tpr at each threshold "fpr_std" # array standard deviations of fpr at each threshold ] ) ROCAveragedThresh.is_valid = property(lambda self: self.points.is_valid) #: Combined data for a ROC curve of a single algorithm ROCData = namedtuple( "ROCData", ["merged", # ROCCurve merged over all folds "folds", # ROCCurve list, one for each fold "avg_vertical", # ROCAveragedVert "avg_threshold", # ROCAveragedThresh ] ) def ROCData_from_results(results, clf_index, target): """ Compute ROC Curve(s) from evaluation results. :param Orange.evaluation.Results results: Evaluation results. :param int clf_index: Learner index in the `results`. :param int target: Target class index (i.e. positive class). :rval ROCData: A instance holding the computed curves. """ merged = roc_curve_for_fold(results, slice(0, -1), clf_index, target) merged_curve = ROCCurve(ROCPoints(*merged), ROCPoints(*roc_curve_convex_hull(merged))) folds = results.folds if results.folds is not None else [slice(0, -1)] fold_curves = [] for fold in folds: # TODO: Check for no FP or no TP points = roc_curve_for_fold(results, fold, clf_index, target) hull = roc_curve_convex_hull(points) c = ROCCurve(ROCPoints(*points), ROCPoints(*hull)) fold_curves.append(c) curves = [fold.points for fold in fold_curves if fold.is_valid] fpr, tpr, std = roc_curve_vertical_average(curves) thresh = numpy.zeros_like(fpr) * numpy.nan hull = roc_curve_convex_hull((fpr, tpr, thresh)) v_avg = ROCAveragedVert( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), std ) all_thresh = numpy.hstack([t for _, _, t in curves]) all_thresh = numpy.clip(all_thresh, 0.0 - 1e-10, 1.0 + 1e-10) all_thresh = numpy.unique(all_thresh)[::-1] thresh = all_thresh[::max(all_thresh.size // 10, 1)] (fpr, fpr_std), (tpr, tpr_std) = \ roc_curve_threshold_average(curves, thresh) hull = roc_curve_convex_hull((fpr, tpr, thresh)) t_avg = ROCAveragedThresh( ROCPoints(fpr, tpr, thresh), ROCPoints(*hull), tpr_std, fpr_std ) return ROCData(merged_curve, fold_curves, v_avg, t_avg) ROCData.from_results = staticmethod(ROCData_from_results) #: A curve item to be displayed in a plot PlotCurve = namedtuple( "PlotCurve", ["curve", # ROCCurve source curve "curve_item", # pg.PlotDataItem main curve "hull_item" # pg.PlotDataItem curve's convex hull ] ) def plot_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=3, name=None): """ Construct a `PlotCurve` for the given `ROCCurve`. :param ROCCurve curve: Source curve. The other parameters are passed to pg.PlotDataItem :rtype: PlotCurve """ def extend_to_origin(points): "Extend ROCPoints to include coordinate origin if not already present" if points.tpr.size and (points.tpr[0] > 0 or points.fpr[0] > 0): points = ROCPoints( numpy.r_[0, points.fpr], numpy.r_[0, points.tpr], numpy.r_[points.thresholds[0] + 1, points.thresholds] ) return points points = extend_to_origin(curve.points) item = pg.PlotCurveItem( points.fpr, points.tpr, pen=pen, shadowPen=shadow_pen, name=name, antialias=True ) sp = pg.ScatterPlotItem( curve.points.fpr, curve.points.tpr, symbol=symbol, size=symbol_size, pen=shadow_pen, name=name ) sp.setParentItem(item) hull = extend_to_origin(curve.hull) hull_item = pg.PlotDataItem( hull.fpr, hull.tpr, pen=pen, antialias=True ) return PlotCurve(curve, item, hull_item) PlotCurve.from_roc_curve = staticmethod(plot_curve) #: A curve displayed in a plot with error bars PlotAvgCurve = namedtuple( "PlotAvgCurve", ["curve", # ROCCurve "curve_item", # pg.PlotDataItem "hull_item", # pg.PlotDataItem "confint_item", # pg.ErrorBarItem ] ) def plot_avg_curve(curve, pen=None, shadow_pen=None, symbol="+", symbol_size=4, name=None): """ Construct a `PlotAvgCurve` for the given `curve`. :param curve: Source curve. :type curve: ROCAveragedVert or ROCAveragedThresh The other parameters are passed to pg.PlotDataItem :rtype: PlotAvgCurve """ pc = plot_curve(curve, pen=pen, shadow_pen=shadow_pen, symbol=symbol, symbol_size=symbol_size, name=name) points = curve.points if isinstance(curve, ROCAveragedVert): tpr_std = curve.tpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) elif isinstance(curve, ROCAveragedThresh): tpr_std, fpr_std = curve.tpr_std, curve.fpr_std error_item = pg.ErrorBarItem( x=points.fpr[1:-1], y=points.tpr[1:-1], height=2 * tpr_std[1:-1], width=2 * fpr_std[1:-1], pen=pen, beam=0.025, antialias=True, ) return PlotAvgCurve(curve, pc.curve_item, pc.hull_item, error_item) PlotAvgCurve.from_roc_curve = staticmethod(plot_avg_curve) Some = namedtuple("Some", ["val"]) def once(f): """ Return a function that will be called only once, and it's result cached. """ cached = None @wraps(f) def wraped(): nonlocal cached if cached is None: cached = Some(f()) return cached.val return wraped plot_curves = namedtuple( "plot_curves", ["merge", # :: () -> PlotCurve "folds", # :: () -> [PlotCurve] "avg_vertical", # :: () -> PlotAvgCurve "avg_threshold", # :: () -> PlotAvgCurve ] ) class InfiniteLine(pg.InfiniteLine): """pyqtgraph.InfiniteLine extended to support antialiasing. """ def __init__(self, pos=None, angle=90, pen=None, movable=False, bounds=None, antialias=False): super().__init__(pos, angle, pen, movable, bounds) self.antialias = antialias def paint(self, painter, *args): if self.antialias: painter.setRenderHint(QtGui.QPainter.Antialiasing, True) super().paint(painter, *args) class OWROCAnalysis(widget.OWWidget): name = "ROC Analysis" description = ("Displays Receiver Operating Characteristics curve " + "based on evaluation of classifiers.") icon = "icons/ROCAnalysis.svg" priority = 1010 inputs = [ {"name": "Evaluation Results", "type": Orange.evaluation.Results, "handler": "set_results"} ] target_index = settings.Setting(0) selected_classifiers = [] display_perf_line = settings.Setting(True) display_def_threshold = settings.Setting(True) fp_cost = settings.Setting(500) fn_cost = settings.Setting(500) target_prior = settings.Setting(50.0) #: ROC Averaging Types Merge, Vertical, Threshold, NoAveraging = 0, 1, 2, 3 roc_averaging = settings.Setting(Merge) display_convex_hull = settings.Setting(False) display_convex_curve = settings.Setting(False) def __init__(self, parent=None): super().__init__(parent) self.results = None self.classifier_names = [] self.perf_line = None self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None box = gui.widgetBox(self.controlArea, "Plot") tbox = gui.widgetBox(box, "Target Class") tbox.setFlat(True) self.target_cb = gui.comboBox( tbox, self, "target_index", callback=self._on_target_changed) cbox = gui.widgetBox(box, "Classifiers") cbox.setFlat(True) self.classifiers_list_box = gui.listBox( cbox, self, "selected_classifiers", "classifier_names", selectionMode=QtGui.QListView.MultiSelection, callback=self._on_classifiers_changed) abox = gui.widgetBox(box, "Combine ROC Curves From Folds") abox.setFlat(True) gui.comboBox(abox, self, "roc_averaging", items=["Merge predictions from folds", "Mean TP rate", "Mean TP and FP at threshold", "Show individual curves"], callback=self._replot) hbox = gui.widgetBox(box, "ROC Convex Hull") hbox.setFlat(True) gui.checkBox(hbox, self, "display_convex_curve", "Show convex ROC curves", callback=self._replot) gui.checkBox(hbox, self, "display_convex_hull", "Show ROC convex hull", callback=self._replot) box = gui.widgetBox(self.controlArea, "Analysis") gui.checkBox(box, self, "display_def_threshold", "Default threshold (0.5) point", callback=self._on_display_def_threshold_changed) gui.checkBox(box, self, "display_perf_line", "Show performance line", callback=self._on_display_perf_line_changed) grid = QtGui.QGridLayout() ibox = gui.indentedBox(box, orientation=grid) sp = gui.spin(box, self, "fp_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FP Cost"), 0, 0) grid.addWidget(sp, 0, 1) sp = gui.spin(box, self, "fn_cost", 1, 1000, 10, callback=self._on_display_perf_line_changed) grid.addWidget(QtGui.QLabel("FN Cost")) grid.addWidget(sp, 1, 1) sp = gui.spin(box, self, "target_prior", 1, 99, callback=self._on_display_perf_line_changed) sp.setSuffix("%") sp.addAction(QtGui.QAction("Auto", sp)) grid.addWidget(QtGui.QLabel("Prior target class probability")) grid.addWidget(sp, 2, 1) self.plotview = pg.GraphicsView(background="w") self.plotview.setFrameStyle(QtGui.QFrame.StyledPanel) self.plot = pg.PlotItem() self.plot.getViewBox().setMenuEnabled(False) self.plot.getViewBox().setMouseEnabled(False, False) pen = QPen(self.palette().color(QtGui.QPalette.Text)) tickfont = QtGui.QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("FP Rate (1-Specificity)") axis = self.plot.getAxis("left") axis.setTickFont(tickfont) axis.setPen(pen) axis.setLabel("TP Rate (Sensitivity)") self.plot.showGrid(True, True, alpha=0.1) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0)) self.plotview.setCentralItem(self.plot) self.mainArea.layout().addWidget(self.plotview) def set_results(self, results): """Set the input evaluation results.""" self.clear() self.error(0) if results is not None: if results.data is None: self.error(0, "Give me data!!") results = None elif not isinstance(results.data.domain.class_var, Orange.data.DiscreteVariable): self.error(0, "Need discrete class variable") results = None self.results = results if results is not None: self._initialize(results) self._setup_plot() def clear(self): """Clear the widget state.""" self.results = None self.plot.clear() self.classifier_names = [] self.selected_classifiers = [] self.target_cb.clear() self.target_index = 0 self.colors = [] self._curve_data = {} self._plot_curves = {} self._rocch = None self._perf_line = None def _initialize(self, results): names = getattr(results, "learner_names", None) if names is None: names = ["#{}".format(i + 1) for i in range(len(results.predicted))] self.colors = colorpalette.ColorPaletteGenerator( len(names), colorbrewer.colorSchemes["qualitative"]["Dark2"]) self.classifier_names = names self.selected_classifiers = list(range(len(names))) for i in range(len(names)): listitem = self.classifiers_list_box.item(i) listitem.setIcon(colorpalette.ColorPixmap(self.colors[i])) class_var = results.data.domain.class_var self.target_cb.addItems(class_var.values) def curve_data(self, target, clf_idx): """Return `ROCData' for the given target and classifier.""" if (target, clf_idx) not in self._curve_data: data = ROCData.from_results(self.results, clf_idx, target) self._curve_data[target, clf_idx] = data return self._curve_data[target, clf_idx] def plot_curves(self, target, clf_idx): """Return a set of functions `plot_curves` generating plot curves.""" def generate_pens(basecolor): pen = QPen(basecolor, 1) pen.setCosmetic(True) shadow_pen = QPen(pen.color().lighter(160), 2.5) shadow_pen.setCosmetic(True) return pen, shadow_pen data = self.curve_data(target, clf_idx) if (target, clf_idx) not in self._plot_curves: pen, shadow_pen = generate_pens(self.colors[clf_idx]) name = self.classifier_names[clf_idx] @once def merged(): return plot_curve( data.merged, pen=pen, shadow_pen=shadow_pen, name=name) @once def folds(): return [plot_curve(fold, pen=pen, shadow_pen=shadow_pen) for fold in data.folds] @once def avg_vert(): return plot_avg_curve(data.avg_vertical, pen=pen, shadow_pen=shadow_pen, name=name) @once def avg_thres(): return plot_avg_curve(data.avg_threshold, pen=pen, shadow_pen=shadow_pen, name=name) self._plot_curves[target, clf_idx] = plot_curves( merge=merged, folds=folds, avg_vertical=avg_vert, avg_threshold=avg_thres ) return self._plot_curves[target, clf_idx] def _setup_plot(self): target = self.target_index selected = self.selected_classifiers curves = [self.plot_curves(target, i) for i in selected] selected = [self.curve_data(target, i) for i in selected] if self.roc_averaging == OWROCAnalysis.Merge: for curve in curves: graphics = curve.merge() curve = graphics.curve self.plot.addItem(graphics.curve_item) if self.display_convex_curve: self.plot.addItem(graphics.hull_item) if self.display_def_threshold: points = curve.points ind = numpy.argmin(numpy.abs(points.thresholds - 0.5)) item = pg.TextItem( text="{:.3f}".format(points.thresholds[ind]), ) item.setPos(points.fpr[ind], points.tpr[ind]) self.plot.addItem(item) hull_curves = [curve.merged.hull for curve in selected] if hull_curves: self._rocch = convex_hull(hull_curves) iso_pen = QPen(QColor(Qt.black), 1) iso_pen.setCosmetic(True) self._perf_line = InfiniteLine(pen=iso_pen, antialias=True) self.plot.addItem(self._perf_line) elif self.roc_averaging == OWROCAnalysis.Vertical: for curve in curves: graphics = curve.avg_vertical() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_vertical.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.Threshold: for curve in curves: graphics = curve.avg_threshold() self.plot.addItem(graphics.curve_item) self.plot.addItem(graphics.confint_item) hull_curves = [curve.avg_threshold.hull for curve in selected] elif self.roc_averaging == OWROCAnalysis.NoAveraging: for curve in curves: graphics = curve.folds() for fold in graphics: self.plot.addItem(fold.curve_item) if self.display_convex_curve: self.plot.addItem(fold.hull_item) hull_curves = [fold.hull for curve in selected for fold in curve.folds] if self.display_convex_hull and hull_curves: hull = convex_hull(hull_curves) hull_pen = QPen(QColor(200, 200, 200, 100), 2) hull_pen.setCosmetic(True) item = self.plot.plot( hull.fpr, hull.tpr, pen=hull_pen, brush=QBrush(QColor(200, 200, 200, 50)), fillLevel=0) item.setZValue(-10000) pen = QPen(QColor(100, 100, 100, 100), 1, Qt.DashLine) pen.setCosmetic(True) self.plot.plot([0, 1], [0, 1], pen=pen, antialias=True) if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() def _on_target_changed(self): self.plot.clear() self._setup_plot() def _on_classifiers_changed(self): self.plot.clear() if self.results is not None: self._setup_plot() def _on_display_perf_line_changed(self): if self.roc_averaging == OWROCAnalysis.Merge: self._update_perf_line() if self.perf_line is not None: self.perf_line.setVisible(self.display_perf_line) def _on_display_def_threshold_changed(self): self._replot() def _replot(self): self.plot.clear() if self.results is not None: self._setup_plot() def _update_perf_line(self): if self._perf_line is None: return self._perf_line.setVisible(self.display_perf_line) if self.display_perf_line: m = roc_iso_performance_slope( self.fp_cost, self.fn_cost, self.target_prior / 100.0) hull = self._rocch ind = roc_iso_performance_line(m, hull) angle = numpy.arctan2(m, 1) # in radians self._perf_line.setAngle(angle * 180 / numpy.pi) self._perf_line.setPos((hull.fpr[ind[0]], hull.tpr[ind[0]])) def onDeleteWidget(self): self.clear() def interp(x, xp, fp, left=None, right=None): """ Like numpy.interp except for handling of running sequences of same values in `xp`. """ x = numpy.asanyarray(x) xp = numpy.asanyarray(xp) fp = numpy.asanyarray(fp) if xp.shape != fp.shape: raise ValueError("xp and fp must have the same shape") ind = numpy.searchsorted(xp, x, side="right") fx = numpy.zeros(len(x)) under = ind == 0 over = ind == len(xp) between = ~under & ~over fx[under] = left if left is not None else fp[0] fx[over] = right if right is not None else fp[-1] if right is not None: # Fix points exactly on the right boundary. fx[x == xp[-1]] = fp[-1] ind = ind[between] df = (fp[ind] - fp[ind - 1]) / (xp[ind] - xp[ind - 1]) fx[between] = df * (x[between] - xp[ind]) + fp[ind] return fx def roc_curve_for_fold(res, fold, clf_idx, target): fold_actual = res.actual[fold] P = numpy.sum(fold_actual == target) N = fold_actual.size - P if P == 0 or N == 0: # Undefined TP and FP rate return numpy.array([]), numpy.array([]), numpy.array([]) fold_probs = res.probabilities[clf_idx][fold][:, target] return skl_metrics.roc_curve( fold_actual, fold_probs, pos_label=target ) def roc_curve_vertical_average(curves, samples=10): fpr_sample = numpy.linspace(0.0, 1.0, samples) tpr_samples = [] for fpr, tpr, _ in curves: tpr_samples.append(interp(fpr_sample, fpr, tpr, left=0, right=1)) tpr_samples = numpy.array(tpr_samples) return fpr_sample, tpr_samples.mean(axis=0), tpr_samples.std(axis=0) def roc_curve_threshold_average(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: ind = numpy.searchsorted(thresh[::-1], thresh_samples, side="left") ind = ind[::-1] ind = numpy.clip(ind, 0, len(thresh) - 1) fpr_samples.append(fpr[ind]) tpr_samples.append(tpr[ind]) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) def roc_curve_threshold_average_interp(curves, thresh_samples): fpr_samples, tpr_samples = [], [] for fpr, tpr, thresh in curves: thresh = thresh[::-1] fpr = interp(thresh_samples, thresh, fpr[::-1], left=1.0, right=0.0) tpr = interp(thresh_samples, thresh, tpr[::-1], left=1.0, right=0.0) fpr_samples.append(fpr) tpr_samples.append(tpr) fpr_samples = numpy.array(fpr_samples) tpr_samples = numpy.array(tpr_samples) return ((fpr_samples.mean(axis=0), fpr_samples.std(axis=0)), (tpr_samples.mean(axis=0), fpr_samples.std(axis=0))) roc_point = namedtuple("roc_point", ["fpr", "tpr", "threshold"]) def roc_curve_convex_hull(curve): def slope(p1, p2): x1, y1, _ = p1 x2, y2, _ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf fpr, _, _ = curve if len(fpr) <= 2: return curve points = map(roc_point._make, zip(*curve)) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point.fpr != last.fpr and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() fpr = numpy.array([p.fpr for p in hull]) tpr = numpy.array([p.tpr for p in hull]) thres = numpy.array([p.threshold for p in hull]) return (fpr, tpr, thres) def convex_hull(curves): def slope(p1, p2): x1, y1, *_ = p1 x2, y2, *_ = p2 if x1 != x2: return (y2 - y1) / (x2 - x1) else: return numpy.inf curves = [list(map(roc_point._make, zip(*curve))) for curve in curves] merged_points = reduce(operator.iadd, curves, []) merged_points = sorted(merged_points) if len(merged_points) == 0: return ROCPoints(numpy.array([]), numpy.array([]), numpy.array([])) if len(merged_points) <= 2: return ROCPoints._make(map(numpy.array, zip(*merged_points))) points = iter(merged_points) hull = deque([next(points)]) for point in points: while True: if len(hull) < 2: hull.append(point) break else: last = hull[-1] if point[0] != last[0] and \ slope(hull[-2], last) > slope(last, point): hull.append(point) break else: hull.pop() return ROCPoints._make(map(numpy.array, zip(*hull))) def roc_iso_performance_line(slope, hull, tol=1e-5): """ Return the indices where a line with `slope` touches the ROC convex hull. """ fpr, tpr, *_ = hull # Compute the distance of each point to a reference iso line # going through point (0, 1). The point(s) with the minimum # distance are our result # y = m * x + 1 # m * x - 1y + 1 = 0 a, b, c = slope, -1, 1 dist = distance_to_line(a, b, c, fpr, tpr) mindist = numpy.min(dist) return numpy.flatnonzero((dist - mindist) <= tol) def distance_to_line(a, b, c, x0, y0): """ Return the distance to a line ax + by + c = 0 """ assert a != 0 or b != 0 return numpy.abs(a * x0 + b * y0 + c) / numpy.sqrt(a ** 2 + b ** 2) def roc_iso_performance_slope(fp_cost, fn_cost, p): assert 0 <= p <= 1 if fn_cost * p == 0:
else: return (fp_cost * (1. - p)) / (fn_cost * p) def main(): import gc import sip from PyQt4.QtGui import QApplication from Orange.classification import (LogisticRegressionLearner, SVMLearner, NuSVMLearner) app = QApplication([]) w = OWROCAnalysis() w.show() w.raise_() # data = Orange.data.Table("iris") data = Orange.data.Table("ionosphere") results = Orange.evaluation.CrossValidation( data, [LogisticRegressionLearner(), LogisticRegressionLearner(penalty="l1"), SVMLearner(probability=True), NuSVMLearner(probability=True)], k=5, store_data=True, ) results.learner_names = ["Logistic", "Logistic (L1 reg.)", "SVM", "NuSVM"] w.set_results(results) rval = app.exec_() w.deleteLater() sip.delete(w) del w app.processEvents() sip.delete(app) del app gc.collect() return rval if __name__ == "__main__": import sys sys.exit(main())
return numpy.inf
conditional_block
user.py
# # Copyright 2008 Google Inc. All Rights Reserved. """ The user module contains the objects and methods used to manage users in Autotest. The valid action is: list: lists user(s) The common options are: --ulist / -U: file containing a list of USERs See topic_common.py for a High Level Design and Algorithm. """ import os import sys from autotest.cli import topic_common, action_common class user(topic_common.atest): """User class atest user list <options>""" usage_action = 'list' topic = msg_topic = 'user' msg_items = '<users>' def __init__(self): """Add to the parser the options common to all the user actions""" super(user, self).__init__() self.parser.add_option('-U', '--ulist', help='File listing the users', type='string', default=None, metavar='USER_FLIST') self.topic_parse_info = topic_common.item_parse_info( attribute_name='users', filename_option='ulist', use_leftover=True) def get_items(self): return self.users class user_help(user): """Just here to get the atest logic working. Usage is set by its parent""" pass class user_list(action_common.atest_list, user): """atest user list <user>|--ulist <file> [--acl <ACL>|--access_level <n>]""" def __init__(self): super(user_list, self).__init__() self.parser.add_option('-a', '--acl', help='Only list users within this ACL') self.parser.add_option('-l', '--access_level', help='Only list users at this access level') def parse(self):
def execute(self): filters = {} check_results = {} if self.acl: filters['aclgroup__name__in'] = [self.acl] check_results['aclgroup__name__in'] = None if self.access_level: filters['access_level__in'] = [self.access_level] check_results['access_level__in'] = None if self.users: filters['login__in'] = self.users check_results['login__in'] = 'login' return super(user_list, self).execute(op='get_users', filters=filters, check_results=check_results) def output(self, results): if self.verbose: keys = ['id', 'login', 'access_level'] else: keys = ['login'] super(user_list, self).output(results, keys)
(options, leftover) = super(user_list, self).parse() self.acl = options.acl self.access_level = options.access_level return (options, leftover)
identifier_body
user.py
# # Copyright 2008 Google Inc. All Rights Reserved. """ The user module contains the objects and methods used to manage users in Autotest. The valid action is: list: lists user(s) The common options are: --ulist / -U: file containing a list of USERs See topic_common.py for a High Level Design and Algorithm. """ import os import sys from autotest.cli import topic_common, action_common class user(topic_common.atest): """User class atest user list <options>""" usage_action = 'list' topic = msg_topic = 'user' msg_items = '<users>' def __init__(self): """Add to the parser the options common to all the user actions""" super(user, self).__init__() self.parser.add_option('-U', '--ulist', help='File listing the users', type='string', default=None, metavar='USER_FLIST') self.topic_parse_info = topic_common.item_parse_info( attribute_name='users', filename_option='ulist', use_leftover=True) def get_items(self): return self.users class user_help(user): """Just here to get the atest logic working. Usage is set by its parent""" pass class
(action_common.atest_list, user): """atest user list <user>|--ulist <file> [--acl <ACL>|--access_level <n>]""" def __init__(self): super(user_list, self).__init__() self.parser.add_option('-a', '--acl', help='Only list users within this ACL') self.parser.add_option('-l', '--access_level', help='Only list users at this access level') def parse(self): (options, leftover) = super(user_list, self).parse() self.acl = options.acl self.access_level = options.access_level return (options, leftover) def execute(self): filters = {} check_results = {} if self.acl: filters['aclgroup__name__in'] = [self.acl] check_results['aclgroup__name__in'] = None if self.access_level: filters['access_level__in'] = [self.access_level] check_results['access_level__in'] = None if self.users: filters['login__in'] = self.users check_results['login__in'] = 'login' return super(user_list, self).execute(op='get_users', filters=filters, check_results=check_results) def output(self, results): if self.verbose: keys = ['id', 'login', 'access_level'] else: keys = ['login'] super(user_list, self).output(results, keys)
user_list
identifier_name
user.py
# # Copyright 2008 Google Inc. All Rights Reserved. """ The user module contains the objects and methods used to manage users in Autotest. The valid action is: list: lists user(s) The common options are: --ulist / -U: file containing a list of USERs See topic_common.py for a High Level Design and Algorithm. """ import os import sys from autotest.cli import topic_common, action_common class user(topic_common.atest): """User class atest user list <options>""" usage_action = 'list' topic = msg_topic = 'user' msg_items = '<users>' def __init__(self): """Add to the parser the options common to all the user actions""" super(user, self).__init__() self.parser.add_option('-U', '--ulist', help='File listing the users', type='string', default=None, metavar='USER_FLIST') self.topic_parse_info = topic_common.item_parse_info( attribute_name='users', filename_option='ulist', use_leftover=True) def get_items(self): return self.users class user_help(user): """Just here to get the atest logic working. Usage is set by its parent""" pass class user_list(action_common.atest_list, user): """atest user list <user>|--ulist <file> [--acl <ACL>|--access_level <n>]""" def __init__(self): super(user_list, self).__init__() self.parser.add_option('-a', '--acl', help='Only list users within this ACL') self.parser.add_option('-l', '--access_level', help='Only list users at this access level') def parse(self): (options, leftover) = super(user_list, self).parse() self.acl = options.acl self.access_level = options.access_level return (options, leftover) def execute(self): filters = {} check_results = {} if self.acl: filters['aclgroup__name__in'] = [self.acl] check_results['aclgroup__name__in'] = None if self.access_level: filters['access_level__in'] = [self.access_level] check_results['access_level__in'] = None if self.users:
filters=filters, check_results=check_results) def output(self, results): if self.verbose: keys = ['id', 'login', 'access_level'] else: keys = ['login'] super(user_list, self).output(results, keys)
filters['login__in'] = self.users check_results['login__in'] = 'login' return super(user_list, self).execute(op='get_users',
random_line_split
user.py
# # Copyright 2008 Google Inc. All Rights Reserved. """ The user module contains the objects and methods used to manage users in Autotest. The valid action is: list: lists user(s) The common options are: --ulist / -U: file containing a list of USERs See topic_common.py for a High Level Design and Algorithm. """ import os import sys from autotest.cli import topic_common, action_common class user(topic_common.atest): """User class atest user list <options>""" usage_action = 'list' topic = msg_topic = 'user' msg_items = '<users>' def __init__(self): """Add to the parser the options common to all the user actions""" super(user, self).__init__() self.parser.add_option('-U', '--ulist', help='File listing the users', type='string', default=None, metavar='USER_FLIST') self.topic_parse_info = topic_common.item_parse_info( attribute_name='users', filename_option='ulist', use_leftover=True) def get_items(self): return self.users class user_help(user): """Just here to get the atest logic working. Usage is set by its parent""" pass class user_list(action_common.atest_list, user): """atest user list <user>|--ulist <file> [--acl <ACL>|--access_level <n>]""" def __init__(self): super(user_list, self).__init__() self.parser.add_option('-a', '--acl', help='Only list users within this ACL') self.parser.add_option('-l', '--access_level', help='Only list users at this access level') def parse(self): (options, leftover) = super(user_list, self).parse() self.acl = options.acl self.access_level = options.access_level return (options, leftover) def execute(self): filters = {} check_results = {} if self.acl:
if self.access_level: filters['access_level__in'] = [self.access_level] check_results['access_level__in'] = None if self.users: filters['login__in'] = self.users check_results['login__in'] = 'login' return super(user_list, self).execute(op='get_users', filters=filters, check_results=check_results) def output(self, results): if self.verbose: keys = ['id', 'login', 'access_level'] else: keys = ['login'] super(user_list, self).output(results, keys)
filters['aclgroup__name__in'] = [self.acl] check_results['aclgroup__name__in'] = None
conditional_block
conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Site Analytics documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys _PROJECT_PATH = os.path.dirname(os.path.dirname(__file__)) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.join(_PROJECT_PATH, 'src')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Site Analytics' copyright = '2016, Craig Hurd-Rindy' author = 'Craig Hurd-Rindy' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # exec(open(os.path.join(_PROJECT_PATH, 'src', 'site_analytics', '_version.py')) .read()) # The short X.Y version. version = '.'.join(str(x) for x in __version_info__[:2]) # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None default_role = 'py:obj' # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. modindex_common_prefix = ['site_analytics.'] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'classic' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. # # html_title = 'Site Analytics v1.0.0' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'SiteAnalyticsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'SiteAnalytics.tex', 'Site Analytics Documentation', 'Craig Hurd-Rindy', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'siteanalytics', 'Site Analytics Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'SiteAnalytics', 'Site Analytics Documentation', author, 'SiteAnalytics', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = project # The HTML theme for the epub output. Since the default themes are not # optimized for small screen space, using the same theme for HTML and epub # output is usually not wise. This defaults to 'epub', a theme designed to save # visual space. # # epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. # # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. # # epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. # # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. # # epub_tocdepth = 3 # Allow duplicate toc entries. # # epub_tocdup = True # Choose between 'default' and 'includehidden'. # # epub_tocscope = 'default' # Fix unsupported image types using the Pillow. # # epub_fix_images = False # Scale large images. # # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # # epub_show_urls = 'inline' # If false, no index is generated. # # epub_use_index = True intersphinx_mapping = { 'python': ( 'https://docs.python.org/{}'.format(sys.version_info[0]), None ), } try: import django except ImportError: pass else:
# autodoc configuration autodoc_member_order = 'bysource' autodoc_default_flags = ['members', 'undoc-members', 'show-inheritance']
_django_major_version = '{}.{}'.format(*django.VERSION[:2]) intersphinx_mapping['django'] = ( 'https://docs.djangoproject.com/en/{}/'.format(_django_major_version), 'https://docs.djangoproject.com/en/{}/_objects/'.format(_django_major_version) ) os.environ['DJANGO_SETTINGS_MODULE'] = 'site_analytics.settings' django.setup()
conditional_block
conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Site Analytics documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys _PROJECT_PATH = os.path.dirname(os.path.dirname(__file__)) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.join(_PROJECT_PATH, 'src')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Site Analytics' copyright = '2016, Craig Hurd-Rindy' author = 'Craig Hurd-Rindy' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # exec(open(os.path.join(_PROJECT_PATH, 'src', 'site_analytics', '_version.py')) .read()) # The short X.Y version. version = '.'.join(str(x) for x in __version_info__[:2]) # The full version, including alpha/beta/rc tags. release = __version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None default_role = 'py:obj' # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. modindex_common_prefix = ['site_analytics.'] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'classic' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. # # html_title = 'Site Analytics v1.0.0' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'SiteAnalyticsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'SiteAnalytics.tex', 'Site Analytics Documentation', 'Craig Hurd-Rindy', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'siteanalytics', 'Site Analytics Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'SiteAnalytics', 'Site Analytics Documentation', author, 'SiteAnalytics', 'One line description of project.', 'Miscellaneous'), ]
# Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = project # The HTML theme for the epub output. Since the default themes are not # optimized for small screen space, using the same theme for HTML and epub # output is usually not wise. This defaults to 'epub', a theme designed to save # visual space. # # epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. # # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. # # epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. # # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # # epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. # # epub_tocdepth = 3 # Allow duplicate toc entries. # # epub_tocdup = True # Choose between 'default' and 'includehidden'. # # epub_tocscope = 'default' # Fix unsupported image types using the Pillow. # # epub_fix_images = False # Scale large images. # # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # # epub_show_urls = 'inline' # If false, no index is generated. # # epub_use_index = True intersphinx_mapping = { 'python': ( 'https://docs.python.org/{}'.format(sys.version_info[0]), None ), } try: import django except ImportError: pass else: _django_major_version = '{}.{}'.format(*django.VERSION[:2]) intersphinx_mapping['django'] = ( 'https://docs.djangoproject.com/en/{}/'.format(_django_major_version), 'https://docs.djangoproject.com/en/{}/_objects/'.format(_django_major_version) ) os.environ['DJANGO_SETTINGS_MODULE'] = 'site_analytics.settings' django.setup() # autodoc configuration autodoc_member_order = 'bysource' autodoc_default_flags = ['members', 'undoc-members', 'show-inheritance']
random_line_split
issue-36116.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Unnecessary path disambiguator is ok // compile-pass // skip-codegen #![allow(unused)] macro_rules! m { ($p: path) => { let _ = $p(0); let _: $p; } } struct Foo<T> { _a: T, } struct S<T>(T);
} fn main() {}
fn f() { let f = Some(Foo { _a: 42 }).map(|a| a as Foo::<i32>); //~ WARN unnecessary path disambiguator let g: Foo::<i32> = Foo { _a: 42 }; //~ WARN unnecessary path disambiguator m!(S::<u8>); // OK, no warning
random_line_split
issue-36116.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Unnecessary path disambiguator is ok // compile-pass // skip-codegen #![allow(unused)] macro_rules! m { ($p: path) => { let _ = $p(0); let _: $p; } } struct Foo<T> { _a: T, } struct S<T>(T); fn
() { let f = Some(Foo { _a: 42 }).map(|a| a as Foo::<i32>); //~ WARN unnecessary path disambiguator let g: Foo::<i32> = Foo { _a: 42 }; //~ WARN unnecessary path disambiguator m!(S::<u8>); // OK, no warning } fn main() {}
f
identifier_name
clamav.py
# This file is part of Viper - https://github.com/botherder/viper # See the file 'LICENSE' for copying permission. import getopt try: import pyclamd HAVE_CLAMD = True except ImportError: HAVE_CLAMD = False from viper.common.out import * from viper.common.abstracts import Module from viper.core.session import __sessions__ class ClamAV(Module): cmd = 'clamav' description = 'Scan file from local ClamAV daemon' authors = ['neriberto'] def run(self): def usage(): self.log('', "usage: clamav [-h] [-s]") def help(): usage() self.log('', "") self.log('', "Options:") self.log('', "\t--help (-h)\tShow this help message") self.log('', "\t--socket(-s)\tSpecify an unix socket (default: Clamd Unix Socket)") self.log('', "")
if not HAVE_CLAMD: self.log('error', "Missing dependency, install requests (`pip install pyclamd`)") return try: opts, argv = getopt.getopt(self.args, 'hs:', ['help', 'socket=']) except getopt.GetoptError as e: self.log('', e) usage() return daemon = None result = None socket = None for opt, value in opts: if opt in ('-h', '--help'): help() return elif opt in ('-s', '--socket'): self.log('info', "Using socket {0} to connect to ClamAV daemon".format(value)) socket = value try: daemon = pyclamd.ClamdUnixSocket(socket) except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return if not __sessions__.is_set(): self.log('error', "No session opened") return try: if not daemon: daemon = pyclamd.ClamdUnixSocket() socket = 'Clamav' except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return try: if daemon.ping(): results = daemon.scan_file(__sessions__.current.file.path) else: self.log('error', "Unable to connect to the daemon") except Exception as e: self.log('error', "Unable to scan with antivirus daemon, {0}".format(e)) return found = None name = 'not found' if results: for item in results: found = results[item][0] name = results[item][1] if found == 'ERROR': self.log('error', "Check permissions of the binary folder, {0}".format(name)) else: self.log('info', "Daemon {0} returns: {1}".format(socket, name))
random_line_split
clamav.py
# This file is part of Viper - https://github.com/botherder/viper # See the file 'LICENSE' for copying permission. import getopt try: import pyclamd HAVE_CLAMD = True except ImportError: HAVE_CLAMD = False from viper.common.out import * from viper.common.abstracts import Module from viper.core.session import __sessions__ class ClamAV(Module): cmd = 'clamav' description = 'Scan file from local ClamAV daemon' authors = ['neriberto'] def run(self): def usage(): self.log('', "usage: clamav [-h] [-s]") def help():
if not HAVE_CLAMD: self.log('error', "Missing dependency, install requests (`pip install pyclamd`)") return try: opts, argv = getopt.getopt(self.args, 'hs:', ['help', 'socket=']) except getopt.GetoptError as e: self.log('', e) usage() return daemon = None result = None socket = None for opt, value in opts: if opt in ('-h', '--help'): help() return elif opt in ('-s', '--socket'): self.log('info', "Using socket {0} to connect to ClamAV daemon".format(value)) socket = value try: daemon = pyclamd.ClamdUnixSocket(socket) except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return if not __sessions__.is_set(): self.log('error', "No session opened") return try: if not daemon: daemon = pyclamd.ClamdUnixSocket() socket = 'Clamav' except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return try: if daemon.ping(): results = daemon.scan_file(__sessions__.current.file.path) else: self.log('error', "Unable to connect to the daemon") except Exception as e: self.log('error', "Unable to scan with antivirus daemon, {0}".format(e)) return found = None name = 'not found' if results: for item in results: found = results[item][0] name = results[item][1] if found == 'ERROR': self.log('error', "Check permissions of the binary folder, {0}".format(name)) else: self.log('info', "Daemon {0} returns: {1}".format(socket, name))
usage() self.log('', "") self.log('', "Options:") self.log('', "\t--help (-h)\tShow this help message") self.log('', "\t--socket(-s)\tSpecify an unix socket (default: Clamd Unix Socket)") self.log('', "")
identifier_body
clamav.py
# This file is part of Viper - https://github.com/botherder/viper # See the file 'LICENSE' for copying permission. import getopt try: import pyclamd HAVE_CLAMD = True except ImportError: HAVE_CLAMD = False from viper.common.out import * from viper.common.abstracts import Module from viper.core.session import __sessions__ class ClamAV(Module): cmd = 'clamav' description = 'Scan file from local ClamAV daemon' authors = ['neriberto'] def run(self): def
(): self.log('', "usage: clamav [-h] [-s]") def help(): usage() self.log('', "") self.log('', "Options:") self.log('', "\t--help (-h)\tShow this help message") self.log('', "\t--socket(-s)\tSpecify an unix socket (default: Clamd Unix Socket)") self.log('', "") if not HAVE_CLAMD: self.log('error', "Missing dependency, install requests (`pip install pyclamd`)") return try: opts, argv = getopt.getopt(self.args, 'hs:', ['help', 'socket=']) except getopt.GetoptError as e: self.log('', e) usage() return daemon = None result = None socket = None for opt, value in opts: if opt in ('-h', '--help'): help() return elif opt in ('-s', '--socket'): self.log('info', "Using socket {0} to connect to ClamAV daemon".format(value)) socket = value try: daemon = pyclamd.ClamdUnixSocket(socket) except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return if not __sessions__.is_set(): self.log('error', "No session opened") return try: if not daemon: daemon = pyclamd.ClamdUnixSocket() socket = 'Clamav' except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return try: if daemon.ping(): results = daemon.scan_file(__sessions__.current.file.path) else: self.log('error', "Unable to connect to the daemon") except Exception as e: self.log('error', "Unable to scan with antivirus daemon, {0}".format(e)) return found = None name = 'not found' if results: for item in results: found = results[item][0] name = results[item][1] if found == 'ERROR': self.log('error', "Check permissions of the binary folder, {0}".format(name)) else: self.log('info', "Daemon {0} returns: {1}".format(socket, name))
usage
identifier_name
clamav.py
# This file is part of Viper - https://github.com/botherder/viper # See the file 'LICENSE' for copying permission. import getopt try: import pyclamd HAVE_CLAMD = True except ImportError: HAVE_CLAMD = False from viper.common.out import * from viper.common.abstracts import Module from viper.core.session import __sessions__ class ClamAV(Module): cmd = 'clamav' description = 'Scan file from local ClamAV daemon' authors = ['neriberto'] def run(self): def usage(): self.log('', "usage: clamav [-h] [-s]") def help(): usage() self.log('', "") self.log('', "Options:") self.log('', "\t--help (-h)\tShow this help message") self.log('', "\t--socket(-s)\tSpecify an unix socket (default: Clamd Unix Socket)") self.log('', "") if not HAVE_CLAMD: self.log('error', "Missing dependency, install requests (`pip install pyclamd`)") return try: opts, argv = getopt.getopt(self.args, 'hs:', ['help', 'socket=']) except getopt.GetoptError as e: self.log('', e) usage() return daemon = None result = None socket = None for opt, value in opts:
if not __sessions__.is_set(): self.log('error', "No session opened") return try: if not daemon: daemon = pyclamd.ClamdUnixSocket() socket = 'Clamav' except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return try: if daemon.ping(): results = daemon.scan_file(__sessions__.current.file.path) else: self.log('error', "Unable to connect to the daemon") except Exception as e: self.log('error', "Unable to scan with antivirus daemon, {0}".format(e)) return found = None name = 'not found' if results: for item in results: found = results[item][0] name = results[item][1] if found == 'ERROR': self.log('error', "Check permissions of the binary folder, {0}".format(name)) else: self.log('info', "Daemon {0} returns: {1}".format(socket, name))
if opt in ('-h', '--help'): help() return elif opt in ('-s', '--socket'): self.log('info', "Using socket {0} to connect to ClamAV daemon".format(value)) socket = value try: daemon = pyclamd.ClamdUnixSocket(socket) except Exception as e: self.log('error', "Daemon connection failure, {0}".format(e)) return
conditional_block
index.tsx
import React from "react"; import Scrap from "../../Models/Scrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faEdit } from "@fortawesome/free-solid-svg-icons"; import WindowService from "../../../Services/Window"; class ScrapCell extends React.Component<{ scrap: Scrap, }, {}> { render() { const { scrap } = this.props; return ( <div className="column col-4"> <div className="card"> <div className="card-image"> <img src={scrap.url} className="img-responsive" /> </div> <div className="card-footer"> <button className="btn btn-primary float-right"> <FontAwesomeIcon icon={faEdit} onClick={() => { WindowService.getInstance().openCapturePage({ url: scrap.url, filename: scrap.name }); }} /> </button> {scrap.name} </div> </div> </div> ); } } export default class ArchiveView extends React.Component<{}, { scraps: Scrap[], }> { constructor(props) { super(props); this.state = { scraps: Scrap.list(), }; }
() { const { scraps } = this.state; return ( <div className="container"> <div className="columns"> {scraps.map(scrap => <ScrapCell key={scrap._id} scrap={scrap} />)} </div> <div className="columns"> <div className="column">TOTAL: {scraps.length}</div> </div> </div> ); } }
render
identifier_name
index.tsx
import React from "react"; import Scrap from "../../Models/Scrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faEdit } from "@fortawesome/free-solid-svg-icons"; import WindowService from "../../../Services/Window"; class ScrapCell extends React.Component<{ scrap: Scrap, }, {}> { render() { const { scrap } = this.props; return ( <div className="column col-4"> <div className="card"> <div className="card-image"> <img src={scrap.url} className="img-responsive" /> </div> <div className="card-footer"> <button className="btn btn-primary float-right"> <FontAwesomeIcon icon={faEdit} onClick={() => {
{scrap.name} </div> </div> </div> ); } } export default class ArchiveView extends React.Component<{}, { scraps: Scrap[], }> { constructor(props) { super(props); this.state = { scraps: Scrap.list(), }; } render() { const { scraps } = this.state; return ( <div className="container"> <div className="columns"> {scraps.map(scrap => <ScrapCell key={scrap._id} scrap={scrap} />)} </div> <div className="columns"> <div className="column">TOTAL: {scraps.length}</div> </div> </div> ); } }
WindowService.getInstance().openCapturePage({ url: scrap.url, filename: scrap.name }); }} /> </button>
random_line_split
config.global.js
{%- from "opencontrail/map.jinja" import web with context %} /* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ var config = {}; config.orchestration = {}; config.orchestration.Manager = 'openstack' {%- if web.identity.version == "3" %} config.multi_tenancy = {}; config.multi_tenancy.enabled = true; {%- endif %} /**************************************************************************** * This boolean flag indicates to communicate with Orchestration * modules(networkManager, imageManager, computeManager, identityManager, * storageManager), should the webServer communicate using the * ip/port/authProtocol/apiVersion as specified in this file, or as returned * from auth catalog list. * Note: config.identityManager.apiVersion is not controlled by this boolean * flag. * * true - These values should be taken from this config * file. * false - These values should be taken from auth catalog list * *****************************************************************************/ config.serviceEndPointFromConfig = true; /**************************************************************************** * This boolean flag indicates if serviceEndPointFromConfig is set as false, * then to take IP/Port/Protocol/Version information from auth catalog, * should publicURL OR internalURL will be used. * * true - publicURL in endpoint will be used to retrieve IP/Port/Protocol/ * Version information * false - internalURL in endpoint will be used to retrieve * IP/Port/Protocol/Version information * * NOTE: if config.serviceEndPointFromConfig is set as true, then this flag * does not have any effect. * *****************************************************************************/ config.serviceEndPointTakePublicURL = true; /**************************************************************************** * Below are the config options for all Orchestration Modules below: * - networkManager * - imageManager * - computeManager * - identityManager * - storageManager * - cnfg * - analytics * * Options: * ip: * IP to connect to for this Server. * port: * Port to connect to for this server * authProtocol: * Specify authProtocol either 'http' or 'https' * apiVersion: * REST API Version for this server to connect to. * Specify a list of Versions in array notation. * Below are the supported list of apiVersion for the modules as of now: * imageManager - ['v1', 'v2'] * computeManager - ['v1.1', 'v2'] * identityManager - ['v2.0'] * storageManager - ['v1'] * * Not applicable for cnfg/analytics as of now * strictSSL: * If true, requires certificates to be valid * ca: * An authority certificate to check the remote host against, * if you do not want to specify then use '' *****************************************************************************/ config.networkManager = {}; config.networkManager.ip = '{{ web.master.host }}'; config.networkManager.port = '9696' config.networkManager.authProtocol = 'http'; config.networkManager.apiVersion = []; config.networkManager.strictSSL = false; config.networkManager.ca = ''; config.imageManager = {}; config.imageManager.ip = '{{ web.identity.host }}'; config.imageManager.port = '9292'; config.imageManager.authProtocol = 'http'; config.imageManager.apiVersion = ['v1', 'v2']; config.imageManager.strictSSL = false; config.imageManager.ca = ''; config.computeManager = {}; config.computeManager.ip = '{{ web.identity.host }}'; config.computeManager.port = '8774'; config.computeManager.authProtocol = 'http'; config.computeManager.apiVersion = ['v1.1', 'v2']; config.computeManager.strictSSL = false; config.computeManager.ca = ''; config.identityManager = {}; config.identityManager.ip = '{{ web.identity.host }}'; config.identityManager.port = '5000'; config.identityManager.authProtocol = 'http'; /****************************************************************************** * Note: config.identityManager.apiVersion is not controlled by boolean flag * config.serviceEndPointFromConfig. If specified apiVersion here, then these * API versions will be used while using REST API to identityManager. * If want to use with default apiVersion(v2.0), then can specify it as * empty array. ******************************************************************************/ config.identityManager.apiVersion = ['v{{ web.identity.version }}']; config.identityManager.strictSSL = false; config.identityManager.ca = ''; config.storageManager = {}; config.storageManager.ip = '{{ web.identity.host }}'; config.storageManager.port = '8776'; config.storageManager.authProtocol = 'http'; config.storageManager.apiVersion = ['v1']; config.storageManager.strictSSL = false; config.storageManager.ca = ''; // VNConfig API server and port. config.cnfg = {}; config.cnfg.server_ip = '{{ web.master.host }}'; config.cnfg.server_port = '8082'; config.cnfg.authProtocol = 'http'; config.cnfg.strictSSL = false; config.cnfg.ca = ''; // Analytics API server and port. config.analytics = {}; config.analytics.server_ip = '{{ web.analytics.host }}'; config.analytics.server_port = '9081'; config.analytics.authProtocol = 'http'; config.analytics.strictSSL = false; config.analytics.ca = ''; // vcenter related parameters config.vcenter = {}; config.vcenter.server_ip = '127.0.0.1'; //vCenter IP config.vcenter.server_port = '443'; //Port config.vcenter.authProtocol = 'https'; //http or https config.vcenter.datacenter = 'vcenter'; //datacenter name config.vcenter.dvsswitch = 'vswitch'; //dvsswitch name config.vcenter.strictSSL = false; //Validate the certificate or ignore config.vcenter.ca = ''; //specify the certificate key file config.vcenter.wsdl = '/var/lib/contrail-webui/contrail-web-core/webroot/js/vim.wsdl'; /* Discovery Service */ config.discoveryService = {}; config.discoveryService.server_port = '5998'; /* Specifiy true if subscription to discovery server should be enabled, else * specify false. Other than true/false value here is treated as true */ config.discoveryService.enable = true; /* Job Server */ config.jobServer = {}; config.jobServer.server_ip = '127.0.0.1'; config.jobServer.server_port = '3000'; /* Upload/Download Directory */ config.files = {}; config.files.download_path = '/tmp'; /* WebUI Redis Server */ config.redis_server_port = '6379'; config.redis_server_ip = '127.0.0.1'; config.redis_dump_file = '/var/lib/redis/dump-webui.rdb'; config.redis_password = ''; /* Cassandra Server */ config.cassandra = {}; config.cassandra.server_ips = [{%- for member in web.members %}'{{ member.host }}'{% if not loop.last %},{% endif %}{%- endfor %}]; config.cassandra.server_port = '9160'; config.cassandra.enable_edit = false; /* KUE Job Scheduler */ config.kue = {}; config.kue.ui_port = '3002' /* IP List to listen on */ config.webui_addresses = ['0.0.0.0']; /* Is insecure access to WebUI? * If set as false, then all http request will be redirected * to https, if set true, then no https request will be processed, but only http * request */ config.insecure_access = false; // HTTP port for NodeJS Server. config.http_port = '8080'; // HTTPS port for NodeJS Server. config.https_port = '8143'; // Activate/Deactivate Login. config.require_auth = false; /* Number of node worker processes for cluster. */ config.node_worker_count = 1; /* Number of Parallel Active Jobs with same type */ config.maxActiveJobs = 10; /* Redis DB index for Web-UI */ config.redisDBIndex = 3; {% if grains.os_family == "Debian" %} /* Logo File: Use complete path of logo file location */ config.logo_file = '/var/lib/contrail-webui/contrail-web-core/webroot/img/opencontrail-logo.png'; /* Favicon File: Use complete path of favicon file location */ config.favicon_file = '/var/lib/contrail-webui/contrail-web-core/webroot/img/juniper-networks-favicon.ico'; config.featurePkg = {}; /* Add new feature Package Config details below */ config.featurePkg.webController = {}; config.featurePkg.webController.path = '/var/lib/contrail-webui/contrail-web-controller'; config.featurePkg.webController.enable = true; {% elif grains.os_family == "RedHat" %} config.logo_file = '/usr/src/contrail/contrail-web-core/webroot/img/juniper-networks-logo.png'; /* Favicon File: Use complete path of favicon file location */ config.favicon_file = '/usr/src/contrail/contrail-web-core/webroot/img/juniper-networks-favicon.ico'; config.featurePkg = {}; /* Add new feature Package Config details below */ config.featurePkg.webController = {}; config.featurePkg.webController.path = '/usr/src/contrail/contrail-web-controller'; config.featurePkg.webController.enable = true; {% endif %} /* Enable/disable Stat Query Links in Sidebar*/
debug, info, notice, warning, error, crit, alert, emerg */ config.logs = {}; config.logs.level = 'debug'; /****************************************************************************** * Boolean flag getDomainProjectsFromApiServer indicates wheather the project * list should come from API Server or Identity Manager. * If Set * - true, then project list will come from API Server * - false, then project list will come from Identity Manager * Default: false * ******************************************************************************/ config.getDomainProjectsFromApiServer = false; /***************************************************************************** * Boolean flag L2_enable indicates the default forwarding-mode of a network. * Allowed values : true / false * Set this flag to true if all the networks are to be L2 networks, * set to false otherwise. *****************************************************************************/ config.network = {}; config.network.L2_enable = false; /****************************************************************************** * Boolean flag getDomainsFromApiServer indicates wheather the domain * list should come from API Server or Identity Manager. * If Set * - true, then domain list will come from API Server * - false, then domain list will come from Identity Manager * Default: true * NOTE: if config.identityManager.apiVersion is set as v2.0, then this flag * does not have any effect, in that case the domain list is retrieved * from API Server. * *****************************************************************************/ config.getDomainsFromApiServer = false; // Export this as a module. module.exports = config; config.features = {}; config.features.disabled = [];
config.qe = {}; config.qe.enable_stat_queries = false; /* Configure level of logs, supported log levels are:
random_line_split
slice-panic-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that if a slicing expr[..] fails, the correct cleanups happen. // pretty-expanded FIXME #23616 use std::thread; struct
; static mut DTOR_COUNT: isize = 0; impl Drop for Foo { fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } } } fn bar() -> usize { panic!(); } fn foo() { let x: &[_] = &[Foo, Foo]; &x[3..bar()]; } fn main() { let _ = thread::spawn(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); } }
Foo
identifier_name
slice-panic-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that if a slicing expr[..] fails, the correct cleanups happen. // pretty-expanded FIXME #23616 use std::thread; struct Foo; static mut DTOR_COUNT: isize = 0; impl Drop for Foo { fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } } } fn bar() -> usize { panic!(); } fn foo() { let x: &[_] = &[Foo, Foo]; &x[3..bar()]; } fn main() { let _ = thread::spawn(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); }
}
random_line_split
slice-panic-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that if a slicing expr[..] fails, the correct cleanups happen. // pretty-expanded FIXME #23616 use std::thread; struct Foo; static mut DTOR_COUNT: isize = 0; impl Drop for Foo { fn drop(&mut self) { unsafe { DTOR_COUNT += 1; } } } fn bar() -> usize
fn foo() { let x: &[_] = &[Foo, Foo]; &x[3..bar()]; } fn main() { let _ = thread::spawn(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); } }
{ panic!(); }
identifier_body
issue-30530.rs
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for Issue #30530: alloca's created for storing // intermediate scratch values during brace-less match arms need to be // initialized with their drop-flag set to "dropped" (or else we end // up running the destructors on garbage data at the end of the // function). pub enum
{ Default, #[allow(dead_code)] Custom(*mut Box<dyn Fn()>), } fn main() { #[allow(unused_must_use)] { take(Handler::Default, Box::new(main)); } } #[inline(never)] pub fn take(h: Handler, f: Box<dyn Fn()>) -> Box<dyn Fn()> { unsafe { match h { Handler::Custom(ptr) => *Box::from_raw(ptr), Handler::Default => f, } } }
Handler
identifier_name
issue-30530.rs
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for Issue #30530: alloca's created for storing // intermediate scratch values during brace-less match arms need to be // initialized with their drop-flag set to "dropped" (or else we end // up running the destructors on garbage data at the end of the // function). pub enum Handler { Default,
Custom(*mut Box<dyn Fn()>), } fn main() { #[allow(unused_must_use)] { take(Handler::Default, Box::new(main)); } } #[inline(never)] pub fn take(h: Handler, f: Box<dyn Fn()>) -> Box<dyn Fn()> { unsafe { match h { Handler::Custom(ptr) => *Box::from_raw(ptr), Handler::Default => f, } } }
#[allow(dead_code)]
random_line_split
issue-30530.rs
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for Issue #30530: alloca's created for storing // intermediate scratch values during brace-less match arms need to be // initialized with their drop-flag set to "dropped" (or else we end // up running the destructors on garbage data at the end of the // function). pub enum Handler { Default, #[allow(dead_code)] Custom(*mut Box<dyn Fn()>), } fn main() { #[allow(unused_must_use)] { take(Handler::Default, Box::new(main)); } } #[inline(never)] pub fn take(h: Handler, f: Box<dyn Fn()>) -> Box<dyn Fn()>
{ unsafe { match h { Handler::Custom(ptr) => *Box::from_raw(ptr), Handler::Default => f, } } }
identifier_body
grid-layout.helper.ts
import { scaleBand } from 'd3-scale'; export function gridSize(dims, len, minWidth) { let rows = 1; let cols = len; const width = dims.width; if (width > minWidth)
return [cols, rows]; } export function gridLayout(dims, data, minWidth, designatedTotal) { const xScale: any = scaleBand<number>(); const yScale: any = scaleBand<number>(); const width = dims.width; const height = dims.height; const [columns, rows] = gridSize(dims, data.length, minWidth); const xDomain = []; const yDomain = []; for (let i = 0; i < rows; i++) { yDomain.push(i); } for (let i = 0; i < columns; i++) { xDomain.push(i); } xScale.domain(xDomain); yScale.domain(yDomain); xScale.rangeRound([0, width], 0.1); yScale.rangeRound([0, height], 0.1); const res = []; const total = designatedTotal ? designatedTotal : getTotal(data); const cardWidth = xScale.bandwidth(); const cardHeight = yScale.bandwidth(); for (let i = 0; i < data.length; i++) { res[i] = {}; res[i].data = { name: data[i] ? data[i].name : '', value: data[i] ? data[i].value : undefined, extra: data[i] ? data[i].extra : undefined, }; res[i].x = xScale(i % columns); res[i].y = yScale(Math.floor(i / columns)); res[i].width = cardWidth; res[i].height = cardHeight; res[i].data.percent = (total > 0) ? res[i].data.value / total : 0; res[i].data.total = total; } return res; } function getTotal(results) { return results .map(d => d ? d.value : 0) .reduce((sum, val) => sum + val, 0); }
{ while (width / cols < minWidth) { rows += 1; cols = Math.ceil(len / rows); } }
conditional_block
grid-layout.helper.ts
import { scaleBand } from 'd3-scale'; export function gridSize(dims, len, minWidth) { let rows = 1; let cols = len; const width = dims.width; if (width > minWidth) { while (width / cols < minWidth) { rows += 1; cols = Math.ceil(len / rows); } } return [cols, rows]; } export function
(dims, data, minWidth, designatedTotal) { const xScale: any = scaleBand<number>(); const yScale: any = scaleBand<number>(); const width = dims.width; const height = dims.height; const [columns, rows] = gridSize(dims, data.length, minWidth); const xDomain = []; const yDomain = []; for (let i = 0; i < rows; i++) { yDomain.push(i); } for (let i = 0; i < columns; i++) { xDomain.push(i); } xScale.domain(xDomain); yScale.domain(yDomain); xScale.rangeRound([0, width], 0.1); yScale.rangeRound([0, height], 0.1); const res = []; const total = designatedTotal ? designatedTotal : getTotal(data); const cardWidth = xScale.bandwidth(); const cardHeight = yScale.bandwidth(); for (let i = 0; i < data.length; i++) { res[i] = {}; res[i].data = { name: data[i] ? data[i].name : '', value: data[i] ? data[i].value : undefined, extra: data[i] ? data[i].extra : undefined, }; res[i].x = xScale(i % columns); res[i].y = yScale(Math.floor(i / columns)); res[i].width = cardWidth; res[i].height = cardHeight; res[i].data.percent = (total > 0) ? res[i].data.value / total : 0; res[i].data.total = total; } return res; } function getTotal(results) { return results .map(d => d ? d.value : 0) .reduce((sum, val) => sum + val, 0); }
gridLayout
identifier_name
grid-layout.helper.ts
import { scaleBand } from 'd3-scale'; export function gridSize(dims, len, minWidth) { let rows = 1; let cols = len; const width = dims.width; if (width > minWidth) { while (width / cols < minWidth) { rows += 1; cols = Math.ceil(len / rows); } } return [cols, rows]; } export function gridLayout(dims, data, minWidth, designatedTotal) { const xScale: any = scaleBand<number>(); const yScale: any = scaleBand<number>(); const width = dims.width; const height = dims.height; const [columns, rows] = gridSize(dims, data.length, minWidth); const xDomain = []; const yDomain = []; for (let i = 0; i < rows; i++) { yDomain.push(i); } for (let i = 0; i < columns; i++) { xDomain.push(i); } xScale.domain(xDomain); yScale.domain(yDomain); xScale.rangeRound([0, width], 0.1); yScale.rangeRound([0, height], 0.1); const res = []; const total = designatedTotal ? designatedTotal : getTotal(data); const cardWidth = xScale.bandwidth(); const cardHeight = yScale.bandwidth(); for (let i = 0; i < data.length; i++) { res[i] = {}; res[i].data = { name: data[i] ? data[i].name : '', value: data[i] ? data[i].value : undefined, extra: data[i] ? data[i].extra : undefined, }; res[i].x = xScale(i % columns); res[i].y = yScale(Math.floor(i / columns)); res[i].width = cardWidth; res[i].height = cardHeight; res[i].data.percent = (total > 0) ? res[i].data.value / total : 0; res[i].data.total = total; } return res; } function getTotal(results)
{ return results .map(d => d ? d.value : 0) .reduce((sum, val) => sum + val, 0); }
identifier_body
grid-layout.helper.ts
import { scaleBand } from 'd3-scale'; export function gridSize(dims, len, minWidth) { let rows = 1; let cols = len; const width = dims.width; if (width > minWidth) { while (width / cols < minWidth) { rows += 1; cols = Math.ceil(len / rows); } } return [cols, rows]; } export function gridLayout(dims, data, minWidth, designatedTotal) { const xScale: any = scaleBand<number>(); const yScale: any = scaleBand<number>(); const width = dims.width; const height = dims.height; const [columns, rows] = gridSize(dims, data.length, minWidth); const xDomain = []; const yDomain = []; for (let i = 0; i < rows; i++) { yDomain.push(i); } for (let i = 0; i < columns; i++) { xDomain.push(i); } xScale.domain(xDomain); yScale.domain(yDomain);
const res = []; const total = designatedTotal ? designatedTotal : getTotal(data); const cardWidth = xScale.bandwidth(); const cardHeight = yScale.bandwidth(); for (let i = 0; i < data.length; i++) { res[i] = {}; res[i].data = { name: data[i] ? data[i].name : '', value: data[i] ? data[i].value : undefined, extra: data[i] ? data[i].extra : undefined, }; res[i].x = xScale(i % columns); res[i].y = yScale(Math.floor(i / columns)); res[i].width = cardWidth; res[i].height = cardHeight; res[i].data.percent = (total > 0) ? res[i].data.value / total : 0; res[i].data.total = total; } return res; } function getTotal(results) { return results .map(d => d ? d.value : 0) .reduce((sum, val) => sum + val, 0); }
xScale.rangeRound([0, width], 0.1); yScale.rangeRound([0, height], 0.1);
random_line_split
security-group-page.component.ts
import { Component, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { SecurityGroup } from '../sg.model'; import { ViewMode } from '../../shared/components/view-mode-switch/view-mode-switch.component'; import { ListService } from '../../shared/components/list/list.service'; import { SecurityGroupViewMode } from '../sg-view-mode'; import { VirtualMachine } from '../../vm'; import { NgrxEntities } from '../../shared/interfaces'; @Component({ selector: 'cs-security-group-page', templateUrl: 'security-group-page.component.html', styleUrls: ['security-group-page.component.scss'], providers: [ListService], }) export class SecurityGroupPageComponent { @Input() public securityGroups: SecurityGroup[]; @Input() public isLoading = false; @Input() public viewMode: SecurityGroupViewMode; @Input() public query: string; @Input() public vmList: NgrxEntities<VirtualMachine>; public mode: ViewMode; public viewModeKey = 'sgPageViewMode'; public get isCreationEnabled(): boolean
constructor( private router: Router, private activatedRoute: ActivatedRoute, public listService: ListService, ) {} public get showSidebarDetails(): boolean { return this.activatedRoute.snapshot.firstChild.firstChild.routeConfig.path === 'details'; } public changeMode(mode) { this.mode = mode; } public showCreationDialog(): void { this.router.navigate(['./create'], { queryParamsHandling: 'preserve', relativeTo: this.activatedRoute, }); } }
{ return this.viewMode !== SecurityGroupViewMode.Private; }
identifier_body
security-group-page.component.ts
import { Component, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { SecurityGroup } from '../sg.model'; import { ViewMode } from '../../shared/components/view-mode-switch/view-mode-switch.component'; import { ListService } from '../../shared/components/list/list.service'; import { SecurityGroupViewMode } from '../sg-view-mode'; import { VirtualMachine } from '../../vm'; import { NgrxEntities } from '../../shared/interfaces'; @Component({ selector: 'cs-security-group-page', templateUrl: 'security-group-page.component.html', styleUrls: ['security-group-page.component.scss'], providers: [ListService], }) export class SecurityGroupPageComponent { @Input() public securityGroups: SecurityGroup[]; @Input() public isLoading = false; @Input() public viewMode: SecurityGroupViewMode; @Input() public query: string; @Input() public vmList: NgrxEntities<VirtualMachine>; public mode: ViewMode; public viewModeKey = 'sgPageViewMode'; public get isCreationEnabled(): boolean { return this.viewMode !== SecurityGroupViewMode.Private; } constructor( private router: Router, private activatedRoute: ActivatedRoute, public listService: ListService, ) {}
public get showSidebarDetails(): boolean { return this.activatedRoute.snapshot.firstChild.firstChild.routeConfig.path === 'details'; } public changeMode(mode) { this.mode = mode; } public showCreationDialog(): void { this.router.navigate(['./create'], { queryParamsHandling: 'preserve', relativeTo: this.activatedRoute, }); } }
random_line_split
security-group-page.component.ts
import { Component, Input } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { SecurityGroup } from '../sg.model'; import { ViewMode } from '../../shared/components/view-mode-switch/view-mode-switch.component'; import { ListService } from '../../shared/components/list/list.service'; import { SecurityGroupViewMode } from '../sg-view-mode'; import { VirtualMachine } from '../../vm'; import { NgrxEntities } from '../../shared/interfaces'; @Component({ selector: 'cs-security-group-page', templateUrl: 'security-group-page.component.html', styleUrls: ['security-group-page.component.scss'], providers: [ListService], }) export class SecurityGroupPageComponent { @Input() public securityGroups: SecurityGroup[]; @Input() public isLoading = false; @Input() public viewMode: SecurityGroupViewMode; @Input() public query: string; @Input() public vmList: NgrxEntities<VirtualMachine>; public mode: ViewMode; public viewModeKey = 'sgPageViewMode'; public get isCreationEnabled(): boolean { return this.viewMode !== SecurityGroupViewMode.Private; }
( private router: Router, private activatedRoute: ActivatedRoute, public listService: ListService, ) {} public get showSidebarDetails(): boolean { return this.activatedRoute.snapshot.firstChild.firstChild.routeConfig.path === 'details'; } public changeMode(mode) { this.mode = mode; } public showCreationDialog(): void { this.router.navigate(['./create'], { queryParamsHandling: 'preserve', relativeTo: this.activatedRoute, }); } }
constructor
identifier_name
remoteIndicator.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { STATUS_BAR_HOST_NAME_BACKGROUND, STATUS_BAR_HOST_NAME_FOREGROUND } from 'vs/workbench/common/theme'; import { themeColorFromId } from 'vs/platform/theme/common/themeService'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { Disposable, dispose } from 'vs/base/common/lifecycle'; import { MenuId, IMenuService, MenuItemAction, MenuRegistry, registerAction2, Action2, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/browser/statusbar'; import { ILabelService } from 'vs/platform/label/common/label'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { Schemas } from 'vs/base/common/network'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { isWeb } from 'vs/base/common/platform'; import { once } from 'vs/base/common/functional'; import { truncate } from 'vs/base/common/strings'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { getRemoteName } from 'vs/platform/remote/common/remoteHosts'; import { getVirtualWorkspaceLocation } from 'vs/platform/workspace/common/virtualWorkspace'; import { getCodiconAriaLabel } from 'vs/base/common/codicons'; import { ILogService } from 'vs/platform/log/common/log'; import { ReloadWindowAction } from 'vs/workbench/browser/actions/windowActions'; import { IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionsViewPaneContainer, LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID, VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { RemoteNameContext, VirtualWorkspaceContext } from 'vs/workbench/common/contextkeys'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { ViewContainerLocation } from 'vs/workbench/common/views'; type ActionGroup = [string, Array<MenuItemAction | SubmenuItemAction>]; export class RemoteStatusIndicator extends Disposable implements IWorkbenchContribution { private static readonly REMOTE_ACTIONS_COMMAND_ID = 'workbench.action.remote.showMenu'; private static readonly CLOSE_REMOTE_COMMAND_ID = 'workbench.action.remote.close'; private static readonly SHOW_CLOSE_REMOTE_COMMAND_ID = !isWeb; // web does not have a "Close Remote" command private static readonly INSTALL_REMOTE_EXTENSIONS_ID = 'workbench.action.remote.extensions'; private static readonly REMOTE_STATUS_LABEL_MAX_LENGTH = 40; private remoteStatusEntry: IStatusbarEntryAccessor | undefined; private readonly legacyIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService)); // to be removed once migration completed private readonly remoteIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarRemoteIndicatorMenu, this.contextKeyService)); private remoteMenuActionsGroups: ActionGroup[] | undefined; private readonly remoteAuthority = this.environmentService.remoteAuthority; private virtualWorkspaceLocation: { scheme: string; authority: string } | undefined = undefined; private connectionState: 'initializing' | 'connected' | 'reconnecting' | 'disconnected' | undefined = undefined; private readonly connectionStateContextKey = new RawContextKey<'' | 'initializing' | 'disconnected' | 'connected'>('remoteConnectionState', '').bindTo(this.contextKeyService); private loggedInvalidGroupNames: { [group: string]: boolean } = Object.create(null); constructor( @IStatusbarService private readonly statusbarService: IStatusbarService, @IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService, @ILabelService private readonly labelService: ILabelService, @IContextKeyService private contextKeyService: IContextKeyService, @IMenuService private menuService: IMenuService, @IQuickInputService private readonly quickInputService: IQuickInputService, @ICommandService private readonly commandService: ICommandService, @IExtensionService private readonly extensionService: IExtensionService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, @IRemoteAuthorityResolverService private readonly remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IHostService private readonly hostService: IHostService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @ILogService private readonly logService: ILogService, @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService ) { super(); // Set initial connection state if (this.remoteAuthority) { this.connectionState = 'initializing'; this.connectionStateContextKey.set(this.connectionState); } else { this.updateVirtualWorkspaceLocation(); } this.registerActions(); this.registerListeners(); this.updateWhenInstalledExtensionsRegistered(); this.updateRemoteStatusIndicator(); } private registerActions(): void { const category = { value: nls.localize('remote.category', "Remote"), original: 'Remote' }; // Show Remote Menu const that = this; registerAction2(class extends Action2 { constructor()
run = () => that.showRemoteMenu(); }); // Close Remote Connection if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, category, title: { value: nls.localize('remote.close', "Close Remote Connection"), original: 'Close Remote Connection' }, f1: true, precondition: ContextKeyExpr.or(RemoteNameContext, VirtualWorkspaceContext) }); } run = () => that.hostService.openWindow({ forceReuseWindow: true, remoteAuthority: null }); }); if (this.remoteAuthority) { MenuRegistry.appendMenuItem(MenuId.MenubarFileMenu, { group: '6_close', command: { id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, title: nls.localize({ key: 'miCloseRemote', comment: ['&& denotes a mnemonic'] }, "Close Re&&mote Connection") }, order: 3.5 }); } } if (this.extensionGalleryService.isEnabled()) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, category, title: { value: nls.localize('remote.install', "Install Remote Development Extensions"), original: 'Install Remote Development Extensions' }, f1: true }); } run = (accessor: ServicesAccessor, input: string) => { const paneCompositeService = accessor.get(IPaneCompositePartService); return paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true).then(viewlet => { if (viewlet) { (viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer).search(`tag:"remote-menu"`); viewlet.focus(); } }); }; }); } } private registerListeners(): void { // Menu changes const updateRemoteActions = () => { this.remoteMenuActionsGroups = undefined; this.updateRemoteStatusIndicator(); }; this._register(this.legacyIndicatorMenu.onDidChange(updateRemoteActions)); this._register(this.remoteIndicatorMenu.onDidChange(updateRemoteActions)); // Update indicator when formatter changes as it may have an impact on the remote label this._register(this.labelService.onDidChangeFormatters(() => this.updateRemoteStatusIndicator())); // Update based on remote indicator changes if any const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator && remoteIndicator.onDidChange) { this._register(remoteIndicator.onDidChange(() => this.updateRemoteStatusIndicator())); } // Listen to changes of the connection if (this.remoteAuthority) { const connection = this.remoteAgentService.getConnection(); if (connection) { this._register(connection.onDidStateChange((e) => { switch (e.type) { case PersistentConnectionEventType.ConnectionLost: case PersistentConnectionEventType.ReconnectionRunning: case PersistentConnectionEventType.ReconnectionWait: this.setState('reconnecting'); break; case PersistentConnectionEventType.ReconnectionPermanentFailure: this.setState('disconnected'); break; case PersistentConnectionEventType.ConnectionGain: this.setState('connected'); break; } })); } } else { this._register(this.workspaceContextService.onDidChangeWorkbenchState(() => { this.updateVirtualWorkspaceLocation(); this.updateRemoteStatusIndicator(); })); } } private updateVirtualWorkspaceLocation() { this.virtualWorkspaceLocation = getVirtualWorkspaceLocation(this.workspaceContextService.getWorkspace()); } private async updateWhenInstalledExtensionsRegistered(): Promise<void> { await this.extensionService.whenInstalledExtensionsRegistered(); const remoteAuthority = this.remoteAuthority; if (remoteAuthority) { // Try to resolve the authority to figure out connection state (async () => { try { await this.remoteAuthorityResolverService.resolveAuthority(remoteAuthority); this.setState('connected'); } catch (error) { this.setState('disconnected'); } })(); } this.updateRemoteStatusIndicator(); } private setState(newState: 'disconnected' | 'connected' | 'reconnecting'): void { if (this.connectionState !== newState) { this.connectionState = newState; // simplify context key which doesn't support `connecting` if (this.connectionState === 'reconnecting') { this.connectionStateContextKey.set('disconnected'); } else { this.connectionStateContextKey.set(this.connectionState); } this.updateRemoteStatusIndicator(); } } private validatedGroup(group: string) { if (!group.match(/^(remote|virtualfs)_(\d\d)_(([a-z][a-z0-9+.-]*)_(.*))$/)) { if (!this.loggedInvalidGroupNames[group]) { this.loggedInvalidGroupNames[group] = true; this.logService.warn(`Invalid group name used in "statusBar/remoteIndicator" menu contribution: ${group}. Entries ignored. Expected format: 'remote_$ORDER_$REMOTENAME_$GROUPING or 'virtualfs_$ORDER_$FILESCHEME_$GROUPING.`); } return false; } return true; } private getRemoteMenuActions(doNotUseCache?: boolean): ActionGroup[] { if (!this.remoteMenuActionsGroups || doNotUseCache) { this.remoteMenuActionsGroups = this.remoteIndicatorMenu.getActions().filter(a => this.validatedGroup(a[0])).concat(this.legacyIndicatorMenu.getActions()); } return this.remoteMenuActionsGroups; } private updateRemoteStatusIndicator(): void { // Remote Indicator: show if provided via options, e.g. by the web embedder API const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator) { this.renderRemoteStatusIndicator(truncate(remoteIndicator.label, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH), remoteIndicator.tooltip, remoteIndicator.command); return; } // Show for remote windows on the desktop, but not when in code server web if (this.remoteAuthority && !isWeb) { const hostLabel = this.labelService.getHostLabel(Schemas.vscodeRemote, this.remoteAuthority) || this.remoteAuthority; switch (this.connectionState) { case 'initializing': this.renderRemoteStatusIndicator(nls.localize('host.open', "Opening Remote..."), nls.localize('host.open', "Opening Remote..."), undefined, true /* progress */); break; case 'reconnecting': this.renderRemoteStatusIndicator(`${nls.localize('host.reconnecting', "Reconnecting to {0}...", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`, undefined, undefined, true); break; case 'disconnected': this.renderRemoteStatusIndicator(`$(alert) ${nls.localize('disconnectedFrom', "Disconnected from {0}", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`); break; default: { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(Schemas.vscodeRemote, this.remoteAuthority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'host.tooltip', comment: ['{0} is a remote host name, e.g. Dev Container'] }, "Editing on {0}", hostLabel)); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); } } return; } // show when in a virtual workspace if (this.virtualWorkspaceLocation) { // Workspace with label: indicate editing source const workspaceLabel = this.labelService.getHostLabel(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (workspaceLabel) { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'workspace.tooltip', comment: ['{0} is a remote workspace name, e.g. GitHub'] }, "Editing on {0}", workspaceLabel)); } if (!isWeb || this.remoteAuthority) { tooltip.appendMarkdown('\n\n'); tooltip.appendMarkdown(nls.localize( { key: 'workspace.tooltip2', comment: ['[features are not available]({1}) is a link. Only translate `features are not available`. Do not change brackets and parentheses or {0}'] }, "Some [features are not available]({0}) for resources located on a virtual file system.", `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}` )); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(workspaceLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); return; } } // Remote actions: offer menu if (this.getRemoteMenuActions().length > 0) { this.renderRemoteStatusIndicator(`$(remote)`, nls.localize('noHost.tooltip', "Open a Remote Window")); return; } // No Remote Extensions: hide status indicator dispose(this.remoteStatusEntry); this.remoteStatusEntry = undefined; } private renderRemoteStatusIndicator(text: string, tooltip?: string | IMarkdownString, command?: string, showProgress?: boolean): void { const name = nls.localize('remoteHost', "Remote Host"); if (typeof command !== 'string' && this.getRemoteMenuActions().length > 0) { command = RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID; } const ariaLabel = getCodiconAriaLabel(text); const properties: IStatusbarEntry = { name, backgroundColor: themeColorFromId(STATUS_BAR_HOST_NAME_BACKGROUND), color: themeColorFromId(STATUS_BAR_HOST_NAME_FOREGROUND), ariaLabel, text, showProgress, tooltip, command }; if (this.remoteStatusEntry) { this.remoteStatusEntry.update(properties); } else { this.remoteStatusEntry = this.statusbarService.addEntry(properties, 'status.host', StatusbarAlignment.LEFT, Number.MAX_VALUE /* first entry */); } } private showRemoteMenu() { const getCategoryLabel = (action: MenuItemAction) => { if (action.item.category) { return typeof action.item.category === 'string' ? action.item.category : action.item.category.value; } return undefined; }; const matchCurrentRemote = () => { if (this.remoteAuthority) { return new RegExp(`^remote_\\d\\d_${getRemoteName(this.remoteAuthority)}_`); } else if (this.virtualWorkspaceLocation) { return new RegExp(`^virtualfs_\\d\\d_${this.virtualWorkspaceLocation.scheme}_`); } return undefined; }; const computeItems = () => { let actionGroups = this.getRemoteMenuActions(true); const items: (IQuickPickItem | IQuickPickSeparator)[] = []; const currentRemoteMatcher = matchCurrentRemote(); if (currentRemoteMatcher) { // commands for the current remote go first actionGroups = actionGroups.sort((g1, g2) => { const isCurrentRemote1 = currentRemoteMatcher.test(g1[0]); const isCurrentRemote2 = currentRemoteMatcher.test(g2[0]); if (isCurrentRemote1 !== isCurrentRemote2) { return isCurrentRemote1 ? -1 : 1; } return g1[0].localeCompare(g2[0]); }); } let lastCategoryName: string | undefined = undefined; for (let actionGroup of actionGroups) { let hasGroupCategory = false; for (let action of actionGroup[1]) { if (action instanceof MenuItemAction) { if (!hasGroupCategory) { const category = getCategoryLabel(action); if (category !== lastCategoryName) { items.push({ type: 'separator', label: category }); lastCategoryName = category; } hasGroupCategory = true; } let label = typeof action.item.title === 'string' ? action.item.title : action.item.title.value; items.push({ type: 'item', id: action.item.id, label }); } } } items.push({ type: 'separator' }); let entriesBeforeConfig = items.length; if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { if (this.remoteAuthority) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeRemoteConnection.title', 'Close Remote Connection') }); if (this.connectionState === 'disconnected') { items.push({ type: 'item', id: ReloadWindowAction.ID, label: nls.localize('reloadWindow', 'Reload Window') }); } } else if (this.virtualWorkspaceLocation) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeVirtualWorkspace.title', 'Close Remote Workspace') }); } } if (!this.remoteAuthority && !this.virtualWorkspaceLocation && this.extensionGalleryService.isEnabled()) { items.push({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, label: nls.localize('installRemotes', "Install Additional Remote Extensions..."), alwaysShow: true }); } if (items.length === entriesBeforeConfig) { items.pop(); // remove the separator again } return items; }; const quickPick = this.quickInputService.createQuickPick(); quickPick.items = computeItems(); quickPick.sortByLabel = false; quickPick.canSelectMany = false; once(quickPick.onDidAccept)((_ => { const selectedItems = quickPick.selectedItems; if (selectedItems.length === 1) { this.commandService.executeCommand(selectedItems[0].id!); } quickPick.hide(); })); // refresh the items when actions change const legacyItemUpdater = this.legacyIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(legacyItemUpdater.dispose); const itemUpdater = this.remoteIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(itemUpdater.dispose); quickPick.show(); } }
{ super({ id: RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID, category, title: { value: nls.localize('remote.showMenu', "Show Remote Menu"), original: 'Show Remote Menu' }, f1: true, }); }
identifier_body
remoteIndicator.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { STATUS_BAR_HOST_NAME_BACKGROUND, STATUS_BAR_HOST_NAME_FOREGROUND } from 'vs/workbench/common/theme'; import { themeColorFromId } from 'vs/platform/theme/common/themeService'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { Disposable, dispose } from 'vs/base/common/lifecycle'; import { MenuId, IMenuService, MenuItemAction, MenuRegistry, registerAction2, Action2, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/browser/statusbar'; import { ILabelService } from 'vs/platform/label/common/label'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { Schemas } from 'vs/base/common/network'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { isWeb } from 'vs/base/common/platform'; import { once } from 'vs/base/common/functional'; import { truncate } from 'vs/base/common/strings'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { getRemoteName } from 'vs/platform/remote/common/remoteHosts'; import { getVirtualWorkspaceLocation } from 'vs/platform/workspace/common/virtualWorkspace'; import { getCodiconAriaLabel } from 'vs/base/common/codicons'; import { ILogService } from 'vs/platform/log/common/log'; import { ReloadWindowAction } from 'vs/workbench/browser/actions/windowActions'; import { IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionsViewPaneContainer, LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID, VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { RemoteNameContext, VirtualWorkspaceContext } from 'vs/workbench/common/contextkeys'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { ViewContainerLocation } from 'vs/workbench/common/views'; type ActionGroup = [string, Array<MenuItemAction | SubmenuItemAction>]; export class RemoteStatusIndicator extends Disposable implements IWorkbenchContribution { private static readonly REMOTE_ACTIONS_COMMAND_ID = 'workbench.action.remote.showMenu'; private static readonly CLOSE_REMOTE_COMMAND_ID = 'workbench.action.remote.close'; private static readonly SHOW_CLOSE_REMOTE_COMMAND_ID = !isWeb; // web does not have a "Close Remote" command private static readonly INSTALL_REMOTE_EXTENSIONS_ID = 'workbench.action.remote.extensions'; private static readonly REMOTE_STATUS_LABEL_MAX_LENGTH = 40; private remoteStatusEntry: IStatusbarEntryAccessor | undefined; private readonly legacyIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService)); // to be removed once migration completed private readonly remoteIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarRemoteIndicatorMenu, this.contextKeyService)); private remoteMenuActionsGroups: ActionGroup[] | undefined; private readonly remoteAuthority = this.environmentService.remoteAuthority; private virtualWorkspaceLocation: { scheme: string; authority: string } | undefined = undefined; private connectionState: 'initializing' | 'connected' | 'reconnecting' | 'disconnected' | undefined = undefined; private readonly connectionStateContextKey = new RawContextKey<'' | 'initializing' | 'disconnected' | 'connected'>('remoteConnectionState', '').bindTo(this.contextKeyService); private loggedInvalidGroupNames: { [group: string]: boolean } = Object.create(null); constructor( @IStatusbarService private readonly statusbarService: IStatusbarService, @IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService, @ILabelService private readonly labelService: ILabelService, @IContextKeyService private contextKeyService: IContextKeyService, @IMenuService private menuService: IMenuService, @IQuickInputService private readonly quickInputService: IQuickInputService, @ICommandService private readonly commandService: ICommandService, @IExtensionService private readonly extensionService: IExtensionService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, @IRemoteAuthorityResolverService private readonly remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IHostService private readonly hostService: IHostService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @ILogService private readonly logService: ILogService, @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService ) { super(); // Set initial connection state if (this.remoteAuthority) { this.connectionState = 'initializing'; this.connectionStateContextKey.set(this.connectionState); } else { this.updateVirtualWorkspaceLocation(); } this.registerActions(); this.registerListeners(); this.updateWhenInstalledExtensionsRegistered(); this.updateRemoteStatusIndicator(); } private registerActions(): void { const category = { value: nls.localize('remote.category', "Remote"), original: 'Remote' }; // Show Remote Menu const that = this; registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID, category, title: { value: nls.localize('remote.showMenu', "Show Remote Menu"), original: 'Show Remote Menu' }, f1: true, }); } run = () => that.showRemoteMenu(); }); // Close Remote Connection if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, category, title: { value: nls.localize('remote.close', "Close Remote Connection"), original: 'Close Remote Connection' }, f1: true, precondition: ContextKeyExpr.or(RemoteNameContext, VirtualWorkspaceContext) }); } run = () => that.hostService.openWindow({ forceReuseWindow: true, remoteAuthority: null }); }); if (this.remoteAuthority) { MenuRegistry.appendMenuItem(MenuId.MenubarFileMenu, { group: '6_close', command: { id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, title: nls.localize({ key: 'miCloseRemote', comment: ['&& denotes a mnemonic'] }, "Close Re&&mote Connection") }, order: 3.5 }); } } if (this.extensionGalleryService.isEnabled()) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, category, title: { value: nls.localize('remote.install', "Install Remote Development Extensions"), original: 'Install Remote Development Extensions' }, f1: true }); } run = (accessor: ServicesAccessor, input: string) => { const paneCompositeService = accessor.get(IPaneCompositePartService); return paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true).then(viewlet => { if (viewlet) { (viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer).search(`tag:"remote-menu"`); viewlet.focus(); } }); }; }); } } private
(): void { // Menu changes const updateRemoteActions = () => { this.remoteMenuActionsGroups = undefined; this.updateRemoteStatusIndicator(); }; this._register(this.legacyIndicatorMenu.onDidChange(updateRemoteActions)); this._register(this.remoteIndicatorMenu.onDidChange(updateRemoteActions)); // Update indicator when formatter changes as it may have an impact on the remote label this._register(this.labelService.onDidChangeFormatters(() => this.updateRemoteStatusIndicator())); // Update based on remote indicator changes if any const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator && remoteIndicator.onDidChange) { this._register(remoteIndicator.onDidChange(() => this.updateRemoteStatusIndicator())); } // Listen to changes of the connection if (this.remoteAuthority) { const connection = this.remoteAgentService.getConnection(); if (connection) { this._register(connection.onDidStateChange((e) => { switch (e.type) { case PersistentConnectionEventType.ConnectionLost: case PersistentConnectionEventType.ReconnectionRunning: case PersistentConnectionEventType.ReconnectionWait: this.setState('reconnecting'); break; case PersistentConnectionEventType.ReconnectionPermanentFailure: this.setState('disconnected'); break; case PersistentConnectionEventType.ConnectionGain: this.setState('connected'); break; } })); } } else { this._register(this.workspaceContextService.onDidChangeWorkbenchState(() => { this.updateVirtualWorkspaceLocation(); this.updateRemoteStatusIndicator(); })); } } private updateVirtualWorkspaceLocation() { this.virtualWorkspaceLocation = getVirtualWorkspaceLocation(this.workspaceContextService.getWorkspace()); } private async updateWhenInstalledExtensionsRegistered(): Promise<void> { await this.extensionService.whenInstalledExtensionsRegistered(); const remoteAuthority = this.remoteAuthority; if (remoteAuthority) { // Try to resolve the authority to figure out connection state (async () => { try { await this.remoteAuthorityResolverService.resolveAuthority(remoteAuthority); this.setState('connected'); } catch (error) { this.setState('disconnected'); } })(); } this.updateRemoteStatusIndicator(); } private setState(newState: 'disconnected' | 'connected' | 'reconnecting'): void { if (this.connectionState !== newState) { this.connectionState = newState; // simplify context key which doesn't support `connecting` if (this.connectionState === 'reconnecting') { this.connectionStateContextKey.set('disconnected'); } else { this.connectionStateContextKey.set(this.connectionState); } this.updateRemoteStatusIndicator(); } } private validatedGroup(group: string) { if (!group.match(/^(remote|virtualfs)_(\d\d)_(([a-z][a-z0-9+.-]*)_(.*))$/)) { if (!this.loggedInvalidGroupNames[group]) { this.loggedInvalidGroupNames[group] = true; this.logService.warn(`Invalid group name used in "statusBar/remoteIndicator" menu contribution: ${group}. Entries ignored. Expected format: 'remote_$ORDER_$REMOTENAME_$GROUPING or 'virtualfs_$ORDER_$FILESCHEME_$GROUPING.`); } return false; } return true; } private getRemoteMenuActions(doNotUseCache?: boolean): ActionGroup[] { if (!this.remoteMenuActionsGroups || doNotUseCache) { this.remoteMenuActionsGroups = this.remoteIndicatorMenu.getActions().filter(a => this.validatedGroup(a[0])).concat(this.legacyIndicatorMenu.getActions()); } return this.remoteMenuActionsGroups; } private updateRemoteStatusIndicator(): void { // Remote Indicator: show if provided via options, e.g. by the web embedder API const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator) { this.renderRemoteStatusIndicator(truncate(remoteIndicator.label, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH), remoteIndicator.tooltip, remoteIndicator.command); return; } // Show for remote windows on the desktop, but not when in code server web if (this.remoteAuthority && !isWeb) { const hostLabel = this.labelService.getHostLabel(Schemas.vscodeRemote, this.remoteAuthority) || this.remoteAuthority; switch (this.connectionState) { case 'initializing': this.renderRemoteStatusIndicator(nls.localize('host.open', "Opening Remote..."), nls.localize('host.open', "Opening Remote..."), undefined, true /* progress */); break; case 'reconnecting': this.renderRemoteStatusIndicator(`${nls.localize('host.reconnecting', "Reconnecting to {0}...", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`, undefined, undefined, true); break; case 'disconnected': this.renderRemoteStatusIndicator(`$(alert) ${nls.localize('disconnectedFrom', "Disconnected from {0}", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`); break; default: { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(Schemas.vscodeRemote, this.remoteAuthority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'host.tooltip', comment: ['{0} is a remote host name, e.g. Dev Container'] }, "Editing on {0}", hostLabel)); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); } } return; } // show when in a virtual workspace if (this.virtualWorkspaceLocation) { // Workspace with label: indicate editing source const workspaceLabel = this.labelService.getHostLabel(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (workspaceLabel) { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'workspace.tooltip', comment: ['{0} is a remote workspace name, e.g. GitHub'] }, "Editing on {0}", workspaceLabel)); } if (!isWeb || this.remoteAuthority) { tooltip.appendMarkdown('\n\n'); tooltip.appendMarkdown(nls.localize( { key: 'workspace.tooltip2', comment: ['[features are not available]({1}) is a link. Only translate `features are not available`. Do not change brackets and parentheses or {0}'] }, "Some [features are not available]({0}) for resources located on a virtual file system.", `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}` )); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(workspaceLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); return; } } // Remote actions: offer menu if (this.getRemoteMenuActions().length > 0) { this.renderRemoteStatusIndicator(`$(remote)`, nls.localize('noHost.tooltip', "Open a Remote Window")); return; } // No Remote Extensions: hide status indicator dispose(this.remoteStatusEntry); this.remoteStatusEntry = undefined; } private renderRemoteStatusIndicator(text: string, tooltip?: string | IMarkdownString, command?: string, showProgress?: boolean): void { const name = nls.localize('remoteHost', "Remote Host"); if (typeof command !== 'string' && this.getRemoteMenuActions().length > 0) { command = RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID; } const ariaLabel = getCodiconAriaLabel(text); const properties: IStatusbarEntry = { name, backgroundColor: themeColorFromId(STATUS_BAR_HOST_NAME_BACKGROUND), color: themeColorFromId(STATUS_BAR_HOST_NAME_FOREGROUND), ariaLabel, text, showProgress, tooltip, command }; if (this.remoteStatusEntry) { this.remoteStatusEntry.update(properties); } else { this.remoteStatusEntry = this.statusbarService.addEntry(properties, 'status.host', StatusbarAlignment.LEFT, Number.MAX_VALUE /* first entry */); } } private showRemoteMenu() { const getCategoryLabel = (action: MenuItemAction) => { if (action.item.category) { return typeof action.item.category === 'string' ? action.item.category : action.item.category.value; } return undefined; }; const matchCurrentRemote = () => { if (this.remoteAuthority) { return new RegExp(`^remote_\\d\\d_${getRemoteName(this.remoteAuthority)}_`); } else if (this.virtualWorkspaceLocation) { return new RegExp(`^virtualfs_\\d\\d_${this.virtualWorkspaceLocation.scheme}_`); } return undefined; }; const computeItems = () => { let actionGroups = this.getRemoteMenuActions(true); const items: (IQuickPickItem | IQuickPickSeparator)[] = []; const currentRemoteMatcher = matchCurrentRemote(); if (currentRemoteMatcher) { // commands for the current remote go first actionGroups = actionGroups.sort((g1, g2) => { const isCurrentRemote1 = currentRemoteMatcher.test(g1[0]); const isCurrentRemote2 = currentRemoteMatcher.test(g2[0]); if (isCurrentRemote1 !== isCurrentRemote2) { return isCurrentRemote1 ? -1 : 1; } return g1[0].localeCompare(g2[0]); }); } let lastCategoryName: string | undefined = undefined; for (let actionGroup of actionGroups) { let hasGroupCategory = false; for (let action of actionGroup[1]) { if (action instanceof MenuItemAction) { if (!hasGroupCategory) { const category = getCategoryLabel(action); if (category !== lastCategoryName) { items.push({ type: 'separator', label: category }); lastCategoryName = category; } hasGroupCategory = true; } let label = typeof action.item.title === 'string' ? action.item.title : action.item.title.value; items.push({ type: 'item', id: action.item.id, label }); } } } items.push({ type: 'separator' }); let entriesBeforeConfig = items.length; if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { if (this.remoteAuthority) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeRemoteConnection.title', 'Close Remote Connection') }); if (this.connectionState === 'disconnected') { items.push({ type: 'item', id: ReloadWindowAction.ID, label: nls.localize('reloadWindow', 'Reload Window') }); } } else if (this.virtualWorkspaceLocation) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeVirtualWorkspace.title', 'Close Remote Workspace') }); } } if (!this.remoteAuthority && !this.virtualWorkspaceLocation && this.extensionGalleryService.isEnabled()) { items.push({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, label: nls.localize('installRemotes', "Install Additional Remote Extensions..."), alwaysShow: true }); } if (items.length === entriesBeforeConfig) { items.pop(); // remove the separator again } return items; }; const quickPick = this.quickInputService.createQuickPick(); quickPick.items = computeItems(); quickPick.sortByLabel = false; quickPick.canSelectMany = false; once(quickPick.onDidAccept)((_ => { const selectedItems = quickPick.selectedItems; if (selectedItems.length === 1) { this.commandService.executeCommand(selectedItems[0].id!); } quickPick.hide(); })); // refresh the items when actions change const legacyItemUpdater = this.legacyIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(legacyItemUpdater.dispose); const itemUpdater = this.remoteIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(itemUpdater.dispose); quickPick.show(); } }
registerListeners
identifier_name
remoteIndicator.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { STATUS_BAR_HOST_NAME_BACKGROUND, STATUS_BAR_HOST_NAME_FOREGROUND } from 'vs/workbench/common/theme'; import { themeColorFromId } from 'vs/platform/theme/common/themeService'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { Disposable, dispose } from 'vs/base/common/lifecycle'; import { MenuId, IMenuService, MenuItemAction, MenuRegistry, registerAction2, Action2, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/browser/statusbar'; import { ILabelService } from 'vs/platform/label/common/label'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { Schemas } from 'vs/base/common/network'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { isWeb } from 'vs/base/common/platform'; import { once } from 'vs/base/common/functional'; import { truncate } from 'vs/base/common/strings'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { getRemoteName } from 'vs/platform/remote/common/remoteHosts'; import { getVirtualWorkspaceLocation } from 'vs/platform/workspace/common/virtualWorkspace'; import { getCodiconAriaLabel } from 'vs/base/common/codicons'; import { ILogService } from 'vs/platform/log/common/log'; import { ReloadWindowAction } from 'vs/workbench/browser/actions/windowActions'; import { IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionsViewPaneContainer, LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID, VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { RemoteNameContext, VirtualWorkspaceContext } from 'vs/workbench/common/contextkeys'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { ViewContainerLocation } from 'vs/workbench/common/views'; type ActionGroup = [string, Array<MenuItemAction | SubmenuItemAction>]; export class RemoteStatusIndicator extends Disposable implements IWorkbenchContribution { private static readonly REMOTE_ACTIONS_COMMAND_ID = 'workbench.action.remote.showMenu'; private static readonly CLOSE_REMOTE_COMMAND_ID = 'workbench.action.remote.close'; private static readonly SHOW_CLOSE_REMOTE_COMMAND_ID = !isWeb; // web does not have a "Close Remote" command private static readonly INSTALL_REMOTE_EXTENSIONS_ID = 'workbench.action.remote.extensions'; private static readonly REMOTE_STATUS_LABEL_MAX_LENGTH = 40; private remoteStatusEntry: IStatusbarEntryAccessor | undefined; private readonly legacyIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService)); // to be removed once migration completed private readonly remoteIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarRemoteIndicatorMenu, this.contextKeyService)); private remoteMenuActionsGroups: ActionGroup[] | undefined; private readonly remoteAuthority = this.environmentService.remoteAuthority; private virtualWorkspaceLocation: { scheme: string; authority: string } | undefined = undefined; private connectionState: 'initializing' | 'connected' | 'reconnecting' | 'disconnected' | undefined = undefined; private readonly connectionStateContextKey = new RawContextKey<'' | 'initializing' | 'disconnected' | 'connected'>('remoteConnectionState', '').bindTo(this.contextKeyService); private loggedInvalidGroupNames: { [group: string]: boolean } = Object.create(null); constructor( @IStatusbarService private readonly statusbarService: IStatusbarService, @IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService, @ILabelService private readonly labelService: ILabelService, @IContextKeyService private contextKeyService: IContextKeyService, @IMenuService private menuService: IMenuService, @IQuickInputService private readonly quickInputService: IQuickInputService, @ICommandService private readonly commandService: ICommandService, @IExtensionService private readonly extensionService: IExtensionService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, @IRemoteAuthorityResolverService private readonly remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IHostService private readonly hostService: IHostService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @ILogService private readonly logService: ILogService, @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService ) { super(); // Set initial connection state if (this.remoteAuthority) { this.connectionState = 'initializing'; this.connectionStateContextKey.set(this.connectionState); } else { this.updateVirtualWorkspaceLocation(); } this.registerActions(); this.registerListeners(); this.updateWhenInstalledExtensionsRegistered(); this.updateRemoteStatusIndicator(); } private registerActions(): void { const category = { value: nls.localize('remote.category', "Remote"), original: 'Remote' }; // Show Remote Menu const that = this; registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID, category, title: { value: nls.localize('remote.showMenu', "Show Remote Menu"), original: 'Show Remote Menu' }, f1: true, }); } run = () => that.showRemoteMenu(); }); // Close Remote Connection if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, category, title: { value: nls.localize('remote.close', "Close Remote Connection"), original: 'Close Remote Connection' }, f1: true, precondition: ContextKeyExpr.or(RemoteNameContext, VirtualWorkspaceContext) }); } run = () => that.hostService.openWindow({ forceReuseWindow: true, remoteAuthority: null }); }); if (this.remoteAuthority) { MenuRegistry.appendMenuItem(MenuId.MenubarFileMenu, { group: '6_close', command: { id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, title: nls.localize({ key: 'miCloseRemote', comment: ['&& denotes a mnemonic'] }, "Close Re&&mote Connection") }, order: 3.5 }); } } if (this.extensionGalleryService.isEnabled()) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, category, title: { value: nls.localize('remote.install', "Install Remote Development Extensions"), original: 'Install Remote Development Extensions' }, f1: true }); } run = (accessor: ServicesAccessor, input: string) => { const paneCompositeService = accessor.get(IPaneCompositePartService); return paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true).then(viewlet => { if (viewlet) { (viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer).search(`tag:"remote-menu"`); viewlet.focus(); } }); }; }); } } private registerListeners(): void { // Menu changes const updateRemoteActions = () => { this.remoteMenuActionsGroups = undefined; this.updateRemoteStatusIndicator(); }; this._register(this.legacyIndicatorMenu.onDidChange(updateRemoteActions)); this._register(this.remoteIndicatorMenu.onDidChange(updateRemoteActions)); // Update indicator when formatter changes as it may have an impact on the remote label this._register(this.labelService.onDidChangeFormatters(() => this.updateRemoteStatusIndicator())); // Update based on remote indicator changes if any const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator && remoteIndicator.onDidChange) { this._register(remoteIndicator.onDidChange(() => this.updateRemoteStatusIndicator())); } // Listen to changes of the connection if (this.remoteAuthority) { const connection = this.remoteAgentService.getConnection(); if (connection) { this._register(connection.onDidStateChange((e) => { switch (e.type) { case PersistentConnectionEventType.ConnectionLost: case PersistentConnectionEventType.ReconnectionRunning: case PersistentConnectionEventType.ReconnectionWait: this.setState('reconnecting'); break; case PersistentConnectionEventType.ReconnectionPermanentFailure: this.setState('disconnected'); break; case PersistentConnectionEventType.ConnectionGain: this.setState('connected'); break; } })); } } else { this._register(this.workspaceContextService.onDidChangeWorkbenchState(() => { this.updateVirtualWorkspaceLocation(); this.updateRemoteStatusIndicator(); })); } } private updateVirtualWorkspaceLocation() { this.virtualWorkspaceLocation = getVirtualWorkspaceLocation(this.workspaceContextService.getWorkspace()); } private async updateWhenInstalledExtensionsRegistered(): Promise<void> { await this.extensionService.whenInstalledExtensionsRegistered(); const remoteAuthority = this.remoteAuthority; if (remoteAuthority) { // Try to resolve the authority to figure out connection state (async () => { try { await this.remoteAuthorityResolverService.resolveAuthority(remoteAuthority); this.setState('connected'); } catch (error) { this.setState('disconnected'); } })(); } this.updateRemoteStatusIndicator(); } private setState(newState: 'disconnected' | 'connected' | 'reconnecting'): void { if (this.connectionState !== newState) { this.connectionState = newState; // simplify context key which doesn't support `connecting` if (this.connectionState === 'reconnecting') { this.connectionStateContextKey.set('disconnected'); } else { this.connectionStateContextKey.set(this.connectionState); } this.updateRemoteStatusIndicator(); } } private validatedGroup(group: string) { if (!group.match(/^(remote|virtualfs)_(\d\d)_(([a-z][a-z0-9+.-]*)_(.*))$/)) { if (!this.loggedInvalidGroupNames[group]) { this.loggedInvalidGroupNames[group] = true; this.logService.warn(`Invalid group name used in "statusBar/remoteIndicator" menu contribution: ${group}. Entries ignored. Expected format: 'remote_$ORDER_$REMOTENAME_$GROUPING or 'virtualfs_$ORDER_$FILESCHEME_$GROUPING.`); } return false; } return true; } private getRemoteMenuActions(doNotUseCache?: boolean): ActionGroup[] { if (!this.remoteMenuActionsGroups || doNotUseCache) { this.remoteMenuActionsGroups = this.remoteIndicatorMenu.getActions().filter(a => this.validatedGroup(a[0])).concat(this.legacyIndicatorMenu.getActions()); } return this.remoteMenuActionsGroups; } private updateRemoteStatusIndicator(): void { // Remote Indicator: show if provided via options, e.g. by the web embedder API const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator) { this.renderRemoteStatusIndicator(truncate(remoteIndicator.label, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH), remoteIndicator.tooltip, remoteIndicator.command); return; } // Show for remote windows on the desktop, but not when in code server web if (this.remoteAuthority && !isWeb) { const hostLabel = this.labelService.getHostLabel(Schemas.vscodeRemote, this.remoteAuthority) || this.remoteAuthority; switch (this.connectionState) { case 'initializing': this.renderRemoteStatusIndicator(nls.localize('host.open', "Opening Remote..."), nls.localize('host.open', "Opening Remote..."), undefined, true /* progress */); break; case 'reconnecting': this.renderRemoteStatusIndicator(`${nls.localize('host.reconnecting', "Reconnecting to {0}...", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`, undefined, undefined, true); break; case 'disconnected': this.renderRemoteStatusIndicator(`$(alert) ${nls.localize('disconnectedFrom', "Disconnected from {0}", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`); break; default: { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(Schemas.vscodeRemote, this.remoteAuthority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'host.tooltip', comment: ['{0} is a remote host name, e.g. Dev Container'] }, "Editing on {0}", hostLabel)); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); } } return; } // show when in a virtual workspace if (this.virtualWorkspaceLocation) { // Workspace with label: indicate editing source const workspaceLabel = this.labelService.getHostLabel(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (workspaceLabel) { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else
if (!isWeb || this.remoteAuthority) { tooltip.appendMarkdown('\n\n'); tooltip.appendMarkdown(nls.localize( { key: 'workspace.tooltip2', comment: ['[features are not available]({1}) is a link. Only translate `features are not available`. Do not change brackets and parentheses or {0}'] }, "Some [features are not available]({0}) for resources located on a virtual file system.", `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}` )); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(workspaceLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); return; } } // Remote actions: offer menu if (this.getRemoteMenuActions().length > 0) { this.renderRemoteStatusIndicator(`$(remote)`, nls.localize('noHost.tooltip', "Open a Remote Window")); return; } // No Remote Extensions: hide status indicator dispose(this.remoteStatusEntry); this.remoteStatusEntry = undefined; } private renderRemoteStatusIndicator(text: string, tooltip?: string | IMarkdownString, command?: string, showProgress?: boolean): void { const name = nls.localize('remoteHost', "Remote Host"); if (typeof command !== 'string' && this.getRemoteMenuActions().length > 0) { command = RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID; } const ariaLabel = getCodiconAriaLabel(text); const properties: IStatusbarEntry = { name, backgroundColor: themeColorFromId(STATUS_BAR_HOST_NAME_BACKGROUND), color: themeColorFromId(STATUS_BAR_HOST_NAME_FOREGROUND), ariaLabel, text, showProgress, tooltip, command }; if (this.remoteStatusEntry) { this.remoteStatusEntry.update(properties); } else { this.remoteStatusEntry = this.statusbarService.addEntry(properties, 'status.host', StatusbarAlignment.LEFT, Number.MAX_VALUE /* first entry */); } } private showRemoteMenu() { const getCategoryLabel = (action: MenuItemAction) => { if (action.item.category) { return typeof action.item.category === 'string' ? action.item.category : action.item.category.value; } return undefined; }; const matchCurrentRemote = () => { if (this.remoteAuthority) { return new RegExp(`^remote_\\d\\d_${getRemoteName(this.remoteAuthority)}_`); } else if (this.virtualWorkspaceLocation) { return new RegExp(`^virtualfs_\\d\\d_${this.virtualWorkspaceLocation.scheme}_`); } return undefined; }; const computeItems = () => { let actionGroups = this.getRemoteMenuActions(true); const items: (IQuickPickItem | IQuickPickSeparator)[] = []; const currentRemoteMatcher = matchCurrentRemote(); if (currentRemoteMatcher) { // commands for the current remote go first actionGroups = actionGroups.sort((g1, g2) => { const isCurrentRemote1 = currentRemoteMatcher.test(g1[0]); const isCurrentRemote2 = currentRemoteMatcher.test(g2[0]); if (isCurrentRemote1 !== isCurrentRemote2) { return isCurrentRemote1 ? -1 : 1; } return g1[0].localeCompare(g2[0]); }); } let lastCategoryName: string | undefined = undefined; for (let actionGroup of actionGroups) { let hasGroupCategory = false; for (let action of actionGroup[1]) { if (action instanceof MenuItemAction) { if (!hasGroupCategory) { const category = getCategoryLabel(action); if (category !== lastCategoryName) { items.push({ type: 'separator', label: category }); lastCategoryName = category; } hasGroupCategory = true; } let label = typeof action.item.title === 'string' ? action.item.title : action.item.title.value; items.push({ type: 'item', id: action.item.id, label }); } } } items.push({ type: 'separator' }); let entriesBeforeConfig = items.length; if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { if (this.remoteAuthority) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeRemoteConnection.title', 'Close Remote Connection') }); if (this.connectionState === 'disconnected') { items.push({ type: 'item', id: ReloadWindowAction.ID, label: nls.localize('reloadWindow', 'Reload Window') }); } } else if (this.virtualWorkspaceLocation) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeVirtualWorkspace.title', 'Close Remote Workspace') }); } } if (!this.remoteAuthority && !this.virtualWorkspaceLocation && this.extensionGalleryService.isEnabled()) { items.push({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, label: nls.localize('installRemotes', "Install Additional Remote Extensions..."), alwaysShow: true }); } if (items.length === entriesBeforeConfig) { items.pop(); // remove the separator again } return items; }; const quickPick = this.quickInputService.createQuickPick(); quickPick.items = computeItems(); quickPick.sortByLabel = false; quickPick.canSelectMany = false; once(quickPick.onDidAccept)((_ => { const selectedItems = quickPick.selectedItems; if (selectedItems.length === 1) { this.commandService.executeCommand(selectedItems[0].id!); } quickPick.hide(); })); // refresh the items when actions change const legacyItemUpdater = this.legacyIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(legacyItemUpdater.dispose); const itemUpdater = this.remoteIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(itemUpdater.dispose); quickPick.show(); } }
{ tooltip.appendText(nls.localize({ key: 'workspace.tooltip', comment: ['{0} is a remote workspace name, e.g. GitHub'] }, "Editing on {0}", workspaceLabel)); }
conditional_block
remoteIndicator.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { STATUS_BAR_HOST_NAME_BACKGROUND, STATUS_BAR_HOST_NAME_FOREGROUND } from 'vs/workbench/common/theme'; import { themeColorFromId } from 'vs/platform/theme/common/themeService'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; import { Disposable, dispose } from 'vs/base/common/lifecycle'; import { MenuId, IMenuService, MenuItemAction, MenuRegistry, registerAction2, Action2, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { StatusbarAlignment, IStatusbarService, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/browser/statusbar'; import { ILabelService } from 'vs/platform/label/common/label'; import { ContextKeyExpr, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { Schemas } from 'vs/base/common/network'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput'; import { IBrowserWorkbenchEnvironmentService } from 'vs/workbench/services/environment/browser/environmentService'; import { PersistentConnectionEventType } from 'vs/platform/remote/common/remoteAgentConnection'; import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import { isWeb } from 'vs/base/common/platform'; import { once } from 'vs/base/common/functional'; import { truncate } from 'vs/base/common/strings'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { getRemoteName } from 'vs/platform/remote/common/remoteHosts'; import { getVirtualWorkspaceLocation } from 'vs/platform/workspace/common/virtualWorkspace'; import { getCodiconAriaLabel } from 'vs/base/common/codicons'; import { ILogService } from 'vs/platform/log/common/log'; import { ReloadWindowAction } from 'vs/workbench/browser/actions/windowActions'; import { IExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionsViewPaneContainer, LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID, VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { RemoteNameContext, VirtualWorkspaceContext } from 'vs/workbench/common/contextkeys'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { ViewContainerLocation } from 'vs/workbench/common/views'; type ActionGroup = [string, Array<MenuItemAction | SubmenuItemAction>]; export class RemoteStatusIndicator extends Disposable implements IWorkbenchContribution { private static readonly REMOTE_ACTIONS_COMMAND_ID = 'workbench.action.remote.showMenu'; private static readonly CLOSE_REMOTE_COMMAND_ID = 'workbench.action.remote.close'; private static readonly SHOW_CLOSE_REMOTE_COMMAND_ID = !isWeb; // web does not have a "Close Remote" command private static readonly INSTALL_REMOTE_EXTENSIONS_ID = 'workbench.action.remote.extensions'; private static readonly REMOTE_STATUS_LABEL_MAX_LENGTH = 40; private remoteStatusEntry: IStatusbarEntryAccessor | undefined; private readonly legacyIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarWindowIndicatorMenu, this.contextKeyService)); // to be removed once migration completed private readonly remoteIndicatorMenu = this._register(this.menuService.createMenu(MenuId.StatusBarRemoteIndicatorMenu, this.contextKeyService)); private remoteMenuActionsGroups: ActionGroup[] | undefined; private readonly remoteAuthority = this.environmentService.remoteAuthority; private virtualWorkspaceLocation: { scheme: string; authority: string } | undefined = undefined; private connectionState: 'initializing' | 'connected' | 'reconnecting' | 'disconnected' | undefined = undefined; private readonly connectionStateContextKey = new RawContextKey<'' | 'initializing' | 'disconnected' | 'connected'>('remoteConnectionState', '').bindTo(this.contextKeyService); private loggedInvalidGroupNames: { [group: string]: boolean } = Object.create(null); constructor( @IStatusbarService private readonly statusbarService: IStatusbarService, @IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService, @ILabelService private readonly labelService: ILabelService, @IContextKeyService private contextKeyService: IContextKeyService, @IMenuService private menuService: IMenuService, @IQuickInputService private readonly quickInputService: IQuickInputService, @ICommandService private readonly commandService: ICommandService, @IExtensionService private readonly extensionService: IExtensionService, @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService, @IRemoteAuthorityResolverService private readonly remoteAuthorityResolverService: IRemoteAuthorityResolverService, @IHostService private readonly hostService: IHostService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @ILogService private readonly logService: ILogService, @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService ) { super(); // Set initial connection state if (this.remoteAuthority) { this.connectionState = 'initializing'; this.connectionStateContextKey.set(this.connectionState); } else { this.updateVirtualWorkspaceLocation(); } this.registerActions(); this.registerListeners(); this.updateWhenInstalledExtensionsRegistered(); this.updateRemoteStatusIndicator(); } private registerActions(): void { const category = { value: nls.localize('remote.category', "Remote"), original: 'Remote' }; // Show Remote Menu const that = this; registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID, category, title: { value: nls.localize('remote.showMenu', "Show Remote Menu"), original: 'Show Remote Menu' }, f1: true, }); } run = () => that.showRemoteMenu(); }); // Close Remote Connection if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, category, title: { value: nls.localize('remote.close', "Close Remote Connection"), original: 'Close Remote Connection' }, f1: true, precondition: ContextKeyExpr.or(RemoteNameContext, VirtualWorkspaceContext) }); } run = () => that.hostService.openWindow({ forceReuseWindow: true, remoteAuthority: null }); }); if (this.remoteAuthority) { MenuRegistry.appendMenuItem(MenuId.MenubarFileMenu, { group: '6_close', command: { id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, title: nls.localize({ key: 'miCloseRemote', comment: ['&& denotes a mnemonic'] }, "Close Re&&mote Connection") }, order: 3.5 }); } } if (this.extensionGalleryService.isEnabled()) { registerAction2(class extends Action2 { constructor() { super({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, category, title: { value: nls.localize('remote.install', "Install Remote Development Extensions"), original: 'Install Remote Development Extensions' }, f1: true }); } run = (accessor: ServicesAccessor, input: string) => { const paneCompositeService = accessor.get(IPaneCompositePartService); return paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true).then(viewlet => { if (viewlet) { (viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer).search(`tag:"remote-menu"`); viewlet.focus(); } }); }; }); } } private registerListeners(): void { // Menu changes const updateRemoteActions = () => { this.remoteMenuActionsGroups = undefined; this.updateRemoteStatusIndicator(); }; this._register(this.legacyIndicatorMenu.onDidChange(updateRemoteActions)); this._register(this.remoteIndicatorMenu.onDidChange(updateRemoteActions)); // Update indicator when formatter changes as it may have an impact on the remote label this._register(this.labelService.onDidChangeFormatters(() => this.updateRemoteStatusIndicator())); // Update based on remote indicator changes if any const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator && remoteIndicator.onDidChange) { this._register(remoteIndicator.onDidChange(() => this.updateRemoteStatusIndicator())); } // Listen to changes of the connection if (this.remoteAuthority) { const connection = this.remoteAgentService.getConnection(); if (connection) { this._register(connection.onDidStateChange((e) => { switch (e.type) { case PersistentConnectionEventType.ConnectionLost: case PersistentConnectionEventType.ReconnectionRunning: case PersistentConnectionEventType.ReconnectionWait: this.setState('reconnecting'); break; case PersistentConnectionEventType.ReconnectionPermanentFailure: this.setState('disconnected'); break; case PersistentConnectionEventType.ConnectionGain: this.setState('connected'); break; } })); } } else { this._register(this.workspaceContextService.onDidChangeWorkbenchState(() => { this.updateVirtualWorkspaceLocation(); this.updateRemoteStatusIndicator(); })); } } private updateVirtualWorkspaceLocation() { this.virtualWorkspaceLocation = getVirtualWorkspaceLocation(this.workspaceContextService.getWorkspace()); } private async updateWhenInstalledExtensionsRegistered(): Promise<void> { await this.extensionService.whenInstalledExtensionsRegistered(); const remoteAuthority = this.remoteAuthority; if (remoteAuthority) { // Try to resolve the authority to figure out connection state (async () => { try { await this.remoteAuthorityResolverService.resolveAuthority(remoteAuthority); this.setState('connected'); } catch (error) { this.setState('disconnected'); } })(); } this.updateRemoteStatusIndicator(); } private setState(newState: 'disconnected' | 'connected' | 'reconnecting'): void { if (this.connectionState !== newState) { this.connectionState = newState; // simplify context key which doesn't support `connecting` if (this.connectionState === 'reconnecting') { this.connectionStateContextKey.set('disconnected'); } else { this.connectionStateContextKey.set(this.connectionState); } this.updateRemoteStatusIndicator(); } } private validatedGroup(group: string) { if (!group.match(/^(remote|virtualfs)_(\d\d)_(([a-z][a-z0-9+.-]*)_(.*))$/)) { if (!this.loggedInvalidGroupNames[group]) { this.loggedInvalidGroupNames[group] = true; this.logService.warn(`Invalid group name used in "statusBar/remoteIndicator" menu contribution: ${group}. Entries ignored. Expected format: 'remote_$ORDER_$REMOTENAME_$GROUPING or 'virtualfs_$ORDER_$FILESCHEME_$GROUPING.`); } return false; } return true; } private getRemoteMenuActions(doNotUseCache?: boolean): ActionGroup[] { if (!this.remoteMenuActionsGroups || doNotUseCache) { this.remoteMenuActionsGroups = this.remoteIndicatorMenu.getActions().filter(a => this.validatedGroup(a[0])).concat(this.legacyIndicatorMenu.getActions()); } return this.remoteMenuActionsGroups; } private updateRemoteStatusIndicator(): void { // Remote Indicator: show if provided via options, e.g. by the web embedder API const remoteIndicator = this.environmentService.options?.windowIndicator; if (remoteIndicator) { this.renderRemoteStatusIndicator(truncate(remoteIndicator.label, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH), remoteIndicator.tooltip, remoteIndicator.command); return; } // Show for remote windows on the desktop, but not when in code server web if (this.remoteAuthority && !isWeb) { const hostLabel = this.labelService.getHostLabel(Schemas.vscodeRemote, this.remoteAuthority) || this.remoteAuthority; switch (this.connectionState) { case 'initializing': this.renderRemoteStatusIndicator(nls.localize('host.open', "Opening Remote..."), nls.localize('host.open', "Opening Remote..."), undefined, true /* progress */); break; case 'reconnecting': this.renderRemoteStatusIndicator(`${nls.localize('host.reconnecting', "Reconnecting to {0}...", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`, undefined, undefined, true); break; case 'disconnected': this.renderRemoteStatusIndicator(`$(alert) ${nls.localize('disconnectedFrom', "Disconnected from {0}", truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH))}`); break; default: { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(Schemas.vscodeRemote, this.remoteAuthority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'host.tooltip', comment: ['{0} is a remote host name, e.g. Dev Container'] }, "Editing on {0}", hostLabel)); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(hostLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); } } return; } // show when in a virtual workspace if (this.virtualWorkspaceLocation) { // Workspace with label: indicate editing source const workspaceLabel = this.labelService.getHostLabel(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (workspaceLabel) { const tooltip = new MarkdownString('', { isTrusted: true, supportThemeIcons: true }); const hostNameTooltip = this.labelService.getHostTooltip(this.virtualWorkspaceLocation.scheme, this.virtualWorkspaceLocation.authority); if (hostNameTooltip) { tooltip.appendMarkdown(hostNameTooltip); } else { tooltip.appendText(nls.localize({ key: 'workspace.tooltip', comment: ['{0} is a remote workspace name, e.g. GitHub'] }, "Editing on {0}", workspaceLabel)); } if (!isWeb || this.remoteAuthority) { tooltip.appendMarkdown('\n\n'); tooltip.appendMarkdown(nls.localize( { key: 'workspace.tooltip2', comment: ['[features are not available]({1}) is a link. Only translate `features are not available`. Do not change brackets and parentheses or {0}'] }, "Some [features are not available]({0}) for resources located on a virtual file system.", `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}` )); } this.renderRemoteStatusIndicator(`$(remote) ${truncate(workspaceLabel, RemoteStatusIndicator.REMOTE_STATUS_LABEL_MAX_LENGTH)}`, tooltip); return; } } // Remote actions: offer menu if (this.getRemoteMenuActions().length > 0) { this.renderRemoteStatusIndicator(`$(remote)`, nls.localize('noHost.tooltip', "Open a Remote Window")); return; } // No Remote Extensions: hide status indicator dispose(this.remoteStatusEntry); this.remoteStatusEntry = undefined; } private renderRemoteStatusIndicator(text: string, tooltip?: string | IMarkdownString, command?: string, showProgress?: boolean): void { const name = nls.localize('remoteHost', "Remote Host"); if (typeof command !== 'string' && this.getRemoteMenuActions().length > 0) { command = RemoteStatusIndicator.REMOTE_ACTIONS_COMMAND_ID; } const ariaLabel = getCodiconAriaLabel(text); const properties: IStatusbarEntry = { name, backgroundColor: themeColorFromId(STATUS_BAR_HOST_NAME_BACKGROUND), color: themeColorFromId(STATUS_BAR_HOST_NAME_FOREGROUND), ariaLabel, text, showProgress, tooltip, command }; if (this.remoteStatusEntry) { this.remoteStatusEntry.update(properties); } else { this.remoteStatusEntry = this.statusbarService.addEntry(properties, 'status.host', StatusbarAlignment.LEFT, Number.MAX_VALUE /* first entry */); } } private showRemoteMenu() { const getCategoryLabel = (action: MenuItemAction) => { if (action.item.category) { return typeof action.item.category === 'string' ? action.item.category : action.item.category.value; } return undefined; }; const matchCurrentRemote = () => { if (this.remoteAuthority) { return new RegExp(`^remote_\\d\\d_${getRemoteName(this.remoteAuthority)}_`); } else if (this.virtualWorkspaceLocation) { return new RegExp(`^virtualfs_\\d\\d_${this.virtualWorkspaceLocation.scheme}_`); } return undefined; }; const computeItems = () => { let actionGroups = this.getRemoteMenuActions(true); const items: (IQuickPickItem | IQuickPickSeparator)[] = []; const currentRemoteMatcher = matchCurrentRemote(); if (currentRemoteMatcher) { // commands for the current remote go first actionGroups = actionGroups.sort((g1, g2) => { const isCurrentRemote1 = currentRemoteMatcher.test(g1[0]); const isCurrentRemote2 = currentRemoteMatcher.test(g2[0]); if (isCurrentRemote1 !== isCurrentRemote2) { return isCurrentRemote1 ? -1 : 1; } return g1[0].localeCompare(g2[0]); }); } let lastCategoryName: string | undefined = undefined; for (let actionGroup of actionGroups) { let hasGroupCategory = false; for (let action of actionGroup[1]) { if (action instanceof MenuItemAction) { if (!hasGroupCategory) { const category = getCategoryLabel(action); if (category !== lastCategoryName) { items.push({ type: 'separator', label: category }); lastCategoryName = category; } hasGroupCategory = true; } let label = typeof action.item.title === 'string' ? action.item.title : action.item.title.value; items.push({ type: 'item', id: action.item.id, label }); } } } items.push({ type: 'separator' }); let entriesBeforeConfig = items.length; if (RemoteStatusIndicator.SHOW_CLOSE_REMOTE_COMMAND_ID) { if (this.remoteAuthority) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeRemoteConnection.title', 'Close Remote Connection') }); if (this.connectionState === 'disconnected') { items.push({ type: 'item', id: ReloadWindowAction.ID, label: nls.localize('reloadWindow', 'Reload Window') }); } } else if (this.virtualWorkspaceLocation) { items.push({ type: 'item', id: RemoteStatusIndicator.CLOSE_REMOTE_COMMAND_ID, label: nls.localize('closeVirtualWorkspace.title', 'Close Remote Workspace') }); } } if (!this.remoteAuthority && !this.virtualWorkspaceLocation && this.extensionGalleryService.isEnabled()) { items.push({ id: RemoteStatusIndicator.INSTALL_REMOTE_EXTENSIONS_ID, label: nls.localize('installRemotes', "Install Additional Remote Extensions..."), alwaysShow: true }); } if (items.length === entriesBeforeConfig) { items.pop(); // remove the separator again } return items; }; const quickPick = this.quickInputService.createQuickPick(); quickPick.items = computeItems(); quickPick.sortByLabel = false; quickPick.canSelectMany = false; once(quickPick.onDidAccept)((_ => { const selectedItems = quickPick.selectedItems; if (selectedItems.length === 1) { this.commandService.executeCommand(selectedItems[0].id!); } quickPick.hide(); })); // refresh the items when actions change const legacyItemUpdater = this.legacyIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(legacyItemUpdater.dispose); const itemUpdater = this.remoteIndicatorMenu.onDidChange(() => quickPick.items = computeItems()); quickPick.onDidHide(itemUpdater.dispose);
quickPick.show(); } }
random_line_split
parks.js
//Author: Sam var parkIds = []; $(document).ready(function() { $('#toMap').on('click', function() { if (typeof map == 'undefined') { initialize(); } }); $('.park').on('click', '.select', function(e) { e.preventDefault(); var parkId = $(this).attr('data-id'); if ($(this).hasClass('btn-success')) { unselectPark(parkId); } else
handleCompareButton(); }); $('#compare-parks-body').on('click', '.selected-park', function() { var parkId = $(this).data('park'); unselectPark(parkId, this); handleCompareButton(); }); }); function handleCompareButton() { if (parkIds.length == 2) { $('#compare').attr('disabled', false); var url = '../compare?park1=' + parkIds[0] + '&park2=' + parkIds[1]; $('#compare').attr('href', url); } else { $('#compare').attr('disabled', true); } } function unselectPark(parkId) { $('#park-' + parkId).find('.select').removeClass('btn-success').text('compare'); parkIds.splice(parkIds.indexOf(parkId), 1); $('#compare-park-' + parkId).remove(); }
{ if (parkIds.length != 2) { $(this).addClass('btn-success'); $(this).text('Selected'); $('#compare-parks-body').append('<button data-park="' + parkId + '" id="compare-park-' + parkId +'" class="btn btn-warning selected-park" aria-label="Right Align">' + $(this).data('name') + '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' + '</button>') parkIds.push(parkId); } }
conditional_block
parks.js
//Author: Sam var parkIds = []; $(document).ready(function() { $('#toMap').on('click', function() { if (typeof map == 'undefined') { initialize(); } }); $('.park').on('click', '.select', function(e) { e.preventDefault(); var parkId = $(this).attr('data-id'); if ($(this).hasClass('btn-success')) { unselectPark(parkId); } else { if (parkIds.length != 2) { $(this).addClass('btn-success'); $(this).text('Selected'); $('#compare-parks-body').append('<button data-park="' + parkId + '" id="compare-park-' + parkId +'" class="btn btn-warning selected-park" aria-label="Right Align">' + $(this).data('name') + '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' + '</button>') parkIds.push(parkId); } } handleCompareButton(); }); $('#compare-parks-body').on('click', '.selected-park', function() { var parkId = $(this).data('park'); unselectPark(parkId, this); handleCompareButton(); });
}); function handleCompareButton() { if (parkIds.length == 2) { $('#compare').attr('disabled', false); var url = '../compare?park1=' + parkIds[0] + '&park2=' + parkIds[1]; $('#compare').attr('href', url); } else { $('#compare').attr('disabled', true); } } function unselectPark(parkId) { $('#park-' + parkId).find('.select').removeClass('btn-success').text('compare'); parkIds.splice(parkIds.indexOf(parkId), 1); $('#compare-park-' + parkId).remove(); }
random_line_split
parks.js
//Author: Sam var parkIds = []; $(document).ready(function() { $('#toMap').on('click', function() { if (typeof map == 'undefined') { initialize(); } }); $('.park').on('click', '.select', function(e) { e.preventDefault(); var parkId = $(this).attr('data-id'); if ($(this).hasClass('btn-success')) { unselectPark(parkId); } else { if (parkIds.length != 2) { $(this).addClass('btn-success'); $(this).text('Selected'); $('#compare-parks-body').append('<button data-park="' + parkId + '" id="compare-park-' + parkId +'" class="btn btn-warning selected-park" aria-label="Right Align">' + $(this).data('name') + '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' + '</button>') parkIds.push(parkId); } } handleCompareButton(); }); $('#compare-parks-body').on('click', '.selected-park', function() { var parkId = $(this).data('park'); unselectPark(parkId, this); handleCompareButton(); }); }); function handleCompareButton() { if (parkIds.length == 2) { $('#compare').attr('disabled', false); var url = '../compare?park1=' + parkIds[0] + '&park2=' + parkIds[1]; $('#compare').attr('href', url); } else { $('#compare').attr('disabled', true); } } function unselectPark(parkId)
{ $('#park-' + parkId).find('.select').removeClass('btn-success').text('compare'); parkIds.splice(parkIds.indexOf(parkId), 1); $('#compare-park-' + parkId).remove(); }
identifier_body
parks.js
//Author: Sam var parkIds = []; $(document).ready(function() { $('#toMap').on('click', function() { if (typeof map == 'undefined') { initialize(); } }); $('.park').on('click', '.select', function(e) { e.preventDefault(); var parkId = $(this).attr('data-id'); if ($(this).hasClass('btn-success')) { unselectPark(parkId); } else { if (parkIds.length != 2) { $(this).addClass('btn-success'); $(this).text('Selected'); $('#compare-parks-body').append('<button data-park="' + parkId + '" id="compare-park-' + parkId +'" class="btn btn-warning selected-park" aria-label="Right Align">' + $(this).data('name') + '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' + '</button>') parkIds.push(parkId); } } handleCompareButton(); }); $('#compare-parks-body').on('click', '.selected-park', function() { var parkId = $(this).data('park'); unselectPark(parkId, this); handleCompareButton(); }); }); function handleCompareButton() { if (parkIds.length == 2) { $('#compare').attr('disabled', false); var url = '../compare?park1=' + parkIds[0] + '&park2=' + parkIds[1]; $('#compare').attr('href', url); } else { $('#compare').attr('disabled', true); } } function
(parkId) { $('#park-' + parkId).find('.select').removeClass('btn-success').text('compare'); parkIds.splice(parkIds.indexOf(parkId), 1); $('#compare-park-' + parkId).remove(); }
unselectPark
identifier_name
workerTest.py
# Copyright (C) 2015-2021 Regents of the University of California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from toil.common import Config from toil.job import CheckpointJobDescription, JobDescription from toil.jobStores.fileJobStore import FileJobStore from toil.test import ToilTest, travis_test from toil.worker import nextChainable class WorkerTests(ToilTest): """Test miscellaneous units of the worker.""" def setUp(self): super(WorkerTests, self).setUp() path = self._getTestJobStorePath() self.jobStore = FileJobStore(path) self.config = Config() self.config.jobStore = 'file:%s' % path self.jobStore.initialize(self.config) self.jobNumber = 0 @travis_test def
(self): """Make sure chainable/non-chainable jobs are identified correctly.""" def createTestJobDesc(memory, cores, disk, preemptable, checkpoint): """ Create a JobDescription with no command (representing a Job that has already run) and return the JobDescription. """ name = 'job%d' % self.jobNumber self.jobNumber += 1 descClass = CheckpointJobDescription if checkpoint else JobDescription jobDesc = descClass(requirements={'memory': memory, 'cores': cores, 'disk': disk, 'preemptable': preemptable}, jobName=name) # Assign an ID self.jobStore.assignID(jobDesc) # Save and return the JobDescription return self.jobStore.create(jobDesc) for successorType in ['addChild', 'addFollowOn']: # Try with the branch point at both child and follow-on stages # Identical non-checkpoint jobs should be chainable. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) chainable = nextChainable(jobDesc1, self.jobStore, self.config) self.assertNotEqual(chainable, None) self.assertEqual(jobDesc2.jobStoreID, chainable.jobStoreID) # Identical checkpoint jobs should not be chainable. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is no child we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there are 2 or more children we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) jobDesc3 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) getattr(jobDesc1, successorType)(jobDesc3.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is an increase in resource requirements we should get nothing to chain. reqs = {'memory': 1, 'cores': 2, 'disk': 3, 'preemptable': True, 'checkpoint': False} for increased_attribute in ('memory', 'cores', 'disk'): jobDesc1 = createTestJobDesc(**reqs) reqs[increased_attribute] += 1 jobDesc2 = createTestJobDesc(**reqs) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # A change in preemptability from True to False should be disallowed. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, False, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
testNextChainable
identifier_name
workerTest.py
# Copyright (C) 2015-2021 Regents of the University of California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from toil.common import Config from toil.job import CheckpointJobDescription, JobDescription from toil.jobStores.fileJobStore import FileJobStore from toil.test import ToilTest, travis_test from toil.worker import nextChainable class WorkerTests(ToilTest): """Test miscellaneous units of the worker.""" def setUp(self):
@travis_test def testNextChainable(self): """Make sure chainable/non-chainable jobs are identified correctly.""" def createTestJobDesc(memory, cores, disk, preemptable, checkpoint): """ Create a JobDescription with no command (representing a Job that has already run) and return the JobDescription. """ name = 'job%d' % self.jobNumber self.jobNumber += 1 descClass = CheckpointJobDescription if checkpoint else JobDescription jobDesc = descClass(requirements={'memory': memory, 'cores': cores, 'disk': disk, 'preemptable': preemptable}, jobName=name) # Assign an ID self.jobStore.assignID(jobDesc) # Save and return the JobDescription return self.jobStore.create(jobDesc) for successorType in ['addChild', 'addFollowOn']: # Try with the branch point at both child and follow-on stages # Identical non-checkpoint jobs should be chainable. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) chainable = nextChainable(jobDesc1, self.jobStore, self.config) self.assertNotEqual(chainable, None) self.assertEqual(jobDesc2.jobStoreID, chainable.jobStoreID) # Identical checkpoint jobs should not be chainable. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is no child we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there are 2 or more children we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) jobDesc3 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) getattr(jobDesc1, successorType)(jobDesc3.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is an increase in resource requirements we should get nothing to chain. reqs = {'memory': 1, 'cores': 2, 'disk': 3, 'preemptable': True, 'checkpoint': False} for increased_attribute in ('memory', 'cores', 'disk'): jobDesc1 = createTestJobDesc(**reqs) reqs[increased_attribute] += 1 jobDesc2 = createTestJobDesc(**reqs) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # A change in preemptability from True to False should be disallowed. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, False, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
super(WorkerTests, self).setUp() path = self._getTestJobStorePath() self.jobStore = FileJobStore(path) self.config = Config() self.config.jobStore = 'file:%s' % path self.jobStore.initialize(self.config) self.jobNumber = 0
identifier_body
workerTest.py
# Copyright (C) 2015-2021 Regents of the University of California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from toil.common import Config from toil.job import CheckpointJobDescription, JobDescription from toil.jobStores.fileJobStore import FileJobStore from toil.test import ToilTest, travis_test from toil.worker import nextChainable class WorkerTests(ToilTest): """Test miscellaneous units of the worker.""" def setUp(self): super(WorkerTests, self).setUp() path = self._getTestJobStorePath() self.jobStore = FileJobStore(path) self.config = Config() self.config.jobStore = 'file:%s' % path self.jobStore.initialize(self.config) self.jobNumber = 0 @travis_test def testNextChainable(self): """Make sure chainable/non-chainable jobs are identified correctly.""" def createTestJobDesc(memory, cores, disk, preemptable, checkpoint): """ Create a JobDescription with no command (representing a Job that has already run) and return the JobDescription. """ name = 'job%d' % self.jobNumber self.jobNumber += 1 descClass = CheckpointJobDescription if checkpoint else JobDescription jobDesc = descClass(requirements={'memory': memory, 'cores': cores, 'disk': disk, 'preemptable': preemptable}, jobName=name) # Assign an ID self.jobStore.assignID(jobDesc) # Save and return the JobDescription return self.jobStore.create(jobDesc) for successorType in ['addChild', 'addFollowOn']: # Try with the branch point at both child and follow-on stages # Identical non-checkpoint jobs should be chainable.
jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) chainable = nextChainable(jobDesc1, self.jobStore, self.config) self.assertNotEqual(chainable, None) self.assertEqual(jobDesc2.jobStoreID, chainable.jobStoreID) # Identical checkpoint jobs should not be chainable. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is no child we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there are 2 or more children we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) jobDesc3 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) getattr(jobDesc1, successorType)(jobDesc3.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is an increase in resource requirements we should get nothing to chain. reqs = {'memory': 1, 'cores': 2, 'disk': 3, 'preemptable': True, 'checkpoint': False} for increased_attribute in ('memory', 'cores', 'disk'): jobDesc1 = createTestJobDesc(**reqs) reqs[increased_attribute] += 1 jobDesc2 = createTestJobDesc(**reqs) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # A change in preemptability from True to False should be disallowed. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, False, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
conditional_block
workerTest.py
# Copyright (C) 2015-2021 Regents of the University of California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from toil.common import Config from toil.job import CheckpointJobDescription, JobDescription from toil.jobStores.fileJobStore import FileJobStore from toil.test import ToilTest, travis_test from toil.worker import nextChainable
self.jobStore = FileJobStore(path) self.config = Config() self.config.jobStore = 'file:%s' % path self.jobStore.initialize(self.config) self.jobNumber = 0 @travis_test def testNextChainable(self): """Make sure chainable/non-chainable jobs are identified correctly.""" def createTestJobDesc(memory, cores, disk, preemptable, checkpoint): """ Create a JobDescription with no command (representing a Job that has already run) and return the JobDescription. """ name = 'job%d' % self.jobNumber self.jobNumber += 1 descClass = CheckpointJobDescription if checkpoint else JobDescription jobDesc = descClass(requirements={'memory': memory, 'cores': cores, 'disk': disk, 'preemptable': preemptable}, jobName=name) # Assign an ID self.jobStore.assignID(jobDesc) # Save and return the JobDescription return self.jobStore.create(jobDesc) for successorType in ['addChild', 'addFollowOn']: # Try with the branch point at both child and follow-on stages # Identical non-checkpoint jobs should be chainable. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) chainable = nextChainable(jobDesc1, self.jobStore, self.config) self.assertNotEqual(chainable, None) self.assertEqual(jobDesc2.jobStoreID, chainable.jobStoreID) # Identical checkpoint jobs should not be chainable. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is no child we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there are 2 or more children we should get nothing to chain. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, True, False) jobDesc3 = createTestJobDesc(1, 2, 3, True, False) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) getattr(jobDesc1, successorType)(jobDesc3.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # If there is an increase in resource requirements we should get nothing to chain. reqs = {'memory': 1, 'cores': 2, 'disk': 3, 'preemptable': True, 'checkpoint': False} for increased_attribute in ('memory', 'cores', 'disk'): jobDesc1 = createTestJobDesc(**reqs) reqs[increased_attribute] += 1 jobDesc2 = createTestJobDesc(**reqs) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config)) # A change in preemptability from True to False should be disallowed. jobDesc1 = createTestJobDesc(1, 2, 3, True, False) jobDesc2 = createTestJobDesc(1, 2, 3, False, True) getattr(jobDesc1, successorType)(jobDesc2.jobStoreID) self.assertEqual(None, nextChainable(jobDesc1, self.jobStore, self.config))
class WorkerTests(ToilTest): """Test miscellaneous units of the worker.""" def setUp(self): super(WorkerTests, self).setUp() path = self._getTestJobStorePath()
random_line_split
lobby.module.ts
import { NgModule } from '@angular/core' import { SharedModule } from '@app/shared/shared.module' import { LobbyComponent } from './lobby.component' // message-window import { LobbyMessagesComponent } from './lobby-messages/lobby-messages.component' import { ItemGroupComponent } from './lobby-messages/item-group/item-group.component' import { ItemComponent, ITEM_DECLARATIONS } from './lobby-messages/item-group/item/item.component' import { LobbyItemOptionsDialogService, DIALOGS } from './dialogs' import { LobbyItemInputComponent } from './lobby-item-input/lobby-item-input.component' import { LobbyRendererService } from './lobby-renderer' import { MaterialModule } from '@angular/material'; import { LobbyRoutingModule } from './lobby-routing.module' @NgModule({ imports: [ SharedModule, LobbyRoutingModule, MaterialModule ], declarations: [ LobbyComponent, LobbyItemInputComponent, LobbyMessagesComponent, ItemGroupComponent, ...DIALOGS, ...ITEM_DECLARATIONS, ItemComponent, ], // Allow the DIALOGS to be made into componentFactories for the MdDialog to use! entryComponents: [...DIALOGS], providers: [ LobbyRendererService, LobbyItemOptionsDialogService ] }) export class
{ }
LobbyModule
identifier_name
lobby.module.ts
import { NgModule } from '@angular/core' import { SharedModule } from '@app/shared/shared.module' import { LobbyComponent } from './lobby.component' // message-window import { LobbyMessagesComponent } from './lobby-messages/lobby-messages.component' import { ItemGroupComponent } from './lobby-messages/item-group/item-group.component' import { ItemComponent, ITEM_DECLARATIONS } from './lobby-messages/item-group/item/item.component' import { LobbyItemOptionsDialogService, DIALOGS } from './dialogs' import { LobbyItemInputComponent } from './lobby-item-input/lobby-item-input.component' import { LobbyRendererService } from './lobby-renderer' import { MaterialModule } from '@angular/material'; import { LobbyRoutingModule } from './lobby-routing.module' @NgModule({ imports: [ SharedModule, LobbyRoutingModule, MaterialModule ], declarations: [ LobbyComponent, LobbyItemInputComponent, LobbyMessagesComponent, ItemGroupComponent, ...DIALOGS, ...ITEM_DECLARATIONS, ItemComponent, ],
// Allow the DIALOGS to be made into componentFactories for the MdDialog to use! entryComponents: [...DIALOGS], providers: [ LobbyRendererService, LobbyItemOptionsDialogService ] }) export class LobbyModule { }
random_line_split
payment-merchant-manage-page.effects.ts
import {HttpClient} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Router} from '@angular/router'; import {Actions, Effect} from '@ngrx/effects'; import {Action, Store} from '@ngrx/store'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/exhaustMap'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/pluck'; import 'rxjs/add/operator/switchMap'; import {Observable} from 'rxjs/Observable'; import {of} from 'rxjs/observable/of'; import {UtilService} from '../../../core/services/util.service'; import {ShowError, ShowWxQrcoode} from '../../../core/store/actions/core'; import {EnlistService} from '../../services/enlist.service'; import {paymentMerchantManagePageActions} from '../../store'; @Injectable() export class
{ @Effect() init$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.INIT) .exhaustMap(() => { return this.enlistService.listPaymentMerchant() .map(res => new paymentMerchantManagePageActions.InitSuccess(res)) .catch(error => of(new ShowError(error))); }); @Effect() invite$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.INVITE) .exhaustMap((action: paymentMerchantManagePageActions.Invite) => { return this.enlistService.paymentMerchantInvite(action.paymentMerchantId) .map(res => new ShowWxQrcoode(res.ticket, '')) .catch(error => of(new ShowError(error))); }); @Effect() deleteManager$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.DELETE_MANAGER) .exhaustMap((action: paymentMerchantManagePageActions.DeleteManager) => { const {paymentMerchantId, managerId} = action.payload; return this.enlistService.deletePaymentMerchantManager(paymentMerchantId, managerId) .map(() => new paymentMerchantManagePageActions.DeleteManagerSuccess({paymentMerchantId, managerId})) .catch(error => of(new ShowError(error))); }); constructor(private store: Store<any>, private actions$: Actions, private router: Router, private http: HttpClient, private utilService: UtilService, private enlistService: EnlistService) { } }
PaymentMerchantManagePageEffects
identifier_name
payment-merchant-manage-page.effects.ts
import {HttpClient} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Router} from '@angular/router'; import {Actions, Effect} from '@ngrx/effects'; import {Action, Store} from '@ngrx/store'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/exhaustMap'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/pluck'; import 'rxjs/add/operator/switchMap'; import {Observable} from 'rxjs/Observable'; import {of} from 'rxjs/observable/of'; import {UtilService} from '../../../core/services/util.service'; import {ShowError, ShowWxQrcoode} from '../../../core/store/actions/core'; import {EnlistService} from '../../services/enlist.service'; import {paymentMerchantManagePageActions} from '../../store'; @Injectable() export class PaymentMerchantManagePageEffects { @Effect() init$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.INIT) .exhaustMap(() => { return this.enlistService.listPaymentMerchant() .map(res => new paymentMerchantManagePageActions.InitSuccess(res)) .catch(error => of(new ShowError(error))); }); @Effect() invite$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.INVITE) .exhaustMap((action: paymentMerchantManagePageActions.Invite) => { return this.enlistService.paymentMerchantInvite(action.paymentMerchantId) .map(res => new ShowWxQrcoode(res.ticket, '')) .catch(error => of(new ShowError(error))); }); @Effect() deleteManager$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.DELETE_MANAGER) .exhaustMap((action: paymentMerchantManagePageActions.DeleteManager) => { const {paymentMerchantId, managerId} = action.payload; return this.enlistService.deletePaymentMerchantManager(paymentMerchantId, managerId) .map(() => new paymentMerchantManagePageActions.DeleteManagerSuccess({paymentMerchantId, managerId})) .catch(error => of(new ShowError(error))); }); constructor(private store: Store<any>, private actions$: Actions, private router: Router, private http: HttpClient, private utilService: UtilService, private enlistService: EnlistService)
}
{ }
identifier_body
payment-merchant-manage-page.effects.ts
import {HttpClient} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Router} from '@angular/router'; import {Actions, Effect} from '@ngrx/effects'; import {Action, Store} from '@ngrx/store'; import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable'; import {of} from 'rxjs/observable/of'; import {UtilService} from '../../../core/services/util.service'; import {ShowError, ShowWxQrcoode} from '../../../core/store/actions/core'; import {EnlistService} from '../../services/enlist.service'; import {paymentMerchantManagePageActions} from '../../store'; @Injectable() export class PaymentMerchantManagePageEffects { @Effect() init$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.INIT) .exhaustMap(() => { return this.enlistService.listPaymentMerchant() .map(res => new paymentMerchantManagePageActions.InitSuccess(res)) .catch(error => of(new ShowError(error))); }); @Effect() invite$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.INVITE) .exhaustMap((action: paymentMerchantManagePageActions.Invite) => { return this.enlistService.paymentMerchantInvite(action.paymentMerchantId) .map(res => new ShowWxQrcoode(res.ticket, '')) .catch(error => of(new ShowError(error))); }); @Effect() deleteManager$: Observable<Action> = this.actions$ .ofType(paymentMerchantManagePageActions.DELETE_MANAGER) .exhaustMap((action: paymentMerchantManagePageActions.DeleteManager) => { const {paymentMerchantId, managerId} = action.payload; return this.enlistService.deletePaymentMerchantManager(paymentMerchantId, managerId) .map(() => new paymentMerchantManagePageActions.DeleteManagerSuccess({paymentMerchantId, managerId})) .catch(error => of(new ShowError(error))); }); constructor(private store: Store<any>, private actions$: Actions, private router: Router, private http: HttpClient, private utilService: UtilService, private enlistService: EnlistService) { } }
import 'rxjs/add/operator/exhaustMap'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/pluck'; import 'rxjs/add/operator/switchMap';
random_line_split
analytics.service.ts
import { Injectable } from '@angular/core'; import { environment } from '../../../environments/environment'; import { AppInsights } from 'applicationinsights-js'; // Declare ga function as ambient declare const ga: Function; @Injectable() export class AnalyticsService { private config: Microsoft.ApplicationInsights.IConfig = { instrumentationKey: environment.appInsights.instrumentationKey }; constructor() { if (!AppInsights.config) { AppInsights.downloadAndSetup(this.config); } } logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
emitEvent(eventCategory: string, eventAction: string, eventLabel: string = null, eventValue: number = null) { ga( 'send', 'event', { eventCategory: eventCategory, eventLabel: eventLabel, eventAction: eventAction, eventValue: eventValue }); } }
AppInsights.trackPageView( name, url, properties, measurements, duration); ga('set', 'page', url); ga('send', 'pageview'); }
identifier_body
analytics.service.ts
import { Injectable } from '@angular/core'; import { environment } from '../../../environments/environment'; import { AppInsights } from 'applicationinsights-js'; // Declare ga function as ambient declare const ga: Function; @Injectable() export class An
private config: Microsoft.ApplicationInsights.IConfig = { instrumentationKey: environment.appInsights.instrumentationKey }; constructor() { if (!AppInsights.config) { AppInsights.downloadAndSetup(this.config); } } logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) { AppInsights.trackPageView( name, url, properties, measurements, duration); ga('set', 'page', url); ga('send', 'pageview'); } emitEvent(eventCategory: string, eventAction: string, eventLabel: string = null, eventValue: number = null) { ga( 'send', 'event', { eventCategory: eventCategory, eventLabel: eventLabel, eventAction: eventAction, eventValue: eventValue }); } }
alyticsService {
identifier_name