language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def question(self, n): """Choose what do to file by file """ print("") prompt_ask = raw_input("{0} [K/O/R/D/M/Q]? ".format(n)) print("") if prompt_ask in ("K", "k"): self.keep() elif prompt_ask in ("O", "o"): self._overwrite(n) elif...
python
def add_mapping(agent, prefix, ip): """Adds a mapping with a contract. It has high latency but gives some kind of guarantee.""" return _broadcast(agent, AddMappingManager, RecordType.record_A, prefix, ip)
java
public void marshall(GetPipelineStateRequest getPipelineStateRequest, ProtocolMarshaller protocolMarshaller) { if (getPipelineStateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getPipelin...
python
def _parse_integrator(int_method): """parse the integrator method to pass to C""" #Pick integrator if int_method.lower() == 'rk4_c': int_method_c= 1 elif int_method.lower() == 'rk6_c': int_method_c= 2 elif int_method.lower() == 'symplec4_c': int_method_c= 3 elif int_metho...
python
def _parse_request(self, enc_request, request_cls, service, binding): """Parse a Request :param enc_request: The request in its transport format :param request_cls: The type of requests I expect :param service: :param binding: Which binding that was used to transport the message...
python
def handle(self, dict): ''' Processes a vaild stats request @param dict: a valid dictionary object ''' # format key key = "statsrequest:{stats}:{appid}".format( stats=dict['stats'], appid=dict['appid']) self.redis_conn.set(key, di...
java
@Override public LocalDateTime plus(long amountToAdd, TemporalUnit unit) { if (unit instanceof ChronoUnit) { ChronoUnit f = (ChronoUnit) unit; switch (f) { case NANOS: return plusNanos(amountToAdd); case MICROS: return plusDays(amountToAdd / MICROS_PER...
java
protected SSLEngineResult.HandshakeStatus doTasks() { Runnable runnable; // We could run this in a separate thread, but do in the current for // now. while ((runnable = sslEngine.getDelegatedTask()) != null) { runnable.run(); } return sslEngine.getHandshakeSt...
java
private void addQueryParams(final Request request) { if (identity != null) { for (String prop : identity) { request.addQueryParam("Identity", prop); } } if (getPageSize() != null) { request.addQueryParam("PageSize", Integer.toString(getPageSiz...
java
public static ORCSchemaProvider createORCSchemaProvider( String className, SecorConfig config) throws Exception { Class<?> clazz = Class.forName(className); if (!ORCSchemaProvider.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException(String.format( ...
python
def detach_storage(self, server, address): """ Detach a Storage object to a Server. Return a list of the server's storages. """ body = {'storage_device': {'address': address}} url = '/server/{0}/storage/detach'.format(server) res = self.post_request(url, body) ret...
java
public static FieldUpdater createFieldUpdater(ObjectUpdater objUpdater, DBObject dbObj, String fieldName) { if (fieldName.charAt(0) == '_') { if (fieldName.equals(CommonDefs.ID_FIELD)) { return new IDFieldUpdater(objUpdater, dbObj); } else { // Allow ...
python
def rename_page(self, old_slug, new_title): '''Load the page corresponding to the slug, and rename it.''' #load page p = s2page.Page(self, old_slug, isslug=True) p.rename(new_title)
python
def empirical_rate(data, sigma=3.0): """ Smooth count data to get an empirical rate """ from scipy.ndimage.filters import gaussian_filter1d return 0.001 + gaussian_filter1d(data.astype(np.float), sigma, axis=0)
java
public BaseGrid setAxisLabel(String... axisLabels) { if (axisLabels.length != base.getDimension()) { throw new IllegalArgumentException("Axis label size don't match base dimension."); } for (int i = 0; i < axisLabels.length; i++) { axis[i].setAxisLabel(axisLabels[i]); ...
python
def set_heap(self, heap_dump, heap_base): """ Heap dump is a dump of the heap from gdb, i.e. the result of the following gdb command: ``dump binary memory [stack_dump] [begin] [end]`` :param heap_dump: The dump file. :param heap_base: The start address of the heap i...
python
def sendFuture(self, future): """Send a Future to be executed remotely.""" try: if shared.getConst(hash(future.callable), timeout=0): # Enforce name reference passing if already shared future.callable = SharedElementEncapsu...
java
@GET public Response getStores() { String msg = "getting stores."; try { return doGetStores(msg); } catch (StorageException se) { return responseBad(msg, se); } catch (Exception e) { return responseBad(msg, e); } }
java
public Response edit(String noteId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException { JinxUtils.validateParams(noteId, noteText); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.edit"); params.put("note_id", noteId); ...
java
@Override public Config getOwnConfig(ConfigKeyPath configKey, String version) throws VersionDoesNotExistException { Preconditions.checkNotNull(configKey, "configKey cannot be null!"); Preconditions.checkArgument(!Strings.isNullOrEmpty(version), "version cannot be null or empty!"); Path datasetDir = getDa...
java
private static final int find(final Memory mem, final int lgArr, final int coupon) { final int arrMask = (1 << lgArr) - 1; int probe = coupon & arrMask; final int loopIndex = probe; do { final int couponAtIndex = extractInt(mem, HASH_SET_INT_ARR_START + (probe << 2)); if (couponAtIndex...
java
private static final int toIndex(List<?> base, Object property) { int index = 0; if (property instanceof Number) { index = ((Number) property).intValue(); } else if (property instanceof String) { try { index = Integer.valueOf((String) property); } catch (NumberFormatException e) { throw new Illeg...
python
def parse_from_json(json_str): """ Given a Unified Uploader message, parse the contents and return a MarketOrderList or MarketHistoryList instance. :param str json_str: A Unified Uploader message as a JSON string. :rtype: MarketOrderList or MarketHistoryList :raises: MalformedUploadError when i...
java
public final void synpred45_InternalPureXbase_fragment() throws RecognitionException { // InternalPureXbase.g:5593:4: ( '!' | '-' | '+' | 'new' | '{' | 'switch' | 'synchronized' | '<' | 'super' | '#' | '[' | 'false' | 'true' | 'null' | 'typeof' | 'if' | 'for' | 'while' | 'do' | 'throw' | 'return' | 'try' | '...
python
def find_donor_catchments(self, limit=6, dist_limit=500): """ Return a suitable donor catchment to improve a QMED estimate based on catchment descriptors alone. :param limit: maximum number of catchments to return. Default: 6. Set to `None` to return all available catchmen...
java
public void init(Record record, int iFieldSeq, String fieldName, int iSecondaryFieldSeq, String secondaryFieldName) { Converter converter = null; m_recMerge = record; m_iFieldSeq = iFieldSeq; m_iSecondaryFieldSeq = iSecondaryFieldSeq; this.fieldName = fieldName; this....
python
def get_uris(self, base_uri, filter_list=None): """Return a set of internal URIs.""" return { re.sub(r'^/', base_uri, link.attrib['href']) for link in self.parsedpage.get_nodes_by_selector('a') if 'href' in link.attrib and ( link.attrib['href'].startsw...
java
public static boolean lossyEquals(final Locale locale, final String source, final String target) { return withinLocale(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return lossyEquals(source, target); } ...
java
@Override protected void unserializeFrom(RawDataBuffer in) { super.unserializeFrom(in); sessionId = new IntegerID(in.readInt()); }
java
public static void sendTextBlocking(final String message, final WebSocketChannel wsChannel) throws IOException { final ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)); sendBlockingInternal(data, WebSocketFrameType.TEXT, wsChannel); }
java
@Override public List<MemberAnnotatedWithAtStat> apply(Class<?> clazz) { List<MemberAnnotatedWithAtStat> annotatedMembers = Lists.newArrayList(); for (Class<?> currentClass = clazz; currentClass != Object.class; currentClass = currentClass.getSuperclass()) { for (Method method : currentCl...
java
private void initEntityClass() { if (from == null) { throw new JPQLParseException("Bad query format FROM clause is mandatory for SELECT queries"); } String fromArray[] = from.split(" "); if (!this.isDeleteUpdate) { if (fromArray.length == 3 && fromArray[1].equals...
java
public void visitPreDestroyMethod(Object declaringType, Object returnType, String methodName) { visitPreDestroyMethodDefinition(); final MethodVisitData methodVisitData = new MethodVisitData( declaringType, ...
java
public void assignNestedDrivers(XTrace trace, Map<List<String>, String> drivers) { XCostDriver.instance().assignNestedValues(trace, drivers); }
python
def _save_account(self, account, username): """ Called when account is created/updated. With username override. """ # retrieve default project, or use null project if none default_project_name = self._null_project if account.default_project is not None: default_project_name ...
java
public void addAll(IntBitRelation right) { int i, max; max = right.line.length; for (i = 0; i < max; i++) { if (right.line[i] != null) { add(i, right.line[i]); } } }
python
def formfields_for_xmlobject(model, fields=None, exclude=None, widgets=None, options=None, declared_subforms=None, max_num=None, extra=None): """ Returns three sorted dictionaries (:class:`django.utils.datastructures.SortedDict`). * The first is a dictionary of form fields based on the :clas...
java
public PlatformResponse disconnect(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) throws ConnectionException { httpClient = new PlatformHttpClient(consumerKey, consumerSecret, accessToken, accessTokenSecret); return this.httpClient.disconnect(); }
java
@Override public java.util.concurrent.Future<DeleteStreamResult> deleteStreamAsync(String streamName, com.amazonaws.handlers.AsyncHandler<DeleteStreamRequest, DeleteStreamResult> asyncHandler) { return deleteStreamAsync(new DeleteStreamRequest().withStreamName(streamName), asyncHandler); }
python
def set_section_order(self, section_name_list): """Set the order of the sections, which are by default unorderd. Any unlisted sections that exist will be placed at the end of the document in no particular order. """ self.section_headings = section_name_list[:] for sectio...
python
def _build_wsgi_env(event, app_name): """Turn the Lambda/API Gateway request event into a WSGI environment dict. :param dict event: The event parameters passed to the Lambda function entrypoint. :param str app_name: Name of the API application. """ gateway = event['parameters']['gat...
java
AtomSymbol alignTo(SymbolAlignment alignment) { return new AtomSymbol(element, adjuncts, annotationAdjuncts, alignment, hull); }
python
def _determine_colorspace(self, colorspace=None, **kwargs): """Determine the colorspace from the supplied inputs. Parameters ---------- colorspace : str, optional Either 'rgb' or 'gray'. """ if colorspace is None: # Must infer the colorspace from ...
python
def create(dataset, target, features=None, validation_set = 'auto', verbose=True): """ Automatically create a suitable classifier model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ...
python
def digest(self): """Get digest of data seen thus far as a list of bytes.""" total = 0 # number of triplets seen if self.count == 3: # 3 chars = 1 triplet total = 1 elif self.count == 4: # 4 chars = 4 triplets ...
python
def add_layer_timing_signal_sinusoid_1d(x, layer, num_layers): """Add sinusoids of different frequencies as layer (vertical) timing signal. Args: x: a Tensor with shape [batch, length, channels] layer: layer num num_layers: total number of layers Returns: a Tensor the same shape as x. """ c...
python
def infer_issubclass(callnode, context=None): """Infer issubclass() calls :param nodes.Call callnode: an `issubclass` call :param InferenceContext: the context for the inference :rtype nodes.Const: Boolean Const value of the `issubclass` call :raises UseInferenceDefault: If the node cannot be infer...
java
@Override public String onCompleted() throws Exception { futureDone(); if (closed.get()) return ""; if (status == Socket.STATUS.ERROR) { return ""; } if (options.reconnect()) { close(false); if (options.reconnectTimeoutInMilliseconds() >...
java
public static CommerceCountry remove(long commerceCountryId) throws com.liferay.commerce.exception.NoSuchCountryException { return getPersistence().remove(commerceCountryId); }
python
def cloud_providers_config(path, env_var='SALT_CLOUD_PROVIDERS_CONFIG', defaults=None): ''' Read in the salt cloud providers configuration file ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS overrides = salt.config.load_con...
python
def gen_uid(i): """ Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 data_uid - UID in string format (16 characters 0..9,a..f) } ...
python
def dump(self, f): """Write Wavefront data to file. Takes File object or filename.""" try: f.write(self._data) except AttributeError: with open(f, 'w') as wf: wf.write(self._data)
java
public QueryInfo withSelectFields(FieldInfo... selectFields) { if (this.selectFields == null) { setSelectFields(new com.amazonaws.internal.SdkInternalList<FieldInfo>(selectFields.length)); } for (FieldInfo ele : selectFields) { this.selectFields.add(ele); } ...
python
def _par_read(dirname, compressed=True): """ Internal write function to read a formatted parameter file. :type dirname: str :param dirname: Directory to read the parameter file from. :type compressed: bool :param compressed: Whether the directory is compressed or not. """ templates = []...
python
def _doublec(self, word): """doublec(word) is TRUE <=> word ends with a double consonant""" if len(word) < 2: return False if (word[-1] != word[-2]): return False return self._cons(word, len(word)-1)
python
def setup(self, target=None, strict=False, minify=False, line_numbers=False, keep_lines=False, no_tco=False): """Initializes parsing parameters.""" if target is None: target = "" else: target = str(target).replace(".", "") if target in pseudo_targets: ...
java
public int getTotalDurationFromFrameDurations(int[] frameDurationMs) { int totalMs = 0; for (int i = 0; i < frameDurationMs.length; i++) { totalMs += frameDurationMs[i]; } return totalMs; }
java
@Deprecated public static StringBuffer convertToUnicode(UCharacterIterator src, int options) throws StringPrepParseException{ return IDNA2003.convertToUnicode(src, options); }
python
async def createWorkerType(self, *args, **kwargs): """ Create new Worker Type Create a worker type. A worker type contains all the configuration needed for the provisioner to manage the instances. Each worker type knows which regions and which instance types are allowed for th...
python
def extremum_icohpvalue(self, summed_spin_channels=True, spin=Spin.up): """ get ICOHP/ICOOP of strongest bond Args: summed_spin_channels: Boolean to indicate whether the ICOHPs/ICOOPs of both spin channels should be summed spin: if summed_spin_channels is equal to False,...
java
public HttpHeaders setBasicAuthentication(String username, String password) { String userPass = Preconditions.checkNotNull(username) + ":" + Preconditions.checkNotNull(password); String encoded = Base64.encodeBase64String(StringUtils.getBytesUtf8(userPass)); return setAuthorization("Basic " + encode...
java
public static base_response sync(nitro_service client, hafiles resource) throws Exception { hafiles syncresource = new hafiles(); syncresource.mode = resource.mode; return syncresource.perform_operation(client,"sync"); }
java
protected <T> Searchable<T> configureMatcher(final Searchable<T> searchable) { if (isCustomMatcherAllowed()) { Matcher<T> matcher = searchable.getMatcher(); if (matcher != null) { MatcherHolder.set(matcher); } } return searchable; }
python
def stop(self): """ Stop logging with this logger. """ if not self.active: return self.removeHandler(self.handlers[-1]) self.active = False return
java
public final void setDialogHeaderIconTintMode(@NonNull final PorterDuff.Mode mode) { Condition.INSTANCE.ensureNotNull(mode, "The dialog icon tint mode may not be null"); this.dialogHeaderIconTintMode = mode; }
java
public boolean containsCycle() throws WikiApiException { DefaultEdge edge = findCycle(); if (edge != null) { Category sourceCat = wiki.getCategory(categoryGraph.getGraph().getEdgeSource(edge)); Category targetCat = wiki.getCategory(categoryGraph.getGraph().getEdgeTarget(edge)); ...
python
def get_formset_class(self, form, name): """ Either return the formset class that was provided as argument to the __init__ method, or build one based on the ``parent_model`` and ``model`` attributes. """ if self.formset_class is not None: return self.formset_c...
java
@Override public Request<UpdateSecurityGroupRuleDescriptionsIngressRequest> getDryRunRequest() { Request<UpdateSecurityGroupRuleDescriptionsIngressRequest> request = new UpdateSecurityGroupRuleDescriptionsIngressRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true...
python
def run(self, num_runs, show_trails, log_file_base): """ Run each agent in the world for 'num_runs' iterations Optionally saves grid results to file if base name is passed to method. """ print("--------------------------------------------------") print("Starting S...
java
public boolean remove(Object o) { boolean ret = super.remove(WeakElement.create(o)); processQueue(); return ret; }
python
def about_axis(cls, center, angle, axis, invert=False): """Create transformation that represents a rotation about an axis Arguments: | ``center`` -- Point on the axis | ``angle`` -- Rotation angle | ``axis`` -- Rotation axis | ``invert`` -- Whe...
java
public void accept(PainterVisitor visitor, Object group, Bbox bounds, boolean recursive) { if (googleMap == null) { // create as first child of raster group map.getRasterContext().drawGroup(null, this); String id = map.getRasterContext().getId(this); String graphicsId = map.getVectorContext().getId(); ...
python
def get_itoken(self, env): """Returns the current internal token to use for the auth system's own actions with other services. Each process will create its own itoken and the token will be deleted and recreated based on the token_life configuration value. The itoken information is stored...
java
public PasswordAuthentication unregisterPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) { return passwordAuthentications.remove(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme)); }
java
private PlayState3 findPlayState3() { PlayState3 result = PLAY_STATE_3_MAP.get(packetBytes[157]); if (result == null) { return PlayState3.UNKNOWN; } return result; }
python
def dfa_to_dot(dfa: dict, name: str, path: str = './'): """ Generates a DOT file and a relative SVG image in **path** folder of the input DFA using graphviz library. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the DOT/SVG files (defa...
java
@Override public final void remove() throws RemoteException, RemoveException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "remove"); //canBeRemoved();//94781 // For stateless beans, it is not upto t...
python
def find_children(self, pattern=r".*", flags=0, candidates=None): """ Finds the children matching the given patten. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode...
java
public final void init(int opmode, Certificate certificate, SecureRandom random) throws InvalidKeyException { initialized = false; checkOpmode(opmode); // Check key usage if the certificate is of // type X.509. if (certificate instanceof ja...
python
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray according to this PrimitiveType definition. NOTE: The parameter ``raw`` is present to adhere to the ``decode()`` inteface, but has no effect for PrimitiveType defini...
python
def _make_rewritten_pyc(state, fn, pyc, co): """Try to dump rewritten code to *pyc*.""" if sys.platform.startswith("win"): # Windows grants exclusive access to open files and doesn't have atomic # rename, so just write into the final file. _write_pyc(state, co, fn, pyc) else: ...
java
public static <T> T wrap(Operation<T> operation) throws EvernoteException { try { return operation.execute(); } catch (Exception ex) { throw convert(ex); } }
java
@Override public CompletableFuture<Void> execute(CommitEvent event) { String scope = event.getScope(); String stream = event.getStream(); OperationContext context = streamMetadataStore.createContext(scope, stream); log.debug("Attempting to commit available transactions on stream {}/{...
python
def get_parameter(self, parameter): "Return a dict for given parameter" parameter = self._get_parameter_name(parameter) return self._parameters[parameter]
java
public void eInit(SarlScript script, String name, IJvmTypeProvider context) { setTypeResolutionContext(context); if (this.sarlArtifact == null) { this.sarlArtifact = SarlFactory.eINSTANCE.createSarlArtifact(); script.getXtendTypes().add(this.sarlArtifact); this.sarlArtifact.setAnnotationInfo(XtendFactory.e...
java
public Object addYToPoint(double y, Object point) { ((Point) point).setY(y); return point; }
java
public String rewrite() { if (sqlTokens.isEmpty()) { return originalSQL; } SQLBuilder result = new SQLBuilder(Collections.emptyList()); int count = 0; for (SQLToken each : sqlTokens) { if (0 == count) { result.appendLiterals(originalSQL.sub...
python
def list_namespaced_pod_disruption_budget(self, namespace, **kwargs): # noqa: E501 """list_namespaced_pod_disruption_budget # noqa: E501 list or watch objects of kind PodDisruptionBudget # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTT...
python
def insert_meta_fields_into_existing_schema(graphql_schema): """Add compiler-specific meta-fields into all interfaces and types of the specified schema. It is preferable to use the EXTENDED_META_FIELD_DEFINITIONS constant above to directly inject the meta-fields during the initial process of building the s...
java
public Graph<K, VV, EV> addEdge(Vertex<K, VV> source, Vertex<K, VV> target, EV edgeValue) { Graph<K, VV, EV> partialGraph = fromCollection(Arrays.asList(source, target), Collections.singletonList(new Edge<>(source.f0, target.f0, edgeValue)), this.context); return this.union(partialGraph); }
python
def set_schedule(self, zone_info): """Sets the schedule for this zone""" # must only POST json, otherwise server API handler raises exceptions try: json.loads(zone_info) except ValueError as error: raise ValueError("zone_info must be valid JSON: ", error) ...
python
def ComplementaryColor(self, mode='ryb'): '''Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.NewFromHsl(30, 1, 0.5).ComplementaryCo...
java
public static boolean nodeMatchesClassByName( Context context, AccessibilityNodeInfoCompat node, CharSequence referenceClassName) { if ((node == null) || (referenceClassName == null)) { return false; } // Attempt to take a shortcut. final CharSequence nodeClassNa...
java
@Override @ConstantTime(amortized = true) public AddressableHeap.Handle<K, V> insert(K key, V value) { if (other != this) { throw new IllegalStateException("A heap cannot be used after a meld"); } if (key == null) { throw new NullPointerException("Null keys not pe...
java
@Override GroupReplyList write_attribute_reply_i(final int rid, final int tmo, final boolean fwd) throws DevFailed { final Integer rid_obj = new Integer(rid); final GroupReplyList rl = new GroupReplyList(); final AsynchRequest ar = arp.get(rid_obj); if (ar == null) { final DevError[] errors = new DevError[...
java
public void addModifier(String modifier) { if (!Strings.isEmpty(modifier)) { this.sarlBehavior.getModifiers().add(modifier); } }
python
def observable_timestamp_compare(instance): """Ensure cyber observable timestamp properties with a comparison requirement are valid. """ for key, obj in instance['objects'].items(): compares = enums.TIMESTAMP_COMPARE_OBSERVABLE.get(obj.get('type', ''), []) print(compares) for fir...
java
@CheckForNull static public BitSet getBytecodeSet(JavaClass clazz, Method method) { XMethod xmethod = XFactory.createXMethod(clazz, method); if (cachedBitsets().containsKey(xmethod)) { return cachedBitsets().get(xmethod); } Code code = method.getCode(); if (code ...
java
public VirtualMachineExtensionInner beginCreateOrUpdate(String resourceGroupName, String vmName, String vmExtensionName, VirtualMachineExtensionInner extensionParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmName, vmExtensionName, extensionParameters).toBlocking().single().b...
java
public void buildDeprecationInfo(XMLNode node, Content fieldDocTree) { writer.addDeprecated( (FieldDoc) fields.get(currentFieldIndex), fieldDocTree); }