language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Pure GP createPath(AStarNode<ST, PT> startPoint, PT endPoint, List<AStarNode<ST, PT>> closeList) { int idx; ST segment; PT point; AStarNode<ST, PT> node; GP path = null; final CloseComparator<ST, PT> cComparator = new CloseComparator<>(); node = newAStarNode(endPoint, Double.NaN, Double.NaN, null); i...
java
protected void applyDrawerWithHeader() { setType(SideNavType.DRAWER_WITH_HEADER); applyBodyScroll(); if (isShowOnAttach()) { Scheduler.get().scheduleDeferred(() -> { pushElement(getHeader(), 0); pushElement(getMain(), 0); }); } ...
python
def _decrypt_ciphertext(cipher): ''' Given a block of ciphertext as a string, and a gpg object, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out. ''' try: cipher = salt.utils.stringutils.to_uni...
python
def snow(im, voxel_size=1, boundary_faces=['top', 'bottom', 'left', 'right', 'front', 'back'], marching_cubes_area=False): r""" Analyzes an image that has been partitioned into void and solid regions and extracts the void and solid phase geometry as well as network connectivity. P...
python
def request(self, method, resource, all_pages=False, **kwargs): """ Makes a request to the given endpoint. Keyword arguments are passed to the :meth:`~requests.request` method. If the content type of the response is JSON, it will be decoded automatically and a dictionary will be ...
java
@Override public CommerceAvailabilityEstimate fetchByPrimaryKey( Serializable primaryKey) { Serializable serializable = entityCache.getResult(CommerceAvailabilityEstimateModelImpl.ENTITY_CACHE_ENABLED, CommerceAvailabilityEstimateImpl.class, primaryKey); if (serializable == nullModel) { return null; } ...
python
def _count_values(self): """Return dict mapping relevance level to sample index""" indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]} return indices
java
private void checkAndValidateParameters(ConfigProperty configProperty) { LOGGER.entering(configProperty); try { switch (configProperty) { case SELENDROID_SERVER_START_TIMEOUT: case SELENDROID_EMULATOR_START_TIMEOUT: { // Selendroid takes timeoutEmulato...
java
public static Container create(Map<String, Object> params) throws EasyPostException { return create(params, null); }
java
@Override public ListResolverRulesResult listResolverRules(ListResolverRulesRequest request) { request = beforeClientExecution(request); return executeListResolverRules(request); }
java
@Override public PutRemediationConfigurationsResult putRemediationConfigurations(PutRemediationConfigurationsRequest request) { request = beforeClientExecution(request); return executePutRemediationConfigurations(request); }
python
def shutdown(self): """shutdown connection""" if self.verbose: print(self.socket.getsockname(), 'xx', self.peername) try: self.socket.shutdown(socket.SHUT_RDWR) except IOError as err: assert err.errno is _ENOTCONN, "unexpected IOError: %s" % err ...
java
public static void throww(Throwable e, String msg) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new JKException(msg, e); }
python
def on_step_end(self, step, logs={}): """ Save weights at interval steps during training """ self.total_steps += 1 if self.total_steps % self.interval != 0: # Nothing to do. return filepath = self.filepath.format(step=self.total_steps, **logs) if self.ver...
java
@Nullable public <T> T getUnique(final URI property, final Class<T> valueClass, @Nullable final T defaultValue) { try { final T value = getUnique(property, valueClass); return value == null ? defaultValue : value; } catch (final IllegalStateException ex) { ...
python
def get_cache_key(path): """ Create a cache key by concatenating the prefix with a hash of the path. """ # Python 2/3 support for path hashing try: path_hash = hashlib.md5(path).hexdigest() except TypeError: path_hash = hashlib.md5(path.encode('utf-8')).hexdigest() return set...
java
public boolean deleteAsync() throws ExecutionException, InterruptedException { // [START deleteAsync] Future<Boolean> future = metric.deleteAsync(); // ... boolean deleted = future.get(); if (deleted) { // the metric was deleted } else { // the metric was not found } // [END ...
java
public Stoichiometry combineWith(Stoichiometry other) { Set<SubunitCluster> combinedClusters = new LinkedHashSet<>(); combinedClusters.addAll(this.orderedClusters); combinedClusters.addAll(other.orderedClusters); Stoichiometry combinedStoichiometry; if (this.strategy == StringOverflowStrategy.CUSTOM) { co...
java
protected void completeSnapshot(Snapshot snapshot) { Assert.notNull(snapshot, "snapshot"); snapshots.put(snapshot.index(), snapshot); if (currentSnapshot == null || snapshot.index() > currentSnapshot.index()) { currentSnapshot = snapshot; } // Delete old snapshots if necessary. if (!stor...
python
def resize_bilinear_nd(t, target_shape): """Bilinear resizes a tensor t to have shape target_shape. This function bilinearly resizes a n-dimensional tensor by iteratively applying tf.image.resize_bilinear (which can only resize 2 dimensions). For bilinear interpolation, the order in which it is applied does no...
python
def _Request(global_endpoint_manager, request, connection_policy, requests_session, path, request_options, request_body): """Makes one http request using the requests module. :param _GlobalEndpointManager global_endpoint_manager: :param dict request: contains the resourceType, operationType, endpoi...
java
public void addRecord(String key, long l) throws TarMalformatException, IOException { addRecord(key, Long.toString(l)); }
java
@SuppressWarnings("unchecked") public String tokenAsString(Comparable tokenAsComparable) { ByteBuffer bb = tokenType.decompose(tokenAsComparable); Token token = tokenFactory.fromByteArray(bb); return tokenFactory.toString(token); }
python
def smith_waterman_similarity(s1, s2, match=5, mismatch=-5, gap_start=-5, gap_continue=-1, norm="mean"): """Smith-Waterman string compar...
python
def _get_id(self): """Construct and return the identifier""" return ''.join(map(str, filter(is_not_None, [self.Prefix, self.Name])))
python
def do_init( dev=False, requirements=False, allow_global=False, ignore_pipfile=False, skip_lock=False, system=False, concurrent=True, deploy=False, pre=False, keep_outdated=False, requirements_dir=None, pypi_mirror=None, ): """Executes the init functionality.""" f...
python
def _get_instance(self): """ Return the instance matching the running_instance_id. """ try: instance = self.compute.virtual_machines.get( self.running_instance_id, self.running_instance_id, expand='instanceView' ) except Exc...
python
def update(self, callback=None, errback=None, **kwargs): """ Update monitor configuration. Pass a list of keywords and their values to update. """ if not self.data: raise MonitorException('monitor not loaded') def success(result, *args): self.data...
java
public void marshall(ActivityFailedEventDetails activityFailedEventDetails, ProtocolMarshaller protocolMarshaller) { if (activityFailedEventDetails == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(a...
python
def generate_megaman_manifold(sampling=2, nfolds=2, rotate=True, random_state=None): """Generate a manifold of the megaman data""" X, c = generate_megaman_data(sampling) for i in range(nfolds): X = np.hstack([_make_S_curve(x) for x in X.T]) if rotate: rand ...
python
def make_header(self, locale, catalog): """Populate header with correct data from top-most locale file.""" return { "po-revision-date": self.get_catalogue_header_value(catalog, 'PO-Revision-Date'), "mime-version": self.get_catalogue_header_value(catalog, 'MIME-Version'), ...
python
def create_chunk(buf): """Create a chunk for the HTTP "chunked" transfer encoding.""" chunk = [] chunk.append(s2b('{:X}\r\n'.format(len(buf)))) chunk.append(buf) chunk.append(b'\r\n') return b''.join(chunk)
java
public String md5Base64Digest(String signature) { byte[] bytes = md5Digest(signature.getBytes()); return new String(Base64.encodeBase64(bytes)); }
python
def data_filler_detailed_registration(self, number_of_rows, db): '''creates and fills the table with detailed regis. information ''' try: detailed_registration = db data_list = list() for i in range(0, number_of_rows): post_det_reg = { ...
python
async def set_webhook(self, url: base.String, certificate: typing.Union[base.InputFile, None] = None, max_connections: typing.Union[base.Integer, None] = None, allowed_updates: typing.Union[typing.List[base.String], None] = None) -> base.Bool...
java
@Override protected void decode(ChannelHandlerContext paramChannelHandlerContext, WebSocketFrame paramINBOUND_IN, List<Object> paramList) throws Exception { if(paramINBOUND_IN instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame msg=(BinaryWebSocketFrame)paramINBOUND_IN; ByteBuf data = msg.content()...
java
public static boolean sendHttpResponse( boolean isSuccess, HttpExchange exchange, byte[] response) { int returnCode = isSuccess ? HttpURLConnection.HTTP_OK : HttpURLConnection.HTTP_UNAVAILABLE; try { exchange.sendResponseHeaders(returnCode, response.length); } catch (IOException e) {...
python
def get_common_register(start, end): """Get the register most commonly used in accessing structs. Access to is considered for every opcode that accesses memory in an offset from a register:: mov eax, [ebx + 5] For every access, the struct-referencing registers, in this case `ebx`, are cou...
python
def check_expired_activation(self, activation_key): """ Check if ``activation_key`` is still valid. Raises a ``self.model.DoesNotExist`` exception if key is not present or ``activation_key`` is not a valid string :param activation_key: String containing the secret ...
python
def set_attribute(self, name, value): """Sets attribute's name and value""" self.attribute_name = name self.attribute = value
java
public static void checkIsSpec(Class<?> clazz) { if (isSpec(clazz)) return; if (Specification.class.isAssignableFrom(clazz)) throw new InvalidSpecException( "Specification '%s' was not compiled properly (Spock AST transform was not run); try to do a clean build" ).withArgs(clazz.getName()); th...
python
def filter_by_pattern(self, pattern): """Filter the Data Collection based on a list of booleans. Args: pattern: A list of True/False values. Typically, this is a list with a length matching the length of the Data Collections values but it can also be a patte...
python
def detect_xid_devices(self): """ For all of the com ports connected to the computer, send an XID command '_c1'. If the device response with '_xid', it is an xid device. """ self.__xid_cons = [] for c in self.__com_ports: device_found = False ...
python
def get_firmware_version(self, cb=None): """ This method retrieves the Firmata firmware version :param cb: Reference to a callback function :returns:If no callback is specified, the firmware version """ task = asyncio.ensure_future(self.core.get_firmware_version()) ...
python
def run_script(scriptfile): '''run a script file''' try: f = open(scriptfile, mode='r') except Exception: return mpstate.console.writeln("Running script %s" % scriptfile) sub = mp_substitute.MAVSubstitute() for line in f: line = line.strip() if line == "" or line....
python
def _from_dict(cls, _dict): """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} if 'sentence_id' in _dict: args['sentence_id'] = _dict.get('sentence_id') else: raise ValueError( 'Required property \'sentence_id\' not presen...
java
public void marshall(DisassociateSkillGroupFromRoomRequest disassociateSkillGroupFromRoomRequest, ProtocolMarshaller protocolMarshaller) { if (disassociateSkillGroupFromRoomRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { ...
java
public void transform(float source[], int sourceOffset, float destination[], int destOffset, int numberOfPoints) { //TODO performance can be improved by removing the safety to the destination array float result[] = source == destination ? new float[numberOfPoints * 2] : destination; ...
python
def exec_args(args, in_data='', chdir=None, shell=None, emulate_tty=False): """ Run a command in a subprocess, emulating the argument handling behaviour of SSH. :param list[str]: Argument vector. :param bytes in_data: Optional standard input for the command. :param bool emulate_...
java
public static <T, L extends List<T>> L sortThis(L list, final Predicate2<? super T, ? super T> predicate) { return Iterate.sortThis(list, new Comparator<T>() { public int compare(T o1, T o2) { if (predicate.accept(o1, o2)) { ...
java
@UiHandler("m_startTime") void onStartTimeChange(CmsDateBoxEvent event) { if (handleChange() && !event.isUserTyping()) { m_controller.setStartTime(event.getDate()); } }
python
def add_process(self, tgt, args=None, kwargs=None, name=None): ''' Create a processes and args + kwargs This will deterimine if it is a Process class, otherwise it assumes it is a function ''' if args is None: args = [] if kwargs is None: ...
python
def from_data(source): """Infers a table/view schema from its JSON representation, a list of records, or a Pandas dataframe. Args: source: the Pandas Dataframe, a dictionary representing a record, a list of heterogeneous data (record) or homogeneous data (list of records) from which to i...
python
def generate(env): """Add Builders and construction variables for ar to an Environment.""" SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['SHLINK'] = '$LINK' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS /dll') env['_SHLINK_TARGETS'] = windowsShlinkTargets...
python
def set_prop(self, prop, value, ef=None): """ set attributes values :param prop: :param value: :param ef: :return: """ if ef: # prop should be restricted to n_decoys, an int, the no. of decoys corresponding to a given FPF. # value i...
python
def _get_resolved_dictionary(self, input_dict, key, resolved_value, remaining): """ Resolves the function and returns the updated dictionary :param input_dict: Dictionary to be resolved :param key: Name of this intrinsic. :param resolved_value: Resolved or updated value for this...
java
public String resolvePackageName (final String packageName) { String resolvedPackageName = packageName; if (resolvedPackageName != null && resolvedPackageName.startsWith ("*")) { resolvedPackageName = getParserPackage () + resolvedPackageName.substring (1); if (resolvedPackageName.startsWith (...
java
public boolean isRenderLabel() { return (boolean) (Boolean) getStateHelper().eval(PropertyKeys.renderLabel, net.bootsfaces.component.ComponentUtils.isRenderLabelDefault()); }
python
def rollout(self, batch_info: BatchInfo, model: RlModel, number_of_steps: int) -> Rollout: """ Calculate env rollout """ assert not model.is_recurrent, "Replay env roller does not support recurrent models" accumulator = TensorAccumulator() episode_information = [] # List of dictionarie...
java
public static byte[] decodeString(String encoded) { return encoded == null ? null : Base64.getDecoder().decode(encoded); }
python
def create(self, name=None, description=None): """Creates a new, empty dataset. Parameters ---------- name : str, optional The name of the dataset. description : str, optional The description of the dataset. Returns ------- reque...
python
def __load_child_classes(self, ac: AssetClass): """ Loads child classes/stocks """ # load child classes for ac db = self.__get_session() entities = ( db.query(dal.AssetClass) .filter(dal.AssetClass.parentid == ac.id) .order_by(dal.AssetClass.sortorder)...
python
def _fix_dependendent_params(self, i): """Unhide keys if necessary after removing the param at index *i*.""" if not self.params[i].showkey: for param in self.params[i + 1:]: if not param.showkey: param.showkey = True
java
public void setMFR(Integer newMFR) { Integer oldMFR = mfr; mfr = newMFR; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.GPARC__MFR, oldMFR, mfr)); }
python
def code(self, text, lang=None): """Add a code block.""" # WARNING: lang is discarded currently. with self.paragraph(stylename='code'): lines = text.splitlines() for line in lines[:-1]: self._code_line(line) self.linebreak() sel...
java
public static <E> PCollection<E> partition(PCollection<E> collection, Dataset<E> dataset) { return partition(collection, dataset, -1); }
python
def _verify_tile_versions(self, hw): """Verify that the tiles have the correct versions """ for tile, expected_tile_version in self._tile_versions.items(): actual_tile_version = str(hw.get(tile).tile_version()) if expected_tile_version != actual_tile_version: ...
python
def is_structured_array(obj): """ Returns True if the given object is a Numpy Structured Array. Parameters ---------- obj: instance The object to test whether or not is a Numpy Structured Array. """ if isinstance(obj, np.ndarray) and hasattr(obj, 'dtype'): if obj.dtype.names...
java
public void registerProviders(Collection<?> theProviders) { Validate.noNullElements(theProviders, "theProviders must not contain any null elements"); myProviderRegistrationMutex.lock(); try { if (!myStarted) { for (Object provider : theProviders) { ourLog.info("Registration of provider [" + provider....
java
@BetaApi public final Operation insertSubnetwork(String region, Subnetwork subnetworkResource) { InsertSubnetworkHttpRequest request = InsertSubnetworkHttpRequest.newBuilder() .setRegion(region) .setSubnetworkResource(subnetworkResource) .build(); return insertSubn...
java
private boolean rvaIsWithin(VirtualLocation loc) { long endpoint = loc.from() + loc.size(); return virtualAddress >= loc.from() && virtualAddress < endpoint; }
java
private static void startIfNotStarted(String serviceName) { synchronized (queueNames) { if (!queueNames.contains(serviceName)) { //以下是新建一个rabbitmq客户端 try { IMqConsumerClient.singleton.consumeStaticQueue(TransferQueueUtil.getTransferQueue(serviceNam...
python
def create_scaffold(project_name): """ create scaffold with specified project name. """ if os.path.isdir(project_name): logger.log_warning(u"Folder {} exists, please specify a new folder name.".format(project_name)) return logger.color_print("Start to create new project: {}".format(proj...
java
@Override public Long getPropertyLong(Class<?> aClass, String key) { return getPropertyLong(new StringBuilder(aClass.getName()).append(".").append(key).toString()); }
python
def liquid_precipitation_depth(self, value=999.0): """Corresponds to IDD Field `liquid_precipitation_depth` Args: value (float): value for IDD Field `liquid_precipitation_depth` Unit: mm Missing value: 999.0 if `value` is None it will not be c...
java
protected String replace(String template, String placeholder, String value) { if (template == null) return null; if ((placeholder == null) || (value == null)) return template; while (true) { int index = template.indexOf(placeholder); if (index...
python
def fetch_googl(): """Returns stock prices for Google company.""" yql = YQL('GOOGL', '2014-01-01', '2014-01-10') for item in yql: print item.get('date'), item.get('price') yql.select('GOOGL', '2014-01-01', '2014-01-10') for item in yql: print item.get('date'), item.get('price')
java
public void save() throws FileNotFoundException { PrintStream p = new PrintStream(file); p.println(COMMENT_PREFIX + "Saved ELKI settings. First line is title, remaining lines are parameters."); for (Pair<String, ArrayList<String>> settings : store) { p.println(settings.first); for (String str : ...
java
public static Bbox intersection(Bbox one, Bbox two) { if (!intersects(one, two)) { return null; } else { double minx = two.getX() > one.getX() ? two.getX() : one.getX(); double maxx = two.getMaxX() < one.getMaxX() ? two.getMaxX() : one.getMaxX(); double miny = two.getY() > one.getY() ? two.getY() : one....
java
private void parseParenthesizedExpr() throws TTXPathException { consume(TokenType.OPEN_BR, true); if (!(mToken.getType() == TokenType.CLOSE_BR)) { parseExpression(); } consume(TokenType.CLOSE_BR, true); }
python
def descr_prototype(self, buf): """ Describe the prototype ("head") of the function. """ state = "define" if self.blocks else "declare" ret = self.return_value args = ", ".join(str(a) for a in self.args) name = self.get_reference() attrs = self.attributes ...
python
def get_free_memory(): """Return current free memory on the machine. Currently supported for Windows, Linux, MacOS. :returns: Free memory in MB unit :rtype: int """ if 'win32' in sys.platform: # windows return get_free_memory_win() elif 'linux' in sys.platform: # li...
python
def append_segment(self, apdu): """This function appends the apdu content to the end of the current APDU being built. The segmentAPDU is the context.""" if _debug: SSM._debug("append_segment %r", apdu) # check for no context if not self.segmentAPDU: raise RuntimeErr...
python
def modes_off(self): """Turn off any mode user may be in.""" bm = self.fitsimage.get_bindmap() bm.reset_mode(self.fitsimage)
java
public void setResult(Object result) { if (resultSent) { throw new RuntimeException("You can only set the result once."); } this.resultSent = true; Channel channel = this.channel.get(); if (channel == null) { log.warn("The client is no longer connec...
java
public GetListOfFeaturedPlaylistsRequest.Builder getListOfFeaturedPlaylists() { return new GetListOfFeaturedPlaylistsRequest.Builder(accessToken) .setDefaults(httpManager, scheme, host, port); }
java
public <T> Optional<T> getValueAsObject(final String name, final TypeToken<T> type) { try { final Optional<String> raw = getValueAsString(name); if (raw.isPresent()) { //noinspection unchecked return Optional.ofNullable((T) objectM...
java
private TempBlockMeta createBlockMetaInternal(long sessionId, long blockId, BlockStoreLocation location, long initialBlockSize, boolean newBlock) throws BlockAlreadyExistsException { // NOTE: a temp block is supposed to be visible for its own writer, unnecessary to acquire // block lock here sin...
java
public static auditsyslogpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{ auditsyslogpolicy_lbvserver_binding obj = new auditsyslogpolicy_lbvserver_binding(); obj.set_name(name); auditsyslogpolicy_lbvserver_binding response[] = (auditsyslogpolicy_lbvserver_binding[]) obj.get_re...
java
public void addIndexes(StorableInfo<S> info, Direction defaultDirection) { for (int i=info.getIndexCount(); --i>=0; ) { add(info.getIndex(i).setDefaultDirection(defaultDirection)); } }
python
def content_types(self): """ Provides access to content type management methods for content types of an environment. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/content-types :return: :class:`EnvironmentContentTypesProxy <cont...
java
public static String getCryptoAlgorithm(String password) { if (null == password) { return null; } String algorithm = null; String data = password.trim(); if (data.length() >= 2) { if ('{' == data.charAt(0)) { int end = data.indexOf('}', 1)...
java
@SuppressWarnings("unchecked") private void addToRootMap(String propertyPath, Object propertyValue) throws PropertyException { // split propertyPath String[] propertyKeyArray = propertyPath.split("\\."); // load configMap from disk Map<String, Object> configMap = load(); // if simple token add too root ...
python
def uriref_startswith_iriref(v1: URIRef, v2: Union[str, ShExJ.IRIREF]) -> bool: """ Determine whether a :py:class:`rdflib.URIRef` value starts with the text of a :py:class:`ShExJ.IRIREF` value """ return str(v1).startswith(str(v2))
python
def Decorate(cls, class_name, member, parent_member): """Decorates a member with @typecheck. Inherit checks from parent member.""" if isinstance(member, property): fget = cls.DecorateMethod(class_name, member.fget, parent_member) fset = None if member.fset: fset = cls.DecorateMethod(cl...
java
public ServiceFuture<Void> addAsync(JobAddParameter job, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(addWithServiceResponseAsync(job), serviceCallback); }
python
async def exit_rescue_mode( self, wait: bool = False, wait_interval: int = 5): """ Exit rescue mode. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ try: self._data =...
python
def instruction_LSR_memory(self, opcode, ea, m): """ Logical shift right memory location """ r = self.LSR(m) # log.debug("$%x LSR memory value $%x >> 1 = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) #...
python
def return_msg(self, reply_code, reply_text, exchange, routing_key): ''' Return a failed message. Not named "return" because python interpreter can't deal with that. ''' args = Writer() args.write_short(reply_code).\ write_shortstr(reply_text).\ w...
python
def update_with(self, name, security_info): """ insert/clear authorizations :param str name: name of the security info to be updated :param security_info: the real security data, token, ...etc. :type security_info: **(username, password)** for *basicAuth*, **token** in str for *oauth2*,...