language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def main(): """Run the program.""" args = parse_arguments() ext = os.path.splitext(args.input_file)[-1].lower() with gzip.open(args.output_file, mode='wt') as outfile: csvwriter = csv.writer(outfile, delimiter=str('\t'), lineterminator='\n') try: if ext in ('.tab', '.txt', ...
java
public void marshall(UntagResourceRequest untagResourceRequest, ProtocolMarshaller protocolMarshaller) { if (untagResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(untagResourceReques...
python
def binary(self): """ return encoded representation """ creation_size = len(self.creation) if creation_size == 1: return ( b_chr(_TAG_PID_EXT) + self.node.binary() + self.id + self.serial + self.creation ) elif creat...
python
def load_from_rho_file(self, filename): """Convenience function that loads two parameter sets from a rho.dat file, as used by CRMod for forward resistivity/phase models. Parameters ---------- filename: string, file path filename of rho.dat file Returns ...
java
private Set<String> getConstraintNameList(){ Set<String> result = new HashSet<>(); String propertyValue = getProperty(ConstraintContextProperty.ALL_CONSTRAINTS); if(propertyValue == null) return result; StringTokenizer attributeTokens = StringUtils.splitArrayString(propertyValue, String.valueOf(ArrayUtils.VA...
java
private <T> T assertReqProp(String key,T val) { if(val == null){ throw new RuntimeException("The property [" + key + "] is not present "); } return val; }
java
public boolean mergeIn(final BatchPoints that) { boolean mergeAble = isMergeAbleWith(that); if (mergeAble) { this.points.addAll(that.points); } return mergeAble; }
java
public final void addFolder(@NotNull final Folder folder) { Contract.requireArgNotNull("folder", folder); if (folders == null) { folders = new ArrayList<>(); } folders.add(folder); }
python
def kuhn_munkres(G): # maximum profit bipartite matching in O(n^4) """Maximum profit perfect matching for minimum cost perfect matching just inverse the weights :param G: squared weight matrix of a complete bipartite graph :complexity: :math:`O(n^4)` """ assert len(G) == len(G[0]) n =...
java
public void setXmlContentAutoCorrect(String xmlContentAutoCorrect) { m_xmlContentAutoCorrect = Boolean.valueOf(xmlContentAutoCorrect).booleanValue(); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( m_xmlContentAutoCorr...
java
public static Geometry drapeLineString(LineString line, Geometry triangles, STRtree sTRtree) { GeometryFactory factory = line.getFactory(); //Split the triangles in lines to perform all intersections Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true); Geometry...
python
def treeReduce(self, f, depth=2): """ Reduces the elements of this RDD in a multi-level tree pattern. :param depth: suggested depth of the tree (default: 2) >>> add = lambda x, y: x + y >>> rdd = sc.parallelize([-5, -4, -3, -2, -1, 1, 2, 3, 4], 10) >>> rdd.treeReduce(ad...
python
def _next_sample_index(self): """ShuffledMux chooses its next sample stream randomly, conditioned on the stream weights. """ return self.rng.choice(self.n_streams, p=(self.stream_weights_ / self.weight_norm_))
java
@Override @Path("{package}/{asset}") public JSONObject get(String assetPath, Map<String,String> headers) throws ServiceException, JSONException { AssetServices assetServices = ServiceLocator.getAssetServices(); AssetInfo asset = assetServices.getAsset(assetPath.substring(7), true); ...
python
def isAuxilied(self): """ Returns if the object is separating and applying to a benefic considering good aspects. """ benefics = [const.VENUS, const.JUPITER] return self.__sepApp(benefics, aspList=[0, 60, 120])
java
public List<DataNode> dataNodes() { List<DataNode> dataNodes = new ArrayList<>(); for (Node node : childNodes) { if (node instanceof DataNode) dataNodes.add((DataNode) node); } return Collections.unmodifiableList(dataNodes); }
java
public Object parseAsPropertyType(String stringToParse, String propertyPath) { Class propertyType = getPropertyType(propertyPath); if (propertyType == null) { return null; } NumberTransformer parser = transformers.get(propertyType); return parser == null ? stringToPa...
python
def static_urls_js(): """ Add global variables to JavaScript about the location and latest version of transpiled files. Usage:: {% static_urls_js %} """ if apps.is_installed('django.contrib.staticfiles'): from django.contrib.staticfiles.storage import staticfiles_storage ...
java
private void createNodeMappings(MtasTokenIdFactory mtasTokenIdFactory, Level level, Level parentLevel) { MtasToken nodeToken; if (level.node != null && level.positionStart != null && level.positionEnd != null) { nodeToken = new MtasTokenString(mtasTokenIdFactory.createTokenId(), le...
java
public Map<String, String> getPrintableHeaders() { final Map<String, String> headers = new HashMap<String, String>( request.headers().entries().size()); for (final Entry<String, String> header : request.headers().entries()) { if (header.getKey().toLowerCase().equals("cookie")) { // null ou...
java
public static double[] unbox(final Double[] a, final double valueForNull) { if (a == null) { return null; } return unbox(a, 0, a.length, valueForNull); }
java
@Override public Enumerable<T> enumerate(SET source) throws E, MappingException { return getMapperFromSet(source).enumerate(source); }
java
@Override public WebSphereEjbServices getWebSphereEjbServices(String applicationID) { WebSphereEjbServices services = null; synchronized (ejbServices) { services = ejbServices.get(applicationID); if (services == null) { services = new WebSphereEjbServicesImpl...
java
private Object handleTxCommand(TxInvocationContext ctx, TransactionBoundaryCommand command) { if (trace) log.tracef("handleTxCommand for command %s, origin %s", command, getOrigin(ctx)); updateTopologyId(command); return invokeNextAndHandle(ctx, command, handleTxReturn); }
java
public ServiceFuture<OperationStatus> deletePatternAsync(UUID appId, String versionId, UUID patternId, final ServiceCallback<OperationStatus> serviceCallback) { return ServiceFuture.fromResponse(deletePatternWithServiceResponseAsync(appId, versionId, patternId), serviceCallback); }
python
def defaultcolour(self, colour): """ Auxiliary method to choose a default colour. Give me a user provided colour : if it is None, I change it to the default colour, respecting negative. Plus, if the image is in RGB mode and you give me 128 for a gray, I translate this to the expected (12...
java
static boolean isGeneralError(Symbol amqpError) { return (amqpError == ClientConstants.SERVER_BUSY_ERROR || amqpError == ClientConstants.TIMEOUT_ERROR || amqpError == AmqpErrorCode.ResourceLimitExceeded); }
java
public Waiter<DescribeInstancesRequest> instanceExists() { return new WaiterBuilder<DescribeInstancesRequest, DescribeInstancesResult>().withSdkFunction(new DescribeInstancesFunction(client)) .withAcceptors(new InstanceExists.IsTrueMatcher(), new InstanceExists.IsInvalidInstanceIDNotFoundMatche...
java
@Override public FileStatus[] globStatus(Path pathPattern, PathFilter filter) throws IOException { checkOpen(); logger.atFine().log("GHFS.globStatus: %s", pathPattern); // URI does not handle glob expressions nicely, for the purpose of // fully-qualifying a path we can URI-encode them. // Using t...
python
def is_bot_the_only_committer(self, pr): """ Checks if the bot is the only committer for the given pull request. :param update: Update to check :return: bool - True if conflict found """ committer = self.provider.get_pull_request_committer( self.user_repo, ...
java
public BaseField getField(String strTableName, int iFieldSeq) // Lookup this field { if (this.getRecord(strTableName) != this) return null; return this.getField(iFieldSeq); }
java
public Query groupby(final Expression... groupbyColumns) { if (groupbyColumns == null) { return this; } return groupby(Arrays.asList(groupbyColumns)); }
java
public static boolean isStructuredType(Type type) { MetaType metaType = type.getMetaType(); return metaType == MetaType.ENTITY || metaType == MetaType.COMPLEX; }
java
static public BagObject url (String urlString, Bag postData, String postDataMimeType) { return url (urlString, postData, postDataMimeType, () -> null); }
python
def _ensure_opened(self): """Start monitors, or restart after a fork. Hold the lock when calling this. """ if not self._opened: self._opened = True self._update_servers() # Start or restart the events publishing thread. if self._publish_t...
python
def getControllerAxisTypeNameFromEnum(self, eAxisType): """returns the name of an EVRControllerAxisType enum value. This function is deprecated in favor of the new IVRInput system.""" fn = self.function_table.getControllerAxisTypeNameFromEnum result = fn(eAxisType) return result
java
final Table SYSTEM_CROSSREFERENCE() { Table t = sysTables[SYSTEM_CROSSREFERENCE]; if (t == null) { t = createBlankTable(sysTableHsqlNames[SYSTEM_CROSSREFERENCE]); addColumn(t, "PKTABLE_CAT", SQL_IDENTIFIER); addColumn(t, "PKTABLE_SCHEM", SQL_IDENTIFIER); ...
python
def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. """ # pylint: disable=g-import-not-at-top from google.protobuf impor...
java
static void closeAllStreams(Iterable<EditLogInputStream> streams) { for (EditLogInputStream s : streams) { IOUtils.closeStream(s); } }
java
public EndpointBuilder<T> export(Class<?>... additional) { this.additionalInterfaces.addAll(Arrays.asList(additional)); return this; }
java
private void clientFinished(Finished mesg) throws IOException { if (debug != null && Debug.isOn("handshake")) { mesg.print(System.out); } /* * Verify if client did send the certificate when client * authentication was required, otherwise server should not proceed ...
java
public static Object convert(Object typeKey, Object value) { if (value==null) { return null; } if (typeKey==null) { return value; } Conversion<?> conversion=getTypeConversion(typeKey,value); // Convert the value if (conversion!=null) { if (value instanceof Listener) { ((Listener)value).be...
python
def set_hosts(sld, tld, hosts): ''' Sets DNS host records settings for the requested domain. returns True if the host records were set successfully sld SLD of the domain name tld TLD of the domain name hosts Must be passed as a list of Python dictionaries, with each d...
java
public static IPv6Address fromString(final String string) { if (string == null) throw new IllegalArgumentException("can not parse [null]"); final String withoutIPv4MappedNotation = IPv6AddressHelpers.rewriteIPv4MappedNotation(string); final String longNotation = IPv6AddressHelpe...
java
public static void writeSecurityBuffer(short length, short allocated, int bufferOffset, byte[] b, int offset) { ByteUtilities.writeShort(length, b, offset); ByteUtilities.writeShort(allocated, b, offset + 2); ByteUtilities.writeInt(bufferOffset, b, offset + 4); }
python
def unicode_escape_sequence_fix(self, value): """ It is possible to define unicode characters in the config either as the actual utf-8 character or using escape sequences the following all will show the Greek delta character. Δ \N{GREEK CAPITAL LETTER DELTA} \U00000394 \u0394 ...
java
@Override public void removeByGroupId(long groupId) { for (CPSpecificationOption cpSpecificationOption : findByGroupId( groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(cpSpecificationOption); } }
python
def read(self, num): """Read ``num`` number of bytes from the stream. Note that this will automatically resets/ends the current bit-reading if it does not end on an even byte AND ``self.padded`` is True. If ``self.padded`` is True, then the entire stream is treated as a bitstream. ...
python
def readTicks(self, start, end): ''' read ticks ''' rows = self.__hbase.scanTable(self.tableName(HBaseDAM.TICK), [HBaseDAM.TICK], start, end) return [self.__rowResultToTick(row) for row in rows]
python
def _check_operators(self, operators): """ Check Inputs This method cheks that the input operators and weights are correctly formatted Parameters ---------- operators : list, tuple or np.ndarray List of linear operator class instances Returns ...
python
def ast_str(self, indent=0): """Return a minimal string to print a tree-like structure. Kwargs: indent (int): The number of indentation levels. """ line = self.line or 0 col = self.column or 0 name = type(self).__name__ spell = getattr(self, 'name', '...
java
public boolean isSessionToken(String site, String token) { // Add a default port if (!site.contains(":")) { site = site + (":80"); } HttpSessionTokensSet siteTokens = sessionTokens.get(site); if (siteTokens == null) return false; return siteTokens.isSessionToken(token); }
java
public final int strLengthNull(byte[]bytes, int p, int end) { int n = 0; while (true) { if (bytes[p] == 0) { int len = minLength(); if (len == 1) return n; int q = p + 1; while (len > 1) { if (bytes[q] != ...
python
def _wrap_function_return(val): """ Recursively walks each thing in val, opening lists and dictionaries, converting all occurrences of UnityGraphProxy to an SGraph, UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray. """ if type(val) is _UnityGraphProxy: return _SGraph(_proxy = ...
java
@Override public boolean deleteKAMStoreSchema(DBConnection dbc, String schemaName) throws IOException { boolean deleteSchemas = getSchemaManagementStatus(dbc); if (deleteSchemas) { runScripts(dbc, "/" + dbc.getType() + DELETE_KAM_SQL_PATH, schemaName, dele...
java
@SuppressWarnings("deprecation") public static RTPBridge getRTPBridge(XMPPConnection connection, String sessionID) throws NotConnectedException, InterruptedException { if (!connection.isConnected()) { return null; } RTPBridge rtpPacket = new RTPBridge(sessionID); rtpPac...
python
def _connectToAPI(self): """ :return: A tweepy.API object that performs the queries """ #authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret) auth.set_access_token(self.access_key, self.access_secret) api = t...
java
public static cacheselector[] get(nitro_service service, options option) throws Exception{ cacheselector obj = new cacheselector(); cacheselector[] response = (cacheselector[])obj.get_resources(service,option); return response; }
java
public boolean getBooleanOrDefault(int key, boolean dfl) { Any3<Boolean, Integer, String> value = data.getOrDefault(Any2.<Integer, String>left(key), Any3.<Boolean, Integer, String>create1(dfl)); return value.get1().orElseThrow(() -> new IllegalArgumentException("expected boolean argument for param " + k...
python
def return_opml_response(self, context, **response_kwargs): ''' Returns export data as an opml file. ''' self.template_name = 'fiction_outlines/outline.opml' response = super().render_to_response(context, content_type='text/xml', **response_kwargs) response['Content-Dispo...
python
def _initiate_replset(self, port, name, maxwait=30): """Initiate replica set.""" if not self.args['replicaset'] and name != 'configRepl': if self.args['verbose']: print('Skipping replica set initialization for %s' % name) return con = self.client('localho...
python
def is_false(self): """ Ensures :attr:`subject` is ``False``. """ self._run(unittest_case.assertFalse, (self._subject,)) return ChainInspector(self._subject)
python
def pre_init(): """ The pre_init function of the plugin. Here rafcon-classes can be extended/monkey-patched or completely substituted. A example is given with the rafcon_execution_hooks_plugin. :return: """ logger.info("Run pre-initiation hook of {} plugin.".format(__file__.split(os.path.sep)[-...
java
public Matrix4f rotationX(float ang) { float sin, cos; sin = (float) Math.sin(ang); cos = (float) Math.cosFromSin(sin, ang); if ((properties & PROPERTY_IDENTITY) == 0) MemUtil.INSTANCE.identity(this); this._m11(cos); this._m12(sin); this._m21(-sin); ...
java
void addCredit(InputChannelID receiverId, int credit) throws Exception { if (fatalError) { return; } NetworkSequenceViewReader reader = allReaders.get(receiverId); if (reader != null) { reader.addCredit(credit); enqueueAvailableReader(reader); } else { throw new IllegalStateException("No reader ...
java
private static void blur(int[] srcPixels, int[] dstPixels, int width, int height, float[] kernel, int radius) { float a; float r; float g; float b; int ca; int cr; int cg; int cb; for (int y = 0; y < height; y++) { int index = y; ...
python
def _M2_sparse(Xvar, mask_X, Yvar, mask_Y, weights=None): """ 2nd moment matrix exploiting zero input columns """ C = np.zeros((len(mask_X), len(mask_Y))) C[np.ix_(mask_X, mask_Y)] = _M2_dense(Xvar, Yvar, weights=weights) return C
java
@SuppressWarnings("unchecked") @Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.localDate()) { return (R) this; } return super.query(query); }
java
public static ScopeFormats fromConfig(Configuration config) { String jmFormat = config.getString(MetricOptions.SCOPE_NAMING_JM); String jmJobFormat = config.getString(MetricOptions.SCOPE_NAMING_JM_JOB); String tmFormat = config.getString(MetricOptions.SCOPE_NAMING_TM); String tmJobFormat = config.getString(Metr...
java
@Override public ResourceSet<Webhook> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
java
public void getRaidInfo(String[] ids, Callback<List<Raid>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ids)); gw2API.getRaidInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback); }
java
private String makeAlias(String prefix) { int i = 0; String result; do { if (i == 0) { result = prefix; } else { result = prefix + i; } } while (m_usedAliases.contains(result)); m_usedAliases.add(result); ...
java
public void deleteWorkflow(String workflowId, boolean archiveWorkflow) { Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "Workflow id cannot be blank"); stub.removeWorkflow( WorkflowServicePb.RemoveWorkflowRequest.newBuilder() .setWorkflodId(workfl...
java
public java.util.List<java.util.Map<String, AttributeValue>> getItems() { return items; }
python
async def discover_nupnp(websession): """Discover bridges via NUPNP.""" async with websession.get(URL_NUPNP) as res: return [Bridge(item['internalipaddress'], websession=websession) for item in (await res.json())]
java
public static LinkedList<String> readLineListWithLessMemory(String path) { LinkedList<String> result = new LinkedList<String>(); String line = null; boolean first = true; try { BufferedReader bw = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path...
python
def _using_stdout(self): """ Return whether the handler is using sys.stdout. """ if WINDOWS and colorama: # Then self.stream is an AnsiToWin32 object. return self.stream.wrapped is sys.stdout return self.stream is sys.stdout
python
def get_group_names(self): """ Returns the set of Django group names that this user belongs to by virtue of LDAP group memberships. """ if self._group_names is None: self._load_cached_attr("_group_names") if self._group_names is None: group_infos ...
java
public Converter<NetworkResponse, ?> getResponseConverter(Type type, Annotation[] annotations) { checkNotNull(type, "type == null"); checkNotNull(annotations, "annotations == null"); for (int i = 0, count = converterFactories.size(); i < count; i++) { Converter<NetworkResponse, ?> c...
java
@UiThread @SafeVarargs public static <T extends View> void run(@NonNull T view, @NonNull Action<? super T>... actions) { for (Action<? super T> action : actions) { action.apply(view, 0); } }
python
def get_dependants(cls, dist): """Yield dependant user packages for a given package name.""" for package in cls.installed_distributions: for requirement_package in package.requires(): requirement_name = requirement_package.project_name # perform case-insensiti...
java
public static void v(Throwable t, String tag, String message, Object... args) { sLogger.v(t, tag, message, args); }
python
def save(filepath, *args, encoding=None, **kwargs): """Same as `get_tikz_code()`, but actually saves the code to a file. :param filepath: The file to which the TikZ output will be written. :type filepath: str :param encoding: Sets the text encoding of the output file, e.g. 'utf-8'. ...
java
@Override public int read(char[] cbuf, int start, int len) throws IOException { // Let's first ensure there's enough room... if (start < 0 || (start+len) > cbuf.length) { reportBounds(cbuf, start, len); } // Already EOF? if (mByteBuffer == null) { ...
java
protected boolean isSupportRefreshToken(OAuth2Request clientAuth) { if (clientDetailsService != null) { ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); return client.getAuthorizedGrantTypes().contains("refresh_token"); } return this.supportRefreshToken; }
java
public void printDot(PrintStream os, int maxLevelsToPrintPerEdge, boolean detail, String optionalTitle, PrintMojo.PrintTreeOptions treeOptions) { os.println("/*"); os.println("Generated by:"); os.println(" http://https://github.com/h2oai/h2o-3/tree/master/h2o-genmodel/src/main/java/hex/genmodel/tools/Pri...
python
def prepare_sorting_fields(self): """ Determine sorting direction and sorting field based on request query parameters and sorting options of self """ if self.sorting_parameter_name in self.request.query_params: # Extract sorting parameter from query string ...
java
public void compileAndRun() throws Exception { synchronized (this.monitor) { try { stop(); Class<?>[] compiledSources = compile(); monitorForChanges(); // Run in new thread to ensure that the context classloader is setup this.runThread = new RunThread(compiledSources); this.runThread.start(...
python
def signup_or_login_with_mobile_phone(cls, phone_number, sms_code): ''' param phone_nubmer: string_types param sms_code: string_types 在调用此方法前请先使用 request_sms_code 请求 sms code ''' data = { 'mobilePhoneNumber': phone_number, 'smsCode': sms_code ...
java
public <T> long bulkGraphOperation(final SecurityContext securityContext, final Iterator<T> iterator, final long commitCount, String description, final BulkGraphOperation<T> operation, boolean validation) { final Predicate<Long> condition = operation.getCondition(); final App app = StructrApp.get...
python
def is_readable(path=None): """ Test if the supplied filesystem path can be read :param path: A filesystem path :return: True if the path is a file that can be read. Otherwise, False """ if os.path.isfile(path) and os.access(path, os.R_OK): return True return False
java
private void fetch() throws Exception { for (; nextFetchIndex < objects.size() && fetchedBytes.get() <= prefetchConfig.getMaxFetchCapacityBytes(); nextFetchIndex++) { final T object = objects.get(nextFetchIndex); LOG.info("Fetching [%d]th object[%s], fetchedBytes[%d]", nextFetchIndex, objec...
java
@Override public void writeSilenceForced(long tick) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "writeSilenceForced", Long.valueOf(tick)); TickRange tr = null; synchronized (oststream) //see defect 289889 { ost...
java
public ClockSkewAdjustment getAdjustment(AdjustmentRequest adjustmentRequest) { ValidationUtils.assertNotNull(adjustmentRequest, "adjustmentRequest"); ValidationUtils.assertNotNull(adjustmentRequest.exception, "adjustmentRequest.exception"); ValidationUtils.assertNotNull(adjustmentRequest.client...
java
public static <T> Typed<T> wrap(final Type type) { return new Typed<T>() { @Override public Type getType() { return type; } }; }
python
def file_contents_safe(self, sentry_unit, file_name, max_wait=60, fatal=False): """Get file contents from a sentry unit. Wrap amulet file_contents with retry logic to address races where a file checks as existing, but no longer exists by the time file_contents is call...
java
@Override public void open() throws InfoStoreException { String methodName = "open"; try { getClassSource().open(); } catch (ClassSource_Exception e) { // defect 84235:we are generating multiple Warning/Error messages for each error due to each level reporting them. ...
python
def from_yaml(): """ Load configuration from yaml source(s), cached to only run once """ default_yaml_str = snippets.get_snippet_content('hatchery.yml') ret = yaml.load(default_yaml_str, Loader=yaml.RoundTripLoader) for config_path in CONFIG_LOCATIONS: config_path = os.path.expanduser(config_pat...
python
def cp_file(): """ dumps databases into /backups, uploads to s3, deletes backups older than a month fab -f ./fabfile.py backup_dbs """ args = parser.parse_args() copy_file(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name, args.file, args.s3_folder)
python
def plotMDS(data, theOrders, theLabels, theColors, theAlphas, theSizes, theMarkers, options): """Plot the MDS data. :param data: the data to plot (MDS values). :param theOrders: the order of the populations to plot. :param theLabels: the names of the populations to plot. :param theColor...