language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def BuildDefaultValue(self, value_cls):
"""Renders default value of a given class.
Args:
value_cls: Default value of this class will be rendered. This class has to
be (or to be a subclass of) a self.value_class (i.e. a class that this
renderer is capable of rendering).
Returns:
... |
python | def facetrecordtrees(table, key, start='start', stop='stop'):
"""
Construct faceted interval trees for the given table, where each node in
the tree is a record.
"""
import intervaltree
getstart = attrgetter(start)
getstop = attrgetter(stop)
getkey = attrgetter(key)
trees = dict()
... |
python | def data_log_encode(self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6):
'''
Configurable data log probes to be used inside Simulink
fl_1 : Log value 1 (float)
fl_2 : Log value 2 (float)
fl_3 ... |
python | def python_like_exts():
"""Return a list of all python-like extensions"""
exts = []
for lang in languages.PYTHON_LIKE_LANGUAGES:
exts.extend(list(languages.ALL_LANGUAGES[lang]))
return ['.' + ext for ext in exts] |
java | private boolean invokeHook(RouteContext context, Route hookRoute) throws Exception {
Method hookMethod = hookRoute.getAction();
Object target = WebContext.blade().ioc().getBean(hookRoute.getTargetType());
if (null == target) {
Class<?> clazz = hookRoute.getAction().getDeclaringCl... |
python | def run_migration(data, version_start, version_end):
"""Runs migration against a data set."""
items = []
if version_start == 1 and version_end == 2:
for item in data['accounts']:
items.append(v2.upgrade(item))
if version_start == 2 and version_end == 1:
for item in data:
... |
python | def compile_proto(source, python_out, proto_path):
"""Invoke Protocol Compiler to generate python from given source .proto."""
if not protoc:
sys.exit('protoc not found. Is the protobuf-compiler installed?\n')
protoc_command = [
protoc,
'--proto_path', proto_path,
'--python_out', python_out... |
python | def emitDataChanged(self, treeItem): # TODO: move to BaseTreeItem?
""" Emits the data changed for the model indices (all columns) for this treeItem
"""
indexLeft, indexRight = self.indexTupleFromItem(treeItem)
checkItem = self.getItem(indexLeft)
assert checkItem is treeItem, "{}... |
python | def unique(keys, axis=semantics.axis_default, return_index=False, return_inverse=False, return_count=False):
"""compute the set of unique keys
Parameters
----------
keys : indexable key object
keys object to find unique keys within
axis : int
if keys is a multi-dimensional array, th... |
python | def status(self, value):
"""Set Query Status"""
if value is not None:
if not isinstance(value, QueryStatusType):
raise AttributeError("%s action type is invalid in mdsol:Query." % (value,))
self._status = value |
python | def normalizeFilename(filename):
"""Take a given filename and return the normalized version of it.
Where ~/ is expanded to the full OS specific home directory and all
relative path elements are resolved.
"""
result = os.path.expanduser(filename)
result = os.path.abspath(result)
return result |
python | def get_queryset(self, request):
"""
Annotate the queryset with the entries count for use in the
admin list view.
"""
qs = super(FormAdmin, self).get_queryset(request)
return qs.annotate(total_entries=Count("entries")) |
python | def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
self.__clear_button.setCursor(Qt.ArrowCursor)
if self.__ui_clear_image and self.__ui_clear_clicked_image:
pixmap = QPixmap(self.__ui_clear_image)
clicked_pixmap = QPixmap(self.__ui_clear_clicke... |
java | @Override
public int size()
{
if (size < 0) {
size = 0;
for (int i = 0; i <= lastWordIndex; i++) {
int w = words[i];
if (isLiteral(w)) {
size += getLiteralBitCount(w);
} else {
if (isZeroSequence(w)) {
if (!isSequenceWithNoBits(w)) {... |
java | protected void configureJaxbMarshaller(javax.xml.bind.Marshaller marshaller)
throws PropertyException {
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT,
m_formatOutput);
} |
java | public void setGroupName(String name)
{
groupName = name;
groupId = (parentId == null ? "" : parentId) + "/" + groupName;
} |
java | public ElementDefinitionDt addType(Type theValue) {
if (theValue == null) {
throw new NullPointerException("theValue must not be null");
}
getType().add(theValue);
return this;
} |
java | @Override
public void process(ImapRequestLineReader request,
ImapResponse response,
ImapSession session) {
try {
doProcess(request, response, session);
} catch (FolderException e) {
log.warn("Error processing command", e)... |
java | @Override
public void getResources(Vector<URL> vector, String name)
{
if (_pathMap != null) {
String cleanName = name;
if (cleanName.endsWith("/"))
cleanName = cleanName.substring(0, cleanName.length() - 1);
JarMap.JarList jarEntryList = _pathMap.get(cleanName);
fo... |
python | def related_records2marc(self, key, value):
"""Populate the ``78708`` MARC field
Also populates the ``78002``, ``78502`` MARC fields through side effects.
"""
if value.get('relation_freetext'):
return {
'i': value.get('relation_freetext'),
'w': get_recid_from_ref(value.g... |
java | private boolean resolveViaRegistry(ErrorReporter reporter) {
JSType type = registry.getType(resolutionScope, reference);
if (type != null) {
setReferencedAndResolvedType(type, reporter);
return true;
}
return false;
} |
python | def add_hosted_zone_id_for_alias_target_if_missing(self, rs):
"""Add proper hosted zone id to record set alias target if missing."""
alias_target = getattr(rs, "AliasTarget", None)
if alias_target:
hosted_zone_id = getattr(alias_target, "HostedZoneId", None)
if not hosted... |
python | def dup(self, other=None, **kwds):
'''Duplicate attributes of dict or other typedef.
'''
if other is None:
d = _dict_typedef.kwds()
else:
d = other.kwds()
d.update(kwds)
self.reset(**d) |
python | def match_entries(entries, pattern):
"""A drop-in replacement for fnmatch.filter that supports pattern
variants (ie. {foo,bar}baz = foobaz or barbaz)."""
matching = []
for variant in expand_braces(pattern):
matching.extend(fnmatch.filter(entries, variant))
return list(_deduplicate(matching... |
python | def __validate_simple_subfield(self, parameter, field, segment_list,
_segment_index=0):
"""Verifies that a proposed subfield actually exists and is a simple field.
Here, simple means it is not a MessageField (nested).
Args:
parameter: String; the '.' delimited name o... |
python | def result(self):
"""
The result from realising the future
If the result is not available, block until done.
:return: result of the future
:raises: any exception encountered during realising the future
"""
if self._result is None:
self.await_result()... |
python | def update_artifact_cache(self, vts_artifactfiles_pairs):
"""Write to the artifact cache, if we're configured to.
vts_artifactfiles_pairs - a list of pairs (vts, artifactfiles) where
- vts is single VersionedTargetSet.
- artifactfiles is a list of absolute paths to artifacts for the VersionedTarget... |
python | def get_valid_class_name(s: str) -> str:
"""Return the given string converted so that it can be used for a class name
Remove leading and trailing spaces; removes spaces and capitalizes each
word; and remove anything that is not alphanumeric. Returns a pep8
compatible class name.
:param s: The str... |
java | @Override
public String psetex(final byte[] key, final long milliseconds, final byte[] value) {
checkIsInMultiOrPipeline();
client.psetex(key, milliseconds, value);
return client.getStatusCodeReply();
} |
python | def get_size(self):
"""Retrieves the size of the file-like object.
Returns:
int: size of the file-like object data.
Raises:
IOError: if the file-like object has not been opened.
OSError: if the file-like object has not been opened.
"""
if not self._is_open:
raise IOError('N... |
java | public static CommerceNotificationTemplate fetchByG_E_First(long groupId,
boolean enabled,
OrderByComparator<CommerceNotificationTemplate> orderByComparator) {
return getPersistence()
.fetchByG_E_First(groupId, enabled, orderByComparator);
} |
python | def _reduce(self):
"""Perform a greedy reduction of token stream.
If a reducer method matches, it will be executed, then the
:meth:`reduce` method will be called recursively to search
for any more possible reductions.
"""
for reduction, methname in self.reducers:
... |
java | public T imeAction(int lable, final View associateView) {
if (view instanceof EditText) {
((EditText)view).setImeActionLabel(context.getString(lable),view.getId());
((EditText)view).setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
... |
python | def __compact_notification_addresses(addresses_):
"""
Input::
{
'default': 'http://domain/notice',
'event1': 'http://domain/notice',
'event2': 'http://domain/notice',
'event3': 'http://domain/notice3',
'event4': 'http://domain/notice3'
... |
java | @Override
@SuppressWarnings("unchecked")
public <D, App extends Applicative<?, App>, TravB extends Traversable<D, Choice3<A, B, ?>>,
AppB extends Applicative<D, App>,
AppTrav extends Applicative<TravB, App>> AppTrav traverse(Function<? super C, ? extends AppB> fn,
... |
python | def compute_BtBinv(B, C):
"""Create block inverses.
Helper function that creates inv(B_i.T B_i) for each block row i in C,
where B_i is B restricted to the sparsity pattern of block row i.
Parameters
----------
B : {array}
(M,k) array, typically near-nullspace modes for coarse grid, i.... |
java | public static void setInternalState(Object object, Object value, Object... additionalValues) {
WhiteboxImpl.setInternalState(object, value, additionalValues);
} |
python | def move(self, fromaccount, toaccount, amount, minconf=1):
"""Send coins between accounts in the same wallet.
If the receiving account does not exist, it is automatically
created (but not automatically assigned an address).
Args:
fromaccount (str): origin account
to... |
java | public static DoubleStream shiftingWindowAveragingLong(LongStream longStream, int rollingFactor) {
Objects.requireNonNull(longStream);
RollingOfLongSpliterator ofLongSpliterator = RollingOfLongSpliterator.of(longStream.spliterator(), rollingFactor);
return StreamSupport.stream(ofLongSpliterator... |
python | def event_payment(self, date, time, pid, commerce_id, transaction_id, request_ip, token, webpay_server):
'''Record the payment event
Official handler writes this information to TBK_EVN%Y%m%d file.
'''
raise NotImplementedError("Logging Handler must implement event_payment") |
python | def compiled(template, delimiters=DEFAULT_DELIMITERS):
"""Compile a template into token tree
:template: TODO
:delimiters: TODO
:returns: the root token
"""
re_tag = delimiters_to_re(delimiters)
# variable to save states
tokens = []
index = 0
sections = []
tokens_stack = []... |
python | def p_example_field_ref(self, p):
'example_field : ID EQ ID NL'
p[0] = AstExampleField(self.path, p.lineno(1), p.lexpos(1),
p[1], AstExampleRef(self.path, p.lineno(3), p.lexpos(3), p[3])) |
python | def die(msg, errlvl=1, prefix="Error: "):
"""Convenience function to write short message to stderr and quit."""
stderr("%s%s\n" % (prefix, msg))
sys.exit(errlvl) |
java | public static double getCosinValue(double[] vector1, double[] vector2) {
if (vector1 == null || vector2 == null) {
return 0;
}
double dotProduct = VectorUtils.dotProduct(vector1, vector2);
double euclideanDistance = VectorUtils.vectorLen(vector1) * VectorUtils.vectorLen(vecto... |
java | @WorkerThread
public static Process runWithEnv(@NonNull String command, Map<String, String> environment) throws IOException {
String[] env;
if (environment != null && environment.size() != 0) {
Map<String, String> newEnvironment = new HashMap<>();
newEnvironment.putAll(System.getenv());
newE... |
java | public Invocable invokeScriptWithOutAddOnLoader(ScriptWrapper script) throws ScriptException {
logger.debug("invokeScriptWithOutAddOnLoader " + script.getName());
preInvokeScript(script);
return invokeScriptImpl(script);
} |
python | def _check_response_for_request_warnings(self):
"""
Override this in a service module to check for errors that are
specific to that module. For example, changing state/province based
on postal code in a Rate Service request.
"""
if self.response.HighestSeverity in ("NOTE... |
java | @Override
long[] generate(long[] current, StereoEncoder encoder, int[][] graph, Suppressed suppressed) {
// for the stereo perception depending on how the
// (BasicPermutationParity) is done we need to set the value to be as
// high (or low) as possible
for (int i : suppressed.toArr... |
java | public void marshall(CreateTrainingJobRequest createTrainingJobRequest, ProtocolMarshaller protocolMarshaller) {
if (createTrainingJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createT... |
java | public synchronized void start(List<Long> weights) throws InterruptedException {
for (int i = 0; i < weights.size(); i++) {
this.weights.add(weights.get(i));
}
int number = latch.decrementAndGet();
if (number == 0) {
Long initWeight = this.weights.peek();
... |
java | @Override
public int compareTo(ValueArray<NullValue> o) {
NullValueArray other = (NullValueArray) o;
return Integer.compare(position, other.position);
} |
python | def _compile_sequence(self, schema, seq_type):
"""Validate a sequence type.
This is a sequence of valid values or validators tried in order.
>>> validator = Schema(['one', 'two', int])
>>> validator(['one'])
['one']
>>> with raises(er.MultipleInvalid, 'expected int @ da... |
java | public static String hexEncode(final String data) {
try {
val result = Hex.encodeHex(data.getBytes(StandardCharsets.UTF_8));
return new String(result);
} catch (final Exception e) {
return null;
}
} |
java | public com.squareup.okhttp.Call connectPostNamespacedPodExecAsync(String name, String namespace, String command, String container, Boolean stderr, Boolean stdin, Boolean stdout, Boolean tty, final ApiCallback<String> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;... |
python | def dump(stuff, filename, verbose=True, protocol=3):
"""Store an object to file by pickling
Parameters
----------
stuff : object to be pickled
filename : path
verbose : bool
protocol : 1,2,3 (default = 3)
Protocol used by Pickler, higher number means more recent version of Python is... |
java | public DeployKey getDeployKey(Object projectIdOrPath, Integer keyId) throws GitLabApiException {
if (keyId == null) {
throw new RuntimeException("keyId cannot be null");
}
Response response = get(Response.Status.OK, null,
"projects", getProjectIdOrPath(projectIdOrPa... |
python | def reset(all=False, vms=False, switches=False):
'''
Reset the running state of VMM or a subsystem.
all:
Reset the running state.
switches:
Reset the configured switches.
vms:
Reset and terminate all VMs.
CLI Example:
.. code-block:: bash
salt '*' vmctl... |
java | private static void renderException(final Map model, final HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
model.put("status", HttpServletResponse.SC_BAD_REQUEST);
render(model, response);
} |
java | @Override
public Map<String, List<Object>> getHandles(String projectId) throws IOException {
File projectDir = getProjectDir(projectId, false);
if (projectDir.exists() && projectDir.isDirectory()) {
return getHandlesFromProjectDirectory(projectDir);
} else {
return ne... |
python | def cortex_to_image_interpolation(obj, mask=None, affine=None, method='linear', shape=None):
'''
cortex_to_image_interpolation(obj) yields a tuple (indices, interp) where indices is a tuple of
voxel indices and interp is an interpolation matrix that converts a vector of cortical
surface vertex value... |
java | public static int getCount(Matcher matcher) {
int counter = 0;
matcher.reset();
while (matcher.find()) {
counter++;
}
return counter;
} |
java | @Override
protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
{
if (log.isDebugEnabled())
log.debug("Persisting " + entity);
// All Modifying Neo4J operations must be executed within a transaction
checkActiveTrans... |
java | public static JulianDate from(TemporalAccessor temporal) {
if (temporal instanceof JulianDate) {
return (JulianDate) temporal;
}
return JulianDate.ofEpochDay(temporal.getLong(EPOCH_DAY));
} |
java | @SuppressWarnings("unchecked")
public static final Map<?, ?> hidePasswords(Map<?, ?> map) {
map = new HashMap<Object, Object>(map);
for (@SuppressWarnings("rawtypes")
Map.Entry entry : map.entrySet())
if (entry.getKey() instanceof String && PropertyService.isPassword((String) en... |
java | @Override
public ListSecretsResult listSecrets(ListSecretsRequest request) {
request = beforeClientExecution(request);
return executeListSecrets(request);
} |
java | protected File [] getTargetFiles (final File targetDirectory, final String grammarFile, final GrammarInfo grammarInfo)
{
final File parserFile = new File (targetDirectory, grammarInfo.getParserFile ());
return new File [] { parserFile };
} |
java | private static void checkFilePattern(String s) throws ProblemException {
// File names like foo/bar/gamma/Bar.java are allowed,
// as well as /bar/jndi.properties as well as,
// */bar/Foo.java
Pattern p = null;
if (File.separatorChar == '\\') {
p = Pattern.compile("\\... |
python | def Get(self,key):
"""Get group by providing name, ID, description or other unique key.
If key is not unique and finds multiple matches only the first
will be returned
>>> clc.v2.Datacenter().Groups().Get("Default Group")
<clc.APIv2.group.Group object at 0x1065e5250>
"""
for group in self.groups:
i... |
python | def _convert_markup_basic(self, soup):
"""
Perform basic conversion of instructions markup. This includes
replacement of several textual markup tags with their HTML equivalents.
@param soup: BeautifulSoup instance.
@type soup: BeautifulSoup
"""
# Inject meta char... |
python | def interventions(self):
""" Dictionary of interventions in /scenario/interventions/vectorPop section """
interventions = {}
if self.et is None:
return interventions
for intervention in self.et.findall("intervention"):
interventions[intervention.attrib['name']] = ... |
python | def rate_of_turn(speed, bank):
'''return expected rate of turn in degrees/s for given speed in m/s and
bank angle in degrees'''
if abs(speed) < 2 or abs(bank) > 80:
return 0
ret = degrees(9.81*tan(radians(bank))/speed)
return ret |
java | public void setMaxRetriesBeforeRequeue(int maxRetriesBeforeRequeue)
{
this.maxRetriesBeforeRequeue = maxRetriesBeforeRequeue;
this.transactionStyle = new TransactionStyle(MithraManagerProvider.getMithraManager().getTransactionTimeout(), maxRetriesBeforeRequeue, this.retryOnTimeout);
} |
python | def delete(self, *, if_unused=True):
"""
Delete the exchange.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool if_unused: If true, the exchange will only be deleted if
it has no queues bound to it.
"""
self.sender.send_ExchangeDelete(self.name, i... |
python | def records(self):
""" Get each record that has been stored in the table. """
output = tempfile.NamedTemporaryFile(suffix='.json')
try:
log.info("Loading table from (%s)...", self._obj)
shutil.copyfileobj(self.fh(), output)
output.seek(0)
for line... |
python | def parse_image_spec(spec):
""" Parses out a Publ-Markdown image spec into a tuple of path, args, title """
# I was having trouble coming up with a single RE that did it right,
# so let's just break it down into sub-problems. First, parse out the
# alt text...
match = re.match(r'(.+)\s+\"(.*)\"\s*$... |
python | def cli(env, date_min, date_max, obj_event, obj_id, obj_type, utc_offset, metadata, limit):
"""Get Event Logs
Example:
slcli event-log get -d 01/01/2019 -D 02/01/2019 -t User -l 10
"""
columns = ['Event', 'Object', 'Type', 'Date', 'Username']
event_mgr = SoftLayer.EventLogManager(env.clien... |
python | def stop(self):
"""Stop the underlying :class:`SparkContext`.
"""
self._sc.stop()
# We should clean the default session up. See SPARK-23228.
self._jvm.SparkSession.clearDefaultSession()
self._jvm.SparkSession.clearActiveSession()
SparkSession._instantiatedSession ... |
python | def AnalyzeEvents(self):
"""Analyzes events from a plaso storage file and generate a report.
Raises:
BadConfigOption: when a configuration parameter fails validation.
RuntimeError: if a non-recoverable situation is encountered.
"""
session = engine.BaseEngine.CreateSession(
command_... |
python | def _need_update(self, project_name, updatetime=None, md5sum=None):
'''Check if project_name need update'''
if project_name not in self.projects:
return True
elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'):
return True
elif updatetime a... |
java | public void log(Log log) {
log.info("Counters: " + size());
for(Group group: this) {
log.info(" " + group.getDisplayName());
for (Counter counter: group) {
log.info(" " + counter.getDisplayName() + "=" +
counter.getCounter());
}
}
} |
python | def _loadMore(self, start=0, trys=0, validation=True):
"""Retrieves the next page of results."""
self._log.debug("Loading page starting from %d" % start)
self._czero = start
self._pageoffs = 0
try:
pyxb.RequireValidWhenParsing(validation)
self._object_list... |
python | def command_long_encode(self, target_system, target_component, command, confirmation, param1, param2, param3, param4, param5, param6, param7):
'''
Send a command with up to seven parameters to the MAV
target_system : System which should execute the command (u... |
python | def set_analysis_config(self, group_name, config):
""" Set Configuration data for analysis group. The ``config`` can
be passed as a dict of dicts e.g. ``{'section': {'key': 'value'}}``
or can be passed directly as a ConfigParser object.
:param group_name: The name of the analys... |
java | private byte[] calculateHmacSHA256(String data, byte[] key)
throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
return mac.doFinal(data.getBytes(ENCODING));
... |
python | def notify_owner(func):
''' A decorator for mutating methods of property container classes
that notifies owners of the property container about mutating changes.
Args:
func (callable) : the container method to wrap in a notification
Returns:
wrapped method
Examples:
A ``_... |
python | def walk(self, match=None, errors='strict'):
""" D.walk() -> iterator over files and subdirs, recursively.
The iterator yields Path objects naming each child item of
this directory and its descendants. This requires that
``D.isdir()``.
This performs a depth-first traversal of ... |
java | public boolean contains(String encoding) {
if (encoding.equalsIgnoreCase("sendrecv") ||
encoding.equalsIgnoreCase("fmtp") ||
encoding.equalsIgnoreCase("audio") ||
encoding.equalsIgnoreCase("AS") ||
encoding.equalsIgnoreCase("IP4")) {
... |
java | public Integer getInitialPoolSize()
{
if (childNode.getTextValueForPatternName("initial-pool-size") != null && !childNode.getTextValueForPatternName("initial-pool-size").equals("null")) {
return Integer.valueOf(childNode.getTextValueForPatternName("initial-pool-size"));
}
return null;
} |
python | def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, Promise):
# The input is the result of a gettex... |
java | public static JobHistoryFileParser createJobHistoryFileParser(
byte[] historyFileContents, Configuration jobConf) throws IllegalArgumentException {
if (historyFileContents == null) {
throw new IllegalArgumentException(
"Job history contents should not be null");
}
HadoopVersion versi... |
java | public void setMethod(BshMethod method) {
String name = method.getName();
if (!this.methods.containsKey(name))
this.methods.put(name, new ArrayList<BshMethod>(1));
this.methods.get(name).remove(method);
this.methods.get(name).add(0, method);
} |
python | def _focus_tab(self, tab_idx):
"""Change tab focus"""
for i in range(self.tab_widget.count()):
self.tab_widget.setTabEnabled(i, False)
self.tab_widget.setTabEnabled(tab_idx, True)
self.tab_widget.setCurrentIndex(tab_idx) |
python | def port_create_vlan(br, port, id, internal=False):
'''
Isolate VM traffic using VLANs.
Args:
br: A string - bridge name.
port: A string - port name.
id: An integer in the valid range 0 to 4095 (inclusive), name of VLAN.
internal: A boolean to create an internal interface if... |
python | def extended_fade_in(self, segment, duration):
"""Add a fade-in to a segment that extends the beginning of the
segment.
:param segment: Segment to fade in
:type segment: :py:class:`radiotool.composer.Segment`
:param duration: Duration of fade-in (in seconds)
:returns: Th... |
python | def authorize_url(self, redirect_uri, state=None):
"""
构造网页授权链接
详情请参考
https://work.weixin.qq.com/api/doc#90000/90135/91022
:param redirect_uri: 授权后重定向的回调链接地址
:param state: 重定向后会带上 state 参数
:return: 返回的 JSON 数据包
"""
redirect_uri = six.moves.urllib.... |
python | def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['SUBST_CMD_FILE'] = LinklocGenerator
env['SHLINK'] = '$LINK'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS')
env['... |
java | public Matrix4d shadow(double lightX, double lightY, double lightZ, double lightW, double a, double b, double c, double d, Matrix4d dest) {
// normalize plane
double invPlaneLen = 1.0 / Math.sqrt(a*a + b*b + c*c);
double an = a * invPlaneLen;
double bn = b * invPlaneLen;
double c... |
java | public static String getCalendarType(ULocale loc) {
String calType = loc.getKeywordValue(CALKEY);
if (calType != null) {
return calType;
}
// Canonicalize, so grandfathered variant will be transformed to keywords
ULocale canonical = ULocale.createCanonical(loc.toStri... |
python | def get_instance(self, payload):
"""
Build an instance of MessageInteractionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionInstance
:rtype: twilio.rest.proxy.v1.service... |
java | private void growTable()
{
if (tc.isEntryEnabled()) SibTr.entry(this, tc, "growTable");
int newSize = Math.min(table.length+TABLE_GROWTH_INCREMENT, maxSize);
if (tc.isDebugEnabled()) SibTr.debug(this, tc, "existing size="+table.length+" new size="+newSize);
Object[] newTable = new Object[ne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.