language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public Request<DeleteVpcEndpointsRequest> getDryRunRequest() { Request<DeleteVpcEndpointsRequest> request = new DeleteVpcEndpointsRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
java
public void setSubjectAlternativeNames(java.util.Collection<String> subjectAlternativeNames) { if (subjectAlternativeNames == null) { this.subjectAlternativeNames = null; return; } this.subjectAlternativeNames = new java.util.ArrayList<String>(subjectAlternativeNames); ...
java
public void close() throws IOException { try { while (processNextResponse(0)) ; file.close(); } catch (SshException ex) { throw new SshIOException(ex); } catch (SftpStatusException ex) { throw new IOException(ex.getMessage()); } }
python
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): """ Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ...
java
public HttpResponse request(HttpRequest smartsheetRequest) throws HttpClientException { Util.throwIfNull(smartsheetRequest); if (smartsheetRequest.getUri() == null) { throw new IllegalArgumentException("A Request URI is required."); } int attempt = 0; long start = Sy...
python
def set_ext_param(self, ext_key, param_key, val): ''' Set the provided parameter in a set of extension parameters. ''' if not self.extensions[ext_key]: self.extensions[ext_key] = defaultdict(lambda: None) self.extensions[ext_key][param_key] = val
java
public static double[] columnPackedCopy(final double[][] m1) { final int rowdim = m1.length, coldim = getColumnDimensionality(m1); final double[] vals = new double[m1.length * coldim]; for(int i = 0; i < rowdim; i++) { final double[] rowM = m1[i]; // assert rowM.length == coldim : ERR_MATRIX_RAG...
java
public void connect() { CommandFactory f = new CommandFactory(); f.addTrainerInitCommand(); initMessage = f.next(); super.start(); super.setName("Trainer"); }
python
def get_default_stats(): """Returns a :class: `dict` of the default stats structure.""" default_stats = { "total_count": 0, "max": 0, "min": 0, "value": 0, "average": 0, "last_update": None, } return { "totals": default_stats, "colors": {...
python
def create_snmp_manager(self, manager, host, **kwargs): """Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide o...
python
def _chunkForSend(self, data): """ limit the chunks that we send over PB to 128k, since it has a hardwired string-size limit of 640k. """ LIMIT = self.CHUNK_LIMIT for i in range(0, len(data), LIMIT): yield data[i:i + LIMIT]
python
def process_params(self, params): ''' Populates the launch data from a dictionary. Only cares about keys in the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or 'ext_'. ''' for key, val in params.items(): if key in LAUNCH_DATA_PARAMETERS and val !=...
java
void removeExportedKeys(Table toDrop) { // toDrop.schema may be null because it is not registerd Schema schema = (Schema) schemaMap.get(toDrop.getSchemaName().name); for (int i = 0; i < schema.tableList.size(); i++) { Table table = (Table) schema.tableList.get(i); for ...
java
private void destroyPingExecutor() { synchronized (pingExecutor) { if (!pingExecutor.isShutdown()) { try { log.debugf("Shutting down WebSocket ping executor"); pingExecutor.shutdown(); if (!pingExecutor.awaitTermination(1, T...
python
def search_ap(self, mode, query): """搜索接入点 查看指定接入点的所有配置信息,包括所有监听端口的配置。 Args: - mode: 搜索模式,可以是domain、ip、host - query: 搜索文本 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回搜索结果,失败返回{"error": "<errMsg string...
java
private static ImmutableMap<String, Annotation> buildAnnotations(Iterable<String> whitelist) { ImmutableMap.Builder<String, Annotation> annotationsBuilder = ImmutableMap.builder(); annotationsBuilder.putAll(Annotation.recognizedAnnotations); for (String unrecognizedAnnotation : whitelist) { if (!unrec...
java
private static SimpleEntry<byte[], Integer> readAllBytes(final InputStream inputStream, final long fileSizeHint) throws IOException { if (fileSizeHint > MAX_BUFFER_SIZE) { throw new IOException("InputStream is too large to read"); } final int bufferSize = fileSizeHint < 1...
python
def new_filename(original_filename, new_locale): """Returns a filename derived from original_filename, using new_locale as the locale""" orig_file = Path(original_filename) new_file = orig_file.parent.parent.parent / new_locale / orig_file.parent.name / orig_file.name return new_file.abspath()
java
public ConversationMessage viewConversationMessage(final String messageId) throws NotFoundException, GeneralException, UnauthorizedException { String url = CONVERSATIONS_BASE_URL + CONVERSATION_MESSAGE_PATH; return messageBirdService.requestByID(url, messageId, ConversationMessage.class); ...
python
def setColor(self, color): """ Sets the current :py:class:`Color` to use. :param color: The :py:class:`Color` to use. :rtype: Nothing. """ self.color = color if self.brush and self.brush.doesUseSourceCaching(): self.brush.cacheBrush(color)
java
public static MySqlConnectionPoolBuilder newBuilder(final String connectionString, final String username) { final String[] arr = connectionString.split(":"); final String host = arr[0]; final int port = Integer.parseInt(arr[1]); return newBuilder(host, port, username); }
python
def conv(self,field_name,conv_func): """When a record is returned by a SELECT, ask conversion of specified field value with the specified function""" if field_name not in self.fields: raise NameError,"Unknown field %s" %field_name self.conv_func[field_name] = conv_func
python
def listVars(prefix="", equals="\t= ", **kw): """List IRAF variables.""" keylist = getVarList() if len(keylist) == 0: print('No IRAF variables defined') else: keylist.sort() for word in keylist: print("%s%s%s%s" % (prefix, word, equals, envget(word)))
java
@Override public TopicSubscriber createDurableSubscriber(Topic topic, String subscriptionName, String messageSelector, boolean noLocal) throws JMSException { throw new IllegalStateException("Method not available on this domain."); }
python
def homegearCheckInit(self, remote): """Check if proxy is still initialized""" rdict = self.remotes.get(remote) if not rdict: return False if rdict.get('type') != BACKEND_HOMEGEAR: return False try: interface_id = "%s-%s" % (self._interface_id,...
python
def select_product(): """ binds the frozen context the selected features should be called only once - calls after the first call have no effect """ global _product_selected if _product_selected: # tss already bound ... ignore return _product_selected = True from dja...
java
protected void assertArgumentNotNull(String argumentName, Object value) { if (argumentName == null) { String msg = "The argument name should not be null: argName=null value=" + value; throw new IllegalArgumentException(msg); } if (value == null) { String msg =...
java
public AwsSecurityFindingFilters withRecommendationText(StringFilter... recommendationText) { if (this.recommendationText == null) { setRecommendationText(new java.util.ArrayList<StringFilter>(recommendationText.length)); } for (StringFilter ele : recommendationText) { th...
python
def run_filter_radia(job, bams, radia_file, univ_options, radia_options, chrom): """ Run filterradia on the RADIA output. :param dict bams: Dict of bam and bai for tumor DNA-Seq, normal DNA-Seq and tumor RNA-Seq :param toil.fileStore.FileID radia_file: The vcf from runnning RADIA :param dict univ_o...
java
public final EObject ruleParenthesizedAssignableElement() throws RecognitionException { EObject current = null; Token otherlv_0=null; Token otherlv_2=null; EObject this_AssignableAlternatives_1 = null; enterRule(); try { // InternalXtext.g:2544:2: ( (oth...
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WMultiDropdown dropdown = (WMultiDropdown) component; XmlStringBuilder xml = renderContext.getWriter(); String dataKey = dropdown.getListCacheKey(); boolean readOnly = dropdown.isReadOnly(); xml.appendTagOp...
python
def addFeatureSet(self): """ Adds a new feature set into this repo """ self._openRepo() dataset = self._repo.getDatasetByName(self._args.datasetName) filePath = self._getFilePath(self._args.filePath, self._args.relativePath) na...
python
def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not an IPv4 or IPv6 address. Returns the value argument. * value (str): The value being validated as an IP address. * blank (bool): If True, a blank strin...
java
public CommandArgs createCommandArgs() throws ParseException { // In case the last arg was a call-by-name , have that parameter parse a 'no-value' value. // Can only succeed in certain cases with certain parameters. if (nextNamedParam.isPresent()) { // The last parsed arg did indeed ...
java
public static void bitVectorToEdge(final BitVector bv, final long seed, final int numVertices, final int partSize, final int e[]) { if (numVertices == 0) { e[0] = e[1] = e[2] = -1; return; } final long[] hash = new long[3]; Hashes.spooky4(bv, seed, hash); e[0] = (int)((hash[0] & 0x7FFFFFFFFFFFFFFFL) % p...
java
private String toAlias(String propertyName) { String result = propertyAliasType.get(propertyName); return result == null ? propertyName : result; }
python
def hmget(self, key, field, *fields, encoding=_NOTSET): """Get the values of all the given fields.""" return self.execute(b'HMGET', key, field, *fields, encoding=encoding)
python
def boost_ranks(job, isoform_expression, merged_mhc_calls, transgene_out, univ_options, rankboost_options): """ Boost the ranks of the predicted peptides:MHC combinations. :param toil.fileStore.FileID isoform_expression: fsID of rsem isoform expression file :param dict merged_mhc_calls:...
java
public static Person getWithJAASKey(final JAASSystem _jaasSystem, final String _jaasKey) throws EFapsException { long personId = 0; Connection con = null; try { con = Context.getConnection(); PreparedStatement stmt = nul...
python
def getSCDPURL(self, serviceType, default=None): """Returns the SCDP (Service Control Protocol Document) URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace th...
java
public static ParametricFactorGraph buildSequenceModel(Iterable<String> emissionFeatureLines, String featureDelimiter) { // Read in the possible values of each variable. List<String> words = StringUtils.readColumnFromDelimitedLines(emissionFeatureLines, 0, featureDelimiter); List<String> labels = Stri...
java
public static IDLProxyObject createSingle(InputStream is, boolean debug, boolean isUniName) throws IOException { return createSingle(is, debug, null, isUniName); }
java
public void marshall(GetSampledRequestsRequest getSampledRequestsRequest, ProtocolMarshaller protocolMarshaller) { if (getSampledRequestsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getS...
python
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): """ Search nodes matching `filter_` but stop at `maxlevel` or `stop`. Return tuple with matching nodes. Args: node: top node, start searching. Keyword Args: filter_: function called with every...
python
def setup_figure(self, figure): """ Makes any desired changes to the figure object This method will be called once with a figure object before any plotting has completed. Subclasses that override this method should make sure that the base class method is called. ...
python
def sync_release_files(self): """ Purge + download files returning files removed + added """ release_files = [] for release in self.releases.values(): release_files.extend(release) downloaded_files = set() deferred_exception = None for release_file in releas...
java
public static void isNotEmpty( Object[] argument, String name ) { isNotNull(argument, name); if (argument.length == 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeEmpty.text(name)); } }
python
def boundaries(self, boundaryEdges=True, featureAngle=65, nonManifoldEdges=True): """ Return an ``Actor`` that shows the boundary lines of an input mesh. :param bool boundaryEdges: Turn on/off the extraction of boundary edges. :param float featureAngle: Specify the feature angle...
java
public static base_response unset(nitro_service client, snmpmib resource, String[] args) throws Exception{ snmpmib unsetresource = new snmpmib(); return unsetresource.unset_resource(client,args); }
java
static ObjectName createObjectName(final String domain, final PathAddress pathAddress) { return createObjectName(domain, pathAddress, null); }
python
def bind_to_constructor(self, cls, constructor): """Bind a class to a callable singleton constructor.""" self._check_class(cls) if constructor is None: raise InjectorException('Constructor cannot be None, key=%s' % cls) self._bindings[cls] = _ConstructorBinding(constructor) ...
java
public static <T> Collector<T, ?, List<T>> filtering(Predicate<? super T> predicate) { return filtering(predicate, Collectors.toList()); }
python
def info(self, request, message, extra_tags='', fail_silently=False): """Add a message with the ``INFO`` level.""" add(self.target_name, request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently)
python
def clone(root, jsontreecls=jsontree, datetimeencoder=_datetimeencoder, datetimedecoder=_datetimedecoder): """Clone an object by first searializing out and then loading it back in. """ return json.loads(json.dumps(root, cls=JSONTreeEncoder, datetimeencoder=datetime...
python
def visit(self, module): """Walk the given astroid *tree* and transform each encountered node Only the nodes which have transforms registered will actually be replaced or changed. """ module.body = [self._visit(child) for child in module.body] return self._transform(modu...
python
def check_arrange_act_spacing(self) -> typing.Generator[AAAError, None, None]: """ * When no spaces found, point error at line above act block * When too many spaces found, point error at 2nd blank line """ yield from self.check_block_spacing( LineType.arrange, ...
java
public JobWithJars getPlanWithJars() throws ProgramInvocationException { if (isUsingProgramEntryPoint()) { return new JobWithJars(getPlan(), getAllLibraries(), classpaths, userCodeClassLoader); } else { throw new ProgramInvocationException("Cannot create a " + JobWithJars.class.getSimpleName() + " for a ...
java
@Override public final String nameForKey(final int mKey) { checkState(!mPageReadTrx.isClosed(), "Transaction is already closed."); NodeMetaPageFactory.MetaKey key = new NodeMetaPageFactory.MetaKey(mKey); NodeMetaPageFactory.MetaValue value = (MetaValue)mPageReadTrx.getMetaBucket().get(key); ...
python
def set_with_conversion(self, variable, value_string): """Convert user supplied string to Python type. Lets user use values such as True, False and integers. All variables can be set to None, regardless of type. Handle the case where a string is typed by the user and is not quoted, as a...
python
def consume(self, f): """ Creates a sink which consumes all values for this Recver. *f* is a callable which takes a single argument. All values sent on this Recver's Sender will be passed to *f* for processing. Unlike *map* however consume terminates this chain:: sen...
python
def init_manager(app, db, **kwargs): """ Initialise Manager :param app: Flask app object :parm db: db instance :param kwargs: Additional keyword arguments to be made available as shell context """ manager.app = app manager.db = db manager.context = kwargs manager.add_command('db...
python
def step(self, observations): """ Sample action from an action space for given state """ log_histogram = self(observations) actions = self.q_head.sample(log_histogram) return { 'actions': actions, 'log_histogram': log_histogram }
python
def unix_install(): """ Edits or creates .bashrc, .bash_profile, and .profile files in the users HOME directory in order to add your current directory (hopefully your PmagPy directory) and assorted lower directories in the PmagPy/programs directory to your PATH environment variable. It also adds the...
python
def list(self, cart_glob=['*.json']): """ List all carts """ carts = [] for glob in cart_glob: # Translate cart names into cart file names if not glob.endswith('.json'): search_glob = glob + ".json" else: search_...
python
def decrypt(data, digest=True): """Decrypt provided data.""" alg, _, data = data.rpartition("$") if not alg: return data data = _from_hex_digest(data) if digest else data try: return implementations["decryption"][alg]( data, implementations["get_key"]() ) exce...
java
public Link link(String name, BaseAsset asset, String url, boolean onMenu, Map<String, Object> attributes) { Link link = new Link(instance); link.setAsset(asset); link.setName(name); link.setURL(url); link.setOnMenu(onMenu); addAttributes(link, attri...
python
def mi(x, y): ''' compute and return the mutual information between x and y inputs: ------- x, y: iterables of hashable items output: ------- mi: float Notes: ------ if you are trying to mix several symbols together as in mi(x, (y0,y1,...)), try ...
python
def check(table='filter', chain=None, rule=None, family='ipv4'): ''' Check for the existence of a rule in the table and chain This function accepts a rule in a standard nftables command format, starting with the chain. Trying to force users to adapt to a new method of creating rules would b...
java
@NonNull public static Term divide(@NonNull Term left, @NonNull Term right) { return new BinaryArithmeticTerm(ArithmeticOperator.QUOTIENT, left, right); }
python
def save_file(self, srcfile): """ Save a (raw) file to the store. """ filehash = digest_file(srcfile) if not os.path.exists(self.object_path(filehash)): # Copy the file to a temporary location first, then move, to make sure we don't end up with # truncated...
python
def get_git_repositories_activity_metrics(self, project, from_date, aggregation_type, skip, top): """GetGitRepositoriesActivityMetrics. [Preview API] Retrieves git activity metrics for repositories matching a specified criteria. :param str project: Project ID or project name :param datet...
java
public ArrayList<OvhProductInformation> cart_cartId_domainTransfer_GET(String cartId, String domain) throws IOException { String qPath = "/order/cart/{cartId}/domainTransfer"; StringBuilder sb = path(qPath, cartId); query(sb, "domain", domain); String resp = execN(qPath, "GET", sb.toString(), null); return co...
python
def _iplot(self,kind='scatter',data=None,layout=None,filename='',sharing=None,title='',xTitle='',yTitle='',zTitle='',theme=None,colors=None,colorscale=None,fill=False,width=None, dash='solid',mode='',interpolation='linear',symbol='circle',size=12,barmode='',sortbars=False,bargap=None,bargroupgap=None,bins=None,histn...
python
def domain(self, default): """ Get the domain for this pipeline. - If an explicit domain was provided at construction time, use it. - Otherwise, infer a domain from the registered columns. - If no domain can be inferred, return ``default``. Parameters ----------...
java
public static String escapeXml11(final String text, final XmlEscapeType type, final XmlEscapeLevel level) { return escapeXml(text, XmlEscapeSymbols.XML11_SYMBOLS, type, level); }
python
def insert(self, context, plan): """ Include an insert operation to the given plan. :param execution.Context context: Current execution context. :param list plan: List of :class:`execution.Operation` instances. """ op = execution.Insert(self.__comp_name, self.__comp()) if op not in plan ...
python
def booted(name, single=False): ''' Ensure zone is booted name : string name of the zone single : boolean boot in single usermode ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} zones = __salt__['zoneadm.list'](instal...
python
def _apply_dvs_infrastructure_traffic_resources(infra_traffic_resources, resource_dicts): ''' Applies the values of the resource dictionaries to infra traffic resources, creating the infra traffic resource if required (vim.DistributedVirtualSwitchProductSp...
python
def minimise_xyz(xyz): """Minimise an (x, y, z) coordinate.""" x, y, z = xyz m = max(min(x, y), min(max(x, y), z)) return (x-m, y-m, z-m)
java
int writeBytes(OutputStream out) throws IOException { int length = myBuffer.length - myOffset; byte[] bytes = new byte[length]; System.arraycopy(myBuffer, myOffset, bytes, 0, length); out.write(bytes); return length; }
java
private void requestSegments(IntSet segments, Map<Address, IntSet> sources, Set<Address> excludedSources) { if (sources.isEmpty()) { findSources(segments, sources, excludedSources); } for (Map.Entry<Address, IntSet> e : sources.entrySet()) { addTransfer(e.getKey(), e.getValue()); ...
java
public void setPageSize(Rectangle pageSize) { if(!guessFormat(pageSize, false)) { this.pageWidth = (int) (pageSize.getWidth() * RtfElement.TWIPS_FACTOR); this.pageHeight = (int) (pageSize.getHeight() * RtfElement.TWIPS_FACTOR); this.landscape = pageWidth > pageHeight; ...
python
def rectangles_from_grid(P, black=1): """Largest area rectangle in a binary matrix :param P: matrix :param black: search for rectangles filled with value black :returns: area, left, top, right, bottom of optimal rectangle consisting of all (i,j) with left <= j < right and top ...
java
@SneakyThrows protected Http signHttpUserPreAuthRequest(final Http request) { request.signRequest( duoProperties.getDuoIntegrationKey(), duoProperties.getDuoSecretKey()); return request; }
java
public int compareTo(MutableDouble anotherMutableDouble) { double thisVal = this.d; double anotherVal = anotherMutableDouble.d; return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1)); }
python
def from_string(self, value): """Convert string to enum value.""" if not isinstance(value, basestring): raise ValueError('expected string value: ' + str(type(value))) self.test_value(value) return value
java
private void initExpressions() { expressions = new LinkedList<>(); for (UriTemplateComponent c : components) { if (c instanceof Expression) { expressions.add((Expression) c); } } }
python
def obtain_token(self, config=None): """Obtain the token to access to QX Platform. Raises: CredentialsError: when token is invalid or the user has not accepted the license. ApiError: when the response from the server couldn't be parsed. """ client...
java
public String buildStyleClassValue(List/*<String>*/ styleClasses) { if(styleClasses == null) return EMPTY; boolean styleWritten = false; InternalStringBuilder buf = new InternalStringBuilder(); for(int i = 0; i < styleClasses.size(); i++) { if(styleWritten) ...
java
private static long parseLong(String s) { try { return Long.parseLong(s); } catch (NumberFormatException nfe) { log.error("Unable to parse long value '" + s + "'", nfe); } return -1; }
java
private boolean readHeader() { boolean correct = true; ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; int c1 = 0; int c2 = 0; try { c1 = data.readByte().toInt(); c2 = data.readByte().toInt(); } catch (Exception ex) { validation.addErrorLoc("Header IO Exception", "Header"); ...
java
public void marshall(ListDeploymentGroupsRequest listDeploymentGroupsRequest, ProtocolMarshaller protocolMarshaller) { if (listDeploymentGroupsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
public String description() { Util.out4.println("DeviceImpl.description() arrived"); // // Record attribute request in black box // blackbox.insert_attr(Attr_Description); // // Return data to caller // Util.out4.println("Leaving DeviceImpl.description()"); return desc; }
java
public boolean isComplete() { return _group != null && _type != null && _kind != null && _name != null && _version != null; }
java
public static AOL getAOL(final MavenProject project, final String architecture, final String os, final Linker linker, final String aol, final Log log) throws MojoFailureException, MojoExecutionException { /* To support a linker that is not the default linker specified in the aol.properties * */ S...
python
def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a like-shaped array of per-row ranks. """ return masked_rankdata_2d( arrays[0], mask, self.inputs[0].missing_value, self._method, se...
python
def render_table(request, table, links=None, context=None, template='tri_table/list.html', blank_on_empty=False, paginate_by=40, # pragma: no mutate page=None, paginator=None, ...
python
def sub_base_uri(self): """ This will return the sub_base_uri parsed from the base_uri :return: str of the sub_base_uri """ return self.base_uri and self.base_uri.split('://')[-1].split('.')[ 0] or self.base_uri
python
def recover_db(self, src_file): """ " Recover DB from xxxxx.backup.json or xxxxx.json.factory to xxxxx.json " [src_file]: copy from src_file to xxxxx.json """ with self.db_mutex: try: shutil.copy2(src_file, self.json_db_path) except IOError...
java
@Nullable public Animator onDisappear(@NonNull final ViewGroup sceneRoot, @Nullable TransitionValues startValues, int startVisibility, @Nullable TransitionValues endValues, int endVisibili...