language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public ModuleItem find(String name) {
if (children == null)
return null;
else
return (ModuleItem) children.get(name);
/*
* for(int i=0; i<children.size(); i++)
* {
* ModuleItem item = (ModuleItem)children.get(i);
* if(item.instance != ... |
java | protected void grow(int index) {
if ((index * literalSize) + (literalSize - 1) >= data.length()) {
int newSize = Math.max((index * literalSize) + defaultSize, 2 * data.length());
Slice newSlice = Slices.allocate(newSize);
newSlice.setBytes(0, data);
setData(newSlice);
}
} |
java | void readClass(ClassSymbol c) {
ClassType ct = (ClassType)c.type;
// allocate scope for members
c.members_field = new Scope(c);
// prepare type variable table
typevars = typevars.dup(currentOwner);
if (ct.getEnclosingType().hasTag(CLASS))
enterTypevars(ct.ge... |
python | def destination(globs, locator, distance, bearing):
"""Calculate destination from locations."""
globs.locations.destination(distance, bearing, locator) |
python | def organizations_show_many(self, external_ids=None, ids=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/organizations#show-many-organizations"
api_path = "/api/v2/organizations/show_many.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kw... |
java | private void setServerLayout(final List<CmsSite> sites) {
m_workplaceServerGroup = new CmsEditableGroup(m_serverLayout, new Supplier<Component>() {
public Component get() {
CmsWorkplaceServerWidget row = new CmsWorkplaceServerWidget(sites, null);
return row;
... |
python | def update_nodes(nodes,**kwargs):
"""
Update multiple nodes.
If new attributes are present, they will be added to the node.
The non-presence of attributes does not remove them.
%TODO:merge this with the 'update_nodes' functionality in the 'update_netework'
function, so we're not duplicating fun... |
python | def isglove(filepath):
""" Get the first word vector in a GloVE file and return its dimensionality or False if not a vector
>>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))
False
"""
with ensure_open(filepath, 'r') as f:
header_line = f.readline()
vector_line = f.readline(... |
java | public PagedList<NameIdentifierInner> listRecommendations(final DomainRecommendationSearchParameters parameters) {
ServiceResponse<Page<NameIdentifierInner>> response = listRecommendationsSinglePageAsync(parameters).toBlocking().single();
return new PagedList<NameIdentifierInner>(response.body()) {
... |
java | public final void configure(Object bean)
{
Objects.requireNonNull(bean);
Thread thread = Thread.currentThread();
ClassLoader loader = thread.getContextClassLoader();
/*
ContextConfig oldContext = ContextConfig.getCurrent();
try {
ContextConfig.setCurrent(new ContextConfig(... |
java | public JobProfile readJobProfile(JobID jobId) {
JobProfile jobProfile = null;
if (active) {
try {
FSDataInputStream dataIn = getJobInfoFile(jobId);
if (dataIn != null) {
readJobStatus(dataIn);
jobProfile = readJobProfile(dataIn);
dataIn.close();
}
... |
java | private void processResponse(Response response) {
// at this point a server response should contain a secure JSON with challenges
JSONObject jsonResponse = Utils.extractSecureJson(response);
JSONObject jsonChallenges = (jsonResponse == null) ? null : jsonResponse.optJSONObject(CHALLENGES_VALUE_N... |
python | def list_metrics(ctx):
"""List the available metrics."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
from wily.commands.list_metrics import list_metrics
list_metrics() |
java | static Map<String, Object> sumOfDelta(Map<String, Object> state, Map<String, Object> delta) {
InstanceKey instanceId = (InstanceKey) delta.get("InstanceKey");
if (instanceId == null) {
throw new RuntimeException("InstanceKey can not be null");
}
for (String key : delta.keySet... |
java | @Override public void onCreate() {
super.onCreate();
MainModule mainModule = new MainModule(this);
objectGraph = ObjectGraph.create(mainModule);
objectGraph.inject(this);
objectGraph.injectStatics();
} |
java | @Override
public void filter(ContainerRequestContext ctx) throws IOException {
String scheme = getValue(ctx.getHeaders(), "x-forwarded-proto");
String port = getValue(ctx.getHeaders(), "x-forwarded-port");
if (scheme == null && port == null)
return;
UriBuilder baseBuild... |
java | public static String toClause(List<String> packages) {
return Joiner.on(", ").skipNulls().join(packages);
} |
java | public static Boolean canAccess(String url) {
return ContextUtils.getAuthorizationEngine(ContextUtils.getRequest())
.check(url) == null;
} |
java | protected long parseLong( String value ) {
long factor = 1;
if (value.endsWith("K")) {
factor = KILO;
} else if (value.endsWith("M")) {
factor = MEGA;
} else if (value.endsWith("G")) {
factor = GIGA;
}
if (factor > 1) {
valu... |
python | def get_all_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... |
python | def save_artists(self, artists, filename="artist_lyrics", overwrite=False):
"""Save lyrics from multiple Artist objects as JSON object
:param artists: List of Artist objects to save lyrics from
:param filename: Name of output file (json)
:param overwrite: Overwrites preexisting file if T... |
java | private void configureH2cPipeline(ChannelPipeline pipeline) {
// Add handler to handle http2 requests without an upgrade
pipeline.addLast(new Http2WithPriorKnowledgeHandler(
interfaceId, serverName, serverConnectorFuture, this));
// Add http2 upgrade decoder and upgrade handler
... |
python | def hsl_to_rgb(arr):
"""
Converts HSL color array to RGB array
H = [0..360]
S = [0..1]
l = [0..1]
http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL
Returns R,G,B in [0..255]
"""
H, S, L = arr.T
H = (H.copy()/255.0) * 360
S = S.copy()/255.0
L = L.copy()/255.0
... |
python | def can_use_cache(self, target: Target) -> bool:
"""Return True if should attempt to load `target` from cache.
Return False if `target` has to be built, regardless of its cache
status (because cache is disabled, or dependencies are dirty).
"""
# if caching is disabled for t... |
java | public void setManagerGroup(String managerGroup) {
CmsGroup group = checkGroup(managerGroup);
if (group != null) {
m_project.setManagerGroupId(group.getId());
}
} |
java | @SuppressWarnings("deprecation")
protected Object createObject(Class<?> targetClass) throws ReflectiveOperationException {
Enhance en = targetClass.getAnnotation(Enhance.class);
boolean enhance = (en != null ? en.value() : this.enhance);
return enhance ? com.jfinal.aop.Enhancer.enhance(targetClass) : tar... |
python | def lms():
'''Install and start a Logitech Media Server (lms).
More infos:
* http://wiki.slimdevices.com/index.php/Logitech_Media_Server
* http://wiki.slimdevices.com/index.php/DebianPackage
* http://www.mysqueezebox.com/download
* XSqueeze on Kodi:
* http://kodi.wiki/view/Add-on:XSq... |
python | def clean_up(self):
"""
Close the I2C bus
"""
self.log.debug("Closing I2C bus for address: 0x%02X" % self.address)
self.bus.close() |
java | public FieldDeclaration getFieldNode(String name, String signature) {
for (EntityDeclaration node : type.getMembers()) {
if (node.getEntityType() == EntityType.FIELD) {
FieldDeclaration field = (FieldDeclaration) node;
if (field.getName().equals(name)
&& signature(field.getReturnTy... |
java | public static List<ExecutableElement> getSortedAnnotationMembers(TypeElement annotation) {
List<ExecutableElement> members = Lists.newArrayList(getMethods(annotation));
Collections.sort(members, (m1, m2) -> getName(m1).compareTo(getName(m2)));
return members;
} |
python | def tri_ttr(k, a):
"""
Custom TTR function.
Triangle distribution does not have an analytical TTR function, but because
of its non-smooth nature, a blind integration scheme will converge very
slowly. However, by splitting the integration into two divided at the
discontinuity in the derivative, ... |
python | def get_segment_summary_times(scienceFile, segmentName):
"""
This function will find the times for which the segment_summary is set
for the flag given by segmentName.
Parameters
-----------
scienceFile : SegFile
The segment file that we want to use to determine this.
segmentName : s... |
java | public static <T1, T2, T3, R> TriPredicate<T1, T2, T3> compose(Predicate<R> predicate, TriFunction<T1, T2, T3, R> function) {
dbc.precondition(predicate != null, "cannot compose function with a null predicate");
dbc.precondition(function != null, "cannot compose predicate with a null ternary function");... |
java | @Programmatic
public List<PublishedEvent> findRecentByUser(final String user) {
return repositoryService.allMatches(
new QueryDefault<>(PublishedEvent.class, "findRecentByUser", "user", user));
} |
java | public static String readString(Path targetPath, String charsetName) {
try {
return new String(Files.readAllBytes(targetPath),
Charset.forName(charsetName));
} catch (IOException e) {
return JMExceptionManager.handleExceptionAndReturnNull(log, e,
... |
python | async def play_tone(self, pin, tone_command, frequency, duration):
"""
This method will call the Tone library for the selected pin.
It requires FirmataPlus to be loaded onto the arduino
If the tone command is set to TONE_TONE, then the specified
tone will be played.
Els... |
python | def parse_from_calc(self):
"""
Parses the datafolder, stores results.
This parser for this simple code does simply store in the DB a node
representing the file of forces in real space
"""
from aiida.common.exceptions import InvalidOperation
from aiida.common impor... |
python | def pack_pointer(self, name):
"""Returns a pointer containing the value.
This only works for int32/uint32/utf-8..
"""
return self.parse("""
raise $_.TypeError('Can\\'t convert %(type_name)s to pointer: %%r' %% $in_)
""" % {"type_name": type(self).__name__}, in_=name)["in_"] |
python | def _CreateDatabase(self):
""" Create all database tables. """
goodlogging.Log.Info("DB", "Initialising new database", verbosity=self.logVerbosity)
with sqlite3.connect(self._dbPath) as db:
# Configuration tables
db.execute("CREATE TABLE Config ("
"Name TEXT UNIQUE NOT NULL, "... |
python | def add_group(group_name, system_group=False, gid=None):
"""Add a group to the system
Will log but otherwise succeed if the group already exists.
:param str group_name: group to create
:param bool system_group: Create system group
:param int gid: GID for user being created
:returns: The passw... |
python | def __get_percpu(self):
"""Update and/or return the per CPU list using the psutil library."""
# Never update more than 1 time per cached_time
if self.timer_percpu.finished():
self.percpu_percent = []
for cpu_number, cputimes in enumerate(psutil.cpu_times_percent(interval=... |
python | def getEncodableAttributes(self, obj, **kwargs):
"""
Returns a C{tuple} containing a dict of static and dynamic attributes
for C{obj}.
"""
attrs = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs)
if not self.exclude_sa_key:
# primary_key_from_inst... |
python | def wait_for_start(self):
"""
Wait for the container to start.
By default this will wait for the log lines matching the patterns
passed in the ``wait_patterns`` parameter of the constructor using an
UnorderedMatcher. For more advanced checks for container startup, this
m... |
python | def _setup_pyudev_monitoring(self):
"""
Setup the udev monitor.
"""
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
self.udev_observer = pyudev.MonitorObserver(monitor, self._udev_event)
self.udev_observer.start()
self.py3_wrapper... |
python | def setup_logging(default_path='logging.yaml', env_key='LOG_CFG'):
"""
Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
configs = yaml.safe_load(f.read(... |
java | public void undeploy(URL url) throws Throwable
{
if (url == null)
throw new IllegalArgumentException("Url is null");
if (!started)
throw new IllegalStateException("Container not started");
log.debugf("Undeploying: %s", url);
kernel.getMainDeployer().undeploy(url);
} |
python | def is_runnnig(self):
"""Determine whether hub server is running
:return:True or False
"""
resp = None
try:
resp = requests.get("http://%s:%s" %(self._ip, self._port))
if resp.status_code == 200:
return True
else:
... |
java | public static <T> T load(String path, TypeReference<T> typeReference) {
return load(path, typeReference, null, false);
} |
python | def fn_std(self, a, axis=None):
"""
Compute the standard deviation of an array, ignoring NaNs.
:param a: The array.
:return: The standard deviation of the array.
"""
return numpy.nanstd(self._to_ndarray(a), axis=axis) |
java | public static float[] getBoundingSize(GVRMesh mesh) {
final float [] dim = new float[3];
final float [] vertices = mesh.getVertices();
final int vsize = vertices.length;
float minx = Integer.MAX_VALUE;
float miny = Integer.MAX_VALUE;
float minz = Integer.MAX_VALUE;
... |
python | def segment(self, webvtt, output='', seconds=SECONDS, mpegts=MPEGTS):
"""Segments the captions based on a number of seconds."""
if isinstance(webvtt, str):
# if a string is supplied we parse the file
captions = WebVTT().read(webvtt).captions
elif not self._validate_webvtt... |
java | public String compile(final Collection<?> objs,
final InputStream templateStream) {
TemplateContainer tc = new DefaultTemplateContainer(templateStream);
closeStream(templateStream);
return compile(new ObjectDataProvider(tc, objs),
new TemplateData... |
java | public static SmartBinder from(Class<?> retType, String name, Class<?> type) {
return from(Signature.returning(retType).appendArg(name, type));
} |
python | def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or ex... |
java | protected byte[] getReportContents(CmsPublishJobFinished publishJob) throws CmsException {
byte[] result = null;
CmsDbContext dbc = m_dbContextFactory.getDbContext();
try {
result = m_driverManager.readPublishReportContents(dbc, publishJob.getPublishHistoryId());
} catch (Cm... |
python | def validation_error_try_to_accept(err, data, schema):
"""
Custom validation error handler which attempts alternative
validation
"""
if not isinstance(err, ValidationError):
abort(Response(err, status=HTTPStatus.BAD_REQUEST))
alernative_schema = dict(schema)
alernative_schema['prope... |
python | def setup_package():
"""Entry point."""
setup(
name='python-form',
version='0.2.2',
description='A package for communicating with FORM',
long_description=readme(),
author='Takahiro Ueda',
author_email='tueda@nikhef.nl',
url='https://github.com/tueda/python... |
python | def edges_to_coo(edges, count=None, data=None):
"""
Given an edge list, return a boolean scipy.sparse.coo_matrix
representing the edges in matrix form.
Parameters
------------
edges : (n,2) int
Edges of a graph
count : int
The total number of nodes in the graph
if None: co... |
java | public static MetaProperty hasProperty(Object self, String name) {
return InvokerHelper.getMetaClass(self).hasProperty(self, name);
} |
python | def _get_lp_matrix(spin_states, nodes, edges, offset_weight, gap_weight):
"""Creates an linear programming matrix based on the spin states, graph, and scalars provided.
LP matrix:
[spin_states, corresponding states of edges, offset_weight, gap_weight]
Args:
spin_states: Numpy array of spin ... |
python | def set_scene_velocity(self, scene_id, velocity):
"""reconfigure a scene by scene ID"""
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to set velocity on scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg... |
java | public Observable<ServiceResponse<Page<Resource>>> listResourceNextWithServiceResponseAsync(final String nextPageLink) {
return listResourceNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<Resource>>, Observable<ServiceResponse<Page<Resource>>>>() {
@Overri... |
python | def slugable(self):
"""
A node is slugable in following cases:
1 - Node doesn't have children.
2 - Node has children but its page doesn't have a regex.
3 - Node has children, its page has regex but it doesn't show it.
4 - Node has children, its page shows his regex and no... |
python | def image_to_url(image, colormap=None, origin='upper'):
"""Infers the type of an image argument and transforms it into a URL.
Parameters
----------
image: string, file or array-like object
* If string, it will be written directly in the output file.
* If file, it's content will be conve... |
python | def _create_network_interface(
self, ip_config_name, nic_name, public_ip, region,
resource_group_name, subnet, accelerated_networking=False
):
"""
Create a network interface in the resource group.
Attach NIC to the subnet and public IP provided.
"""
nic_confi... |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.BPG__PAGE_NAME:
return PAGE_NAME_EDEFAULT == null ? pageName != null : !PAGE_NAME_EDEFAULT.equals(pageName);
case AfplibPackage.BPG__TRIPLETS:
return triplets != null && !triplets.isEmpty();
}
return super.eIsS... |
python | def on_to_coordinates(self, speed, x_target_mm, y_target_mm, brake=True, block=True):
"""
Drive to (`x_target_mm`, `y_target_mm`) coordinates at `speed`
"""
assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates"
# stop moving
self.of... |
java | public void marshall(GetRateBasedRuleRequest getRateBasedRuleRequest, ProtocolMarshaller protocolMarshaller) {
if (getRateBasedRuleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getRateBas... |
python | async def run_script(self, script):
"""Execute the script and save results."""
script = os.linesep.join(['set -x', 'set +B', script, 'exit']) + os.linesep
self.proc.stdin.write(script.encode('utf-8'))
await self.proc.stdin.drain()
self.proc.stdin.close() |
java | public void copyDocumentationTo(/* @Nullable */ final EObject source, /* @Nullable */ JvmIdentifiableElement jvmElement) {
if(source == null || jvmElement == null)
return;
DocumentationAdapter documentationAdapter = new DocumentationAdapter() {
private boolean computed = false;
@Override
public Strin... |
java | private Type parseBracketedType(EnclosingScope scope) {
int start = index;
match(LeftBrace);
Type type = parseType(scope);
match(RightBrace);
return type;
} |
java | public static ShardedJedisPool newShardedJedisPool(JedisPoolConfig poolConfig,
String hostsAndPorts) {
return newShardedJedisPool(poolConfig, hostsAndPorts, null, Protocol.DEFAULT_TIMEOUT);
} |
python | def evaluate(self, data):
"""Evaluate the code needed to compute a given Data object."""
return 'PYTHONPATH="{runtime}" python3 -u -m resolwe.process {program} --slug {slug} --inputs {inputs}'.format(
runtime=PYTHON_RUNTIME_VOLUME,
program=PYTHON_PROGRAM_VOLUME,
slug=... |
java | public void setAgentProtocols(Set<String> protocols) {
Set<String> disabled = new TreeSet<>();
Set<String> enabled = new TreeSet<>();
for (AgentProtocol p : AgentProtocol.all()) {
String name = p.getName();
if (name != null && !p.isRequired()) {
// we want... |
python | def detect_scheme_and_format(source):
"""Detect scheme and format based on source and return as a tuple.
Scheme is a minimum 2 letters before `://` (will be lower cased).
For example `http` from `http://example.com/table.csv`
"""
# Scheme: stream
if hasattr(source, 'read'):
return ('s... |
java | @Nonnull
public FineUploaderBasic setEndpoint (@Nonnull final ISimpleURL aRequestEndpoint)
{
m_aRequestEndpoint = ValueEnforcer.notNull (aRequestEndpoint, "RequestEndpoint");
return this;
} |
python | def _is_in_keep_going(self, x, y):
"""Checks if the mouse is in the keep going button, and if the won overlay is shown."""
x1, y1, x2, y2 = self._keep_going
return self.won == 1 and x1 <= x < x2 and y1 <= y < y2 |
java | public static String[] getQueryParameterValues(RESTRequest request, String name) {
if (!"post".equalsIgnoreCase(request.getMethod())) {
return request.getParameterValues(name);
}
if (request.getQueryString() == null) {
return null;
}
Hashtable params = n... |
python | def centroid(im):
"""
Computes the centroid of an image using the image moments:
centroid = {m10/m00, m01/m00}
These calls point to Python version of moments function
m00 = immoments(im,0,0)
m10 = immoments(im, 1,0)
m01 = immoments(im,0,1)
"""
# These calls point to Python version... |
java | public boolean send(RoxPayload payload) throws MalformedURLException {
final URL payloadResourceUrl = getPayloadResourceUrl();
if (payloadResourceUrl == null) {
return false;
}
LOGGER.info("Connected to ROX Center API at {}", configuration.getServerConfiguration().getApiUrl());
// Print the payload to t... |
python | def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator |
python | def kde_gauss(events_x, events_y, xout=None, yout=None):
""" Gaussian Kernel Density Estimation
Parameters
----------
events_x, events_y: 1D ndarray
The input points for kernel density estimation. Input
is flattened automatically.
xout, yout: ndarray
The coordinates at which... |
python | def get_item_data(self, session, item, byte_range=None):
"""
Return a file pointer to the item file. Assumes `item.file_name` points
to the file on disk.
"""
# Parse byte range
if byte_range is not None:
begin, end = parse_byte_range(byte_range, max_byte=item... |
python | def get_count(cls, date_field=None, start=None, end=None, filters={}):
"""
Build the DSL query for counting the number of items.
:param date_field: field with the date
:param start: date from which to start counting, should be a datetime.datetime object
:param end: date until wh... |
java | public <R> Iterator<R> iterator(int fetchSize, int partitionId, Projection<Map.Entry<K, V>, R> projection,
Predicate<K, V> predicate) {
checkNotNull(projection, NULL_PROJECTION_IS_NOT_ALLOWED);
checkNotNull(predicate, NULL_PREDICATE_IS_NOT_ALLOWED);
checkNotPa... |
java | private byte[] getLastItem() throws IOException
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int[] lastItem =
{0x2E, 0x80, 0x00, 0xDF, 0xEA, 0xBD, 0x65, 0xC2, 0xD0, 0x11, 0xBC, 0xED, 0x00, 0xA0, 0xC9, 0x0A, 0xB5, 0x0F};
writeInts(lastItem, outStream);
return ou... |
java | public static OType getType(final String iValue, final char iCharType) {
if (iCharType == 'f')
return OType.FLOAT;
else if (iCharType == 'c')
return OType.DECIMAL;
else if (iCharType == 'l')
return OType.LONG;
else if (iCharType == 'd')
return OType.DOUBLE;
else if (... |
java | private static boolean isStackCleared(final Instruction instruction) {
return instruction.getType() == Instruction.InstructionType.RETURN || instruction.getType() == Instruction.InstructionType.THROW;
} |
python | def _register_dataparser(self, plugin_name, plugin_instance):
"""
Register a parser.
:param plugin_name: Parser name
:param plugin_instance: PluginBase
:return: Nothing
"""
for parser in plugin_instance.get_parsers().keys():
if self.responseparser.has... |
python | def libvlc_video_get_logo_int(p_mi, option):
'''Get integer logo option.
@param p_mi: libvlc media player instance.
@param option: logo option to get, values of libvlc_video_logo_option_t.
'''
f = _Cfunctions.get('libvlc_video_get_logo_int', None) or \
_Cfunction('libvlc_video_get_logo_int',... |
python | def clean_total_refund_amount(self):
'''
The Javascript should ensure that the hidden input is updated, but double check it here.
'''
initial = self.cleaned_data.get('initial_refund_amount', 0)
total = self.cleaned_data['total_refund_amount']
summed_refunds = sum([v for k... |
java | private void tfConversionStrategyClassActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfConversionStrategyClassActionPerformed
{//GEN-HEADEREND:event_tfConversionStrategyClassActionPerformed
// Commit on ENTER
aTable.setConversionStrategyClass(this.tfConversionStrategyClass.getTe... |
python | def fix_header_comment(filename, timestamp):
"""Fixes the header-comment of the given file."""
# Fix input file.
name = os.path.basename( filename )
for line in fileinput.input( filename, inplace=1, mode="rU" ):
# If header-comment already contains anything for '$Id$', remove it.
line = ... |
java | public void disposeAll() {
for( WeakReference<Com4jObject> ref : objects) {
Com4jObject o = ref.get();
if(o != null) {
o.dispose();
}
}
objects.clear();
} |
java | public static Config stormConfig(Properties source) {
Config result = new Config();
logger.debug("Mapping declared types for Storm properties...");
for (Field field : result.getClass().getDeclaredFields()) {
if (field.getType() != String.class) continue;
if (field.getName().endsWith(CONFIGURATION_TYPE_FIEL... |
python | def _get_ess(sample_array):
"""Compute the effective sample size for a 2D array."""
shape = sample_array.shape
if len(shape) != 2:
raise TypeError("Effective sample size calculation requires 2 dimensional arrays.")
n_chain, n_draws = shape
if n_chain <= 1:
raise TypeError("Effective ... |
java | public static <T extends TOP> int count(final Class<T> type, final JCas aJCas)
{
return JCasUtil.select(aJCas, type).size();
} |
python | def highlight(code, lexer, formatter, outfile=None):
"""
Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
If ``outfile`` is given and a valid file object (an object
with a ``write`` method), the result will be written to it, otherwise
it is returned as a string.
"""
... |
python | def get_default_values(self):
"""Overriding to make updating the defaults after instantiation of
the option parser possible, _update_defaults() does the dirty work."""
if not self.process_default_values:
# Old, pre-Optik 1.5 behaviour.
return optparse.Values(self.defaults... |
java | public static Element createElement(String localPart, String prefix, String uri)
{
Document doc = getOwnerDocument();
if (prefix == null || prefix.length() == 0)
{
if (ROOT_LOGGER.isTraceEnabled()) ROOT_LOGGER.trace("createElement {" + uri + "}" + localPart);
return doc.createElem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.