language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def mag_field(RAW_IMU, SENSOR_OFFSETS=None, ofs=None):
'''calculate magnetic field strength from raw magnetometer'''
mag_x = RAW_IMU.xmag
mag_y = RAW_IMU.ymag
mag_z = RAW_IMU.zmag
if SENSOR_OFFSETS is not None and ofs is not None:
mag_x += ofs[0] - SENSOR_OFFSETS.mag_ofs_x
mag_y += o... |
python | def getQwordAtRva(self, rva):
"""
Returns a C{QWORD} from a given RVA.
@type rva: int
@param rva: The RVA to get the C{QWORD} from.
@rtype: L{QWORD}
@return: The L{QWORD} obtained at the given RVA.
"""
return datatypes.QWORD.parse(utils.... |
java | @Nonnull
public EChange addListener (@Nonnull final EventListener aListener)
{
ValueEnforcer.notNull (aListener, "Listener");
// Small consistency check
if (!(aListener instanceof ServletContextListener) &&
!(aListener instanceof HttpSessionListener) &&
!(aListener instanceof ServletReq... |
java | public static long calc(String arg0, String arg1, String format, DateUnit dateUnit) {
try {
return calc(getTime(format, arg0), getTime(format, arg1), dateUnit);
} catch (Exception e) {
logger.error("日期计算出错", e);
return -1;
}
} |
python | def get(no_create=False, server=None, port=None, force_uuid=None):
"""Get the thread local singleton"""
pid = os.getpid()
thread = threading.current_thread()
wdb = Wdb._instances.get((pid, thread))
if not wdb and not no_create:
wdb = object.__new__(Wdb)
Wd... |
python | def get_stem(self, noun, gender, mimation=True):
"""Return the stem of a noun, given its gender"""
stem = ''
if mimation and noun[-1:] == 'm':
# noun = noun[:-1]
pass
# Take off ending
if gender == 'm':
if noun[-2:] in list(self.endings['m']['s... |
python | def calculate(self, token_list_x, token_list_y):
'''
Calculate similarity with the so-called Cosine similarity of Tf-Idf vectors.
Concrete method.
Args:
token_list_x: [token, token, token, ...]
token_list_y: [token, token, token, ...]
... |
python | def info():
"""
Show info about colin and its dependencies.
"""
installation_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
click.echo("colin {} {}".format(__version__, installation_path))
click.echo("colin-cli {}\n".format(os.path.realpath(__file__)))
# cl... |
python | def load_factors():
"""Load risk factor returns.
Factors
-------
Symbol Description Source
------ ---------- ------
MKT French
... |
python | def is_equal(self, other):
""" Two DictCells are equal when they share ALL Keys, and all of their
is_equal() methods return True. This ensures substructure equality.
"""
if not isinstance(other, DictCell):
return False
for (this, that) in itertools.izip_longest(sel... |
java | public String print(boolean velocityHasNext, String whenTrue, String whenFalse) {
return velocityHasNext ? whenTrue : whenFalse;
} |
java | @NonNull
@Card.CardBrand
public static String getPossibleCardType(@Nullable String cardNumber) {
return getPossibleCardType(cardNumber, true);
} |
java | protected void addValidators() {
m_target.removeAllValidators();
m_target.addValidator(new TargetValidator());
for (Component c : m_componentsToValidate) {
if (c instanceof CmsPathSelectField) {
((CmsPathSelectField)c).removeAllValidators();
((CmsPat... |
python | def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:
"""Get elements in this document which matches condition."""
return getElementsBy(self, cond) |
python | def getsdm(*args, **kwargs):
""" Wrap sdmpy.SDM to get around schema change error """
try:
sdm = sdmpy.SDM(*args, **kwargs)
except XMLSyntaxError:
kwargs['use_xsd'] = False
sdm = sdmpy.SDM(*args, **kwargs)
return sdm |
python | def list_files(self, remote_path, by=None, order=None,
limit=None, **kwargs):
"""获取目录下的文件列表.
:param remote_path: 网盘中目录的路径,必须以 /apps/ 开头。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " ... |
python | def constraint(self):
"""Constraint string"""
constraint_arr = []
if self._not_null:
constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL")
if self._unique:
constraint_arr.append("UNIQUE")
return " ".join(constraint_arr) |
python | def _parse_path(self, path):
"""
Parses a Registry path and returns the hive and key.
@type path: str
@param path: Registry path.
@rtype: tuple( int, str )
@return: Tuple containing the hive handle and the subkey path.
For a local Registry, the hive handle... |
python | def feeling_lucky(cls, obj):
"""Tries to convert given object to an UTC timestamp is ms, based
on its type.
"""
if isinstance(obj, six.string_types):
return cls.from_str(obj)
elif isinstance(obj, six.integer_types) and obj <= MAX_POSIX_TIMESTAMP:
return cl... |
python | def __diff_internal(self):
"""Differentiate a B-spline once, and return the resulting coefficients and Bspline objects.
This preserves the Bspline object nature of the data, enabling recursive implementation
of higher-order differentiation (see `diff`).
The value of the first derivative of `B` at a point `x` ... |
python | def GetParentFileEntry(self):
"""Retrieves the root file entry.
Returns:
FakeFileEntry: parent file entry or None if not available.
"""
location = getattr(self.path_spec, 'location', None)
if location is None:
return None
parent_location = self._file_system.DirnamePath(location)
... |
java | public void setCharacterEncoding(String encoding)
throws UnsupportedEncodingException
{
if (_inputState!=0)
throw new IllegalStateException("getReader() or getInputStream() called");
"".getBytes(encoding);
_httpRequest.setCharacterEncoding(encoding,false);
} |
python | def maskIndex(self):
""" Returns a boolean index with True if the value is masked.
Always has the same shape as the maksedArray.data, event if the mask is a single boolan.
"""
if isinstance(self.mask, bool):
return np.full(self.data.shape, self.mask, dtype=np.bool)
... |
python | def restore(self):
"""Restore signal handlers to their original settings."""
signal.signal(signal.SIGINT, self.original_sigint)
signal.signal(signal.SIGTERM, self.original_sigterm)
if os.name == 'nt':
signal.signal(signal.SIGBREAK, self.original_sigbreak) |
java | @Override
public String getPostParamSaveMethod() {
WebAppSecurityConfig globalConfig = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig();
if (globalConfig != null)
return WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().getPostParamSaveMethod();
else
... |
java | public void setPreferredOrder(final Collection<Class<? extends Saga>> preferredOrder) {
checkNotNull(preferredOrder, "Preferred order list may not be null. Empty is allowed.");
cacheLoader.setPreferredOrder(preferredOrder);
sagasForMessageType.invalidateAll();
} |
python | def simulate(simulated_variables, year):
'''
Construction de la DataFrame à partir de laquelle sera faite l'analyse des données
'''
input_data_frame = get_input_data_frame(year)
TaxBenefitSystem = openfisca_france_indirect_taxation.init_country()
tax_benefit_system = TaxBenefitSystem()
surv... |
java | private ApiListType executeRequest(Call call) throws IOException, ApiException {
return client.handleResponse(call.execute(), listType);
} |
python | def managed(name, probes, defaults=None):
'''
Ensure the networks device is configured as specified in the state SLS file.
Probes not specified will be removed, while probes not confiured as expected will trigger config updates.
:param probes: Defines the probes as expected to be configured on the
... |
python | def amplitude(self, caldb, calv, atten=0):
"""Calculates the voltage amplitude for this stimulus, using
internal intensity value and the given reference intensity & voltage
:param caldb: calibration intensity in dbSPL
:type caldb: float
:param calv: calibration voltage that was ... |
java | public String assembleProviderUrlString(String[] ldapUrls) {
StringBuilder providerUrlBuffer = new StringBuilder(DEFAULT_BUFFER_SIZE);
for (String ldapUrl : ldapUrls) {
providerUrlBuffer.append(ldapUrl);
if (!base.isEmpty()) {
if (!ldapUrl.endsWith("/")) {
... |
python | def trigger_event(self, event, *args):
"""Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed... |
python | def info(path):
"""info(path)
path is a string
"""
fh = None
try:
fh = open(path,'rb')
return __readHeader(fh)
finally:
if fh:
fh.close()
return None |
java | public static CPAttachmentFileEntry removeByC_C_F(long classNameId,
long classPK, long fileEntryId)
throws com.liferay.commerce.product.exception.NoSuchCPAttachmentFileEntryException {
return getPersistence().removeByC_C_F(classNameId, classPK, fileEntryId);
} |
java | public byte[] toByteArray() {
// First step: compute the size in bytes of the ClassFile structure.
// The magic field uses 4 bytes, 10 mandatory fields (minor_version, major_version,
// constant_pool_count, access_flags, this_class, super_class, interfaces_count, fields_count,
// methods_count and attri... |
python | def _compute_mod_regs(self, regs_init, regs_fini):
"""Compute modified registers.
"""
assert regs_init.keys() == regs_fini.keys()
modified_regs = []
for reg in regs_init:
if regs_init[reg] != regs_fini[reg]:
modified_regs.append(reg)
return ... |
java | public Stream<Module> requiresTransitive(Module m) {
// find requires transitive
return m.descriptor()
.requires().stream()
.filter(req -> req.modifiers().contains(TRANSITIVE))
.map(ModuleDescriptor.Requires::name)
.map(config::findModule)
... |
java | public synchronized static void append(File file,String content) throws IOException {
Writer writer = writerCache.getOrDefault(file.getPath(), new FileWriter(file,true));
writer.write(content);
writer.flush();
writerCache.put(file.getPath(), writer);
} |
java | public void populateReference(final Reference reference,
final Map properties, final Map defaults) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "populateReference", new Object[] {
reference, properties, defaults});
... |
java | public static void writeXml(Serializable serializable, OutputStream output) throws IOException {
TransportFormat.XML.writeSerializableTo(serializable, output);
} |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.MMD__RG:
getRG().clear();
return;
}
super.eUnset(featureID);
} |
java | private File createNewUniqueFile(File srcFile, boolean showError) throws IOException {
String dateString = getDateString();
int index = findFileIndexAndUpdateCounter(dateString);
String destFileName;
File destFile;
do {
int counter = lastCounter++;
destFi... |
python | def display_list_by_prefix(names_list, starting_spaces=0):
"""Creates a help string for names_list grouped by prefix."""
cur_prefix, result_lines = None, []
space = " " * starting_spaces
for name in sorted(names_list):
split = name.split("_", 1)
prefix = split[0]
if cur_prefix != prefix:
resul... |
python | def load_gltf(file_obj=None,
resolver=None,
**mesh_kwargs):
"""
Load a GLTF file, which consists of a directory structure
with multiple files.
Parameters
-------------
file_obj : None or file-like
Object containing header JSON, or None
resolver : trimesh.vi... |
java | @Pure
public static <P1, P2, P3> Procedure2<P2, P3> curry(final Procedure3<? super P1, ? super P2, ? super P3> procedure, final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure2<P2, P3>() {
@Override
public void apply(P2 p2, P3 p3) {
procedure.app... |
python | def random_word(self, *args, **kwargs):
"""
Return a random word from this tree. The length of the word depends on
the this tree.
:return: a random word from this tree.
args and kwargs are ignored.
"""
word = ""
current = (">", 0)
while current[0... |
java | private List<Locale> initWorkplaceLocales(CmsObject cms) {
Set<Locale> locales = new HashSet<Locale>();
// collect locales from the VFS
if (cms.existsResource(CmsWorkplace.VFS_PATH_LOCALES)) {
List<CmsResource> localeFolders;
try {
localeFolders = cms.ge... |
python | def Tethering_unbind(self, port):
"""
Function path: Tethering.unbind
Domain: Tethering
Method name: unbind
Parameters:
Required arguments:
'port' (type: integer) -> Port number to unbind.
No return value.
Description: Request browser port unbinding.
"""
assert isinstance(port, (in... |
python | def _do_weak_search(self, obj, recursive):
"""Search for an element that looks like *obj* within the node list.
This follows the same rules as :meth:`_do_strong_search` with some
differences. *obj* is treated as a string that might represent any
:class:`.Node`, :class:`.Wikicode`, or co... |
python | def AppendPathEntries(
cls, path, path_separator, number_of_wildcards, skip_first):
"""Appends glob wildcards to a path.
This function will append glob wildcards "*" to a path, returning paths
with an additional glob wildcard up to the specified number. E.g. given
the path "/tmp" and a number of ... |
python | def _add_column(self, column):
"""
Add a new column to the DataFrame
:param column: column name
:return: nothing
"""
self._columns.append(column)
if self._blist:
self._data.append(blist([None] * len(self._index)))
else:
self._data.... |
java | private SQLException createTimeoutException(long startTime)
{
logPoolState("Timeout failure ");
metricsTracker.recordConnectionTimeout();
String sqlState = null;
final Throwable originalException = getLastConnectionFailure();
if (originalException instanceof SQLException) {
sq... |
java | public Element merge(final Element element) {
types.addAll(element.types);
possibleValues.addAll(element.possibleValues);
return this;
} |
java | private void parseTemplateCommands() throws MiniTemplator.TemplateSyntaxException {
int p = 0; // p is the current position within templateText
while (true) {
int p0 = templateText.indexOf(cmdStartStr, p); // p0 is the start of the current command
boolean shortForm = false;
... |
python | def dispatch(self, *args, **kwargs):
"""
Call handlers that match args or kwargs
:return: set of handlers called
"""
called_handlers = set()
for handler_list in self.handlers.values():
for handler, argspec in handler_list:
accept_args, accept_... |
java | public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shado... |
python | def data(self):
"""Returns the request data as a dictionary.
Merges the path parameters, GET parameters and POST parameters
(form-encoded or JSON dictionary). If a key is present in multiple of
these, the first one defined is used.
"""
if self._data:
return s... |
python | def list(self, opts):
"""List all confs or if a conf is given, all the stanzas in it."""
argv = opts.args
count = len(argv)
# unflagged arguments are conf, stanza, key. In this order
# but all are optional
cpres = True if count > 0 else False
spres = True if cou... |
python | def module_sys_modules_key(key):
"""
Check if a module is in the sys.modules dictionary in some manner. If so,
return the key used in that dictionary.
:param key: our key to the module.
:returns: the key in sys.modules or None.
"""
moduleparts = key.split(".")
for partnum, part in enum... |
java | public int size(Long pipelineId) {
Assert.notNull(pipelineId);
TerminMonitor terminMonitor = ArbitrateFactory.getInstance(pipelineId, TerminMonitor.class);
return terminMonitor.size();
} |
python | def _log_progress(self, bytes_downloaded):
"""Logs progress information about ongoing module download.
Args:
bytes_downloaded: Number of bytes downloaded.
"""
self._total_bytes_downloaded += bytes_downloaded
now = time.time()
if (self._interactive_mode() or
now - self._last_progre... |
java | public static <R> Stream<R> zip(final CharIterator a, final CharIterator b, final CharIterator c, final CharTriFunction<R> zipFunction) {
return new IteratorStream<>(new ObjIteratorEx<R>() {
@Override
public boolean hasNext() {
return a.hasNext() && b.hasNext() && c.h... |
java | protected List<HttpMessageConverter<?>> getMessageConverters() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(getFormMessageConverter());
messageConverters.add(getJsonMessageConverter())... |
java | private static void autofit(TextView view, TextPaint paint, float minTextSize, float maxTextSize,
int maxLines, float precision) {
if (maxLines <= 0 || maxLines == Integer.MAX_VALUE) {
// Don't auto-size since there's no limit on lines.
return;
}
int targetWi... |
python | def _check_list_len(row, length):
"""
Sanity check for csv parser
:param row
:param length
:return:None
"""
if len(row) != length:
raise Exception(
"row length does not match expected length of " +
str(length) + "\nrow: ... |
python | def get_handler(name, logname, args):
"""
Retrieve a logger given its name and initialize it by passing it
appropriate arguments from the configuration. (Unnecessary
arguments will be logged, and missing required arguments will
cause a TypeError to be thrown.) The result should be a callable.
... |
java | public void marshall(DeleteLicenseConfigurationRequest deleteLicenseConfigurationRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteLicenseConfigurationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocol... |
python | def recreate_relationships(self, class_, attribute_name, key):
'''
Recreates one-to-many relationship
'''
iterable = self.record_keeper.foreign_to_many_foreign_map[key]
for foreign_page_id, foreign_page_id_list in iteritems(iterable):
# Assumption: local page has bee... |
python | def fmt_number(p):
"""Format a number.
It will be printed as a fraction if the denominator isn't too big and as a
decimal otherwise.
"""
formatted = '{:n}'.format(p)
if not config.PRINT_FRACTIONS:
return formatted
fraction = Fraction(p)
nice = fraction.limit_denominator(128)
... |
python | def part(self):
"""Retrieve the part that holds this Property.
:returns: The :class:`Part` associated to this property
:raises APIError: if the `Part` is not found
"""
part_id = self._json_data['part']
return self._client.part(pk=part_id, category=self._json_data['categ... |
java | public boolean isForUpdate() {
mLock.lock();
try {
return (mClosed || mActive == null) ? false : mActive.isForUpdate();
} finally {
mLock.unlock();
}
} |
java | private LocalVariable getConnection(CodeBuilder b, LocalVariable capVar) {
b.loadLocal(capVar);
b.invokeInterface(TypeDesc.forClass(JDBCConnectionCapability.class),
"getConnection", TypeDesc.forClass(Connection.class), null);
LocalVariable conVar = b.createLocalVari... |
python | def smart_storage(self):
"""This property gets the object for smart storage.
This property gets the object for smart storage.
There is no collection for smart storages.
:returns: an instance of smart storage
"""
return hpe_smart_storage.HPESmartStorage(
self.... |
java | public static DiffSet diffSet(Map<String, Object> introspectionOld, Map<String, Object> introspectionNew) {
return new DiffSet(introspectionOld, introspectionNew);
} |
java | protected void indexVectorInternal(double[] vector) throws Exception {
if (vector.length != vectorLength) {
throw new Exception("The dimensionality of the vector is wrong!");
}
// append the persistent index
appendPersistentIndex(vector);
// append the ram-based index
if (loadIndexInMemory) {
... |
java | private void writeBufferedValsToStorage() {
List<Versioned<byte[]>> obsoleteVals = storageEngine.multiVersionPut(currBufferedKey,
currBufferedVals);
// log Obsolete versions in debug mode
if(logger.isDebugEnabled() && o... |
python | def syntheticMemberDecorator(self,
memberName,
defaultValue,
contract,
readOnly,
privateMemberName,
memberDelegate):
... |
python | def clear_line(self, lines=None, bitmask=None,
leave_remaining_lines=False):
"""
The inverse of activate_line. If a line is active, it deactivates it.
This has the same parameters as activate_line()
"""
if lines is None and bitmask is None:
raise ... |
python | def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
"""
Parameters
----------
outname: str or None
the name of the file to write; If `None`, the bounding box is returned as vector object
format: str
The file format to write
overw... |
java | public static File siblingDirectory(final File f, final String siblingDirName) {
checkNotNull(f);
checkNotNull(siblingDirName);
checkArgument(!siblingDirName.isEmpty());
final File parent = f.getParentFile();
if (parent != null) {
return new File(parent, siblingDirName);
} else {
th... |
java | public static <I extends ImageGray<I>, D extends ImageGray<D>>
GeneralFeatureIntensity<I,D> kitros( Class<D> derivType ) {
return new WrapperKitRosCornerIntensity<>(derivType);
} |
python | def filter_renderers(self, renderers, format):
"""
If there is a '.json' style format suffix, filter the renderers
so that we only negotiation against those that accept that format.
"""
renderers = [renderer for renderer in renderers
if renderer.format == for... |
java | @XmlElementDecl(namespace = "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0", name = "AddressDetails")
public JAXBElement<AddressDetails> createAddressDetails(AddressDetails value) {
return new JAXBElement<AddressDetails>(_AddressDetails_QNAME, AddressDetails.class, null, value);
} |
python | def _get_next_node(self, time_qualifier):
""" Method goes to the top of the tree and traverses from
there in search of the next suitable node for processing
to the level defined by the given time_qualifier
:param time_qualifier: defines target level of the tree
:r... |
python | def alignments(self):
"""
Get alignments from the SAM/BAM file, subject to filtering.
"""
referenceIds = self.referenceIds
dropUnmapped = self.dropUnmapped
dropSecondary = self.dropSecondary
dropSupplementary = self.dropSupplementary
dropDuplicates = self.... |
java | public static KryoPool withByteArrayOutputStream(int poolSize,
final KryoInstantiator ki) {
return new KryoPool(poolSize) {
protected SerDeState newInstance() {
return new SerDeState(ki.newKryo(), new Input(), new Output(new ByteArrayOutputStream())) {
/*
* We have to take e... |
java | private void connect(ZooKeeperClient injectedClient) throws InterruptedException {
if (!initialized.get()) {
if (injectedClient == null) {
List<InetSocketAddress> hosts = new ArrayList<InetSocketAddress>();
for (String host : config.hosts.split(",")) {
... |
java | @Override
protected int msd(Integer a, Integer b) {
/*
* Value equal
*/
if (a.intValue() == b.intValue()) {
return -1;
}
/*
* This is a fast way to compute floor(log_2(a xor b)).
*/
float axorb = a ^ b;
return Math.getEx... |
python | def connect_sts(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.sts.STSConnectio... |
java | public Observable<RoleAssignmentInner> createAsync(String scope, String roleAssignmentName, RoleAssignmentCreateParameters parameters) {
return createWithServiceResponseAsync(scope, roleAssignmentName, parameters).map(new Func1<ServiceResponse<RoleAssignmentInner>, RoleAssignmentInner>() {
@Override... |
java | public ServerBuilder idleTimeout(Duration idleTimeout) {
requireNonNull(idleTimeout, "idleTimeout");
idleTimeoutMillis = ServerConfig.validateIdleTimeoutMillis(idleTimeout.toMillis());
return this;
} |
python | def t_DOCCOMMENT(t):
r'((\'\'\'((?!\'\'\')[\s\S])*\'\'\')|(\'{6,8})|("""((?!""")[\s\S])*""")|("{6,8}))[ \t]*\n'
lineNoInc(t)
pos = t.value.rfind('"""')
if pos == -1:
pos = t.value.rfind('\'\'\'')
t.value = '/**' + t.value[3:pos] + '**/'
return t |
java | private Object getRawValueOrNullIfAbsent(String columnName, Map<String, Object> content)
throws SerDeException {
try {
return getRawValue(columnName, content);
} catch (ColumnNotFoundException e) {
return null;
}
} |
python | def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgradi... |
java | @NonNull
public Expression match(@NonNull String query) {
if (query == null) {
throw new IllegalArgumentException("query is null.");
}
return new FullTextMatchExpression(this.name, query);
} |
java | public BufferedImage drawImage( ReferencedEnvelope ref, int imageWidth, int imageHeight, double buffer ) {
checkMapContent();
if (buffer > 0.0)
ref.expandBy(buffer, buffer);
Rectangle2D refRect = new Rectangle2D.Double(ref.getMinX(), ref.getMinY(), ref.getWidth(), ref.getHeight());... |
java | public synchronized static Session getSession(Properties properties) {
if(session == null){
if(properties == null){
throw new ConfigurationException("jdbc.properties is not found!");
}
try {
String sessionClass = properties.getProperty(... |
python | def read_file(name):
"""Read file name (without extension) to string."""
cur_path = os.path.dirname(__file__)
exts = ('txt', 'rst')
for ext in exts:
path = os.path.join(cur_path, '.'.join((name, ext)))
if os.path.exists(path):
with open(path, 'rt') as file_obj:
... |
java | private String generateAbbreviatedExceptionMessage(final Throwable throwable) {
final StringBuilder builder = new StringBuilder();
builder.append(": ");
builder.append(throwable.getClass().getCanonicalName());
builder.append(": ");
builder.append(throwable.getMessage());
Throwable cause = throwable.getCau... |
python | def smart_query(cls, filters=None, sort_attrs=None, schema=None):
"""
Does magic Django-ish joins like post___user___name__startswith='Bob'
(see https://goo.gl/jAgCyM)
Does filtering, sorting and eager loading at the same time.
And if, say, filters and sorting need the same join... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.