language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public List<CommerceUserSegmentEntry> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def _make_unknown_name(self, cursor): '''Creates a name for unname type''' parent = cursor.lexical_parent pname = self.get_unique_name(parent) log.debug('_make_unknown_name: Got parent get_unique_name %s',pname) # we only look at types declarations _cursor_decl = cursor.t...
python
def get_context_data(self, **kwargs): """ Returns context dictionary for view. :rtype: dict. """ kwargs.update({ 'view': self, 'email_form': EmailLinkForm(), 'external_form': ExternalLinkForm(), 'type_email': ...
python
def iqr(a): """ Calculate the IQR for an array of numbers. """ a = np.asarray(a) q1 = stats.scoreatpercentile(a, 25) q3 = stats.scoreatpercentile(a, 75) return q3 - q1
java
public static boolean fundamentalCompatible3( DMatrixRMaj F21 , DMatrixRMaj F31 , DMatrixRMaj F32 , double tol ) { FundamentalExtractEpipoles extractEpi = new FundamentalExtractEpipoles(); Point3D_F64 e21 = new Point3D_F64(); Point3D_F64 e12 = new Point3D_F64(); Point3D_F64 e31 = new Point3D_F64(); Point3D_...
python
def c2s(self,p=[0,0]): """Convert from canvas to screen coordinates""" return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))
java
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { // Don't mo...
python
def dec(self, byts): ''' Decode an envelope dict and decrypt the given bytes. Args: byts (bytes): Bytes to decrypt. Returns: bytes: Decrypted message. ''' envl = s_msgpack.un(byts) iv = envl.get('iv', b'') asscd = envl.get('asscd'...
java
public static boolean isUncheckedException(ObjectType type) throws ClassNotFoundException { if (type.equals(Type.THROWABLE) || type.equals(RUNTIME_EXCEPTION_TYPE) || type.equals(ERROR_TYPE)) { return true; } ClassDescriptor c = DescriptorFactory.getClassDescriptor(type); Subt...
python
def save(self, render_name=False, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg """Save the data model.""" if self.name != self._original_name: self.named_by_user = True create = self.pk is None if create: fill_with_defaults(self.input, self.proc...
java
public ConnectionListener getConnectionListener() throws ResourceException { if (pool.getLogger().isTraceEnabled()) { synchronized (this) { pool.getLogger().trace(ManagedConnectionPoolUtility.fullDetails(this, "getConnectionListener()", pool.get...
java
public SearchProvisionedProductsResult withProvisionedProducts(ProvisionedProductAttribute... provisionedProducts) { if (this.provisionedProducts == null) { setProvisionedProducts(new java.util.ArrayList<ProvisionedProductAttribute>(provisionedProducts.length)); } for (ProvisionedPro...
python
def returnDepositsWithdrawals(self, start=0, end=2**32-1): """Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps.""" return self._private('returnDepositsWithdrawals', start=start...
java
public boolean isIPv4Mapped() { //::ffff:x:x/96 indicates IPv6 address mapped to IPv4 if(getSegment(5).matches(IPv6Address.MAX_VALUE_PER_SEGMENT)) { for(int i = 0; i < 5; i++) { if(!getSegment(i).isZero()) { return false; } } return true; } return false; }
java
public static void centerWindow(Component component) { Window window = getWindow(component); if (window != null) { window.center(); } }
python
def plot(self, stachans='all', size=(10, 7), show=True): """ Plot the output basis vectors for the detector at the given dimension. Corresponds to the first n horizontal vectors of the V matrix. :type stachans: list :param stachans: list of tuples of station, channel pairs to p...
python
def generate_metadata(self): # type: (Descriptor) -> dict """Generate metadata for descriptor :param Descriptor self: this :rtype: dict or None :return: kv metadata dict """ genmeta = {} encmeta = {} # page align md5 if (self.must_compute_m...
python
def _read_packet(self): """Read a packet from the input.""" status = STATUS_WAITING mode = 0 checksum = 0 checksum_calculated = 0 length = 0 version = 0 i = 0 cnt = 0 packet = bytearray(0) while (status != STATUS_PACKET_DONE): ...
python
def do_cld_check(self, cld): """ Do the "clause :math:`D`" check. This method receives a list of literals, which serves a "clause :math:`D`" [1]_, and checks whether the formula conjoined with :math:`D` is satisfiable. If clause :math:`D` cannot be satisfied toge...
java
public void beforeTransformation(TypeDescription typeDescription, ClassLoader classLoader) { if (isPreventDuplicateTransformation()) { Dispatcher.put(getClassAlreadyTransformedKey(typeDescription, classLoader), Boolean.TRUE); } if (DEBUG_INSTRUMENTATION && logger.isDebugEnabled()) { logger.debug("TRANSFORM...
java
@RequestMapping(value = "changeLog/fileFilter/{projectId}", method = RequestMethod.GET) public Resources<Resource<SCMFileChangeFilter>> getChangeLogFileFilters(@PathVariable ID projectId) { // Gets the store SCMFileChangeFilters config = loadStore(projectId); // Resources return Reso...
java
@Override public void visitCode(Code obj) { Method m = getMethod(); if (prescreen(m)) { String methodName = m.getName(); if (Values.STATIC_INITIALIZER.equals(methodName) || Values.CONSTRUCTOR.equals(methodName)) { super.visitCode(obj); } } ...
python
def main(self): """ This is the main entry point of the ElastiCluster CLI. First the central configuration is created, which can be altered through the command line interface. Then the given command from the command line interface is called. """ assert self.param...
java
private void writeEntry(InputStream input, JarEntry entry) throws IOException { // add the entry to the jar archive mOutputJar.putNextEntry(entry); // read the content of the entry from the input stream, and write it into the archive. int count; while ((count = input.read(mBuffe...
java
public void marshall(DescribeLunaClientRequest describeLunaClientRequest, ProtocolMarshaller protocolMarshaller) { if (describeLunaClientRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(desc...
java
@Override public DeleteBandwidthRateLimitResult deleteBandwidthRateLimit(DeleteBandwidthRateLimitRequest request) { request = beforeClientExecution(request); return executeDeleteBandwidthRateLimit(request); }
python
def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None, use_columns=False, xticks=None, colormap=None, axvlines=True, axvlines_kwds=None, sort_labels=False, **kwds): """Parallel coordinates plotting. Parameters ...
python
def get_ecdh_key(self, other): ''' other-->Key25519 instance ''' if self.__secretkey is None: raise KeyTypeError('Wrong key type for operation') # Copy because curve25519_dh_CreateSharedKey changes secretkey tmp_secretkey = ffi.new(C_SECRETKEY, self.secretkey)...
java
public void addIdentifiers(String[] id) { XmpArray array = new XmpArray(XmpArray.UNORDERED); for (int i = 0; i < id.length; i++) { array.add(id[i]); } setProperty(IDENTIFIER, array); }
java
public <T> T runTotalLocked(Job<T> j) { long[] _stamps = lockAll(); try { return j.call(); } finally { unlockAll(_stamps); } }
python
def _contour(f, vertexlabels=None, contourfunc=None, **kwargs): '''Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.''' if contourfunc is None: contourfunc = plt.tricontour if vertexlabels is None: vertexlabels = ('1','2...
python
def _run_cnvkit_shared_orig(inputs, backgrounds): """Original CNVkit implementation with full normalization and segmentation. """ work_dir = _sv_workdir(inputs[0]) raw_work_dir = utils.safe_makedir(os.path.join(work_dir, "raw")) background_name = dd.get_sample_name(backgrounds[0]) if backgrounds els...
java
public <K extends Comparable<K>> PartitionOperator<T> partitionByHash(KeySelector<T, K> keyExtractor) { final TypeInformation<K> keyType = TypeExtractor.getKeySelectorTypes(keyExtractor, getType()); return new PartitionOperator<>(this, PartitionMethod.HASH, new Keys.SelectorFunctionKeys<>(clean(keyExtractor), this....
java
@SuppressWarnings("unchecked") public static List<Long> getAt(long[] array, Collection indices) { return primitiveArrayGet(array, indices); }
python
def output_size(self) -> Tuple[Sequence[Shape], Sequence[Shape], Sequence[Shape], int]: '''Returns the simulation cell output size.''' return (self.state_size, self.action_size, self.interm_size, 1)
java
public ResourceAdapter merge(MergeableMetadata<?> jmd) throws Exception { if (jmd instanceof ResourceAdapterImpl) { ResourceAdapterImpl inputRA = (ResourceAdapterImpl) jmd; InboundResourceAdapter newInboundResourceadapter = this.inboundResourceadapter == null ? inputRA.i...
java
public static <T> PatternStream<T> pattern(DataStream<T> input, Pattern<T, ?> pattern) { return new PatternStream<>(input, pattern); }
python
def capture(self, to_camera_storage=False): """ Capture an image. Some cameras (mostly Canon and Nikon) support capturing to internal RAM. On these devices, you have to specify `to_camera_storage` if you want to save the images to the memory card. On devices that do not support ...
java
static Comment asEngineComment(final IComment comment) { if (comment instanceof Comment) { return (Comment) comment; } return new Comment(comment.getContent(), comment.getTemplateName(), comment.getLine(), comment.getCol()); }
python
def get_percentage_from_prob(prob): """ Converted probability of being treated to total percentage of clinical cases treated """ assert isinstance(prob, (float, int)) prob = float(prob) assert prob >= 0 assert prob <= 1 percentages = list(probability_list.keys()) percentages.sort() ...
python
def find_strings(self, string=".*"): """ Find strings by regex :param string: regular expression for the string to search for :rtype: generator of `StringAnalysis` """ for s, sa in self.strings.items(): if re.match(string, s): yield sa
java
public static List<MutableIntTuple> create( int dimensions, int numElements) { List<MutableIntTuple> list = new ArrayList<MutableIntTuple>(numElements); create(dimensions, numElements, list); return list; }
java
public SourcedToken[] sourcedTokenize(String input,String source) { Token[] tokens = tokenize(input); SourcedToken[] sourcedTokens = new SourcedToken[tokens.length]; for (int i=0; i<tokens.length; i++) { String key = tokens[i].getValue()+"@"+source; if (tokMap.get(ke...
python
def save_jsonf(data: Union[list, dict], fpath: str, encoding: str, indent=None) -> str: """ :param data: list | dict data :param fpath: write path :param encoding: encoding :param indent: :rtype: written path """ with codecs.open(fpath, mode='w', encoding=encoding) as f: f.write(...
java
public static String handleElasticSearchSpecialChars(String condition){ if(condition == null || condition.equals("")){ return condition; } condition = condition.replace(":","\\:"); condition = condition.replace("-","\\-"); condition = condition.replace("+","\\+"); condition = condition.replace("&","\\&")...
python
def basic_c_defines( layout, keyboard_prefix="KEY_", led_prefix="LED_", sysctrl_prefix="SYS_", cons_prefix="CONS_", code_suffix=True, all_caps=True, space_char="_" ): ''' Generates a list of C defines that can be used to generate a header file @param layout: Layout object ...
python
def get_hosting_devices_qry(self, context, hosting_device_ids, load_agent=True): """Returns hosting devices with <hosting_device_ids>.""" query = context.session.query(hd_models.HostingDevice) if load_agent: query = query.options(joinedload('cfg_agent'...
python
def get_X(self): ''' :return: term freq matrix or metadata freq matrix ''' if self._use_non_text_features: return self._term_doc_matrix._mX else: return self._term_doc_matrix._X
python
def read_ligolw(source, contenthandler=LIGOLWContentHandler, **kwargs): """Read one or more LIGO_LW format files Parameters ---------- source : `str`, `file` the open file or file path to read contenthandler : `~xml.sax.handler.ContentHandler`, optional content handler used to pars...
java
public StringGrabber get(int index) { if (index < 0) { return new StringGrabber(); } else if (index > size() - 1) { return new StringGrabber(); } else { return mSgList.get(index); } }
python
def parametererror(self): """Return the first parameter error, or False if there is none""" for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.error: return parameter.error ...
java
public static boolean isElement(Node node) { return (null == node) ? false : Node.ELEMENT_NODE == node.getNodeType(); }
python
def on_if(self, node): # ('test', 'body', 'orelse') """Regular if-then-else statement.""" block = node.body if not self.run(node.test): block = node.orelse for tnode in block: self.run(tnode)
java
public com.google.api.ads.adwords.axis.v201809.billing.BudgetOrderRequest getLastRequest() { return lastRequest; }
python
def register_pivot_wavelength(self, telescope, band, wlen): """Register precomputed pivot wavelengths.""" if (telescope, band) in self._pivot_wavelengths: raise AlreadyDefinedError('pivot wavelength for %s/%s already ' 'defined', telescope, band) ...
python
def get_service_name(self, service_id: str) -> str: """Get the name of the docker service. Only the manager nodes can retrieve service name Args: service_id (string): List of service ID Returns: string, name of the docker service """ # Raise an...
python
def include(self, location, namespace=None, app_name=None): """ Return an object suitable for url_patterns. :param location: root URL for all URLs from this router :param namespace: passed to url() :param app_name: passed to url() """ sorted_entries = sorted(self...
python
def delegate(attribute_name, method_names): """Pass the call to the attribute called attribute_name for every method listed in method_names.""" # hack for python 2.7 as nonlocal is not available info = { 'attribute': attribute_name, 'methods': method_names } def decorator(cls): ...
python
def load(self, system_effect): """ Return a :class:`.BanksManager` instance contains the banks present in :attr:`~pluginsmanager.observer.autosaver.autosaver.Autosaver.data_path` :param SystemEffect system_effect: SystemEffect used in pedalboards :return BanksManager: :class:`.B...
python
def translate(self, disp): """ Translate Geometry. disp: displacement (array of floats) """ d = Vector(disp[0], disp[1], disp[2]) for poly in self.polygons: for v in poly.vertices: v.pos = v.pos.plus(d)
python
def set(self, param, value): """ sets the param to the value provided """ self.raw_dict[param] = value self.manifest.set(self.feature_name, param, value)
python
def sun_rise_set(latitude, longitude, date, mode='rise', timezone=0, zenith=None): """Calculate sunrise or sunset for a specific location. This function calculates the time sunrise or sunset, or optionally the beginning or end of a specified twilight period. Source:: Almanac ...
java
public static void writeInt16LE(final int value, final byte[] buffer, int offset) { buffer[offset++] = (byte) value; buffer[offset] = (byte) ((value >>> 8) & 0xFF); }
java
@Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { MatchResult directResult = firstNonNullMatchResult(DIRECT_MATCHERS, tree, state); MatchResult typeArgResult = null; if (directResult == null) { typeArgResult = firstNonNullMatchResult(TYPE_ARG_MATCHER...
python
def get_annotation_url(module, version): """Get a BEL annotation file from artifactory given the name and version. :param str module: :param str version: :type: str """ module = module.strip('/') return '{module}/{name}'.format( module=get_annotation_module_url(module), nam...
java
public void setMetadataSettings (boolean store, boolean index, boolean token) { indexMetadata = index; storeMetadata = store; tokenizeMetadata = token; }
java
public static <T1, T2, R> CompletableFuture<R> zip(final CompletableFuture<? extends T1> f, final Iterable<? extends T2> v, final BiFunction<? super T1, ? super T2, ? extends R> fn) { return narrow(Future.of(f) .zip(v, fn) .getFuture()); ...
python
def getResultsRange(self): """Returns the valid result ranges for the analyses this Analysis Request contains. By default uses the result ranges defined in the Analysis Specification set in "Specification" field if any. Values manually set through `ResultsRange` field for any gi...
python
def random_board(max_x, max_y, load_factor): """Return a random board with given max x and y coords.""" return dict(((randint(0, max_x), randint(0, max_y)), 0) for _ in xrange(int(max_x * max_y / load_factor)))
java
@Override public ITextRegion getTextRegion(EObject object, EStructuralFeature feature, int indexInList, ILocationInFileProviderExtension.RegionDescription query) { return super.getTextRegion(convertToSource(object), feature, indexInList, query); }
java
private Object[] processByteArrayWithData(long rowOffset, long rowLength, List<String> columnNames) { Object[] rowElements; if (columnNames != null) { rowElements = new Object[columnNames.size()]; } else { rowElements = new Object[(int) sasFileProperties.getColumnsCount()...
python
def match_iter(self, path_elements, start_at): """A generator that searches over *path_elements* (starting from the index *start_at*), yielding for each match. Each value yielded is the index into *path_elements* to the first element *after* each match. In other words, the returned inde...
python
def isStochastic(matrix): """Check that ``matrix`` is row stochastic. Returns ======= is_stochastic : bool ``True`` if ``matrix`` is row stochastic, ``False`` otherwise. """ try: absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0]))) except AttributeError: ...
python
def CollectData(self): """Return some current samples. Call StartDataCollection() first. """ while 1: # loop until we get data or a timeout _bytes = self._ReadPacket() if not _bytes: return None if len(_bytes) < 4 + 8 + 1 or _bytes[0] < 0x20 o...
python
def new_tag(self, name: str, category: str=None) -> models.Tag: """Create a new tag.""" new_tag = self.Tag(name=name, category=category) return new_tag
python
def redo(self): ''' Redo the last undone action. This is only possible if no other actions have occurred since the last undo call. ''' if self.canredo(): undoable = self._redos.pop() with self._pausereceiver(): try: ...
java
public static void runIntoJATSync(final String runnableName, final Runnable runnable, final long... timeout) { runIntoJATSync(new JrbReferenceRunnable(runnableName, runnable), timeout); }
python
def get_serializer( self, action_kwargs: Dict=None, *args, **kwargs) -> Serializer: """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_seria...
java
private static void failFastOnIncompatibleSubclass(Class<?> clazz) { while (clazz != DynamoDBMapper.class) { Class<?>[] classOverride = new Class<?>[] { Class.class, Map.class }; Class<?>[] nameOverride = new Class<?>[] { ...
java
public void statementClosed(javax.sql.StatementEvent event) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) Tr.event(this, tc, "statementClosed", "Notification of statement closed received from the JDBC driver", AdapterUtil.toString(even...
python
def read_file(fpath): """Reads a file within package directories.""" with io.open(os.path.join(PATH_BASE, fpath)) as f: return f.read()
python
def remove_local_zip(self): """ Remove our local zip file. """ if self.stage_config.get('delete_local_zip', True): try: if os.path.isfile(self.zip_path): os.remove(self.zip_path) if self.handler_path and os.path.isfile(self...
java
public static CrsTo createCrsTo(String crsName) { String nameToUse = crsName == null ? "EPSG:4326" : crsName; CrsTo result = new CrsTo(); NamedCrsPropertyTo property = new NamedCrsPropertyTo(); property.setName(nameToUse); result.setProperties(property); return result; ...
python
def deallocate(self): """Releases all resources.""" if self._domain is not None: domain_delete(self._domain, self.logger) if self._network is not None: self._network_delete() if self._storage_pool is not None: self._storage_pool_delete() if sel...
java
public Goal goal(String name, Project project) { return goal(name, project, null); }
python
def _post_process_apply(self, result_data, axis, try_scale=True): """Recompute the index after applying function. Args: result_data: a BaseFrameManager object. axis: Target axis along which function was applied. Returns: A new PandasQueryCompiler. ""...
python
def _log_prior_gradients(self): """evaluate the gradients of the priors""" if self.priors.size == 0: return 0. x = self.param_array ret = np.zeros(x.size) #compute derivate of prior density [np.put(ret, ind, p.lnpdf_grad(x[ind])) for p, ind in self.priors.item...
python
def _get_xlabel(self): """ Determines the xlabel based on the underlying data structure """ # Return user-specified label if self.xlabel: return self.xlabel # Label for coefficients if hasattr(self.estimator, "coef_"): if self.relative: ...
java
public double getValue(int index, double x, double y, double z) { double sum = 0; for (int i = 0; i < count_basis; i++) if (C.matrix[i][index] != 0d) sum += C.matrix[i][index] * basis.getValue(i, x, y, z); return sum; }
java
void registerCatch(DiagnosticPosition pos, int startpc, int endpc, int handler_pc, int catch_type) { char startpc1 = (char)startpc; char endpc1 = (char)endpc; char handler_pc1 = (char)handler_pc; if (startpc1 == startp...
python
def decide(self, package): # type: (Package) -> None """ Adds an assignment of package as a decision and increments the decision level. """ # When we make a new decision after backtracking, count an additional # attempted solution. If we backtrack multiple times in a row...
python
def string(self, *args): """ return string stored in node """ data = self.bytes(*args) if data is not None: return data.rstrip(b"\x00").decode('utf-8')
java
public static synchronized void initialize( int myHostId, CatalogContext catalogContext, boolean isRejoin, boolean forceCreate, HostMessenger messenger, List<Pair<Integer, Integer>> partitions) throws ExportManager.SetupException { ...
java
@Override public UpdateDeviceStatusResult updateDeviceStatus(UpdateDeviceStatusRequest request) { request = beforeClientExecution(request); return executeUpdateDeviceStatus(request); }
java
public void marshall(RefreshSchemasStatus refreshSchemasStatus, ProtocolMarshaller protocolMarshaller) { if (refreshSchemasStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(refreshSchemasStatu...
java
public static MutableDoubleTuple apply( DoubleTuple t0, DoubleTuple t1, DoubleBinaryOperator op, MutableDoubleTuple result) { Utils.checkForEqualSize(t0, t1); result = DoubleTuples.validate(t0, result); int n = t0.getSize(); for (int i=0; i<n; i++) ...
python
def add_debugged_source_file(self, debugged_source_file): """Add a DebuggedSourceFile proto.""" # TODO(cais): Should the key include a host name, for certain distributed # cases? key = debugged_source_file.file_path self._source_file_host[key] = debugged_source_file.host self._source_file_last...
java
public static boolean areEqual(Object value1, Object value2) { return ((value1 == null) && (value2 == null)) || // (isNaN(value1) && isNaN(value2)) || // ((value1 != null) && value1.equals(value2)); }
python
def ReleaseProcessedFlow(self, flow_obj): """Releases a flow that the worker was processing to the database.""" key = (flow_obj.client_id, flow_obj.flow_id) next_id_to_process = flow_obj.next_request_to_process request_dict = self.flow_requests.get(key, {}) if (next_id_to_process in request_dict and...
java
public static void extractHouseholderRow( ZMatrixRMaj A , int row , int col0, int col1 , double u[], int offsetU ) { int indexU = (offsetU+col0)*2; u[indexU] = 1; u[indexU+1] = 0; int index...