code
stringlengths 0
30.8k
| source
stringclasses 6
values | language
stringclasses 9
values | __index_level_0__
int64 0
100k
|
---|---|---|---|
public JobflowInfo compileJobflow(Class<? extends FlowDescription> description) throws IOException {
JobFlowDriver driver = JobFlowDriver.analyze(description);
assertThat(driver.getDiagnostics().toString(), driver.hasError(), is(false));
List<File> classPath = buildClassPath(description);
JobflowInfo info = DirectFlowCompiler.compile(
driver.getJobFlowClass().getGraph(),
"testing",
driver.getJobFlowClass().getConfig().name(),
"com.example",
hadoopDriver.toPath(path("runtime", "jobflow")),
new File("target/localwork", testName),
classPath,
getClass().getClassLoader(),
options);
return info;
} | function | java | 500 |
public void StartRendering(IVideoSource source)
{
_source = source as RemoteVideoTrack;
Debug.Assert(_source != null, "NativeVideoRender currently only supports RemoteVideoTack");
switch (source.FrameEncoding)
{
case VideoEncoding.I420A:
_i420aFrameQueue = new VideoFrameQueue<I420AVideoFrameStorage>(2);
_source.I420AVideoFrameReady += I420AVideoFrameReady;
break;
case VideoEncoding.Argb32:
break;
}
} | function | c# | 501 |
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async Task<CacheClientProxy> GetClientAsync(ITransportClient transport)
{
var rpcClient = new RPCClient(transport);
var proxy = await rpcClient.CreateProxyAsync<CacheClientProxy>().ConfigureAwait(false);
Core.Status.AttachChild(rpcClient, proxy);
return proxy;
} | function | c# | 502 |
public static void addManifestClassPath(JarFile moduleFile, URI moduleBaseUri, Collection<String> manifestClasspath, JarFileFactory factory) throws DeploymentException {
List<DeploymentException> problems = new ArrayList<DeploymentException>();
ClassPathUtils.addManifestClassPath(moduleFile, moduleBaseUri, manifestClasspath, factory, problems);
if (!problems.isEmpty()) {
if (problems.size() == 1) {
throw problems.get(0);
}
throw new DeploymentException("Determining complete manifest classpath unsuccessful: ", problems);
}
} | function | java | 503 |
func (r *Reconciler) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx).WithName("status")
logger.Info("reconciling UserAccountStatus")
var syncIndex string
userAcc := &toolchainv1alpha1.UserAccount{}
err := r.Client.Get(context.TODO(), request.NamespacedName, userAcc)
if err != nil {
if errors.IsNotFound(err) {
logger.Info("Updating MUR after UserAccount deletion")
syncIndex = "deleted"
} else {
return reconcile.Result{}, err
}
} else {
if userAcc.DeletionTimestamp != nil {
logger.Info("Updating MUR during UserAccount deletion")
syncIndex = "0"
} else {
logger.Info("Updating MUR")
syncIndex = userAcc.ResourceVersion
}
}
mur, err := r.updateMasterUserRecord(request.Name, syncIndex)
if err != nil {
if mur != nil {
logger.Error(err, "unable to update the master user record", "MasterUserRecord", mur, "UserAccount", userAcc)
} else {
logger.Error(err, "unable to get the master user record for the UserAccount", "UserAccount", userAcc)
}
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
} | function | go | 504 |
unsafe fn populate_pt_entries() -> Result<(), &'static str> {
for (l2_nr, l2_entry) in TABLES.lvl2.iter_mut().enumerate() {
*l2_entry = TABLES.lvl3[l2_nr].base_addr_usize().into();
for (l3_nr, l3_entry) in TABLES.lvl3[l2_nr].iter_mut().enumerate() {
let virt_addr = (l2_nr << FIVETWELVE_MIB_SHIFT) + (l3_nr << SIXTYFOUR_KIB_SHIFT);
let (output_addr, attribute_fields) =
bsp::memory::mmu::virt_mem_layout().get_virt_addr_properties(virt_addr)?;
*l3_entry = PageDescriptor::new(output_addr, attribute_fields);
}
}
Ok(())
} | function | rust | 505 |
bool httpd::init ()
{
try {
if (!is_open ())
open (SOCK_STREAM);
inaddr me (INADDR_ANY, port_num);
bind (me);
}
catch (erc& x)
{
x.deactivate ();
TRACE ("httpd::init Error %x", (int)x);
return false;
}
return tcpserver::init ();
} | function | c++ | 506 |
public class GenericKeyValueCache<TK, T> : IDisposable
{
private readonly Dictionary<TK, T> _cache = new Dictionary<TK, T>();
private readonly Dictionary<TK, Timer> _timers = new Dictionary<TK, Timer>();
private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();
private bool _disposed;
public void AddOrUpdate(TK key, T cacheObject, int cacheTimeout, bool restartTimerIfExists = false)
{
if (_disposed) return;
if (cacheTimeout != Timeout.Infinite && cacheTimeout < 1)
{
throw new ArgumentOutOfRangeException(nameof(cacheTimeout));
}
_locker.EnterWriteLock();
try
{
CheckTimer(key, cacheTimeout, restartTimerIfExists);
if (!_cache.ContainsKey(key))
_cache.Add(key, cacheObject);
else
_cache[key] = cacheObject;
}
finally { _locker.ExitWriteLock(); }
}
public void AddOrUpdate(TK key, T cacheObject)
{
AddOrUpdate(key, cacheObject, Timeout.Infinite);
}
public T this[TK key] => Get(key);
public T Get(TK key)
{
if (_disposed) return default(T);
_locker.EnterReadLock();
try
{
T rv;
return (_cache.TryGetValue(key, out rv) ? rv : default(T));
}
finally { _locker.ExitReadLock(); }
}
public bool TryGet(TK key, out T value)
{
if (_disposed)
{
value = default(T);
return false;
}
_locker.EnterReadLock();
try
{
return _cache.TryGetValue(key, out value);
}
finally { _locker.ExitReadLock(); }
}
public void Remove(Predicate<TK> keyPattern)
{
if (_disposed) return;
_locker.EnterWriteLock();
try
{
var removers = (from k in _cache.Keys
where keyPattern(k)
select k).ToList();
foreach (var workKey in removers)
{
try { _timers[workKey].Dispose(); }
catch
{
}
_timers.Remove(workKey);
_cache.Remove(workKey);
}
}
finally { _locker.ExitWriteLock(); }
}
public void Remove(TK key)
{
if (_disposed) return;
_locker.EnterWriteLock();
try
{
if (!_cache.ContainsKey(key))
{
return;
}
try { _timers[key].Dispose(); }
catch
{
}
_timers.Remove(key);
_cache.Remove(key);
}
finally { _locker.ExitWriteLock(); }
}
public void Clear()
{
_locker.EnterWriteLock();
try
{
try
{
foreach (var t in _timers.Values)
{
t.Dispose();
}
}
catch
{
}
_timers.Clear();
_cache.Clear();
}
finally { _locker.ExitWriteLock(); }
}
public bool Exists(TK key)
{
if (_disposed) return false;
_locker.EnterReadLock();
try
{
return _cache.ContainsKey(key);
}
finally { _locker.ExitReadLock(); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void CheckTimer(TK key, int cacheTimeout, bool restartTimerIfExists)
{
Timer timer;
if (_timers.TryGetValue(key, out timer))
{
if (restartTimerIfExists)
{
timer.Change(
(cacheTimeout == Timeout.Infinite ? Timeout.Infinite : cacheTimeout * 1000),
Timeout.Infinite);
}
}
else
_timers.Add(
key,
new Timer(
RemoveByTimer,
key,
(cacheTimeout == Timeout.Infinite ? Timeout.Infinite : cacheTimeout * 1000),
Timeout.Infinite));
}
private void RemoveByTimer(object state)
{
Remove((TK)state);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (!disposing)
{
return;
}
Clear();
_locker.Dispose();
}
} | class | c# | 507 |
public class VisualisationClock {
public enum State {
PLAYING, PAUSED, STOPPED, ENDED
};
public static final int DEFAULT_MILLIS_PER_TIMESTEP = 1000;
public static final int MAX_MILLIS_PER_TIMESTEP = 5000;
public static final int TICKS_PER_SECOND = 60;
private long length;
private volatile int millisPerTimestep;
protected volatile int ticksPerTimestep;
protected volatile long timestep;
protected volatile int tick;
protected volatile State state;
private final EventListenerList listeners;
private Timer timestepTimer;
private ClockTickTask incTickTask;
protected volatile int changeCheck;
/**
* @param length
* length of the simulation in timesteps.
*/
public VisualisationClock(long length) {
if (length < 1)
throw new IllegalArgumentException(
"Created VisualisationClock with invalid length.");
this.length = length;
listeners = new EventListenerList();
timestep = 0;
tick = 0;
state = State.STOPPED;
changeCheck = 0;
setMillisPerTimestep(DEFAULT_MILLIS_PER_TIMESTEP);
}
/**
* Sets the rate at which the clock changes. The number of ticks per
* timestep adapts to ensure smooth transition of messages in visualisation.
*
* @param millis
* the number of milliseconds taken for the visualisation to
* advance one timestep of simulation. If negative, the clock
* will travel backwards through time.
*
* @throws IllegalArgumentException
* if <code>millis</code> is less than 1.
*/
public void setMillisPerTimestep(int millis) {
synchronized (this) {
if (millis == 0)
throw new IllegalArgumentException(
"Attempted to set clock to advance at 0 milliseconds per timestep.");
changeCheck++;
final boolean playing = state == State.PLAYING;
if (playing) {
pause();
}
millisPerTimestep = millis;
ticksPerTimestep = TICKS_PER_SECOND * Math.abs(millis) / 1000;
if (ticksPerTimestep == 0)
ticksPerTimestep++;
tick = (millis < 0 && timestep > 0) ? ticksPerTimestep - 1 : 0;
if (playing)
play();
}
}
/**
* @return The time taken for the clock to advance one timestep whilst
* playing.
*/
public int getMillisPerTimestep() {
return millisPerTimestep;
}
/**
* Resumes the advancement of the clock at the rate returned by
* <code>getMillisPerTimestep()</code>.
*/
public void play() {
synchronized (this) {
if (state == State.PLAYING)
throw new IllegalStateException(
"Called play whilst already playing.");
final boolean atStart = millisPerTimestep < 0 && timestep == 0
&& tick == 0;
final boolean atEnd = millisPerTimestep > 0
&& ticksPerTimestep == length;
if (atStart || atEnd)
return;
if (state == State.ENDED && millisPerTimestep > 0) {
stop();
}
ClockSpeedEvent event = new ClockSpeedEvent(this, ticksPerTimestep);
for (ClockListener listener : listeners
.getListeners(ClockListener.class)) {
listener.onSpeedChange(event);
}
setState(State.PLAYING);
final int timeBetweenTicks = 1000 / TICKS_PER_SECOND;
timestepTimer = new Timer();
incTickTask = new ClockTickTask(this);
if (timestep == 0 && tick == 0) {
setTimestep(0);
broadcastTick();
} else if (timestep == length) {
setTimestep(length - 1);
broadcastTick();
}
timestepTimer.scheduleAtFixedRate(incTickTask, 0, timeBetweenTicks);
}
}
/**
* Pauses the advancement of the clock.
*
* @return the timestep that the clock has paused at.
*/
public long pause() {
synchronized (this) {
if (state != State.PLAYING)
throw new IllegalStateException("Paused clock outside of play.");
timestepTimer.cancel();
setState(State.PAUSED);
return timestep;
}
}
/**
* @return The timestep of the visualisation,
*/
public long getTimestep() {
return timestep;
}
/**
* @return The tick of the visualisation.
*/
public int getTick() {
return tick;
}
private void setTimestep(long timestep) {
synchronized (this) {
this.timestep = timestep;
ClockTimestepEvent event = new ClockTimestepEvent(this, timestep);
for (ClockListener listener : listeners
.getListeners(ClockListener.class)) {
listener.onTimestepEvent(event);
}
}
}
/**
* @return The timestep that the clock will run to.
*/
public long getLength() {
return length;
}
public State getState() {
return state;
}
public void addListener(ClockListener listener) {
listeners.add(ClockListener.class, listener);
}
private void setState(State state) {
synchronized (this) {
this.state = state;
ClockStateEvent stateEvent = new ClockStateEvent(this, state);
for (ClockListener listener : listeners
.getListeners(ClockListener.class)) {
listener.onStateChange(stateEvent);
}
}
}
protected void nextTick() {
synchronized (this) {
final boolean forwards = millisPerTimestep > 0;
if (timestep == length)
return;
if (forwards) {
if (++tick % ticksPerTimestep == 0) {
tick = 0;
setTimestep(timestep + 1);
}
} else {
if (--tick < 0) {
tick = ticksPerTimestep - 1;
setTimestep(timestep - 1);
}
}
broadcastTick();
if (timestep == length) {
timestepTimer.cancel();
setState(State.ENDED);
} else if (timestep == 0 && tick == 0 && !forwards) {
timestepTimer.cancel();
setState(State.STOPPED);
}
}
}
/**
* Allows the visualisation clock to jump the timestep it is at to a
* specific step. This resets the tick of the clock to zero.
*
* @param jumpStep
* the step to jump to.
*/
public synchronized void jumpToTimestep(long jumpStep) {
synchronized (this) {
changeCheck++;
final boolean playing = state == State.PLAYING;
if (playing) {
pause();
}
setTimestep(jumpStep);
tick = (millisPerTimestep < 0 && state != State.STOPPED) ? ticksPerTimestep - 1
: 0;
broadcastTick();
if (playing && state != State.STOPPED)
play();
}
}
private void broadcastTick() {
ClockTickEvent tickEvent = new ClockTickEvent(this, tick);
for (ClockListener listener : listeners
.getListeners(ClockListener.class)) {
listener.onTickEvent(tickEvent);
}
}
/**
* Stops execution of the clock and resets it to the start of the
* simulation.
*/
public void stop() {
synchronized (this) {
setState(State.STOPPED);
jumpToTimestep(0);
}
}
public int getTicksPerTimestep() {
synchronized (this) {
return ticksPerTimestep;
}
}
public synchronized void setLength(long visLength) {
length = visLength;
}
} | class | java | 508 |
public Drawable loadIcon(ApplicationSuggestion suggestion) {
try {
InputStream is = mContext.getContentResolver()
.openInputStream(suggestion.getThumbailUri());
return Drawable.createFromStream(is, null);
} catch (FileNotFoundException e) {
return null;
}
} | function | java | 509 |
public TxRecord readTxRecord(ByteBufferBackedDataInput in) throws IOException, IgniteCheckedException {
byte txState = in.readByte();
TransactionState state = TransactionState.fromOrdinal(txState);
GridCacheVersion nearXidVer = RecordV1Serializer.readVersion(in, true);
GridCacheVersion writeVer = RecordV1Serializer.readVersion(in, true);
int participatingNodesSize = in.readInt();
Map<Object, Collection<Object>> participatingNodes = new HashMap<>(2 * participatingNodesSize);
for (int i = 0; i < participatingNodesSize; i++) {
Object primaryNode = readConsistentId(in);
int backupNodesSize = in.readInt();
Collection<Object> backupNodes = new ArrayList<>(backupNodesSize);
for (int j = 0; j < backupNodesSize; j++) {
Object backupNode = readConsistentId(in);
backupNodes.add(backupNode);
}
participatingNodes.put(primaryNode, backupNodes);
}
boolean hasRemote = in.readByte() == 1;
Object primaryNode = null;
if (hasRemote)
primaryNode = readConsistentId(in);
long timestamp = in.readLong();
return new TxRecord(state, nearXidVer, writeVer, participatingNodes, primaryNode, timestamp);
} | function | java | 510 |
public void SetVertexMetadatum(Point2D vertex, string key, string value)
{
if (null == vertex)
throw new ArgumentNullException("vertex");
FailIfReserved(key);
var vertexIndex = IndexOf(vertex, "vertex");
structure.SetVertexMetadatum(vertexIndex, key, value);
} | function | c# | 511 |
Boolean HTTPConnection::closeConnectionOnTimeout(struct timeval* timeNow)
{
if (_acceptPending)
{
PEGASUS_ASSERT(!_isClient());
if ((timeNow->tv_sec - _acceptPendingStartTime.tv_sec >
PEGASUS_SSL_ACCEPT_TIMEOUT_SECONDS) &&
(timeNow->tv_sec > _acceptPendingStartTime.tv_sec))
{
PEG_TRACE_CSTRING(TRC_DISCARDED_DATA, Tracer::LEVEL4,
"HTTPConnection: close acceptPending connection for timeout");
_closeConnection();
return true;
}
}
else if (getIdleConnectionTimeout())
{
if (timeNow->tv_sec < _idleStartTime.tv_sec)
{
Time::gettimeofday(timeNow);
}
else if ((Uint32)(timeNow->tv_sec - _idleStartTime.tv_sec) >
getIdleConnectionTimeout())
{
PEG_TRACE((TRC_DISCARDED_DATA, Tracer::LEVEL3,
"HTTPConnection: close idle connection for timeout "
"of %d seconds\n", getIdleConnectionTimeout()));
_closeConnection();
return true;
}
}
return false;
} | function | c++ | 512 |
public
class JToolsetComparePanel
extends JPanel
{
/*----------------------------------------------------------------------------------------*/
/* C O N S T R U C T O R */
/*----------------------------------------------------------------------------------------*/
/**
* Construct a new panel.
*
* @param os
* The operating system type.
*/
protected
JToolsetComparePanel
(
OsType os
)
{
/* initialize fields */
{
pOsType = os;
}
/* create dialog body components */
{
setLayout(new BorderLayout());
JPanel mpanel = new JPanel();
mpanel.setName("MainPanel");
mpanel.setLayout(new BoxLayout(mpanel, BoxLayout.X_AXIS));
mpanel.add(Box.createRigidArea(new Dimension(20, 0)));
{
Box vbox = new Box(BoxLayout.Y_AXIS);
vbox.add(Box.createRigidArea(new Dimension(0, 20)));
vbox.add(UIFactory.createPanelLabel(pOsType + " Environment:"));
vbox.add(Box.createRigidArea(new Dimension(0, 4)));
{
Box hbox = new Box(BoxLayout.X_AXIS);
{
JPanel panel = new JPanel();
pTitlePanel = panel;
panel.setName("TitlePanel");
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Dimension size = new Dimension(sTSize, 80);
panel.setMinimumSize(size);
panel.setPreferredSize(size);
panel.setMaximumSize(new Dimension(sTSize, Integer.MAX_VALUE));
hbox.add(panel);
}
{
JPanel panel = new JPanel();
pLeftValuePanel = panel;
panel.setName("ValuePanel");
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
hbox.add(panel);
}
{
JPanel panel = new JPanel();
pRightValuePanel = panel;
panel.setName("ValuePanel");
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
hbox.add(panel);
}
JScrollPane scroll =
UIFactory.createVertScrollPane(hbox, sTSize+sVSize*2+52, 80);
vbox.add(scroll);
}
vbox.add(Box.createRigidArea(new Dimension(0, 20)));
mpanel.add(vbox);
}
mpanel.add(Box.createRigidArea(new Dimension(20, 0)));
add(mpanel);
}
}
/*----------------------------------------------------------------------------------------*/
/* U S E R I N T E R F A C E */
/*----------------------------------------------------------------------------------------*/
/**
* Update the toolsets being displayed in the left and right portions of the panel.
*
* @param left
* The versions of the toolset.
*
* @param right
* The versions of the toolset.
*/
public void
updateToolsets
(
Toolset left,
Toolset right
)
{
pTitlePanel.removeAll();
pLeftValuePanel.removeAll();
pRightValuePanel.removeAll();
TreeMap<String,String> lenv = null;
if(left != null)
lenv = left.getEnvironment();
else
lenv = new TreeMap<String,String>();
TreeMap<String,String> renv = null;
if(right != null)
renv = right.getEnvironment();
else
renv = new TreeMap<String,String>();
TreeSet<String> keys = new TreeSet<String>();
keys.addAll(lenv.keySet());
keys.addAll(renv.keySet());
for(String key : keys) {
String lvalue = lenv.get(key);
String rvalue = renv.get(key);
Color fg = Color.white;
if(((lvalue == null) && (rvalue != null)) ||
((lvalue != null) && (rvalue == null)))
fg = Color.yellow;
else if((lvalue != null) && !lvalue.equals(rvalue))
fg = Color.cyan;
{
JLabel label = UIFactory.createLabel(key + ":", sTSize, JLabel.RIGHT);
label.setForeground(fg);
pTitlePanel.add(label);
pTitlePanel.add(Box.createRigidArea(new Dimension(0, 3)));
}
{
String text = (lvalue != null) ? lvalue : "-";
JTextField field =
UIFactory.createTextField
(text, sVSize, (lvalue != null) ? JLabel.LEFT : JLabel.CENTER);
field.setForeground(fg);
field.setEnabled(lvalue != null);
pLeftValuePanel.add(field);
pLeftValuePanel.add(Box.createRigidArea(new Dimension(0, 3)));
}
{
String text = (rvalue != null) ? rvalue : "-";
JTextField field =
UIFactory.createTextField
(text, sVSize, (rvalue != null) ? JLabel.LEFT : JLabel.CENTER);
field.setForeground(fg);
field.setEnabled(rvalue != null);
pRightValuePanel.add(field);
pRightValuePanel.add(Box.createRigidArea(new Dimension(0, 3)));
}
}
pTitlePanel.add(Box.createVerticalGlue());
pLeftValuePanel.add(Box.createVerticalGlue());
pRightValuePanel.add(Box.createVerticalGlue());
validate();
repaint();
}
/*----------------------------------------------------------------------------------------*/
/* S T A T I C I N T E R N A L S */
/*----------------------------------------------------------------------------------------*/
private static final long serialVersionUID = -8476905541457079505L;
private static final int sTSize = 200;
private static final int sVSize = 300;
/*----------------------------------------------------------------------------------------*/
/* I N T E R N A L S */
/*----------------------------------------------------------------------------------------*/
/**
* The target operating system type.
*/
private OsType pOsType;
/**
* The environmental variable title and value container panels.
*/
private JPanel pTitlePanel;
private JPanel pLeftValuePanel;
private JPanel pRightValuePanel;
} | class | java | 513 |
void Cmssw_LoadHits_End(EventOfHits &eoh)
{
for (auto &&l : eoh.m_layers_of_hits)
{
l.EndRegistrationOfHits(false);
}
} | function | c++ | 514 |
public void testPropsOfDataGroupRef( ) throws Exception
{
openDesign( FILE_NAME );
TableHandle table2 = (TableHandle) designHandle
.findElement( "myTable2" );
TableGroupHandle group2 = (TableGroupHandle) table2.getGroups( )
.get( 0 );
assertEquals( "row[\"CUSTOMERNAME\"]", group2.getKeyExpr( ) );
assertEquals( "group1", group2.getName( ) );
assertEquals( "group1", group2.getDisplayLabel( ) );
Iterator iter1 = group2.filtersIterator( );
FilterConditionHandle filter = (FilterConditionHandle) iter1.next( );
assertEquals( "table 1 filter expression", filter.getExpr( ) );
assertEquals( DesignChoiceConstants.FILTER_OPERATOR_LT, filter
.getOperator( ) );
iter1 = group2.sortsIterator( );
SortKeyHandle sort = (SortKeyHandle) iter1.next( );
assertEquals( "table 1 name", sort.getKey( ) );
assertEquals( DesignChoiceConstants.SORT_DIRECTION_ASC, sort
.getDirection( ) );
TableHandle table1 = (TableHandle) designHandle
.findElement( "myTable1" );
TableGroupHandle group1 = (TableGroupHandle) table1.getGroups( )
.get( 0 );
group1.setKeyExpr( "the new expression" );
assertEquals( "the new expression", group2.getKeyExpr( ) );
group1.setName( "newGroup1" );
assertEquals( "newGroup1", group2.getDisplayLabel( ) );
ListHandle list1 = (ListHandle) designHandle.findElement( "myList1" );
ListGroupHandle listGroup = (ListGroupHandle) list1.getGroups( )
.get( 0 );
assertEquals( "the new expression", listGroup.getKeyExpr( ) );
assertEquals( "newGroup1", listGroup.getName( ) );
assertEquals( "newGroup1", listGroup.getDisplayLabel( ) );
iter1 = listGroup.filtersIterator( );
filter = (FilterConditionHandle) iter1.next( );
assertEquals( "table 1 filter expression", filter.getExpr( ) );
assertEquals( DesignChoiceConstants.FILTER_OPERATOR_LT, filter
.getOperator( ) );
} | function | java | 515 |
public boolean next() {
if(nextToken > tokenIndex){
tokenIndex = nextToken;
} else {
tokenIndex++;
nextToken = tokenIndex;
}
final boolean hasNext;
if(chunk != null){
for(;tokenIndex > chunk.getEnd() && chunks.hasNext();chunk = chunks.next());
if(tokenIndex <= chunk.getEnd()){
if(chunk.getStart() > tokenIndex) {
tokenIndex = chunk.getStart();
}
if(chunk.getStart() > consumedIndex){
consumedIndex = chunk.getStart()-1;
}
hasNext = true;
} else {
hasNext = initNextSentence();
}
} else {
if(sentence == null){
hasNext = initNextSentence();
} else if(tokenIndex >= sentence.getTokens().size()){
hasNext = initNextSentence();
} else {
hasNext = true;
}
}
if(hasNext){
token = sentence.getTokens().get(tokenIndex);
}
return hasNext;
} | function | java | 516 |
def flip_normals(self):
if not self.is_all_triangles:
raise NotAllTrianglesError('Can only flip normals on an all triangle mesh.')
if _vtk.VTK9:
f = self._connectivity_array
f[::3], f[2::3] = f[2::3], f[::3].copy()
else:
f = self.faces
f[1::4], f[3::4] = f[3::4], f[1::4].copy()
self.faces[:] = f | function | python | 517 |
def _gatherpostkey(self):
self._login_preload(dl.LOGIN_AES_INI_PATH)
response = self.wca_url_request_handler(target_url=dl.LOGIN_POSTKEY_URL,
post_data=None,
timeout=30,
target_page_word='post-key',
logpath=None)
web_src = response.read().decode("UTF-8", "ignore")
post_pattern = re.compile(dl.POSTKEY_REGEX, re.S)
postkey = re.findall(post_pattern, web_src)
if not postkey:
dl.LT_PRINT('regex parse post key failed')
return dl.PUB_E_REGEX_FAIL
post_orderdict = OrderedDict()
post_orderdict['captcha'] = ""
post_orderdict['g_recaptcha_response'] = ""
post_orderdict['password'] = self.passwd
post_orderdict['pixiv_id'] = self.username
post_orderdict['post_key'] = postkey[0]
post_orderdict['source'] = "accounts"
post_orderdict['ref'] = ""
post_orderdict['return_to'] = dl.HTTPS_HOST_URL
post_orderdict['recaptcha_v3_token'] = ""
self.postway_data = urllib.parse.urlencode(post_orderdict).encode("UTF-8")
return dl.PUB_E_OK | function | python | 518 |
public class NamedColor
{
#region Constructors
public NamedColor()
{
ColorCode = 0xFF000000;
ColorName = this.ColorCode.ToHex();
}
public NamedColor(uint colorCode)
{
ColorCode = colorCode;
ColorName = ColorCode.ToHex();
}
public NamedColor(Color color)
{
ColorCode = color.ToArgb();
ColorName = ColorCode.ToHex();
}
public NamedColor(SolidColorBrush brush)
{
ColorCode = brush.Color.ToArgb();
ColorName = ColorCode.ToHex();
}
#endregion
#region Properties
public SolidColorBrush BrushOpacity(double opacity)
{
return new SolidColorBrush(this.ColorOpacity(opacity));
}
public Color ColorOpacity(double opacity)
{
var alpha = (byte)(opacity * 255);
var color = this.Color;
color.A = alpha;
return color;
}
public SolidColorBrush Brush { get { return this.ToBrush(); } }
private Color _color;
public Color Color
{
get { return ColorCode.ToColor(); }
set
{
if (_color == value) return;
_color = value;
this.ColorCode = _color.ToArgb();
this.ColorName = _color.ToHex();
}
}
public string ColorName { get; set; }
public uint ColorCode { get; set; }
#endregion
#region Methods
public Color ToColor()
{
return this.Color;
}
public SolidColorBrush ToBrush()
{
return new SolidColorBrush(this.Color);
}
Blends the this color with specified color together</summary>
public void Blend(Color withColor, double amount = 0.5)
{
this.Color = this.Color.Blend(withColor, amount);
}
public void Blend(NamedColor withColor, double amount = 0.5)
{
this.Color = this.Color.Blend(withColor.Color, amount);
}
public static NamedColor FromBrush(Brush brush)
{
var color = brush.ToColor();
return NamedColor.FromColor(color);
}
public static NamedColor FromHex(string colorHex)
{
var color = new Color().FromHex(colorHex);
return NamedColor.FromColor(color);
}
public static NamedColor FromHex(uint colorArgb)
{
return new NamedColor { ColorName = "#" + colorArgb, ColorCode = colorArgb };
}
public static NamedColor FromColor(Color color)
{
var colorArgb = color.ToArgb();
return NamedColor.FromHex(colorArgb);
}
#endregion
} | class | c# | 519 |
class AgglomerativeTreeletRestructuringBvh : public Bvh
{
public:
AgglomerativeTreeletRestructuringBvh(System& system,
const SettingNodeBase* settings) noexcept;
private:
struct RestructuringData : public zisc::NonCopyable<RestructuringData>
{
RestructuringData(const uint treelet_size,
zisc::pmr::memory_resource* work_resource) noexcept;
zisc::pmr::vector<uint32> inner_index_list_;
zisc::pmr::vector<uint32> leaf_index_list_;
zisc::pmr::vector<Float> distance_matrix_;
};
void buildRelationship(const uint32 parent_index,
const uint32 left_child_index,
const uint32 right_child_index,
zisc::pmr::vector<BvhBuildingNode>& tree) const noexcept;
Float calcNodeDistance(const BvhBuildingNode& lhs,
const BvhBuildingNode& rhs) const noexcept;
void constructBvh(
System& system,
const zisc::pmr::vector<Object>& object_list,
zisc::pmr::vector<BvhBuildingNode>& tree) const noexcept override;
void constructOptimalTreelet(
RestructuringData& data,
zisc::pmr::vector<BvhBuildingNode>& tree) const noexcept;
std::tuple<uint, uint> findBestMatch(
const uint num_of_leafs,
const zisc::pmr::vector<Float>& distance_matrix) const noexcept;
void formTreelet(const uint treelet_size,
const uint32 root_index,
const zisc::pmr::vector<BvhBuildingNode>& tree,
RestructuringData& data) const noexcept;
void initialize(const SettingNodeBase* settings) noexcept;
the distance matrix, calculate the distances
void initializeDistanceMatrix(const zisc::pmr::vector<BvhBuildingNode>& tree,
RestructuringData& data) const noexcept;
uint optimizationLoopCount() const noexcept;
template <bool threading = false>
uint restructureTreelet(System& system,
const uint32 index,
RestructuringData& data,
zisc::pmr::vector<BvhBuildingNode>& tree) const noexcept;
uint treeletSize() const noexcept;
void updateDistanceMatrix(const zisc::pmr::vector<BvhBuildingNode>& tree,
const uint row,
const uint column,
RestructuringData& data) const noexcept;
uint treelet_size_;
uint optimization_loop_count_;
} | class | c++ | 520 |
public override void RenderControl(HtmlTextWriter writer)
{
Debug.WriteLine("SPSXsltControl RenderControl");
if (!string.IsNullOrEmpty(XmlData) && !string.IsNullOrEmpty(Xsl))
{
try
{
RenderControlInternal(writer);
}
catch(Exception ex)
{
TrapError(GetType(),"RenderControl",ex);
}
}
} | function | c# | 521 |
def _adjust_brush_radius(self, increase=True):
radius_var = self._control_vars["brush"]["BrushSize"]
current_val = radius_var.get()
new_val = min(100, current_val + 2) if increase else max(1, current_val - 2)
logger.trace("Adjusting brush radius from %s to %s", current_val, new_val)
radius_var.set(new_val)
delta = new_val - current_val
if delta == 0:
return
current_coords = self._canvas.coords(self._mouse_location[0])
new_coords = tuple(coord - delta if idx < 2 else coord + delta
for idx, coord in enumerate(current_coords))
logger.trace("Adjusting brush coordinates from %s to %s", current_coords, new_coords)
self._canvas.coords(self._mouse_location[0], new_coords) | function | python | 522 |
def plot_cascade(self, dictionary_names_cascade, fraction_to_fail):
FONT = 15
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(5,5))
plt.title("Cascade size histogram C="+ str(fraction_to_fail), fontsize= FONT)
plt.xlabel("Value", fontsize= FONT)
plt.ylabel("Fraction of nodes", fontsize= FONT)
cascade_sizes = list(dictionary_names_cascade.values())
unique, counts = np.unique(cascade_sizes, return_counts=True)
cascade_sizes_counts = dict(zip(unique, counts))
possible_cascade_sizes, counts = zip(*cascade_sizes_counts.items())
fractions = [i/sum(counts) for i in counts]
plt.plot(possible_cascade_sizes, fractions,"*", color="royalblue",markersize=4)
plt.show(block=True) | function | python | 523 |
def identify(ui, repo, source=None, rev=None,
num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
if not repo and not source:
raise util.Abort(_("there is no Mercurial repository here "
"(.hg not found)"))
if ui.debugflag:
hexfunc = hex
else:
hexfunc = short
default = not (num or id or branch or tags or bookmarks)
output = []
revs = []
if source:
source, branches = hg.parseurl(ui.expandpath(source))
peer = hg.peer(repo or ui, opts, source)
repo = peer.local()
revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
if not repo:
if num or branch or tags:
raise util.Abort(
_("can't query remote revision number, branch, or tags"))
if not rev and revs:
rev = revs[0]
if not rev:
rev = "tip"
remoterev = peer.lookup(rev)
if default or id:
output = [hexfunc(remoterev)]
def getbms():
bms = []
if 'bookmarks' in peer.listkeys('namespaces'):
hexremoterev = hex(remoterev)
bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
if bmr == hexremoterev]
return sorted(bms)
if bookmarks:
output.extend(getbms())
elif default and not ui.quiet:
bm = '/'.join(getbms())
if bm:
output.append(bm)
else:
if not rev:
ctx = repo[None]
parents = ctx.parents()
changed = ""
if default or id or num:
if (util.any(repo.status())
or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
changed = '+'
if default or id:
output = ["%s%s" %
('+'.join([hexfunc(p.node()) for p in parents]), changed)]
if num:
output.append("%s%s" %
('+'.join([str(p.rev()) for p in parents]), changed))
else:
ctx = scmutil.revsingle(repo, rev)
if default or id:
output = [hexfunc(ctx.node())]
if num:
output.append(str(ctx.rev()))
if default and not ui.quiet:
b = ctx.branch()
if b != 'default':
output.append("(%s)" % b)
t = '/'.join(ctx.tags())
if t:
output.append(t)
bm = '/'.join(ctx.bookmarks())
if bm:
output.append(bm)
else:
if branch:
output.append(ctx.branch())
if tags:
output.extend(ctx.tags())
if bookmarks:
output.extend(ctx.bookmarks())
ui.write("%s\n" % ' '.join(output)) | function | python | 524 |
protected static List<RaveError> checkNullable(
@Nullable Collection<?> collection,
boolean isNullable,
ValidationContext validationContext) {
List<RaveError> errors = checkNullable((Object) collection, isNullable, validationContext);
return collection == null ? errors : checkIterable(collection, errors);
} | function | java | 525 |
class Sentry:
"""A Basic falsey singleton type useful for when ``None`` actually means something.
Only one instance of Sentry may be created (within a session).
To prevent weirdness in with import reloads or multiprocessing we test equality /
based on is tested based on class membership and disallow subclassing.
The following actions are is forbidden on the Sentry type:
- subclassing
- setting attributes
"""
__slots__ = ()
_instance: ClassVar[Optional['Sentry']] = None
def __init_subclass__(cls, *args, **kwargs):
raise TypeError('Sentry may not be subclassed')
def __new__(cls) -> 'Sentry':
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __eq__(self, other: Any) -> bool:
return isinstance(other, Sentry)
def __bool__(self) -> bool:
return False
def __repr__(self) -> str:
return f'{self.__class__.__name__}()' | class | python | 526 |
protected void damageEntity(DamageSource damageSrc, float damageAmount)
{
if (!this.isEntityInvulnerable(damageSrc))
{
damageAmount = net.minecraftforge.common.ForgeHooks.onLivingHurt(this, damageSrc, damageAmount);
if (damageAmount <= 0) return;
damageAmount = net.minecraftforge.common.ISpecialArmor.ArmorProperties.applyArmor(this, inventory.armorInventory, damageSrc, damageAmount);
if (damageAmount <= 0) return;
damageAmount = this.applyPotionDamageCalculations(damageSrc, damageAmount);
float f = damageAmount;
damageAmount = Math.max(damageAmount - this.getAbsorptionAmount(), 0.0F);
this.setAbsorptionAmount(this.getAbsorptionAmount() - (f - damageAmount));
if (damageAmount != 0.0F)
{
this.addExhaustion(damageSrc.getHungerDamage());
float f1 = this.getHealth();
this.setHealth(this.getHealth() - damageAmount);
this.getCombatTracker().trackDamage(damageSrc, f1, damageAmount);
if (damageAmount < 3.4028235E37F)
{
this.addStat(StatList.DAMAGE_TAKEN, Math.round(damageAmount * 10.0F));
}
}
}
} | function | java | 527 |
public final class IndexedClass extends IndexedElement implements ClassElement {
/** This class is a module rather than a proper class */
public static final int MODULE = 1 << 6;
private final String simpleName;
protected IndexedClass(IndexResult result, String fqn, String simpleName, String attributes, int flags) {
super(result, fqn, attributes, flags);
this.simpleName = simpleName;
}
public static IndexedClass create(String simpleName, String fqn, IndexResult result,
String attributes, int flags) {
IndexedClass c = new IndexedClass(result, fqn, simpleName, attributes, flags);
return c;
}
// XXX Is this necessary?
@Override
public String getSignature() {
return in;
}
@Override
public String getName() {
return simpleName;
}
@Override
public ElementKind getKind() {
return (flags & MODULE) != 0 ? ElementKind.MODULE : ElementKind.CLASS;
}
@Override
public boolean equals(Object o) {
if (o instanceof IndexedClass && in != null) {
return in.equals(((IndexedClass) o).in);
}
return super.equals(o);
}
@Override
public int hashCode() {
return in == null ? super.hashCode() : in.hashCode();
}
@Override
public String getFqn() {
return in;
}
} | class | java | 528 |
public static BeanReflectGetter create(DeployBeanProperty prop) {
if (!prop.isId()){
return new NonIdGetter(prop.getFullBeanName());
} else {
String property = prop.getFullBeanName();
Method readMethod = prop.getReadMethod();
if (readMethod == null){
String m = "Abstract class with no readMethod for "+property;
throw new RuntimeException(m);
}
return new IdGetter(property, readMethod);
}
} | function | java | 529 |
class Page:
"""Represents a single rendered page.
Should be obtained from :attr:`Document.pages` but not
instantiated directly.
"""
def __init__(self, page_box):
#: The page width, including margins, in CSS pixels.
self.width = page_box.margin_width()
#: The page height, including margins, in CSS pixels.
self.height = page_box.margin_height()
#: The page bleed widths as a :obj:`dict` with ``'top'``, ``'right'``,
#: ``'bottom'`` and ``'left'`` as keys, and values in CSS pixels.
self.bleed = {
side: page_box.style[f'bleed_{side}'].value
for side in ('top', 'right', 'bottom', 'left')}
#: The :obj:`list` of ``(level, label, target, state)``
#: :obj:`tuples <tuple>`. ``level`` and ``label`` are respectively an
#: :obj:`int` and a :obj:`string <str>`, based on the CSS properties
#: of the same names. ``target`` is an ``(x, y)`` point in CSS pixels
#: from the top-left of the page.
self.bookmarks = []
#: The :obj:`list` of ``(link_type, target, rectangle)`` :obj:`tuples
#: <tuple>`. A ``rectangle`` is ``(x, y, width, height)``, in CSS
#: pixels from the top-left of the page. ``link_type`` is one of three
#: strings:
#:
#: * ``'external'``: ``target`` is an absolute URL
#: * ``'internal'``: ``target`` is an anchor name (see
#: :attr:`Page.anchors`).
#: The anchor might be defined in another page,
#: in multiple pages (in which case the first occurence is used),
#: or not at all.
#: * ``'attachment'``: ``target`` is an absolute URL and points
#: to a resource to attach to the document.
self.links = []
#: The :obj:`dict` mapping each anchor name to its target, an
#: ``(x, y)`` point in CSS pixels from the top-left of the page.
self.anchors = {}
gather_links_and_bookmarks(
page_box, self.anchors, self.links, self.bookmarks)
self._page_box = page_box
def paint(self, stream, left_x=0, top_y=0, scale=1, clip=False):
"""Paint the page into the PDF file.
:type stream: ``document.Stream``
:param stream:
A document stream.
:param float left_x:
X coordinate of the left of the page, in PDF points.
:param float top_y:
Y coordinate of the top of the page, in PDF points.
:param float scale:
Zoom scale.
:param bool clip:
Whether to clip/cut content outside the page. If false or
not provided, content can overflow.
"""
with stacked(stream):
# Make (0, 0) the top-left corner, and make user units CSS pixels:
stream.transform(a=scale, d=scale, e=left_x, f=top_y)
if clip:
stream.rectangle(0, 0, self.width, self.height)
stream.clip()
draw_page(self._page_box, stream) | class | python | 530 |
func (c *DefaultConfig) UnmarshalJSON(input []byte) error {
type Alias DefaultConfig
aux := &struct {
UpdateTime CustomTime `json:"update_time"`
OpenTime CustomTime `json:"openTime"`
CloseTime CustomTime `json:"closeTime"`
ClosedDaysOfTheWeek []weekday `json:"closedDaysOfTheWeek"`
ClosedDays []CustomDay `json:"closedDays"`
*Alias
}{Alias: (*Alias)(c)}
if err := json.Unmarshal(input, &aux); err != nil {
return err
}
c.UpdateTime = time.Time(aux.UpdateTime)
c.OpenTime = time.Time(aux.OpenTime)
c.CloseTime = time.Time(aux.CloseTime)
c.ClosedDaysOfTheWeek = convertTime(aux.ClosedDaysOfTheWeek)
c.ClosedDays = convertDate(aux.ClosedDays)
return nil
} | function | go | 531 |
func (c *Client) SaveBusVehicleDataMessage(vehicleID string, message []byte) (int, error) {
err := c.pool.Do(
radix.Cmd(nil, "SET", fmt.Sprintf("busVehicleData:%s", vehicleID), string(message)),
)
if err != nil {
return 0, err
}
var reply int
err = c.pool.Do(
radix.Cmd(&reply, "PUBLISH", busVehicleDataChannel, string(message)),
)
return reply, err
} | function | go | 532 |
private static void lineChart_update (String tittle ,DataTable table, String col1Name ,String col2Name) {
System.out.println("line chart update" + tittle + table + col1Name + col2Name);
xAxis.setLabel(col1Name);
yAxis.setLabel(col2Name);
lineChart.setTitle(tittle);
DataColumn xCol = table.getCol(col1Name);
DataColumn yCol = table.getCol(col2Name);
if (xCol != null && yCol != null && xCol.getTypeName().equals(DataType.TYPE_NUMBER)
&& yCol.getTypeName().equals(DataType.TYPE_NUMBER)) {
XYChart.Series series = new XYChart.Series();
series.setName(tittle);
Number[] xValues = (Number[]) xCol.getData();
Number[] yValues = (Number[]) yCol.getData();
int len = xValues.length;
for (int i = 0; i < len; i++) {
if (xValues[i] != null && yValues[i] != null) {
series.getData().add(new XYChart.Data(xValues[i], yValues[i]));
}
}
lineChart.getData().clear();
lineChart.getData().add(series);
}
} | function | java | 533 |
public class ExtendedData : DisposableBase
{
public unsafe string Value
{
get
{
var status = NativeInterface.ExtendedData.GetValue(
Handle, out IntPtr value);
if (status != Status.ELECTIONGUARD_STATUS_SUCCESS)
{
Console.WriteLine($"ExtendedData Error Value: {status}");
return null;
}
return Marshal.PtrToStringAnsi(value);
}
}
public unsafe long Length
{
get
{
return NativeInterface.ExtendedData.GetLength(Handle);
}
}
internal unsafe NativeExtendedData Handle;
unsafe internal ExtendedData(NativeExtendedData handle)
{
Handle = handle;
}
public unsafe ExtendedData(string value, long length)
{
var status = NativeInterface.ExtendedData.New(
value, length, out Handle);
if (status != Status.ELECTIONGUARD_STATUS_SUCCESS)
{
Console.WriteLine($"ExtendedData Error Status: {status}");
}
}
protected override unsafe void DisposeUnmanaged()
{
base.DisposeUnmanaged();
if (Handle == null || Handle.IsInvalid) return;
Handle.Dispose();
Handle = null;
}
} | class | c# | 534 |
public List<String> readAllLines() {
ArrayList<String> res = new ArrayList<>();
while (true) {
String s = nextLine();
if (s == null) break;
res.add(s);
}
return Collections.unmodifiableList(res);
} | function | java | 535 |
[Theory]
[InlineData(3)]
[InlineData(5)]
[InlineData(7)]
public async Task OnNetworkDisconnectionANewLeaderIsElectedAfterReconnectOldLeaderStepsDownAndRollBackHisLog(int numberOfNodes)
{
var firstLeader = await CreateNetworkAndGetLeader(numberOfNodes);
var timeToWait = TimeSpan.FromMilliseconds(firstLeader.ElectionTimeout.TotalMilliseconds * 4 * numberOfNodes);
await IssueCommandsAndWaitForCommit(firstLeader, 3, "test", 1);
DisconnectFromNode(firstLeader);
List<Task> invalidCommands = IssueCommandsWithoutWaitingForCommits(firstLeader, 3, "test", 1);
var followers = GetFollowers();
List<Task> waitingList = new List<Task>();
var currentTerm = 1L;
while (true)
{
foreach (var follower in followers)
{
waitingList.Add(follower.WaitForState(RachisState.Leader, CancellationToken.None));
}
if (Log.IsInfoEnabled)
{
Log.Info("Started waiting for new leader");
}
var done = await Task.WhenAny(waitingList).WaitAsync(timeToWait);
if (done)
{
break;
}
var maxTerm = followers.Max(f => f.CurrentTerm);
Assert.True(currentTerm + 1 < maxTerm, "Followers didn't become leaders although old leader can't communicate with the cluster");
Assert.True(maxTerm < 10, "Followers were unable to elect a leader.");
currentTerm = maxTerm;
waitingList.Clear();
}
var newLeader = followers.First(f => f.CurrentState == RachisState.Leader);
var newLeaderLastIndex = await IssueCommandsAndWaitForCommit(newLeader, 5, "test", 1);
if (Log.IsInfoEnabled)
{
Log.Info("Reconnect old leader");
}
ReconnectToNode(firstLeader);
Assert.True(await firstLeader.WaitForState(RachisState.Follower, CancellationToken.None).WaitAsync(timeToWait), "Old leader didn't become follower after two election timeouts");
var waitForCommitIndexChange = firstLeader.WaitForCommitIndexChange(RachisConsensus.CommitIndexModification.GreaterOrEqual, newLeaderLastIndex);
Assert.True(await waitForCommitIndexChange.WaitAsync(timeToWait), "Old leader didn't rollback his log to the new leader log");
Assert.Equal(numberOfNodes, RachisConsensuses.Count);
var leaderUrl = new HashSet<string>();
foreach (var consensus in RachisConsensuses)
{
if (consensus.Tag != consensus.LeaderTag)
{
Assert.True(await consensus.WaitForState(RachisState.Follower, CancellationToken.None).WaitAsync(1000));
}
leaderUrl.Add(consensus.LeaderTag);
}
Assert.True(leaderUrl.Count == 1, "Not all nodes agree on the leader");
foreach (var invalidCommand in invalidCommands)
{
Assert.True(invalidCommand.IsCompleted);
Assert.NotEqual(TaskStatus.RanToCompletion, invalidCommand.Status);
}
} | function | c# | 536 |
def plot_data(title, algorithm_data, yticks, ylabel, xlabel, savefig):
for i, data in enumerate(algorithm_data):
plot.plot(data[0], label=data[1], color=data[3])
plot.text(0, 5 + (len(algorithm_data) * 10) - (i * 5), data[2], color=data[3])
plot.title(title)
plot.yticks(yticks)
plot.ylabel(ylabel)
plot.xlabel(xlabel)
plot.legend()
plot.savefig(savefig)
plot.grid()
plot.show() | function | python | 537 |
func unmarshalYAML(content []byte) (interface{}, error) {
object := map[string]interface{}{}
if err := yaml.Unmarshal(content, object); err != nil {
if err, ok := err.(*yaml.TypeError); ok {
for _, e := range err.Errors {
if strings.HasSuffix(e, "cannot unmarshal !!seq into map[string]interface {}") {
a := []interface{}{}
if err := yaml.Unmarshal(content, &a); err != nil {
return nil, fmt.Errorf("error unmarshalling from YAML: %w", err)
}
return a, nil
}
}
return nil, fmt.Errorf("error: %s, %+v", err.Error(), err.Errors)
}
return nil, fmt.Errorf("error unmarshalling from YAML: %w (%T)", err, err)
}
return object, nil
} | function | go | 538 |
public virtual DescribeProvisionedProductPlanResponse DescribeProvisionedProductPlan(DescribeProvisionedProductPlanRequest request)
{
var options = new InvokeOptions();
options.RequestMarshaller = DescribeProvisionedProductPlanRequestMarshaller.Instance;
options.ResponseUnmarshaller = DescribeProvisionedProductPlanResponseUnmarshaller.Instance;
return Invoke<DescribeProvisionedProductPlanResponse>(request, options);
} | function | c# | 539 |
func (s *Server) ListEchoMessages(ctx context.Context, _ *pb.EmptyRequest) (*pb.EchoMessageCollection, error) {
var out []*pb.EchoMessage
for _, m := range messages {
out = append(out, &pb.EchoMessage{Content: m})
}
return &pb.EchoMessageCollection{
EchoMessages: out,
}, nil
} | function | go | 540 |
def list_transforms ():
print 'Available transforms - Level 1:'
for Transform in transform_classes1:
print '- %s: %s' % (Transform.gen_id, Transform.gen_name)
print ''
print 'Level 2:'
for Transform in transform_classes2:
print '- %s: %s' % (Transform.gen_id, Transform.gen_name)
print ''
print 'Level 3:'
for Transform in transform_classes3:
print '- %s: %s' % (Transform.gen_id, Transform.gen_name)
sys.exit() | function | python | 541 |
static struct dp_test_expected *create_expected_packet(const char *src,
const char *dst,
const char *dst_mac,
uint32_t spi,
int payload_len,
const char *ifname)
{
struct dp_test_expected *exp;
struct rte_mbuf *pak;
char *payload;
payload = calloc(payload_len, 1);
pak = dp_test_create_esp_ipv4_pak(src, dst, 1,
&payload_len, payload,
spi, 1, 0, 255,
NULL,
NULL );
(void)dp_test_pktmbuf_eth_init(pak, dst_mac,
dp_test_intf_name2mac_str(ifname),
RTE_ETHER_TYPE_IPV4);
exp = dp_test_exp_create(pak);
dp_test_exp_set_oif_name(exp, ifname);
dp_test_exp_set_check_len(exp, (dp_pktmbuf_l2_len(pak) +
sizeof(struct iphdr) + 8));
rte_pktmbuf_free(pak);
free(payload);
return exp;
} | function | c | 542 |
def _get_args_without_prototype(self, il_code, symbol_table, c):
final_args = []
for arg_given in self.args:
arg = arg_given.make_il(il_code, symbol_table, c)
if arg.ctype.is_arith() and arg.ctype.size < 4:
arg = set_type(arg, ctypes.integer, il_code)
final_args.append(arg)
return final_args | function | python | 543 |
int4 ScoreUnionFields::scoreLockedType(Datatype *ct,Datatype *lockType)
{
int score = 0;
if (lockType == ct)
score += 5;
while(ct->getMetatype() == TYPE_PTR) {
if (lockType->getMetatype() != TYPE_PTR) break;
score += 5;
ct = ((TypePointer *)ct)->getPtrTo();
lockType = ((TypePointer *)lockType)->getPtrTo();
}
type_metatype ctMeta = ct->getMetatype();
type_metatype vnMeta = lockType->getMetatype();
if (ctMeta == vnMeta) {
if (ctMeta == TYPE_STRUCT || ctMeta == TYPE_UNION || ctMeta == TYPE_ARRAY || ctMeta == TYPE_CODE)
score += 10;
else
score += 3;
}
else {
if ((ctMeta == TYPE_INT && vnMeta == TYPE_UINT)||(ctMeta == TYPE_UINT && vnMeta == TYPE_INT))
score -= 1;
else
score -= 5;
if (ct->getSize() != lockType->getSize())
score -= 2;
}
return score;
} | function | c++ | 544 |
@Override
protected void paintComponent(Graphics g) {
int imageX = 0,
imageY = 0,
imageWidth = this.getWidth(),
imageHeight = this.getHeight();
synchronized (this.frameMutex) {
/* Adjust the image size and location depending on how the aspect ratio matches up with the aspect ratio
* of this component. */
if (this.frame != null) {
float thisAspectRatio = (float) this.getWidth() / this.getHeight();
float imageAspectRatio = (float) this.frame.getWidth(null) / this.frame.getHeight(null);
if (imageAspectRatio < thisAspectRatio) {
imageWidth = (int) (this.getHeight() * imageAspectRatio);
imageX = (this.getWidth() - imageWidth) / 2;
} else {
imageHeight = (int) (this.getWidth() / imageAspectRatio);
imageY = (this.getHeight() - imageHeight) / 2;
}
g.drawImage(this.frame, imageX, imageY, imageWidth, imageHeight, null, null);
}
/* If there's some problem getting the image, show the error on the screen */
if (this.errorMessage != null) {
g.setClip(imageX, imageY, imageWidth, imageHeight);
g.setColor(Color.pink);
g.fillRect(imageX, imageY + imageHeight - 18, imageWidth, 18);
g.setColor(Color.black);
Font font = g.getFont();
g.setFont(font.deriveFont(Font.BOLD));
g.drawString("Error: ", imageX + 2, imageY + imageHeight - 6);
g.setFont(font);
g.drawString(this.errorMessage, imageX + 40, imageY + imageHeight - 6);
}
}
} | function | java | 545 |
def transliterate(text, rosetta=rosetta_stone):
transliteration = u''
try:
for char in text:
if char in rosetta:
transliteration_char = rosetta[char]
else:
transliteration_char = char
transliteration += transliteration_char
except Exception as e:
print(e)
return transliteration | function | python | 546 |
public static String decodeReceiptMessage(String output) {
if (output.length() <= 10) {
return null;
} else {
Function function =
new Function(
"Error",
Collections.emptyList(),
Collections.singletonList(new TypeReference<Utf8String>() {}));
FunctionReturnDecoder functionReturnDecoder = new FunctionReturnDecoder();
List<Type> r =
functionReturnDecoder.decode(
output.substring(10), function.getOutputParameters());
return ((Type) r.get(0)).toString();
}
} | function | java | 547 |
public bool ForceCheckoutQueueRemove(int id)
{
using (helpdesksystemContext context = new helpdesksystemContext())
{
DateTime time = DateTime.Now;
var unitIds = context.Helpdeskunit.Where(hu => hu.HelpdeskId == id).Select(hu => hu.UnitId).ToList();
foreach(int unitId in unitIds)
{
List<Checkinhistory> checkins = context.Checkinhistory.Where(c => c.CheckoutTime == null && c.UnitId == unitId).ToList();
foreach (Checkinhistory checkin in checkins)
{
if (checkin.CheckoutTime == null)
{
checkin.CheckoutTime = time;
checkin.ForcedCheckout = true;
}
}
var topicIds = context.Topic.Where(t => t.UnitId == unitId).Select(t => t.TopicId).ToList();
foreach (int topicId in topicIds)
{
List<Queueitem> queueItems = context.Queueitem.Where(q => q.TimeRemoved == null && q.TopicId == topicId).ToList();
foreach (Queueitem queueItem in queueItems)
{
if (queueItem.TimeRemoved == null)
{
queueItem.TimeRemoved = time;
}
}
}
}
context.SaveChanges();
}
return true;
} | function | c# | 548 |
public void StartTracking(OsuLogo logo, double duration = 0, Easing easing = Easing.None)
{
if (logo == null)
throw new ArgumentNullException(nameof(logo));
if (logo.IsTracking && Logo == null)
throw new InvalidOperationException($"Cannot track an instance of {typeof(OsuLogo)} to multiple {typeof(LogoTrackingContainer)}s");
if (Logo != logo && Logo != null)
{
Logo.IsTracking = false;
}
Logo = logo;
Logo.IsTracking = true;
this.duration = duration;
this.easing = easing;
startTime = null;
startPosition = null;
} | function | c# | 549 |
def calibrate(fragment: Fragment, match_text: str, orig_text:str, distance=3) -> Fragment:
fragment_text = fragment.extract(match_text).lower()
print(f'INPUT FRAGMENT = [{fragment_text}]')
first_word_re = re.compile('\A\W*(\w+)\W.*', re.MULTILINE | re.DOTALL)
last_word_re = re.compile('.*\W(\w+[!.?]?)\W*\Z', re.MULTILINE | re.DOTALL)
m = first_word_re.match(fragment_text+' ')
assert m is not None, f"First word matching failed for [{fragment_text} ] for {fragment}"
first_word = m.group(1)
if len(first_word) == 1 and first_word not in ['i', 'a']:
fragment.start += 1
fragment_text = fragment_text[1:]
m = first_word_re.match(fragment_text+' ')
assert m is not None, f"First word matching failed (b) for [{fragment_text} ] for {fragment}"
first_word = m.group(1)
n = last_word_re.match(' ' + fragment_text)
assert n is not None, f"Last word matching failed for [ {fragment_text}] for {fragment}"
last_word = n.group(1)
have_set_first_word = False
have_set_last_word = False
start, end = fragment.start, fragment.end
startpos = max(start - distance, 0)
for i in range(startpos, start + distance):
if orig_text[i:].lower().startswith(first_word):
start = i
have_set_first_word = True
break
endpos = min(end + distance, len(orig_text))
for i in range(end - distance, endpos):
if orig_text[:i].lower().endswith(last_word):
end = i
have_set_last_word = True
break
if not have_set_first_word:
res = surrounding_word(orig_text, start)
if res is None:
print("starting in empty space")
else:
start = res[0]
if not have_set_last_word:
res = surrounding_word(orig_text, end, with_line_end=True)
if res is None:
print("ending in empty space")
else:
end = res[1]
fragment.start = start
fragment.end = end
print(f'OUTPUT FRAGMENT = [{fragment.extract(orig_text)}]')
return fragment | function | python | 550 |
public class EditContactActivity extends AppCompatActivity {
private ContactList contact_list = new ContactList();
private Contact contact;
private EditText email;
private EditText username;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_contact);
context = getApplicationContext();
contact_list.loadContacts(context);
Intent intent = getIntent();
int pos = intent.getIntExtra("position", 0);
contact = contact_list.getContact(pos);
username = (EditText) findViewById(R.id.username);
email = (EditText) findViewById(R.id.email);
username.setText(contact.getUsername());
email.setText(contact.getEmail());
}
public void saveContact(View view) {
String email_str = email.getText().toString();
if (email_str.equals("")) {
email.setError("Empty field!");
return;
}
if (!email_str.contains("@")){
email.setError("Must be an email address!");
return;
}
String username_str = username.getText().toString();
// Check that username is unique AND username is changed (Note: if username was not changed
// then this should be fine, because it was already unique.)
if (!contact_list.isUsernameAvailable(username_str) && !(contact.getUsername().equals(username_str))) {
username.setError("Username already taken!");
return;
}
String id = contact.getId(); // Reuse the contact id
Contact updated_contact = new Contact(username_str, email_str, id);
// Edit contact
EditContactCommand edit_contact_command = new EditContactCommand(contact_list, contact, updated_contact, context);
edit_contact_command.execute();
boolean success = edit_contact_command.isExecuted();
if (!success){
return;
}
// End EditContactActivity
finish();
}
public void deleteContact(View view) {
// Delete contact
DeleteContactCommand delete_contact_command = new DeleteContactCommand(contact_list, contact, context);
delete_contact_command.execute();
boolean success = delete_contact_command.isExecuted();
if (!success){
return;
}
// End EditContactActivity
finish();
}
} | class | java | 551 |
def physical_filename(self):
class_ = silx.io.utils.get_h5_class(self.__h5py_object)
if class_ == silx.io.utils.H5Type.EXTERNAL_LINK:
return self.__h5py_object.filename
if class_ == silx.io.utils.H5Type.SOFT_LINK:
return self.local_file.filename
return self.physical_file.filename | function | python | 552 |
protected void printNodeInfo(String iNodeTypeString, Node iNode) {
StringBuffer typeStr = new StringBuffer("(null)");
StringBuffer nodeType = new StringBuffer("(null)");
StringBuffer nodeName = new StringBuffer("(null)");
StringBuffer nodeValue = new StringBuffer("(null)");
String sp = " -- ";
if (iNode != null) {
if (iNodeTypeString != null) {
typeStr = new StringBuffer(iNodeTypeString);
}
nodeType = new StringBuffer(Integer.valueOf(iNode.getNodeType()).toString());
if (iNode.getNodeName() != null) {
nodeName = new StringBuffer(iNode.getNodeName());
}
if (iNode.getNodeValue() != null) {
nodeValue = new StringBuffer(iNode.getNodeValue());
}
}
while (typeStr.length() < 42) {
typeStr.append(" ");
}
while (nodeName.length() < 15) {
nodeName.append(" ");
}
while (nodeValue.length() < 10) {
nodeValue.append(" ");
}
log.debug(typeStr + sp + nodeType + sp + nodeName + sp + nodeValue);
} | function | java | 553 |
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this.callbackContext = callbackContext;
if (action.equals("takePicture")) {
this.targetHeight = 0;
this.targetWidth = 0;
this.mQuality = 50;
try {
this.mQuality = args.getInt(1);
this.targetWidth = args.getInt(3);
this.targetHeight = args.getInt(4);
}catch (Exception e){
e.printStackTrace();
}
if (this.targetWidth < 1) {
this.targetWidth = -1;
}
if (this.targetHeight < 1) {
this.targetHeight = -1;
}
this.takePicture();
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
return true;
}
return false;
} | function | java | 554 |
public static byte[] readAllBytes(InputStream stream) throws IOException {
byte[] allBytes = null;
int readBufferSize = 32768;
byte[] readBuffer = new byte[readBufferSize];
try {
boolean more = true;
do {
int count = stream.read(readBuffer,0,readBufferSize);
if (count > 0) {
if (allBytes == null) {
allBytes = new byte[count];
System.arraycopy(readBuffer,0,allBytes,0,count);
}
else {
byte[] newAllBytes = new byte[allBytes.length+count];
System.arraycopy(allBytes,0,newAllBytes,0,allBytes.length);
System.arraycopy(readBuffer,0,newAllBytes,allBytes.length,count);
allBytes = newAllBytes;
}
}
else {
break;
}
} while (true);
}
catch (IOException e) {
throw e;
}
finally {
stream.close();
}
return allBytes;
} | function | java | 555 |
@Override
public YogaDirection recursivelyResolveLayoutDirection() {
YogaNode yogaNode = mYogaNode;
while (yogaNode != null && yogaNode.getLayoutDirection() == YogaDirection.INHERIT) {
yogaNode = yogaNode.getOwner();
}
return yogaNode == null ? YogaDirection.INHERIT : yogaNode.getLayoutDirection();
} | function | java | 556 |
public PoxPayloadOut synchronizeItemWithExistingContext(
ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
String parentIdentifier,
String itemIdentifier,
boolean syncHierarchicalRelationships
) throws Exception {
PoxPayloadOut result = null;
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(),
existingCtx.getResourceMap(),
existingCtx.getUriInfo());
if (existingCtx.getCurrentRepositorySession() != null) {
ctx.setCurrentRepositorySession(existingCtx.getCurrentRepositorySession());
}
result = synchronizeItem(ctx, parentIdentifier, itemIdentifier, syncHierarchicalRelationships);
return result;
} | function | java | 557 |
HRESULT RenderScene(ID3D11DeviceContext* pd3dContext, const SceneParamsStatic *pStaticParams,
const SceneParamsDynamic *pDynamicParams, STEREO_OUTPUT_TYPE outputType)
{
HRESULT hr = S_OK;
if (g_bClearStateUponBeginCommandList)
{
pd3dContext->ClearState();
}
if (pStaticParams->m_pDepthStencilView)
{
pd3dContext->ClearDepthStencilView(pStaticParams->m_pDepthStencilView,
D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0, 0);
}
if (IsRenderMultithreadedPerChunk())
{
for (int iInstance = 0; iInstance < g_iNumPerChunkRenderThreads; ++iInstance)
{
g_iPerChunkQueueOffset[iInstance] = 0;
ChunkQueue& WorkerQueue = g_ChunkQueue[iInstance];
int iQueueOffset = g_iPerChunkQueueOffset[iInstance];
HANDLE hSemaphore = g_hBeginPerChunkRenderDeferredSemaphore[iInstance];
g_iPerChunkQueueOffset[iInstance] += sizeof(WorkQueueEntrySetup);
assert(g_iPerChunkQueueOffset[iInstance] < g_iSceneQueueSizeInBytes);
auto pEntry = reinterpret_cast<WorkQueueEntrySetup*>(&WorkerQueue[iQueueOffset]);
pEntry->m_iType = WORK_QUEUE_ENTRY_TYPE_SETUP;
pEntry->m_pSceneParamsStatic = pStaticParams;
pEntry->m_SceneParamsDynamic = *pDynamicParams;
ReleaseSemaphore(hSemaphore, 1, nullptr);
}
}
else if (IsRenderDeferredPerChunk())
{
for (int iInstance = 0; iInstance < g_iNumPerChunkRenderThreads; ++iInstance)
{
ID3D11DeviceContext* pd3dDeferredContext = g_pd3dPerChunkDeferredContext[iInstance];
V(RenderSceneSetup(pd3dDeferredContext, pStaticParams, pDynamicParams));
}
}
else
{
V(RenderSceneSetup(pd3dContext, pStaticParams, pDynamicParams));
}
D3D11_VIEWPORT* viewports = g_CameraResources.GetViewport();
if (outputType == STEREO_OUTPUT_TYPE::DEFAULT ||
outputType == STEREO_OUTPUT_TYPE::LEFT_EYE)
{
pd3dContext->RSSetViewports(1, viewports);
g_Mesh11.Render(pd3dContext, 0, 1);
}
else if (outputType == STEREO_OUTPUT_TYPE::RIGHT_EYE)
{
pd3dContext->RSSetViewports(1, viewports + 1);
g_Mesh11.Render(pd3dContext, 0, 1);
}
if (IsRenderDeferredPerChunk())
{
if (IsRenderMultithreadedPerChunk())
{
for (int iInstance = 0; iInstance < g_iNumPerChunkRenderThreads; ++iInstance)
{
ChunkQueue& WorkerQueue = g_ChunkQueue[iInstance];
int iQueueOffset = g_iPerChunkQueueOffset[iInstance];
HANDLE hSemaphore = g_hBeginPerChunkRenderDeferredSemaphore[iInstance];
g_iPerChunkQueueOffset[iInstance] += sizeof(WorkQueueEntryFinalize);
assert(g_iPerChunkQueueOffset[iInstance] < g_iSceneQueueSizeInBytes);
auto pEntry = reinterpret_cast<WorkQueueEntryFinalize*>(&WorkerQueue[iQueueOffset]);
pEntry->m_iType = WORK_QUEUE_ENTRY_TYPE_FINALIZE;
ReleaseSemaphore(hSemaphore, 1, nullptr);
}
WaitForMultipleObjects(g_iNumPerChunkRenderThreads,
g_hEndPerChunkRenderDeferredEvent, TRUE, INFINITE);
}
else
{
for (int iInstance = 0; iInstance < g_iNumPerChunkRenderThreads; ++iInstance)
{
V(g_pd3dPerChunkDeferredContext[iInstance]->FinishCommandList(
!g_bClearStateUponFinishCommandList, &g_pd3dPerChunkCommandList[iInstance]));
}
}
for (int iInstance = 0; iInstance < g_iNumPerChunkRenderThreads; ++iInstance)
{
pd3dContext->ExecuteCommandList(g_pd3dPerChunkCommandList[iInstance],
!g_bClearStateUponExecuteCommandList);
SAFE_RELEASE(g_pd3dPerChunkCommandList[iInstance]);
}
}
else
{
if (g_bClearStateUponFinishCommandList || g_bClearStateUponExecuteCommandList)
{
pd3dContext->ClearState();
}
}
return hr;
} | function | c++ | 558 |
fn choose_dependencies<'a>(
available_params: &ParamTypes<R::TypeId>,
deps: &'a [(R::DependencyKey, Vec<Entry<R>>)],
) -> Result<Option<Vec<ChosenDependency<'a, R>>>, Diagnostic<R::TypeId>> {
let mut combination = Vec::new();
for (key, input_entries) in deps {
let provided_param = key.provided_param();
let satisfiable_entries = input_entries
.iter()
.filter(|input_entry| {
input_entry
.params()
.iter()
.all(|p| available_params.contains(p) || Some(*p) == provided_param)
})
.collect::<Vec<_>>();
let chosen_entries = Self::choose_dependency(satisfiable_entries);
match chosen_entries.len() {
0 => {
return Ok(None);
}
1 => {
combination.push((key, chosen_entries[0]));
}
_ => {
let params_clause = match available_params.len() {
0 => "",
1 => " with parameter type ",
_ => " with parameter types ",
};
return Err(Diagnostic {
params: available_params.clone(),
reason: format!(
"Ambiguous rules to compute {}{}{}",
key,
params_clause,
params_str(&available_params),
),
details: chosen_entries.into_iter().map(entry_str).collect(),
});
}
}
}
Ok(Some(combination))
} | function | rust | 559 |
protected boolean renderIncludeStatusFilter(StringBuilder whereQuery, String userObjectAlias,
String prefix, I queryInstance) {
String includeStatusFilterQuery = renderStatusFilter(queryInstance.getIncludeStatusFilter());
if (!StringUtils.isEmpty(includeStatusFilterQuery)) {
whereQuery.append(prefix);
whereQuery.append(" ");
whereQuery.append(userObjectAlias);
whereQuery.append(".status IN ");
whereQuery.append(includeStatusFilterQuery);
return true;
}
return false;
} | function | java | 560 |
func DetectWinSize() *WinSize {
w := &WinSize{
make(chan bool),
make(chan bool),
make(chan bool),
}
changeSig := make(chan os.Signal)
signal.Notify(changeSig, unix.SIGWINCH)
go func() {
for {
select {
case <-changeSig:
time.Sleep(7 * time.Millisecond)
w.Change <- true
case <-w.quit:
w.wait <- true
return
}
}
}()
return w
} | function | go | 561 |
class DropTriggerConstantAction extends DDLSingleTableConstantAction
{
private final String triggerName;
private final SchemaDescriptor sd;
// CONSTRUCTORS
/**
* Make the ConstantAction for a DROP TRIGGER statement.
*
* @param sd Schema that stored prepared statement lives in.
* @param triggerName Name of the Trigger
* @param tableId The table upon which the trigger is defined
*
*/
DropTriggerConstantAction
(
SchemaDescriptor sd,
String triggerName,
UUID tableId
)
{
super(tableId);
this.sd = sd;
this.triggerName = triggerName;
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(sd != null, "SchemaDescriptor is null");
}
}
/**
* This is the guts of the Execution-time logic for DROP STATEMENT.
*
* @see ConstantAction#executeConstantAction
*
* @exception StandardException Thrown on failure
*/
public void executeConstantAction( Activation activation )
throws StandardException
{
TriggerDescriptor triggerd;
LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
DataDictionary dd = lcc.getDataDictionary();
DependencyManager dm = dd.getDependencyManager();
/*
** Inform the data dictionary that we are about to write to it.
** There are several calls to data dictionary "get" methods here
** that might be done in "read" mode in the data dictionary, but
** it seemed safer to do this whole operation in "write" mode.
**
** We tell the data dictionary we're done writing at the end of
** the transaction.
*/
dd.startWriting(lcc);
TableDescriptor td = dd.getTableDescriptor(tableId);
if (td == null)
{
throw StandardException.newException(
SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION,
tableId.toString());
}
TransactionController tc = lcc.getTransactionExecute();
lockTableForDDL(tc, td.getHeapConglomerateId(), true);
// get td again in case table shape is changed before lock is acquired
td = dd.getTableDescriptor(tableId);
if (td == null)
{
throw StandardException.newException(
SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION,
tableId.toString());
}
/*
** Get the trigger descriptor. We're responsible for raising
** the error if it isn't found
*/
triggerd = dd.getTriggerDescriptor(triggerName, sd);
if (triggerd == null)
{
throw StandardException.newException(SQLState.LANG_OBJECT_NOT_FOUND_DURING_EXECUTION, "TRIGGER",
(sd.getSchemaName() + "." + triggerName));
}
/*
** Prepare all dependents to invalidate. (This is there chance
** to say that they can't be invalidated. For example, an open
** cursor referencing a table/trigger that the user is attempting to
** drop.) If no one objects, then invalidate any dependent objects.
*/
dropTriggerDescriptor(lcc, dm, dd, tc, triggerd, activation);
}
static void dropTriggerDescriptor
(
LanguageConnectionContext lcc,
DependencyManager dm,
DataDictionary dd,
TransactionController tc,
TriggerDescriptor triggerd,
Activation activation
) throws StandardException
{
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(triggerd!=null, "trigger descriptor is null");
}
dm.invalidateFor(triggerd, DependencyManager.DROP_TRIGGER, lcc);
// Drop the trigger
dd.dropTriggerDescriptor(triggerd, tc);
// Clear the dependencies for the trigger
dm.clearDependencies(lcc, triggerd);
// Drop the spses
SPSDescriptor spsd = dd.getSPSDescriptor(triggerd.getActionId());
// there shouldn't be any dependencies, but in case
// there are, lets clear them
dm.invalidateFor(spsd, DependencyManager.DROP_TRIGGER, lcc);
dm.clearDependencies(lcc, spsd);
dd.dropSPSDescriptor(spsd, tc);
if (triggerd.getWhenClauseId() != null)
{
spsd = dd.getSPSDescriptor(triggerd.getWhenClauseId());
dm.invalidateFor(spsd, DependencyManager.DROP_TRIGGER, lcc);
dm.clearDependencies(lcc, spsd);
dd.dropSPSDescriptor(spsd, tc);
}
}
public String toString()
{
// Do not put this under SanityManager.DEBUG - it is needed for
// error reporting.
return "DROP TRIGGER "+triggerName;
}
} | class | java | 562 |
public abstract class AbstractArrayAssert<SELF extends AbstractArrayAssert<SELF, ACTUAL, ELEMENT>, ACTUAL, ELEMENT>
extends AbstractEnumerableAssert<SELF, ACTUAL, ELEMENT>
implements ArraySortedAssert<AbstractArrayAssert<SELF, ACTUAL, ELEMENT>, ELEMENT> {
public AbstractArrayAssert(final ACTUAL actual, final Class<?> selfType) {
super(actual, selfType);
}
} | class | java | 563 |
public int GetColumnIndex (string columnName) {
if (columnName == null) throw new ArgumentNullException(nameof(columnName));
int columnIndex;
if (this.columnMap.TryGetValue(columnName, out columnIndex)) {
return (columnIndex);
} else {
return (-1);
}
} | function | c# | 564 |
public static CharSequence escapeCsv(CharSequence value, boolean trimWhiteSpace) {
int length = checkNotNull(value, "value").length();
int start;
int last;
if (trimWhiteSpace) {
start = indexOfFirstNonOwsChar(value, length);
last = indexOfLastNonOwsChar(value, start, length);
} else {
start = 0;
last = length - 1;
}
if (start > last) {
return EMPTY_STRING;
}
int firstUnescapedSpecial = -1;
boolean quoted = false;
if (isDoubleQuote(value.charAt(start))) {
quoted = isDoubleQuote(value.charAt(last)) && last > start;
if (quoted) {
start++;
last--;
} else {
firstUnescapedSpecial = start;
}
}
if (firstUnescapedSpecial < 0) {
if (quoted) {
for (int i = start; i <= last; i++) {
if (isDoubleQuote(value.charAt(i))) {
if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
firstUnescapedSpecial = i;
break;
}
i++;
}
}
} else {
for (int i = start; i <= last; i++) {
char c = value.charAt(i);
if (c == LINE_FEED || c == CARRIAGE_RETURN || c == COMMA) {
firstUnescapedSpecial = i;
break;
}
if (isDoubleQuote(c)) {
if (i == last || !isDoubleQuote(value.charAt(i + 1))) {
firstUnescapedSpecial = i;
break;
}
i++;
}
}
}
if (firstUnescapedSpecial < 0) {
return quoted? value.subSequence(start - 1, last + 2) : value.subSequence(start, last + 1);
}
}
StringBuilder result = new StringBuilder(last - start + 1 + CSV_NUMBER_ESCAPE_CHARACTERS);
result.append(DOUBLE_QUOTE).append(value, start, firstUnescapedSpecial);
for (int i = firstUnescapedSpecial; i <= last; i++) {
char c = value.charAt(i);
if (isDoubleQuote(c)) {
result.append(DOUBLE_QUOTE);
if (i < last && isDoubleQuote(value.charAt(i + 1))) {
i++;
}
}
result.append(c);
}
return result.append(DOUBLE_QUOTE);
} | function | java | 565 |
protected String reserveNode(DomainType domainType) {
LOGGER.info("Trying to reserve a node...");
final int maxRetryCount = controllerProperties.getController().getRetryCount();
String nodeId = null;
int i = 0;
do {
nodeId = nodeRegistry.reserveNode(domainType);
LOGGER.info("Reserved node is {}", nodeId);
if(nodeId == null) {
i++;
waitForRetry();
}
}
while(nodeId == null && i < maxRetryCount);
if(nodeId == null) {
LOGGER.info("No free nodes found after {} retries", maxRetryCount);
}
return nodeId;
} | function | java | 566 |
public class ExternalEdgeRecognizerContext implements EvaluationContext {
private CompositeRowKeyReader rowKeyReader;
/**
* Whether the row contains all fields represented in the predicate
* expressions and all predicates were evaluated successfully.
*/
private boolean rowEvaluatedCompletely;
/**
* Constructs an empty context.
*/
public ExternalEdgeRecognizerContext(PlasmaType contextType, StoreMappingContext mappingContext) {
this.rowKeyReader = new CompositeRowKeyReader(contextType, mappingContext);
}
public void read(byte[] rowKey) {
this.rowKeyReader.read(rowKey);
this.rowEvaluatedCompletely = true;
}
public Object getValue(Endpoint endpoint) {
return this.rowKeyReader.getValue(endpoint);
}
public Collection<Endpoint> getEndpoints() {
return rowKeyReader.getEndpoints();
}
public Collection<KeyValue> getValues() {
return this.rowKeyReader.getValues();
}
public PlasmaType getContextType() {
return this.rowKeyReader.getContextType();
}
public boolean isRowEvaluatedCompletely() {
return rowEvaluatedCompletely;
}
void setRowEvaluatedCompletely(boolean rowEvaluatedCompletely) {
this.rowEvaluatedCompletely = rowEvaluatedCompletely;
}
} | class | java | 567 |
static <X extends NotificationRecipient<?>> NotificationRecipientResolver of(X... recipients) {
final List<X> list = new ArrayList<>(recipients.length);
Collections.addAll(list, recipients);
return new NotificationRecipientResolver() {
@Override
public List<X> resolveNotificationRecipients(NotificationJobInstance<Long, ?> jobInstance, JobInstanceProcessingContext<?> jobProcessingContext) {
return list;
}
};
} | function | java | 568 |
def _compensate_rotation_shift(self, img, scale):
ctr = np.asarray([self.center[1]*scale, self.center[0]*scale])
tform1 = transform.SimilarityTransform(translation=ctr)
tform2 = transform.SimilarityTransform(rotation=np.pi/2 - self.angle)
tform3 = transform.SimilarityTransform(translation=-ctr)
tform = tform3 + tform2 + tform1
rows, cols = img.shape[0], img.shape[1]
corners = np.array([
[0, 0],
[0, rows - 1],
[cols - 1, rows - 1],
[cols - 1, 0]
])
corners = tform.inverse(corners)
minc = corners[:, 0].min()
minr = corners[:, 1].min()
maxc = corners[:, 0].max()
maxr = corners[:, 1].max()
out_rows = maxr - minr + 1
out_cols = maxc - minc + 1
return ((cols - out_cols) / 2., (rows - out_rows) / 2.) | function | python | 569 |
def length_between_idx(self, idx1, idx2, shortest=True):
if idx1 == idx2:
return 0.
if idx1 < idx2:
first = idx1
second = idx2
else:
first = idx2
second = idx1
string_1 = LineString(self.pts[first:second + 1])
string_2 = LineString(np.concatenate((self.pts[0:first + 1], self.pts[second:])))
len_1 = string_1.length
len_2 = string_2.length
if len_1 < len_2:
if idx1 < idx2:
if shortest:
return len_1
else:
return -len_2
else:
if shortest:
return -len_1
else:
return len_2
else:
if idx1 < idx2:
if shortest:
return -len_2
else:
return len_1
else:
if shortest:
return len_2
else:
return -len_1 | function | python | 570 |
def write_measurement(measurement,
root_file=None,
xml_path=None,
output_path=None,
output_suffix=None,
write_workspaces=False,
apply_xml_patches=True,
silence=False):
context = silence_sout_serr if silence else do_nothing
output_name = measurement.name
if output_suffix is not None:
output_name += '_{0}'.format(output_suffix)
output_name = output_name.replace(' ', '_')
if xml_path is None:
xml_path = 'xml_{0}'.format(output_name)
if output_path is not None:
xml_path = os.path.join(output_path, xml_path)
if not os.path.exists(xml_path):
mkdir_p(xml_path)
if root_file is None:
root_file = 'ws_{0}.root'.format(output_name)
if output_path is not None:
root_file = os.path.join(output_path, root_file)
own_file = False
if isinstance(root_file, string_types):
root_file = root_open(root_file, 'recreate')
own_file = True
with preserve_current_directory():
root_file.cd()
log.info("writing histograms and measurement in {0} ...".format(
root_file.GetName()))
with context():
measurement.writeToFile(root_file)
out_m = root_file.Get(measurement.name)
log.info("writing XML in {0} ...".format(xml_path))
with context():
out_m.PrintXML(xml_path)
if write_workspaces:
log.info("writing combined model in {0} ...".format(
root_file.GetName()))
workspace = make_workspace(measurement, silence=silence)
workspace.Write()
for channel in measurement.channels:
log.info("writing model for channel `{0}` in {1} ...".format(
channel.name, root_file.GetName()))
workspace = make_workspace(
measurement, channel=channel, silence=silence)
workspace.Write()
if apply_xml_patches:
patch_xml(glob(os.path.join(xml_path, '*.xml')),
root_file=os.path.basename(root_file.GetName()))
if own_file:
root_file.Close() | function | python | 571 |
private static Boolean TryInvokeParseFrom(Object target, PropertyInfo property, String label, String value, Object fallback, CultureInfo culture)
{
Object converter = ConfigParser<TInstance>.ConstructConverter(property);
if (converter is null)
{
return false;
}
try
{
MethodInfo method = converter.GetType().GetMethod(
nameof(ICustomParser<Object>.Parse),
new Type[] { typeof(String), typeof(String), typeof(Object), typeof(CultureInfo) }
);
if (method is null)
{
return false;
}
property.SetValue(target, method.Invoke(converter, new Object[] { label, value, fallback, culture }));
return true;
}
catch (Exception exception)
{
if (exception.InnerException is CustomParserException)
{
throw exception.InnerException;
}
else
{
throw new CustomParserException(label, value,
$"Unable to parse value of type `{property.PropertyType.Name}`. See inner exception for more details.",
exception is TargetInvocationException ? exception.InnerException : exception
);
}
}
} | function | c# | 572 |
public static LayoutPos From(IDrawArea pane, ScreenPos pos)
{
return new LayoutPos
{
X = LayoutX.From(pane, pos.X),
Y = LayoutY.From(pane, pos.Y),
};
} | function | c# | 573 |
public class MessageCommandExecutor extends CommandExecutor {
/** The validator used to validate invocations. */
private static final Validator validator = new Validator();
/**
* Creates a new instance.
*
* @param client The client to receive events from.
* @param registry The registry to use to look up commands.
* @param prefixProvider The provider to get prefixes from.
*/
public MessageCommandExecutor( final GatewayDiscordClient client, final Registry registry,
final PrefixProvider prefixProvider ) {
super( client, registry, new Builder( prefixProvider ) );
}
/**
* Builder used to construct the processing pipeline.
*
* @version 1.0
* @since 1.0
*/
private static class Builder extends PipelineBuilder<MessageCreateEvent,
MessageCommand, MessageContextImpl, MessageInvocationHandler, MessageResultHandler> {
/** Provides the prefixes that commands should have. */
private final PrefixProvider prefixProvider;
/**
* Creates a new instance.
*
* @param prefixProvider Provides the prefixes that commands should have.
*/
Builder( final PrefixProvider prefixProvider ) {
this.prefixProvider = prefixProvider;
}
@Override
protected Class<MessageCreateEvent> eventType() {
return MessageCreateEvent.class;
}
@Override
protected Class<MessageCommand> commandType() {
return MessageCommand.class;
}
@Override
protected boolean fullMatch() {
return false;
}
@Override
protected boolean eventFilter( final MessageCreateEvent event ) {
return event.getMessage().getAuthor().isPresent();
}
@Override
protected InvocationValidator<MessageCreateEvent> getValidator() {
return validator;
}
/**
* Finds the index of the next whitespace character in the given string.
*
* @param message The message to look into.
* @return The index of the first whitespace, or -1 if none were found.
* @implSpec This method does not consider extended Unicode.
*/
private static int nextWhitespace( final String message ) {
for ( int i = 0; i < message.length(); i++ ) {
if ( Character.isWhitespace( message.charAt( i ) ) ) {
return i;
}
}
return -1;
}
/**
* Finds the index of the next closing delimiter character in the given message.
*
* <p>A closing delimiter must be followed by either a space or the end of the
* message. The first character is ignored, as it is assumed to be the opening
* delimiter.
*
* @param message The message to look into.
* @param delim The delimiter character to look for.
* @return The index of the delimiter, or -1 if one was not found.
* @implSpec This method does not consider extended Unicode.
*/
private static int nextClose( final String message, final Character delim ) {
int cur = 1;
while ( cur >= 0 ) {
cur = message.indexOf( delim, cur );
if ( cur >= 0 && ( cur == message.length() - 1
|| Character.isWhitespace( message.charAt( cur + 1 ) ) ) ) {
return cur;
}
}
return -1;
}
/**
* Parses the next arg from the message.
*
* <p>Args are delimited by whitespace characters, unless enclosed by quotes (single
* or double).
*
* @param message The message to parse.
* @return A tuple with the next arg, and the remainder of the message (in that
* order).
* @implSpec This method does not consider extended Unicode.
*/
private static Tuple2<String, String> nextArg( final String message ) {
int startIdx = 1;
int endIdx;
final int nextStart;
if ( message.startsWith( "\"" ) ) {
endIdx = nextClose( message, '"' );
} else if ( message.startsWith( "'" ) ) {
endIdx = nextClose( message, '\'' );
} else {
startIdx = 0;
endIdx = nextWhitespace( message );
}
if ( endIdx < 0 ) {
startIdx = 0;
endIdx = message.length();
nextStart = message.length();
} else {
nextStart = endIdx + 1;
}
return Tuples.of( message.substring( startIdx, endIdx ),
message.substring( nextStart ).trim() );
}
@Override
protected List<String> parse( final MessageCreateEvent event ) {
String message = event.getMessage().getContent().trim();
final String prefix = prefixProvider.getPrefix( event.getGuildId().orElse( null ) );
if ( message.startsWith( prefix ) ) {
message = message.substring( prefix.length() );
} else {
return Collections.emptyList();
}
final List<String> args = new LinkedList<>();
while ( !message.isEmpty() ) {
final var next = nextArg( message );
args.add( next.getT1() );
message = next.getT2();
}
return args;
}
@Override
protected MessageContextImpl makeContext( final MessageCreateEvent event,
final MessageCommand command, final Invocation invocation,
final List<String> args ) {
return new MessageContextImpl( event, invocation, command.parameters(), args );
}
@Override
protected Optional<Snowflake> getGuildId( final MessageCreateEvent event ) {
return event.getGuildId();
}
@Override
protected MessageInvocationHandler getInvocationHandler( final MessageCommand command ) {
return command.invocationHandler();
}
@Override
protected Mono<CommandResult> invoke( final MessageInvocationHandler handler,
final MessageContextImpl context ) throws Exception {
return handler.handle( context );
}
@Override
protected List<? extends MessageResultHandler> getResultHandlers(
final MessageCommand command ) {
return command.resultHandlers();
}
@Override
protected Mono<Boolean> handle( final MessageResultHandler handler,
final MessageContextImpl context, final CommandResult result ) {
return handler.handle( context, result );
}
}
/**
* The validator used to validate invocations.
*
* @version 1.0
* @since 1.0
*/
private static class Validator extends InvocationValidator<MessageCreateEvent> {
/** Creates a new instance. */
Validator() {}
@Override
protected User getCaller( final MessageCreateEvent event ) {
// Guaranteed to be present due to the event filter.
@SuppressWarnings( "cast.unsafe" )
final var author = ( @Present Optional<User> ) event.getMessage().getAuthor();
return author.get();
}
@Override
protected Mono<MessageChannel> getChannel( final MessageCreateEvent event ) {
return event.getMessage().getChannel();
}
@Override
protected Mono<Guild> getGuild( final MessageCreateEvent event ) {
return event.getGuild();
}
}
} | class | java | 574 |
internal bool FindPublishedContent(IPublishedRequestBuilder request)
{
const string tracePrefix = "FindPublishedContent: ";
using (_profilingLogger.DebugDuration<PublishedRouter>(
$"{tracePrefix}Begin finders",
$"{tracePrefix}End finders"))
{
var found = _contentFinders.Any(finder =>
{
_logger.LogDebug("Finder {ContentFinderType}", finder.GetType().FullName);
return finder.TryFindContent(request);
});
_logger.LogDebug(
"Found? {Found}, Content: {PublishedContentId}, Template: {TemplateAlias}, Domain: {Domain}, Culture: {Culture}, StatusCode: {StatusCode}",
found,
request.HasPublishedContent() ? request.PublishedContent.Id : "NULL",
request.HasTemplate() ? request.Template?.Alias : "NULL",
request.HasDomain() ? request.Domain.ToString() : "NULL",
request.Culture ?? "NULL",
request.ResponseStatusCode);
return found;
}
} | function | c# | 575 |
def trigger(self, event_name: str, parameters: Any = None) -> ServiceResponse:
parameters = self._validate_parameters(parameters)
url = self._url.format(event_name=event_name, key=self._key)
response = requests.post(url, parameters)
logging.debug(f'Request body: {response.request.body}')
logging.info(f'{response.text}')
print(response)
return ServiceResponse.from_response(response) | function | python | 576 |
uint8_t LSM303C::read(lsm303c_xl_raw_data_t data[], uint8_t max_measurements) {
uint8_t buffer[LSM303C_XL_READ_SIZE * LSM303C_FIFO_CAPACITY];
lsm303c_fifo_status_t fifo;
read(fifo);
if (fifo.level > max_measurements) fifo.level = max_measurements;
uint16_t read_size = LSM303C_XL_READ_SIZE * fifo.level;
if (read_size > 0) {
read(buffer, LSM303C_I2C_ADDRESS_XL, OUT_X_L, read_size);
}
for (size_t i = 0; i < fifo.level; i++) {
data[i].x = buffer[i * LSM303C_XL_READ_SIZE] | (uint16_t(buffer[i * LSM303C_XL_READ_SIZE + 1]) << 8);
data[i].y = buffer[i * LSM303C_XL_READ_SIZE + 2] | (uint16_t(buffer[i * LSM303C_XL_READ_SIZE + 3]) << 8);
data[i].z = buffer[i * LSM303C_XL_READ_SIZE + 4] | (uint16_t(buffer[i * LSM303C_XL_READ_SIZE + 5]) << 8);
}
return fifo.level;
} | function | c++ | 577 |
public Type GetTypeFromName(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return null;
}
Type pageType;
return this.pageTypeCache.TryGetValue(typeName.ToLookupKey(), out pageType) ? pageType : null;
} | function | c# | 578 |
def remove_dataset(self, dataset, type=None, clean_locations=False):
logging.debug('Removing dataset "{}"'.format(dataset))
sql = "DELETE FROM {schema}.data WHERE dataset='{dataset}'".format(schema=self.schema, dataset=dataset)
if type is not None:
sql += " AND type='{type}'".format(type=type)
logging.debug(sql)
self.execute(sql)
if clean_locations:
logging.debug('Removing locations...')
sql = "DELETE FROM {schema}.location WHERE id NOT IN (SELECT location_id FROM {schema}.data)".format(schema=self.schema)
self.execute(sql) | function | python | 579 |
def rect_overlap(r1, r2):
left = float(max(r1.left, r2.left))
right = float(min(r1.left + r1.width, r2.left + r2.width))
top = float(max(r1.top, r2.top))
bottom = float(min(r1.top + r1.height, r2.top + r2.height))
if left >= right or top >= bottom:
return 0.
return (right - left) * (bottom - top) | function | python | 580 |
BOOL LLPermissions::setEveryoneBits(const LLUUID& agent, const LLUUID& group, BOOL set, PermissionMask bits)
{
BOOL ownership = FALSE;
if((agent.isNull()) || (agent == mOwner)
|| ((group == mGroup) && (!mGroup.isNull())))
{
ownership = TRUE;
}
if (ownership)
{
if (set)
{
mMaskEveryone |= bits;
}
else
{
mMaskEveryone &= ~bits;
}
fix();
}
return ownership;
} | function | c++ | 581 |
func NewCore(db database.DB, redisPool *redis.Pool, redisWorkerPrefix string) *Core {
return &Core{
db: db,
redisPool: redisPool,
redisWorkerPrefix: redisWorkerPrefix,
}
} | function | go | 582 |
public class FragmentTransactionDetails extends Fragment {
public TextView mTitle;
public LinearLayout backgroundLayout;
private ViewPager txViewPager;
private TransactionPagerAdapter txPagerAdapter;
private List<TxItem> items;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(R.layout.fragment_transaction_details, container, false);
mTitle = (TextView) rootView.findViewById(R.id.title);
backgroundLayout = (LinearLayout) rootView.findViewById(R.id.background_layout);
txViewPager = (ViewPager) rootView.findViewById(R.id.tx_list_pager);
txViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
txPagerAdapter = new TransactionPagerAdapter(getChildFragmentManager(), items);
txViewPager.setAdapter(txPagerAdapter);
txViewPager.setOffscreenPageLimit(5);
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16 * 2, getResources().getDisplayMetrics());
txViewPager.setPageMargin(-margin);
int pos = getArguments().getInt("pos");
txViewPager.setCurrentItem(pos, false);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ViewTreeObserver observer = txViewPager.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if(observer.isAlive()) {
observer.removeOnGlobalLayoutListener(this);
}
BRAnimator.animateBackgroundDim(backgroundLayout, false);
BRAnimator.animateSignalSlide(txViewPager, false, null);
}
});
}
@Override
public void onStop() {
super.onStop();
final Activity app = getActivity();
BRAnimator.animateBackgroundDim(backgroundLayout, true);
BRAnimator.animateSignalSlide(txViewPager, true, new BRAnimator.OnSlideAnimationEnd() {
@Override
public void onAnimationEnd() {
if (app != null && !app.isDestroyed())
app.getFragmentManager().popBackStack();
else
Timber.d("onAnimationEnd: app is null");
}
});
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
public void setItems(List<TxItem> items) {
this.items = items;
}
} | class | java | 583 |
public class HomeFragment extends Fragment {
Animation imgAnim, titleAnim ,logoAnim; // animations
ImageView image; // elements the animations will perform on
LinearLayout title;
ImageView logo;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment HomeFragment.
*/
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
return fragment;
}
/**
* This method is used to draw the Fragment UI -- the things to be viewed on screen
*
* @param inflater a system service that converts xml files into view objects
* @param container the invisible container that holds View and ViewGroup
* @param savedInstanceState a reference to a bundle object passed into the onCreate method
* @return the view that holds all the viewable objects
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_home, container, false);
fab.hide();
fab.setImageResource(R.drawable.ic_baseline_color_lens_24); // setting the image resource for the fab
// performing the animations on the elements
// image will fade in
image = view.findViewById(R.id.homeImage);
imgAnim = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
image.startAnimation(imgAnim);
// title and logo will come from the "corner"
title = view.findViewById(R.id.logoContainer);
titleAnim = AnimationUtils.loadAnimation(getContext(), R.anim.corner_entrance);
title.startAnimation(titleAnim);
logo = view.findViewById(R.id.logo);
logoAnim = AnimationUtils.loadAnimation(getContext(), R.anim.corner_entrance);
logo.startAnimation(logoAnim);
// when the account button is pressed
Button accountButton = view.findViewById(R.id.accountButton);
accountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Navigation.findNavController(view)
.navigate(R.id.action_nav_home_to_nav_account); // it will take you to the account fragment
}
});
// when the menu button is pressed
Button menuButton = view.findViewById(R.id.menuButton);
menuButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Navigation.findNavController(view)
.navigate(R.id.action_nav_home_to_nav_menu); // it will take you to the menu fragment
}
});
return view;
}
} | class | java | 584 |
public class SdkThread {
private static final SdkThread instance = new SdkThread();
private static final String TAG = "SdkThread";
private Thread mThread;
private boolean initFailed = false;
private Handler mHandler;
private SdkThread() {}
/**
* Callback interface for displaying messages such as errors from the SDK.
*/
public interface Callback {
void displayMessage(final int msgId, String error);
}
public void init(final String configFile, final Callback callback) {
synchronized (this) {
if (initComplete()) {
return;
}
try {
mThread = new Thread(new Runnable() {
@Override
public void run() {
initSdk(configFile, callback);
}
});
mThread.start();
synchronized (mThread) {
while (!initComplete() && !initFailed) {
mThread.wait();
}
}
} catch (Exception e) {
Log.e(TAG, "Connection error", e);
}
}
}
private void initSdk(final String configFile, final Callback callback) {
try {
// Prepare a looper on current thread.
Looper.prepare();
// The Handler will automatically bind to the current thread's Looper.
mHandler = new Handler();
// Initialise VNC SDK logging
Logger.createAndroidLogger();
try {
// Create the filestore with the absolute path to Android's app files directory
DataStore.createFileStore(configFile);
} catch (Library.VncException e) {
callback.displayMessage(R.string.failed_to_create_datastore, e.getMessage());
}
// Init the SDK
Library.init(Library.EventLoopType.ANDROID);
synchronized (mThread) {
mThread.notifyAll();
}
// After the following line the thread will start running the message loop and will not
// normally exit the loop unless a problem happens or you quit() the looper.
Looper.loop();
} catch (Library.VncException e) {
initFailed = true;
Log.e(TAG, "Initialisation error: ", e);
callback.displayMessage(R.string.failed_to_initialise_vnc_sdk, e.getMessage());
mHandler = null;
synchronized (mThread) {
mThread.notifyAll();
}
}
}
/**
* Posts a runnable the SDK thread. {@link #init} must be called first.
* @param runnable The Runnable to run on the SDK thread.
*/
public void post(Runnable runnable) {
if (!initComplete()) {
throw new RuntimeException("init() must be called first");
}
mHandler.post(runnable);
}
/**
* Helper method to determine whether or not we need to init the VNC SDK.
* @return
*/
public boolean initComplete() {
return !initFailed && mHandler != null;
}
public static SdkThread getInstance() {
return instance;
}
} | class | java | 585 |
protected I convertInput(Object input) {
final ArgumentConversionContext<I> cc = ConversionContext.of(inputType);
final Optional<I> converted = applicationContext.getConversionService().convert(
input,
cc
);
return converted.orElseThrow(() ->
new IllegalArgumentException("Unconvertible input: " + input, cc.getLastError().map(ConversionError::getCause).orElse(null))
);
} | function | java | 586 |
pub fn deserialize<T>(slice: &[u8], format: &Format) -> Result<T>
where
T: DeserializeOwned,
{
match format {
#[cfg(feature = "serde-json")]
Format::Json => serde_json::from_slice(slice).map_err(|_| StorageError::SerializationError),
#[cfg(feature = "serde-cbor")]
Format::Cbor => serde_cbor::from_slice(slice).map_err(|_| StorageError::SerializationError),
#[cfg(feature = "serde-ron")]
Format::Ron => ron::de::from_bytes(slice).map_err(|_| StorageError::SerializationError),
#[cfg(feature = "serde-yaml")]
Format::Yaml => serde_yaml::from_slice(slice).map_err(|_| StorageError::SerializationError),
#[cfg(feature = "serde-bincode")]
Format::Bincode => {
bincode::deserialize(slice).map_err(|_| StorageError::SerializationError)
}
#[cfg(feature = "serde-xml")]
Format::Xml => {
quick_xml::de::from_reader(slice).map_err(|_| StorageError::SerializationError)
}
#[cfg(not(any(
feature = "serde-json",
feature = "serde-cbor",
feature = "serde-ron",
feature = "serde-yaml",
feature = "serde-bincode",
feature = "serde-xml"
)))]
Format::None => panic!(
"At least one of the serde extension features should be active to use deserialzie"
),
}
} | function | rust | 587 |
public final class BAD_OPERATION
extends SystemException
implements Serializable
{
/**
* Use serialVersionUID for interoperability.
*/
private static final long serialVersionUID = 1654621651720499682L;
/**
* Creates a BAD_OPERATION with the default minor code of 0, completion state
* COMPLETED_NO and the given explaining message.
*
* @param message the explaining message.
*/
public BAD_OPERATION(String message)
{
super(message, 0, CompletionStatus.COMPLETED_NO);
}
/**
* Creates BAD_OPERATION with the default minor code of 0 and a completion
* state COMPLETED_NO.
*/
public BAD_OPERATION()
{
super("", 0, CompletionStatus.COMPLETED_NO);
}
/**
* Creates a BAD_OPERATION exception with the specified minor code and
* completion status.
*
* @param minor additional error code.
* @param completed the method completion status.
*/
public BAD_OPERATION(int minor, CompletionStatus completed)
{
super("", minor, completed);
}
/**
* Created BAD_OPERATION exception, providing full information.
*
* @param reason explaining message.
* @param minor additional error code (the "minor").
* @param completed the method completion status.
*/
public BAD_OPERATION(String reason, int minor, CompletionStatus completed)
{
super(reason, minor, completed);
}
} | class | java | 588 |
func (t *Table) GetVOffsetTSlot(slot VOffsetT, d VOffsetT) VOffsetT {
off := t.Offset(slot)
if off == 0 {
return d
}
return VOffsetT(off)
} | function | go | 589 |
public static class AuthUser {
/**
* SHA-1 double hashed copy of the users clear text password
*/
private final byte[] m_sha1ShadowPassword;
/**
* SHA-2 double hashed copy of the users clear text password
*/
private final byte[] m_sha2ShadowPassword;
/**
* SHA-1 hashed and then bcrypted copy of the users clear text password
*/
private final String m_bcryptShadowPassword;
/**
* SHA-2 hashed and then bcrypted copy of the users clear text password
*/
private final String m_bcryptSha2ShadowPassword;
/**
* Name of the user
*/
public final String m_name;
/**
* Fast iterable list of groups this user is a member of.
*/
private List<AuthGroup> m_groups = new ArrayList<AuthGroup>();
private EnumSet<Permission> m_permissions = EnumSet.noneOf(Permission.class);
private String[] m_permissions_list;
/**
* Fast membership check set of stored procedures this user has permission to invoke.
* This is generated when the catalog is parsed and it includes procedures the user has permission
* to invoke by virtue of group membership. The catalog entry for the stored procedure is used here.
*/
private Set<Procedure> m_authorizedProcedures = new HashSet<Procedure>();
/**
* Set of export connectors this user is authorized to access.
*/
private Set<Connector> m_authorizedConnectors = new HashSet<Connector>();
/**
* The constructor accepts the password as either sha1 or bcrypt. In practice
* there will be only one passed in depending on the format of the password in the catalog.
* The other will be null and that is used to determine how to hash the supplied password
* for auth
* @param shadowPassword SHA-1 double hashed copy of the users clear text password
* @param name Name of the user
*/
private AuthUser(byte[] sha1ShadowPassword, byte[] sha2ShadowPassword, String bcryptShadowPassword, String bCryptSha2ShadowPassword, String name) {
m_sha1ShadowPassword = sha1ShadowPassword;
m_sha2ShadowPassword = sha2ShadowPassword;
m_bcryptShadowPassword = bcryptShadowPassword;
m_bcryptSha2ShadowPassword = bCryptSha2ShadowPassword;
if (name != null) {
m_name = name.intern();
} else {
m_name = null;
}
}
/**
* Check if a user has permission to invoke the specified stored procedure
* Handle both user-written procedures and default auto-generated ones.
* @param proc Catalog entry for the stored procedure to check
* @return true if the user has permission and false otherwise
*/
public boolean hasUserDefinedProcedurePermission(Procedure proc) {
if (proc == null) {
return false;
}
return hasPermission(Permission.ALLPROC) || m_authorizedProcedures.contains(proc);
}
/**
* Check if a user has any one of given permission.
* @return true if the user has permission and false otherwise
*/
public boolean hasPermission(Permission... perms) {
for (Permission perm : perms) {
if (m_permissions.contains(perm)) {
return true;
}
}
return false;
}
/**
* Get group names.
* @return group name array
*/
public final List<String> getGroupNames() {
return m_groups.stream().map(g -> g.m_name).collect(Collectors.toList());
}
public boolean authorizeConnector(String connectorClass) {
if (connectorClass == null) {
return false;
}
for (Connector c : m_authorizedConnectors) {
if (c.getLoaderclass().equals(connectorClass)) {
return true;
}
}
return false;
}
public boolean isAuthEnabled() {
return true;
}
private void finish() {
m_groups = ImmutableList.copyOf(m_groups);
m_authorizedProcedures = ImmutableSet.copyOf(m_authorizedProcedures);
m_authorizedConnectors = ImmutableSet.copyOf(m_authorizedConnectors);
}
} | class | java | 590 |
private void prepareApplication(DataWorkflowTask pTask) throws ExecutionPreparationException {
File executionBasePath;
try {
executionBasePath = DataWorkflowHelper.getStagingBasePath(pTask);
} catch (IOException ex) {
throw new ExecutionPreparationException("Failed to prepare execution.", ex);
}
File workingDirectory = DataWorkflowHelper.getTaskWorkingDirectory(executionBasePath);
File destination = new File(workingDirectory, "userApplication.zip");
FileOutputStream propertiesStream = null;
try {
LOGGER.debug("Obtaining application package URL");
AbstractFile applicationPackage = new AbstractFile(new URL(pTask.getConfiguration().getApplicationPackageUrl()));
LOGGER.debug("Downloading application archive from {} to {}", applicationPackage, destination);
applicationPackage.downloadFileToFile(new AbstractFile(destination));
LOGGER.debug("User application archive successfully downloaded. Extracting user application to {}", destination.getParentFile());
ZipUtils.unzip(destination, destination.getParentFile());
LOGGER.debug("Deleting user application archive. Success: {}", destination.delete());
LOGGER.debug("User application successfully extracted. Performing variable substition.");
DataWorkflowHelper.substituteVariablesInDirectory(pTask);
LOGGER.debug("Variable substitution finished. Storing custom properties.");
Properties settings = pTask.getExecutionSettingsAsObject();
if (settings != null) {
propertiesStream = new FileOutputStream(new File(workingDirectory, "dataworkflow.properties"));
settings.store(propertiesStream, null);
}
LOGGER.debug("Custom properties stored. User application successfully prepared.");
} catch (MalformedURLException | AdalapiException ex) {
throw new ExecutionPreparationException("Failed to obtain user application package.", ex);
} catch (IOException | URISyntaxException ex) {
throw new ExecutionPreparationException("Failed to extract user application package or failed to substitute DataWorkflow variables.", ex);
} finally {
if (propertiesStream != null) {
try {
propertiesStream.close();
} catch (IOException ex) {
}
}
}
} | function | java | 591 |
public SyntaxNodeOrTokenList Insert(int index, SyntaxNodeOrToken nodeOrToken)
{
if (nodeOrToken == default)
{
throw new ArgumentOutOfRangeException(nameof(nodeOrToken));
}
return InsertRange(index, SpecializedCollections.SingletonEnumerable(nodeOrToken));
} | function | c# | 592 |
def relabel(self, exclude=None, limit1=None, limit2=None, fix_outliers=None, **kwargs):
printout = ''
size = self._size
if limit1 is None:
limit1 = int(np.sqrt(size))
printout += 'limit1 is set to ' + str(limit1) + ', '
else:
if limit1 < 0:
raise ValueError('Limit1 must be non-negative integer!')
if limit1 < 1:
limit1 = int(limit1 * size)
if limit2 is None:
limit2 = int(size / 2 + 1)
printout += 'limit2 is set to ' + str(limit2) + ', '
else:
if limit2 < 0:
raise ValueError('Limit2 must be non-negative integer!')
if limit2 <= 1:
limit2 = int(limit2 * size + 1)
if fix_outliers is None:
fix_outliers = 0
printout += 'fix_outliers is set to ' + str(fix_outliers)
if printout:
print ('Relabeling using defaults for: ' + printout)
self.labels_ = label(self.mst_, self.values_, self._size, exclude, int(limit1), int(limit2), fix_outliers, **kwargs)
return self.labels_ | function | python | 593 |
void cgi_neo_error (CGI *cgi, NEOERR *given_err)
{
NEOERR *err;
STRING str;
string_init(&str);
err = cgiwrap_writef("Status: 500\n");
if (err != STATUS_OK) _log_clear_error(&err);
err = cgiwrap_writef("Content-Type: text/html\n\n");
if (err != STATUS_OK) _log_clear_error(&err);
err = cgiwrap_writef("<html><body>\nAn error occured:<pre>");
if (err != STATUS_OK) _log_clear_error(&err);
nerr_error_traceback(given_err, &str);
err = cgiwrap_write(str.buf, str.len);
if (err != STATUS_OK) _log_clear_error(&err);
err = cgiwrap_writef("</pre></body></html>\n");
if (err != STATUS_OK) _log_clear_error(&err);
string_clear(&str);
} | function | c | 594 |
Int String_CompareRange(const String a, Int astart, Int alength, const String b, Int bstart, Int blength)
{
const Byte *aptr, *bptr, *aend, *bend;
Byte abyte, bbyte;
if (astart < 0)
{
alength += astart;
astart = 0;
}
if (bstart < 0)
{
blength += bstart;
bstart = 0;
}
if (String_IsNullOrEmpty(a) || astart >= String_Length(a) || alength <= 0)
{
return String_IsNullOrEmpty(b) || bstart >= String_Length(b) || blength <= 0 ? 0 : -1;
}
if (String_IsNullOrEmpty(b) || bstart >= String_Length(b) || blength <= 0)
{
return -1;
}
if (alength > String_Length(a) - astart)
{
alength = String_Length(a) - astart;
}
if (blength > String_Length(b) - bstart)
{
blength = String_Length(b) - bstart;
}
aptr = String_GetBytes(a) + astart;
bptr = String_GetBytes(b) + bstart;
aend = aptr + alength;
bend = bptr + blength;
while (aptr < aend && bptr < bend)
{
if ((abyte = *aptr++) != (bbyte = *bptr++))
return abyte < bbyte ? -1 : +1;
}
if (aptr != aend) return +1;
if (bptr != bend) return -1;
return 0;
} | function | c | 595 |
public virtual iText.Kernel.Pdf.Canvas.PdfCanvas BeginLayer(IPdfOCG layer) {
if (layer is PdfLayer && ((PdfLayer)layer).GetTitle() != null) {
throw new ArgumentException("Illegal layer argument.");
}
if (layerDepth == null) {
layerDepth = new List<int>();
}
if (layer is PdfLayerMembership) {
layerDepth.Add(1);
AddToPropertiesAndBeginLayer(layer);
}
else {
if (layer is PdfLayer) {
int num = 0;
PdfLayer la = (PdfLayer)layer;
while (la != null) {
if (la.GetTitle() == null) {
AddToPropertiesAndBeginLayer(la);
num++;
}
la = la.GetParent();
}
layerDepth.Add(num);
}
else {
throw new NotSupportedException("Unsupported type for operand: layer");
}
}
return this;
} | function | c# | 596 |
private static class IdleStopper {
private boolean acceptDoneContinuation = false;
private ImapConnection imapConnection;
public synchronized void startAcceptingDoneContinuation(ImapConnection connection) {
if (connection == null) {
throw new NullPointerException("connection must not be null");
}
acceptDoneContinuation = true;
imapConnection = connection;
}
public synchronized void stopAcceptingDoneContinuation() {
acceptDoneContinuation = false;
imapConnection = null;
}
public synchronized void stopIdle() {
if (acceptDoneContinuation) {
acceptDoneContinuation = false;
sendDone();
}
}
private void sendDone() {
try {
imapConnection.setReadTimeout(RemoteStore.SOCKET_READ_TIMEOUT);
imapConnection.sendContinuation("DONE");
} catch (IOException e) {
imapConnection.close();
}
}
} | class | java | 597 |
async function startParseServer(parseServerOptions = {}) {
const mongodbPort = process.env.MONGODB_PORT || 27017;
const {
databaseName = 'parse-test',
databaseURI = `mongodb://localhost:${mongodbPort}/${databaseName}`,
masterKey = 'test',
javascriptKey = 'test',
appId = 'test',
port = 30001,
mountPath = '/1',
serverURL = `http://localhost:${port}${mountPath}`,
} = parseServerOptions;
let mongoConnection = await connectDB(databaseURI);
await mongoConnection.db().dropDatabase();
parseServerOptions = Object.assign({
masterKey, javascriptKey, appId,
serverURL,
databaseURI,
silent: process.env.VERBOSE !== '1',
}, parseServerOptions);
const app = express();
const parseServer = new ParseServer(parseServerOptions);
app.use(mountPath, parseServer);
const httpServer = http.createServer(app);
Promise.promisifyAll(httpServer);
await httpServer.listenAsync(port)
Object.assign(parseServerState, {
parseServer,
httpServer,
mongoConnection,
expressApp: app,
parseServerOptions,
});
} | function | javascript | 598 |
public XnRegion asSimpleRegion() {
if (isSimple()) {
return this;
}
if (isBoundedBelow()) {
if (isBoundedAbove()) {
return IntegerRegion.make(start(), stop());
} else {
return IntegerRegion.after(start());
}
} else {
if (isBoundedAbove()) {
return IntegerRegion.before(stop());
} else {
return IntegerRegion.allIntegers();
}
}
/*
udanax-top.st:68482:IntegerRegion methodsFor: 'accessing'!
{XnRegion} asSimpleRegion
"Will always return the smallest simple region which contains all my positions"
self isSimple ifTrue: [^self].
self isBoundedBelow
ifTrue: [self isBoundedAbove
ifTrue: [^IntegerRegion make: self start with: self stop]
ifFalse: [^IntegerRegion after: self start]]
ifFalse: [self isBoundedAbove
ifTrue: [^IntegerRegion before: self stop]
ifFalse: [^IntegerRegion allIntegers]]!
*/
} | function | java | 599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.