language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static UUID parseId(final String id) throws WarcFormatException {
if (! (id.startsWith(UUID_HEAD) && id.endsWith(UUID_TAIL))) throw new WarcFormatException("'" + id + "' wrong format for " + Name.WARC_RECORD_ID.value);
final int len = id.length();
UUID uuid;
try {
uuid = UUID.fromString(id.substring(U... |
python | def main():
"""
NAME
huji_sample_magic.py
DESCRIPTION
takes tab delimited Hebrew University sample file and converts to MagIC formatted tables
SYNTAX
huji_sample_magic.py [command line options]
OPTIONS
-f FILE: specify input file
-Fsa FILE: specify sample o... |
java | @Override
public Path extract() {
if (sptEntry == null || edgeTo == null)
return this;
if (sptEntry.adjNode != edgeTo.adjNode)
throw new IllegalStateException("Locations of the 'to'- and 'from'-Edge have to be the same. " + toString() + ", fromEntry:" + sptEntry + ", toEntry... |
java | public int count(Entity where) throws SQLException {
Connection conn = null;
try {
conn = this.getConnection();
return runner.count(conn, where);
} catch (SQLException e) {
throw e;
} finally {
this.closeConnection(conn);
}
} |
java | private void verifyEditStreams() throws IOException {
// we check if the shared stream is still available
if (getFSImage().getEditLog().isSharedJournalAvailable()
&& InjectionHandler
.trueCondition(InjectionEvent.AVATARNODE_CHECKEDITSTREAMS)) {
return;
}
// for sanity check if... |
python | def mapper(module, entry_point,
modpath='pkg_resources', globber='root', modname='es6',
fext=JS_EXT, registry=_utils):
"""
General mapper
Loads components from the micro registry.
"""
modname_f = modname if callable(modname) else _utils['modname'][modname]
return {
... |
python | def agent_update(self, agent_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/agents#update-agent"
api_path = "/api/v2/agents/{agent_id}"
api_path = api_path.format(agent_id=agent_id)
return self.call(api_path, method="PUT", data=data, **kwargs) |
python | async def create_post_request(self, method: str, params: Dict = None):
"""Call the given method over POST.
:param method: Name of the method
:param params: dict of parameters
:return: JSON object
"""
if params is None:
params = {}
headers = {"Content-... |
python | def _extract_email(gh):
"""Get user email from github."""
return next(
(x.email for x in gh.emails() if x.verified and x.primary), None) |
java | protected Transformer getTransformer() {
TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory();
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.... |
java | protected void onFaultedResolution(String dependencyKey, Throwable throwable) {
if (toBeResolved == 0) {
throw new RuntimeException("invalid state - " + this.key() + ": The dependency '" + dependencyKey + "' is already reported or there is no such dependencyKey");
}
toBeResolved--;
... |
java | private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) {
if (str == null || suffix == null) {
return str == null && suffix == null;
}
if (suffix.length() > str.length()) {
return false;
}
final int strO... |
java | public CamelRouteActionBuilder create(RouteBuilder routeBuilder) {
CreateCamelRouteAction camelRouteAction = new CreateCamelRouteAction();
try {
if (!routeBuilder.getContext().equals(getCamelContext())) {
routeBuilder.configureRoutes(getCamelContext());
} else {
routeBuilder.configure();
}
cam... |
python | def status(self):
'''returns information about module'''
transfered = self.download - self.prev_download
now = time.time()
interval = now - self.last_status_time
self.last_status_time = now
return("DFLogger: %(state)s Rate(%(interval)ds):%(rate).3fkB/s Block:%(block_cnt)d... |
python | def index(in_bam, config, check_timestamp=True):
"""Index a BAM file, skipping if index present.
Centralizes BAM indexing providing ability to switch indexing approaches.
"""
assert is_bam(in_bam), "%s in not a BAM file" % in_bam
index_file = "%s.bai" % in_bam
alt_index_file = "%s.bai" % os.pat... |
java | public void addMPDestinationChangeListener(MPDestinationChangeListener destinationChangeListener)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "addMPDestinationChangeListener",
new Object[]{destinationChangeListener});
_destinationChangeListeners.add(destin... |
python | def p_function(self, p):
'''function : oneway function_type IDENTIFIER '(' field_seq ')' \
throws annotations '''
p[0] = ast.Function(
name=p[3],
parameters=p[5],
return_type=p[2],
exceptions=p[7],
oneway=p[1],
... |
java | @Override
public boolean write(Writer writer) throws IOException {
writeBlock(writer, EmblPadding.PA_PADDING, accession);
return true;
} |
java | @NotNull
public IntStream scan(@NotNull final IntBinaryOperator accumulator) {
Objects.requireNonNull(accumulator);
return new IntStream(params, new IntScan(iterator, accumulator));
} |
java | PreparedStatement getPreparedStatementForFilter(Connection conn, String baseQuery, CmsUrlNameMappingFilter filter)
throws SQLException {
CmsPair<String, List<I_CmsPreparedStatementParameter>> conditionData = prepareUrlNameMappingConditions(filter);
String whereClause = "";
if (!conditionDat... |
java | public static String encodeBase64URLSafeString(final byte[] binaryData) {
return new String(encodeBase64(binaryData, false, true), StandardCharsets.UTF_8);
} |
java | public static <T extends ImageGray<T>>
T convolve( T integral ,
IntegralKernel kernel,
T output ) {
if( integral instanceof GrayF32) {
return (T)IntegralImageOps.convolve((GrayF32)integral,kernel,(GrayF32)output);
} else if( integral instanceof GrayF64) {
return (T)IntegralImageOps.convolve((GrayF64)... |
java | protected String getTextLineNumber(int rowStartOffset) {
Element root = component.getDocument().getDefaultRootElement();
int index = root.getElementIndex(rowStartOffset);
Element line = root.getElement(index);
if (line.getStartOffset() == rowStartOffset)
return String.valueOf(index + 1);
else... |
java | public DatabaseAccessConfiguration swap(final DataSource dataSource) {
DataSourcePropertyProvider provider = DataSourcePropertyProviderLoader.getProvider(dataSource);
try {
String url = (String) findGetterMethod(dataSource, provider.getURLPropertyName()).invoke(dataSource);
Strin... |
java | public com.squareup.okhttp.Call getMarketsRegionIdOrdersAsync(String orderType, Integer regionId,
String datasource, String ifNoneMatch, Integer page, Integer typeId,
final ApiCallback<List<MarketOrdersResponse>> callback) throws ApiException {
com.squareup.okhttp.Call call = getMarkets... |
java | @Override
public List<CommerceOrderPayment> getCommerceOrderPayments(int start,
int end) {
return commerceOrderPaymentPersistence.findAll(start, end);
} |
java | public TimeZoneFormat setGMTOffsetDigits(String digits) {
if (isFrozen()) {
throw new UnsupportedOperationException("Attempt to modify frozen object");
}
if (digits == null) {
throw new NullPointerException("Null GMT offset digits");
}
String[] digitArray ... |
python | def copy_data(from_client, from_project, from_logstore, from_time, to_time=None,
to_client=None, to_project=None, to_logstore=None,
shard_list=None,
batch_size=None, compress=None, new_topic=None, new_source=None):
"""
copy data from one logstore to another one (could b... |
java | public ApiSuccessResponse getWorkbinContent(String workbinId, GetWorkbinContentData getWorkbinContentData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = getWorkbinContentWithHttpInfo(workbinId, getWorkbinContentData);
return resp.getData();
} |
java | public BytesWritable evaluate(DoubleWritable x, DoubleWritable y, DoubleWritable z, DoubleWritable m) {
if (x == null || y == null || z == null) {
return null;
}
Point stPt = new Point(x.get(), y.get(), z.get());
if (m != null)
stPt.setM(m.get());
return GeometryUtils.geometryToEsriShapeBytesWritable(OG... |
python | def genargs() -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser()
parser.add_argument("spec", help="JSG specification - can be file name, URI or string")
parser.add_argument("-o", "--outfile", help="Output python file - if omitted, python is not... |
python | async def messages(self):
"""Iterate through RMB posts from newest to oldest.
Returns
-------
an asynchronous generator that yields :class:`Post`
"""
# Messages may be posted on the RMB while the generator is running.
oldest_id_seen = float('inf')
for off... |
python | def _resolve_intervals_2dplot(val, func_name):
"""
Helper function to replace the values of a coordinate array containing
pd.Interval with their mid-points or - for pcolormesh - boundaries which
increases length by 1.
"""
label_extra = ''
if _valid_other_type(val, [pd.Interval]):
if ... |
java | public Map<String, ResourceList> getAllResourcesAsMap() {
if (pathToWhitelistedResourcesCached == null) {
final Map<String, ResourceList> pathToWhitelistedResourceListMap = new HashMap<>();
for (final Resource res : getAllResources()) {
ResourceList resList = pathToWhitel... |
python | def hide_object(self, key, hide=True):
'''hide an object on the map by key'''
self.object_queue.put(SlipHideObject(key, hide)) |
python | def _EvaluateExpressions(self, frame):
"""Evaluates watched expressions into a string form.
If expression evaluation fails, the error message is used as evaluated
expression string.
Args:
frame: Python stack frame of breakpoint hit.
Returns:
Array of strings where each string correspo... |
java | public
static
String getFacilityString(int syslogFacility) {
switch(syslogFacility) {
case LOG_KERN: return "kern";
case LOG_USER: return "user";
case LOG_MAIL: return "mail";
case LOG_DAEMON: return "daemon";
case LOG_AUTH: return "auth";
case LOG_SYSLOG: retur... |
python | def var(
self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs
):
"""Computes variance across the DataFrame.
Args:
axis (int): The axis to take the variance on.
skipna (bool): True to skip NA values, false otherwise.
ddof (... |
java | private Map<String, String> executeRequestWithBody(HttpClientService csHttpClient, HttpClientInputs httpClientInputs, String body) {
httpClientInputs.setBody(body);
Map<String, String> requestResponse = csHttpClient.execute(httpClientInputs);
if (UNAUTHORIZED_STATUS_CODE.equals(requestResponse.g... |
python | def _parse_output_for_errors(data, command, **kwargs):
'''
Helper method to parse command output for error information
'''
if re.search('% Invalid', data):
raise CommandExecutionError({
'rejected_input': command,
'message': 'CLI excution error',
'code': '400',... |
python | def encode_request(uuid, address, interrupt):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(uuid, address, interrupt))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(uuid)
Addr... |
java | @Override
public final void makeOtherEntries(final Map<String, Object> pAddParam,
final PrepaymentFrom pEntity, final IRequestData pRequestData,
final boolean pIsNew) throws Exception {
// nothing
} |
java | private void processAssignments() throws SQLException
{
List<Row> permanentAssignments = getRows("select * from permanent_schedul_allocation inner join perm_resource_skill on permanent_schedul_allocation.allocatiop_of = perm_resource_skill.perm_resource_skillid where permanent_schedul_allocation.projid=? order... |
java | public static UrlMappingsHolder lookupUrlMappings(ServletContext servletContext) {
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
return (UrlMappingsHolder)wac.getBean(UrlMappingsHolder.BEAN_ID);
} |
python | def get_response(self):
'''
Returns response according submitted the data and method.
'''
self.process_commmon()
self.process_data()
urlencoded_data = urllib.urlencode(self.data)
if self.METHOD == POST:
req = urllib2.Request(self.URL, urlencoded_data)
... |
python | def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, bn=True, stoch=False):
"""
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
... |
java | public void matches(int expectedMatches, double seconds) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
if (expectedMatches > 0) {
elementPresent(seconds);
}
while (element.get().matchCount() != expectedMatches && System.currentTim... |
java | public static Geometry drapePolygon(Polygon p, Geometry triangles, STRtree sTRtree) {
GeometryFactory factory = p.getFactory();
//Split the triangles in lines to perform all intersections
Geometry triangleLines = LinearComponentExtracter.getGeometry(triangles, true);
Polygon spli... |
java | public synchronized void shutdownDbmsPools() {
//force shutdown
//runnable
datasourceCleaner.shutdown();
datasourceCleaner = null;
//shell for the runnable
cleanerThread.interrupt();//stop the thread
cleanerThread = null;
if (dbmsPoolTable == null) {
... |
java | public WindowFuture offer(K key, R request, long offerTimeoutMillis, long expireTimeoutMillis, boolean callerWaitingHint) throws DuplicateKeyException, OfferTimeoutException, PendingOfferAbortedException, InterruptedException {
if (offerTimeoutMillis < 0) {
throw new IllegalArgumentException("offerT... |
java | public String selectColor(List<String> colors) {
String tr="transparent";
for (String c: colors) {
if (!(c.equals(tr))) return c;
}
return tr;
} |
python | def get_action_arguments(self, service_name, action_name):
"""
Returns a list of tuples with all known arguments for the given
service- and action-name combination. The tuples contain the
argument-name, direction and data_type.
"""
return self.services[service_name].actio... |
python | def getuvalue(self):
"""
.. _getuvalue:
Get the unsigned value of the Integer, truncate it and handle Overflows.
"""
bitset = [0] * self.width
zero = [1] * self.width
for shift in range(self.width):
bitset[shift] = (self._value & (1 << shift)) >> shift
if(self._sign):
bitset = bitsetxor(zero, bit... |
java | @Override
public Certificates getAvailableCertificates(Integer pageNo, Integer perPage)
throws DigitalOceanException, RequestUnsuccessfulException {
validatePageNo(pageNo);
return (Certificates) perform(new ApiRequest(ApiAction.AVAILABLE_CERTIFICATES, pageNo, perPage))
.getData();
} |
python | def learn(self, state, action, reward, next_state, done):
"""
Update replay memory and learn from a batch of random experiences sampled
from the replay buffer
:return: optimization loss if enough experiences are available, None otherwise
"""
self.steps += 1
self.replay.append((state, action,... |
python | def os_info():
"""Returns os data.
"""
return {
'uname': dict(platform.uname()._asdict()),
'path': os.environ.get('PATH', '').split(':'),
'shell': os.environ.get('SHELL', '/bin/sh'),
} |
java | private boolean checkEsTin(final String ptin) {
final char[] checkArray = {'T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J',
'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E'};
final char checkSum = ptin.charAt(8);
final char calculatedCheckSum;
final int sum;
if (StringU... |
java | @Override
public Set<String> getVariables() {
Set<String> variables = new HashSet<>();
if(lhs.getVariable() != null) variables.add(lhs.getVariable());
if(rhs.getVariable() != null) variables.add(rhs.getVariable());
return variables;
} |
python | def add_layer_to_canvas(layer, name):
"""Helper method to add layer to QGIS.
:param layer: The layer.
:type layer: QgsMapLayer
:param name: Layer name.
:type name: str
"""
if qgis_version() >= 21800:
layer.setName(name)
else:
layer.setLayerName(name)
QgsProject.in... |
python | def sc_cuts_alg(self, viewer, event, msg=True):
"""Adjust cuts algorithm interactively.
"""
if self.cancut:
direction = self.get_direction(event.direction)
self._cycle_cuts_alg(viewer, msg, direction=direction)
return True |
python | def removeActor(self, a):
"""Remove ``vtkActor`` or actor index from current renderer."""
if not self.initializedPlotter:
save_int = self.interactive
self.show(interactive=0)
self.interactive = save_int
return
if self.renderer:
self.ren... |
python | def pave_project(self):
"""
Usage:
containment pave_project
"""
settings.project_customization.path.mkdir()
settings.project_customization.entrypoint.write_text(
self.context.entrypoint_text
)
settings.project_customization.runfile.write_text... |
python | def arcsin_sqrt(biom_tbl):
"""
Applies the arcsine square root transform to the
given BIOM-format table
"""
arcsint = lambda data, id_, md: np.arcsin(np.sqrt(data))
tbl_relabd = relative_abd(biom_tbl)
tbl_asin = tbl_relabd.transform(arcsint, inplace=False)
return tbl_asin |
java | protected void update(long readBytes) throws IOException {
if (progressListener.isAborted()) {
throw new IOException("Reading Cancelled by ProgressListener");
}
this.bytesRead += readBytes;
int step = (int)(bytesRead / stepSize);
if(step > lastStep) {
lastStep = step;
progressListener.updateProgress(... |
python | def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
"""
Returns all the model fields that are being mapped to by fields
on the serializer class.
Returned as a dict of 'model field name' -> 'model field'.
Used internally by `get_uniqueness_field_options`.
... |
java | public int interpolateARGB(final double xNormalized, final double yNormalized){
double xF = xNormalized * (getWidth()-1);
double yF = yNormalized * (getHeight()-1);
int x = (int)xF;
int y = (int)yF;
int c00 = getValue(x, y);
int c01 = getValue(x, (y+1 < getHeight() ? y+1:y));
int c10 = get... |
java | public static void closeChainedTasks(List<ChainedDriver<?, ?>> tasks, AbstractInvokable parent) throws Exception {
for (int i = 0; i < tasks.size(); i++) {
final ChainedDriver<?, ?> task = tasks.get(i);
task.closeTask();
if (LOG.isDebugEnabled()) {
LOG.debug(constructLogString("Finished task code", t... |
python | def render_tooltip(self, tooltip, obj):
"""Render the tooltip for this column for an object
"""
if self.tooltip_attr:
val = getattr(obj, self.tooltip_attr)
elif self.tooltip_value:
val = self.tooltip_value
else:
return False
setter = ge... |
python | def cmdSubstitute(self, cmd, count):
""" s
"""
cursor = self._qpart.textCursor()
for _ in range(count):
cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
if cursor.selectedText():
_globalClipboard.value = cursor.selectedText()
cur... |
python | def generator_samples(tmp_dir, pb_cst):
"""Generator for the dataset samples.
If not present, download and extract the dataset.
Args:
tmp_dir: path to the directory where to download the dataset.
pb_cst: CodingPbConstants object defining paths
Yields:
A CodingPbInfo object containing the next cha... |
java | public Command receiveCommand(String queueName, long timeout) {
try {
Message message = receiveMessage(queueName, timeout);
if(message == null){
return null;
}else{
Command command;
if(binaryMode){
command =... |
python | def insert_arguments_into_match_query(compilation_result, arguments):
"""Insert the arguments into the compiled MATCH query to form a complete query.
Args:
compilation_result: a CompilationResult object derived from the GraphQL compiler
arguments: dict, mapping argument name to its value, for e... |
java | public void setConfigurationProperty(final String name, final Object value)
{
if (XIncProcConfiguration.ALLOW_FIXUP_BASE_URIS.equals(name))
{
if (value instanceof Boolean)
{
this.baseUrisFixup = (Boolean) value;
}
else if (value instanc... |
python | def _Close(self):
"""Closes the file-like object."""
if self._database_object:
self._database_object.Close()
self._blob = None
self._current_offset = 0
self._size = 0
self._table_name = None |
java | @Override public int read() throws IOException
{
int c;
if (m_searching)
{
int index = 0;
c = -1;
while (m_searching)
{
c = m_stream.read();
if (c == -1)
{
m_searchFailed = true;
throw new IOExcep... |
java | public static double[][] transpose(double[][] A) {
int m = A.length;
int n = A[0].length;
double[][] matrix = new double[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[j][i] = A[i][j];
}
}
return matrix;... |
java | private static int binarySearch(int[] array, int toIndex, int key) {
int low = 0;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = array[mid];
if (midVal < key) {
low = mid + 1;
} else if (m... |
java | public final void exclusiveOrExpression() throws RecognitionException {
int exclusiveOrExpression_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 114) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1154:5: ( andExpression ( '^' an... |
java | private void setFileSizesAfterRestart(boolean coldStart,
long minimumPermanentStoreSize, long maximumPermanentStoreSize, boolean isPermanentStoreSizeUnlimited,
long minimumTemporaryStoreSize, long maximumTemporaryStoreSize, boolean isTe... |
python | def write_gexf(docgraph, output_file):
"""
takes a document graph, converts it into GEXF format and writes it to
a file.
"""
dg_copy = deepcopy(docgraph)
remove_root_metadata(dg_copy)
layerset2str(dg_copy)
attriblist2str(dg_copy)
nx_write_gexf(dg_copy, output_file) |
python | def get_jac(self):
""" Derives the jacobian from ``self.exprs`` and ``self.dep``. """
if self._jac is True:
if self.sparse is True:
self._jac, self._colptrs, self._rowvals = self.be.sparse_jacobian_csc(self.exprs, self.dep)
elif self.band is not None: # Banded
... |
java | public void setGenericKeywords(java.util.Collection<String> genericKeywords) {
if (genericKeywords == null) {
this.genericKeywords = null;
return;
}
this.genericKeywords = new java.util.ArrayList<String>(genericKeywords);
} |
python | def replace_label(self, oldLabel, newLabel):
""" Replaces old label with a new one
"""
if oldLabel == newLabel:
return
tmp = re.compile(r'\b' + oldLabel + r'\b')
last = 0
l = len(newLabel)
while True:
match = tmp.search(self.asm[last:])
... |
python | def handle(self, key, value):
'''
Processes a vaild stats request
@param key: The key that matched the request
@param value: The value associated with the key
'''
# break down key
elements = key.split(":")
stats = elements[1]
appid = elements[2]
... |
java | private void validateInput() {
// Check for null values first.
if (url == null) {
throw new NullPointerException("URL should not be null");
}
if (!url.getProtocol().matches("^https?$")) {
throw new IllegalArgumentException(
"URL protocol should... |
python | def embed(self, x, nfeatures=2):
"""Embed all given tensors into an nfeatures-dim space. """
list_split = 0
if isinstance(x, list):
list_split = len(x)
x = tf.concat(x, 0)
# pre-process MNIST dataflow data
x = tf.expand_dims(x, 3)
x = x * 2 - 1
... |
java | public PagedList<DscNodeReportInner> listByNodeNext(final String nextPageLink) {
ServiceResponse<Page<DscNodeReportInner>> response = listByNodeNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<DscNodeReportInner>(response.body()) {
@Override
public Pa... |
java | public boolean limit() {
//get connection
Object connection = getConnection();
Object result = limitRequest(connection);
if (FAIL_CODE != (Long) result) {
return true;
} else {
return false;
}
} |
java | public String getLabel() {
String label = getProperty(labelProperty);
label = label == null ? node.getLabel() : label;
if (label == null) {
label = getDefaultInstanceName();
setProperty(labelProperty, label);
}
return label;
... |
java | @Override
public synchronized void close() {
if (currentStatus != StreamStatus.CLOSED) {
// Only flush the print stream: don't close it.
currentPrintStream.flush();
if (!LoggingFileUtils.tryToClose(currentPrintStream)) {
LoggingFileUtils.tryToClose(curren... |
python | def transformer_aux_base():
"""Set of hyperparameters."""
hparams = transformer.transformer_base()
hparams.shared_embedding_and_softmax_weights = False
hparams.add_hparam("shift_values", "1,2,3,4")
return hparams |
python | def read_config(configpath=None, specpath=None, checks=None,
report_extra=False):
"""
get a (validated) config object for given config file path.
:param configpath: path to config-file or a list of lines as its content
:type configpath: str or list(str)
:param specpath: path to spec... |
java | private void init() {
setTitle("Validation Framework Test");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Create content pane
JPanel contentPane = new JPanel(new MigLayout("fill, wrap 1"));
setContentPane(contentPane);
// Tabbed pane
JTabbedPane t... |
java | @Handler
public void onStart(Start event) {
synchronized (this) {
if (runner != null && !runner.isInterrupted()) {
return;
}
runner = new Thread(this, Components.simpleObjectName(this));
runner.start();
}
} |
java | @Override
public final SessionDestroyedListener addingService(ServiceReference<SessionDestroyedListener> serviceReference) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Listener [" + serviceReference + "] has been added.");
}
final SessionDestroyedListener listener = context.ge... |
python | def must_contain(tag_name, tag_content, container_tag_name):
"""
Generate function, which checks if given element contains `tag_name` with
string content `tag_content` and also another tag named
`container_tag_name`.
This function can be used as parameter for .find() method in HTMLElement.
"""
... |
java | public static int ofSetBits32_1(int i) {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = ((i + (i >>> 4)) & 0x0F0F0F0F);
return (i * (0x01010101)) >>> 24;
} |
java | @Override
public List<CommerceCountry> findByG_S_A(long groupId,
boolean shippingAllowed, boolean active) {
return findByG_S_A(groupId, shippingAllowed, active, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null);
} |
python | def get_line_color(self, increment=1):
"""
Returns the current color, then increments the color by what's specified
"""
i = self.line_colors_index
self.line_colors_index += increment
if self.line_colors_index >= len(self.line_colors):
self.line_colors_index ... |
java | public void loadProfile(Object key)
{
if (!isEnablePerThreadChanges())
{
throw new MetadataException("Can not load profile with disabled per thread mode");
}
DescriptorRepository rep = (DescriptorRepository) metadataProfiles.get(key);
if (rep == null)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.