language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _add_user_to_file(file_id, service, user_email, perm_type='user', role='writer'): """ Grants the given set of permissions for a given file_id. service is an already-credentialed Google Drive service instance. """ new_permission = { 'value': user_email, 'type...
python
def addGlyph(self, glyphName, unicodes=None, instanceLocation=None, sources=None, note=None): """ Calculate a new glyph and add it to this instance. * glyphName: The name of the glyph * unicodes: The unicode values for this glyph (optional) * instanceLocation: ...
java
@Nullable public static XMLGregorianCalendar getXMLCalendarDate (@Nullable final LocalDate aBase) { if (aBase == null) return null; return s_aDTFactory.newXMLGregorianCalendarDate (aBase.getYear (), aBase.getMonth ().getValue (), ...
java
public void setScope(String scope) throws ApplicationException { scope = scope.toLowerCase().trim(); if (scope.equals("server")) this.scope = SCOPE_SERVER; else if (scope.equals("application")) this.scope = SCOPE_APPLICATION; else if (scope.equals("session")) this.scope = SCOPE_SESSION; else if (scope.equals("req...
python
def junos_copy_file(src, dst, **kwargs): ''' .. versionadded:: 2019.2.0 Copies the file on the remote Junos device. src The source file path. This argument accepts the usual Salt URIs (e.g., ``salt://``, ``http://``, ``https://``, ``s3://``, ``ftp://``, etc.). dst The dest...
python
def connect_mysql(): """ return an inspector object """ MySQLConnection.get_characterset_info = MySQLConnection.get_charset db = create_engine(engine_name) db.echo = True db.connect() return db
python
def parse_multiple_rpcs(cls, record_data): """Parse record_data into multiple error checking rpcs.""" rpcs = [] while len(record_data) > 0: total_length, record_type = struct.unpack_from("<LB3x", record_data) if record_type != SendErrorCheckingRPCRecord.RecordType: ...
java
public void checkpoint() { if (log.isDebugEnabled()) log.debug("Checkpoint was called, commit changes hold locks on tx " + this); try { checkOpen(); doWriteObjects(true); // do commit on PB if (hasBroker() && broker.isInTransaction()) b...
java
public static void saveAsFile(String data, String charset, String addr) throws IOException { charset = StringUtils.isEmpty(charset) ? "UTF8" : charset; saveAsFile(data.getBytes(charset), addr); }
java
@Override public String toNormalizedWildcardString() { String result; if(hasNoStringCache() || (result = stringCache.normalizedWildcardString) == null) { if(hasZone()) { stringCache.normalizedWildcardString = result = toNormalizedString(IPv6StringCache.wildcardNormalizedParams); } else { result = get...
python
def Run(self, force=False): """Do the actual work of the Cron. Will first check if DueToRun is True. CronJob object must be locked (i.e. opened via OpenWithLock) for Run() to be called. Args: force: If True, the job will run no matter what (i.e. even if DueToRun() returns False). ...
java
public List<FacesConfigApplicationResourceLibraryContractsType<FacesConfigApplicationType<T>>> getAllResourceLibraryContracts() { List<FacesConfigApplicationResourceLibraryContractsType<FacesConfigApplicationType<T>>> list = new ArrayList<FacesConfigApplicationResourceLibraryContractsType<FacesConfigApplicatio...
python
def answer_num(self): """获取问题答案数量. :return: 问题答案数量 :rtype: int """ answer_num_block = self.soup.find('h3', id='zh-question-answer-num') # 当0人回答或1回答时,都会找不到 answer_num_block, # 通过找答案的赞同数block来判断到底有没有答案。 # (感谢知乎用户 段晓晨 提出此问题) if answer_num_block is No...
java
public final List<MethodInfo> getMethods(String name) { List<MethodInfo> namedMethod = methods.get(name); if (null == namedMethod) return Collections.emptyList(); else return namedMethod; }
java
public static Resource child(@NotNull Resource parentResource, @NotNull String name, @NotNull String resourceType) { return child(parentResource, name, resourceType, ValueMap.EMPTY); }
java
private static void createShadowPolygons(Collection<Polygon> shadows, Coordinate[] coordinates, double[] shadow, GeometryFactory factory) { for (int i = 1; i < coordinates.length; i++) { Coordinate startCoord = coordinates[i - 1]; Coordinate endCoord = coordinates[i]; Coordin...
python
def generate_traffic_chain(self, pages, loops=1): """ Similar to generate_referral_chain(), but for multiple loops. """ for loop in range(loops): self.generate_referral_chain(pages) time.sleep(0.05)
python
def send(self, packet, retry=True): """send a packet down the line to the inteface""" addr = ('255.255.255.255', self.port) # 255. is the broadcast IP for UDP try: self.send_socket.sendto(packet, addr) except Exception as e: self.log("Link failed to send packet o...
java
public Matrix4 setToRotationScale (IMatrix3 rotScale) { return set(rotScale.m00(), rotScale.m01(), rotScale.m02(), 0f, rotScale.m10(), rotScale.m11(), rotScale.m12(), 0f, rotScale.m20(), rotScale.m21(), rotScale.m22(), 0f, 0, 0, 0, 1); }
java
private Symbol findDiamond(Env<AttrContext> env, Type site, List<Type> argtypes, List<Type> typeargtypes, boolean allowBoxing, boolean useVarargs) { Symbol bestSo...
java
@Override public EClass getPluginConfiguration() { if (pluginConfigurationEClass == null) { pluginConfigurationEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(11); } return pluginConfigurationEClass; }
java
@Override public int compareTo(Instant otherInstant) { int cmp = Jdk8Methods.compareLongs(seconds, otherInstant.seconds); if (cmp != 0) { return cmp; } return nanos - otherInstant.nanos; }
python
def trigger_event(name, event, value1=None, value2=None, value3=None ): ''' Trigger an event in IFTTT .. code-block:: yaml ifttt-event: ifttt.trigger_event: - event: TestEvent ...
python
def _delToC(self): """_delToC(self) -> PyObject *""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") val = _fitz.Document__delToC(self) self.initData() return val
java
public void initializeSendGrid(String apiKey) { this.apiKey = apiKey; this.host = "api.sendgrid.com"; this.version = "v3"; this.requestHeaders = new HashMap<String, String>(); this.requestHeaders.put("Authorization", "Bearer " + apiKey); this.requestHeaders.put("User-agent", USER_AGENT); thi...
java
protected CachingPojoPath getRecursive(String pojoPath, PojoPathContext context, PojoPathState state) { // try to read from cache... CachingPojoPath currentPath = state.getCachedPath(pojoPath); if (currentPath != null) { if (state.isGetType()) { // called from getType... if (currentPa...
java
@Override public synchronized void deleteAllUrlsForType(int type) throws DatabaseException { try { psDeleteAllUrlsForType.setInt(1, type); psDeleteAllUrlsForType.executeUpdate(); } catch (SQLException e) { throw new DatabaseException(e); } }
java
@Override public void sendMail(final String theTo, final String theFrom, final String theSubject, final String theBody) { if (log.isDebugEnabled()) { log.debug("Sending mail, TO: <" + theTo + ">, FROM: <" + theFrom + ...
java
Object asJSON() { final List<Object> json = new ArrayList<>(); for (Join join : joins) { json.add(join.asJSON()); } return json; }
java
public static TIntIntHashMap makeVMIndex(Collection<Instance> instances) { TIntIntHashMap index = new TIntIntHashMap(); int p = 0; for (Instance i : instances) { Mapping m = i.getModel().getMapping(); for (Node n : m.getOnlineNodes()) { for (VM v : m.getRu...
java
public static <T> T callInTransaction(final DatabaseConnection connection, boolean saved, final DatabaseType databaseType, final Callable<T> callable) throws SQLException { boolean restoreAutoCommit = false; TransactionLevel levelCount = transactionLevelThreadLocal.get(); try { boolean hasSavePoint = false...
java
public static Properties loadInheritedProperties (String path, ClassLoader loader) throws IOException { Properties props = new Properties(); loadInheritedProperties(path, loader, props); return props; }
java
public static String[] tokenize(String str, String delimiters) { return tokenize(str, delimiters, false); }
python
def head(self, *args, **kwargs): """ Executes an HTTP HEAD. :Parameters: - `args`: Non-keyword arguments - `kwargs`: Keyword arguments """ return self.session.head(*args, **self.get_kwargs(**kwargs))
python
def get_comments(self): """Gets all comments. return: (osid.commenting.CommentList) - a list of comments raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """...
python
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
java
public synchronized Repository getRepository() throws ResourceException { if (this.repository == null) { LOGGER.debug("Deploying repository URL [{0}]", repositoryURL); this.repository = deployRepository(repositoryURL); } return this.repository; }
java
public Vector getConnectedSocketDetails() { Vector details = new Vector(socketList.size()); for (Enumeration enumeration = socketList.elements(); enumeration.hasMoreElements(); ) { Socket socket = (Socket) enumeration.nextElement(); details.add( new SocketDetail(socket,...
python
def _save_sign(self, filepath): """Sign so that the new file may be retrieved without safe mode""" if self.code_array.safe_mode: msg = _("File saved but not signed because it is unapproved.") try: post_command_event(self.main_window, self.StatusBarMsg, ...
python
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: """Iterates a response JSON yielding data point by point. Can be used with both regular and chunked responses. By default, returns just a plain list of values representing each point, without column names, or other metadata...
java
public OperationFuture<Server> removePublicIp(Server serverRef, String ipAddress) { checkNotNull(ipAddress, "ipAddress must be not null"); Link response = client.removePublicIp(idByRef(serverRef), ipAddress); return new OperationFuture<>( serverRef, response.getId(), ...
java
public static com.liferay.commerce.product.model.CPMeasurementUnit createCPMeasurementUnit( long CPMeasurementUnitId) { return getService().createCPMeasurementUnit(CPMeasurementUnitId); }
java
private void defineDefaultBorders(UIDefaults d) { try { if (Boolean.FALSE.toString().equalsIgnoreCase(System.getProperty("SeaGlass.BorderFactory.overrideDefaults"))) { return; } // Etched Borders Field highLightColor = EtchedBorder.cl...
python
def score_meaning(text): """ Returns a score in [0,1] range if the text makes any sense in English. """ #all_characters = re.findall('[ -~]', text) # match 32-126 in ASCII table all_characters = re.findall('[a-zA-Z ]', text) # match 32-126 in ASCII table if len(all_characters) == 0: re...
java
public void writeLong(long pLong) throws IOException { out.write((int) pLong & 0xFF); out.write((int) (pLong >>> 8) & 0xFF); out.write((int) (pLong >>> 16) & 0xFF); out.write((int) (pLong >>> 24) & 0xFF); out.write((int) (pLong >>> 32) & 0xFF); out.write((int) (pLon...
python
def delete_one(self, *args, **kwargs): """ Run the pymongo delete_one command against the default database and collection and return the deleted IDs. """ result = self.collection.delete_one(*args, **kwargs) return result.raw_result
java
protected Parameter createSizeParameter(ParameterContext context) { ModelReference intModel = createModelRefFactory(context).apply(resolver.resolve(Integer.TYPE)); return new ParameterBuilder() .name(getSizeName()) .parameterType(SIZE_TYPE) .modelRef(intModel) ...
python
def match_regex(input_str, pattern, language, context, case_insensitive=True): """Take input string and a regex pattern, then yield generator of matches in desired format. TODO: Rename this `match_pattern` and incorporate the keyword expansion code currently in search_corpus. :param input_str:...
java
public String decrypt(final String pEncryptedText) throws GeneralSecurityException { byte[] allEncryptedBytes = Base64Util.decode(pEncryptedText); int totalLen = allEncryptedBytes.length; byte[] salt = new byte[SALT_SIZE]; System.arraycopy(allEncryptedBytes, 0, salt, 0, SALT_SIZE); ...
java
public PropertyDataReader forProperty(InternalQName name, int type) { if (nodePropertyReader == null) { nodePropertyReader = new PropertyDataReader(parent, dataManager); } return nodePropertyReader.forProperty(name, type); }
python
def plot_silhouette(clf, X, title='Silhouette Analysis', metric='euclidean', copy=True, ax=None, figsize=None, cmap='nipy_spectral', title_fontsize="large", text_fontsize="medium"): """Plots silhouette analysis of clusters using fit_predict. Args: clf: Clusterer ...
java
public String getCompressor(String type) { if (mCompressionMap == null) { return null; } return mCompressionMap.get(type).toString(); }
python
def services(self): """ Gets the services object which will provide the ArcGIS Server's admin information about services and folders. """ if self._resources is None: self.__init() if "services" in self._resources: url = self._url + "/services" ...
python
def download_file(self, owner, id, file, **kwargs): """ Download file This endpoint will return a file within the dataset as originally uploaded. If you are interested retrieving clean data extracted from those files by data.world, check out `GET:/sql` and `GET:/sparql`. This method ma...
java
public <T> ContextManager execute(Action<T> action, Handler<AsyncResult<T>> resultHandler) { vertx.executeBlocking(action, resultHandler); return this; }
python
def clear_sessions(hyperstream, inactive_only=True, clear_history=False): """ Clear all (inactive) sessions and (optionally) their history :param hyperstream: The hyperstream object :param inactive_only: Whether to only clear inactive sessions (active sessions may be owned by an...
python
def __wrap(self, func): '''This decorator overrides the default arguments of a function. For each keyword argument in the function, the decorator first checks if the argument has been overridden by the caller, and uses that value instead if so. If not, the decorator consults the Preset...
java
@Override public EClass getIfcFlowMovingDeviceType() { if (ifcFlowMovingDeviceTypeEClass == null) { ifcFlowMovingDeviceTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(285); } return ifcFlowMovingDeviceTypeEClass; }
java
public String getCidr() { if (cidr != null) { return cidr; } if (ipAddress != null) { if (mask != null) { return new SubnetUtils(ipAddress, mask).getCidrSignature(); } if (cidrMask != null) { return new SubnetUtils(i...
python
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by ...
java
public static String[] split(String pattern, CharSequence input) { input = new InterruptibleCharSequence(input); Matcher m = getMatcher(pattern,input); String[] retVal = m.pattern().split(input); recycleMatcher(m); return retVal; }
python
def initialize(self, init=initializer.Uniform(), ctx=None, verbose=False, force_reinit=False): """Initializes :py:class:`Parameter` s of this :py:class:`Block` and its children. Equivalent to ``block.collect_params().initialize(...)`` Parameters ---------- ini...
java
public com.cloudant.client.api.model.Response removeAttachment(Object object, String attachmentName) { Response couchDbResponse = db.removeAttachment(object, attachmentName); com.cloudant.client.api.model.Response response = new com.cloudant.client.api.model .Response(couchDbResponse); ...
java
public String getLanguage() { return this.attrValues.get(Person.AttrName.LANGUAGE) != null ? this.attrValues.get(Person.AttrName.LANGUAGE) : Locale.ENGLISH.getISO3Language(); }
java
@Override public ModuleBuild build(String mid, IResource resource, HttpServletRequest request, List<ICacheKeyGenerator> inKeyGens) throws Exception { // Manage life span of thread locals used by this module builder if (isFeatureDependent) { threadLocalRequest.set(request); threadLocalDependentFeatures...
java
public static <T extends Enum> @Nullable T getEnum(@NotNull ServletRequest request, @NotNull String param, @NotNull Class<T> enumClass) { return getEnum(request, param, enumClass, null); }
java
public Observable<FluentModelTImpl> commitAsync() { if (this.isPostRunMode) { return Observable.error(new IllegalStateException("commitAsync() cannot be invoked when 'post run' mode is enabled")); } final ExternalChildResourceCollectionImpl<FluentModelTImpl, FluentModelT, InnerModel...
java
String resetSubject(long sessionId) { if (prefix == null) { return String.format("reset-%d", sessionId); } else { return String.format("%s-reset-%d", prefix, sessionId); } }
java
boolean consistentChoice(int varIndex) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "consistentChoice", new Object[]{Integer.valueOf(varIndex)}); JSType field = findDominatingCase(variants[varIndex]); JSVariant parent = (JSVariant) field.getParent(); if (par...
python
def get_searches(quick, saved): '''List searches''' cl = clientv1() echo_json_response(call_and_wrap(cl.get_searches, quick, saved), True)
java
public RuntimeException traceError( RuntimeException cause ) { getLogger().log( Level.SEVERE, "Error during deserialization", cause ); if ( wrapExceptions ) { return new JsonDeserializationException( cause ); } else { return cause; } }
java
@Override @Deprecated public DescribeConnectionsOnInterconnectResult describeConnectionsOnInterconnect(DescribeConnectionsOnInterconnectRequest request) { request = beforeClientExecution(request); return executeDescribeConnectionsOnInterconnect(request); }
java
@Override public void hardmsg(String key, Object... args) { hard(messageFormat(key, args)); }
java
private static String encode(byte[] bytes) { try { if (System.getProperty("java.version").startsWith("1.")) { // return DatatypeConverter.printBase64Binary(str); Class<?> DatatypeConverter = Class.forName("javax.xml.bind.DatatypeConverter"); return (St...
python
def debug_sync(self, conn_id, cmd_name, cmd_args, progress_callback): """Asynchronously complete a named debug command. The command name and arguments are passed to the underlying device adapter and interpreted there. If the command is long running, progress_callback may be used to pro...
java
public static RectangleLength2D_F32 boundBox_F32( int srcWidth , int srcHeight , PixelTransform<Point2D_F32> transform , Point2D_F32 transformed ) { ImageRectangle_F32 r=new ImageRectangle_F32(); r.x0=r.y0=Float.MAX_VALUE; r.x1=r.y1=-Float.MAX_VALUE; for( int y = 0; y < srcHeigh...
python
def disassociate_public_ip(self, public_ip_id): """Disassociate a external IP""" floating_ip = self.client.floating_ips.get(public_ip_id) floating_ip = floating_ip.to_dict() instance_id = floating_ip.get('instance_id') address = floating_ip.get('ip') self.client.servers....
python
def _start_event_client(self): """Overrides superclass.""" event_client = SnippetClient(package=self.package, ad=self._ad) event_client.host_port = self.host_port event_client.device_port = self.device_port event_client.connect(self.uid, jsonrpc_clien...
java
public static SecretKey hmacShaKeyFor(byte[] bytes) throws WeakKeyException { if (bytes == null) { throw new InvalidKeyException("SecretKey byte array cannot be null."); } int bitLength = bytes.length * 8; for (SignatureAlgorithm alg : PREFERRED_HMAC_ALGS) { if...
java
@SuppressWarnings("unchecked") public static Map<String, String> getLabels(ObjectMeta metadata) { if (metadata != null) { Map<String, String> labels = metadata.getLabels(); if (labels != null) { return labels; } } return Collections.EMPTY_MAP; }
java
public void marshall(DesiredWeightAndCapacity desiredWeightAndCapacity, ProtocolMarshaller protocolMarshaller) { if (desiredWeightAndCapacity == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(desired...
python
def post_from_style(self, column_style): """Yield post-format processors based on `column_style`. Parameters ---------- column_style : dict A style where the top-level keys correspond to style attributes such as "bold" or "color". Returns -------...
python
def aliased_slot_name(self, slot: SLOT_OR_SLOTNAME) -> str: """ Return the overloaded slot name -- the alias if one exists otherwise the actual name @param slot: either a slot name or a definition @return: overloaded name """ if isinstance(slot, str): slot = self.sch...
java
@Override public DescribeDestinationsResult describeDestinations(DescribeDestinationsRequest request) { request = beforeClientExecution(request); return executeDescribeDestinations(request); }
python
def command_publish(self, command, **kwargs): """ Publish a MQTT message """ mqttc = mqtt.Client() mqttc.connect( command['host'], port=int(command['port'])) mqttc.loop_start() try: mqttc.publish( command['endpoint'], ...
java
static public void writeStringAsCharArray(Writer writer, String str) throws IOException { writeStringAsCharArray(writer, str, 0, str.length()); }
java
@Override public Map<String, Object> updateConfig(Map<String, Object> properties) throws ParsingException { if (logger.isInfoEnabled()) { boolean printKeys = logger.isDebugEnabled(); Set<String> configHiddenKeys = getHiddenKeys(); StringBuilder builder = new StringBuilder...
java
@XmlElement(name="attribute") public void setAttributeInfos(final List<AttributeInfo> attributeInfos) { if(attributeInfos == this.attributes) { // Java7の場合、getterで取得したインスタンスをそのまま設定するため、スキップする。 return; } this.attributes.clear(); for(AttributeIn...
java
public float getFloat(@NotNull final String key, float defaultValue) { float retValue = defaultValue; try { retValue = Float.parseFloat(getString(key)); } catch (Throwable ignore) { LOGGER.trace("ignore", ignore); } return retValue; }
java
public void trigger(DelegateExecution execution, String signalName, Object signalData) { if (activityBehaviorInstance == null) { activityBehaviorInstance = getActivityBehaviorInstance(); } if (activityBehaviorInstance instanceof TriggerableActivityBehavior) { ((TriggerableActivityBehavior) acti...
java
@Override public AggregateCounter getCounts(String name, Interval interval, AggregateCounterResolution resolution) { DateTime end = interval.getEnd(); Chronology c = interval.getChronology(); long[] counts; if (resolution == AggregateCounterResolution.minute) { // Iterate through each hour in the interva...
java
public void marshall(ModelPackageValidationSpecification modelPackageValidationSpecification, ProtocolMarshaller protocolMarshaller) { if (modelPackageValidationSpecification == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { pr...
java
protected void setRegion(float cx, float cy) { x0 = cx - radius; y0 = cy - radius; if( x0 < 0 ) { x0 = 0;} else if( x0+width > image.width ) { x0 = image.width-width; } if( y0 < 0 ) { y0 = 0;} else if( y0+width > image.height ) { y0 = image.height-width; } }
java
<T> void bindWith(final PeasyRecyclerView<T> binder, final int viewType) { this.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getLayoutPosition(); position = (position <= binder.getLastItemI...
python
def remove_listener(self, registration_id): """ Removes a lifecycle listener. :param registration_id: (str), the id of the listener to be removed. :return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise. """ try: self._listeners...
java
@Nonnull public static CpuInfo x86(@Nonnull CpuInfoX86 x86) { CpuInfo self = new CpuInfo(); self.arch = CpuInfoArch.x86; self.x86 = x86; return self; }
python
def initialize_notebook(): """Initialize the IPython notebook display elements""" try: from IPython.core.display import display, HTML except ImportError: print("IPython Notebook could not be loaded.") lib_js = ENV.get_template('ipynb_init_js.html') lib_css = ENV.get_template('ipynb_...
python
def log_likelihood(self): r""" Returns the value of the log-likelihood of the converged TRAM estimate. """ # TODO: check that we are estimated... return _tram.log_likelihood_lower_bound( self.log_lagrangian_mult, self.biased_conf_energies, self.count_matri...
java
public static String getHashedKey(String key, String hashingAlgorithm) { final long start = System.nanoTime(); HashFunction hf = null; switch(hashingAlgorithm.toLowerCase()) { case "murmur3" : hf = Hashing.murmur3_128(); break; case "...
python
def get_access_token(username=None, password=None, client_id=None, client_secret=None, app_url=defaults.APP_URL): """ get the access token (http://docs.jut.io/api-guide/#unique_171637733), by either using the direct username...