language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def assert_datasource_protocol(event):
"""Assert that an event meets the protocol for datasource outputs."""
assert event.type in DATASOURCE_TYPE
# Done packets have no dt.
if not event.type == DATASOURCE_TYPE.DONE:
assert isinstance(event.dt, datetime)
assert event.dt.tzinfo == pytz.u... |
java | public static FlacFile open(File f) throws IOException, FileNotFoundException {
// Open, in a way that we can skip backwards a few bytes
InputStream inp = new BufferedInputStream(new FileInputStream(f), 8);
FlacFile file = open(inp);
return file;
} |
java | public static float distanceEuclidean(HashSparseVector sv1 ,HashSparseVector sv2) {
float dist = 0.0f;
TIntFloatIterator it1 = sv1.data.iterator();
TIntFloatIterator it2 = sv2.data.iterator();
int increa = 0;
while(it1.hasNext()&&it2.hasNext()){
if(increa==0){
it1.advance();
it2.advance();
... |
java | public final <A extends Number & Comparable<?>> BooleanExpression between(@Nullable A from, @Nullable A to) {
if (from == null) {
if (to != null) {
return loe(to);
} else {
throw new IllegalArgumentException("Either from or to needs to be non-null");
... |
python | def get_default_queryset(self):
"""
looks for default groups excluding the current one
overridable by openwisp-radius and other 3rd party apps
"""
return self.__class__.objects.exclude(pk=self.pk) \
.filter(default=True) |
java | public static EdgeScores getEdgeMarginalsRealSemiring(O2AllGraDpHypergraph graph, Scores sc) {
Algebra s = graph.getAlgebra();
int nplus = graph.getNumTokens()+1;
Hypernode[][][][] c = graph.getChart();
EdgeScores marg = new EdgeScores(graph.getNumTokens(), 0.0);
for (int width ... |
python | def is_prettytable(string):
""" returns true if the input looks like a prettytable """
return type(string).__name__ in {'str','unicode'} and (
len(string.splitlines()) > 1
) and (
all(string[i] == string[-i-1] for i in range(3))
) |
python | def encoding(self):
"""the character encoding of the request, usually only set in POST type requests"""
encoding = None
ct = self.get_header('content-type')
if ct:
ah = AcceptHeader(ct)
if ah.media_types:
encoding = ah.media_types[0][2].get("charse... |
java | public int lookForSelectablePosition(int position, boolean lookDown) {
final ListAdapter adapter = getAdapter();
if (adapter == null || isInTouchMode()) {
return INVALID_POSITION;
}
final int count = adapter.getCount();
if (!getAdapter().areAllItemsEnabled()) {
... |
java | @Override
public void receivePong(Tree message) {
// Verify protocol version
if (checkVersion) {
String ver = message.get("ver", "unknown");
if (!PROTOCOL_VERSION.equals(ver)) {
logger.warn("Invalid protocol version (" + ver + ")!");
return;
}
}
// Get response's unique ID
String id = mess... |
python | def forward_until(self, condition):
"""Forward until one of the provided matches is found.
The returned string contains all characters found *before the condition
was met. In other words, the condition will be true for the remainder
of the buffer.
:param condition: set of valid... |
python | def _local_info(self, args):
'''
List info for a package file
'''
if len(args) < 2:
raise SPMInvocationError('A package filename must be specified')
pkg_file = args[1]
if not os.path.exists(pkg_file):
raise SPMInvocationError('Package file {0} no... |
java | public String getTooltip() {
final String key = "pm.field." + getEntity().getId() + "." + getId() + ".tooltip";
if (key == null) {
return null;
}
final String message = getPm().message(key);
if (key.equals(message)) {
return null;
}
return ... |
java | protected void initCudaContextForThread(Long threadId) {
// we set device to be used prior to stream creation
nativeOps.setDevice(getDeviceId());
CudaContext context = new CudaContext();
context.initHandle();
context.initOldStream();
context.initStream();
conte... |
java | private boolean isDate(Class clazz)
{
return clazz.isAssignableFrom(Date.class) || clazz.isAssignableFrom(java.sql.Date.class)
|| clazz.isAssignableFrom(Timestamp.class) || clazz.isAssignableFrom(Time.class)
|| clazz.isAssignableFrom(Calendar.class);
} |
python | def pick_random_target(self):
"""
returns coords of a randomly generated starting position
mostly over to the right hand side of the world
"""
start_x = math.floor(self.grd.grid_height/2)
start_y = math.floor(self.grd.grid_width /2)
min_dist_from_x = 3
min... |
java | @Override
public String lookup(String key, Object[] msgValues) {
String msg = lookup(key);
if (msg != null) {
msg = MessageFormat.format(msg, msgValues);
}
return msg;
} |
python | def top_i_answer(self, i):
"""获取排名某一位的答案.
:param int i: 要获取的答案的排名
:return: 答案对象,能直接获取的属性参见answers方法
:rtype: Answer
"""
for j, a in enumerate(self.answers):
if j == i - 1:
return a |
java | @Reference
protected void setSecurityService(SecurityService securityService) {
SibTr.entry(tc, CLASS_NAME + "setSecurityService", securityService);
this.securityService = securityService;
SibTr.exit(tc, CLASS_NAME + "setSecurityService");
} |
python | def to_string(value, ctx):
"""
Tries conversion of any value to a string
"""
if isinstance(value, bool):
return "TRUE" if value else "FALSE"
elif isinstance(value, int):
return str(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isinstance(va... |
python | def kernel_image(self, kernel_image):
"""
Sets the kernel image path for this QEMU VM.
:param kernel_image: QEMU kernel image path
"""
kernel_image = self.manager.get_abs_image_path(kernel_image)
log.info('QEMU VM "{name}" [{id}] has set the QEMU kernel image path to {k... |
java | public CollectionRequest<Story> findByTask(String task) {
String path = String.format("/tasks/%s/stories", task);
return new CollectionRequest<Story>(this, Story.class, path, "GET");
} |
java | public static String decode(Image image, boolean isTryHarder, boolean isPureBarcode) {
final MultiFormatReader formatReader = new MultiFormatReader();
final LuminanceSource source = new BufferedImageLuminanceSource(ImgUtil.toBufferedImage(image));
final Binarizer binarizer = new HybridBinarizer(source);
f... |
java | private Map findMappingsForLifecycle( MavenProject project, Lifecycle lifecycle )
throws LifecycleExecutionException, PluginNotFoundException
{
String packaging = project.getPackaging();
Map mappings = null;
LifecycleMapping m =
(LifecycleMapping) findExtension( project,... |
java | public static String removePattern(final String text, final String regex) {
return replacePattern(text, regex, N.EMPTY_STRING);
} |
java | public void setValue(XExpression newValue)
{
if (newValue != value)
{
NotificationChain msgs = null;
if (value != null)
msgs = ((InternalEObject)value).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - XbasePackage.XASSIGNMENT__VALUE, null, msgs);
if (newValue != null)
msgs = ((InternalEObject)newValu... |
python | def create_invoice_from_albaran(pk, list_lines):
MODEL_SOURCE = SalesAlbaran
MODEL_FINAL = SalesInvoice
url_reverse = 'CDNX_invoicing_invoicesaless_list'
# type_doc
msg_error_relation = _("Hay lineas asignadas a facturas")
msg_error_not_found = _('Sales albaran not found'... |
java | private void tred2 () {
// This is derived from the Algol procedures tred2 by
// Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutine in EISPACK.
for (int j = 0; j < n; j++) {
d[j] = V[n-1][j];
}
// Householder reduc... |
java | @Override
public void debug(String msg, Throwable throwable) {
LOGGER.debug(msg, throwable);
} |
java | public final void mT__26() throws RecognitionException {
try {
int _type = T__26;
int _channel = DEFAULT_TOKEN_CHANNEL;
// InternalXbase.g:24:7: ( '===' )
// InternalXbase.g:24:9: '==='
{
match("===");
}
state.ty... |
java | public static final boolean createTableIfNotExists(final AmazonDynamoDB dynamo, final CreateTableRequest createTableRequest) {
try {
dynamo.createTable(createTableRequest);
return true;
} catch (final ResourceInUseException e) {
if (LOG.isTraceEnabled()) {
... |
python | def inverse(self):
"""Returns the inverse bijection."""
result = self.__class__()
result.forward = copy.copy(self.reverse)
result.reverse = copy.copy(self.forward)
return result |
java | public void setUserInfo(String username, String infoName, String value) throws CmsException {
CmsUser user = m_cms.readUser(username);
user.setAdditionalInfo(infoName, value);
m_cms.writeUser(user);
} |
python | def get_config(self, key, default=None):
""" Lookup a config field and return its value, first checking the
route.config, then route.app.config."""
depr(0, 13, "Route.get_config() is deprectated.",
"The Route.config property already includes values from the"
... |
java | public static io.opencensus.trace.MessageEvent asMessageEvent(
io.opencensus.trace.BaseMessageEvent event) {
Utils.checkNotNull(event, "event");
if (event instanceof io.opencensus.trace.MessageEvent) {
return (io.opencensus.trace.MessageEvent) event;
}
io.opencensus.trace.NetworkEvent networ... |
java | public boolean isSocket() {
if (permissions != null
&& (permissions.longValue() & SftpFileAttributes.S_IFSOCK) == SftpFileAttributes.S_IFSOCK) {
return true;
}
return false;
} |
java | public long[] getTrackNumbers() {
List<TrackBox> trackBoxes = this.getBoxes(TrackBox.class);
long[] trackNumbers = new long[trackBoxes.size()];
for (int trackCounter = 0; trackCounter < trackBoxes.size(); trackCounter++) {
trackNumbers[trackCounter] = trackBoxes.get(trackCounter).ge... |
java | public void writeTo(OutputStream out)
throws IOException
{
out.write(_buf,_start,_pos-_start);
} |
python | def is_installed(self, pkgname):
"""Given a package name, returns whether it is installed in the environment
:param str pkgname: The name of a package
:return: Whether the supplied package is installed in the environment
:rtype: bool
"""
return any(d for d in self.get_d... |
python | def _init_classes(self, y):
"""Map all possible classes to the range [0,..,C-1]
Parameters
----------
y : list of arrays of int, each element has shape=[samples_i,]
Labels of the samples for each subject
Returns
-------
new_y : list of arrays of in... |
python | def parallel_bulk(
client,
actions,
thread_count=4,
chunk_size=500,
max_chunk_bytes=100 * 1024 * 1024,
queue_size=4,
expand_action_callback=expand_action,
*args,
**kwargs
):
"""
Parallel version of the bulk helper run in multiple threads at once.
:arg client: instance of... |
java | protected static Number minimum(List<?> slaveValues) {
Number min = null;
for (Object slaveValue : slaveValues) {
if (min == null) {
min = (Number) slaveValue;
} else {
Comparable<Object> comparable = NumberComparator.getComparable(min);
... |
java | public Update withParams(UpdateParam... params) {
if (this.params == null) {
setParams(new java.util.ArrayList<UpdateParam>(params.length));
}
for (UpdateParam ele : params) {
this.params.add(ele);
}
return this;
} |
python | def computeEntropyAndEnthalpy(self, uncertainty_method=None, verbose=False, warning_cutoff=1.0e-10):
"""Decompose free energy differences into enthalpy and entropy differences.
Compute the decomposition of the free energy difference between
states 1 and N into reduced free energy differences, r... |
java | private void sendNextPayload() {
singleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
try {
sendNextPayloadSync();
} catch (Exception e) {
ApptentiveLog.e(e, "Exception while trying to send next payload");
logException(e);
}
}
});
} |
java | private Pair<Integer, Integer> findLeafCombineDegreeAndNumBuffers(
ByteBuffer combineBuffer,
int requiredMinimumBufferCapacity,
int numAvailableThreads,
int numLeafNodes
)
{
for (int leafCombineDegree = MINIMUM_LEAF_COMBINE_DEGREE; leafCombineDegree <= numLeafNodes; leafCombineDegree++) ... |
java | public static void isBlankThen(String str, Consumer<String> consumer) {
if (isBlank(str)) {
consumer.accept(str);
}
} |
java | @Override
public EClass getIfcTransformerType() {
if (ifcTransformerTypeEClass == null) {
ifcTransformerTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(729);
}
return ifcTransformerTypeEClass;
} |
java | public void initialize(){
thread = new Thread(collectorProcessor);
thread.start();
for (DriverNode dn : this.children){
dn.initialize();
}
} |
python | def set_model_doc_string(model, doc, override=False):
"""
Sets the doc string of the ONNX model.
:param model: instance of an ONNX model
:param doc: string containing the doc string that describes the model.
:param override: bool if true will always override the doc string with the new value
E... |
java | int calculateConnectionID(int currentConnectionID, final Set<ExecutionGroupVertex> alreadyVisited) {
if (!alreadyVisited.add(this)) {
return currentConnectionID;
}
for (final ExecutionGroupEdge backwardLink : this.backwardLinks) {
backwardLink.setConnectionID(currentConnectionID);
++currentCon... |
java | public LocalDate withYear(int year) {
if (this.year == year) {
return this;
}
YEAR.checkValidValue(year);
return resolvePreviousValid(year, month, day);
} |
python | def Prep(self, size, additionalBytes):
"""
Prep prepares to write an element of `size` after `additional_bytes`
have been written, e.g. if you write a string, you need to align
such the int length field is aligned to SizeInt32, and the string
data follows it directly.
If ... |
python | def display(self):
"""Displays the symbol table content"""
#Finding the maximum length for each column
sym_name = "Symbol name"
sym_len = max(max(len(i.name) for i in self.table),len(sym_name))
kind_name = "Kind"
kind_len = max(max(len(SharedData.KINDS[i.kind]) for ... |
java | private void appendJoinSQL92(Join join, StringBuffer where, StringBuffer buf)
{
if (join.isOuter)
{
buf.append(" LEFT OUTER JOIN ");
}
else
{
buf.append(" INNER JOIN ");
}
if (join.right.hasJoins())
{
buf... |
python | def _makeflags(self):
"""Set variable MAKEFLAGS with the numbers of
processors
"""
if self.meta.makeflags in ["on", "ON"]:
cpus = multiprocessing.cpu_count()
os.environ["MAKEFLAGS"] = "-j{0}".format(cpus) |
python | def open_channel(self):
"""Open a new channel with RabbitMQ.
When RabbitMQ responds that the channel is open, the on_channel_open
callback will be invoked by pika.
"""
logger.debug('Creating new channel')
self._connection.channel(on_open_callback=self.on_channel_open) |
python | def save_rdd_as_pickle(rdd, path, batch_size=10, overwrite=False):
""" Saves an rdd by grouping all the records of each partition as one pickle file
:param rdd: rdd to save
:param path: where to save
:param batch_size: batch size to pass to spark saveAsPickleFile
:param overwrite: if director... |
python | def approx_count_distinct(col, rsd=None):
"""Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>> df.agg(approx_coun... |
python | def run(self, cmd, sudo=False, ignore_error=False, success_status=(0,),
error_callback=None, custom_log=None, retry=0):
"""Run a command on the remote host.
The command is run on the remote host, if there is a redirected host
then the command will be run on that redirected host. See... |
python | def get_func_lno(self, funcname):
"""The first line number of the last defined 'funcname' function."""
class FuncLineno(ast.NodeVisitor):
def __init__(self):
self.clss = []
def generic_visit(self, node):
for child in ast.iter_child_nodes(node):
... |
java | synchronized PollObj get_polled_obj_by_type_name(final int obj_type, final String obj_name)
throws DevFailed {
// Get vector and search for type and name.
final Vector po_list = get_poll_obj_list();
for (int i = 0; i < po_list.size(); i++) {
final PollObj polled_obj = (PollObj) po_list.elementAt(i);
i... |
java | protected void addOverview(Content body) throws IOException {
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.addStyle(HtmlStyle.contentContainer);
addOverviewComment(div);
addTagsInfo(root, div);
body.addContent(div);
} |
java | private ExtensionRepositoryDescriptor parseRepository(String repositoryString)
throws URISyntaxException, ExtensionManagerConfigurationException
{
Matcher matcher = REPOSITORYIDPATTERN.matcher(repositoryString);
if (matcher.matches()) {
return this.extensionFactory.getExtensionR... |
java | public static void init(final CertManAPI cmAPI) throws Exception {
cmAPI.route(HttpMethods.POST, "/cert/artifacts", API.ARTIFACTS, new Code(cmAPI,"Create Artifacts") {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
Result<Void> r = context... |
java | protected Collection<File> extractDependentLibs(final File cachedir) throws IOException {
final Attributes attributes = getMainAttributes();
if (null == attributes) {
debug("no manifest attributes");
return null;
}
final ArrayList<File> files = new ArrayList<File... |
python | def _checkDimensionsListLike(arrays):
"""Check that each array in a list of arrays has the same size.
"""
dim1 = len(arrays)
dim2, dim3 = arrays[0].shape
for aa in range(1, dim1):
dim2_aa, dim3_aa = arrays[aa].shape
if (dim2_aa != dim2) or (dim3_aa != dim3):
raise _error... |
python | def root_hypernyms(self):
"""Retrieves all the root hypernyms.
Returns
-------
list of Synsets
Roots via hypernymy relation.
"""
visited = set()
hypernyms_next_level = set(self.hypernyms())
current_hypernyms = set(hypernyms_next... |
java | public void setContentViewExitAnimation(int anim) {
contentExitAnimation = AnimationUtils.loadAnimation(
mTrigger.getContext(), anim);
contentExitAnimation.setAnimationListener(mExitAnimationListener);
} |
python | def get_frames(self, channels=2):
"""Get numpy array of frames corresponding to the segment.
:param integer channels: Number of channels in output array
:returns: Array of frames in the segment
:rtype: numpy array
"""
tmp_frame = self.track.current_frame
self.tr... |
python | def init_attachment_cache(self):
""" Initializes the attachment cache for the current view. """
if self.request.method == 'GET':
# Invalidates previous attachments
attachments_cache.delete(self.get_attachments_cache_key(self.request))
return
# Try to restore ... |
java | public void setLastModHint(Record record)
{
m_objLastModHint = null;
for (m_iLastModType = DBConstants.MAIN_FIELD; m_iLastModType < record.getFieldCount() + DBConstants.MAIN_FIELD; m_iLastModType++)
{
BaseField field = record.getField(m_iLastModType);
if (field.isModi... |
java | public static GeometryExpression<?> fromText(String text) {
return geometryOperation(SpatialOps.GEOM_FROM_TEXT, ConstantImpl.create(text));
} |
java | public int getColumns() {
return (java.lang.Integer) getStateHelper().eval(PropertyKeys.columns, Integer.MIN_VALUE);
} |
java | @Override
public void removeListener(final WorkerListener listener, final WorkerEvent... events) {
if (listener != null) {
for (final WorkerEvent event : events) {
final ConcurrentSet<WorkerListener> listeners = this.eventListenerMap.get(event);
if (listeners != n... |
java | public static <T> void finish(T query, long correlationId, EventBus bus, String... types) {
for (String type : types) {
RemoveQuery<T> next = finish(query, correlationId, type);
bus.post(next);
}
} |
python | def list_team_repos(team_name, profile="github", ignore_cache=False):
'''
Gets the repo details for a given team as a dict from repo_name to repo details.
Note that repo names are always in lower case.
team_name
The name of the team from which to list repos.
profile
The name of the... |
java | public static void addCharges(Structure structure) {
// Loop through the models
for(int i=0; i<structure.nrModels(); i++){
for(Chain c: structure.getChains(i)){
for(Group g: c.getAtomGroups()){
ChemComp thisChemComp = ChemCompGroupFactory.getChemComp(g.getPDBName());
List<ChemCompAtom> chemAtoms = ... |
java | public void println() {
Object object;
try {
object = getProperty("out");
} catch (MissingPropertyException e) {
System.out.println();
return;
}
InvokerHelper.invokeMethod(object, "println", ArgumentListExpression.EMPTY_ARRAY);
} |
java | @Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { // NOPMD
try {
final Class<?> clazz = Class.forName(initialContextFactory);
final InitialContextFactory icf = (InitialContextFactory) clazz.newInstance();
final Context context = icf.getInitialContext(envir... |
python | def from_dict(d):
"""
Re-create the noise model from a dictionary representation.
:param Dict[str,Any] d: The dictionary representation.
:return: The restored noise model.
:rtype: NoiseModel
"""
return NoiseModel(
gates=[KrausModel.from_dict(t) for t ... |
python | def _api_request(self, uri, method, **kwargs):
"""
Any request that involves messages must define the client ID. This
handles all failures due to lack of client ID and raises the
appropriate exception.
"""
try:
return super(QueueClient, self)._api_request(uri,... |
java | private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex()))
.build();
} |
python | def extend_back(self, missing_dts):
"""
Resizes the buffer to hold a new window with a new cap_multiple.
If cap_multiple is None, then the old cap_multiple is used.
"""
delta = len(missing_dts)
if not delta:
raise ValueError(
'missing_dts must... |
java | void register(ResourceMonitorImpl monitorImpl) throws IOException
{
Path path = monitorImpl.getResourcePath();
registerAll(path, monitorImpl);
} |
java | public ApiResponse<List<CorporationMedalsResponse>> getCorporationsCorporationIdMedalsWithHttpInfo(
Integer corporationId, String datasource, String ifNoneMatch, Integer page, String token)
throws ApiException {
com.squareup.okhttp.Call call = getCorporationsCorporationIdMedalsValidateBe... |
python | def namespace_lower(self, namespace):
"""
Return a copy with only the keys from a given namespace, lower-cased.
The keys in the returned dict will be transformed to lower case after
filtering, so they can be easily passed as keyword arguments to other
functions. This is just syn... |
java | protected float intersectionY (IRay3 ray, float y) {
IVector3 origin = ray.origin(), dir = ray.direction();
float t = (y - origin.y()) / dir.y();
if (t < 0f) {
return Float.MAX_VALUE;
}
float ix = origin.x() + t*dir.x(), iz = origin.z() + t*dir.z();
return (ix... |
java | public List<Config> getConfListByParameter(Long appId, Long envId, String version, Boolean hasValue) {
return configDao.getConfigList(appId, envId, version, hasValue);
} |
java | private synchronized void configure(Configuration config) throws IOException {
logger.atFine().log("GHFS.configure");
logger.atFine().log("GHFS_ID = %s", GHFS_ID);
overrideConfigFromFile(config);
copyDeprecatedConfigurationOptions(config);
// Set this configuration as the default config for this in... |
python | def select_mastery_path(self, id, course_id, module_id, assignment_set_id=None, student_id=None):
"""
Select a mastery path.
Select a mastery path when module item includes several possible paths.
Requires Mastery Paths feature to be enabled. Returns a compound document
w... |
java | @Override
public JsonElement serialize(Deployment deployment, Type type, JsonSerializationContext context)
{
JsonElement element = gson.toJsonTree(deployment, type);
JsonObject obj = new JsonObject();
obj.add("deployment", element);
return obj;
} |
java | public void setBoundary(byte[] boundary)
throws IllegalBoundaryException {
if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) {
throw new IllegalBoundaryException(
"The length of a boundary token can not be changed");
}
System.arraycopy(bo... |
python | def getIndexGrid(self, name):
"""
Returns GDALGrid object of index map
Paramters:
name(str): Name of index map in 'cmt' file.
Returns:
GDALGrid
"""
index_map = self.mapTableFile.indexMaps.filter_by(name=name).one()
gssha_pro_card = self.... |
java | public synchronized String getUploadURL() throws IOException {
if (m_uploadURL != null) {
return m_uploadURL;
} else {
m_uploadURL = m_baseURL + "management/upload";
if (m_uploadURL.startsWith("http:")) {
URL redirectURL = getRedirectURL(m_uploadURL);
... |
python | def _importAndCheckStack(importName):
"""
Import the given name as a module, then walk the stack to determine whether
the failure was the module not existing, or some code in the module (for
example a dependent import) failing. This can be helpful to determine
whether any actual application code wa... |
java | public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style)
throws IllegalAccessException, InstantiationException, InvocationTargetException {
T spec;
try {
spec = optionClass.getConstructor().newInstance();
} catch (NoSuchMethodException noSuchMetho... |
python | def get_guest_connection_status(self, userid):
'''Get guest vm connection status.'''
rd = ' '.join(('getvm', userid, 'isreachable'))
results = self._request(rd)
if results['rs'] == 1:
return True
else:
return False |
python | def docs(session):
"""Build the docs."""
# Build docs against the latest version of Python, because we can.
session.interpreter = 'python3.6'
# Set the virtualenv dirname.
session.virtualenv_dirname = 'docs'
# Install Sphinx and also all of the google-cloud-* packages.
session.chdir(os.pa... |
python | def set_wd_mult(self, args_wd_mult):
"""Sets an individual weight decay multiplier for each parameter.
By default, if `param_idx2name` was provided in the
constructor, the weight decay multipler is set as 0 for all
parameters whose name don't end with ``_weight`` or
``_gamma``.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.