language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public Map<String, Map<String, Set<String>>> getTargetLanguagesMap() {
if (targetLanguagesMap == null) {
assert false;
return Collections.emptyMap();
}
return Collections.unmodifiableMap(targetLanguagesMap);
} |
java | @Override
public void handleChannelData(final String action, final JSONArray payload) throws BitfinexClientException {
if (payload.isEmpty()) {
return;
}
// channel symbol trade:1m:tLTCUSD
final Set<BitfinexCandle> candlestickList = new TreeSet<>(Comparator.comparing(Bitf... |
python | def set_trace_cond(*args, **kw):
""" Sets a condition for set_trace statements that have the
specified marker. A condition can either callable, in
which case it should take one argument, which is the
number of times set_trace(marker) has been called,
or it can be a number, in which ... |
python | def get_varname_from_locals(val, locals_, default='varname-not-found',
strict=False, cmpfunc_=operator.is_):
""" Finds the string name which has where locals_[name] is val
Check the varname is in the parent namespace
This will only work with objects not primatives
Args:
... |
python | def install(self):
"""
Run the actual installation
"""
self._start_install()
mr_link = self._get_mr_link()
# Set up the progress bar
pbar = ProgressBar(100, 'Running installation...')
pbar.start()
mr_j, mr_r = self._ajax(mr_link)
# Loop u... |
python | def run_commands (self):
"""Generate config file and run commands."""
cwd = os.getcwd()
data = []
data.append('config_dir = %r' % os.path.join(cwd, "config"))
data.append("install_data = %r" % cwd)
data.append("install_scripts = %r" % cwd)
self.create_conf_file(da... |
python | def firmware_autoupgrade_params_ipaddress(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware = ET.SubElement(config, "firmware", xmlns="urn:brocade.com:mgmt:brocade-firmware")
autoupgrade_params = ET.SubElement(firmware, "autoupgrade-params")
... |
python | def UploadArtifactYamlFile(file_content,
overwrite=True,
overwrite_system_artifacts=False):
"""Upload a yaml or json file as an artifact to the datastore."""
loaded_artifacts = []
registry_obj = artifact_registry.REGISTRY
# Make sure all artifacts are loaded... |
java | private void readConfigFile() {
File configFile = new File(CONFIG_FILE_PATH);
/* config file is not there -> create config file with default */
if (!configFile.exists()) {
resetConfigToDefault();
}
try {
PropertiesConfiguration conf = new PropertiesConfiguration(CONFIG_FILE_PATH... |
python | def find_typed_function(pytype, prefix, suffix, module=lal):
"""Returns the lal method for the correct type
Parameters
----------
pytype : `type`, `numpy.dtype`
the python type, or dtype, to map
prefix : `str`
the function name prefix (before the type tag)
suffix : `str`
... |
python | def ParseNotificationcenterRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses a message row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
... |
python | def _notification_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Handle notification statement."""
self._handle_child(NotificationNode(), stmt, sctx) |
python | def scan_posts(self, really=True, ignore_quit=False, quiet=True):
"""Rescan the site."""
while (self.db.exists('site:lock') and
int(self.db.get('site:lock')) != 0):
self.logger.info("Waiting for DB lock...")
time.sleep(0.5)
self.db.incr('site:lock')
... |
python | def sendPassword(self, password):
"""send password"""
pw = (password + '\0' * 8)[:8] #make sure its 8 chars long, zero padded
des = RFBDes(pw)
response = des.encrypt(self._challenge)
self.transport.write(response) |
python | def get(self, path, query, **options):
"""Parses GET request options and dispatches a request."""
api_options = self._parse_api_options(options, query_string=True)
query_options = self._parse_query_options(options)
parameter_options = self._parse_parameter_options(options)
# opt... |
python | def get_repo(self, cached=True):
"""Get a git repository object for this instance."""
module = sys.modules[self.__module__]
# We use module.__file__ instead of module.__path__[0]
# to include modules without a __path__ attribute.
if hasattr(self.__class__, '_repo') and cached:
... |
python | def get_subaccount_info(self):
"""Get information about a sub account."""
method = 'GET'
endpoint = '/rest/v1/users/{}/subaccounts'.format(
self.client.sauce_username)
return self.client.request(method, endpoint) |
java | static boolean isDefinedValue(Node value) {
switch (value.getToken()) {
case ASSIGN: // Only the assigned value matters here.
case CAST:
case COMMA:
return isDefinedValue(value.getLastChild());
case AND:
case OR:
return isDefinedValue(value.getFirstChild())
... |
java | private void parseMappingDefinitions(BeanDefinitionBuilder builder, Element element) {
HashMap<String, String> mappings = new HashMap<String, String>();
for (Element matcher : DomUtils.getChildElementsByTagName(element, "mapping")) {
mappings.put(matcher.getAttribute("path"), matcher.getAttr... |
java | public final void annotationName() throws RecognitionException {
int annotationName_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 66) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:617:5: ( Identifier ( '.' Identifier )* )
//... |
python | def _import_data(self):
"""Import data from a stat file.
"""
# set default state to ironpython for very old ironpython (2.7.0)
iron_python = True
try:
iron_python = True if platform.python_implementation() == 'IronPython' \
else False
except Va... |
python | def delete_row(self, index):
""""Deletes the row from the worksheet at the specified index.
:param index: Index of a row for deletion.
:type index: int
"""
body = {
"requests": [{
"deleteDimension": {
"range": {
... |
python | def RenderPayload(self, result, value):
"""Renders GrrMessage payload and renames args_rdf_name field."""
if "args_rdf_name" in result:
result["payload_type"] = result["args_rdf_name"]
del result["args_rdf_name"]
if "args" in result:
result["payload"] = self._PassThrough(value.payload)
... |
java | public Instances samoaInstances(weka.core.Instances instances) {
Instances samoaInstances = samoaInstancesInformation(instances);
//We assume that we have only one samoaInstanceInformation for WekaToSamoaInstanceConverter
this.samoaInstanceInformation = samoaInstances;
for (int i = 0; i ... |
java | public CmsDNDHandler getDNDHandler() {
if (m_dndHandler == null) {
m_dndHandler = new CmsDNDHandler(new CmsAttributeDNDController());
m_dndHandler.setOrientation(Orientation.VERTICAL);
m_dndHandler.setScrollEnabled(true);
m_dndHandler.setScrollElement(m_scr... |
java | public static MozuUrl addProductInCatalogUrl(String productCode, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/ProductInCatalogs?responseFields={responseFields}");
formatter.formatUrl("productCode", productCode);
formatter.formatUrl("re... |
python | def edgelist_to_adjacency(edgelist):
"""Converts an iterator of edges to an adjacency dict.
Args:
edgelist (iterable):
An iterator over 2-tuples where each 2-tuple is an edge.
Returns:
dict: The adjacency dict. A dict of the form {v: Nv, ...} where v is a node in a graph and
... |
python | def launch_eval_job(tag, m1_path, m2_path, job_name, completions):
"""Launches an evaluator job.
tag: name for this eval job (used as top level folder name)
m1_path, m2_path: full gs:// paths to the .pb files to match up
job_name: string, appended to the container, used to differentiate the job
name... |
java | public static boolean containsRTLText(String str)
{
if (str != null)
{
for (int i = 0; i < str.length(); i++)
{
char cc = str.charAt(i);
// hebrew extended and basic, arabic basic and extendend
if (cc >= 1425 && cc <= 1785)
{
return true;
}
... |
python | def update_resources(Cnt):
'''Update resources.py with the paths to the new installed apps.
'''
# list of path names which will be saved
key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR']
# get the local path to NiftyPET resources.py
path_resources = cs.path_niftypet_local()
... |
java | public static <K,V> Map<?, ?> collectEntries(Map<K, V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<?> transform) {
return collectEntries(self, createSimilarMap(self), transform);
} |
java | public void handleEvent(Object event) throws InvocationTargetException {
if (!valid) {
throw new IllegalStateException(toString() + " has been invalidated and can no longer handle events.");
}
try {
method.invoke(target, event);
} catch (IllegalAccessException e) {
throw new AssertionE... |
java | public boolean exists() {
// Try file existence: can we find the file in the file system?
try {
return getFile().exists();
}
catch (IOException ex) {
// Fall back to stream existence: can we open the stream?
try {
InputStream is = getInputStream();
is.close();
return true;
}
catch (Th... |
java | public int getSelectedFontSize() {
int fontSize = 1;
String fontSizeString = getFontSizeTextField().getText();
while (true) {
try {
fontSize = Integer.parseInt(fontSizeString);
break;
} catch (NumberFormatException e) {
font... |
java | public static final void validateToken(AuthToken token) throws IllegalArgumentException {
if (token.getExpiresOn().before(new Date())) {
throw new IllegalArgumentException("Authentication token expired: " + token.getExpiresOn()); //$NON-NLS-1$
}
String validSig = generateSignature(to... |
java | private void set(int pos, String s) {
buffer.delete(pos, buffer.length());
buffer.insert(pos, s);
} |
java | @Override
protected List<Object> populateEntities(EntityMetadata m, Client client)
{
ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();
if (!MetadataUtils.useSecondryIndex(clientMetadata) && (clientMetadata.getIndexImplementor() != null))
{
return po... |
python | def createTemplate(data):
"""
Create a new template.
Args:
`data`: json data required for creating a template
Returns:
Dictionary containing the details of the template with its ID.
"""
conn = Qubole.agent()
return conn.post(Template.rest_... |
python | def get_resource_url(self):
""" Get resource complete url """
name = self.__class__.resource_name
url = self.__class__.rest_base_url()
if self.id is not None:
return "%s/%s/%s" % (url, name, self.id)
return "%s/%s" % (url, name) |
java | @Override
public Collection<KamEdge> getEdges(EdgeFilter filter) {
return wrapEdges(kam.getEdges(filter));
} |
python | def maps_get_default_rules_output_rules_groupname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_default_rules = ET.Element("maps_get_default_rules")
config = maps_get_default_rules
output = ET.SubElement(maps_get_default_rules, "output... |
java | public java.lang.String getFullName() {
java.lang.Object ref = fullName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
fullNa... |
python | def get(self, ids, **kwargs):
"""
Method to get interfaces by their ids.
:param ids: List containing identifiers of interfaces.
:return: Dict containing interfaces.
"""
url = build_uri_with_ids('api/v3/interface/%s/', ids)
return super(ApiInterfaceRequest, self)... |
java | @SuppressWarnings("rawtypes")
public static Class loadClass(Class loadClass, String name,
boolean checkParents) throws ClassNotFoundException {
ClassNotFoundException ex = null;
Class<?> c = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
while (c == null && loader != null)... |
python | def radialrange(self, origin, return_all_global_extrema=False):
"""returns the tuples (d_min, t_min, idx_min), (d_max, t_max, idx_max)
which minimize and maximize, respectively, the distance
d = |self[idx].point(t)-origin|."""
if return_all_global_extrema:
raise NotImplemente... |
java | public static <K, V, T> T[] toArray(Map<K, V> map, T[] entryArray) {
return toList(map, entryArray.getClass().getComponentType()).toArray(entryArray);
} |
python | def from_yaml(cls, yaml_path, filename=None):
"""Split a dictionary into parameters controllers parts blocks defines
Args:
yaml_path (str): File path to YAML file, or a file in the same dir
filename (str): If give, use this filename as the last element in
the yam... |
java | private void processLog() {
if (!database.isFilesInJar() && fa.isStreamElement(logFileName)) {
ScriptRunner.runScript(database, logFileName,
ScriptWriterBase.SCRIPT_TEXT_170);
}
} |
java | public static String open(Tag tag, AttributeValue... attrs) {
StringBuffer sb = new StringBuffer();
sb.append("<").append(tag.name());
for (AttributeValue attr : attrs) {
sb.append(" ").append(attr.toString());
}
sb.append(">");
return sb.toString();
} |
java | public Configuration getConfiguration() {
final Configuration conf = new Configuration();
for (Map.Entry<String, String> entry : data.entrySet()) {
conf.setString(entry.getKey(), entry.getValue());
}
return conf;
} |
java | public final void initLineNumber(int lineNumber)
{
if (lineNumber <= 0) throw new IllegalArgumentException(String.valueOf(lineNumber));
if (this.lineNumber > 0) throw new IllegalStateException();
this.lineNumber = lineNumber;
} |
python | def request_log_level(self, req, msg):
"""Query or set the current logging level.
Parameters
----------
level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \
'off'}, optional
Name of the logging level to set the device server to (the default
... |
python | def fBellStates(self):
"""
Get a dictionary of two-qubit Bell state fidelities (normalized to unity)
from the specs, keyed by targets (qubit-qubit pairs).
:return: A dictionary of Bell state fidelities, normalized to unity.
:rtype: Dict[tuple(int, int), float]
"""
... |
java | public ServiceFuture<VirtualMachineExtensionImageInner> getAsync(String location, String publisherName, String type, String version, final ServiceCallback<VirtualMachineExtensionImageInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(location, publisherName, type, version), ... |
python | def main(_):
"""Create or load configuration and launch the trainer."""
utility.set_up_logging()
if not FLAGS.config:
raise KeyError('You must specify a configuration.')
logdir = FLAGS.logdir and os.path.expanduser(os.path.join(
FLAGS.logdir, '{}-{}'.format(FLAGS.timestamp, FLAGS.config)))
try:
... |
java | public void addHttpSession(HttpSession session) {
synchronized (this.sessions) {
this.sessions.add(session);
}
this.model.addHttpSession(session);
} |
python | def add_args(self):
"""
Adds arguments
"""
self.parser.description = textwrap.dedent("""
Segment the .po files in LOCALE(s) based on the segmenting rules in
config.yaml.
Note that segmenting is *not* idempotent: it modifies the input file, so
be careful t... |
java | protected void snapshot(String fileName) throws Exception {
configuration.save(new File(fileName));
model.snapshotSessionDb(this.fileName, fileName);
} |
java | @Override
public void removeDeploymentGroup(final String name) throws DeploymentGroupDoesNotExistException {
log.info("removing deployment-group: name={}", name);
final ZooKeeperClient client = provider.get("removeDeploymentGroup");
try {
client.ensurePath(Paths.configDeploymentGroups());
clie... |
java | private Response readResponse() throws IOException {
Response response = new Response();
response.setResponseCode(connection.getResponseCode());
response.setResponseMessage(connection.getResponseMessage());
response.setHeaders(connection.getHeaderFields());
try {
response.setBody(getStringFromStream(connec... |
java | private void parsePEReference() throws SAXException, IOException {
String name;
name = "%" + readNmtoken(true);
require(';');
switch (getEntityType(name)) {
case ENTITY_UNDECLARED:
// VC: Entity Declared
handler.verror("reference to undeclared... |
java | public void setTail(final WComponent tail) {
DecoratedLabelModel model = getOrCreateComponentModel();
if (model.tail != null) {
remove(model.tail);
}
model.tail = tail;
if (tail != null) {
add(tail);
}
} |
java | public CallTreeNode onStopwatchStop(Split split) {
CallTreeNode currentNode = callStack.removeLast();
currentNode.addSplit(split);
if (callStack.isEmpty()) {
onRootStopwatchStop(currentNode, split);
}
return currentNode;
} |
java | private Set<String> getSchemaHeadIncludes(CmsObject cms, CmsResource res, String type) throws CmsLoaderException {
if (type.equals(TYPE_CSS)) {
return getCSSHeadIncludes(cms, res);
} else if (type.equals(TYPE_JAVASCRIPT)) {
return getJSHeadIncludes(cms, res);
}
r... |
java | public long getRepositoryDataSize(String repositoryName) throws QuotaManagerException
{
RepositoryQuotaManager rqm = getRepositoryQuotaManager(repositoryName);
return rqm.getRepositoryDataSize();
} |
python | def list_menu_multi(self, options, title="Choose one or more values", message="Choose one or more values",
defaults: list=None, **kwargs):
"""
Show a multiple-selection list menu
Usage: C{dialog.list_menu_multi(options, title="Choose one or more values", message=... |
python | def mock(config_or_spec=None, spec=None, strict=OMITTED):
"""Create 'empty' objects ('Mocks').
Will create an empty unconfigured object, that you can pass
around. All interactions (method calls) will be recorded and can be
verified using :func:`verify` et.al.
A plain `mock()` will be not `strict`,... |
java | public static com.apptentive.android.sdk.model.SdkAndAppReleasePayload getPayload(Sdk sdk, AppRelease appRelease) {
com.apptentive.android.sdk.model.SdkAndAppReleasePayload ret = new com.apptentive.android.sdk.model.SdkAndAppReleasePayload();
if (appRelease == null) {
return ret;
}
// sdk data
ret.setAuth... |
python | def draw_peaks(self, x, peaks, line_color):
"""Draw 2 peaks at x"""
y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
if self.previous_y:
self.draw.line(
[self.prev... |
java | public Record []
run() {
if (done)
reset();
if (name.isAbsolute())
resolve(name, null);
else if (searchPath == null)
resolve(name, Name.root);
else {
if (name.labels() > defaultNdots)
resolve(name, Name.root);
if (done)
return answers;
for (int i = 0; i < searchPath.length; i++) {
resolve(name... |
java | private static String formatISO6709Medium(final PointLocation pointLocation)
{
final Latitude latitude = pointLocation.getLatitude();
final Longitude longitude = pointLocation.getLongitude();
String string = formatLatitudeMedium(latitude) +
formatLongitudeMedium(longitude);
final d... |
java | @Override
public Time fromString(Class targetClass, String s)
{
if (s == null)
{
return null;
}
if (StringUtils.isNumeric(s))
{
return new Time(Long.parseLong(s));
}
Time t = Time.valueOf(s);
return t;
} |
python | def _parse_write_concern(options):
"""Parse write concern options."""
concern = options.get('w')
wtimeout = options.get('wtimeoutms')
j = options.get('journal')
fsync = options.get('fsync')
return WriteConcern(concern, wtimeout, j, fsync) |
python | def _get_any_translated_model(self, meta=None):
"""
Return any available translation.
Returns None if there are no translations at all.
"""
if meta is None:
meta = self._parler_meta.root
tr_model = meta.model
local_cache = self._translations_cache[tr_... |
python | def open_remote(url, entry, container, user_parameters, description, http_args,
page_size=None, auth=None, getenv=None, getshell=None):
"""Create either local direct data source or remote streamed source"""
from intake.container import container_map
if url.startswith('intake://'):
ur... |
java | public void setPropertyValue(final JsiiObjectRef objRef, final String property, final JsonNode value) {
ObjectNode req = makeRequest("set", objRef);
req.put("property", property);
req.set("value", value);
this.runtime.requestResponse(req);
} |
java | private void initCodec(IoSession session) throws Exception {
// Creates the decoder and stores it into the newly created session
ProtocolDecoder decoder = factory.getDecoder(session);
session.setAttribute(DECODER, decoder);
// Creates the encoder and stores it into the newly created ses... |
java | public InferenceSpecification withSupportedTransformInstanceTypes(TransformInstanceType... supportedTransformInstanceTypes) {
java.util.ArrayList<String> supportedTransformInstanceTypesCopy = new java.util.ArrayList<String>(supportedTransformInstanceTypes.length);
for (TransformInstanceType value : supp... |
java | @Override
public boolean remove(Object object) {
if (booleanTerms == null) {
return false;
}
return booleanTerms.remove(object);
} |
java | public Object createConnectionFactory(
final ConnectionManager connectionManager) {
if (TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "createConnectionFactory",
connectionManager);
}
final Object connectionFactory = new SibRaConnectionFactory(th... |
python | def set_pipeline(filename, scan, fileroot='', paramfile='', **kwargs):
""" Function defines pipeline state for search. Takes data/scan as input.
fileroot is base name for associated products (cal files, noise, cands). if blank, it is set to filename.
paramfile is name of file that defines all pipeline param... |
java | public static int readLength(InputStream in) throws IOException, EOFException {
int b0 = in.read();
if (b0 < 0) {
throw new EOFException();
}
if (b0 <= 0x7f) {
return b0;
}
int b1 = in.read();
if (b1 < 0) {
throw new E... |
python | def _get_task_target():
"""Get the default target for a pipeline task.
Current version id format is: user_defined_version.minor_version_number
Current module id is just the module's name. It could be "default"
Returns:
A complete target name is of format version.module. If module is the
default module, ... |
java | @Scope(DocScope.IO)
public <T> T read(final Class<T> projectionInterface) throws IOException {
Class<?> callerClass = null;
if (IOHelper.isResourceProtocol(url)) {
callerClass = ReflectionHelper.getDirectCallerClass();
}
Document document = IOHelper.getDocumentFromURL(pro... |
python | def _data_received(self, next_bytes):
"""Maintains buffer of bytes received from peer and extracts bgp
message from this buffer if enough data is received.
Validates bgp message marker, length, type and data and constructs
appropriate bgp message instance and calls handler.
:Pa... |
python | def set_controller(self, controllers):
"""
Sets the OpenFlow controller address.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl set-controller <bridge> <target>...
"""
command = ovs_vsctl.VSCtlCommand('set-controller', [self.br_name])
... |
java | public static void setFactory(IFactory myFactory) {
if (INSTANCE==null) {
INSTANCE = myFactory;
} else {
throw new RuntimeException("Factory has already been set to value [" + INSTANCE.getClass().getName() + "]");
}
} |
python | def setupViewletByName(self, name):
""" Constructs a viewlet instance by its name.
Viewlet update() and render() method are not called.
@return: Viewlet instance of None if viewlet with name does not exist
"""
context = aq_inner(self.context)
request = self.request
... |
python | def add_problem_hparams(hparams, problem_name_or_instance):
"""Add problem hparams for the problems."""
if isinstance(problem_name_or_instance, problem_lib.Problem):
problem = problem_name_or_instance
else:
problem = registry.problem(problem_name_or_instance)
p_hparams = problem.get_hparams(hparams)
h... |
java | public static SocketTransport connect(InetSocketAddress address, X509Certificate pinnedcert) throws IOException {
SSLSocketFactory factory = get_ssl_socket_factory(pinnedcert);
Socket s = factory.createSocket(address.getHostString(), address.getPort());
return new SocketTransport(s);
} |
java | protected void disconnect() {
if (client != null) {
try {
client.stop();
} catch (Exception ignored) {
}
}
synchronized (publishers) {
for (TopicPublisher publisher : publishers.values()) {
try {
publisher.close();
} catch (Exception ignored) {
}
}
publishers.c... |
java | public MultipleSheetBindingErrors<Object> saveMultipleDetail(final InputStream templateXlsIn, final OutputStream xlsOut, final Object[] beanObjs)
throws XlsMapperException, IOException {
ArgUtils.notNull(templateXlsIn, "templateXlsIn");
ArgUtils.notNull(xlsOut, "xlsOut");
ArgUt... |
java | static boolean uninstall() {
boolean uninstalled = false;
synchronized (lock) {
if (locationCollectionClient != null) {
locationCollectionClient.locationEngineController.onDestroy();
locationCollectionClient.settingsChangeHandlerThread.quit();
locationCollectionClient.sharedPrefere... |
python | def request(self, method, url, params=None, **kwargs):
"""Perform a request, or return a cached response if available."""
params_key = tuple(params.items()) if params else ()
if method.upper() == "GET":
if (url, params_key) in self.get_cache:
print("Returning cached r... |
java | public static Optional<JobReturnEvent> parse(Event event) {
Matcher matcher = PATTERN.matcher(event.getTag());
if (matcher.matches()) {
Data data = event.getData(Data.class);
JobReturnEvent result = new JobReturnEvent(matcher.group(1), matcher.group(2),
data);... |
python | def get_sections(self, hdrgo, dflt_section=True):
"""Given a header GO, return the sections that contain it."""
dflt_list = []
# If the hdrgo is not in a section, return the default name for a section
if dflt_section:
dflt_list = [self.secdflt]
return self.hdrgo2secti... |
java | public ColumnType getType(int column) {
if (column < 0 || column >= columnMetaData.size())
throw new IllegalArgumentException(
"Invalid column number. " + column + "only " + columnMetaData.size() + "present.");
return columnMetaData.get(column).getColumnType();
... |
java | public static void changeProperty(String filename, String[] allowedHosts, String[] allowedUsers) throws IOException {
if ((allowedHosts == null || allowedHosts.length == 0) && (allowedUsers == null || allowedUsers.length == 0)) {
return;
}
final File file = new File(filename);
... |
java | public final hqlParser.quantifiedExpression_return quantifiedExpression() throws RecognitionException {
hqlParser.quantifiedExpression_return retval = new hqlParser.quantifiedExpression_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token SOME226=null;
Token EXISTS227=null;
Token ALL228=n... |
python | def post(self, command, output_dir, vars):
"""
Do some tasks after install
"""
if command.simulate:
return
# Find the 'project/' dir in the created paste project
project_path = join(getcwd(), vars['project'], 'project')
# 1. Mods
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.