language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def add_command(self, command):
"""Adds a :class:`.Command` or its subclasses into the internal list
of commands.
This is usually not called, instead the :meth:`~.GroupMixin.command` or
:meth:`~.GroupMixin.group` shortcut decorators are used instead.
Parameters
--------... |
java | @Override
public IFeatureLinkingCandidate getLinkingCandidate(/* @Nullable */ XAbstractFeatureCall featureCall) {
if (featureCall == null)
return null;
IResolvedTypes delegate = getDelegate(featureCall);
return delegate.getLinkingCandidate(featureCall);
} |
python | def drawGrid( self, painter ):
"""
Draws the rulers for this scene.
:param painter | <QPainter>
"""
# draw the minor grid lines
pen = QPen(self.borderColor())
painter.setPen(pen)
painter.setBrush(self.baseColor())
... |
python | def get_valid_error(x1, x2=-1):
"""
Function that validates:
* x1 is possible to convert to numpy array
* x2 is possible to convert to numpy array (if exists)
* x1 and x2 have the same length (if both exist)
"""
# just error
if type(x2) == int and x2 == -1:
try:
... |
java | public <V> V execute(RedisCallback<V> cb) {
Jedis jedis = jedisPool.getResource();
boolean success = true;
try {
return cb.execute(jedis);
} catch (JedisException e) {
success = false;
if (jedis != null) {
jedisPool.returnBrokenResource... |
java | public String tileTable(String table) {
StringBuilder output = new StringBuilder();
TileDao tileDao = geoPackage.getTileDao(table);
output.append("Table Name: " + tileDao.getTableName());
long minZoom = tileDao.getMinZoom();
long maxZoom = tileDao.getMaxZoom();
output.append("\nMin Zoom: " + minZoom);
ou... |
python | def SetupPrometheusExportsFromConfig():
"""Exports metrics so Prometheus can collect them."""
port = getattr(settings, 'PROMETHEUS_METRICS_EXPORT_PORT', None)
port_range = getattr(
settings, 'PROMETHEUS_METRICS_EXPORT_PORT_RANGE', None)
addr = getattr(settings, 'PROMETHEUS_METRICS_EXPORT_ADDRESS... |
python | def pop_one(self, priority=None):
"""
NON-BLOCKING POP IN QUEUE, IF ANY
"""
with self.lock:
if not priority:
priority = self.highest_entry()
if self.closed:
return [THREAD_STOP]
elif not self.queue:
retur... |
python | def deactivate_boost_by_name(self, zone_name):
"""
Deactivate boost by the name of the zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return self.deactivate_boost_by_id(zone["zoneId"]) |
java | public void download(GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream)
throws IOException {
Preconditions.checkArgument(downloadState == DownloadState.NOT_STARTED);
requestUrl.put("alt", "media");
if (directDownloadEnabled) {
updateStateAndNotifyListener(DownloadStat... |
java | public void pushUlterior(String key, Object value) {
assertArgumentNotNull("key", key);
assertArgumentNotNull("value", value);
postcard.pushUlterior(key, value);
} |
python | def _DisableNetworkManager(self, interfaces, logger):
"""Disable network manager management on a list of network interfaces.
Args:
interfaces: list of string, the output device names enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
... |
java | @Override
protected void saxpyi(long N, double alpha, INDArray X, DataBuffer pointers, INDArray Y) {
cblas_saxpyi((int) N, (float) alpha, (FloatPointer) X.data().addressPointer(), (IntPointer) pointers.addressPointer(),
(FloatPointer) Y.data().addressPointer());
} |
python | async def sendmail(
self, sender, recipients, message, mail_options=None, rcpt_options=None
):
"""
Performs an entire e-mail transaction.
Example:
>>> try:
>>> with SMTP() as client:
>>> try:
>>> r = client.sen... |
python | def retrieve_outputs(self):
""" Declare the outputs of the algorithms as attributes: x_final,
y_final, metrics.
"""
metrics = {}
for obs in self._observers['cv_metrics']:
metrics[obs.name] = obs.retrieve_metrics()
self.metrics = metrics |
java | public boolean goTo(MonthAdapter.CalendarDay day, boolean animate, boolean setSelected, boolean forceScroll) {
// Set the selected day
if (setSelected) {
mSelectedDay.set(day);
}
mTempDay.set(day);
int minMonth = mController.getStartDate().get(Calendar.MONTH);
... |
python | def r_get_numbers(matchgroup, num):
"""A helper function which can be used similarly to fscanf(fid,'%f',num) to extract num arguments from the regex iterator"""
res = []
for i in range(num):
res.append(float(matchgroup.next().group()))
return np.array(res) |
python | def disallowed_table(*tables):
"""Returns True if a set of tables is in the blacklist or, if a whitelist is set,
any of the tables is not in the whitelist. False otherwise."""
# XXX: When using a black or white list, this has to be done EVERY query;
# It'd be nice to make this as fast as possible. In g... |
java | public static void setTo(Configured from, Object... targets){
for(Object target:targets){
if(target instanceof Configured){
Configured configuredTarget = (Configured) target;
configuredTarget.setConf(from.getConf());
}
}
} |
java | @Nonnull
public IMPLTYPE arg (@Nonnegative final int nIndex, @Nonnull final IJSExpression aArgument)
{
ValueEnforcer.notNull (aArgument, "Argument");
m_aArgs.add (nIndex, aArgument);
return _thisAsT ();
} |
java | public void addInjectionTarget(Class<?> injectionType,
String targetName,
String targetClassName)
throws InjectionException
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.... |
python | def present(name, DomainName,
ElasticsearchClusterConfig=None,
EBSOptions=None,
AccessPolicies=None,
SnapshotOptions=None,
AdvancedOptions=None,
Tags=None,
region=None, key=None, keyid=None, profile=None,
ElasticsearchVersio... |
java | public SipServletRequestImpl getMatchingRequest(
SipServletRequestImpl request) {
if(request.getMethod().equals(Request.ACK)) {
Iterator<TransactionApplicationData> ongoingTransactions = proxy.getTransactionMap().values().iterator();
// Issue 1837 http://code.google.com/p/mobicents/issues/detail?id=1837
/... |
python | def __update_cursor_info(self):
""" Map the mouse to the 1-d position within the line graph. """
if not self.delegate: # allow display to work without delegate
return
if self.__mouse_in and self.__last_mouse:
pos_1d = None
axes = self.__axes
lin... |
python | def entrez(db, acc):
"""
search entrez using specified database
and accession
"""
c1 = ['esearch', '-db', db, '-query', acc]
c2 = ['efetch', '-db', 'BioSample', '-format', 'docsum']
p1 = Popen(c1, stdout = PIPE, stderr = PIPE)
p2 = Popen(c2, stdin = p1.stdout, stdout = PIPE, stderr = PIP... |
java | private boolean isAuthorized(EventHandler handler, Map<String,String> headers)
throws AuthorizationException {
// Exclude unless it is REST or SOAP (i.e. HTTP)
if (!Listener.METAINFO_PROTOCOL_REST.equals(headers.get(Listener.METAINFO_PROTOCOL)) && !Listener.METAINFO_PROTOCOL_SOAP.equals(headers.get(... |
python | def objectMD5(obj):
'''Get md5 of an object'''
if hasattr(obj, 'target_name'):
return obj.target_name()
try:
return textMD5(pickle.dumps(obj))
except:
return '' |
python | def bridge(filename):
""" Add hash to filename for cache invalidation.
Uses gulp-buster for cache invalidation. Adds current file hash as url arg.
"""
if not hasattr(settings, 'BASE_DIR'):
raise Exception("You must provide BASE_DIR in settings for bridge")
file_path = getattr(settings, 'BUS... |
python | def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model)
self.do_import('error_model', self.options.worker_class.error_model)
self.do_import('callback', ... |
python | def _get_index(self, beacon_config, label):
'''
Return the index of a labeled config item in the beacon config, -1 if the index is not found
'''
indexes = [index for index, item in enumerate(beacon_config) if label in item]
if not indexes:
return -1
else:
... |
java | public JSONObject deleteByContract(String contractId, String ts) throws JSONException {
return oClient.delete("/team/v3/snapshots/contracts/" + contractId + "/" + ts);
} |
python | def getContactEditorialParameters(self, person):
"""
Yield L{LiveForm} parameters to edit each contact item of each contact
type for the given person.
@type person: L{Person}
@return: An iterable of two-tuples. The first element of each tuple
is an L{IContactType} p... |
java | @Override
public void convertOperationParameter(PathAddress address, String attributeName, ModelNode attributeValue, ModelNode operation, TransformationContext context) {
convertAttribute(address, attributeName, attributeValue, context);
} |
java | public Observable<Page<GenericResourceInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<GenericResourceInner>>, Page<GenericResourceInner>>() {
@Override
public Page<GenericReso... |
java | public void stop() {
if (cacheDispatcher != null) {
cacheDispatcher.quit();
addMarker(EVENT_CACHE_DISPATCHER_STOP, cacheDispatcher);
}
for (NetworkDispatcher netDispatcher : networkDispatchers) {
if (netDispatcher != null) {
netDispatcher.quit... |
java | private AFTPClient actionPutFile() throws IOException, PageException {
required("remotefile", remotefile);
required("localfile", localfile);
AFTPClient client = getClient();
Resource local = ResourceUtil.toResourceExisting(pageContext, localfile);// new File(localfile);
// if(failifexists && local.exists()) throw... |
java | private int[][] generateWorkingKey(byte[] key, boolean forEncryption) {
int keyLen = key.length;
if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) {
throw new IllegalArgumentException("Key length not 128/192/256 bits.");
}
int KC = keyLen >>> 2;
ROUNDS = KC + 6; ... |
java | public void setDefCharID(String newDefCharID) {
String oldDefCharID = defCharID;
defCharID = newDefCharID;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.CPC__DEF_CHAR_ID, oldDefCharID, defCharID));
} |
python | def move_window(win_key, bbox):
"""
CommandLine:
# List windows
wmctrl -l
# List desktops
wmctrl -d
# Window info
xwininfo -id 60817412
python -m utool.util_ubuntu XCtrl.move_window joncrall 0+1920,680,400,600,400
... |
python | def getLinkInterfaces(self, node1, node2):
'''
Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given).
'''
linkdata = self.getLink(node1,node2)
return linkdata[node... |
python | def fly(self):
"""
Generate doc tree.
"""
dst_dir = Path(self.conf_file).parent.abspath
package_dir = Path(dst_dir, self.package.shortname)
# delete existing api document
try:
if package_dir.exists():
shutil.rmtree(package_dir.abspath... |
python | def _write_data(self, symbols, err_recs, nr_recordings,
total_error_count, percentages, time_max_list):
"""Write all obtained data to a file.
Parameters
----------
symbols : list of tuples (String, non-negative int)
List of all symbols with the count of r... |
python | def set_recursion_limit(limit):
"""Set the Python recursion limit."""
if limit < minimum_recursion_limit:
raise CoconutException("--recursion-limit must be at least " + str(minimum_recursion_limit))
sys.setrecursionlimit(limit) |
python | def write_catalog(filename, catalog, fmt=None, meta=None, prefix=None):
"""
Write a catalog (list of sources) to a file with format determined by extension.
Sources must be of type :class:`AegeanTools.models.OutputSource`,
:class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.IslandSo... |
python | def selectAll( self ):
"""
Selects all the items in the scene.
"""
currLayer = self._currentLayer
for item in self.items():
layer = item.layer()
if ( layer == currLayer or not layer ):
item.setSelected(True) |
java | public int getExpandedTypeID(int nodeHandle)
{
// %REVIEW% This _should_ only be null if someone asked the wrong DTM about the node...
// which one would hope would never happen...
int id=makeNodeIdentity(nodeHandle);
if(id==NULL)
return NULL;
return _exptype(id);
} |
java | public static String getRecurlySignature(String privateJsKey, Long unixTime, String nonce, List<String> extraParams) {
// Mandatory parameters shared by all signatures (as per spec)
extraParams = (extraParams == null) ? new ArrayList<String>() : extraParams;
extraParams.add(String.format(PARAMET... |
python | def request(self, path, method='GET', params=None, type=REST_TYPE):
"""Builds a request, gets a response and decodes it."""
response_text = self._get_http_client(type).request(path, method, params)
if not response_text:
return response_text
response_json = json.loads(respon... |
java | public String transform(CharSequence text,
byte inParaLevel, Order inOrder,
byte outParaLevel, Order outOrder,
Mirroring doMirroring, int shapingOptions)
{
if (text == null || inOrder == null || outOrder == null || doMirroring == null) {
throw new IllegalArgum... |
java | @BetaApi
public final Operation insertNodeTemplate(
ProjectRegionName region, NodeTemplate nodeTemplateResource) {
InsertNodeTemplateHttpRequest request =
InsertNodeTemplateHttpRequest.newBuilder()
.setRegion(region == null ? null : region.toString())
.setNodeTemplateResourc... |
python | def parse(self, content):
"""Parse raw response content for a list of remote artifact cache URLs.
:API: public
"""
if self.format == 'json_map':
try:
return assert_list(json.loads(content.decode(self.encoding))[self.index])
except (KeyError, UnicodeDecodeError, ValueError) as e:
... |
python | def as_salesforce(self, compiler, connection):
"""
Return the SQL version of the where clause and the value to be
substituted in. Return '', [] if this node matches everything,
None, [] if this node is empty, and raise EmptyResultSet if this
node can't match anything.
"""... |
java | public static final String[] parseURLs(Tree config, String name, String[] defaultURLs) {
Tree urlNode = config.get(name);
List<String> urlList;
if (urlNode == null) {
return defaultURLs;
} else if (urlNode.isPrimitive()) {
urlList = new ArrayList<>();
String[] urls = urlNode.asString().split(","... |
java | Table findUserTableForIndex(Session session, String name,
String schemaName) {
Schema schema = (Schema) schemaMap.get(schemaName);
HsqlName indexName = schema.indexLookup.getName(name);
if (indexName == null) {
return null;
}
re... |
python | def deploy(remote, assets_to_s3):
""" To DEPLOY your application """
header("Deploying...")
if assets_to_s3:
for mod in get_deploy_assets2s3_list(CWD):
_assets2s3(mod)
remote_name = remote or "ALL"
print("Pushing application's content to remote: %s " % remote_name)
hosts =... |
java | public boolean detect(Predicate<Row> predicate) {
Row row = new Row(this);
while (row.hasNext()) {
if (predicate.test(row.next())) {
return true;
}
}
return false;
} |
java | public void disconnect() {
if (!connected) {
return;
}
try {
socket.close();
} catch (IOException e) {
LOG.debug("I/O exception when closing socket", e);
}
this.connected = false;
} |
java | public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {
org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(
currentModule.groupId, currentModule.artifactId);
Map<org.jfrog.buil... |
python | def _self_signed(cert):
"""
Determines if a certificate is self-signed
:param cert:
An asn1crypto.x509.Certificate object to check
:return:
A boolean - True if the certificate is self-signed, False otherwise
"""
self_signed = cert.self_signed
if self_signed == 'yes':
... |
python | def parser_from_buffer(cls, fp):
"""Construct YamlParser from a file pointer."""
yaml = YAML(typ="safe")
return cls(yaml.load(fp)) |
python | def set(self, key, value):
"""
Set a value in the database.
:param str key: Key to set the value for
:param value: Any JSON-serializable value to be set
"""
serialized = json.dumps(value)
self.cursor.execute('select data from kv where key=?', [key])
exis... |
java | public void attributeDecl(
String arg0,
String arg1,
String arg2,
String arg3,
String arg4)
throws SAXException
{
m_handler.attributeDecl(arg0, arg1, arg2, arg3, arg4);
} |
java | public Set<String> absentKeysOrValues() {
return underlyingMap.entrySet()
.stream()
.filter(LinkedOptionalMap::keyOrValueIsAbsent)
.map(Entry::getKey)
.collect(Collectors.toCollection(LinkedHashSet::new));
} |
python | def routine_import(self):
"""
Dynamically import routines as defined in ``routines/__init__.py``.
The command-line argument ``--routine`` is defined in ``__cli__`` in
each routine file. A routine instance will be stored in the system
instance with the name being all lower case.
... |
python | def _list_machines(self):
"""
Request a list of all added machines.
Populates self._machines dict with mist.client.model.Machine instances
"""
try:
req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines')
machines = req.get().json()
... |
python | def get_daemon_stats(self, details=False):
"""Increase the stats provided by the Daemon base class
:return: stats dictionary
:rtype: dict
"""
# Call the base Daemon one
res = super(Broker, self).get_daemon_stats(details=details)
res.update({'name': self.name, 't... |
java | public <T> T addMaybeStartManagedInstance(T o, Stage stage) throws Exception
{
addMaybeStartHandler(new AnnotationBasedHandler(o), stage);
return o;
} |
python | def finalize( self, already_done=None ):
"""Finalize our values (recursively) taken from our children"""
if already_done is None:
already_done = {}
if already_done.has_key( self ):
return True
already_done[self] = True
self.filter_children()
childr... |
python | def retract(self, e, a, v):
""" redact the value of an attribute
"""
ta = datetime.datetime.now()
ret = u"[:db/retract %i :%s %s]" % (e, a, dump_edn_val(v))
rs = self.tx(ret)
tb = datetime.datetime.now() - ta
print cl('<<< retracted %s,%s,%s in %sms' % (e,a,v, tb.microseconds/1000.0), 'cyan'... |
java | public void setValuesForIn(String values, String name, Map<String, Object> map) {
getMapHelper().setValuesForIn(values, name, map);
} |
java | @Override
public RandomAccessStream openFileRandomAccess() throws IOException
{
if (_isWindows && isAux())
throw new FileNotFoundException(_file.toString());
return new FileRandomAccessStream(new RandomAccessFile(getFile(), "rw"));
} |
java | public static <T> void writeJson(T obj, File file) {
StringWriter writer = new StringWriter();
try {
objectMapper.writeValue(writer, obj);
Files.write(file.toPath(), writer.toString().getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
python | def ofp_instruction_from_str(ofproto, action_str):
"""
Parse an ovs-ofctl style action string and return a list of
jsondict representations of OFPInstructionActions, which
can then be passed to ofproto_parser.ofp_instruction_from_jsondict.
Please note that this is for making transition from ovs-ofc... |
java | public String info() {
CodeScript codeScript = (CodeScript) entityDao.get(CodeScript.class, getInt("codeScriptId"));
put("codeScript", codeScript);
return forward();
} |
java | @Override
public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown,
Supplier<String> msgSupplier) {
super.logp(level, sourceClass, sourceMethod, thrown, maskPassword(msgSupplier));
} |
java | public final void sendMail(final Email email)
throws MailException {
if (validate(email)) {
try {
// create new wrapper for each mail being sent (enable sending multiple emails with one mailer)
final MimeEmailMessageWrapper messageRoot = new MimeEmailMessageWrapper();
// fill and send wrapped ... |
python | def plot_station_mapping(
target_latitude,
target_longitude,
isd_station,
distance_meters,
target_label="target",
): # pragma: no cover
""" Plots this mapping on a map."""
try:
import matplotlib.pyplot as plt
except ImportError:
raise ImportError("Plotting requires matpl... |
python | def somatic_batches(items):
"""Group items into somatic calling batches (tumor-only or tumor/normal).
Returns batches, where a data item may be in pairs, and somatic and non_somatic
(which are the original list of items).
"""
non_somatic = []
somatic = []
data_by_batches = defaultdict(list)... |
java | private boolean hasComplexKeys(TabularType pType) {
List<String> indexes = pType.getIndexNames();
CompositeType rowType = pType.getRowType();
for (String index : indexes) {
if ( ! (rowType.getType(index) instanceof SimpleType)) {
return true;
}
}
... |
java | public void setSliderPosition(float x, float y) {
if (x > 255) {
x = 255;
}
if (x < 0) {
x = 0;
}
if (y > 255) {
y = 255;
}
if (y < 0) {
y = 0;
}
x -= 7;
y -= 7;
m_sli... |
java | public static Set<String> getWeaveSourceFiles( String[] weaveDirs )
throws MojoExecutionException
{
Set<String> result = new HashSet<String>();
for ( int i = 0; i < weaveDirs.length; i++ )
{
String weaveDir = weaveDirs[i];
if ( FileUtils.fileExists( weaveDir ... |
java | public void setTabindex(int tabindex)
{
_state.registerAttribute(AbstractHtmlState.ATTR_GENERAL, HtmlConstants.TABINDEX, Integer.toString(tabindex));
} |
python | def next(self, type=None):
""" Returns the next word in the sentence with the given type.
"""
i = self.index + 1
s = self.sentence
while i < len(s):
if type in (s[i].type, None):
return s[i]
i += 1 |
python | def _get_description(self, args: Tuple, kwargs: Dict[str, Any]) -> Dict[str, Any]:
"""Return the dictionary to be sent to the queue."""
return {
'id': uuid1().hex,
'args': args,
'kwargs': kwargs,
'module': self._module_name,
'function': self.f.... |
java | private void registerListeners() {
protocol.registerAppendHandler(this::append);
protocol.registerBackupHandler(this::backup);
protocol.registerConsumeHandler(this::consume);
protocol.registerResetConsumer(this::reset, threadContext);
} |
python | def index_open(self, index):
'''
Opens the speicified index.
http://www.elasticsearch.org/guide/reference/api/admin-indices-open-close.html
> ElasticSearch().index_open('my_index')
'''
request = self.session
url = 'http://%s:%s/%s/_open' % (self.host, self.port, ... |
java | public DoubleBuffer put (DoubleBuffer src) {
if (src == this) {
throw new IllegalArgumentException();
}
if (src.remaining() > remaining()) {
throw new BufferOverflowException();
}
double[] doubles = new double[src.remaining()];
src.get(doubles);
... |
python | def remove_diagnostic(self, name):
""" Removes a diagnostic from the ``process.diagnostic`` dictionary
and also delete the associated process attribute.
:param str name: name of diagnostic quantity to be removed
:Example:
Remove diagnostic variable 'icelat' from energy ... |
java | @Override
@SuppressWarnings("unchecked")
public T answer(@Nonnull final InvocationOnMock invocation) throws Throwable {
final Class<?> methodReturnType = invocation.getMethod().getReturnType();
if (type.isAssignableFrom(methodReturnType) // fluent api methods
|| Query.class.isAssignableFrom(methodRetu... |
java | public void marshall(ParameterHistory parameterHistory, ProtocolMarshaller protocolMarshaller) {
if (parameterHistory == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(parameterHistory.getName(), NAM... |
python | def date_browser_selection_changed(self, selected_indexes):
"""
Called to handle selection changes in the tree widget.
This method should be connected to the on_selection_changed event. This method builds a list
of keys represented by all selected items. It then provides dat... |
python | def GetMethodConfig(self, method):
"""Returns service cached method config for given method."""
method_config = self._method_configs.get(method)
if method_config:
return method_config
func = getattr(self, method, None)
if func is None:
raise KeyError(metho... |
python | def set(self, response: 'requests.Response') -> None:
"""Adds a response to the cache.
Args:
response: response from ESI
Returns:
None
"""
self.data[response.url] = SavedEndpoint(
response.json(),
self._get_expiration(response.hea... |
java | public String removeExtraneousCharacters(final String fragment,
final CleaningContext context) {
if (fragment == null || fragment.length() == 0) {
return fragment;
}
Matcher matcher;
Matcher alphanumLiteralMatcher;
StringBuilder cleanedLine = new StringBui... |
java | public static <E> Distribution<E> goodTuringSmoothedCounter(Counter<E> counter, int numberOfKeys) {
// gather count-counts
int[] countCounts = getCountCounts(counter);
// if count-counts are unreliable, we shouldn't be using G-T
// revert to laplace
for (int i = 1; i <= 10; i++) {
if (... |
java | public static nshttpparam get(nitro_service service) throws Exception{
nshttpparam obj = new nshttpparam();
nshttpparam[] response = (nshttpparam[])obj.get_resources(service);
return response[0];
} |
python | def main(argv=None):
''' Runs the program and handles command line options '''
parser = get_parser()
# Parse arguments and run the function
global args
args = parser.parse_args(argv)
args.func() |
python | def get_expected_bindings(self):
"""Query the neutron DB for SG->switch interface bindings
Bindings are returned as a dict of bindings for each switch:
{<switch1>: set([(intf1, acl_name, direction),
(intf2, acl_name, direction)]),
<switch2>: set([(intf1, acl_na... |
python | def serialize(self,
node: SchemaNode,
appstruct: Union[PotentialDatetimeType,
ColanderNullType]) \
-> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if not appstru... |
java | @Override
public JsonNode evaluate(List<JsonNode> evaluatedArgs) throws InvalidTypeException {
JsonNode arg = evaluatedArgs.get(0);
if (arg.isTextual()) {
return getStringLength(arg);
} else if (arg.isArray() || arg.isObject()) {
return new IntNode(arg.size());
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.