language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static String format(Date d, TimeZone tz) {
if (d == null) throw new IllegalArgumentException("Null date value");
long offset = d.getTime();
int tzOffsetMs = (tz != null ? tz : LOCAL_TZ).getOffset(d.getTime());
if (offset > Long.MAX_VALUE - EPOCH_OFFSET_MS - tzOffsetMs) throw new ArithmeticE... |
java | private boolean deleteSettersGetters(JDefinedClass clazz, String fieldPublicName) {
boolean result = false;
for (Iterator<JMethod> iter = clazz.methods().iterator(); iter.hasNext();) {
JMethod m = iter.next();
if (m.name().equals("set" + fieldPublicName) || m.name().equals("get" + fieldPublicName)) {
it... |
python | def should_be_excluded(name, exclude_patterns):
"""Check if a name should be excluded.
Returns True if name matches at least one of the exclude patterns in
the exclude_patterns list.
"""
for pattern in exclude_patterns:
if fnmatch.fnmatch(name, pattern):
return True
return ... |
python | def create_int_or_none(help_string=NO_HELP, default=NO_DEFAULT):
# type: (str, Union[int, None, NO_DEFAULT_TYPE]) -> Union[int, None]
"""
Create an int parameter
:param help_string:
:param default:
:return:
"""
# noinspection PyTypeChecker
return P... |
python | def generate_py():
"""Generate the python output file"""
model = {}
vk = init()
format_vk(vk)
model_alias(vk, model)
model_typedefs(vk, model)
model_enums(vk, model)
model_macros(vk, model)
model_funcpointers(vk, model)
model_exceptions(vk, model)
model_constructors(vk, mode... |
python | def related_items_changed(self, instance, related_manager):
"""
Stores the number of comments. A custom ``count_filter``
queryset gets checked for, allowing managers to implement
custom count logic.
"""
try:
count = related_manager.count_queryset()
exc... |
python | def games_by_time(self, start_game, end_game):
"""Given a range of games, return the games sorted by time.
Returns [(time, game_number), ...]
The time will be a `datetime.datetime` and the game
number is the integer used as the basis of the row ID.
Note that when a cluster of ... |
java | public ExtensionArchive getExtensionArchiveForBundle(Bundle bundle,
Set<String> extraClasses,
Set<String> extraAnnotations,
boolean applicationBDAsVi... |
java | public void afterPropertiesSet() throws Exception {
Resource portletXml = resourceLoader.getResource("/WEB-INF/portlet.xml");
Document doc = getDocument(portletXml.getInputStream());
final XPathExpression roleNamesExpression;
if (portletConfig == null) {
final XPathFact... |
python | def generate_random_lifetimes(hazard_rates, timelines, size=1, censor=None):
"""
Based on the hazard rates, compute random variables from the survival function
hazard_rates: (n,t) array of hazard rates
timelines: (t,) the observation times
size: the number to return, per hardard rate
cen... |
python | def append(self,text):
"""Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech)
"""
if text is Text:
... |
java | public void actionPerformed(ActionEvent ev) {
if (ev.getSource() instanceof TextField) {
saveTable();
return;
}
String s = ev.getActionCommand();
MenuItem i = new MenuItem();
if (s == null) {
if (ev.getSource() instanceof MenuItem) {
... |
java | public String hashAndHexPassword(final String password, final String salt,
final HashAlgorithm hashAlgorithm, final Charset charset)
throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
InvalidKeySpecException... |
java | private static boolean propertyIsImplicitCast(ObjectType type, String prop) {
for (; type != null; type = type.getImplicitPrototype()) {
JSDocInfo docInfo = type.getOwnPropertyJSDocInfo(prop);
if (docInfo != null && docInfo.isImplicitCast()) {
return true;
}
}
return false;
} |
java | protected long getDelayBeforeNextRetryInMillis(HttpRequestBase method, BceClientException exception, int attempt,
RetryPolicy retryPolicy) {
int retries = attempt - 1;
int maxErrorRetry = retryPolicy.getMaxErrorRetry();
// Immediately fails when it has exceeds the max retry count.
... |
java | public void notifyCallbacks(final T exchangeOrder) {
// Notify callbacks async
if(callbacks == null) {
return;
}
synchronized(callbacks) {
if(callbacks.isEmpty()) {
return;
}
callbacks.forEach((c) -> {
final Runnable runnable = () -> c.accept(exchangeOrder);
executorService.s... |
java | public static <T extends ImageGray<T>, D extends TupleDesc>
DetectDescribePoint<T,D> fuseTogether( InterestPointDetector<T> detector,
@Nullable OrientationImage<T> orientation,
DescribeRegionPoint<T, D> describe) {
return new DetectDescribeFusion<>(detector, orientation, describe);
} |
java | @HtmlSafe
public String getStylesheetHtml()
{
Space space = gpUtil.getSpaceManager().getSpace(getSpaceKey());
return String.format("<style>\n%s\n</style>\n<base href=\"%s\"/>\n",
StyleSheetExtractorFactory.getInstance().renderStyleSheet(space), gpUtil.getBaseUrl());
} |
java | private void commitAddActiveMessage()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "commitAddActiveMessage");
// If this consumer is in a set then commit the add to the set
_consumerKey.commitAddActiveMessage();
// Check the _... |
java | @Override
public void trsm(char Order, char Side, char Uplo, char TransA, char Diag, double alpha, INDArray A, INDArray B) {
if (Nd4j.getExecutioner().getProfilingMode() == OpExecutioner.ProfilingMode.ALL)
OpProfiler.getInstance().processBlasCall(false, A, B);
// FIXME: int cast
... |
python | def reftrack_restricted_data(rt, role, attr):
"""Return the data for restriction of the given attr of the given reftrack
:param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data
:type rt: :class:`jukeboxcore.reftrack.Reftrack`
:param role: item data role
:type role: QtCore.Qt.ItemDataRo... |
python | def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(StateEditorController, self).register_view(view)
view.prepare_the_labels() # the preparation of th... |
java | @Override
public int parseArgument(Options opts, String[] args, int i) throws BadCommandLineException {
initLoggerIfNecessary(opts);
int recognized = 0;
String arg = args[i];
logger.trace("Argument[" + i + "] = " + arg);
if (arg.equals(getArgumentName(ConfigurationOption.APPLY_PLURAL_FORM.optionN... |
java | protected void processLeak(ClassLoaderLeakPreventor preventor, Thread thread, Reference<?> entry,
ThreadLocal<?> threadLocal, Object value, String message) {
preventor.warn(message);
} |
python | def install_json_schema(self):
"""Load install.json schema file."""
if self._install_json_schema is None and self.install_json_schema_file is not None:
# remove old schema file
if os.path.isfile('tcex_json_schema.json'):
# this file is now part of tcex.
... |
python | def get_endpoints_by_subscriber_id(self, subscriber_id):
"""
Search for all endpoints by a given subscriber
"""
self._validate_subscriber_id(subscriber_id)
url = "/notification/v1/endpoint?subscriber_id={}".format(
subscriber_id)
response = NWS_DAO().getURL(... |
python | def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs):
"""
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param... |
python | def GET_blockchain_num_subdomains( self, path_info, blockchain_name ):
"""
Handle GET /blockchains/:blockchainID/subdomains_count
Takes `all=true` to include expired names
Reply with the number of names on this blockchain
"""
if blockchain_name != 'bitcoin':
#... |
python | def _ssl_agent(self):
"""
Get a Twisted Agent that performs Client SSL authentication for Koji.
"""
# Load "cert" into a PrivateCertificate.
certfile = self.lookup(self.profile, 'cert')
certfile = os.path.expanduser(certfile)
with open(certfile) as certfp:
... |
python | def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6):
"""Generate the implementation of step HMC"""
init_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
end_params = {k: v.copyto(v.context) for k, v in exe_params.items()}
init_momentums =... |
java | public <T> T handleResponse(Response response, Type returnType) throws ApiException {
if (response.isSuccessful()) {
if (returnType == null || response.code() == 204) {
// returning null if the returnType is not defined,
// or the status code is 204 (No Content)
... |
python | def sample(self, sampling_mode=None):
"""
Sample a point in the leaf region with max competence progress (recursive).
Parameters
----------
sampling_mode : dict
How to sample a point in the tree: {'multiscale':bool, 'mode':string, 'param':float}
... |
python | def evaluate(self, parameters):
"""Returns False if there's no match, or whatever the ParameterCondition evaluates to (recursively applied!)"""
if self.match(parameters):
if isinstance(self.then, ParameterCondition):
#recursive parametercondition
return self.t... |
java | @Override
public DeleteApplicationOutputResult deleteApplicationOutput(DeleteApplicationOutputRequest request) {
request = beforeClientExecution(request);
return executeDeleteApplicationOutput(request);
} |
java | public Observable<ServiceResponse<Page<SecretItem>>> getSecretVersionsWithServiceResponseAsync(final String vaultBaseUrl, final String secretName) {
return getSecretVersionsSinglePageAsync(vaultBaseUrl, secretName)
.concatMap(new Func1<ServiceResponse<Page<SecretItem>>, Observable<ServiceResponse<Pa... |
python | def context(root, project=""):
"""Produce the be environment
The environment is an exact replica of the active
environment of the current process, with a few
additional variables, all of which are listed below.
"""
environment = os.environ.copy()
environment.update({
"BE_PROJECT":... |
java | public static Delay equalJitter(Duration lower, Duration upper, long base, TimeUnit targetTimeUnit) {
LettuceAssert.notNull(lower, "Lower boundary must not be null");
LettuceAssert.isTrue(lower.toNanos() >= 0, "Lower boundary must be greater or equal to 0");
LettuceAssert.notNull(upper, "Upper ... |
python | def pipe_urlinput(context=None, _INPUT=None, conf=None, **kwargs):
"""An input that prompts the user for a url and yields it forever.
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : unused
conf : {
'name': {'value': 'parameter name'},
'prompt': ... |
java | public ServiceFuture<TopicInner> updateAsync(String resourceGroupName, String topicName, Map<String, String> tags, final ServiceCallback<TopicInner> serviceCallback) {
return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, topicName, tags), serviceCallback);
} |
java | protected AstNode literal() throws ScanException, ParseException {
AstNode v = null;
switch (token.getSymbol()) {
case TRUE:
v = new AstBoolean(true);
consumeToken();
break;
case FALSE:
v = new AstBoolean(false);
consumeToken();
break;
case STRING:
v = new AstString(token.getIma... |
java | @Override
public T element() {
T retrievedElement = peek();
if (retrievedElement == null) {
throw new NoSuchElementException();
}
return retrievedElement;
} |
java | @Override
protected void printElement(final Writer out, final FormatStack fstack,
final NamespaceStack nstack, final Element element) throws IOException {
nstack.push(element);
try {
final List<Content> content = element.getContent();
// Print the beginning of the tag plus attributes and a... |
python | def execute_migrations(self, show_traceback=True):
"""
Executes all pending migrations across all capable
databases
"""
all_migrations = get_pending_migrations(self.path, self.databases)
if not len(all_migrations):
sys.stdout.write("There are no migra... |
java | private Wave createWave(final WaveGroup waveGroup, final WaveType waveType, final Class<?> componentClass, final WaveBean waveBean, final WaveBean... waveBeans) {
final List<WaveBean> waveBeanList = new ArrayList<>();
waveBeanList.add(waveBean);
if (waveBeans.length > 0) {
waveBeanL... |
python | def node_label_folder_absent(name, node, **kwargs):
'''
Ensures the label folder doesn't exist on the specified node.
name
The name of label folder
node
The name of the node
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''... |
java | private static void callbackResult(String str, String pubKey, ICheckLoginSignHandler callback){
JSONObject json = null;
try {
json = new JSONObject(str);
} catch (JSONException e) {
callback.onCheckResult(null, "json parse fail:" + e.getMessage(), false);
... |
python | def default_blocks(self):
"""
Return a list of default block tuples (appname.ModelName, verbose name).
Next to the dropdown list of block types, a small number of common blocks which are
frequently used can be added immediately to a column with one click. This method defines
the... |
java | void copyPool(final ClassWriter classWriter) {
char[] buf = new char[maxStringLength];
int ll = items.length;
Item[] items2 = new Item[ll];
for (int i = 1; i < ll; i++) {
int index = items[i];
int tag = b[index - 1];
Item item = new Item(i);
... |
python | def RIBSystemRouteLimitExceeded_originator_switch_info_switchIdentifier(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
RIBSystemRouteLimitExceeded = ET.SubElement(config, "RIBSystemRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
... |
python | def get_grade_system_query_session(self):
"""Gets the ``OsidSession`` associated with the grade system query service.
return: (osid.grading.GradeSystemQuerySession) - a
``GradeSystemQuerySession``
raise: OperationFailed - unable to complete request
raise: Unimplemented... |
java | public static synchronized TypefaceCache getInstance(Context context) {
if (sInstance == null)
sInstance = new TypefaceCache((Application)context.getApplicationContext());
return sInstance;
} |
java | @Override
public CPDefinitionLink findByCP_T_First(long CProductId, String type,
OrderByComparator<CPDefinitionLink> orderByComparator)
throws NoSuchCPDefinitionLinkException {
CPDefinitionLink cpDefinitionLink = fetchByCP_T_First(CProductId, type,
orderByComparator);
if (cpDefinitionLink != null) {
re... |
java | @Nonnull
public PDFObjectOptions setFallbackLink (@Nullable final String sText)
{
m_aFallbackLink = sText == null ? null : JSExpr.lit (sText);
return this;
} |
java | @SuppressWarnings("unchecked")
public T create(Object[] args)
{
for(int i=0, n=args.length; i<n; i++)
{
if(arguments[i] instanceof FactoryDefinition.InjectedArgument)
{
args[i] = arguments[i].getValue(null);
}
}
try
{
return (T) raw.newInstance(args);
}
catch(IllegalArgumentException e)... |
java | @SuppressWarnings("static-method")
protected String getDefaultMavenGroupId() {
final String userdomain = System.getenv("userdomain"); //$NON-NLS-1$
if (Strings.isNullOrEmpty(userdomain)) {
return "com.foo"; //$NON-NLS-1$
}
final String[] elements = userdomain.split(Pattern.quote(".")); //$NON-NLS-1$
final... |
java | public @CheckForNull R search(final int n, final Direction d) {
switch (d) {
case EXACT:
return getByNumber(n);
case ASC:
for (int m : numberOnDisk) {
if (m < n) {
// TODO could be made more efficient with numberOnDisk.find
... |
java | public void setDriver(final Driver driver) {
final Driver old = this.driver;
this.driver = driver;
this.connectionConfig = System.currentTimeMillis();
this.connectionValidated = false;
this.pcs.firePropertyChange("driver", old, this.driver);
} |
python | def _evalTimeStd(self, datetimeString, sourceTime):
"""
Evaluate text passed by L{_partialParseTimeStd()}
"""
s = datetimeString.strip()
sourceTime = self._evalDT(datetimeString, sourceTime)
# Given string is in the format HH:MM(:SS)
yr, mth, dy, hr, mn, sec, wd,... |
java | @Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case TypesPackage.JVM_GENERIC_ARRAY_TYPE_REFERENCE__COMPONENT_TYPE:
return componentType != null;
}
return super.eIsSet(featureID);
} |
python | def print_crawl(self):
''' Print the opening crawl one line at a time '''
print("Star Wars")
time.sleep(.5)
print("Episode {0}".format(self.episode_id))
time.sleep(.5)
print("")
time.sleep(.5)
print("{0}".format(self.title))
for line in self.gen_op... |
java | public static <T> ArrayList<T> mergeLists(final T... array) {
final ArrayList<T> retValue = new ArrayList<T>();
Collections.addAll(retValue, array);
return retValue;
} |
python | def release(self):
"""
New implementation to free up Redis subscriptions when websockets close. This prevents
memory sap when Redis Output Buffer and Output Lists build when websockets are abandoned.
"""
if self._subscription and self._subscription.subscribed:
self._s... |
python | def get_all_rules(self, id_env):
"""Save an environment rule
:param id_env: Environment id
:return: Estrutura:
::
{ 'rules': [{'id': < id >,
'environment': < Environment Object >,
'content': < content >,
'name': < name >,
'c... |
java | public static void dumpSystemInfo(PrintWriter out) {
out.println("--------------");
out.println(getJvmSpecInfo());
out.println("--------------");
out.println(getJvmInfo());
out.println("--------------");
out.println(getJavaSpecInfo());
out.println("--------------");
out.println(getJavaInfo());
... |
python | def modularity_louvain_und_sign(W, gamma=1, qtype='sta', seed=None):
'''
The optimal community structure is a subdivision of the network into
nonoverlapping groups of nodes in a way that maximizes the number of
within-group edges, and minimizes the number of between-group edges.
The modularity is a ... |
java | protected final void putInt32(long i32) {
ensureCapacity(position + 4);
byte[] buf = buffer;
buf[position++] = (byte) (i32 & 0xff);
buf[position++] = (byte) (i32 >>> 8);
buf[position++] = (byte) (i32 >>> 16);
buf[position++] = (byte) (i32 >>> 24);
} |
python | def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = CheckBox(self.get_context(), None,
d.style or "@attr/checkboxStyle") |
java | private int getTotalLandscapePointsInPage(CriterionBidLandscapePage page) {
if (page.getEntries() == null) {
return 0;
}
int totalLandscapePointsInPage = 0;
for (CriterionBidLandscape criterionBidLandscape : page.getEntries()) {
totalLandscapePointsInPage += criterionBidLandscape.getLandscap... |
java | public long getDateTimeMillis(long instant,
int hourOfDay, int minuteOfHour,
int secondOfMinute, int millisOfSecond)
throws IllegalArgumentException
{
instant = hourOfDay().set(instant, hourOfDay);
instant = minuteOfHour().s... |
python | def create_commit(self, message, tree, parents, author={}, committer={}):
"""Create a commit on this repository.
:param str message: (required), commit message
:param str tree: (required), SHA of the tree object this
commit points to
:param list parents: (required), SHAs of ... |
java | public static List<String> getAvailableLocaleSuffixesForBundle(
String messageBundlePath, String fileSuffix,
GrailsServletContextResourceReader rsReader) {
int idxNameSpace = messageBundlePath.indexOf("(");
int idxFilter = messageBundlePath.indexOf("[");
int idx = -1;
if (idxNameSpace != -1 && idxFilter ... |
java | @SuppressWarnings("null")
public @NotNull SuffixBuilder pages(@NotNull List<Page> pages, @NotNull Page suffixBasePage) {
List<Resource> resources = Lists.transform(pages, new Function<Page, Resource>() {
@Override
public Resource apply(Page page) {
return page.adaptTo(Resource.class);
}
... |
python | def _get_description(self, element):
"""
Returns the description of element.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: The description of element.
:rtype: str
"""
description = None
if e... |
python | def get_project_source_path(path: str) -> str:
"""
Converts the given path into a project source path, to the cauldron.json
file. If the path already points to a cauldron.json file, the path is
returned without modification.
:param path:
The path to convert into a project source path
""... |
python | def count_by_state_unsynced(self, arg):
"""Extends the original object in order to inject checking
for stalled jobs and killing them if they are running for too long
"""
if self.kill_timeout is not None:
self.delete_running(self.kill_timeout)
return super(CMongoTrials... |
java | public void setCiphers(java.util.Collection<Cipher> ciphers) {
if (ciphers == null) {
this.ciphers = null;
return;
}
this.ciphers = new java.util.ArrayList<Cipher>(ciphers);
} |
java | public Tag createTag(UUID projectId, String name, CreateTagOptionalParameter createTagOptionalParameter) {
return createTagWithServiceResponseAsync(projectId, name, createTagOptionalParameter).toBlocking().single().body();
} |
python | def SetIndexName(self, index_name):
"""Set the index name.
Args:
index_name (str): name of the index.
"""
self._index_name = index_name
logger.debug('Elasticsearch index name: {0:s}'.format(index_name)) |
java | public static <T> GenericResponseBuilder<T> ok(T entity, MediaType type) {
return ok(entity).type(type);
} |
python | def persistent_id(self, obj):
"""Instead of pickling as a regular class instance, we emit a
persistent ID."""
if isinstance(obj, Element):
# Here, our persistent ID is simply a tuple, containing a tag and
# a key
return obj.__class__.__name__, obj.symbol
... |
java | public void setStatusOrder(Status... statusOrder) {
String[] order = new String[statusOrder.length];
for (int i = 0; i < statusOrder.length; i++) {
order[i] = statusOrder[i].getCode();
}
setStatusOrder(Arrays.asList(order));
} |
python | def on_channel_closed(self, channel, reply_code, reply_text):
"""Invoked by pika when RabbitMQ unexpectedly closes the channel.
Channels are usually closed if you attempt to do something that
violates the protocol, such as re-declare an exchange or queue with
different parameters.
... |
python | def fetch_cdn_data(self, container):
"""
Returns a dict containing the CDN information for the specified
container. If the container is not CDN-enabled, returns an empty dict.
"""
name = utils.get_name(container)
uri = "/%s" % name
try:
resp, resp_body... |
python | def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type):
"""Given an AST node object, returns a string containing the symbol.
"""
return fmt % symbol_data[type(obj)] |
python | def _find_pg_binary(util):
'''
... versionadded:: 2016.3.2
Helper function to locate various psql related binaries
'''
pg_bin_dir = __salt__['config.option']('postgres.bins_dir')
util_bin = salt.utils.path.which(util)
if not util_bin:
if pg_bin_dir:
return salt.utils.pa... |
java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WSuggestions suggestions = (WSuggestions) component;
XmlStringBuilder xml = renderContext.getWriter();
// Cache key for a lookup table
String dataKey = suggestions.getListCacheKey();
// Use AJAX if not usin... |
python | def layers(self):
"""returns a list of layer classes (including subclasses) in this packet""" # noqa: E501
layers = []
lyr = self
while lyr:
layers.append(lyr.__class__)
lyr = lyr.payload.getlayer(0, _subclass=True)
return layers |
java | public <T> List<Class<? extends T>> getImplementations(final Class<T> clazz, Predicate<Class<? extends T>> predicate)
{
final long started = System.currentTimeMillis();
try
{
if (clazz.isInterface())
return filter(finder.findImplementations(clazz), predicate);
else
return filter(finder.findSubclass... |
python | def refine_get_urls(original):
"""
serve static files (and media files also)
in production the webserver should serve requested
static files itself and never let requests to /static/*
and /media/* get to the django application.
"""
def get_urls():
from django.conf.urls import url
... |
java | public Expression<T> as(String alias) {
return as(ExpressionUtils.path(getType(), alias));
} |
java | public AwsSecurityFindingFilters withDescription(StringFilter... description) {
if (this.description == null) {
setDescription(new java.util.ArrayList<StringFilter>(description.length));
}
for (StringFilter ele : description) {
this.description.add(ele);
}
... |
java | protected void processConstraintViolation(final Set<ConstraintViolation<Object>> violations,
final SheetBindingErrors<?> errors) {
for(ConstraintViolation<Object> violation : violations) {
final String fieldName = violation.getPropertyPath().toString();
... |
java | private static Collection<? extends Class<?>> findEnumClassesWithJar(final String packageName, final JarFile jarFile) {
String resourceName = packageName.replace('.', '/');
Set<Class<?>> classes = new HashSet<>();
Collections.list(jarFile.entries()).stream().map(JarEntry::getName)
.filter(name -> name.startsW... |
python | def create_intent(self,
parent,
intent,
language_code=None,
intent_view=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
... |
python | def get_url(self, name, view_name, kwargs, request):
"""
Given a name, view name and kwargs, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
... |
java | public Observable<ApplicationInsightsComponentAnalyticsItemInner> getAsync(String resourceGroupName, String resourceName, ItemScopePath scopePath, String id, String name) {
return getWithServiceResponseAsync(resourceGroupName, resourceName, scopePath, id, name).map(new Func1<ServiceResponse<ApplicationInsightsC... |
java | public String getPackageAnchorName(PackageDoc packageDoc) {
return packageDoc == null || packageDoc.name().length() == 0 ?
SectionName.UNNAMED_PACKAGE_ANCHOR.getName() : packageDoc.name();
} |
java | @Override
public void filterSetup() {
int type = getIntParameter(SimpleJob.READER_TYPE);
if (type == SimpleJob.SINGLE_COLUMN_JOIN_READER) {
joinColumn = new String[1];
joinColumn[0] = getStringParameter(SimpleJob.JOIN_MASTER_COLUMN);
} else if (type == SimpleJob.SOME_... |
python | def handle_play_pause_clicked(self):
""" Call this when the user clicks the play/pause button. """
if self.__hardware_source:
if self.is_playing:
self.__hardware_source.stop_playing()
else:
self.__hardware_source.start_playing() |
java | public void startMonitoring()
throws IOException
{
if (file == null) {
writer = new PrintWriter(new BufferedOutputStream(System.out));
} else {
writer = new PrintWriter(new FileWriter(file, true));
}
super.startMonitoring();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.