language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def dump(self):
""" Returns a tuple containing code ORG, and a list of OUTPUT
"""
org = min(self.memory_bytes.keys()) # Org is the lowest one
OUTPUT = []
align = []
for i in range(org, max(self.memory_bytes.keys()) + 1):
if gl.has_errors:
ret... |
python | def _visibleToRealColumn(self, text, visiblePos):
"""If \t is used, real position of symbol in block and visible position differs
This function converts visible to real.
Bigger value is returned, if visiblePos is in the middle of \t, None if text is too short
"""
if visiblePos ==... |
java | public String findWithinHorizon(Pattern pattern, int horizon) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
if (horizon < 0)
throw new IllegalArgumentException("horizon < 0");
clearCaches();
// Search for the pattern
while... |
python | def readDir(dirPath, numLabels, modify=False):
"""
Reads in data from a directory of CSV files; assumes the directory only
contains CSV files.
@param dirPath (str) Path to the directory.
@param numLabels (int) Number of columns of category labels.
@param modify ... |
java | public void transformDownSamplerToRollupQuery(final Aggregator group_by,
final String str_interval) {
if (downsampler != null && downsampler.getInterval() > 0) {
if (tsdb.getRollupConfig() != null) {
try {
best_match_rollups = tsdb.getRollupConfig().
getRollupInter... |
python | def pretty_print_config_to_json(self, services, hostname=None, x_google_api_name=False):
"""JSON string description of a protorpc.remote.Service in OpenAPI format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hos... |
java | public void execute(AbstractCompile task) {
if (byteBuddyExtension.implies(task)) {
task.doLast(new TransformationAction(project, byteBuddyExtension, task));
} else {
project.getLogger().info("Skipping non-specified task {}", task.getName());
}
} |
java | @Override
public ListenableFuture<Table> modifyColumnFamilyAsync(ModifyColumnFamiliesRequest request) {
return createUnaryListener(request, modifyColumnFamilyRpc, request.getName()).getAsyncResult();
} |
python | def table(self, oid, columns=None, column_value_mapping=None, non_repeaters=0,
max_repetitions=20, fetch_all_columns=True):
"""
Get a table of values with the given OID prefix.
"""
snmpsecurity = self._get_snmp_security()
base_oid = oid.strip(".")
if not fe... |
java | public static Node findOrAddChildNode(Document doc, Node parentNode, String childName, String childValue){
Node matchingChild = getChildNode(parentNode, childName, childValue);
return matchingChild != null ? matchingChild : addChildNode(doc, parentNode, childName, childValue);
} |
python | def handle_program_options():
"""Parses the given options passed in at the command line."""
parser = argparse.ArgumentParser(description="Calculate the alpha diversity\
of a set of samples using one or more \
metrics and output a kernal d... |
python | def reason(self, reason):
"""
Sets the reason of this ServicePackageQuotaHistoryItem.
Type of quota usage entry.
:param reason: The reason of this ServicePackageQuotaHistoryItem.
:type: str
"""
if reason is None:
raise ValueError("Invalid value for `r... |
python | def copy_config(project_path, output_dir):
"""Copy current config file to output directory
"""
project_config = os.path.join(project_path, 'config.json')
saved_config = os.path.join(output_dir, 'config.json')
shutil.copy(project_config, saved_config) |
python | def save_formatted_data(self, data):
"""
This will save the formatted data as a repr object (see returns.py)
:param data: dict of the return data
:return: None
"""
self.data = data
self._timestamps['process'] = time.time()
self._stage = STAGE_DONE_DATA_FOR... |
java | private WFieldLayout recursiveFieldLayout(final int curr, final int startAt) {
WFieldLayout innerLayout = new WFieldLayout();
innerLayout.setLabelWidth(20);
if (curr == 0 && startAt == 0) {
innerLayout.setMargin(new Margin(Size.LARGE, null, null, null));
}
innerLayout.setOrdered(true);
if (startAt > 1)... |
java | public static Duration parse(String value) {
/*
* Implementation note: Regular expressions are not used to improve
* performance.
*/
if (value.length() == 0) {
throw parseError(value);
}
int index = 0;
char first = value.charAt(index);
boolean prior = (first == '-');
if (first == '-' || firs... |
python | def people_getPublicPhotos(user_id, per_page='', page=''):
"""Returns list of Photo objects."""
method = 'flickr.people.getPublicPhotos'
data = _doget(method, user_id=user_id, per_page=per_page, page=page)
photos = []
if hasattr(data.rsp.photos, "photo"): # Check if there are photos at all (may be b... |
python | def blob_handler(self, cmd):
"""Process a BlobCommand."""
# These never pass through directly. We buffer them and only
# output them if referenced by an interesting command.
self.blobs[cmd.id] = cmd
self.keep = False |
python | def gate_angle(gate0: Gate, gate1: Gate) -> bk.BKTensor:
"""The Fubini-Study angle between gates"""
return fubini_study_angle(gate0.vec, gate1.vec) |
python | def create_healthcheck(self):
"""Get an instance of Poll services facade."""
return Healthcheck(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) |
python | def send_client_cmd(self, data, cmd=None, via_queue=None):
"""
Send arbitrary cmd and data to client
if queue name passed by "via_queue" parameter,
that queue will be used instead of users private exchange.
Args:
data: dict
cmd: string
via_que... |
java | private void sendUsingConnection(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "sendUsingConnection", new Object[] { destination, message, deliver... |
java | @Override
public AudioFileFormat getAudioFileFormat(InputStream inputStream, long medialength) throws UnsupportedAudioFileException, IOException {
return getAudioFileFormat(inputStream, (int) medialength, AudioSystem.NOT_SPECIFIED);
} |
python | def validate(self):
"""Iterate over all triples in the graph and validate each one
appropriately
"""
log.info("{}\nValidating against {}"
.format("-" * 100, self.schema_def.__class__.__name__))
if not self.schema_def:
raise ValueError("No schema ... |
java | public void destroyThriftConnectionPartition(ThriftConnectionPartition<T> thriftConnectionPartition) {
try {
serverListLock.writeLock().lock();
// 首先移除分区信息
partitions.remove(thriftConnectionPartition);
thriftConnectionPartition.stopThreads();
ThriftServerInfo thriftServerInfo = thriftConnectionPartitio... |
java | public static String hexJBcrypt(String data) {
Objects.requireNonNull(data, Required.DATA.toString());
return BCrypt.hashpw(data, BCrypt.gensalt(Default.JBCRYPT_ROUNDS.toInt()));
} |
java | protected Xpp3Dom createSREConfiguration() throws MojoExecutionException, MojoFailureException {
final Xpp3Dom xmlConfiguration = new Xpp3Dom("configuration"); //$NON-NLS-1$
final Xpp3Dom xmlArchive = new Xpp3Dom("archive"); //$NON-NLS-1$
xmlConfiguration.addChild(xmlArchive);
final String mainClass = getMainC... |
java | public ArrayList<Long> billingAccount_easyHunting_serviceName_screenListConditions_conditions_GET(String billingAccount, String serviceName, OvhOvhPabxDialplanExtensionConditionScreenListTypeEnum screenListType) throws IOException {
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/screenListCondi... |
java | public ThymeleafEngineConfigBuilder<P> setDefaultMessageResolvers(final Set<? extends IMessageResolver> defaultMessageResolvers) {
this.defaultMessageResolvers().clear();
this.defaultMessageResolvers().addAll(defaultMessageResolvers);
return this;
} |
java | public CreateLayerRequest withAttributes(java.util.Map<String, String> attributes) {
setAttributes(attributes);
return this;
} |
java | protected InboxAmp createSystemInbox()
{
String path = getSystemAddress();
StubAmpSystem actorSystem = new StubAmpSystem(path, this);
//ServiceConfig config = ServiceConfig.Builder.create().build();
//ServiceRefAmp serviceRef = service(actorSystem, path, config)... |
java | public <Solution> Collection<Objective<Solution, ?>> createFromGettersWithoutSetters(
Class<Solution> solutionClass) {
Map<String, Method> getters = new HashMap<>();
Map<String, Method> setters = new HashMap<>();
for (Method method : solutionClass.getMethods()) {
if (isGetter(method)) {
String name = me... |
java | public ApplicationInsightsComponentExportConfigurationInner get(String resourceGroupName, String resourceName, String exportId) {
return getWithServiceResponseAsync(resourceGroupName, resourceName, exportId).toBlocking().single().body();
} |
java | public void addObscurer (Obscurer obscurer) {
if (_obscurerList == null) {
_obscurerList = Lists.newArrayList();
}
_obscurerList.add(obscurer);
} |
java | @SuppressWarnings("deprecation")
protected void rollbackRuntime(OperationContext context, final ModelNode operation, final Resource resource) {
rollbackRuntime(context, operation, resource.getModel(), new ArrayList<ServiceController<?>>(0));
} |
python | def _generate_feature_labels(self, X):
'''
Generates string feature labels
'''
Xt, Xc = get_ts_data_parts(X)
ftr_sizes = self._check_features(self.features, Xt[0:3])
f_labels = []
# calculated features
for key in ftr_sizes:
for i in range(ftr... |
python | def _negotiate_SOCKS5(self, *dest_addr):
"""
Negotiates a stream connection through a SOCKS5 server.
"""
CONNECT = b"\x01"
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self,
CONNECT, dest_addr) |
java | public static VaadinForHeroku localServer(final VaadinForHeroku server) {
return server.withHttpPort(VaadinForHeroku.DEFAULT_PORT)
.withProductionMode(false)
.openBrowser(true);
} |
python | def include(*what):
"""
Whitelist *what*.
:param what: What to whitelist.
:type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or att... |
python | def _mk_lcberr(rc, name=None, default=CouchbaseError, docstr="", extrabase=[]):
"""
Create a new error class derived from the appropriate exceptions.
:param int rc: libcouchbase error code to map
:param str name: The name of the new exception
:param class default: Default exception to return if no c... |
python | def get_relationships_for_destination(self, destination_id=None):
"""Gets a ``RelationshipList`` corresponding to the given peer ``Id``.
arg: destination_id (osid.id.Id): a peer ``Id``
return: (osid.relationship.RelationshipList) - the relationships
raise: NullArgument - ``destinati... |
java | private void returnTemperature(Buffer buffer) {
Callback<Integer> callback = getFirstCallback(BeanMessageID.CC_TEMP_READ);
if (callback != null) {
callback.onResult((int) buffer.readByte());
}
} |
java | public static ByteBuf copyFloat(float... values) {
if (values == null || values.length == 0) {
return EMPTY_BUFFER;
}
ByteBuf buffer = buffer(values.length * 4);
for (float v: values) {
buffer.writeFloat(v);
}
return buffer;
} |
python | def _set_zone_name(self, zoneid, name):
"""Private method to override zone name."""
# zone starts with index 0
zoneid -= 1
data = {
'_set_zone_name': 'Set Name',
'select_zone': str(zoneid),
'zone_name': name,
}
self._controller.post(dat... |
java | @Override
public List<CommerceNotificationAttachment> findByUuid_C(String uuid,
long companyId, int start, int end) {
return findByUuid_C(uuid, companyId, start, end, null);
} |
java | public static void projectiveToMetricKnownK( DMatrixRMaj cameraMatrix ,
DMatrixRMaj H , DMatrixRMaj K,
Se3_F64 worldToView )
{
DMatrixRMaj tmp = new DMatrixRMaj(3,4);
CommonOps_DDRM.mult(cameraMatrix,H,tmp);
DMatrixRMaj K_inv = new DMatrixRMaj(3,3);
CommonOps_DDRM.invert(K,K_inv);
... |
python | def long_click(self):
'''
Perform a long click action on the object.
Usage:
d(text="Image").long_click() # long click on the center of the ui object
d(text="Image").long_click.topleft() # long click on the topleft of the ui object
d(text="Image").long_click.bottomright(... |
java | public synchronized void unregister(final OStorage iStorage) {
for (ODatabaseComplex<?> db : new HashSet<ODatabaseComplex<?>>(instances.keySet())) {
if (db != null && db.getStorage() == iStorage) {
db.close();
instances.remove(db);
}
}
} |
python | def get_code_object(x):
"""Helper to handle methods, functions, generators, strings and raw code objects"""
if hasattr(x, '__func__'): # Method
x = x.__func__
if hasattr(x, '__code__'): # Function
x = x.__code__
if hasattr(x, 'gi_code'): # Generator
x = x.gi_code
if isinstan... |
java | public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
byte[] buf;
int length = in.readInt();
if (length >= 0)
{
buf = new byte[length];
in.readFully(buf);
ownerId = new String(buf, Constants.DEFAULT_ENCODING);
... |
python | def format_text(value):
"""
Takes cleaned text and creates HTML-formatted, web-friendly version.
- converts links to images and video to actual media objects.
- Make raw links clickable (and truncated, if necessary).
- Converts smilies and markdown to valid HTML.
_ Bleaches output (again) to cat... |
java | final AbstractItem cmdRemoveIfMatches(final Filter filter, PersistentTransaction transaction) throws SevereMessageStoreException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "cmdRemoveIfMatches", new Object[] { "Item Link: " + this, "Stream Link: " +... |
java | private void verifyReservedBit1(WebSocketFrame frame) throws WebSocketException
{
// If a per-message compression extension has been agreed.
if (mPMCE != null)
{
// Verify the RSV1 bit using the rule described in RFC 7692.
boolean verified = verifyReservedBit1ForPMCE(... |
python | def get_text(nodelist):
"""Return a concatenation of text fields from list of nodes
"""
s = ''
for node in nodelist:
if node.nodeType == Node.TEXT_NODE:
s += node.nodeValue + ', '
if len(s)>0: s = s[:-2]
return s |
python | def find_events(symbols, d_data, market_sym='$SPX', trigger=drop_below, trigger_kwargs={}):
'''Return dataframe of 1's (event happened) and NaNs (no event), 1 column for each symbol'''
df_close = d_data['actual_close']
ts_market = df_close[market_sym]
print "Finding `{0}` events with kwargs={1} for {2... |
python | def install(self, force_install=False):
"""
Installs an app. Blocks until the installation is complete, or raises :exc:`AppInstallError` if it fails.
While this method runs, "progress" events will be emitted regularly with the following signature: ::
(sent_this_interval, sent_total,... |
python | def preprocess_points(points, preprocessor):
"""form points if there is a preprocessor else keep them as such (assumes
that check_points has already been called)"""
try:
points = preprocessor(points)
except Exception as e:
raise PreprocessorError(e)
return points |
python | def _set_maps_get_rules(self, v, load=False):
"""
Setter method for maps_get_rules, mapped from YANG variable /brocade_maps_ext_rpc/maps_get_rules (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_maps_get_rules is considered as a private
method. Backends looking... |
python | def describe_api_stages(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None):
'''
Get all API stages for a given apiID and deploymentID
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.describe_api_stages restApiId deploymentId
'''
try:
con... |
python | def reset_to_default(self):
"""Restore initial values for default color schemes."""
# Checks that this is indeed a default scheme
scheme = self.current_scheme
names = self.get_option('names')
if scheme in names:
for key in syntaxhighlighters.COLOR_SCHEME_KEYS:
... |
python | def final_bearing(self, format='numeric'):
"""Calculate final bearing between locations in segments.
Args:
format (str): Format of the bearing string to return
Returns:
list of list of float: Groups of bearings between points in
segments
"""
... |
python | def v_posts_from_dataframe(df,N=1e4,alpha=0.23,l0=20,sigl=20):
""" names: Prot, e_Prot, R, e_R, vsini, e_vsini
"""
vsini_posts = []
veq_posts = []
if 'ep_R' in df:
for R,dR_p,dR_m,P,dP,v,dv in zip(df['R'],df['ep_R'],df['em_R'],
df['Prot'],df['e_Prot'],
... |
java | public static Diagram parseJson(String json,
Boolean keepGlossaryLink) throws JSONException {
JSONObject modelJSON = new JSONObject(json);
return parseJson(modelJSON,
keepGlossaryLink);
} |
java | public static Point2i convert(Tuple2D<?> tuple) {
if (tuple instanceof Point2i) {
return (Point2i) tuple;
}
return new Point2i(tuple.getX(), tuple.getY());
} |
python | def CreateString(self, s, encoding='utf-8', errors='strict'):
"""CreateString writes a null-terminated byte string as a vector."""
self.assertNotNested()
## @cond FLATBUFFERS_INTERNAL
self.nested = True
## @endcond
if isinstance(s, compat.string_types):
x = ... |
python | def makePartitions(self):
"""Make partitions with gmane help.
"""
class NetworkMeasures:
pass
self.nm=nm=NetworkMeasures()
nm.degrees=self.network.degree()
nm.nodes_= sorted(self.network.nodes(), key=lambda x : nm.degrees[x])
nm.degrees_=[nm.degrees[i]... |
python | def flatten_models(models):
" Create 1d-array containing all disctinct models from ``models``. "
if isinstance(models, MultiFitterModel):
ans = [models]
else:
tasklist = MultiFitter._compile_models(models)
ans = MultiFitter._flatten_models(tasklist)
re... |
java | private void taskHosts(RESTRequest request, RESTResponse response) {
String taskID = RESTHelper.getRequiredParam(request, APIConstants.PARAM_TASK_ID);
String taskHostsJson = getMultipleRoutingHelper().getHosts(taskID);
OutputHelper.writeJsonOutput(response, taskHostsJson);
} |
java | public void deleteRootPathMap() throws WikiApiException {
File rootPathFile = new File(this.rootPathMapFilename + "_" + wiki.getLanguage() + "_" + wiki.getMetaData().getVersion());
rootPathFile.delete();
} |
java | @Override
public <F, G> Choice5<A, B, C, F, G> biMap(Function<? super D, ? extends F> lFn,
Function<? super E, ? extends G> rFn) {
return match(Choice5::a, Choice5::b, Choice5::c, d -> d(lFn.apply(d)), e -> e(rFn.apply(e)));
} |
java | private String normalize(String user) {
if(user != null){
if(user.contains("@"))
user = user.replaceAll("@", "%40");
}
if(logger.isDebugEnabled())
logger.debug("Normalized User = " + user);
return user;
} |
java | public static double[][] getMatrix(final double[][] m1, final int r0, final int r1, final int[] c) {
assert r0 <= r1 : ERR_INVALID_RANGE;
assert r1 <= m1.length : ERR_MATRIX_DIMENSIONS;
final int rowdim = r1 - r0, coldim = c.length;
final double[][] X = new double[rowdim][coldim];
for(int i = r0; i ... |
java | public boolean register(final Object pProvider) {
Iterator<Class<?>> categories = compatibleCategories(pProvider);
boolean registered = false;
while (categories.hasNext()) {
Class<?> category = categories.next();
if (registerImpl(pProvider, category) && !registered) ... |
python | def _remove_files(self, directory, pattern):
'''
Removes all files matching the search path
Arguments:
search_path -- The path you would like to remove, can contain wildcards
Example:
self._remove_files("output/*.html")
'''
for root, dirnames, file_names... |
java | public static DataSource getDataSource(Connection conn) {
if (conn == null) {
return null;
}
String dsName = openConnDsName.get().get(conn);
return getJdbcDataSource(dsName);
} |
python | def command(self, name=None):
"""A decorator to add subcommands.
"""
def decorator(f):
self.add_command(f, name)
return f
return decorator |
java | public void multT(DoubleMatrix bMat, DoubleMatrix cMat, boolean transposeA, boolean transposeB) {
if (!transposeA) {
throw new IllegalArgumentException("Multiplication where this matrix NOT transposed is not implemented.");
}
SparseRowDoubleMatrix.checkMultDimens... |
java | public String findParameterNameByAlias(String nameOrAlias) {
String[] arrays = nameOrAlias.split("\\.");
String prefix = "";
if (arrays.length == 2) {
nameOrAlias = arrays[0];
prefix = "." + arrays[1];
}
if (parameterAlias2NameField.containsKey(nameOrAlias)) {
return parameterAlias2NameField.get(n... |
python | def set_attributes(self, **attributes):
""" Set group of attributes without calling set between attributes regardless of global auto_set.
Set will be called only after all attributes are set based on global auto_set.
:param attributes: dictionary of <attribute, value> to set.
"""
... |
python | def get_slice(self, key, column_parent, predicate, consistency_level):
"""
Get the group of columns contained by column_parent (either a ColumnFamily name or a ColumnFamily/SuperColumn name
pair) specified by the given SlicePredicate. If no matching values are found, an empty list is returned.
Paramete... |
java | public static void resetIfAppVersionChanged(Context context) {
SharedPreferences prefs = getSharedPreferences(context);
int appVersionCode = Integer.MIN_VALUE;
final int previousAppVersionCode = prefs.getInt(PREF_KEY_APP_VERSION_CODE, Integer.MIN_VALUE);
try {
appVersionCode... |
java | @SuppressWarnings("Unchecked class type")
@Override
public <T> T deserialize(@Nullable ByteBuffer data) {
if (data == null) {
return null;
}
Object deserializedObject = columnDataType.deserialize(data, ProtocolVersion.NEWEST_SUPPORTED);
return (T) deserializedObject... |
python | def main(argv=None):
""" Script execution.
The project repo will be cloned to a temporary directory, and the desired
branch, tag, or commit will be checked out. Then, the application will be
installed into a self-contained virtualenv environment.
"""
@contextmanager
def tmpdir():
"... |
java | public static List<CPRuleAssetCategoryRel> findByAssetCategoryId(
long assetCategoryId, int start, int end) {
return getPersistence()
.findByAssetCategoryId(assetCategoryId, start, end);
} |
java | public Money withAmount(double amount, RoundingMode roundingMode) {
return with(money.withAmount(amount).withCurrencyScale(roundingMode));
} |
java | public static Level getLevel(Class cls, Level defLevel) {
Level result;
String levelStr;
result = defLevel;
levelStr = System.getenv(cls.getName() + LOGLEVEL_SUFFIX);
if (levelStr != null) {
switch (levelStr) {
case "ALL":
return Level.ALL;
case "OFF":
return Level.OFF;
case "INFO":... |
java | @Override
public Object js_split(Context cx, Scriptable scope,
String target, Object[] args)
{
// create an empty Array to return;
Scriptable result = cx.newArray(scope, 0);
// Use the second argument as the split limit, if given.
boolean limit... |
python | def _initialise_approximator(self, closest_point=None,
wavelengths_required=None, rescale=True, **kwargs):
"""
Initialise a spectrum interpolator.
"""
if self._initialised and not kwargs.get("force", False):
logger.debug("Ignoring call to re-initialise approximator b... |
java | @Override
public void addSSOCookiesToResponse(Subject subject, HttpServletRequest req, HttpServletResponse resp) {
if (!allowToAddCookieToResponse(req))
return;
addJwtSsoCookiesToResponse(subject, req, resp);
if (!JwtSSOTokenHelper.shouldAlsoIncludeLtpaCookie()) {
r... |
python | def resolve_dict_link(self, dct, array=None):
"""Convenience method for resolving links given a dict object.
Extract link values and pass to the :func:`.resolve` method of this class.
:param dct: (dict) Dictionary with the link data.
:param array: (:class:`.Array`) Optional array resou... |
java | public static Locale resolveLocale(Object locale, String clientId) {
Locale result = null;
if (locale != null) {
if (locale instanceof String) {
result = toLocale((String) locale);
}
else if (locale instanceof java.util.Locale) {
resul... |
java | private String getPercentFormatted(final Integer value)
{
final Integer val = checkQuietly(getName(), value);
return NumberFormat.getPercentInstance().format((double)val / 100);
} |
python | def predict_median(self, X, ancillary_X=None):
"""
Predict the median lifetimes for the individuals. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate nu... |
python | def _is_valid(self, s):
'''Check if a state is valid.'''
# valid states: no more cannibals than missioners on each side,
# and numbers between 0 and 3
return ((s[0] >= s[1] or s[0] == 0)) and \
((3 - s[0]) >= (3 - s[1]) or s[0] == 3) and \
(0 <= s[0] <= 3)... |
java | public void mTokens() throws RecognitionException {
// InternalXtext.g:1:8: ( T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | T__26 | T__27 | T__28 | T__29 | T__30 | T__31 | T__32 | T__33 | T__34 | T__35 | T__36 | T__37 | T__38 | T__39 | T_... |
python | def _match_data_to_parameter(cls, data):
""" find the appropriate parameter for a parameter field """
in_value = data["in"]
for cls in [QueryParameter, HeaderParameter, FormDataParameter,
PathParameter, BodyParameter]:
if in_value == cls.IN:
return cls
return None |
python | def options_formatting(self):
""" Formating options """
group = self.parser.add_argument_group("Format")
group.add_argument(
"--format", dest="formatting", default=None,
help="Custom output format using the {} expansion")
group.add_argument(
"--value",... |
java | @Read()
public Patient getResourceById(@IdParam IdDt theId) {
Patient patient = new Patient();
patient.addIdentifier();
patient.getIdentifier().get(0).setSystem(new UriDt("urn:hapitest:mrns"));
patient.getIdentifier().get(0).setValue("00002");
patient.addName().addFamily("Test");
patient.getName().get(0).a... |
python | def command(self, func):
"""
Decorator to add a command function to the registry.
:param func: command function.
"""
command = Command(func)
self._commands[func.__name__] = command
return func |
python | def deploy_template(access_token, subscription_id, resource_group, deployment_name, template,
parameters):
'''Deploy a template referenced by a JSON string, with parameters as a JSON string.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.