language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected <T> T eval(Object value, T defaultValue) { return getExpressionUtil().eval(value, defaultValue); }
python
def already_downloaded(track, title, filename): """ Returns True if the file has already been downloaded """ global arguments already_downloaded = False if os.path.isfile(filename): already_downloaded = True if arguments['--flac'] and can_convert(filename) \ ...
python
def sanitize(self): ''' Check if the current settings conform to the LISP specifications and fix where possible. ''' # WARNING: http://tools.ietf.org/html/draft-ietf-lisp-ddt-00 # does not define this field so the description is taken from # http://tools.ietf.org/...
python
def query_dated(num=10, kind='1'): ''' List the wiki of dated. ''' return TabWiki.select().where( TabWiki.kind == kind ).order_by( TabWiki.time_update.desc() ).limit(num)
java
@Override public Map<String, String[]> getParameterMap() { if (this.charset.equalsIgnoreCase(this.originCharset)) { return super.getParameterMap(); } Map<String, String[]> v = super.getParameterMap(); if (v.isEmpty()) { return v; } Map<String, ...
python
def remove(self, value, _sa_initiator=None): """Remove an item by value, consulting the keyfunc for the key.""" key = self.keyfunc(value) # Let self[key] raise if key is not in this collection # testlib.pragma exempt:__ne__ if not self.__contains__(key) or value not in self[key]...
java
public void addResponseCommitListener(final ResponseCommitListener listener) { //technically it is possible to modify the exchange after the response conduit has been created //as the response channel should not be retrieved until it is about to be written to //if we get complaints about this w...
python
def process(self, sched, coro): """Add the calling coro in a waiting for signal queue.""" super(WaitForSignal, self).process(sched, coro) waitlist = sched.sigwait[self.name] waitlist.append((self, coro)) if self.name in sched.signals: sig = sched.signals[self.na...
java
public static Component getDescendantNamed(String name, Component parent) { Assert.notNull(name, "name"); Assert.notNull(parent, "parent"); if (name.equals(parent.getName())) { // Base case return parent; } else if (parent instanceof Container) { // Recursive case ...
java
public void marshall(StopAutomationExecutionRequest stopAutomationExecutionRequest, ProtocolMarshaller protocolMarshaller) { if (stopAutomationExecutionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
java
Key getSigningKey(JwtConsumerConfig config, JwtContext jwtContext, Map properties) throws KeyException { Key signingKey = null; if (config == null) { if (tc.isDebugEnabled()) { Tr.debug(tc, "JWT consumer config object is null"); } return null; } signingKey = getSigningKeyBasedOnSignatureAlgorithm(c...
java
private void recacheChildren() throws CacheReloadException { if (isDirty()) { Type.cacheType(this); } for (final Type child : getChildTypes()) { child.recacheChildren(); } }
java
public static boolean areEquals(final String s1, final String s2) { return s1 == null ? s2 == null : s1.equals(s2); }
python
def new_stats_exporter(options=None, interval=None): """Get a stats exporter and running transport thread. Create a new `StackdriverStatsExporter` with the given options and start periodically exporting stats to stackdriver in the background. Fall back to default auth if `options` is null. This will r...
java
void handle(OngoingRequest ongoingRequest, RequestContext requestContext, Endpoint endpoint) { try { endpoint.invoke(requestContext) .whenComplete((message, throwable) -> { try { if (message != null) { ongoingRequest.reply(message); } else if (...
java
public LocalTime withNano(int nanoOfSecond) { if (this.nano == nanoOfSecond) { return this; } NANO_OF_SECOND.checkValidValue(nanoOfSecond); return create(hour, minute, second, nanoOfSecond); }
java
@Override public DescribePortfolioShareStatusResult describePortfolioShareStatus(DescribePortfolioShareStatusRequest request) { request = beforeClientExecution(request); return executeDescribePortfolioShareStatus(request); }
python
def setNeutral(self, aMathObject, deltaName="origin"): """Set the neutral object.""" self._neutral = aMathObject self.addDelta(Location(), aMathObject-aMathObject, deltaName, punch=False, axisOnly=True)
java
private ParseTree parseSwitchStatement() { SourcePosition start = getTreeStartLocation(); eat(TokenType.SWITCH); eat(TokenType.OPEN_PAREN); ParseTree expression = parseExpression(); eat(TokenType.CLOSE_PAREN); eat(TokenType.OPEN_CURLY); ImmutableList<ParseTree> caseClauses = parseCaseClauses...
python
def _get_formset_data(self): """Formats the self.filtered_data in a way suitable for a formset.""" data = [] for datum in self.filtered_data: form_data = {} for column in self.columns.values(): value = column.get_data(datum) form_data[colum...
java
public double evaluateClustering(Database db, Relation<O> rel, DistanceQuery<O> dq, Clustering<?> c) { List<? extends Cluster<?>> clusters = c.getAllClusters(); MeanVariance msil = new MeanVariance(); int ignorednoise = 0; for(Cluster<?> cluster : clusters) { // Note: we treat 1-element clusters t...
python
def is_chat_admin(user): """Checks if a user is a chat admin""" from indico_chat.plugin import ChatPlugin return ChatPlugin.settings.acls.contains_user('admins', user)
java
public SDVariable eye(String name, int rows, int cols) { return eye(name, rows, cols, Eye.DEFAULT_DTYPE); }
java
public static boolean getSetPortUsedBySupervisor(String instanceName, String supervisorHost, int port, RegistryOperations registryOperations) { String appPath = RegistryUtils.serviceclassPath( JOYConstants.APP_NAME, JOYConstants.APP_TYPE); String path = RegistryUtils.servicePath( ...
java
private void writeArray(JsonGenerator jsonGenerator, Object[] array, boolean firstInHierarchy) throws IOException, SQLException { if(!firstInHierarchy) { jsonGenerator.writeStartArray(); } for(int i = 0; i < array.length; i++) { if (array[i] instanceof Integer) { ...
python
def _generate_O(self, L): """Form the overlaps matrix, which is just all the different observed combinations of values of pairs of sources Note that we only include the k non-abstain values of each source, otherwise the model not minimal --> leads to singular matrix """ ...
java
public JsonDeserializationException traceError( String message, JsonReader reader ) { getLogger().log( Level.SEVERE, message ); traceReaderInfo( reader ); return new JsonDeserializationException( message ); }
python
def init(spark_home=None, python_path=None, edit_rc=False, edit_profile=False): """Make pyspark importable. Sets environment variables and adds dependencies to sys.path. If no Spark location is provided, will try to find an installation. Parameters ---------- spark_home : str, optional, defaul...
python
def get_url(self, version=None): """ Return the filename of the bundled bundle """ if self.fixed_bundle_url: return self.fixed_bundle_url return '%s.%s.%s' % (os.path.join(self.bundle_url_root, self.bundle_filename), version or self.get_version(), self.bundle_type)
python
def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned...
java
public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelPromise promise) { if (channel == null) { throw new NullPointerException("channel"); } channel.writeAndFlush(frame, promise); applyForceCloseTimeout(channel, promise); return promise; }
java
public static Map toMap(String json) { try { return mapper.readValue(json, Map.class); } catch (IOException e) { throw new RuntimeException(e); } }
java
@Service public String startWorkflow(StartWorkflowRequest startWorkflowRequest) { return startWorkflow(startWorkflowRequest.getName(), startWorkflowRequest.getVersion(), startWorkflowRequest.getCorrelationId(), startWorkflowRequest.getInput(), startWorkflowRequest.getExternalInputPayloadStor...
java
private SimpleHash buildModel(ValueStack stack, Component component) { Map<?, ?> context = stack.getContext(); HttpServletRequest req = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST); // build hash SimpleHash model = (SimpleHash) req.getAttribute(FreemarkerManager.ATTR_TEMPLATE_MODE...
java
private MembershipImpl getFromCache(String userName, String groupId, String type) { return (MembershipImpl)cache.get(cache.getMembershipKey(userName, groupId, type), CacheType.MEMBERSHIP); }
java
static byte[][] getPathComponents(String[] strings) { if (strings.length == 0) { return new byte[][]{null}; } byte[][] bytes = new byte[strings.length][]; for (int i = 0; i < strings.length; i++) bytes[i] = DFSUtil.string2Bytes(strings[i]); return bytes; }
python
def save(self, *args, **kwargs): """Saving ensures that the slug, if not set, is set to the slugified name.""" self.clean() if not self.slug: self.slug = slugify(self.name) super(SpecialCoverage, self).save(*args, **kwargs) if self.query and self.query != {}: ...
java
public static Query all(String field, Object... values) { return new Query().all(field, values); }
java
@SuppressWarnings("unchecked") public Dictionary<String, String> updateDictionaryConfig(Dictionary<String, String> dictionary, boolean returnCopy) { if (returnCopy) dictionary = BaseBundleActivator.putAll(dictionary, null); if (dictionary == null) dictionary = new Hashtab...
python
def execute(self, commands, encoding='json', **kwargs): """Executes the list of commands on the destination node This method takes a list of commands and sends them to the destination node, returning the results. The execute method handles putting the destination node in enable mode an...
python
def avl_join2(t1, t2): """ join two trees without any intermediate key Returns: Node: new_root O(log(n) + log(m)) = O(r(t1) + r(t2)) For AVL-Trees the rank r(t1) = height(t1) - 1 """ if t1 is None and t2 is None: new_root = None elif t2 is None: new_root = t1 ...
java
public Observable<WorkItemConfigurationInner> createAsync(String resourceGroupName, String resourceName, WorkItemCreateConfiguration workItemConfigurationProperties) { return createWithServiceResponseAsync(resourceGroupName, resourceName, workItemConfigurationProperties).map(new Func1<ServiceResponse<WorkItemCo...
python
def EAS2TAS(ARSP,GPS,BARO,ground_temp=25): '''EAS2TAS from ARSP.Temp''' tempK = ground_temp + 273.15 - 0.0065 * GPS.Alt return sqrt(1.225 / (BARO.Press / (287.26 * tempK)))
java
private Collection<IndexedInstance> getInstancesForVertex(Map<String, AttributeValueMap> map, AtlasVertex foundVertex) { //loop through the unique attributes. For each attribute, check to see if the vertex property that //corresponds to that attribute has a value from one or more of the instances that...
python
def package_meta(): """Read __init__.py for global package metadata. Do this without importing the package. """ _version_re = re.compile(r'__version__\s+=\s+(.*)') _url_re = re.compile(r'__url__\s+=\s+(.*)') _license_re = re.compile(r'__license__\s+=\s+(.*)') with open('lambda_uploader/__in...
python
def _handle_tag_definemorphshape2(self): """Handle the DefineMorphShape2 tag.""" obj = _make_object("DefineMorphShape2") obj.CharacterId = unpack_ui16(self._src) obj.StartBounds = self._get_struct_rect() obj.EndBounds = self._get_struct_rect() obj.StartEdgeBounds = self._...
java
public VDirectory createApplication(String appName) { Tenant tenant = new Tenant(TenantService.instance().getDefaultTenantDef()); return createApplication(tenant, appName); }
python
def _extract_from_subworkflow(vs, step): """Remove internal variable names when moving from sub-workflow to main. """ substep_ids = set([x.name for x in step.workflow]) out = [] for var in vs: internal = False parts = var["id"].split("/") if len(parts) > 1: if par...
python
def with_details(self, key, value): """ Sets a parameter for additional error details. This details can be used to restore error description in other languages. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param key: a...
python
def get(self,style): """ what's the value of a style at the current stack level""" level = len(self.stack) -1 while level >= 0: if style in self.stack[level]: return self.stack[level][style] else: level = level - 1 return None
python
def step_impl(context): """Compares text as written to the log output""" expected_lines = context.text.split('\n') assert len(expected_lines) == len(context.output) for expected, actual in zip(expected_lines, context.output): print('--\n\texpected: {}\n\tactual: {}'.format(expected, actual)) ...
java
String getWhereTaskletWasScheduledTo(final int taskletId) { for (final Map.Entry<String, VortexWorkerManager> entry : runningWorkers.entrySet()) { final String workerId = entry.getKey(); final VortexWorkerManager vortexWorkerManager = entry.getValue(); if (vortexWorkerManager.containsTasklet(taskl...
python
def fetch_userid(self, side): """Return the userid for the specified bed side.""" for user in self.users: obj = self.users[user] if obj.side == side: return user
python
def load_scene(self, item): """Load scene from json.""" scene = Scene.from_config(self.pyvlx, item) self.add(scene)
java
@Override void visit(ImageElement element, String value) throws IOException { if(inInode) { switch(element) { case INODE_PATH: if(value.equals("")) path = "/"; else path = value; break; case PERMISSION_STRING: perms = value; break; case REPLICATION: ...
java
@Override protected void saveBeans(List<ProxyActionStatus> addedBeans, List<ProxyActionStatus> modifiedBeans, List<ProxyActionStatus> removedBeans) { // CRUD operations on Target will be done through repository methods }
java
public static <T extends ResourceId> Builder<T> newBuilder(Status status, T replacement) { return new Builder<T>().setStatus(status).setReplacement(replacement); }
python
def _board_from_game_image(self, game_image): """Return a board object matching the board in the game image. Return None if any tiles are not identified. """ # board image board_rect = self._board_tools['board_region'].region_in(game_image) t, l, b, r = board_rect ...
python
def _resize_image_if_necessary(image_fobj, target_pixels=None): """Resize an image to have (roughly) the given number of target pixels. Args: image_fobj: File object containing the original image. target_pixels: If given, number of pixels that the image must have. Returns: A file object. """ if ...
java
@Override @PublicEvolving public <R> SingleOutputStreamOperator<R> transform(String operatorName, TypeInformation<R> outTypeInfo, OneInputStreamOperator<T, R> operator) { SingleOutputStreamOperator<R> returnStream = super.transform(operatorName, outTypeInfo, operator); // inject the key selector and key type...
java
private boolean waitForTasksToFinish() throws Exception { for (Future<Boolean> future : futures) { try { if (!future.get()) { cancel(); return false; } } catch (Exception e) { error.compareAndSet(null...
java
@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "log") public JAXBElement<ElementaryFunctionsType> createLog(ElementaryFunctionsType value) { return new JAXBElement<ElementaryFunctionsType>(_Log_QNAME, ElementaryFunctionsType.class, null, value); }
python
def _step(self, model: TrainingModel, batch: mx.io.DataBatch, checkpoint_interval: int, metric_train: mx.metric.EvalMetric, metric_loss: Optional[mx.metric.EvalMetric] = None): """ Performs an update to model given a batch and updates...
java
public final SIDestinationAddress createSIDestinationAddress(String destinationName ,boolean localOnly ) throws NullPointerException ...
java
public void doAESEncryption() throws Exception{ if(!initAESDone) initAES(); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //System.out.println(secretKey.getEncoded()); cipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = cipher.getParameters(); iv = params.getParameterSpec(IvP...
python
def _give_columns_django_field_attributes(self): """ Add Django Field attributes to each cqlengine.Column instance. So that the Django Options class may interact with it as if it were a Django Field. """ methods_to_add = ( django_field_methods.value_from_obje...
java
public static Image getInstance(PdfWriter writer, java.awt.Image awtImage, float quality) throws BadElementException, IOException { return getInstance(new PdfContentByte(writer), awtImage, quality); }
python
def _get_response(self, params): """ wrap the call to the requests package """ return self._session.get( self._api_url, params=params, timeout=self._timeout ).json(encoding="utf8")
python
def get_file(self, user, handle): """Retrieve a file for a user. :returns: a :class:`pathlib.Path` instance to this file, or None if no file can be found for this handle. """ user_dir = self.user_dir(user) if not user_dir.exists(): return None if...
java
public void addChild(TreeElement child) throws IllegalArgumentException { TreeElement theChild = child; theChild.setParent(this); if (getName() == null) { setName("0"); } if (_children == null) { _children = new ArrayList(); } ...
java
public static long calculateCRC32(byte[] buffer, int offset, int length) { if (!init_done) { initialize(); } for (int i = offset; i < offset + length; i++) { long tmp1 = (crc >>> 8) & 0x00FFFFFFL; long tmp2 = values[(int) ((crc ^ Character.toUpperCase((char) buffer[i])) & 0xff)]; crc = tmp1 ^ tmp...
python
def disaggregate_radiation(self, method='pot_rad', pot_rad=None): """ Disaggregate solar radiation. Parameters ---------- method : str, optional Disaggregation method. ``pot_rad`` Calculates potential clear-sky hourly radiation and scales...
python
def plot_series(self, xres, varied_data, varied_idx, **kwargs): """ Plots the results from :meth:`solve_series`. Parameters ---------- xres : array Of shape ``(varied_data.size, self.nx)``. varied_data : array See :meth:`solve_series`. varied_idx ...
java
@SuppressWarnings("PMD.UseStringBufferForStringAppends") private static String processClass(final Class clazz) { String res; // simpleName on anonymous class is empty string if (clazz.isAnonymousClass()) { res = clazz.getEnclosingClass().getSimpleName(); try { ...
python
def has_public_binary_operator(type_, operator_symbol): """returns True, if `type_` has public binary operator, otherwise False""" type_ = type_traits.remove_alias(type_) type_ = type_traits.remove_cv(type_) type_ = type_traits.remove_declarated(type_) assert isinstance(type_, class_declaration.clas...
python
def nvmlDeviceGetCurrPcieLinkGeneration(handle): r""" /** * Retrieves the current PCIe link generation * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param currLinkGen ...
java
public void setLastAccessTime(long lastAccessTime) { while (true) { long current = this.lastAccessTime; if (current >= lastAccessTime) { break; } if (ACCESSTIME_UPDATER.compareAndSet(this, current, lastAccessTime)) { break; } } }
python
def reinstall_ruby(ruby, runas=None, env=None): ''' Reinstall a ruby implementation ruby The version of ruby to reinstall runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. CLI Example: .. code-block:...
java
List<ControlFlowBlock> getControlFlowBlocksForMethod(final String methodName, final Type returnType, final Type... argumentTypes) { final MethodNode method = findMethodByDescriptor(methodName, returnType, argumentTypes); return getControlFlowBlocksForMethod(method); }
python
def make_error_router(): """ Creates an error router An error router takes a higher order observable a input and returns two observables: One containing the flattened items of the input observable and another one containing the flattened errors of the input observable. .. image:: ../docs/asset/err...
python
def label_field(self, f): """ Select one field as the label field. Note that this field will be exclude from feature fields. :param f: Selected label field :type f: str :rtype: DataFrame """ if f is None: raise ValueError("Label field name ca...
python
def solve(self): """ Solve the entire F2L. (Generator) """ for i in range(4): for slot in ["FR", "RB", "BL", "LF"]: solver = F2LPairSolver(self.cube, slot) if not solver.is_solved(): yield tuple([self.cube[slot[i]].colour fo...
java
public void norm_setBaseRelated(){ String [] time_grid=new String[6]; time_grid=normalizer.getTimeBase().split("-"); int[] ini = new int[6]; for(int i = 0 ; i < 6; i++) ini[i] = Integer.parseInt(time_grid[i]); Calendar calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); c...
python
def _get_version(): """Return the project version from VERSION file.""" with open(join(dirname(__file__), '{{project.package}}/VERSION'), 'rb') as f: version = f.read().decode('ascii').strip() return version
java
private void clear(long time) { if (time < lastTime.get() + size) { return; } int index = (int) (time % size); for (int i = 0; i < size; i++) { if (i != index) { counts.set(i, 0); } } }
python
def update(self, item_id, attributes, silent=False, hook=True): """ Updates the item using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. Important: webhooks will still be called. """...
python
def swap(self, position: int) -> None: """ Perform a SWAP operation on the stack. """ idx = -1 * position - 1 try: self.values[-1], self.values[idx] = self.values[idx], self.values[-1] except IndexError: raise InsufficientStack("Insufficient stack ...
java
public static void addDataOptions(final ArgP argp) { argp.addOption("--full-scan", "Scan the entire data table."); argp.addOption("--fix", "Fix errors as they're found. Use in combination with" + " other flags."); argp.addOption("--fix-all", "Set all flags and fix errors as they're found."); arg...
java
@Override public void close() { if (closed) return; closed = true; tcpSocketConsumer.prepareToShutdown(); if (shouldSendCloseMessage) eventLoop.addHandler(new EventHandler() { @Override public boolean action() throws InvalidEv...
java
@Override public Page<Dashboard> getDashboardByTitleWithFilter(String title, String type, Pageable pageable) { Page<Dashboard> dashboardItems = null; if ((type != null) && (!type.isEmpty()) && (!UNDEFINED.equalsIgnoreCase(type))) { dashboardItems = dashboardRepository.findAllByTypeContai...
java
public static CommerceTierPriceEntry fetchByUuid_C_First(String uuid, long companyId, OrderByComparator<CommerceTierPriceEntry> orderByComparator) { return getPersistence() .fetchByUuid_C_First(uuid, companyId, orderByComparator); }
python
def log_url (self, url_data): """Send new url to all configured loggers.""" self.check_active_loggers() do_print = self.do_print(url_data) # Only send a transport object to the loggers, not the complete # object instance. for log in self.loggers: log.log_filte...
java
public RESTParameter add(RESTParameter childParam) { Utils.require(!Utils.isEmpty(childParam.getName()), "Child parameter name cannot be empty"); m_parameters.add(childParam); return this; }
java
private void processInheritsCall(Node n) { if (n.getChildCount() == 3) { Node subClass = n.getSecondChild(); Node superClass = subClass.getNext(); if (subClass.isUnscopedQualifiedName() && superClass.isUnscopedQualifiedName()) { knownClosureSubclasses.add(subClass.getQualifiedName()); ...
python
def subtract(self, expr, simplify): """ Return a new expression where the `expr` expression has been removed from this expression if it exists. """ args = self.args if expr in self.args: args = list(self.args) args.remove(expr) elif isinsta...
java
public void writeTo(OutputStream out) throws TLVParserException { Util.notNull(out, "Output stream"); try { assertActualContentLengthIsInTLVLimits(getContentLength()); out.write(encodeHeader()); out.write(getContent()); } catch (IOException e) { th...
python
def set_courses(self, course_ids): """Sets the courses. arg: course_ids (osid.id.Id[]): the course ``Ids`` raise: InvalidArgument - ``course_ids`` is invalid raise: NullArgument - ``course_ids`` is ``null`` raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *c...
python
def before_run(self): """Initialize the scheduling process""" # Actions and checks counters self.nb_checks = 0 self.nb_internal_checks = 0 self.nb_checks_launched = 0 self.nb_actions_launched = 0 self.nb_checks_results = 0 self.nb_checks_results_timeout =...
java
public Observable<Void> renewAsync(String resourceGroupName, String certificateOrderName, RenewCertificateOrderRequest renewCertificateOrderRequest) { return renewWithServiceResponseAsync(resourceGroupName, certificateOrderName, renewCertificateOrderRequest).map(new Func1<ServiceResponse<Void>, Void>() { ...
java
public void runQueryWithNamedParameters() throws InterruptedException { // [START bigquery_query_params_named] // BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); String corpus = "romeoandjuliet"; long minWordCount = 250; String query = "SELECT word, word_count\n" ...