language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public final void innerCreator() throws RecognitionException {
int innerCreator_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 132) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1256:5: ( Identifier classCreatorRest )
// src/... |
java | public static boolean containsIgnoreCase(CharSequence a, CharSequence b) {
return contains(a, b, AsciiCaseInsensitiveCharEqualityComparator.INSTANCE);
} |
python | def unicode(self, *, invert_color: bool = False, borders: bool = False) -> str:
"""
Returns a string representation of the board with Unicode pieces.
Useful for pretty-printing to a terminal.
:param invert_color: Invert color of the Unicode pieces.
:param borders: Show borders a... |
python | def as_enum(enum):
""" Turn a possibly string enum into an integer enum.
"""
if isinstance(enum, string_types):
try:
enum = getattr(gl, 'GL_' + enum.upper())
except AttributeError:
try:
enum = _internalformats['GL_' + enum.upper()]
except K... |
java | final Set<String> getAllColumnNames() {
final Set<String> columnNameSet = mColumnNameFieldInfoMap.keySet();
// Returns clone of columnNameSet because {@see D6Inex} directly
// manipulats(almost delete) columnNameSet,so it effects
// mColumnNameFieldInfoMap.
// So, prevent original columnNameSet from getting ... |
java | public TimeOfDay withChronologyRetainFields(Chronology newChronology) {
newChronology = DateTimeUtils.getChronology(newChronology);
newChronology = newChronology.withUTC();
if (newChronology == getChronology()) {
return this;
} else {
TimeOfDay newTimeOfDay = new ... |
python | def summary(args):
"""
%prog summary *.fasta
Report real bases and N's in fastafiles in a tabular report
"""
from jcvi.utils.natsort import natsort_key
p = OptionParser(summary.__doc__)
p.add_option("--suffix", default="Mb",
help="make the base pair counts human readable [defau... |
java | public void setBundleList(java.util.Collection<BundleDetails> bundleList) {
if (bundleList == null) {
this.bundleList = null;
return;
}
this.bundleList = new java.util.ArrayList<BundleDetails>(bundleList);
} |
python | def geolocation_buses(network, session):
"""
If geopandas is installed:
Use Geometries of buses x/y(lon/lat) and Polygons
of Countries from RenpassGisParameterRegion
in order to locate the buses
Else:
Use coordinats of buses to locate foreign buses, which is less accurate.
Param... |
python | def serve(
host,
port,
app,
request_handler,
error_handler,
before_start=None,
after_start=None,
before_stop=None,
after_stop=None,
debug=False,
request_timeout=60,
response_timeout=60,
keep_alive_timeout=5,
ssl=None,
sock=None,
request_max_size=None,
... |
java | public static String normalizePattern(final String pattern) {
if (pattern == null || "".equals(pattern.trim())) {
return "/";
}
if (pattern.length() > 0 && !pattern.startsWith("/")
&& !pattern.startsWith("*")) {
return "/" + pattern;
}
return pattern;
} |
python | def postproc_mask (stats_result):
"""Simple helper to postprocess angular outputs from StatsCollectors in the
way we want.
"""
n, mean, scat = stats_result
ok = np.isfinite (mean)
n = n[ok]
mean = mean[ok]
scat = scat[ok]
mean *= 180 / np.pi # rad => deg
scat /= n # variance-o... |
python | def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PR... |
python | def write_message(
self, message: Union[str, bytes], binary: bool = False
) -> "Future[None]":
"""Sends the given message to the client of this Web Socket."""
if binary:
opcode = 0x2
else:
opcode = 0x1
message = tornado.escape.utf8(message)
ass... |
python | def get_deprecated_msg(self, wrapped, instance):
"""
Get the deprecation warning message for the user.
:param wrapped: Wrapped class or function.
:param instance: The object to which the wrapped function was bound when it was called.
:return: The warning message.
"""
... |
java | public com.google.api.ads.adwords.axis.v201809.billing.BudgetOrderErrorReason getReason() {
return reason;
} |
python | async def get_prefix(self, message):
"""|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Returns
--------
... |
java | public TraceSummary withServiceIds(ServiceId... serviceIds) {
if (this.serviceIds == null) {
setServiceIds(new java.util.ArrayList<ServiceId>(serviceIds.length));
}
for (ServiceId ele : serviceIds) {
this.serviceIds.add(ele);
}
return this;
} |
java | public TrxMessageHeader addTransportProperties(TrxMessageHeader trxMessageHeader, String strVersion)
{
if (trxMessageHeader.get(MessageTransport.TRANSPORT_ID_PARAM) != null)
{
RecordOwner recordOwner = this.findRecordOwner();
if (m_recMessageTransport == null)
{
... |
java | private String stripPassword(String str)
{
if (str.indexOf("<password>") == -1)
return str;
Pattern pattern = Pattern.compile("<password>[^<]*</password>");
String[] strs = pattern.split(str);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strs.length; i++)
... |
python | def save_json(obj, filename, **kwargs):
"""
Save an object as a JSON file.
Args:
obj: The object to save. Must be JSON-serializable.
filename: Path to the output file.
**kwargs: Additional arguments to `json.dump`.
"""
with open(filename, 'w', encoding='utf-8') as f:
... |
java | public synchronized int addColumn(double[] row) {
if (isFinished)
throw new IllegalStateException(
"Cannot add columns to a MatrixBuilder that is finished");
// Update the size of the matrix based on the size of the array
if (row.length > numCols)
numCols... |
python | async def update(self):
"""
Update sirbot
Trigger the update method of the plugins. This is needed if the plugins
need to perform update migration (i.e database)
"""
logger.info('Updating Sir Bot-a-lot')
for name, plugin in self._plugins.items():
plug... |
python | def plot_f_rate(self, ax, X, i, xlim, x, y, binsize=1, yscale='linear',
plottype='fill_between', show_label=False, rasterized=False):
"""
Plot network firing rate plot in subplot object.
Parameters
----------
ax : `matplotlib.axes.AxesSubplot... |
java | public ApiSuccessResponse complete(String mediatype, String id, CompleteData completeData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = completeWithHttpInfo(mediatype, id, completeData);
return resp.getData();
} |
python | def create_db(file_pth):
""" Create an empty SQLite database for library spectra.
Example:
>>> from msp2db.db import create_db
>>> db_pth = 'library.db'
>>> create_db(file_pth=db_pth)
Args:
file_pth (str): File path for SQLite database
"""
conn = sqlite3.connect(fi... |
python | def code_deparse(co, out=sys.stdout, version=None, debug_opts=DEFAULT_DEBUG_OPTS,
code_objects={}, compile_mode='exec', is_pypy=IS_PYPY, walker=SourceWalker):
"""
ingests and deparses a given code block 'co'. If version is None,
we will use the current Python interpreter version.
"""
... |
java | @SuppressWarnings("unchecked")
public void createSymbols(String ctDescriptionFile, String ctSymLocation, CtSymKind ctSymKind) throws IOException {
ClassList classes = load(Paths.get(ctDescriptionFile));
splitHeaders(classes);
for (ClassDescription classDescription : classes) {
... |
java | public DescribeAccountAttributesResult withAccountAttributes(AccountAttribute... accountAttributes) {
if (this.accountAttributes == null) {
setAccountAttributes(new com.amazonaws.internal.SdkInternalList<AccountAttribute>(accountAttributes.length));
}
for (AccountAttribute ele : acco... |
java | @SuppressWarnings("unchecked")
static Class<? extends ServerChannel> getServerSocketChannelClass(final EventLoopGroup eventLoopGroup) {
Objects.requireNonNull(eventLoopGroup);
final String serverSocketChannelClassName = SERVER_SOCKET_CHANNEL_CLASSES.get(eventLoopGroup.getClass().getName());
... |
java | ResolveSource replaceWithinCurrentParent(AbstractConfigValue old, AbstractConfigValue replacement) {
if (ConfigImpl.traceSubstitutionsEnabled())
ConfigImpl.trace("replaceWithinCurrentParent old " + old + "@" + System.identityHashCode(old)
+ " replacement " + replacement + "@" + S... |
python | async def on_raw_353(self, message):
""" Response to /NAMES. """
target, visibility, channel, names = message.params
if not self.in_channel(channel):
return
# Set channel visibility.
if visibility == protocol.PUBLIC_CHANNEL_SIGIL:
self.channels[channel]['... |
python | def _VAR_DECL_value(self, cursor, _type):
"""Handles Variable value initialization."""
# always expect list [(k,v)] as init value.from list(cursor.get_children())
# get the init_value and special cases
init_value = self._get_var_decl_init_value(cursor.type,
... |
python | def render_html_report(summary, report_template=None, report_dir=None):
""" render html report with specified report name and template
Args:
report_template (str): specify html report template path
report_dir (str): specify html report save directory
"""
if not report_template:
... |
python | def netconf_state_files_file_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
files = ET.SubElement(netconf_state, "files", xmlns="htt... |
java | public static UserBean unmarshallUser(Map<String, Object> source) {
if (source == null) {
return null;
}
UserBean bean = new UserBean();
bean.setUsername(asString(source.get("username")));
bean.setEmail(asString(source.get("email")));
bean.setFullName(asString... |
python | def edit_ini(ini_filepath=None):
"""
Open the .ini file with the operating system’s associated editor.
"""
if ini_filepath == None:
ini_filepath = get_ini_filepath()
try:
click.edit(filename=ini_filepath)
except click.exceptions.ClickException as err:
print("Click err: %... |
java | private static String formatName( String name )
{
if ( name.length() < NAME_COL_WIDTH )
{
return name;
}
return name.substring( 0, NAME_COL_WIDTH - 1 ) + ">";
} |
python | def read_file(filename, print_error=True):
"""Returns the contents of a file."""
try:
for encoding in ['utf-8', 'latin1']:
try:
with io.open(filename, encoding=encoding) as fp:
return fp.read()
except UnicodeDecodeError:
pass
... |
java | private void enQueueCurNodeEdges(CQueue queWork, int nCurNode)
{
int nPreNode;
double eWeight;
List<EdgeFrom> pEdgeToList;
queWork.clear();
pEdgeToList = graph.getEdgeListTo(nCurNode);
// Get all the edgesFrom
for (EdgeFrom e : pEdgeToList)
{
... |
python | def status(self):
"""
Determine the status of the connection and receiver, and return
ERROR, CONNECTED, or DISCONNECTED as appropriate.
For simplicity, we only consider ourselves to be connected
after the Connection class has setup a receiver task. This
only happens afte... |
java | public boolean isCompetitor(Island isl) {
for (Coordinate c : isl) {
for (Coordinate d : islandCoordinates) {
if (c.sameColumn(d) || c.sameRow(d)) return true;
}
}
return false;
} |
python | def save_default_values(self):
"""Save InaSAFE default values."""
for parameter_container in self.default_value_parameter_containers:
parameters = parameter_container.get_parameters()
for parameter in parameters:
set_inasafe_default_value_qsetting(
... |
python | def gen_inherited(self) -> str:
""" Generate the list of slot properties that are inherited across slot_usage or is_a paths """
inherited_head = 'inherited_slots: List[str] = ['
inherited_slots = ', '.join([f'"{underscore(slot.name)}"' for slot in self.schema.slots.values()
... |
java | public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) {
int newOps = 0;
// Translate ops
if ((ops & SelectionKey.OP_ACCEPT) != 0)
newOps |= PollArrayWrapper.POLLIN;
// Place ops into pollfd array
sk.selector.putEventOps(sk, newOps);
} |
python | def _set_dynamic_bypass(self, v, load=False):
"""
Setter method for dynamic_bypass, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/dynamic_bypass (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dynamic_bypass is considered as a private
... |
python | def _num_vowel_to_acc(vowel, tone):
"""Convert a numbered vowel to an accented vowel."""
try:
return VOWEL_MAP[vowel + str(tone)]
except IndexError:
raise ValueError("Vowel must be one of '{}' and tone must be a tone.".format(VOWELS)) |
java | public final Object getValue(final String id, final String property) {
final CriteriaBuilder builder = getSession().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = builder.createQuery(Object.class);
final Root<PrintJobStatusExtImpl> root = criteria.from(PrintJobStatusExtImpl.class);... |
python | def create(self, request):
"""Create a new product request
"""
variant_id = request.data.get("variant_id", None)
if variant_id is not None:
variant = ProductVariant.objects.get(id=variant_id)
product_request = ProductRequest(variant=variant)
product_r... |
python | def _cas_4(self):
''' Longitude/Lagitude overlap (4 images) '''
lonc_left = self._format_lon(self.lonm)
lonc_right = self._format_lon(self.lonM)
latc_top = self._format_lat(self.latM)
latc_bot = self._format_lat(self.latm)
img_name_00 = self._format_name_map(lonc_left, ... |
python | def data_log_send(self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6, force_mavlink1=False):
'''
Configurable data log probes to be used inside Simulink
fl_1 : Log value 1 (float)
fl_2 : Log value 2 (float)
... |
java | public static BIG hashModOrder(byte[] data) {
HASH256 hash = new HASH256();
for (byte b : data) {
hash.process(b);
}
byte[] hasheddata = hash.hash();
BIG ret = BIG.fromBytes(hasheddata);
ret.mod(IdemixUtils.GROUP_ORDER);
return ret;
} |
java | public List<CoNLLWord> findChildren(CoNLLWord word, String relation)
{
List<CoNLLWord> result = new LinkedList<CoNLLWord>();
for (CoNLLWord other : this)
{
if (other.HEAD == word && other.DEPREL.equals(relation))
result.add(other);
}
return result;... |
java | public com.squareup.okhttp.Call getAlliancesAllianceIdContactsLabelsAsync(Integer allianceId, String datasource,
String ifNoneMatch, String token, final ApiCallback<List<AllianceContactsLabelsResponse>> callback)
throws ApiException {
com.squareup.okhttp.Call call = getAlliancesAlliance... |
java | public List<CorporationOrdersHistoryResponse> getCorporationsCorporationIdOrdersHistory(Integer corporationId,
String datasource, String ifNoneMatch, Integer page, String token) throws ApiException {
ApiResponse<List<CorporationOrdersHistoryResponse>> resp = getCorporationsCorporationIdOrdersHistory... |
java | public static IntSet concurrentCopyFrom(IntSet intSet, int maxExclusive) {
ConcurrentSmallIntSet cis = new ConcurrentSmallIntSet(maxExclusive);
intSet.forEach((IntConsumer) cis::set);
return cis;
} |
java | public Observable<IntegrationAccountMapInner> getAsync(String resourceGroupName, String integrationAccountName, String mapName) {
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, mapName).map(new Func1<ServiceResponse<IntegrationAccountMapInner>, IntegrationAccountMapInner>() {
... |
java | @Override
public EClass getIfcPropertyDefinition() {
if (ifcPropertyDefinitionEClass == null) {
ifcPropertyDefinitionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(467);
}
return ifcPropertyDefinitionEClass;
} |
python | def get_dataset(self, key, info):
"""Load a dataset."""
if self.channel not in key.name:
return
logger.debug('Reading %s.', key.name)
if key.calibration == 'brightness_temperature':
variable = self.nc['{}_BT_{}{}'.format(self.channel, self.stripe, self.view)]
... |
python | def ok_check(function, *args, **kwargs):
'''Ensure that the response body is OK'''
req = function(*args, **kwargs)
if req.content.lower() != 'ok':
raise ClientException(req.content)
return req.content |
java | protected ActivityBehavior determineBehaviour(ActivityBehavior delegateInstance) {
if (hasMultiInstanceCharacteristics()) {
multiInstanceActivityBehavior.setInnerActivityBehavior((AbstractBpmnActivityBehavior) delegateInstance);
return multiInstanceActivityBehavior;
}
return delegateInstance;
... |
java | @SuppressWarnings("unused")
@Override
public Iterator<Instance> newIteratorFrom(Iterator<Instance> source) {
List<Instance> output = new LinkedList<Instance>();
while (source.hasNext()) {
Instance carrier = (Instance) source.next();
JCas jCas = (JCas) carrier.getData();
... |
python | def addMsrunContainers(mainContainer, subContainer):
"""Adds the complete content of all specfile entries from the subContainer
to the mainContainer. However if a specfile of ``subContainer.info`` is
already present in ``mainContainer.info`` its contents are not added to the
mainContainer.
:param m... |
java | public ServiceFuture<Void> deleteUserAsync(String poolId, String nodeId, String userName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromHeaderResponse(deleteUserWithServiceResponseAsync(poolId, nodeId, userName), serviceCallback);
} |
python | def do_command(self):
"""Call a single command with arguments."""
method = self.args[0]
raw_args = self.args[1:]
if '=' in method:
if raw_args:
self.parser.error("Please don't mix rTorrent and shell argument styles!")
method, raw_args = method.spl... |
java | @Override
public Value caseACasesExp(ACasesExp node, Context ctxt)
throws AnalysisException
{
BreakpointManager.getBreakpoint(node).check(node.getLocation(), ctxt);
Value val = node.getExpression().apply(VdmRuntime.getExpressionEvaluator(), ctxt);
for (ACaseAlternative c : node.getCases())
{
Value rv ... |
java | public static String choose(String dictElem, String romaji) {
dictElem = clean(dictElem);
// simplify verbs
// if (pos.contains("verb") && dictElem.startsWith("to ")) {
// dictElem = dictElem.substring(3);
// }
// discard elements of more than 4 words
if (isLong(dictElem)) {
return null;
}
... |
java | public static String getClassName(QName qname) {
try {
StringBuilder className = new StringBuilder();
// e.g., {http://www.w3.org/2001/XMLSchema}decimal
StringTokenizer st1 = new StringTokenizer(qname.getNamespaceURI(),
"/");
// --> "http:" -> "www.w3.org" --> "2001" -> "XMLSchema"
st1.nextToken(... |
java | public Matrix3f rotateY(float ang, Matrix3f dest) {
float sin, cos;
if (ang == (float) Math.PI || ang == -(float) Math.PI) {
cos = -1.0f;
sin = 0.0f;
} else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) {
cos = 0.0f;
sin = 1.... |
python | def libvlc_video_get_chapter_description(p_mi, i_title):
'''Get the description of available chapters for specific title.
@param p_mi: the media player.
@param i_title: selected title.
@return: list containing description of available chapter for title i_title.
'''
f = _Cfunctions.get('libvlc_vi... |
python | def only(self, *keys):
"""
Get the items with the specified keys.
:param keys: The keys to keep
:type keys: tuple
:rtype: Collection
"""
items = []
for key, value in enumerate(self.items):
if key in keys:
items.append(value)
... |
java | public void setCode(final String code) {
if (isAttached()) {
setCode(getElement(), code);
} else {
getElement().setInnerHTML(code);
}
} |
java | public Set<T> dfs(Set<T> roots) {
Deque<T> deque = new LinkedList<>(roots);
Set<T> visited = new HashSet<>();
while (!deque.isEmpty()) {
T u = deque.pop();
if (!visited.contains(u)) {
visited.add(u);
if (contains(u)) {
a... |
python | def publish_receiver_count(
self, service, routing_id, method, timeout=None):
'''Get the number of peers that would handle a particular publish
This method will block until a response arrives
:param service: the service name
:type service: anything hash-able
:param ... |
java | public synchronized CheckBox setChecked(final boolean checked) {
this.checked = checked;
runOnGUIThreadIfExistsOtherwiseRunDirect(new Runnable() {
@Override
public void run() {
for(Listener listener : listeners) {
listener.onStatusChanged(check... |
java | public JSONObject put(String key, float value) throws JSONException {
return this.put(key, Float.valueOf(value));
} |
python | def save_profile(self, userdata, data):
""" Save user profile modifications """
result = userdata
error = False
# Check if updating username.
if not userdata["username"] and "username" in data:
if re.match(r"^[-_|~0-9A-Z]{4,}$", data["username"], re.IGNORECASE) is No... |
python | def get_steam():
"""
Returns a Steam object representing the current Steam installation on the
users computer. If the user doesn't have Steam installed, returns None.
"""
# Helper function which checks if the potential userdata directory exists
# and returns a new Steam instance with that userdata directory... |
python | def find_crs(op, element):
"""
Traverses the supplied object looking for coordinate reference
systems (crs). If multiple clashing reference systems are found
it will throw an error.
"""
crss = [crs for crs in element.traverse(lambda x: x.crs, [_Element])
if crs is not None]
if no... |
python | def _repack(h5file):
"""
Repack archive to remove freespace.
Returns
-------
file : h5py File or None
If the input is a h5py.File then a h5py File instance of the
repacked archive is returned. The input File instance will no longer
be useable.
"""
f1,... |
python | def GetDefaultContract(self):
"""
Get the default contract.
Returns:
contract (Contract): if Successful, a contract of type neo.SmartContract.Contract, otherwise an Exception.
Raises:
Exception: if no default contract is found.
Note:
Prints ... |
python | def wait(self):
"""
Block until a matched message appears.
"""
if not self._patterns:
raise RuntimeError('Listener has nothing to capture')
while 1:
msg = self._queue.get(block=True)
if any(map(lambda p: filtering.match_all(msg, p), self._pat... |
java | public final void setEntryFactory(Callback<CreateEntryParameter, Entry<?>> factory) {
Objects.requireNonNull(factory);
entryFactoryProperty().set(factory);
} |
java | @Override
public org.fcrepo.server.types.gen.Validation validate(String pid,
String asOfDateTime) {
assertInitialized();
try {
MessageContext ctx = context.getMessageContext();
return TypeUtility
.... |
python | def external_system_identifiers(endpoint):
"""Populate the ``external_system_identifiers`` key.
Also populates the ``new_record`` key through side effects.
"""
@utils.flatten
@utils.for_each_value
def _external_system_identifiers(self, key, value):
new_recid = maybe_int(value.get('d'))
... |
java | @Autowired
@RefreshScope
@Bean
public IgniteConfiguration igniteConfiguration(@Qualifier("ticketCatalog") final TicketCatalog ticketCatalog) {
val ignite = casProperties.getTicket().getRegistry().getIgnite();
val config = new IgniteConfiguration();
val spi = new TcpDiscoverySpi();
... |
python | def remove_esc_chars(text_string):
'''
Removes any escape character within text_string and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is None or... |
java | @Override
public void consume(@NotNull final Purchase itemInfo) throws IabException {
Logger.i("NokiaStoreHelper.consume");
final String token = itemInfo.getToken();
final String productId = itemInfo.getSku();
final String packageName = itemInfo.getPackageName();
Logger.d("... |
python | def _reprJSON(self):
"""Returns a JSON serializable represenation of a ``MzmlPrecursor``
class instance. Use :func:`maspy.core.MzmlPrecursor._fromJSON()` to
generate a new ``MzmlPrecursor`` instance from the return value.
:returns: a JSON serializable python object
"""
r... |
python | def sendAZ(self, az):
'''
Sends AZ velocity.
@param az: AZ velocity
@type az: float
'''
self.lock.acquire()
self.data.az = az
self.lock.release() |
python | def clip_gradients(batch_result, model, max_grad_norm):
""" Clip gradients to a given maximum length """
if max_grad_norm is not None:
grad_norm = torch.nn.utils.clip_grad_norm_(
filter(lambda p: p.requires_grad, model.parameters()),
max_norm=max_grad_norm
)
else:
... |
java | static void colorKeyCursor(byte[] source,
Buffer dest,
int targetDepth,
int transparentPixel) {
switch (targetDepth) {
case 32:
colorKeyCursor32(source,
... |
python | def return_dat(self, chan, begsam, endsam):
"""Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last ... |
python | def get_state(self, minimal:bool=True):
"Return the inner state of the `Callback`, `minimal` or not."
to_remove = ['exclude', 'not_min'] + getattr(self, 'exclude', []).copy()
if minimal: to_remove += getattr(self, 'not_min', []).copy()
return {k:v for k,v in self.__dict__.items() if k no... |
python | def split_n(string, seps, reg=False):
r"""Split strings into n-dimensional list.
::
from torequests.utils import split_n
ss = '''a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6'''
print(split_n(ss, ('\n', ' ', ' ')))
# [[['a',... |
python | def remove_comments(self, recursive=True):
"""Remove latex comments from document (modifies document in place).
Parameters
----------
recursive : bool
Remove comments from all input LaTeX documents (default ``True``).
"""
self.text = texutils.remove_comments(... |
python | def get_all_environment_option_pool(self, id_environment=None, option_id=None, option_type=None):
"""Get all Option VIP by Environment .
:return: Dictionary with the following structure:
::
{[{‘id’: < id >,
option: {
'id': <id>
... |
python | def minimum_needs(self, input_layer):
"""Compute minimum needs given a layer and a column containing pop.
:param input_layer: Vector layer assumed to contain
population counts.
:type input_layer: QgsVectorLayer
:returns: A tuple containing True and the vector layer if
... |
python | def add_user(self, **kwargs):
"""Add a User object, with properties specified in ``**kwargs``."""
user = self.UserClass(**kwargs)
if hasattr(user, 'active'):
user.active = True
self.db_adapter.add_object(user)
return user |
java | public static TagLib nameSpace(Data data) {
boolean hasTag = false;
int start = data.srcCode.getPos();
TagLib tagLib = null;
// loop over NameSpaces
for (int i = 1; i >= 0; i--) {
for (int ii = 0; ii < data.tlibs[i].length; ii++) {
tagLib = data.tlibs[i][ii];
char[] c = tagLib.getNameSpaceAndSeperatorAsC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.