language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Override
public void afterPropertiesSet() throws Exception {
greenMail = new GreenMail(createServerSetup());
if (null != users) {
for (String user : users) {
int posColon = user.indexOf(':');
int posAt = user.indexOf('@');
String login = u... |
python | def regret(self):
'''
Calculate expected regret, where expected regret is
maximum optimal reward - sum of collected rewards, i.e.
expected regret = T*max_k(mean_k) - sum_(t=1-->T) (reward_t)
Returns
-------
float
'''
return (sum(self.pulls)*np.m... |
python | def _download_datasets():
"""Utility to download datasets into package source"""
def filepath(*args):
return abspath(join(dirname(__file__), '..', 'vega_datasets', *args))
dataset_listing = {}
for name in DATASETS_TO_DOWNLOAD:
data = Dataset(name)
url = data.url
filename ... |
java | @Override
public Path relativize(final Path other) {
if (other == null) {
throw new IllegalArgumentException("other path must be specified");
}
if (!(other instanceof ShrinkWrapPath)) {
throw new IllegalArgumentException("Can only relativize paths of type "
... |
java | public static <T> File writeLines(Collection<T> list, File file, String charset) throws IORuntimeException {
return writeLines(list, file, charset, false);
} |
python | def save(self, target, storage=None, **options):
"""https://github.com/frictionlessdata/tableschema-py#schema
"""
# Save (tabulator)
if storage is None:
with Stream(self.iter, headers=self.__schema.headers) as stream:
stream.save(target, **options)
... |
python | def UpdateSNMPObjs():
""" Function that does the actual data update. """
global threadingString
LogMsg("Beginning data update.")
data = ""
# Obtain the data by calling an external command. We don't use
# subprocess.check_output() here for compatibility with Python versions
# older than 2.7.
LogMsg("Calling e... |
java | public <T> T parse(String input, Class<T> targetType) {
if (input == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("input"));
}
if (targetType == null) {
throw new NullPointerException(makeNullArgumentErrorMsg("targetType"));
}
@Suppress... |
python | def activate_debug():
"""Activate debug logging on console
This function is useful when playing with python-textops through a python console.
It is not recommended to use this function in a real application : use standard logging
functions instead.
"""
ch = logging.StreamHandler()
ch.setLev... |
python | def makedbthreads(self):
"""
Setup and create threads for class
"""
# Find all the target folders in the analysis and add them to the targetfolders set
for sample in self.metadata:
if sample[self.analysistype].combinedtargets != 'NA':
self.targetfolder... |
java | public static int[] intArrayCopyOf(CollectionNumber coll) {
int[] data = new int[coll.size()];
IteratorNumber iter = coll.iterator();
int index = 0;
while (iter.hasNext()) {
data[index] = iter.nextInt();
index++;
}
return data;
} |
python | def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.pop("stream", six.StringIO())
self.selected_fields = options.pop("fields", None)
self.use_natural_foreign_keys = options.pop('use_natural_foreign_... |
java | public void setJobGroup (final String jobGroup)
{
if (jobGroup != null && jobGroup.trim ().length () == 0)
throw new IllegalArgumentException ("Group name cannot be null or empty.");
if (jobGroup == null)
m_sJobGroup = IScheduler.DEFAULT_GROUP;
else
m_sJobGroup = jobGroup;
} |
java | public static SSLSocket upgrade(SSLSocketFactory sslSocketFactory,
HostnameVerifier hostnameVerifier, Socket socket, String host, int port,
ConnectionSpec spec) throws IOException {
Preconditions.checkNotNull(sslSocketFactory, "sslSocketFactory");
Preconditions.checkNotNull(socket, "socket");
Pr... |
python | def get_max_sum_ind(self, indices_list, distances, i, m):
'''Get the indices that belong to the maximum distance in `distances`
Arguments
---------
indices_list : list
list of tuples
distances : numpy.ndarray
size M
i : int
m : int
... |
python | def is_generator(self, node):
"""Traverse the tree below node looking for 'yield [expr]'."""
results = {}
if self.yield_expr.match(node, results):
return True
for child in node.children:
if child.type not in (syms.funcdef, syms.classdef):
if self.i... |
python | def AddSourceRestriction(self,cidr):
"""Add and commit a single source IP restriction policy.
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
.AddSourceRestriction(cidr="132.200.20.1/32").WaitUntilComplete()
0
"""
self.source_restrictions.append(SourceRestriction(self,cidr))
return(self.Up... |
python | def last_room_temp(self):
"""Return avg room temperature for last session."""
try:
rmtemps = self.intervals[1]['timeseries']['tempRoomC']
except KeyError:
return None
tmp = 0
num_temps = len(rmtemps)
if num_temps == 0:
return None
... |
python | def _link_to_img(self):
"""
Generates a link to the user's Gravatar.
>>> Gravatar('gridaphobe@gmail.com')._link_to_img()
'http://www.gravatar.com/avatar/16b87da510d278999c892cdbdd55c1b6?s=80&r=g'
"""
# make sure options are valid
if self.rating.lower() no... |
java | @Nullable
public static CascadingStyleSheet readFromReader (@Nonnull final IHasReader aRP,
@Nonnull final ECSSVersion eVersion,
@Nullable final ICSSParseErrorHandler aCustomErrorHandler,
... |
java | @Override
public Result call(Transactional configuration, RequestContext context) throws Exception {
propagation.onEntry(configuration.propagation(),
configuration.timeout(),
context.route().getControllerMethod().getName());
try {
Result result = context.p... |
python | def add_node(self, node, weight=None):
"""
Adds a single node to the Graph.
Parameters
----------
node: str, int, or any hashable python object.
The node to add to the graph.
weight: int, float
The weight of the node.
Examples
--... |
java | public void doBenchmarkFile(String filename)
{
try
{
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(filename), "UTF-8"));)
{
Map<String, Integer> queryRun = new HashMap<>();
Map<String, Integer> queryId = new HashMap<>();
... |
java | @Pure
public static Point2d L1_L3(double x, double y) {
final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y,
LAMBERT_1_N,
LAMBERT_1_C,
LAMBERT_1_XS,
LAMBERT_1_YS);
return NTFLambdaPhi_NTFLambert(
ntfLambdaPhi.getX(), ntfLambdaPhi.getY(),
LAMBERT_3_N,
LAMBERT_3_C,
LAMBERT_3_XS,... |
java | public static UnicodeUtil getInstance() {
if (instance == null) {
synchronized (UnicodeUtilImpl.class) {
if (instance == null) {
new UnicodeUtilImpl().initialize();
}
}
}
return instance;
} |
python | def addMPCandHumanWealth(self,solution):
'''
Take a solution and add human wealth and the bounding MPCs to it.
Parameters
----------
solution : ConsumerSolution
The solution to this period's consumption-saving problem.
Returns:
----------
sol... |
java | public static synchronized Properties getConfig() {
if (config == null) {
try {
String rpcConfig = "config/rpc-config.properties";
InputStream ins = SofaConfigs.class.getClassLoader().getResourceAsStream(rpcConfig);
if (ins == null) {
... |
java | public java.util.List<String> getTopicNames() {
if (topicNames == null) {
topicNames = new com.amazonaws.internal.SdkInternalList<String>();
}
return topicNames;
} |
java | @Override
public Connection getConnection(ConnectionRequestContext requestContext) throws SQLException {
int remainingAttempts = retryAttempts;
try {
do {
try {
return getConnectionFactory().getConnection(requestContext);
} catch... |
java | public ListDeploymentTargetsRequest withTargetFilters(java.util.Map<String, java.util.List<String>> targetFilters) {
setTargetFilters(targetFilters);
return this;
} |
python | def get_fixed_block(self, keys=[], unbuffered=False):
"""Get the decoded "fixed block" of settings and min/max data.
A subset of the entire block can be selected by keys."""
if unbuffered or not self._fixed_block:
self._fixed_block = self._read_fixed_block()
format = self.fi... |
java | public static xen_health_monitor[] get_filtered(nitro_service service, String filter) throws Exception
{
xen_health_monitor obj = new xen_health_monitor();
options option = new options();
option.set_filter(filter);
xen_health_monitor[] response = (xen_health_monitor[]) obj.getfiltered(service, option);
... |
python | def subnet_create(request, network_id, **kwargs):
"""Create a subnet on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param cidr: (optional) subnet IP address range
:param ip_version: (optional) IP version (4 or 6)
:param gateway_ip: ... |
python | def registerApp(self,
itemId,
appType,
redirect_uris=None):
"""
The register app operation registers an app item with the portal.
App registration results in an APPID and APPSECRET (also known as
client_id and client_secret (in ... |
python | def get_realms_and_credentials(self, uri, http_method='GET', body=None,
headers=None):
"""Fetch realms and credentials for the presented request token.
:param uri: The full URI of the token request.
:param http_method: A valid HTTP verb, i.e. GET, POST, PUT, H... |
python | def import_classes(names, src, dst):
"""Import classes in package from their implementation modules."""
for name in names:
module = importlib.import_module('pygsp.' + src + '.' + name.lower())
setattr(sys.modules['pygsp.' + dst], name, getattr(module, name)) |
java | public WorkbookReader turnToSheet(int index) {
checkState(!isClosed, WORKBOOK_CLOSED);
sheet = workbook.getSheetAt(index);
setHeader();
return this;
} |
python | def wait(self):
"""Wait on a task to finish and stop it when it has finished.
Raises:
RuntimeError: If the task hasn't been started or has already been
stopped.
Returns:
The ``return_values`` of the task.
"""
if self._status is not TaskSt... |
python | def get_schema(self, *args, **kwargs):
"""
Return the schema instance that should be used for validating and
deserializing input, and for serializing output.
"""
klass = self.get_schema_class()
# kwargs context value take precedence.
kwargs['context'] = dict(
... |
python | def _load_config(self):
"Load and parse config file, pass options to livestreamer"
config = SafeConfigParser()
config_file = os.path.join(self.config_path, 'settings.ini')
config.read(config_file)
for option, type in list(AVAILABLE_OPTIONS.items()):
if confi... |
python | def get_distribution_id(vm_):
r'''
Returns the distribution ID for a VM
vm\_
The VM to get the distribution ID for
'''
distributions = _query('avail', 'distributions')['DATA']
vm_image_name = config.get_cloud_config_value('image', vm_, __opts__)
distro_id = ''
for distro in di... |
java | public static String hostAndPortToUrlString(String host, int port) throws UnknownHostException {
return ipAddressAndPortToUrlString(InetAddress.getByName(host), port);
} |
java | public void finest(String msg) {
if (Level.FINEST.intValue() < levelValue) {
return;
}
log(Level.FINEST, msg);
} |
python | def make_bezier(n):
""" Bezier curves:
http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization
"""
try:
return beziers[n]
except KeyError:
combinations = pascal_row(n - 1)
result = []
for t in tsequence:
tpowers = (t ** i for i in range(n))
... |
java | public static void registerLog(LogController controller) throws UnsupportedLocaleException {
// When the first LogController registers, do one-time initialization
forceInit(Library.class);
String locale = Library.getLocale();
// Set the locale on the controller
if (controller.... |
python | def load_file(self, afile=None, verbose=False):
"""
Load a new network from a network file type (e.g. SIF, XGMML, etc.).
Use network import file to load networks from Excel or csv files. This
command will create a new network collection if no current network collection
is selecte... |
python | def close(self, notes=None):
'''Save all changes and close this issue'''
self.set_status(self._redmine.ISSUE_STATUS_ID_CLOSED, notes=notes) |
java | public static OnJqueryFunction on(final Attr events, final Attr selector, JavaScriptInlineFunction handler) {
return on(events, selector, Attr.nullValue(), handler);
} |
python | def resample(df, rule, time_index, groupby=None, aggregation='mean'):
"""pd.DataFrame.resample adapter.
Call the `df.resample` method on the given time_index
and afterwards call the indicated aggregation.
Optionally group the dataframe by the indicated columns before
performing the resampling.
... |
java | public static final BigDecimal printUnits(Number value)
{
return (value == null ? BIGDECIMAL_ONE : new BigDecimal(value.doubleValue() / 100));
} |
java | @Deprecated
public static <B extends Bean> LightMetaBean<B> of(
Class<B> beanType,
MethodHandles.Lookup lookup,
Object... defaultValues) {
// the field name order is undefined (not source code order)
// this is fundamentally broken as they are being matched again... |
java | public static Optional<File> resolvePluginDependency(Dependency d, List<RemoteRepository> pluginRepos,
ArtifactResolver resolver, RepositorySystemSession repoSystemSession) {
Artifact a = new DefaultArtifact(d.getGroupId(), d.getArtifactId(), d.getClassifier(), d.getType(), d.getVersion());
ArtifactReques... |
python | def set_step(self, value, block_events=False):
"""
Sets the step of the number box.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value.
"""
if block_events: self.block_events()
self._widget.setSingleStep(va... |
java | public synchronized boolean sendData(byte[] bytes) {
if (bytes != null && bytes.length > 0 && !closed.get()) {
try {
if (listeners == null) {
buffer.addLast(bytes);
} else if (listeners.length == 1) {
listeners[0].onPacket(bytes, null, false);
} else {
for (PacketListener listene... |
java | public static Guid deserialize(String str) throws IOException {
if (str.length() != 2 * GUID_LENGTH) {
throw new IOException("String is not an encoded guid.");
}
try {
return new Guid(Hex.decodeHex(str.toCharArray()), true);
} catch (DecoderException de) {
throw new IOException(de);
... |
python | def get_fun(fun):
'''
Return the most recent jobs that have executed the named function
'''
conn, mdb = _get_conn(ret=None)
ret = {}
rdata = mdb.saltReturns.find_one({'fun': fun}, {'_id': 0})
if rdata:
ret = rdata
return ret |
java | @Override
public void merge(JMSDestinationDefinition annotation, Class<?> instanceClass, Member member) throws InjectionException {
if (member != null) {
// JMSDestinationDefinition is a class-level annotation only.
throw new IllegalArgumentException(member.toString());
}
... |
java | public static long[] asLongArray(Collection collection) {
long[] result = new long[collection.size()];
int i = 0;
for (Object c : collection) {
result[i++] = asLong(c);
}
return result;
} |
java | public OutputStream createOutOutputStream(OutputStream os) {
return new InstrumentedOutputStream(collector(), Direction.Out, os, null);
} |
python | def add_download_filename(response: HttpResponse, filename: str) -> None:
"""
Adds a ``Content-Disposition`` header to the HTTP response to say that
there is an attachment with the specified filename.
"""
# https://docs.djangoproject.com/en/1.9/howto/outputting-csv/
add_http_headers_for_attachme... |
python | def _load_stream(self):
"""
Return the content body of the request, as a stream.
"""
meta = self._request.META
try:
content_length = int(
meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0))
)
except (ValueError, TypeError... |
java | public static MozuUrl upsertPackageFileUrl(String applicationKey, String filepath, String lastModifiedTime, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/platform/developer/packages/{applicationKey}/files/{filepath}?lastModifiedTime={lastModifiedTime}&responseFields={responseFields}");
... |
java | public static void vertical(Kernel1D_S32 kernel,
InterleavedU8 input, InterleavedI16 output , ImageBorder_IL_S32<InterleavedU8> border ) {
InputSanityCheck.checkSameShapeB(input, output);
boolean processed = BOverrideConvolveImage.invokeNativeVertical(kernel,input,output,border);
if( !processed ) {
... |
python | def getPositionByType(self, tagSet):
"""Return field position by its ASN.1 type.
Parameters
----------
tagSet: :class:`~pysnmp.type.tag.TagSet`
ASN.1 tag set distinguishing one ASN.1 type from others.
Returns
-------
: :py:class:`int`
ASN... |
java | public static <T> T checkNotNull(T reference) {
return com.google.common.base.Preconditions.checkNotNull(reference);
} |
python | def _select_exposures_requiring_dophot_extraction(
self,
batch=10):
"""* select exposures requiring dophot extraction*
**Key Arguments:**
- ``batch`` -- the batch size of dophot file to process
**Return:**
- ``expnames`` -- the names of the expso... |
java | protected void addFacetPart(CmsSolrQuery query) {
query.set("facet", "true");
String excludes = "";
if (m_config.getIgnoreAllFacetFilters()
|| (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {
excludes = "{!ex=" + m_config.getIgnoreTags() + "}";
... |
python | def load_schema(schema_path):
'''
Returns a schema loaded from the file at `schema_path`.
Will recursively load referenced schemas assuming they can be found in
files in the same directory and named with the convention
`<type_name>.avsc`.
'''
with open(schema_path) as fd:
schema = j... |
java | protected void populateBean(final T resultBean, final String[] nameMapping, final CsvBindingErrors bindingErrors) {
// map each column to its associated field on the bean
for( int i = 0; i < nameMapping.length; i++ ) {
final String fieldName = nameMapping[i];
final ... |
java | @BetaApi
public final Operation deleteSnapshot(ProjectGlobalSnapshotName snapshot) {
DeleteSnapshotHttpRequest request =
DeleteSnapshotHttpRequest.newBuilder()
.setSnapshot(snapshot == null ? null : snapshot.toString())
.build();
return deleteSnapshot(request);
} |
java | public static Object invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException {
try {
return method.invoke(target, args);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
}
catch (InvocationTargetException ex) {
if (ex.getTargetException() instanceof SQLE... |
python | def full_protocol_list(self):
"""
:return: all protocols including not shown ones
:rtype: list of ProtocolAnalyzer
"""
result = []
for group in self.groups:
result.extend(group.all_protocols)
return result |
java | @ManyToOne(targetEntity = org.openprovenance.prov.sql.QualifiedName.class, cascade = {
CascadeType.ALL
})
@JoinColumn(name = "GENERALENTITY_MENTIONOF_PK")
public org.openprovenance.prov.model.QualifiedName getGeneralEntity() {
return generalEntity;
} |
java | @Override
public synchronized Map<NodeId, NodeInfo> getAllNodeInfos(NodeId bigger, int maxCount) throws ItemStateException {
ResultSet rs = null;
try {
String sql = bundleSelectAllBundlesSQL;
NodeId lowId = null;
Object[] keys = new Object[0];
if (bigg... |
java | public Observable<Page<CloudTask>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders>, Page<CloudTask>>() {
@Override
public Page<CloudTask> call(... |
python | def swipe_left(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe left.'''
self.swipe(0.8*width, 0.5*length, 0.2*width, 0.5*length) |
java | public static AreaF area(final AreaSizeF size)
{
Objects.requireNonNull(size, "Size");
return AreaF.of(0.0f, size.sizeX(), 0.0f, size.sizeY());
} |
java | public List<Term> seg(char[] text)
{
assert text != null;
if (HanLP.Config.Normalization)
{
CharTable.normalization(text);
}
return segSentence(text);
} |
python | def create_unary_node(self, operator, child, param=None, schema=None):
"""
Return a Unary Node whose type depends on the specified operator.
:param schema:
:param child:
:param operator: A relational algebra operator (see constants.py)
:param param: A list of parameters ... |
java | public void marshall(TransactWriteItem transactWriteItem, ProtocolMarshaller protocolMarshaller) {
if (transactWriteItem == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(transactWriteItem.getConditi... |
java | public final void formalParameters() throws RecognitionException {
int formalParameters_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 56) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:566:5: ( '(' ( formalParameterDecls )? ')' ... |
java | public static InstanceType constructFromDescription(String description) {
final Matcher m = INSTANCE_TYPE_PATTERN.matcher(description);
if (!m.matches()) {
LOG.error("Cannot extract instance type from string " + description);
return null;
}
final String identifier = m.group(1);
final int numComputeUni... |
python | def check_checkbox(self, value):
"""Check the checkbox with label (recommended), name or id."""
check_box = find_field(world.browser, 'checkbox', value)
assert check_box, "Cannot find checkbox '{}'.".format(value)
if not check_box.is_selected():
check_box.click() |
java | @BetaApi
public final Operation moveInstanceProject(
ProjectName project, InstanceMoveRequest instanceMoveRequestResource) {
MoveInstanceProjectHttpRequest request =
MoveInstanceProjectHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.setInst... |
java | private void copySchemaConceptLabelsToKeyspaceCache(TransactionOLTP tx) {
copyToCache(tx.getMetaConcept());
copyToCache(tx.getMetaRole());
copyToCache(tx.getMetaRule());
} |
java | public void compareTable(ExpectedTableDefinition expectedContent, WebElement table) throws Throwable {
try {
SenBotContext.getSeleniumDriver().manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
List<List<String>> expectedRows = expectedContent.getExpected().raw();
... |
java | public static RoundedBitmapDrawable fromBitmapDrawable(
Resources res,
BitmapDrawable bitmapDrawable) {
return new RoundedBitmapDrawable(res, bitmapDrawable.getBitmap(), bitmapDrawable.getPaint());
} |
java | @Override
public final void init(Driver d, Properties properties) {
this.driver = d;
this.driver.getEventManager().register(EventManager.EVENT_FRAGMENT_PRE, this);
this.driver.getEventManager().register(EventManager.EVENT_FRAGMENT_POST, this);
loginUrl = CAS_LOGIN_URL.getValue(proper... |
java | @XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "includeAllowableActions", scope = GetObjectRelationships.class)
public JAXBElement<Boolean> createGetObjectRelationshipsIncludeAllowableActions(
Boolean value) {
return new JAXBElement<Boolean>(
_GetObjectOfLatestV... |
python | def stop(self, accountID, **kwargs):
"""
Shortcut to create a Stop Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a StopOrderRequest
Returns:
v20.response.Response containing the results from submitting
... |
java | @VisibleForTesting
String obfuscateConfidentialData(final CharSequence confidentialSequence, @Nullable final CharSequence unmasked) {
final int maskedLength = unmasked == null ? confidentialSequence.length() : confidentialSequence.length() - unmasked.length();
return new String(new char[maskedLength... |
python | async def _send_scan_event(self, device):
"""Send a scan event from a device."""
conn_string = str(device.iotile_id)
info = {
'connection_string': conn_string,
'uuid': device.iotile_id,
'signal_strength': 100,
'validity_period': self.ExpirationTim... |
python | def get_dataset_end_date(self, date_format=None):
# type: (Optional[str]) -> Optional[str]
"""Get dataset date as string in specified format. For range returns start date.
If no format is supplied, an ISO 8601 string is returned.
Args:
date_format (Optional[str]): Date forma... |
java | public boolean isJavaInheritance()
{
if(javaInheritance == null)
{
javaInheritance = getClassDescriptor().getSuperClassDescriptor().getClassOfObject()
.isAssignableFrom(getClassDescriptor().getClassOfObject()) ? Boolean.TRUE : Boolean.FALSE;
}
r... |
python | def add_to_gitignore(line: str):
"""
Adds a line to the .gitignore file of the repo
Args:
line: line to add
"""
if not line.endswith('\n'):
line = f'{line}\n'
if GIT_IGNORE.exists():
if line in GIT_IGNORE.read_text(encoding='utf8'):
return
previous_co... |
python | def _create_font_face_buttons(self):
"""Creates font face buttons"""
font_face_buttons = [
(wx.FONTFLAG_BOLD, "OnBold", "FormatTextBold", _("Bold")),
(wx.FONTFLAG_ITALIC, "OnItalics", "FormatTextItalic",
_("Italics")),
(wx.FONTFLAG_UNDERLINED, "OnUnderli... |
python | def _parse_vrf(self, config):
"""Parses config file for the OSPF vrf name
Args:
config(str): Running configuration
Returns:
dict: key: ospf_vrf (str)
"""
match = re.search(r'^router ospf \d+ vrf (\w+)', config)
if match:
r... |
python | def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(set(iterable))
combs = chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
res = set(frozenset(x) for x in combs)
# res = map(frozenset, combs)
return res |
python | def merge(data,skip=50,fraction=1.0):
"""Merge one every 'skip' clouds into a single emcee population,
using the later 'fraction' of the run."""
w,s,d = data.chains.shape
start = int((1.0 - fraction) * s)
total = int((s - start) / skip)
return data.chains[:,start::skip,:].reshape(... |
java | private void processAJPHeader() {
int oldState = this.state;
if (anyAreSet(oldState, FLAG_START)) {
PooledByteBuffer[] byteBuffers = null;
//merge the cookies into the header map
Connectors.flattenCookies(exchange);
PooledByteBuffer pooled = pool.alloca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.