language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _parse_entry(self, cols): """Parses an entry's row and adds the result to py:attr:`entries`. Parameters ---------- cols: :class:`bs4.ResultSet` The list of columns for that entry. """ rank, name, vocation, *values = [c.text.replace('\xa0', ' ').strip() fo...
java
public Integer toInteger() { Integer value; value = Integer.valueOf(this.isNeg ? Integer.parseInt(this.param)*-1 : Integer.parseInt(this.param)); return value; }
java
@SuppressWarnings("unchecked") public static <T> T getBean(BeanManager bm, Class<T> clazz, Annotation... annotations) { Bean<?> bean; if (annotations != null) { bean = bm.getBeans(clazz, annotations).iterator().next(); } else { bean =...
python
def _insert(self, docs, ordered=True, check_keys=True, manipulate=False, write_concern=None, op_id=None, bypass_doc_val=False, session=None): """Internal insert helper.""" if isinstance(docs, abc.Mapping): return self._insert_one( docs, ordered...
java
private boolean compareAndSet(final State current, final State next) { if (state.compareAndSet(current, next)) { return true; } parkNanos(1); // back-off return false; }
python
def diff(s1, s2): """ Return a normalised Levenshtein distance between two strings. Distance is normalised by dividing the Levenshtein distance of the two strings by the max(len(s1), len(s2)). Examples: >>> text.diff("foo", "foo") 0 >>> text.diff("foo", "fooo") 1 ...
python
def _compute_bgid(self, bg=None): """Return a unique identifier for the background data""" if bg is None: bg = self._bgdata if isinstance(bg, qpimage.QPImage): # Single QPImage if "identifier" in bg: return bg["identifier"] else: ...
java
public DescribeEnvironmentsRequest withEnvironmentIds(String... environmentIds) { if (this.environmentIds == null) { setEnvironmentIds(new java.util.ArrayList<String>(environmentIds.length)); } for (String ele : environmentIds) { this.environmentIds.add(ele); } ...
java
BlockCrcInfoWritable getNextRecord() throws IOException { // By calling getBucketIdForNextRecord(), we make sure the next field // to read is the next record (if there is any record left in the file) // Also, by checking the return value, we know whether we've finished // the file. if (moveToNextRec...
java
public void openLockReportForElement(final CmsContainerPageElementPanel element) { CmsLockReportDialog.openDialogForResource(null, element.getStructureId(), new Command() { public void execute() { m_controller.reloadElements(new String[] {element.getStructureId().toString()}); ...
java
@SuppressWarnings("all") public static Method findMethod(Class<?> type, String methodName, Object... arguments) { for (Method method : type.getDeclaredMethods()) { if (method.getName().equals(methodName)) { Class<?>[] parameterTypes = method.getParameterTypes(); if (ArrayUtils.nullSafeLe...
python
def batting_stats_bref(season=None): """ Get all batting stats for a set season. If no argument is supplied, gives stats for current season to date. """ if season is None: season = datetime.datetime.today().strftime("%Y") season = str(season) start_dt = season + '-03-01' #opening day...
python
def generate_local_port(): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63.""" global _PREVIOUS_LOCAL_PORT if _PREVIOUS_LOCAL_PORT is None: try: with contextlib.closing(socket.socket(getattr(socket, 'AF_NETLINK', -1), socket.SOCK_RAW)) as s: s.bind((...
java
public long skip(long n) throws IOException { if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"skip", "skip"); } if ( total >= limit ) { if (TraceComponent.isAnyTracingEnable...
python
def secure(self, func): '''Enforce authentication on a given method/verb and optionally check a given permission ''' if isinstance(func, basestring): return self._apply_permission(Permission(RoleNeed(func))) elif isinstance(func, Permission): return self._...
python
def find_by_filename(filename=None, engines=None): """ Find a list of template engine classes to render template `filename`. :param filename: Template file name (may be a absolute/relative path) :param engines: Template engines :return: A list of engines support given template file """ if ...
java
public <T> TypeParserBuilder registerParser(Class<T> targetType, Parser<T> parser) { if (parser == null) { throw new NullPointerException(makeNullArgumentErrorMsg("parser")); } if (targetType == null) { throw new NullPointerException(makeNullArgumentErrorMsg("targetType")...
java
public static RandomICAutomatonGenerator<Boolean, Void> forDFA() { return new RandomICAutomatonGenerator<Boolean, Void>().withStateProperties(Random::nextBoolean); }
java
private void regenerate() { try { ArrayList list = new ArrayList(); for (int i=0;i<sprites.size();i++) { list.add(sprites.elementAt(i)); } int b = ((Integer) border.getValue()).intValue(); Sheet sheet = pack.packImages(list, twidth, theight, b, null); sheetPanel.setImage(sheet); ...
python
def configure(conf, channel=False, group=False, fm_integration=False): """Guide user to set up the bot, saves configuration at `conf`. # Arguments conf (str): Path where to save the configuration file. May contain `~` for user's home. channel (Optional[bool]): Configure a channel. ...
python
def handle_args(): """ Default values are defined here. """ default_database_name = dbconfig.testdb_corpus_url.database parser = argparse.ArgumentParser( prog=os.path.basename(__file__), formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('dbname', ...
java
public java.util.List<ByoipCidr> getByoipCidrs() { if (byoipCidrs == null) { byoipCidrs = new com.amazonaws.internal.SdkInternalList<ByoipCidr>(); } return byoipCidrs; }
python
def upgrade(): """Upgrade database.""" current_date = datetime.utcnow() # Add 'created' and 'updated' columns to RemoteAccount _add_created_updated_columns('oauthclient_remoteaccount', current_date) # Add 'created' and 'updated' columns to RemoteToken _add_created_updated_columns('oauthclient_...
java
public EpollServerSocketChannelConfig setTcpMd5Sig(Map<InetAddress, byte[]> keys) { try { ((EpollServerSocketChannel) channel).setTcpMd5Sig(keys); return this; } catch (IOException e) { throw new ChannelException(e); } }
java
public static Type resolveLastTypeParameter(Type genericContext, Class<?> supertype) throws IllegalStateException { Type resolvedSuperType = Types.getSupertype(genericContext, Types.getRawType(genericContext), supertype); checkState(resolvedSuperType instanceof ParameterizedType, "could no...
python
def set_fluxinfo(self): """ Uses list of known flux calibrators (with models in CASA) to find full name given in scan. """ knowncals = ['3C286', '3C48', '3C147', '3C138'] # find scans with knowncals in the name sourcenames = [self.sources[source]['source'] for source in self.so...
python
def get_route(self, route_id): """ Gets specified route. Will be detail-level if owned by authenticated user; otherwise summary-level. https://strava.github.io/api/v3/routes/#retreive :param route_id: The ID of route to fetch. :type route_id: int :rtype: :clas...
java
@Override public String encode() throws IOException { FastStringWriter fsw = new FastStringWriter(); try { fsw.write(super.encode()); if (this.type != null) { fsw.write(",\"type\":\"" + this.type + "\""); } ChartUtils.writeDataValue(...
java
private boolean scheduleRolloutGroup(final JpaRollout rollout, final JpaRolloutGroup group) { final long targetsInGroup = rolloutTargetGroupRepository.countByRolloutGroup(group); final long countOfActions = actionRepository.countByRolloutAndRolloutGroup(rollout, group); long actionsLeft = targe...
java
public final void validate(Method method) throws ValidationException { final Validator<CalendarComponent> validator = getValidator(method); if (validator != null) { validator.validate(this); } else { throw new ValidationException("Unsupported method: " + method); ...
python
def to_shcoeffs(self, nmax=None, normalization='4pi', csphase=1): """ Return the spherical harmonic coefficients using the first n Slepian coefficients. Usage ----- s = x.to_shcoeffs([nmax]) Returns ------- s : SHCoeffs class instance ...
python
def list_functions(awsclient): """List the deployed lambda functions and print configuration. :return: exit_code """ client_lambda = awsclient.get_client('lambda') response = client_lambda.list_functions() for function in response['Functions']: log.info(function['FunctionName']) ...
python
def parse_frames(filename): ''' quick and dirty eprime txt file parsing - doesn\'t account for nesting **Example usage**:: for frame in neural.eprime.parse_frames("experiment-1.txt"): trial_type = frame['TrialSlide.Tag'] trial_rt = float(frame['TrialSlide.RT']) ...
java
public void destroy() { ByteArrayPool.returnByteArray(_buf); _byteBuffer=null; _reader=null; _lineBuffer=null; _encoding=null; }
python
def set_env_info(self, env_state=None, env_id=None, episode_id=None, bump_past=None, fps=None): """Atomically set the environment state tracking variables. """ with self.cv: if env_id is None: env_id = self._env_id if env_state is None: env...
java
static void configure(final File f) { new Configurator() { @Override void withConfigurator(JoranConfigurator configurator) throws JoranException { configurator.doConfigure(f); } }.configure(); }
java
@Override public final V merge( K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { if (value == null) throw new NullPointerException(); if (remappingFunction == null) throw new NullPointerException(); long hash; retu...
python
def snmp_server_user_username(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") user = ET.SubElement(snmp_server, "user") username = ET.SubElement(user, "...
java
public ArrayList<OvhTask> serviceName_domainTrust_POST(String serviceName, String activeDirectoryIP, String dns1, String dns2, String domain) throws IOException { String qPath = "/horizonView/{serviceName}/domainTrust"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Ob...
java
private Path gotLeftTopArrowPath() { Path path = new Path(); int diameter = cSize * 2; // 左上角圆角起点 path.moveTo(aWidth, cSize); RectF rectF = new RectF(aWidth, 0, aWidth + diameter, diameter); path.arcTo(rectF, 180, 90); // 右上角圆角起点 path.lineTo(mWidth - cSize...
python
def _create_extn_pattern(single_extn_symbols): """Helper initialiser method to create the regular-expression pattern to match extensions, allowing the one-char extension symbols provided by single_extn_symbols.""" # There are three regular expressions here. The first covers RFC 3966 # format, where ...
java
public void sFeature1Init(int y, int cp) { ftype = STAT_FEATURE1; idx = -1; this.y = y; this.cp = cp; val = 1; wgt = 0.0; strId = "s1_" + Integer.toString(y) + "_" + Integer.toString(cp); }
java
private StreamSource getSource(String pURI) throws IOException, MalformedURLException { if (pURI != null && pURI.indexOf("://") < 0) { // If local, get as stream return new StreamSource(getResourceAsStream(pURI)); } // ...else, create from URI string ...
python
def _line_to_entry(self,line): """parse the line into entries and keys""" f = line.rstrip().split("\t") """ 'chrom' 'chromStart' 'chromEnd' 'name' 'score' 'strand' 'thickStart' 'thickEnd' 'itemRgb' 'blockCount' 'blockSizes' 'blockStarts' """ return Bed...
python
def delete_message_type(self, message_type_id): """ Delete an existing message type :param message_type_id: is the id of the message type the client wants to delete """ self._validate_uuid(message_type_id) url = "/notification/v1/message-t...
java
@SuppressWarnings("unchecked") public static <T extends View> T get(View view, int id) { SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(); if (viewHolder == null) { viewHolder = new SparseArray<View>(); view.setTag(viewHolder); } View childView...
python
def get_elt_projected_plots_color(self, zero_to_efermi=True, elt_ordered=None): """ returns a pylab plot object with one plot where the band structure line color depends on the character of the band (along different elements). Each element is associa...
java
public List<FacesConfigAttributeType<FacesConfigRendererType<T>>> getAllAttribute() { List<FacesConfigAttributeType<FacesConfigRendererType<T>>> list = new ArrayList<FacesConfigAttributeType<FacesConfigRendererType<T>>>(); List<Node> nodeList = childNode.get("attribute"); for(Node node: nodeList) ...
python
def delete_permissions(self, grp_name, resource): """Removes permissions from the group for the given resource. Args: grp_name (string): Name of group. resource (intern.resource.boss.BossResource): Identifies which data model object to operate on. Raises: re...
java
public CreateInstanceResponse createInstance(CreateInstanceRequest request) throws BceClientException { checkNotNull(request, "request should not be null."); if (Strings.isNullOrEmpty(request.getClientToken())) { request.setClientToken(this.generateClientToken()); } ...
java
@Nullable public GeoLocation getGeoLocation() { Rational[] latitudes = getRationalArray(TAG_LATITUDE); Rational[] longitudes = getRationalArray(TAG_LONGITUDE); String latitudeRef = getString(TAG_LATITUDE_REF); String longitudeRef = getString(TAG_LONGITUDE_REF); // Make s...
java
public static String escape(String string, char escape, boolean isPath) { try { BitSet validChars = isPath ? URISaveEx : URISave; byte[] bytes = string.getBytes("utf-8"); StringBuilder out = new StringBuilder(bytes.length); for (int i = 0; i < bytes.length; i++) ...
java
public static List<Match> search(Match m, Pattern pattern) { assert pattern.getStartingClass().isAssignableFrom(m.get(0).getModelInterface()); return searchRecursive(m, pattern.getConstraints(), 0); }
java
@Override public List<CommerceCurrency> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
java
@SuppressWarnings("unchecked") // marshall from apache commons cli private void parse() throws ParseException { _argValues = new HashMap<Argument, String>(); _varargValues = new ArrayList<String>(); List<String> argList = _commandLine.getArgList(); int required = 0; boolean hasOptional = false; boolea...
python
def convert_to_str(data): """ Decodes data to the Python 3.x str (Python 2.x unicode) type. Decodes `data` to a Python 3.x ``str`` (Python 2.x ``unicode``). If it can't be decoded, it is returned as is. Unsigned integers, Python ``bytes``, and Numpy strings (``numpy.unicode_`` and ``numpy.bytes_``)...
python
async def get_supported_playback_functions( self, uri="" ) -> List[SupportedFunctions]: """Return list of inputs and their supported functions.""" return [ SupportedFunctions.make(**x) for x in await self.services["avContent"]["getSupportedPlaybackFunction"]( ...
python
def _do_include(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name): """ Implements @include, for @mixins """ funct, params, _ = name.partition('(') funct = funct.strip() funct = self.do_glob_math( funct, ...
python
def get_nearest_observation_site(self, latitude=None, longitude=None): """ This function returns the nearest Site to the specified coordinates that supports observations """ if longitude is None: print('ERROR: No longitude given.') return False if...
python
def senior_email_forward_view(request): """Add a forwarding address for graduating seniors.""" if not request.user.is_senior: messages.error(request, "Only seniors can set their forwarding address.") return redirect("index") try: forward = SeniorEmailForward.objects.get(user=request....
java
static <T> SettableSupplier<CompletableFuture<T>> settableSupplierOf(Supplier<CompletableFuture<T>> supplier) { return new SettableSupplier<CompletableFuture<T>>() { volatile boolean called; volatile CompletableFuture<T> value; @Override public CompletableFuture<T> get() { if (!call...
java
public String getDate(Date date, CmsDateTimeUtil.Format format) { return CmsDateTimeUtil.getDate(date, format); }
python
def ae_latent_softmax(latents_pred, latents_discrete_hot, vocab_size, hparams): """Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: ...
python
def rdcandump(filename, count=None, is_not_log_file_format=False, interface=None): """Read a candump log file and return a packet list count: read only <count> packets is_not_log_file_format: read input with candumps stdout format interfaces: return only packets from a specified interfa...
python
def write(self, b: bytes) -> None: """Add bytes to internal bytes buffer and if echo is True, echo contents to inner stream.""" if not isinstance(b, bytes): raise TypeError('a bytes-like object is required, not {}'.format(type(b))) if not self.std_sim_instance.pause_storage: ...
python
def _find_sources_with_paths(im, target, sources, polarity): """Get the subset of source nodes with paths to the target. Given a target, a list of sources, and a path polarity, perform a breadth-first search upstream from the target to find paths to any of the upstream sources. Parameters ----...
java
public static String ipForwardedFor() { String h = header("X-Forwarded-For"); return !Util.blank(h) ? h : remoteAddress(); }
python
def to_cortex(c): ''' to_cortex(c) yields a Cortex object if the argument c can be coerced to one and otherwise raises an error. An object can be coerced to a Cortex object if: * it is a cortex object * it is a tuple (subject, h) where subject is a subject object and h is a subject hemisp...
python
def prepare_data_keys(primary_master_key, master_keys, algorithm, encryption_context): """Prepares a DataKey to be used for encrypting message and list of EncryptedDataKey objects to be serialized into header. :param primary_master_key: Master key with which to generate the encryption data key :type pr...
python
def sum(context, key, value, multiplier=1): """ Adds the given value to the total value currently held in ``key``. Use the multiplier if you want to turn a positive value into a negative and actually substract from the current total sum. Usage:: {% sum "MY_TOTAL" 42 -1 %} {{ MY_TO...
python
def subseq(self, start_offset=0, end_offset=None): """ Return a subset of the sequence starting at start_offset (defaulting to the beginning) ending at end_offset (None representing the end, whih is the default) Raises ValueError if duration_64 is missing on any element "...
python
def users_create_or_update_many(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users#create-or-update-many-users" api_path = "/api/v2/users/create_or_update_many.json" return self.call(api_path, method="POST", data=data, **kwargs)
java
@Override @SuppressWarnings("unused") public String toJson() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeometryAdapterFactory.create()) .registerTypeAdapter(BoundingBox.class, new BoundingBoxTypeAdapter()) .registerTypeAdapterFactory(GeocodingAdapterFactory.create()) ....
java
public void setADJSTMNT(Integer newADJSTMNT) { Integer oldADJSTMNT = adjstmnt; adjstmnt = newADJSTMNT; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.SIA__ADJSTMNT, oldADJSTMNT, adjstmnt)); }
python
def get_dbg_brk_linux64(): ''' Return the current brk value in the debugged process (only x86_64 Linux) ''' # TODO this method is so weird, find a unused address to inject code not # the base address debugger = get_debugger() code = b'\x0f\x05' # syscall rax = debugger.get_reg("rax")...
java
@XmlElementDecl(namespace = "http://www.opengis.net/citygml/vegetation/1.0", name = "_GenericApplicationPropertyOfPlantCover") public JAXBElement<Object> create_GenericApplicationPropertyOfPlantCover(Object value) { return new JAXBElement<Object>(__GenericApplicationPropertyOfPlantCover_QNAME, Object.class,...
python
def upload_path(instance, filename): ''' Sanitize the user-provided file name, add timestamp for uniqness. ''' filename = filename.replace(" ", "_") filename = unicodedata.normalize('NFKD', filename).lower() return os.path.join(str(timezone.now().date().isoformat()), filename)
python
def user_absent(name, htpasswd_file=None, runas=None): ''' Make sure the user is not in the specified htpasswd file name User name htpasswd_file Path to the htpasswd file runas The system user to run htpasswd command with ''' ret = {'name': name, 'chang...
python
def update_cer(self, symbol, cer, account=None): """ Update the Core Exchange Rate (CER) of an asset :param str symbol: Symbol of the asset to publish feed for :param bitshares.price.Price cer: Core exchange Rate :param str account: (optional) the account to allow access ...
python
def _get_mpr_table(self, connection, partition): """ Returns name of the sqlite table who stores mpr data. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: str: Raises: ...
python
def _locate_element(dom, el_content, transformer=None): """ Find element containing `el_content` in `dom`. Use `transformer` function to content of all elements in `dom` in order to correctly transforming them to match them with `el_content`. Args: dom (obj): HTMLElement tree. el_co...
python
def download_package_to_sandbox(sandbox, package_url): """ Downloads an unzips a package to the sandbox :param sandbox: temporary directory name :param package_url: link to package download :returns: name of unzipped package directory """ response = requests.get(package_url) package_ta...
java
public PrimaryKey addComponents(KeyAttribute ... components) { if (components != null) { for (KeyAttribute ka: components) { InternalUtils.rejectNullInput(ka); this.components.put(ka.getName(), ka); } } return this; }
python
def json2pb(pb, js, useFieldNumber=False): ''' convert JSON string to google.protobuf.descriptor instance ''' for field in pb.DESCRIPTOR.fields: if useFieldNumber: key = field.number else: key = field.name if key not in js: continue if field.ty...
java
public static <E extends Comparable<? super E>> AbstractGroupExpression<E, SortedSet<E>> sortedSet(Expression<E> expression) { return GSet.createSorted(expression); }
python
def parse(readDataInstance): """Returns a L{DataDirectory}-like object. @type readDataInstance: L{ReadData} @param readDataInstance: L{ReadData} object to read from. @rtype: L{DataDirectory} @return: The L{DataDirectory} object containing L{consts.IMAGE_NUMBEROF...
java
public void verify(String pkg, File path, Configuration conf) { if (!path.isDirectory()) { throw new IllegalArgumentException(path.getAbsolutePath().concat(" is not a directory.")); } for (File file : path.listFiles()) { if (file.isDirectory()) { verify(combine(pkg, file.getName()), fil...
java
protected List<Expression> transformExpressions(List<? extends Expression> expressions, ExpressionTransformer transformer) { List<Expression> list = new ArrayList<Expression>(expressions.size()); for (Expression expr : expressions ) { list.add(transformer.transform(expr)); } ...
python
def num_feats(self): """ The number of features per time step in the corpus. """ if not self._num_feats: filename = self.get_train_fns()[0][0] feats = np.load(filename) # pylint: disable=maybe-no-member if len(feats.shape) == 3: # Then ther...
python
def read_single(db, collection, match_params=None): """ Wrapper for pymongo.find_one() :param db: db connection :param collection: collection to read data from :param match_params: a query that matches the documents to select :return: document ('_id' is excluded from resu...
java
public void registerLoaderIndicators(By... loaderIndicators) { for(By locator : loaderIndicators) { log.debug("Registered loader: " + locator); this.expectedGlobalConditions.add(new ExpectedWebElementCondition(locator)); } }
python
def add_element(self, element, col, row, cols=1, rows=1): """Adds the given element to the given position in the grid, with the given size. There is no limit to the number of elements that can be assigned to the same cell(s).""" # Update the number of rows and colums self.rows =...
java
public static void preparePeerEntitySamlEndpointContext(final RequestAbstractType request, final MessageContext outboundContext, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, ...
python
def to_xml(self): """ Returns a string containing the XML version of the Lifecycle configuration as defined by S3. """ s = '<LifecycleConfiguration>' for rule in self: s += rule.to_xml() s += '</LifecycleConfiguration>' return s
java
@NullSafe public static long count(Iterable<?> iterable) { return iterable instanceof Collection ? ((Collection) iterable).size() : count(iterable, (element) -> true); }
java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo); ButterKnife.bind(this); mCacheId = getIntent().getStringExtra(EXTRA_ID_CACHE); mDiskCacheSize = getIntent().getIntExtra(EXTRA_DISK_CACH...
python
def top(**kwargs): ''' Query |reclass| for the top data (states of the minions). ''' # If reclass is installed, __virtual__ put it onto the search path, so we # don't need to protect against ImportError: # pylint: disable=3rd-party-module-not-gated from reclass.adapters.salt import top as r...
java
public static void visitList(Manager manager, String pattern, Set<SimonType> types, SimonVisitor visitor) throws IOException { List<Simon> simons = new ArrayList<>(manager.getSimons(SimonPattern.create(pattern))); Collections.sort(simons, new Comparator<Simon>() { public int compare(Simon s1, Simon s2) { ...
python
def icohpvalue(self, spin=Spin.up): """ Args: spin: Spin.up or Spin.down Returns: icohpvalue (float) corresponding to chosen spin """ if not self.is_spin_polarized and spin == Spin.down: raise ValueError("The calculation was not performed with ...
java
public static int decompressBlockByS16(int[] outDecompBlock, int[] inCompBlock, int inStartOffsetInBits, int blockSize) { int inOffset = (inStartOffsetInBits + 31) >>> 5; int num, outOffset = 0, numLeft; for (numLeft = blockSize; numLeft > 0; numLeft -= nu...