language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | protected void checkIndex(int parameterIndex, int type1, int type2, String getName)
throws SQLException {
checkIndex(parameterIndex);
if (type1 != this.testReturn[parameterIndex - 1]
&& type2 != this.testReturn[parameterIndex - 1]) {
throw new PSQLException(
GT.tr("Parameter of typ... |
python | def name(self):
"""Get the name of the action."""
name = getattr(self.action, "__name__", None)
# ascii(action) not defined for all actions, so must only be evaluated if getattr fails
return name if name is not None else ascii(self.action) |
python | def get_stats_display_height(self, curse_msg):
r"""Return the height of the formatted curses message.
The height is defined by the number of '\n' (new line).
"""
try:
c = [i['msg'] for i in curse_msg['msgdict']].count('\n')
except Exception as e:
logger.d... |
java | public ActedOnBehalfOf newActedOnBehalfOf(QualifiedName id,
QualifiedName delegate,
QualifiedName responsible,
QualifiedName activity) {
ActedOnBehalfOf res = of.createActedOnBehalfOf();
res.setId(id);
res.setActivity(activity);
res.setDelegate(de... |
python | def update_task(client, task_id, revision, title=None, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None, remove=None):
'''
Updates the task with the given ID
See https://developer.wunderlist.com/documentation/endpoints/task for detailed parameter in... |
java | public Object[] getObjects(String pType, Object[] pIds)
throws SQLException {
// Create Vector to hold the result
Vector result = new Vector(pIds.length);
// Loop through Id's and fetch one at a time (no good performance...)
for (int i = 0; i < pIds.length; i++) {
// ... |
python | async def result(self) -> T:
"""\
Wait for the task's termination; either the result is returned or a raised exception is reraised.
If an event is sent before the task terminates, an `EventException` is raised with the event as argument.
"""
try:
event = await self.re... |
java | public Map<String, Object> retrieve(String entityName, String groupId, String entityId) throws MnoException {
return retrieve(entityName, groupId, entityId, getAuthenticatedClient());
} |
java | @SafeVarargs
public final ServerListenerBuilder addStartingCallbacks(Consumer<? super Server>... consumers) {
return addStartingCallbacks(Arrays.asList(consumers));
} |
python | def patch_requests():
""" Customize the cacerts.pem file that requests uses.
Automatically updates the cert file if the contents are different.
"""
config.create_config_directory()
ca_certs_file = config.CERT_FILE
ca_certs_contents = requests.__loader__.get_data('requests/cacert.pem')
shoul... |
java | public static void encryptPrivateKeyWithPassword(final PrivateKey privateKey,
final @NonNull OutputStream outputStream, final String password)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
Bad... |
java | private static boolean isBindingCompatible( Tuple tuple, VarBindingDef binding)
{
VarValueDef currentValue = tuple.getBinding( binding.getVarDef());
return (currentValue == null || currentValue.equals( binding.getValueDef()));
} |
java | public void removeEmptyBlocks() {
Block curr = blocklistHead;
Block prev = null;
int effId = 0;
while (curr != null) {
if (!curr.isEmpty()) {
curr.id = effId++;
if (prev != null) {
prev.nextBlock = curr;
} el... |
java | protected AstEval eval() throws ScanException, ParseException {
AstEval e = eval(false, false);
if (e == null) {
e = eval(false, true);
if (e == null) {
fail(START_EVAL_DEFERRED + "|" + START_EVAL_DYNAMIC);
}
}
return e;
} |
java | private Format getFormat(String desc)
{
if (registry != null)
{
String name = desc;
String args = "";
int i = desc.indexOf(START_FMT);
if (i > 0)
{
name = desc.substring(0, i).trim();
args = desc.substring(i... |
python | def drawBackground(self, painter, rect):
"""
Draws the background for this scene.
:param painter | <QPainter>
rect | <QRect>
"""
if self._dirty:
self.rebuild()
# draw the alternating rects
gantt ... |
python | def find_template_companion(template, extension='', check=True):
"""
Returns the first found template companion file
"""
if check and not os.path.isfile(template):
yield ''
return # May be '<stdin>' (click)
template = os.path.abspath(template)
template_dirname = os.path.dirname... |
java | public CMRFidelityRepCMREx createCMRFidelityRepCMRExFromString(EDataType eDataType, String initialValue) {
CMRFidelityRepCMREx result = CMRFidelityRepCMREx.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName(... |
python | def emitDataChanged(self, regItem):
""" Emits the dataChagned signal for the regItem
"""
#self.sourceModel().emitDataChanged(regItem) # Does this work?
leftIndex = self.indexFromItem(regItem, col=0)
rightIndex = self.indexFromItem(regItem, col=-1)
self.dataChanged.emit(le... |
python | def isxmap(xmethod, opt):
"""Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser.
"""
if xmethod == 'admm':
isx = {'XPrRsdl': 'PrimalRsdl', 'XDlRsdl': 'DualRsdl',
'XRho': 'Rho'}
else:
isx = {'X_F_Btrack': 'F_Btrack', 'X_Q_Btrack': 'Q_Btrack',
'X... |
java | @SuppressWarnings("unchecked")
protected final <E extends Event> EventHandler<E> getHandler(final EventType<E> eventType) throws CoreException {
EventType<?> temp = eventType;
EventHandler<E> handler = null;
while (temp != null && handler == null) {
handler = (EventHandler<E>)... |
java | public BoundCodeDt<PropertyRepresentationEnum> addRepresentation(PropertyRepresentationEnum theValue) {
BoundCodeDt<PropertyRepresentationEnum> retVal = new BoundCodeDt<PropertyRepresentationEnum>(PropertyRepresentationEnum.VALUESET_BINDER, theValue);
getRepresentation().add(retVal);
return retVal;
} |
python | def is_seq(obj):
"""
Check if an object is a sequence.
"""
return (not is_str(obj) and not is_dict(obj) and
(hasattr(obj, "__getitem__") or hasattr(obj, "__iter__"))) |
java | private void initialize(Map context) {
// Guard against recursion.
context.put(jsTypeTree, this);
// Create temporary accumulators for the contents of the fields and variants instance
// variables.
List tmpFields = new ArrayList();
List tmpVariants = new ArrayList();
// Perform tasks assig... |
java | protected String getAccessByField(String target, Field field, Class<?> cls) {
if (field.getModifiers() == Modifier.PUBLIC) {
return target + ClassHelper.PACKAGE_SEPARATOR + field.getName();
}
// check if has getter method
String getter;
if ("boolean".equalsIgnoreCase(... |
python | def geocode(address):
'''Query function to obtain a latitude and longitude from a location
string such as `Houston, TX` or`Colombia`. This uses an online lookup,
currently wrapping the `geopy` library, and providing an on-disk cache
of queries.
Parameters
----------
address : str
... |
java | public static void setSharedVariable(String name, Object object) {
try {
FreeMarkerRender.getConfiguration().setSharedVariable(name, object);
} catch (TemplateException e) {
throw new RuntimeException(e);
}
} |
python | def slice_reStructuredText(input, output):
"""
Slices given reStructuredText file.
:param input: ReStructuredText file to slice.
:type input: unicode
:param output: Directory to output sliced reStructuredText files.
:type output: unicode
:return: Definition success.
:rtype: bool
"""... |
java | public static void print(Object self, PrintWriter out) {
if (out == null) {
out = new PrintWriter(System.out);
}
out.print(InvokerHelper.toString(self));
} |
java | @Nonnull
public JSBlock body ()
{
if (m_aBody == null)
m_aBody = new JSBlock ().newlineAtEnd (false);
return m_aBody;
} |
python | def _value(obj):
"""
make sure to get a float
"""
# TODO: this is ugly and makes everything ugly
# can we handle this with a clean decorator or just requiring that only floats be passed??
if hasattr(obj, 'value'):
return obj.value
elif isinstance(obj, np.ndarray):
return np.a... |
python | def connect(self, host=None, port=None, connect=False, **kwargs):
""" Explicitly creates the MongoClient; this method must be used
in order to specify a non-default host or port to the MongoClient.
Takes arguments identical to MongoClient.__init__"""
try:
self.__conne... |
java | private byte[] getUploadFileContent(RequestElements requestElements) throws FMSException {
Attachable attachable = (Attachable) requestElements.getEntity();
InputStream docContent = requestElements.getUploadRequestElements().getDocContent();
// gets the mime value form the filename
String mime = getMime(atta... |
java | private void readHierarchy(Object object, ObjectStreamClass classDesc)
throws IOException, ClassNotFoundException, NotActiveException {
if (object == null && mustResolve) {
throw new NotActiveException();
}
List<ObjectStreamClass> streamClassList = classDesc.getHierarchy... |
java | public Fixture fixtureFor(Object target) {
if(!(target instanceof CommandProcessor))
throw new IllegalArgumentException("Can only get a SeleniumFixture for an instance of CommandProcessor.");
return new SeleniumFixture((CommandProcessor)target);
} |
python | def generate_property_deprecation_message(to_be_removed_in_version, old_name, new_name, new_attribute,
module_name='Client'):
"""Generate a message to be used when warning about the use of deprecated properties.
:param to_be_removed_in_version: Version of this module t... |
java | public static Map<String, Object> parseCommandArgs(String argString, String[] paramKeys) {
return parseArgsArray(argString.split("\\s+"), null, null, Arrays.asList(paramKeys));
} |
java | @Override
public void warn(String msg, Throwable throwable) {
LOGGER.log(Level.WARNING, msg, throwable);
} |
java | @Override
public void remove(Object cacheKey) {
if (cacheKey != null) {
CacheObject cacheObject = getCachedObject(cacheKey);
if (cacheObject != null) {
removeCachedObject(cacheObject);
}
}
} |
java | private ResourceBundleDefinition buildCustomBundleDefinition(String bundleName, boolean isChildBundle) {
// Id for the bundle
String bundleId = props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_ID);
if (null == bundleId && !isChildBundle)
throw new IllegalArgumentException(
"No id defined f... |
python | def strip_ansi(text, c1=False, osc=False):
''' Strip ANSI escape sequences from a portion of text.
https://stackoverflow.com/a/38662876/450917
Arguments:
line: str
osc: bool - include OSC commands in the strippage.
c1: bool - include C1 commands in the strippa... |
java | private String convertDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
Date creationDate = sdf.parse(date);
sdf = new SimpleDateFormat("\\'yr'yyyy\\'mo'MM\\'dy'dd\\'hr'HH\\'min'mm\\'sec'ss");
return sdf.format(crea... |
python | def extract_fields(document_data, prefix_path, expand_dots=False):
"""Do depth-first walk of tree, yielding field_path, value"""
if not document_data:
yield prefix_path, _EmptyDict
else:
for key, value in sorted(six.iteritems(document_data)):
if expand_dots:
sub_... |
java | public void goTo(final ContentScene contentScene) {
Log.d(TAG, "Go to %s", contentScene.getName());
if (!goBackTo(contentScene)) {
mContentSceneViewStack.push(contentScene);
}
executeHideShowCycle(contentScene);
} |
python | def windowed_statistic(pos, values, statistic, size=None, start=None,
stop=None, step=None, windows=None, fill=np.nan):
"""Calculate a statistic from items in windows over a single
chromosome/contig.
Parameters
----------
pos : array_like, int, shape (n_items,)
The i... |
python | def flush(self):
"""Flush(apply) all changed to datastore."""
self.puts.flush()
self.deletes.flush()
self.ndb_puts.flush()
self.ndb_deletes.flush() |
java | @Override
public void removeByCommercePriceListId(long commercePriceListId) {
for (CommercePriceListAccountRel commercePriceListAccountRel : findByCommercePriceListId(
commercePriceListId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commercePriceListAccountRel);
}
} |
java | public static final Function<Number,String> toCurrencyStr(Locale locale) {
return new ToString(NumberFormatType.CURRENCY, locale);
} |
java | public static double[][] toDouble(int[][] array) {
double[][] n = new double[array.length][array[0].length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
n[i][j] = (double) array[i][j];
}
}
return n;
} |
python | def all(self, order_by=None, limit=0):
"""
Fetch all items.
:param limit: How many rows to fetch.
:param order_by: column on which to order the results. \
To change the sort, prepend with < or >.
"""
with rconnect() as conn:
try:
... |
python | def parse_venue(data):
"""
Parse a ``MeetupVenue`` from the given response data.
Returns
-------
A `pythonkc_meetups.types.`MeetupVenue``.
"""
return MeetupVenue(
id=data.get('id', None),
name=data.get('name', None),
address_1=data.get('address_1', None),
ad... |
python | def single_node_env(args):
"""Sets up environment for a single-node TF session.
Args:
:args: command line arguments as either argparse args or argv list
"""
# setup ARGV for the TF process
if isinstance(args, list):
sys.argv = args
elif args.argv:
sys.argv = args.argv
# setup ENV for Had... |
python | def get_batches(self, batch_size, shuffle=True):
"""Get batch iterator
Parameters
----------
batch_size : int
size of one batch
shuffle : bool
whether to shuffle batches. Don't set to True when evaluating on dev or test set.
Returns
------... |
java | public RegistryConfig setParameters(Map<String, String> parameters) {
if (this.parameters == null) {
this.parameters = new ConcurrentHashMap<String, String>();
this.parameters.putAll(parameters);
}
return this;
} |
python | def search_knn(self, point, k, dist=None):
""" Return the k nearest neighbors of point and their distances
point must be an actual point, not a node.
k is the number of results to return. The actual results can be less
(if there aren't more nodes to return) or more in case of equal
... |
java | public static void publish(MqttSettings settings, String subtopic, Object data) throws JsonProcessingException, MqttException {
ObjectMapper objectMapper = new ObjectMapper();
publish(settings, subtopic, objectMapper.writeValueAsBytes(data), 1, false);
} |
python | def errors_as_text(self):
"""
only available to Django 1.7+
"""
errors = []
errors.append(self.non_field_errors().as_text())
errors_data = self.errors.as_data()
for key, value in errors_data.items():
field_label = self.fields[key].label
err... |
python | def handle_branch(repo, **kwargs):
""":return: Local.create()"""
log.info('branch: %s %s' %(repo, kwargs))
if type(repo) in [unicode, str]:
path = os.path.join(repo, kwargs.get('name', 'Unnamed'))
desc = kwargs.get('desc')
branch = Repo.new(path=path, desc=desc, bare=True)
else:
... |
java | public static <K, V> Predicate<Map<K, V>> anyEntry(
Predicate<? super Map.Entry<K, V>> p) {
return forEntries(Predicates.<Map.Entry<K, V>>any(p));
} |
python | def _calc_degreeminutes(decimal_degree):
'''
Calculate degree, minute second from decimal degree
'''
sign = compare(decimal_degree, 0) # Store whether the coordinate is negative or positive
decimal_degree = abs(decimal_degree)
degree = decimal_degree//1 # Truncate degree ... |
java | @Override
public void discard() // PQ57408 Implemented this function
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "discard : " + this);
// If this is a BeanO for a home (i.e. home field will be null) the... |
python | def get_seebeck_eff_mass(self, output='average', temp=300, doping_levels=False,
Lambda=0.5):
"""
Seebeck effective mass calculated as explained in Ref.
Gibbs, Z. M. et al., Effective mass and fermi surface complexity factor
from ab initio band structure c... |
java | public static void keepMainThread(Runnable toContinue) {
mainThread = Thread.currentThread();
Thread thread = new Thread(toContinue, "LC Core - Main");
thread.start();
mainThreadLoop();
} |
java | @SuppressWarnings("deprecation")
public static @ColorInt int resolveColor(@ColorRes int color, Context context) {
if (Build.VERSION.SDK_INT >= 23) {
return context.getResources().getColor(color, context.getTheme());
}
else {
return context.getResources().getColor(colo... |
java | public static void convert(DMatrixRMaj src , DMatrixRBlock dst ) {
if( src.numRows != dst.numRows || src.numCols != dst.numCols )
throw new IllegalArgumentException("Must be the same size.");
for( int i = 0; i < dst.numRows; i += dst.blockLength ) {
int blockHeight = Math.min( d... |
java | public static ActionForm lookupActionForm(HttpServletRequest request, String formName) {
ActionForm actionForm = null;
actionForm = (ActionForm) request.getAttribute(formName);
if (actionForm == null && request.getSession(false) != null) {
HttpSession session = request.getSession(false);
actionForm = (... |
java | public static SecuritySettingsPlugin get()
{
final Application app = Application.get();
if (null == app)
{
throw new IllegalStateException(
"No wicket application is bound to the current thread.");
}
final SecuritySettingsPlugin plugin = app.getMetaData(SECURITY_SETTINGS_PLUGIN_KEY);
if (null == plu... |
java | private JPanel getJPanel2() {
if (jPanel2 == null) {
jPanel2 = new JPanel();
jPanel2.add(getBtnAccept(), null);
jPanel2.add(getBtnDecline(), null);
}
return jPanel2;
} |
python | def find_funcs_called_with_kwargs(sourcecode, target_kwargs_name='kwargs'):
r"""
Finds functions that are called with the keyword `kwargs` variable
CommandLine:
python3 -m utool.util_inspect find_funcs_called_with_kwargs
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
... |
python | def do_fit(self, event):
"""
Re-fit the window to the size of the content.
"""
#self.grid.ShowScrollbars(wx.SHOW_SB_NEVER, wx.SHOW_SB_NEVER)
if event:
event.Skip()
self.main_sizer.Fit(self)
disp_size = wx.GetDisplaySize()
actual_size = self.Get... |
python | async def get_request_token(self, loop=None, **params):
"""Get a request_token and request_token_secret from OAuth1 provider."""
params = dict(self.params, **params)
data = await self.request('GET', self.request_token_url, params=params, loop=loop)
self.oauth_token = data.get('oauth_tok... |
java | public NodeData[] getAggregatedNodeStates(NodeData nodeState) throws RepositoryException
{
if (nodeState.getPrimaryTypeName().equals(nodeTypeName))
{
List<NodeData> nodeStates = new ArrayList<NodeData>();
for (int i = 0; i < nodeIncludes.length; i++)
{
nodeStates.ad... |
python | def extract_domain(host):
"""
Domain name extractor. Turns host names into domain names, ported
from pwdhash javascript code"""
host = re.sub('https?://', '', host)
host = re.match('([^/]+)', host).groups()[0]
domain = '.'.join(host.split('.')[-2:])
if domain in _domains:
domain = '.... |
python | async def identify(self):
"""Sends the IDENTIFY packet."""
payload = {
'op': self.IDENTIFY,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'discord.py',
'$dev... |
java | public ArrayList<OvhStreamRule> serviceName_output_graylog_stream_streamId_rule_ruleId_GET(String serviceName, String streamId, String ruleId) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/output/graylog/stream/{streamId}/rule/{ruleId}";
StringBuilder sb = path(qPath, serviceName, streamId, ruleId)... |
python | def from_authorized_user_info(cls, info, scopes=None):
"""Creates a Credentials instance from parsed authorized user info.
Args:
info (Mapping[str, str]): The authorized user info in Google
format.
scopes (Sequence[str]): Optional list of scopes to include in the... |
java | public static HttpMockServer start(ConfigReader configReader, NetworkType networkType) {
return HttpMockServer.startMockApiServer(configReader, networkType);
} |
java | public static <T extends Number> double divide(final T dividend, final T divisor) {
if (JudgeUtils.hasNull(dividend, divisor)) {
return 0d;
}
if (JudgeUtils.equals(dividend, divisor) || divisor.doubleValue() == 0) {
return 1d;
}
return dividend.doubleValu... |
java | @Override
public final void setHasName(final SeService pHasName) {
this.hasName = pHasName;
if (this.itsId == null) {
this.itsId = new IdI18nSeService();
}
this.itsId.setHasName(this.hasName);
} |
python | def matrix_multiplication_blockwise(self, matrix, blocksize):
"""
http://en.wikipedia.org/wiki/Block_matrix#Block_matrix_multiplication
"""
#Create the blockwise version of self and matrix
selfBlockwise = self.matrix_to_blockmatrix(blocksize)
matrixBlockwise = matrix.matr... |
python | def _makeResult(self):
"""Return a Result that doesn't print dots.
Nose's ResultProxy will wrap it, and other plugins can still print
stuff---but without smashing into our progress bar, care of
ProgressivePlugin's stderr/out wrapping.
"""
return ProgressiveResult(self._... |
java | @Override
protected Artifact getArtifact(final ArtifactItem item) throws MojoExecutionException {
assert item != null;
Artifact artifact = null;
if (item.getVersion() != null) {
// if version is set in ArtifactItem, it will always override the one in project dependency
... |
java | private void processRegexRule(final String parsed_value) {
if (rule.getCompiledRegex() == null) {
throw new IllegalArgumentException("Regex was null for rule: " +
rule);
}
final Matcher matcher = rule.getCompiledRegex().matcher(parsed_value);
if (matcher.find()) {
// The first gr... |
python | def backward_word(self, e): # (M-b)
u"""Move back to the start of the current or previous word. Words are
composed of letters and digits."""
self.l_buffer.backward_word(self.argument_reset)
self.finalize() |
python | def __read(usr_path, file_type):
"""
Determine what path needs to be taken to read in file(s)
:param str usr_path: Path (optional)
:param str file_type: File type to read
:return none:
"""
# is there a file path specified ?
if usr_path:
# Is this a URL? Download the file and re... |
python | def _fill_cache(self):
"""Fill the cache from the `astropy.table.Table`"""
for irow in range(len(self._table)):
file_handle = self._make_file_handle(irow)
self._cache[file_handle.path] = file_handle |
python | def _put_metadata(self, fs_remote, ds):
"""Store metadata on a pyfs remote"""
from six import text_type
from fs.errors import ResourceNotFoundError
identity = ds.identity
d = identity.dict
d['summary'] = ds.config.metadata.about.summary
d['title'] = ds.config.... |
python | def execute_hook(self, event_name):
"""Execute shell commands related to current event_name"""
hook = self.settings.hooks.get_string('{!s}'.format(event_name))
if hook is not None and hook != "":
hook = hook.split()
try:
subprocess.Popen(hook)
... |
python | def convert_time(self, time):
"""
A helper function to convert seconds into hh:mm:ss for better
readability.
time: A string representing time in seconds.
"""
time_string = str(datetime.timedelta(seconds=int(time)))
if time_string.split(':')[0] == '0':
... |
java | @Override
public <T> OperationFuture<Boolean> prepend(long cas, String key, T val,
Transcoder<T> tc) {
return asyncCat(ConcatenationType.prepend, cas, key, val, tc);
} |
python | def _make_sync_method(name):
"""Helper to synthesize a synchronous method from an async method name.
Used by the @add_sync_methods class decorator below.
Args:
name: The name of the synchronous method.
Returns:
A method (with first argument 'self') that retrieves and calls
self.<name>, passing it... |
python | def create_parameter_map(self):
"""
Creates a parameter map which takes a tuple of the exchange 'from' and exchange 'to' codes
and returns the parameter name for that exchange
"""
names = self.modelInstance.names
db = self.modelInstance.database['items']
paramete... |
python | def is_legal_sequence(self, packet: DataPacket) -> bool:
"""
Check if the Sequence number of the DataPacket is legal.
For more information see page 17 of http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf.
:param packet: the packet to check
:return: true if the sequence is leg... |
python | def get_bounding_box(self, maxdist):
"""
Bounding box containing all the point sources, enlarged by the
maximum distance.
"""
return utils.get_bounding_box([ps.location for ps in self], maxdist) |
java | private static void parseMaxErrors(String current, Pipeline pipeline)
throws ParseException {
try {
String errorsStr = current.replaceFirst("max_errors: ", "").trim();
int errors = parseInt(errorsStr);
pipeline.setMaxErrors(errors);
LOG.info("+-using {... |
java | private void processChildEvent(WatchedEvent event) throws Exception {
HashMap<String, JSONObject> cacheCopy = new HashMap<String, JSONObject>(m_publicCache.get());
ByteArrayCallback cb = new ByteArrayCallback();
m_zk.getData(event.getPath(), m_childWatch, cb, null);
try {
byt... |
python | def __str_cleanup(line):
"""
Remove the unnecessary characters in the line that we don't want
:param str line:
:return str:
"""
if '#' in line:
line = line.replace("#", "")
line = line.strip()
if '-----------' in line:
line = ''... |
python | def email(self):
""" User email(s) """
try:
return self.parser.get("general", "email")
except NoSectionError as error:
log.debug(error)
raise ConfigFileError(
"No general section found in the config file.")
except NoOptionError as error... |
java | private void computePartialChunkCrc(long blkoff, long ckoff,
int bytesPerChecksum, DataChecksum checksum) throws IOException {
// find offset of the beginning of partial chunk.
//
int sizePartialChunk = (int) (blkoff % bytesPerChecksum);
int checksumSize = checksum.getChecksumSize();
blkoff =... |
java | @Override
public CreateStageResult createStage(CreateStageRequest request) {
request = beforeClientExecution(request);
return executeCreateStage(request);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.