language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def dict_to_html_attrs(dict_):
"""
Banana banana
"""
res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items())
return res |
java | private void insert(ArrayList<String> list, String input) {
if (!list.contains(input)) {
if (input.equals("a") || input.equals("rdf:type")) {
list.add(0, input);
} else {
list.add(input);
}
}
} |
python | def original_unescape(self, s):
"""Since we need to use this sometimes"""
if isinstance(s, basestring):
return unicode(HTMLParser.unescape(self, s))
elif isinstance(s, list):
return [unicode(HTMLParser.unescape(self, item)) for item in s]
else:
return ... |
java | public static <T extends Tree> Matcher<T> isVoidType() {
return new Matcher<T>() {
@Override
public boolean matches(T t, VisitorState state) {
Type type = getType(t);
return type != null && state.getTypes().isSameType(type, state.getSymtab().voidType);
}
};
} |
python | def parse_reaction_table_file(path, f, default_compartment):
"""Parse a tab-separated file containing reaction IDs and properties
The reaction properties are parsed according to the header which specifies
which property is contained in each column.
"""
context = FilePathContext(path)
for line... |
python | def _get_speed(element_duration, wpm, word_ref=WORD):
"""
Returns
element duration when element_duration and/or code speed is given
wpm
>>> _get_speed(0.2, None)
(0.2, 5.999999999999999)
>>> _get_speed(None, 15)
(0.08, 15)
>>> _get_speed(None, None)
(0.08, 15)
"""
... |
python | def monitor(options={}):
"""Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook.
It's currently a context manager for legacy reasons.
"""
try:
from IPython.display import display
except ImportError:
def display(stuff): return None
c... |
java | private void writeInitializers(
GinjectorBindings bindings,
StringBuilder initializeEagerSingletonsBody, StringBuilder initializeStaticInjectionsBody,
SourceWriteUtil sourceWriteUtil, SourceWriter writer) {
if (bindings.hasEagerSingletonBindingInSubtree()) {
sourceWriteUtil.writeMethod(writ... |
java | public void validate() {
if (null != failedNodesfile && failedNodesfile.getName().startsWith("${") && failedNodesfile.getName()
.endsWith("}")) {
failedNodesfile=null;
}
} |
python | def cmdSubstituteLines(self, cmd, count):
""" S
"""
lineIndex = self._qpart.cursorPosition[0]
availableCount = len(self._qpart.lines) - lineIndex
effectiveCount = min(availableCount, count)
_globalClipboard.value = self._qpart.lines[lineIndex:lineIndex + effectiveCount]
... |
python | def return_dat(self, chan, begsam, endsam):
"""Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last ... |
java | public static void premain(String agentArgs, @Nonnull Instrumentation inst) {
kvs = splitCommaColonStringToKV(agentArgs);
Logger.setLoggerImplType(getLogImplTypeFromAgentArgs(kvs));
final Logger logger = Logger.getLogger(TtlAgent.class);
try {
logger.info("[TtlAgent.premain... |
java | public void prepareSmallElement(Widget widget) {
m_hasSmallElements = true;
widget.addStyleName(
org.opencms.ade.containerpage.client.ui.css.I_CmsLayoutBundle.INSTANCE.containerpageCss().smallElement());
} |
java | private Future<Boolean> _add(String key, int exp, CachedData value, EVCacheLatch latch) throws Exception {
if (enableChunking.get()) throw new EVCacheException("This operation is not supported as chunking is enabled on this EVCacheClient.");
if (addCounter == null) addCounter = EVCacheMetricsFactory.get... |
python | def set_metadata(self, queue, metadata, clear=False):
"""
Accepts a dictionary and adds that to the specified queue's metadata.
If the 'clear' argument is passed as True, any existing metadata is
replaced with the new metadata.
"""
return self._manager.set_metadata(queue,... |
python | def is_suburi(self, base, test):
"""Check if test is below base in a URI tree
Both args must be URIs in reduced form.
"""
if base == test:
return True
if base[0] != test[0]:
return False
common = posixpath.commonprefix((base[1], test[1]))
... |
java | private static <T> T nullForNotFound(IOException exception) {
ComputeException serviceException = translate(exception);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return null;
}
throw serviceException;
} |
python | def channel_close(
self,
registry_address: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
):
"""Close a channel opened with `partner_address` for the given
`to... |
python | def searchNs(self, node, nameSpace):
"""Search a Ns registered under a given name space for a
document. recurse on the parents until it finds the defined
namespace or return None otherwise. @nameSpace can be None,
this is a search for the default namespace. We don't allow
... |
java | public ServiceFuture<VaultInner> getByResourceGroupAsync(String resourceGroupName, String vaultName, final ServiceCallback<VaultInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, vaultName), serviceCallback);
} |
java | public static List<String> getParameterList(String parameterString) {
List<String> parameterList = new ArrayList<>();
StringTokenizer tok = new StringTokenizer(parameterString, ",");
while (tok.hasMoreElements()) {
String param = tok.nextToken().trim();
parameterList.add... |
python | def heatmaps_to_keypoints(maps, rois):
"""Extract predicted keypoint locations from heatmaps. Output has shape
(#rois, 4, #keypoints) with the 4 rows corresponding to (x, y, logit, prob)
for each keypoint.
"""
# This function converts a discrete image coordinate in a HEATMAP_SIZE x
# HEATMAP_SIZ... |
python | def add_params(self, **kw):
"""
Add [possibly many] parameters to the track.
Parameters will be checked against known UCSC parameters and their
supported formats.
E.g.::
add_params(color='128,0,0', visibility='dense')
"""
for k, v in kw.items():
... |
java | public <T> void setHintValue(Hint<T> hint, T value) {
if (value == null) {
throw new IllegalArgumentException("Null value passed.");
}
hintValues.put(hint, value);
} |
java | public void flush() {
for (Iterator<Map.Entry<OFileMMap, OMMapBufferEntry[]>> it = bufferPoolPerFile.entrySet().iterator(); it.hasNext();) {
OFileMMap file;
final Map.Entry<OFileMMap, OMMapBufferEntry[]> mapEntry = it.next();
file = mapEntry.getKey();
lockManager.acquireLock(Thread.curr... |
python | def transpose(self):
"""transpose operation of self
Returns
-------
Matrix : Matrix
transpose of self
"""
if not self.isdiagonal:
return type(self)(x=self.__x.copy().transpose(),
row_names=self.col_names,
... |
python | def subplots_adjust(fig=None, inches=1):
"""Enforce margin to be equal around figure, starting at subplots.
.. note::
You probably should be using wt.artists.create_figure instead.
See Also
--------
wt.artists.plot_margins
Visualize margins, for debugging / layout.
wt.artists.c... |
java | @NonNull
public static PaymentIntentParams createConfirmPaymentIntentWithPaymentMethodCreateParams(
@Nullable PaymentMethodCreateParams paymentMethodCreateParams,
@NonNull String clientSecret,
@NonNull String returnUrl,
boolean savePaymentMethod) {
return new ... |
python | def _update_tree_feature_weights(X, feature_names, clf, feature_weights):
""" Update tree feature weights using decision path method.
"""
tree_value = clf.tree_.value
if tree_value.shape[1] == 1:
squeeze_axis = 1
else:
assert tree_value.shape[2] == 1
squeeze_axis = 2
tree... |
java | private File resolveIndexDirectoryPath() throws IOException {
if (StringUtils.isEmpty(indexDirectoryPath)) {
indexDirectoryPath = System.getProperty("java.io.tmpdir") + appContext.getApplicationName();
}
File dir = new File(indexDirectoryPath, getClass().getPackage().getName... |
java | private void determineChangesSince(File file, long lastScanTime) {
try {
if (GlobalConfiguration.verboseMode && log.isLoggable(Level.INFO)) {
log.info("Firing file changed event " + file);
}
listener.fileChanged(file);
if (file.isDirectory()) {
File[] filesOfInterest = file.listFiles(new RecentCha... |
python | def select(*signals: Signal, **kwargs) -> List[Signal]:
"""
Allows the current process to wait for multiple concurrent signals. Waits until one of the signals turns on, at
which point this signal is returned.
:param timeout:
If this parameter is not ``None``, it is taken as a delay at the end o... |
python | def interact(self, escape_character=chr(29),
input_filter=None, output_filter=None):
'''This gives control of the child process to the interactive user (the
human at the keyboard). Keystrokes are sent to the child process, and
the stdout and stderr output of the child process is pri... |
python | def _exec_check_pointers(executable):
"""Checks the specified executable for the pointer condition that not
all members of the derived type have had their values set.
Returns (list of offending members, parameter name).
"""
oparams = []
pmembers = {}
xassigns = map(lambda x: x.lower().strip... |
java | public JobSchedulePatchOptions withIfUnmodifiedSince(DateTime ifUnmodifiedSince) {
if (ifUnmodifiedSince == null) {
this.ifUnmodifiedSince = null;
} else {
this.ifUnmodifiedSince = new DateTimeRfc1123(ifUnmodifiedSince);
}
return this;
} |
python | def _refresh(self, session, stopping=False):
'''Get this task's current state.
This must be called under the registry's lock. It updates
the :attr:`finished` and :attr:`failed` flags and the
:attr:`data` dictionary based on the current state in the
registry.
In the nor... |
java | public org.osmdroid.views.overlay.Polygon toPolygon(Polygon polygon) {
org.osmdroid.views.overlay.Polygon newPoloygon = new org.osmdroid.views.overlay.Polygon();
List<GeoPoint> pts = new ArrayList<>();
List<List<GeoPoint>> holes = new ArrayList<>();
List<LineString> rings = polygon.getR... |
java | @Deprecated
public @Nonnull
String getMessage(String key) {
BugPattern bugPattern = DetectorFactoryCollection.instance().lookupBugPattern(key);
if (bugPattern == null) {
return L10N.getLocalString("err.missing_pattern", "Error: missing bug pattern for key") + " " + key;
}
... |
java | @Nullable
public T getItem(final int position) {
if (position < 0 || position >= mObjects.size()) {
return null;
}
return mObjects.get(position);
} |
python | def scan_for_field(self, field_key):
'''
Scan for a field in the container and its enclosed fields
:param field_key: name of field to look for
:return: field with name that matches field_key, None if not found
'''
if field_key == self.get_name():
return self
... |
python | def _is_interactive(self):
''' Prevent middlewares and orders to work outside live mode '''
return not (
self.realworld and (dt.date.today() > self.datetime.date())) |
java | public Group addGroup(String name, String path, String description, Visibility visibility,
Boolean lfsEnabled, Boolean requestAccessEnabled, Integer parentId) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("name", name)
.withParam("path", ... |
java | List<String> argNames(int size) {
List<String> argNames = new ArrayList<>();
for (int i = 0 ; i < size ; i++) {
argNames.add(StubKind.FACTORY_METHOD_ARG.format(i));
}
return argNames;
} |
python | def group_members(self, group, limit=99999):
"""
Get group of members
:param group:
:param limit: OPTIONAL: The limit of the number of users to return, this may be restricted by
fixed system limits. Default by built-in method: 99999
:return:
"""
... |
java | public static boolean getBooleanProperty(final String key) {
return (getPropertyOrNull(key) == null)?
false: Boolean.valueOf(getPropertyOrNull(key)).booleanValue();
} |
java | public static <T extends Exception> org.hamcrest.Matcher<T> hasMessageThat(
Matcher<String> stringMatcher) {
return new ExceptionMessageMatcher<>(stringMatcher);
} |
java | public MessageProcessor createMessageProcessor(@NonNull MessageToSend message, @Nullable List<Attachment> attachments, @NonNull String conversationId, @NonNull String profileId) {
return new MessageProcessor(conversationId, profileId, message, attachments, maxPartSize, log);
} |
python | def create_read_replica(name, source_name, db_instance_class=None,
availability_zone=None, port=None,
auto_minor_version_upgrade=None, iops=None,
option_group_name=None, publicly_accessible=None,
tags=None, db_subnet_group_n... |
java | public static void main (String[] args) throws IOException {
if (args.length < 1) {
System.out.println("Usage: java opennlp.maxent.io.OldFormatGISModelReader model_name_prefix (new_model_name)");
System.exit(0);
}
int nameIndex = 0;
String infilePrefix = args[nameIndex];
String outfile;
if (args.leng... |
java | @Nonnull
public static List<SCMDecisionHandler> listShouldPollVetos(@Nonnull Item item) {
List<SCMDecisionHandler> result = new ArrayList<>();
for (SCMDecisionHandler handler : all()) {
if (!handler.shouldPoll(item)) {
result.add(handler);
}
}
... |
python | def _collect_unrecognized_values(self, scheme, data, ancestors):
""" Looks for values that aren't defined in the scheme and returns a dict with any unrecognized values found.
:param scheme: A :dict:, The scheme defining the validations.
:param data: A :dict: user supplied for this specific prop... |
python | def data_available(dataset_name=None):
"""Check if the data set is available on the local machine already."""
dr = data_resources[dataset_name]
if 'dirs' in dr:
for dirs, files in zip(dr['dirs'], dr['files']):
for dir, file in zip(dirs, files):
if not os.path.exists(os.pa... |
java | public void addValueSet(ValueSet theValueSet) {
Validate.notBlank(theValueSet.getUrl(), "theValueSet.getUrl() must not return a value");
myValueSets.put(theValueSet.getUrl(), theValueSet);
} |
java | @SafeVarargs
public final DataStream<T> union(DataStream<T>... streams) {
List<StreamTransformation<T>> unionedTransforms = new ArrayList<>();
unionedTransforms.add(this.transformation);
for (DataStream<T> newStream : streams) {
if (!getType().equals(newStream.getType())) {
throw new IllegalArgumentExcep... |
java | public static short[] trimToCapacity(short[] array, int maxCapacity) {
if (array.length > maxCapacity) {
short oldArray[] = array;
array = new short[maxCapacity];
System.arraycopy(oldArray, 0, array, 0, maxCapacity);
}
return array;
} |
python | def _get_order_clause(archive_table):
"""Returns an ascending order clause on the versioned unique constraint as well as the
version column.
"""
order_clause = [
sa.asc(getattr(archive_table, col_name)) for col_name in archive_table._version_col_names
]
order_clause.append(sa.asc(archive... |
java | public Observable<PolicySetDefinitionInner> getAsync(String policySetDefinitionName) {
return getWithServiceResponseAsync(policySetDefinitionName).map(new Func1<ServiceResponse<PolicySetDefinitionInner>, PolicySetDefinitionInner>() {
@Override
public PolicySetDefinitionInner call(Service... |
python | def marker_split(block):
"""Yield marker, value pairs from a text block (i.e. a list of lines).
:param block: text block consisting of \n separated lines as it will be the case for \
files read using "rU" mode.
:return: generator of (marker, value) pairs.
"""
marker = None
value = []
f... |
java | public static MutableFst importFst(String basename, Semiring semiring) {
Optional<MutableSymbolTable> maybeInputs = importSymbols(basename + INPUT_SYMS);
Optional<MutableSymbolTable> maybeOutputs = importSymbols(basename + OUTPUT_SYMS);
Optional<MutableSymbolTable> maybeStates = importSymbols(basename + ST... |
java | @Override
public Collection<String> wordsNearestSum(Collection<String> positive, Collection<String> negative, int top) {
INDArray words = Nd4j.create(lookupTable.layerSize());
// Set<String> union = SetUtils.union(new HashSet<>(positive), new HashSet<>(negative));
for (String s : positive... |
python | def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
"""Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) ar... |
python | def weighted_choice(self, probabilities, key):
"""Makes a weighted choice between several options.
Probabilities is a list of 2-tuples, (probability, option). The
probabilties don't need to add up to anything, they are automatically
scaled."""
try:
choice = self.val... |
java | public ClusterInner getByResourceGroup(String resourceGroupName, String clusterName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, clusterName).toBlocking().single().body();
} |
java | public void put(Entity entity) {
int bytesHere = EntityTranslator.convertToPb(entity).getSerializedSize();
// Do this before the add so that we guarantee that size is never > sizeLimit
if (putsBytes + bytesHere >= params.getBytesLimit()) {
flushPuts();
}
putsBytes += bytesHere;
puts.add(... |
java | private String getEs6ModuleNameFromImportNode(NodeTraversal t, Node n) {
String importName = n.getLastChild().getString();
boolean isNamespaceImport = importName.startsWith("goog:");
if (isNamespaceImport) {
// Allow importing Closure namespace objects (e.g. from goog.provide or goog.module) as
... |
java | public static String[] intersect(String[] arr1, String[] arr2) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
LinkedList<String> list = new LinkedList<String>();
for (String str : arr1) {
if (!map.containsKey(str)) {
map.put(str, Boolean.FALSE);
}
}
for (String str : arr2) {
if (map... |
java | @Override
public Character unmarshal(String object) {
if (object.length() == 1) {
return Character.valueOf(object.charAt(0));
} else {
throw new IllegalArgumentException("Only single character String can be unmarshalled to a Character");
}
} |
java | @Pure
@SuppressWarnings("resource")
public static InputStream getResourceAsStream(Class<?> classname, String path) {
if (classname == null) {
return null;
}
InputStream is = getResourceAsStream(classname.getClassLoader(), classname.getPackage(), path);
if (is == null) {
is = getResourceAsStream(classnam... |
python | def disable(self):
"""Disables the plotters in this list"""
for arr in self:
if arr.psy.plotter:
arr.psy.plotter.disabled = True |
python | def set_linetrace_on_frame(f, localtrace=None):
"""
Non-portable function to modify linetracing.
Remember to enable global tracing with :py:func:`sys.settrace`, otherwise no
effect!
"""
traceptr, _, _ = get_frame_pointers(f)
if localtrace is not None:
# Need to incref to avoid the f... |
python | def _initialize_components(self, kwargs):
"""initialize the various components using the supplied \*\*kwargs
Parameters
----------
kwargs: dict
\*\*kwargs dict as received by __init__()
"""
tomodir = None
# load/assign grid
if 'tomodir' in k... |
java | public SipTransaction resendWithAuthorization(ResponseEvent event) {
Response response = event.getResponse();
int status = response.getStatusCode();
if ((status == Response.UNAUTHORIZED) || (status == Response.PROXY_AUTHENTICATION_REQUIRED)) {
try {
// modify the request to include user autho... |
python | def dicom2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False,
visit_in_path=False, rep_in_path=False):
"""Extract some meta-data from a DICOM file and store in a DB.
Arguments:
:param file_path: File path.
:param file_type: File type (should be 'DICO... |
java | public static Map<String, Object> from(Pair... pairs) {
Map<String, Object> map = new HashMap<String, Object>(pairs.length);
for (Pair p : pairs) {
map.put(p.key, p.value);
}
return map;
} |
python | def init(name, languages, run):
"""Initializes your CONFIG_FILE for the current submission"""
contents = [file_name for file_name in glob.glob("*.*") if file_name != "brains.yaml"]
with open(CONFIG_FILE, "w") as output:
output.write(yaml.safe_dump({
"run": run,
"name": name,... |
python | def _parse_message(self, data):
"""
Parses the raw message from the device.
:param data: message data
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
"""
try:
_, values = data.split(':')
self.serial_number, ... |
java | @Override
public void handleApplicationNotification(final PreloaderNotification n) {
if (n instanceof MessageNotification) {
this.messageText.setText(((MessageNotification) n).getMessage());
} else if (n instanceof ProgressNotification) {
handleProgressNotification((Prog... |
python | def add_locus(self,inlocus):
""" Adds a locus to our loci, but does not go through an update our locus sets yet"""
if self.use_direction == True and inlocus.use_direction == False:
sys.stderr.write("ERROR if using the direction in Loci, then every locus added needs use_direction to be True\n")
sys.e... |
python | def _get_term_object(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
**term_fields):
'''
Return an instance of the ``_Term`` class given the te... |
python | def fetch(url, binary, outfile, noprint, rendered):
'''
Fetch a specified URL's content, and output it to the console.
'''
with chrome_context.ChromeContext(binary=binary) as cr:
resp = cr.blocking_navigate_and_get_source(url)
if rendered:
resp['content'] = cr.get_rendered_page_source()
resp['binary'] = F... |
java | public TaskLevelPolicyChecker getTaskLevelPolicyChecker(TaskState taskState, int index) throws Exception {
return TaskLevelPolicyCheckerBuilderFactory.newPolicyCheckerBuilder(taskState, index).build();
} |
java | boolean hasPointFeatures()
{
for (int geometry = getFirstGeometry(); geometry != -1; geometry = getNextGeometry(geometry))
{
if (!Geometry.isMultiPath(getGeometryType(geometry)))
return true;
}
return false;
} |
python | def sync_remote_to_local(force="no"):
"""
Replace your remote db with your local
Example:
sync_remote_to_local:force=yes
"""
assert "local_wp_dir" in env, "Missing local_wp_dir in env"
if force != "yes":
message = "This will replace your local database with your "\
... |
java | public static long fastLongMix(long k) {
// phi = 2^64 / goldenRatio
final long phi = 0x9E3779B97F4A7C15L;
long h = k * phi;
h ^= h >>> 32;
return h ^ (h >>> 16);
} |
python | def deparse_code2str(code, out=sys.stdout, version=None,
debug_opts=DEFAULT_DEBUG_OPTS,
code_objects={}, compile_mode='exec',
is_pypy=IS_PYPY, walker=SourceWalker):
"""Return the deparsed text for a Python code object. `out` is where any intermediate
... |
python | def merge_path_config(configs, config_dir_override):
"""
Given a list of PathConfig objects, merges them into a single PathConfig,
giving priority in the order of the configs (first has highest priority).
"""
config_dir = None
log_dir = None
data_dir = None
key_dir = None
policy_dir ... |
java | @PostMapping(
value = "/{entityTypeId}/{id}",
params = "_method=GET",
produces = APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, Object> retrieveEntity(
@PathVariable("entityTypeId") String entityTypeId,
@PathVariable("id") String untypedId,
@Valid @RequestBody EntityTyp... |
python | def select_row(self, steps):
"""Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows).
"""
row = self.current_row() + steps
if 0 <= row < self.count():
self.set_current_row(row) |
python | def from_python_file(
cls, python_file, lambdas_path, json_filename: str, stem: str
):
"""Builds GrFN object from Python file."""
with open(python_file, "r") as f:
pySrc = f.read()
return cls.from_python_src(pySrc, lambdas_path, json_filename, stem) |
python | def error_map_source(self, kwargs_source, x_grid, y_grid, cov_param):
"""
variance of the linear source reconstruction in the source plane coordinates,
computed by the diagonal elements of the covariance matrix of the source reconstruction as a sum of the errors
of the basis set.
... |
python | def _generate_struct_class_reflection_attributes(self, ns, data_type):
"""
Generates two class attributes:
* _all_field_names_: Set of all field names including inherited fields.
* _all_fields_: List of tuples, where each tuple is (name, validator).
If a struct has enumerate... |
java | public static Class getTypeClass(Type type)
{
Class typeClassClass = null;
if (type instanceof Class) {
typeClassClass = (Class) type;
} else if (type instanceof ParameterizedType) {
typeClassClass = (Class) ((ParameterizedType) type).getRawType();
} else if ... |
java | public OAuthAccessToken getAccessToken(InputStream inputStream) throws JinxException {
JinxUtils.validateParams(inputStream);
Properties legacyTokenProperties = loadLegacyTokenProperties(inputStream);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.auth.oauth.getAccessToken");... |
python | def unassigned(data, as_json=False):
""" https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses
The /ips rest endpoint returns information about the IP addresses
and the usernames assigned to an IP
unassigned returns a listing of the IP addresses that are allocated
but hav... |
python | def pipe(self, other_task):
""" Add a pipe listener to the execution of this task. The
output of this task is required to be an iterable. Each item in
the iterable will be queued as the sole argument to an execution
of the listener task.
Can also be written as::
pip... |
python | def handle(self):
"""Parse the RPC, make the call, and pickle up the return value."""
data = cPickle.load(self.rfile) # pylint: disable=E1101
method = data.pop('method')
try:
retval = getattr(self, 'do_{0}'.format(method))(**data)
except Exception as e:
#... |
python | def mtz(n,c):
"""mtz: Miller-Tucker-Zemlin's model for the (asymmetric) traveling salesman problem
(potential formulation)
Parameters:
- n: number of nodes
- c[i,j]: cost for traversing arc (i,j)
Returns a model, ready to be solved.
"""
model = Model("atsp - mtz")
x,u = {},... |
python | def discriminator(self, imgs, y):
""" return a (b, 1) logits"""
yv = y
y = tf.reshape(y, [-1, 1, 1, 10])
with argscope(Conv2D, kernel_size=5, strides=1):
l = (LinearWrap(imgs)
.ConcatWith(tf.tile(y, [1, 28, 28, 1]), 3)
.Conv2D('conv0', 11)
... |
python | def _fulfills_version_string(installed_versions, version_conditions_string, ignore_epoch=False, allow_updates=False):
'''
Returns True if any of the installed versions match the specified version conditions,
otherwise returns False.
installed_versions
The installed versions
version_conditi... |
java | private static BitMatrix encodeLowLevel(DefaultPlacement placement, SymbolInfo symbolInfo, int width, int height) {
int symbolWidth = symbolInfo.getSymbolDataWidth();
int symbolHeight = symbolInfo.getSymbolDataHeight();
ByteMatrix matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHei... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.