language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public String hackInv(ARecordDeclIR type) {
if (type.getInvariant() != null) {
AFuncDeclIR invFunc = (AFuncDeclIR) type.getInvariant();
StringBuilder sb = new StringBuilder();
sb.append("inv ");
sb.append(invFunc.getFormalParams().get(0).getPattern().toString());... |
java | private void overChoiceEntry(CmsChoiceMenuEntryWidget entryWidget) {
cancelChoiceTimer();
cleanUpSubmenus(entryWidget);
CmsChoiceMenuEntryBean entryBean = entryWidget.getEntryBean();
if (!entryBean.isLeaf()) {
addSubmenu(entryWidget);
}
} |
python | def _get_assignment_target_end(self, ast_module):
"""Returns position of 1st char after assignment traget.
If there is no assignment, -1 is returned
If there are more than one of any ( expressions or assigments)
then a ValueError is raised.
"""
if len(ast_module.body)... |
java | public void marshall(DomainDescriptionType domainDescriptionType, ProtocolMarshaller protocolMarshaller) {
if (domainDescriptionType == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(domainDescriptio... |
python | def _cumprod(l):
"""Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1)
"""
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret |
python | def fill_archive(self, stream=None, kind='tgz', prefix=None,
subrepos=False):
"""
Fills up given stream.
:param stream: file like object.
:param kind: one of following: ``zip``, ``tgz`` or ``tbz2``.
Default: ``tgz``.
:param prefix: name of root d... |
java | private void initLocaleSelect() {
if (m_availableLocales.size() < 2) {
return;
}
Map<String, String> selectOptions = new HashMap<String, String>();
for (Entry<String, String> localeEntry : m_availableLocales.entrySet()) {
if (m_contentLocales.contains(loca... |
python | def decrypt(data, _key):
"""
ACCEPT BYTES -> UTF8 -> JSON -> {"salt":s, "length":l, "data":d}
"""
# Key and iv have not been generated or provided, bail out
if _key is None:
Log.error("Expecting a key")
_input = get_module("mo_json").json2value(data.decode('utf8'), leaves=False, flexibl... |
java | final public Expression ValuePrefix() throws ParseException {
Expression ret;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case INTEGER_LITERAL:
case FLOATING_POINT_LITERAL:
case STRING_LITERAL:
case TRUE:
case FALSE:
case NULL:
ret = Literal();
break;
case LPAREN:
jj_cons... |
java | public void setOptionGroupOptionSettings(java.util.Collection<OptionGroupOptionSetting> optionGroupOptionSettings) {
if (optionGroupOptionSettings == null) {
this.optionGroupOptionSettings = null;
return;
}
this.optionGroupOptionSettings = new com.amazonaws.internal.SdkI... |
java | void setEndPoints() {
float angleNum = 360f / (rayNum - 1);
for (int i = 0; i < rayNum; i++) {
final float angle = angleNum * i;
sin[i] = MathUtils.sinDeg(angle);
cos[i] = MathUtils.cosDeg(angle);
endX[i] = distance * cos[i];
endY[i] = distance * sin[i];
}
} |
python | def filtre(liste_base, criteres) -> groups.Collection:
"""
Return a filter list, bases on criteres
:param liste_base: Acces list
:param criteres: Criteria { `attribut`:[valeurs,...] }
"""
def choisi(ac):
for cat, li in criteres.items():
v = a... |
python | def destroy_plugin(plugin_name, conn=None):
"""
Creates a new plugin
:param plugin_name: <str>
:param conn:
:return: <dict> rethinkdb response
"""
results = {}
if plugin_exists(plugin_name, conn=conn):
results = RPX.table_drop(plugin_name).run(conn)
return results |
python | def matplotlibensure(func):
"""If matplotlib isn't installed, this decorator alerts the user and
suggests how one might obtain the package."""
@wraps(func)
def wrap(*args):
if MPLINSTALLED == False:
raise ImportError(msg)
return func(*args)
... |
python | def edges2nodes(edges):
"""gather the nodes from the edges"""
nodes = []
for e1, e2 in edges:
nodes.append(e1)
nodes.append(e2)
nodedict = dict([(n, None) for n in nodes])
justnodes = list(nodedict.keys())
# justnodes.sort()
justnodes = sorted(justnodes, key=lambda x: str(x[0... |
python | def create_commerce():
"""
Creates commerce from environment variables ``TBK_COMMERCE_ID``, ``TBK_COMMERCE_KEY``
or for testing purposes ``TBK_COMMERCE_TESTING``.
"""
commerce_id = os.getenv('TBK_COMMERCE_ID')
commerce_key = os.getenv('TBK_COMMERCE_KEY')
commerce_... |
python | def end_policy_update(self):
"""
Inform Metrics class that policy update has started.
"""
if self.time_policy_update_start:
self.delta_policy_update = time() - self.time_policy_update_start
else:
self.delta_policy_update = 0
delta_train_start = tim... |
java | public List<Row> getAllRawExcelRows(String sheetName, boolean heading) {
return excelReader.getAllExcelRows(sheetName, heading);
} |
python | def list_milestones(self, project_id, find=None):
"""
This lets you query the list of milestones for a project. You can
either return all milestones, or only those that are late, completed,
or upcoming.
"""
path = '/projects/%u/milestones/list' % project_id
req = ... |
python | def get_bookmarks(self, time=None, chan=None):
"""
Raises
------
IndexError
When there is no selected rater
"""
# get bookmarks inside window
try:
bookmarks = self.rater.find('bookmarks')
except AttributeError:
raise Ind... |
java | public static void main(String[] argv) throws Exception {
System.out.println("Enter an English word in plural form and press ENTER");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
while(true) {
String w=in.readLine();
if(w.length()==0) break;
if(isPlural(w)) S... |
java | public @Nonnull final <T> T getRequiredValue(Class<T> type) {
return getRequiredValue(AnnotationMetadata.VALUE_MEMBER, type);
} |
java | public List<CmsModelPageConfig> getModelPages(boolean includeDisable) {
CmsADEConfigData parentData = parent();
List<CmsModelPageConfig> parentModelPages;
if ((parentData != null) && !m_data.isDiscardInheritedModelPages()) {
parentModelPages = parentData.getModelPages();
} e... |
java | private void setupUI() {
add(new WMessageBox(WMessageBox.WARN,
"This example is for framework testing ONLY and must not be used as an example of how to set up any UI controls"));
WFieldLayout layout = new WFieldLayout();
add(layout);
layout.addField("Select an option with spaces", drop);
layout.addField(... |
java | public static base_response delete(nitro_service client, dnsnsrec resource) throws Exception {
dnsnsrec deleteresource = new dnsnsrec();
deleteresource.domain = resource.domain;
deleteresource.nameserver = resource.nameserver;
return deleteresource.delete_resource(client);
} |
python | def _iter_grouped_shortcut(self):
"""Fast version of `_iter_grouped` that yields Variables without
metadata
"""
var = self._obj.variable
for indices in self._group_indices:
yield var[{self._group_dim: indices}] |
java | public void marshall(DescribeActivitiesRequest describeActivitiesRequest, ProtocolMarshaller protocolMarshaller) {
if (describeActivitiesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(desc... |
java | @Override
public boolean isUnknownType() {
// If the object is unknown now, check the supertype again,
// because it might have been resolved since the last check.
if (unknown) {
ObjectType implicitProto = getImplicitPrototype();
if (implicitProto == null || implicitProto.isNativeObjectType())... |
java | public KafkaClient init() throws Exception {
if (executorService == null) {
int numThreads = Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 1), 4);
executorService = Executors.newFixedThreadPool(numThreads);
myOwnExecutorService = true;
} else {
... |
java | public static Mapping<Boolean> bool(Constraint... constraints) {
return new FieldMapping(
InputMode.SINGLE,
mkSimpleConverter(s ->
isEmptyStr(s) ? false : Boolean.parseBoolean(s)
), new MappingMeta(MAPPING_BOOLEAN, Boolean.class)
).... |
java | public <T> void notifyObserversOfRequestSuccess(CachedSpiceRequest<T> request) {
RequestProcessingContext requestProcessingContext = new RequestProcessingContext();
requestProcessingContext.setExecutionThread(Thread.currentThread());
post(new RequestSucceededNotifier<T>(request, spiceServiceList... |
python | def options(cls):
"""Provide a sorted list of options."""
return sorted((value, name) for (name, value) in cls.__dict__.items() if not name.startswith('__')) |
python | def _get_principal_axes_from_ndk_string(self, ndk_string, exponent):
"""
Gets the principal axes from the ndk string and returns an instance
of the GCMTPrincipalAxes class
"""
axes = GCMTPrincipalAxes()
# The principal axes is defined in characters 3:48 of the 5th line
... |
python | def customFilter(self, filterFunc):
'''
customFilter - Apply a custom filter to elements and return a QueryableList of matches
@param filterFunc <lambda/function< - A lambda/function that is passed an item, and
returns True if the item matches (will be returned), otherwis... |
python | def conf_budget(self, budget):
"""
Set limit on the number of conflicts.
"""
if self.glucose:
pysolvers.glucose41_cbudget(self.glucose, budget) |
java | static
public Function getFunction(String name){
if(name == null){
return null;
} // End if
if(FunctionRegistry.functions.containsKey(name)){
Function function = FunctionRegistry.functions.get(name);
return function;
}
Class<?> functionClazz;
if(FunctionRegistry.functionClazzes.containsKey(na... |
python | def ttl(self, value):
"""Change self ttl with input value.
:param float value: new ttl in seconds.
"""
# get timer
timer = getattr(self, Annotation.__TIMER, None)
# if timer is running, stop the timer
if timer is not None:
timer.cancel()
# ... |
python | def _RemoveRegistryKeys(self, metadata_value_pairs):
"""Filter out registry keys to operate on files."""
filtered_pairs = []
for metadata, stat_entry in metadata_value_pairs:
# Ignore registry keys.
if stat_entry.pathspec.pathtype != rdf_paths.PathSpec.PathType.REGISTRY:
filtered_pairs.a... |
python | def userBrowser(self, request, tag):
"""
Render a TDB of local users.
"""
f = LocalUserBrowserFragment(self.browser)
f.docFactory = webtheme.getLoader(f.fragmentName)
f.setFragmentParent(self)
return f |
java | public String encodeURL(String relativePath, String scheme) {
return convergedSessionDelegate.encodeURL(relativePath, scheme);
} |
python | def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0):
'''
Receive a stream via the XMODEM protocol.
>>> stream = file('/etc/issue', 'wb')
>>> print modem.recv(stream)
2342
Returns the number of bytes received on success or ``None`` in c... |
java | @Override
public ExecuteChangeSetResult executeChangeSet(ExecuteChangeSetRequest request) {
request = beforeClientExecution(request);
return executeExecuteChangeSet(request);
} |
java | @Sensitive
public static byte[] decodeLTPAToken(Codec codec, @Sensitive byte[] token_arr) throws SASException {
byte[] ltpaTokenBytes = null;
try {
byte[] data = readGSSTokenData(LTPAMech.LTPA_OID.substring(4), token_arr);
if (data != null) {
// Check if it i... |
java | public void executeSearch(boolean replaceOldTab, boolean freshQuery)
{
if (freshQuery)
{
getState().getOffset().setValue(0l);
getState().getSelectedMatches().setValue(new TreeSet<Long>());
// get the value for the visible segmentation from the configured context
Set<String> selectedCor... |
java | public BaseJsonBo removeSubAttr(String attrName, String dPath) {
Lock lock = lockForWrite();
try {
JsonNode attr = cacheJsonObjs.get(attrName);
JacksonUtils.deleteValue(attr, dPath);
return (BaseJsonBo) setAttribute(attrName, SerializationUtils.toJsonString(attr),
... |
python | def reconstruct(self, b, X=None):
"""Reconstruct representation of signal b in signal set."""
if X is None:
X = self.getcoef()
Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN)
slc = (slice(None),)*self.dimN + \
(slice(self.chncs[b], self.chncs[b+1]),)
Sf = ... |
python | def _get_site_amplification(self, sites, coeffs):
"""
Compute fourth term of equation (1) on p. 1200:
``b5 * S``
"""
is_rock = self.get_site_type_dummy_variables(sites)
return coeffs['b5']*is_rock |
java | public CMAArray<CMASpaceMembership> fetchAll(String spaceId, Map<String, String> query) {
assertNotNull(spaceId, "spaceId");
if (query == null) {
return service.fetchAll(spaceId).blockingFirst();
} else {
return service.fetchAll(spaceId, query).blockingFirst();
}
} |
java | public static void write(Writer writer, Object jsonObject)
throws JsonGenerationException, IOException {
final JsonGenerator jw = JSON_FACTORY.createGenerator(writer);
jw.writeObject(jsonObject);
} |
java | public static aaaglobal_aaapreauthenticationpolicy_binding[] get_filtered(nitro_service service, String filter) throws Exception{
aaaglobal_aaapreauthenticationpolicy_binding obj = new aaaglobal_aaapreauthenticationpolicy_binding();
options option = new options();
option.set_filter(filter);
aaaglobal_aaapreauth... |
java | public static org.jfrog.hudson.ArtifactoryServer prepareArtifactoryServer(String artifactoryServerID,
ArtifactoryServer pipelineServer) {
if (artifactoryServerID == null && pipelineServer == null) {
return null;
}... |
java | @Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
SiteNode node = null;
Target target = null;
if (value instan... |
java | public int readMessages(Reader is)
throws IOException
{
//InboxAmp oldInbox = null;
try (OutboxAmp outbox = OutboxAmp.currentOrCreate(getManager())) {
//OutboxThreadLocal.setCurrent(_outbox);
return readMessages(is, outbox);
} finally {
//OutboxThreadLocal.setCurrent(null);
... |
python | def _time_from_json(value, field):
"""Coerce 'value' to a datetime date, if set or not nullable"""
if _not_null(value, field):
if len(value) == 8: # HH:MM:SS
fmt = _TIMEONLY_WO_MICROS
elif len(value) == 15: # HH:MM:SS.micros
fmt = _TIMEONLY_W_MICROS
else:
... |
python | def get_compatible_generator_action(self, filename):
"""
Return the **first** compatible :class:`GeneratorAction` for a given filename or ``None`` if none is found.
Args:
filename (str): The filename of the template to process.
"""
# find first compatible generator a... |
python | def blocks(self, lines):
"""Groups lines into markdown blocks"""
state = markdown.blockparser.State()
blocks = []
# We use three states: start, ``` and '\n'
state.set('start')
# index of current block
currblock = 0
for line in lines:
line +=... |
java | protected void generateConstructor(SourceWriter sourceWriter, String simpleName, JClassType inputType, PojoDescriptor<?> pojoDescriptor,
GeneratorContext context) {
generateSourcePublicConstructorDeclaration(sourceWriter, simpleName);
sourceWriter.print("super(new ");
sourceWriter.print(SimpleGeneric... |
python | def load(self):
""" Loads the user's account details and
Raises
parseException
"""
pg = self.usr.getPage("http://www.neopets.com/bank.phtml")
# Verifies account exists
if not "great to see you again" in pg.content:
logging.getL... |
java | public void decode(DataItemListener dataItemListener) throws CborException {
Objects.requireNonNull(dataItemListener);
DataItem dataItem = decodeNext();
while (dataItem != null) {
dataItemListener.onDataItem(dataItem);
dataItem = decodeNext();
}
} |
python | def configure():
"""
Configures YAML parser for Step serialization and deserialization
Called in drain/__init__.py
"""
yaml.add_multi_representer(Step, step_multi_representer)
yaml.add_multi_constructor('!step', step_multi_constructor)
yaml.Dumper.ignore_aliases = lambda *args: True |
python | def iscomplex(polynomial):
"""Returns whether the polynomial has complex coefficients
:param polynomial: Polynomial of noncommutive variables.
:type polynomial: :class:`sympy.core.expr.Expr`.
:returns: bool -- whether there is a complex coefficient.
"""
if isinstance(polynomial, (int, float)):... |
java | public static TimecodeDuration calculateDuration(Timecode inPoint, Timecode outPoint)
{
if (!inPoint.isCompatible(outPoint)) {
MutableTimecode mutableTimecode = new MutableTimecode(outPoint);
mutableTimecode.setTimecodeBase(inPoint.getTimecodeBase());
mutableTimecode.setD... |
python | def get_child(parent, child_index):
"""
Get the child at the given index, or return None if it doesn't exist.
"""
if child_index < 0 or child_index >= len(parent.childNodes):
return None
return parent.childNodes[child_index] |
java | private Subject authenticateWithCertificateChain(SSLSession session) throws SSLPeerUnverifiedException, AuthenticationException, CredentialExpiredException, CredentialDestroyedException {
Subject transportSubject = null;
if (session != null) {
Certificate[] certificateChain = session.getPeer... |
python | def _toOriginal(self, val):
""" Pitty attempt to convert itertools result into a real object
"""
if self._clean.isTuple():
return tuple(val)
elif self._clean.isList():
return list(val)
elif self._clean.isDict():
return dict(val)
else:
... |
java | public void marshall(ConferenceProvider conferenceProvider, ProtocolMarshaller protocolMarshaller) {
if (conferenceProvider == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(conferenceProvider.getArn... |
java | @Api
public void initializeList(Collection<SearchWidget> searchWidgets) {
LinkedHashMap<String, String> values = new LinkedHashMap<String, String>();
for (SearchWidget searchWidget : searchWidgets) {
values.put(searchWidget.getSearchWidgetId(), searchWidget.getName());
}
selectSearch.setValueMap(values);
... |
python | def getMeasurement(self, measurementId, measurementStatus=None):
"""
Gets the measurement with the given id.
:param measurementId: the id.
:param measurementStatus: the status of the requested measurement.
:return: the matching measurement or none if it doesn't exist.
"""... |
java | private boolean validate(TextInputControl tf) {
boolean res = tf.getText().trim().length() == 0;
ObservableList<String> styleClass = tf.getStyleClass();
if (res) {
if (!styleClass.contains("error")) {
tf.setStyle("-text-area-background: " + errorColor + ";");
... |
python | def cache_infos(self, queryset):
"""
Cache the number of entries published and the last
modification date under each tag.
"""
self.cache = {}
for item in queryset:
# If the sitemap is too slow, don't hesitate to do this :
# self.cache[item.pk] = ... |
python | def get_gated_grpc_tensors(self, matching_debug_op=None):
"""Extract all nodes with gated-gRPC debug ops attached.
Uses cached values if available.
This method is thread-safe.
Args:
graph_def: A tf.GraphDef proto.
matching_debug_op: Return tensors and nodes with only matching the
s... |
python | def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False):
'''
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* a... |
python | def _method_response_handler(self, response: Dict[str, Any]):
"""处理200~399段状态码,为对应的响应设置结果.
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True
"""
code = response.get("CODE")
if code in (200, 300):
self._resu... |
python | def on_get(resc, req, resp):
""" Get the models identified by query parameters
We return an empty list if no models are found.
"""
signals.pre_req.send(resc.model)
signals.pre_req_search.send(resc.model)
models = goldman.sess.store.search(resc.rtype, **{
'filters': req.filters,
... |
python | def _process_name_or_alias_filter_directive(filter_operation_info, location, context, parameters):
"""Return a Filter basic block that checks for a match against an Entity's name or alias.
Args:
filter_operation_info: FilterOperationInfo object, containing the directive and field info
... |
python | def _nvram_file(self):
"""
Path to the nvram file
"""
return os.path.join(self.working_dir, "nvram_{:05d}".format(self.application_id)) |
python | def showPopup( self ):
"""
Displays a custom popup widget for this system if a checkable state \
is setup.
"""
if not self.isCheckable():
return super(XComboBox, self).showPopup()
if not self.isVisible():
return
# update t... |
java | public static ExceptionAnnotation exception(Throwable t)
{
if (t instanceof InvocationTargetException)
{
if (GreenPepper.isDebugEnabled()) {
LOGGER.info("Caught exception in fixture execution", t);
}
return new ExceptionAnnotation( ((InvocationTargetException) t).getTa... |
java | public void fillTo(int size)
{
if (size <= 0)
return;
if (pool.getLogger().isTraceEnabled())
{
synchronized (this)
{
pool.getLogger().trace(ManagedConnectionPoolUtility.fullDetails(this,
"fillTo(" + size + ")",
pool.getConnection... |
python | def read_data(self, **kwargs):
"""
get the data from the service
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
trigger_id = kwargs.get('trigger_id')
date_triggered = str(kwargs.get('date_trigg... |
java | public boolean add(Cell c) {
if (c == null) {
throw new DeepGenericException(new IllegalArgumentException("cell parameter cannot be null"));
}
return getCellsByTable(nameSpace).add(c);
} |
java | @Override
protected boolean copyRequestedContentToResponse(String requestedPath, HttpServletResponse response,
String contentType) throws IOException {
boolean copyDone = false;
if (isValidRequestedPath(requestedPath)) {
try {
writeContent(requestedPath, null, response);
response.setContentType(con... |
java | private void removeEventWait(String eventName) throws SQLException {
String query = "delete from EVENT_WAIT_INSTANCE where EVENT_NAME=?";
db.runUpdate(query, eventName);
this.recordEventHistory(eventName, EventLog.SUBCAT_DEREGISTER,
"N/A", 0L, "Deregister all existing waiters");
... |
java | private static <T> List<T> unmodifiableList(List<T> list) {
if (list == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(list);
} |
java | private long doUnwrap(ByteBuffer[] userBuffers, int off, int len) throws IOException {
if(anyAreSet(state, FLAG_CLOSED)) {
throw new ClosedChannelException();
}
if(outstandingTasks > 0) {
return 0;
}
if(anyAreSet(state, FLAG_READ_REQUIRES_WRITE)) {
... |
java | public XMLNode parseXML(String root) {
if (xmlElementsMap.containsKey(root)) {
return xmlElementsMap.get(root);
}
try {
currentRoot = root;
isParsing = false;
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParse... |
python | def event(self, event):
"""
Forwards events to the corresponding instance of your event handler
for this process.
If you subclass L{EventSift} and reimplement this method, no event
will be forwarded at all unless you call the superclass implementation.
If your filtering... |
java | static <T> T transform(Object value, Class<T> toClazz, Registry registry) {
try {
if (toClazz.isInstance(value)) {
return (T) value;
}
else if (value instanceof BindObject) {
T bean = newInstance(toClazz);
for(Map.Entry<String,... |
python | def new_feed(self, name: str, layer_shape: tuple):
"""
Creates a feed layer. This is usually the first layer in the network.
:param name: name of the layer
:return:
"""
feed_data = tf.placeholder(tf.float32, layer_shape, 'input')
self.__network.add_layer(name, la... |
java | public Item getItem(int position) {
//if we are out of range just return null
if (position < 0 || position >= mGlobalSize) {
return null;
}
//now get the adapter which is responsible for the given position
int index = floorIndex(mAdapterSizes, position);
retur... |
python | def _writeSedimentTable(self, session, fileObject, mapTable, replaceParamFile):
"""
Write Sediment Mapping Table Method
This method writes the sediments special mapping table case.
"""
# Write the sediment mapping table header
fileObject.write('%s\n' % (mapTable.name))
... |
java | @SuppressWarnings("resource")
private InputStream loadFile(String trustStorePath) throws FileNotFoundException {
InputStream input;
try {
input = new FileInputStream(trustStorePath);
} catch (FileNotFoundException e) {
LOGGER.warn("File {} not found. Fallback to class... |
python | def get_unique_constraint_declaration_sql(self, name, index):
"""
Obtains DBMS specific SQL code portion needed to set a unique
constraint declaration to be used in statements like CREATE TABLE.
:param name: The name of the unique constraint.
:type name: str
:param inde... |
python | def OnCellSelected(self, event):
"""Cell selection event handler"""
key = row, col, tab = event.Row, event.Col, self.grid.current_table
# Is the cell merged then go to merging cell
cell_attributes = self.grid.code_array.cell_attributes
merging_cell = cell_attributes.get_merging... |
python | def delete_dagobah(self, dagobah_id):
""" Deletes the Dagobah and all child Jobs from the database.
Related run logs are deleted as well.
"""
rec = self.dagobah_coll.find_one({'_id': dagobah_id})
for job in rec.get('jobs', []):
if 'job_id' in job:
se... |
java | public static String data(byte[] data, int offset, int length) {
try {
return stream(new ByteArrayInputStream(data, offset, length), length);
} catch (IOException e) {
throw new AssertionError(e);
}
} |
java | private void setParam(ElementEnum elementEnumParam, String objectParam, LiteralOption selector)
{
this.elementEnumParam = elementEnumParam;
this.objectParam = objectParam;
this.selector = selector;
} |
java | private static void decodeEdifactSegment(BitSource bits, StringBuilder result) {
do {
// If there is only two or less bytes left then it will be encoded as ASCII
if (bits.available() <= 16) {
return;
}
for (int i = 0; i < 4; i++) {
int edifactValue = bits.readBits(6);
... |
python | def compile_flags(args):
"""
Build a dictionnary with an entry for cppflags, ldflags, and cxxflags.
These options are filled according to the command line defined options
"""
compiler_options = {
'define_macros': args.defines,
'undef_macros': args.undefs,
'include_dirs': a... |
java | public static <T> Iterator<T> toUnique(Iterator<T> self, Comparator<T> comparator) {
return new UniqueIterator<T>(self, comparator);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.