code
stringlengths 0
30.8k
| source
stringclasses 6
values | language
stringclasses 9
values | __index_level_0__
int64 0
100k
|
---|---|---|---|
public new bool Equals(object obj)
{
var p = obj as WindowOpenMessage;
if (p == null)
{
return false;
}
return ((WindowOpenMessage)obj).WindowType == WindowType;
} | function | c# | 200 |
@Startup
@Singleton
@SuppressWarnings("unused")
public class DatabaseInitializer {
private static final int MAX_AMOUNT_OF_PERSONS_TO_GENERATE = 5;
@PersistenceContext
private EntityManager entityManager;
@PostConstruct
public void initializeDatabase() {
generatePersons(MAX_AMOUNT_OF_PERSONS_TO_GENERATE);
}
private void generatePersons(int maxAmount) {
IntStream.rangeClosed(1, MAX_AMOUNT_OF_PERSONS_TO_GENERATE).forEach(index -> {
Person person = new Person();
person.setFirstName("FirstName_" + index);
person.setMiddleName("MiddleName_" + index);
person.setLastName("LastName_" + index);
entityManager.persist(person);
});
}
} | class | java | 201 |
private VOSubscription createAndSubscribeToServiceWithParameter(
String paraValue) throws Exception {
technicalServiceWithParameter = createTechnicalService("tp1");
List<VOParameter> params = createParametersForTechnicalService(
technicalServiceWithParameter, paraValue);
serviceWithParameter = createServiceWithParameter(params);
createdSubscription = createSubscription();
createdSubscription = subscrServiceForCustomer.subscribeToService(
createdSubscription, serviceWithParameter, usageLicences, null,
null, new ArrayList<VOUda>());
return createdSubscription;
} | function | java | 202 |
public class ModelArrows : GeometricElement
{
public IList<(Vector3 origin, Vector3 direction, double magnitude, Color? color)> Vectors { get; set; }
public bool ArrowAtStart { get; set; }
public bool ArrowAtEnd { get; set; }
public double ArrowAngle { get; set; }
[JsonConstructor]
public ModelArrows(IList<(Vector3 location, Vector3 direction, double magnitude, Color? color)> vectors = null,
bool arrowAtStart = false,
bool arrowAtEnd = true,
double arrowAngle = 60.0,
Transform transform = null,
bool isElementDefinition = false,
Guid id = default(Guid),
string name = null) : base(transform != null ? transform : new Transform(),
BuiltInMaterials.Default,
null,
isElementDefinition,
id != default(Guid) ? id : Guid.NewGuid(),
name)
{
this.Vectors = vectors != null ? vectors : new List<(Vector3, Vector3, double, Color?)>();
this.ArrowAtEnd = arrowAtEnd;
this.ArrowAtStart = arrowAtStart;
this.ArrowAngle = arrowAngle;
}
internal GraphicsBuffers ToGraphicsBuffers()
{
var x = 0.1 * Math.Cos(Units.DegreesToRadians(-this.ArrowAngle));
var y = 0.1 * Math.Sin(Units.DegreesToRadians(-this.ArrowAngle));
var gb = new GraphicsBuffers();
for (var i = 0; i < this.Vectors.Count; i++)
{
var v = this.Vectors[i];
var start = v.origin;
var end = v.origin + v.direction * v.magnitude;
var up = v.direction.IsParallelTo(Vector3.ZAxis) ? Vector3.YAxis : Vector3.ZAxis;
var tx = v.direction.Cross(up);
var ty = v.direction;
var tz = ty.Cross(tx);
var tr = new Transform(Vector3.Origin, tx, ty, tz);
var pts = new List<Vector3>() { v.origin, end };
if (this.ArrowAtStart)
{
var arrow1 = tr.OfPoint(new Vector3(x, -y));
var arrow2 = tr.OfPoint(new Vector3(-x, -y));
pts.Add(start);
pts.Add(start + arrow1);
pts.Add(start);
pts.Add(start + arrow2);
}
if (this.ArrowAtEnd)
{
var arrow1 = tr.OfPoint(new Vector3(x, y));
var arrow2 = tr.OfPoint(new Vector3(-x, y));
pts.Add(end);
pts.Add(end + arrow1);
pts.Add(end);
pts.Add(end + arrow2);
}
for (var j = 0; j < pts.Count; j++)
{
var pt = pts[j];
gb.AddVertex(pt, default(Vector3), default(UV), v.color ?? Colors.Red);
gb.AddIndex((ushort)(i * pts.Count + j));
}
}
return gb;
}
} | class | c# | 203 |
class COMPSsConfiguration:
"""
Class containing the configuration options provided by the COMPSs test configuration file
:attribute user: User executing the tests
+ type: String
:attribute target_base_dir: Path to store the tests execution sandbox
+ type: String
:attribute compss_base_log_dir: Path to the COMPSs base log directory
+ type: String
:attribute java_home: JAVA_HOME environment variable
+ type: String or None
:attribute compss_home: COMPSS_HOME environment variable
+ type: String or None
:attribute comm: Runtime Adaptor class to be loaded on tests execution
+ type: String
:attribute runcompss_opts: Extra options for the runcompss command
+ type: List<String> or None
:attribute execution_envs: List of different execution environments for each test
+ type: List<String>
"""
def __init__(self, user=None, java_home=None, compss_home=DEFAULT_COMPSS_HOME, target_base_dir=None,
comm=DEFAULT_COMM, runcompss_opts=None, execution_envs=DEFAULT_EXECUTION_ENVS):
"""
Initializes the COMPSsConfiguration class with the given options
:param user: User executing the tests
:param java_home: JAVA_HOME environment variable
:param compss_home: COMPSS_HOME environment variable
:param target_base_dir: Path to store the tests execution sandbox
:param comm: Adaptor class to be loaded on tests execution
:param runcompss_opts: Extra options for the runcompss command
:param execution_envs: List of different execution environments for each test
:raise ConfigurationError: If some mandatory variable is undefined
"""
# Either we receive a user from cfg or we load it from current user (always defined)
if user is None:
import getpass
self.user = getpass.getuser()
else:
self.user = user
# Either we receive a java_home or we load it from environment, if not defined we raise an exception
if java_home is not None:
self.java_home = java_home
else:
# Load from env
self.java_home = os.getenv("JAVA_HOME", None)
if self.java_home is None:
raise ConfigurationError(
"[ERROR] Undefined variable JAVA_HOME in both the configuration file and the environment")
# Store COMPSs_HOME (always defined because it has a default value)
self.compss_home = compss_home
# Define compss_base_log_dir
user_home = os.path.expanduser("~")
self.compss_base_log_dir = os.path.join(user_home, ".COMPSs")
# Either we receive the target_base_dir or we compute it from user home
if target_base_dir is None:
self.target_base_dir = os.path.join(user_home, "tests_execution_sandbox")
else:
self.target_base_dir = target_base_dir
# Receive comm (always defined, has default value)
self.comm = comm
# Receive comm (can be None)
self.runcompss_opts = runcompss_opts
# Receive comm (always defined, has default value)
self.execution_envs = execution_envs
def get_user(self):
"""
Returns the user executing the tests
:return: The user executing the tests
+ type: String
"""
return self.user
def get_java_home(self):
"""
Returns the JAVA_HOME environment variable
:return: The JAVA_HOME environment variable
+ type: String or None
"""
return self.java_home
def get_compss_home(self):
"""
Returns the COMPSS_HOME environment variable
:return: The COMPSS_HOME environment variable
+ type: String or None
"""
return self.compss_home
def get_target_base_dir(self):
"""
Returns the path to store the tests execution sandbox
:return: The path to store the tests execution sandbox
+ type: String
"""
return self.target_base_dir
def get_compss_base_log_dir(self):
"""
Returns the path to the COMPSs log base directory
:return: The path to the COMPSs log base directory
+ type: String
"""
return self.compss_base_log_dir
def get_comm(self):
"""
Returns the adaptor class to be loaded on tests execution
:return: The adaptor class to be loaded on tests execution
+ type: String
"""
return self.comm
def get_runcompss_opts(self):
"""
Returns the extra options for the runcompss command
:return: The extra options for the runcompss command
+ type: List<String> or None
"""
return self.runcompss_opts
def get_execution_envs(self):
"""
Returns the list of different execution environments for each test
:return: The list of different execution environments for each test
+ type: List<String>
"""
return self.execution_envs
def get_execution_envs_str(self):
"""
Returns the list of different execution environments for each test
:return: A string representing the list of different execution environments for each test
+ type: String
"""
return ' '.join(str(x) for x in self.execution_envs) | class | python | 204 |
int
debug_call_with_fault_handler(jmp_buf jumpBuffer, void (*function)(void*),
void* parameter)
{
cpu_ent* cpu = gCPU + sDebuggerOnCPU;
addr_t oldFaultHandler = cpu->fault_handler;
addr_t oldFaultHandlerStackPointer = cpu->fault_handler_stack_pointer;
int result = setjmp(jumpBuffer);
if (result == 0) {
arch_debug_call_with_fault_handler(cpu, jumpBuffer, function,
parameter);
}
cpu->fault_handler = oldFaultHandler;
cpu->fault_handler_stack_pointer = oldFaultHandlerStackPointer;
return result;
} | function | c++ | 205 |
public static void loadImageAssets(ImageCollection imageCollection,
String fileName) throws Exception {
try (ZipFile zipFile = new ZipFile(fileName)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
ZipEntry entry;
while (entries.hasMoreElements()) {
entry = entries.nextElement();
if (!entry.getName().equals(PGTUtil.IMAGES_SAVE_PATH)) {
continue;
}
break;
}
while (entries.hasMoreElements()) {
entry = entries.nextElement();
if (entry.isDirectory()) {
break;
}
BufferedImage img;
try (InputStream imageStream = zipFile.getInputStream(entry)) {
String name = entry.getName().replace(".png", "")
.replace(PGTUtil.IMAGES_SAVE_PATH, "");
int imageId = Integer.parseInt(name);
img = ImageIO.read(imageStream);
ImageNode imageNode = new ImageNode();
imageNode.setId(imageId);
imageNode.setImage(img);
imageCollection.getBuffer().setEqual(imageNode);
imageCollection.insert(imageId);
}
}
}
} | function | java | 206 |
public static BlangFile Parse(string path)
{
var blangFile = new BlangFile();
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (var binaryReader = new BinaryReader(fileStream))
{
var blangStrings = new List<BlangString>();
fileStream.Seek(0xC, SeekOrigin.Begin);
var strBytes = binaryReader.ReadBytes(5);
fileStream.Seek(0x0, SeekOrigin.Begin);
if (!Encoding.UTF8.GetString(strBytes).ToLower().Equals("#str_"))
{
byte[] unknownDataBytes = binaryReader.ReadBytes(8);
Array.Reverse(unknownDataBytes, 0, unknownDataBytes.Length);
blangFile.UnknownData = BitConverter.ToInt64(unknownDataBytes, 0);
}
byte[] stringAmountBytes = binaryReader.ReadBytes(4);
Array.Reverse(stringAmountBytes, 0, stringAmountBytes.Length);
int stringAmount = BitConverter.ToInt32(stringAmountBytes, 0);
bool skipUnknown = false;
long currentPosition = fileStream.Position;
fileStream.Seek(0x4, SeekOrigin.Current);
fileStream.Seek(binaryReader.ReadUInt32(), SeekOrigin.Current);
fileStream.Seek(binaryReader.ReadUInt32(), SeekOrigin.Current);
fileStream.Seek(0x8, SeekOrigin.Current);
if (Encoding.UTF8.GetString(binaryReader.ReadBytes(5)).ToLower().Equals("#str_"))
{
skipUnknown = true;
}
fileStream.Seek(currentPosition, SeekOrigin.Begin);
for (int i = 0; i < stringAmount; i++)
{
uint hash = binaryReader.ReadUInt32();
int identifierBytes = binaryReader.ReadInt32();
string identifier = Encoding.UTF8.GetString(binaryReader.ReadBytes(identifierBytes));
int textBytes = binaryReader.ReadInt32();
string text = Encoding.UTF8.GetString(binaryReader.ReadBytes(textBytes));
string unknown = "";
if (!skipUnknown)
{
int unknownBytes = binaryReader.ReadInt32();
unknown = Encoding.UTF8.GetString(binaryReader.ReadBytes(unknownBytes));
}
blangStrings.Add(new BlangString(hash, identifier, identifier, text, text, unknown, false));
}
blangFile.Strings = blangStrings;
}
}
return blangFile;
} | function | c# | 207 |
fn name_to_properties(name: Name) -> (Vec<String>, Option<TypeQualifier>) {
let (bare_name, opt_q) = name.into_inner();
let raw_name: String = bare_name.into();
let raw_name_copy = raw_name.clone();
let split = raw_name_copy.split('.');
let mut parts: Vec<String> = vec![];
for part in split {
if part.is_empty() {
// abort
parts.clear();
parts.push(raw_name);
break;
} else {
parts.push(part.to_owned());
}
}
(parts, opt_q)
} | function | rust | 208 |
public virtual void ApplyTo(RSTR response)
{
if (response == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
}
if (tokenType != null)
{
response.TokenType = tokenType;
}
if (token != null)
{
response.RequestedSecurityToken = new RequestedSecurityToken(token);
}
if (attachedReference != null)
{
response.RequestedAttachedReference = attachedReference;
}
if (unattachedReference != null)
{
response.RequestedUnattachedReference = unattachedReference;
}
if (lifetime != null)
{
response.Lifetime = lifetime;
}
if (proofDescriptor != null)
{
proofDescriptor.ApplyTo(response);
}
} | function | c# | 209 |
public boolean execute(String command) {
String[] args = command.trim().split("[ ]{1,}");
if (args[0].isEmpty()) {
return true;
}
Log.log(Shell.class, "Invocation request: " + Arrays.toString(args));
Class<?> commandClass = classesMap.get(args[0]);
if (commandClass == null) {
Log.log(Shell.class,
String.format("Command not found by name %s", args[0]));
System.err.println("Sorry, this command is missing");
return false;
} else {
try {
Command commandInstance = (Command) commandClass.newInstance();
commandInstance.execute(this, args);
return true;
} catch (Throwable exc) {
if (!(exc instanceof HandledException)) {
Log.log(Shell.class,
exc,
String.format("Error during execution of %s",
args[0]));
System.err.println(String.format("%s: Method execution error",
args[0]));
}
return false;
}
}
} | function | java | 210 |
public void updateGame(Seed theSeed, int rowSelected, int colSelected) {
if (hasWon(theSeed, rowSelected, colSelected)) {
currentState = (theSeed == Seed.CROSS) ? GameState.CROSS_WON : GameState.NOUGHT_WON;
} else if (isDraw()) {
currentState = GameState.DRAW;
}
} | function | java | 211 |
public static ResultSet varArgsFunctionTable(int... values) throws SQLException {
if (values.length != 6) {
throw new SQLException("Unexpected argument count");
}
SimpleResultSet result = new SimpleResultSet();
result.addColumn("A", Types.INTEGER, 0, 0);
for (int value : values) {
result.addRow(value);
}
return result;
} | function | java | 212 |
[Guid(Guids.ColorCoderOptionPackage)]
[DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\14.0")]
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideOptionPage(typeof(ChangeColorOptionGrid), "ColorCoder", "Colors", 1000, 1001, true)]
[ProvideOptionPage(typeof(PresetOptionGrid), "ColorCoder", "Presets", 1000, 1001, true)]
[InstalledProductRegistration("ColorCoder", "Color Coder provides semantic coloring for C# and VB - http://hamidmosalla.com/color-coder/", Vsix.Version, IconResourceID = 400)]
public sealed class ColorCoderPackage : AsyncPackage
{
public const string PackageGuidString = "b9c81946-7fc5-4544-8f62-881252590edb";
#region Package Members
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
}
#endregion
} | class | c# | 213 |
public static String serialize(World w, Scene s, ActionCallback cb) {
String id = null;
if (cb == null)
return null;
id = serialize(cb, w.getUIActors());
if (id != null)
return id;
id = serialize(cb, w.getInventory());
if (id != null)
return id;
if (w.getInkManager() != null) {
id = serialize(cb, w.getInkManager().getVerbRunners());
}
if (id != null)
return id;
id = serialize(cb, s);
if (id != null)
return id;
id = serialize(cb, s.getPlayer());
if (id != null)
return id;
for (BaseActor a : s.getActors().values()) {
if (!(a instanceof InteractiveActor))
continue;
id = serialize(cb, (InteractiveActor) a);
if (id != null)
return id;
}
for (Verb v : w.getVerbManager().getVerbs().values()) {
id = serialize(cb, v);
if (id != null) {
StringBuilder stringBuilder = new StringBuilder(DEFAULT_VERB_TAG);
stringBuilder.append(SEPARATION_SYMBOL).append(id);
return stringBuilder.toString();
}
}
return null;
} | function | java | 214 |
@Test
void isValidQuantityGreaterMaxQuantityOtherListings() throws Exception {
listing = new Listing(
inventoryItem,
15,
99.99,
"More info",
LocalDateTime.now(),
LocalDateTime.of(2022, 1,1, 0, 0)
);
inventoryItem.addListing(listing);
int quantity = 20;
assertFalse(ListingValidation.isValidQuantity(quantity, inventoryItem));
} | function | java | 215 |
def create_snapshot_if_not_exist(volume_id, tags, time_limit):
try:
snap = check_snapshot_exist(volume_id, time_limit)
if snap:
logger.info("An existing snapshot was found: {0}" .format(snap))
return snap
logger.info("Launch of the snapshot creation process")
snapshot_id = ec2.create_snapshot(VolumeId=volume_id,
Description='Snapshot create to scale the volume: {0}' .format(volume_id))['SnapshotId']
ec2.create_tags(Resources=[snapshot_id], Tags=tags)
logger.info("Waiting until the snapshot become available")
if not check_the_resource_state('snapshot_completed',
'SnapshotIds',
snapshot_id):
logger.error("Snapshot still not available, timeout reached")
return None
tags = [{'Key': "To_Delete", 'Value': "True"}]
ec2.create_tags(Resources=[volume_id], Tags=tags)
return snapshot_id
except Exception as e:
logger.error('Can\'t create snapshot: {0}' .format(str(e))) | function | python | 216 |
def warp_image(image, warp_matrix, source_coords = None, dest_coords = None,
inverse = False, lines = False):
if inverse:
flags = cv2.WARP_INVERSE_MAP
else:
flags = cv2.INTER_LINEAR
img_size = (image.shape[1], image.shape[0])
warped = cv2.warpPerspective(image, M_warp, img_size, flags = flags)
if lines:
if (source_coords is None) or (dest_coords is None):
print("Warning: If you want lines to be drawn, you must provide \
'source_coords' and 'dest_coords'. No lines drawn this time.")
col = (0, 0, 255)
src = np.int32(source_coords)
dst = np.int32(dest_coords)
image = cv2.polylines(image, [src], isClosed = 1, color = col,
thickness = 3)
warped = cv2.polylines(warped, [dst], isClosed = 1, color = col,
thickness = 3)
return image, warped | function | python | 217 |
static bool parseIncoming(HttpConn *conn, HttpPacket *packet)
{
HttpRx *rx;
ssize len;
char *start, *end;
if (packet == NULL) {
return 0;
}
if (mprShouldDenyNewRequests()) {
httpError(conn, HTTP_ABORT | HTTP_CODE_NOT_ACCEPTABLE, "Server terminating");
return 0;
}
if (!conn->rx) {
conn->rx = httpCreateRx(conn);
conn->tx = httpCreateTx(conn, NULL);
}
rx = conn->rx;
if ((len = httpGetPacketLength(packet)) == 0) {
return 0;
}
start = mprGetBufStart(packet->content);
#if FUTURE
while (*start == '\r' || *start == '\n') {
mprGetCharFromBuf(packet->content);
start = mprGetBufStart(packet->content);
}
#endif
if ((end = sncontains(start, "\r\n\r\n", len)) == 0) {
if (len >= conn->limits->headerSize) {
httpError(conn, HTTP_ABORT | HTTP_CODE_REQUEST_TOO_LARGE,
"Header too big. Length %d vs limit %d", len, conn->limits->headerSize);
}
return 0;
}
len = end - start;
mprAddNullToBuf(packet->content);
if (len >= conn->limits->headerSize) {
httpError(conn, HTTP_ABORT | HTTP_CODE_REQUEST_TOO_LARGE,
"Header too big. Length %d vs limit %d", len, conn->limits->headerSize);
return 0;
}
if (conn->endpoint) {
if (!parseRequestLine(conn, packet)) {
return 0;
}
} else if (!parseResponseLine(conn, packet)) {
return 0;
}
if (!parseHeaders(conn, packet)) {
return 0;
}
if (conn->endpoint) {
httpMatchHost(conn);
if (httpSetUri(conn, rx->uri, "") < 0 || rx->pathInfo[0] != '/') {
httpError(conn, HTTP_ABORT | HTTP_CODE_BAD_REQUEST, "Bad URL format");
}
if (conn->secure) {
rx->parsedUri->scheme = sclone("https");
}
rx->parsedUri->port = conn->sock->listenSock->port;
rx->parsedUri->host = rx->hostHeader ? rx->hostHeader : conn->host->name;
if (!rx->parsedUri->host) {
rx->parsedUri->host = (conn->host->name[0] == '*') ? conn->sock->acceptIp : conn->host->name;
}
} else if (!(100 <= rx->status && rx->status <= 199)) {
httpCreateRxPipeline(conn, conn->http->clientRoute);
}
httpSetState(conn, HTTP_STATE_PARSED);
return 1;
} | function | c | 218 |
public class Utils {
/**
* Turn a string address or host name (IPV4, IPV6, host.domain.tld) into an InetAddress
* @param _addr
* @return the internet address IPV4 of the IP address, or host name in _addr
*/
public static InetAddress parseInetAddress(String _addr)
throws UnknownHostException, NumberFormatException {
byte[] octets = null;
Inet4Address addr4 = null; // a composed address to add to the access list stored in result and returned to the caller
Inet6Address addr6 = null;
// if it contains a colon, this is an IPV6 host address
if (_addr.indexOf(":") > -1) {
StringTokenizer st = new StringTokenizer(_addr,":");
octets = new byte[16];
int j = 0;
String s = null;
while (st.hasMoreTokens()) {
s = st.nextToken();
short val = Short.parseShort(s,16);
octets[j] = (byte) ( (val >> 8) & 0x00FF);
octets[j+1] = (byte) ( val & 0x00FF);
j+=2;
}
addr6 = (Inet6Address) InetAddress.getByAddress(octets);
return (InetAddress) addr6;
}
// otherwise if it ends in a digit, this is an IPV4 HOST ADDRESS
else if ( Character.isDigit(_addr.charAt(_addr.length()-1))) {
StringTokenizer st = new StringTokenizer(_addr,".");
octets = new byte[4];
int j = 0;
while (st.hasMoreTokens()) {
String s = st.nextToken();
octets[j] = Byte.parseByte(s,10);
j++;
}
addr4 = (Inet4Address) InetAddress.getByAddress(octets);
return (InetAddress) addr4;
}
// otherwise this is a HOST NAME
else {
addr4 = (Inet4Address) InetAddress.getByName(_addr);
return (InetAddress) addr4;
}
}
/**
* This expects a <> wrapped email address. It will return the parts of the address, parsed, if there was one or null if an email address could not be recognized
* @param _fullEmailAddress an email address in the form "<user+command@host.tld>" including the < and > brackets around it. the "+command" part is optional of course
* @return a String[] array containing in order: username+command, the username, the command, the host name, the full address less <> brackets and lowercased. [2] the commandw ill be NULL if there was no command (there is not usually a command)
*/
public static String[] parseEmailAddress(String _fullEmailAddress) {
String[] result = new String[5];
_fullEmailAddress=_fullEmailAddress.trim().toLowerCase();
// parses <username+command@host> into username+command, host
final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(".*?<(.*?)@(.*?)>.*");
// parses username+command into username, command
final Pattern EMAIL_COMMAND_PATTERN = Pattern.compile("(.*?)\\+(.*?)");
final Pattern EMAIL_AROUND_ATSIGN = Pattern.compile(".*?(<|\\s)([a-zA-Z_0-9\\+\\-\\.]*?@[a-zA-Z_0-9\\.]*?)(\\s|>)");
Matcher m = EMAIL_ADDRESS_PATTERN.matcher(_fullEmailAddress);
if (m.matches()) {
result[0] = m.group(1);
result[3] = m.group(2);
Matcher m2 = EMAIL_COMMAND_PATTERN.matcher(result[0]);
if (m2.matches()) {
result[1] = m2.group(1);
result[2] = m2.group(2);
}
else { // no plus sign, so just copy over what's needed and null out the command as there was none
result[1] = result[0];
result[2] = null;
}
// finally set the "whole" address less brackets, if any
Matcher mm = EMAIL_AROUND_ATSIGN.matcher(_fullEmailAddress);
if (mm.find()) {
result[4] = mm.group(2);
}
else
result = null;
}
else result = null;
return result;
}
public static void main(String[] x) {
String[] s= Utils.parseEmailAddress("cvhaos <jim+electric@agentzero.com>");
for (int i = 0; i < s.length; i++)
System.out.println(i+" "+s[i]);
}
} | class | java | 219 |
def run(self, name: str = None):
if self.raise_if_missing and name not in os.environ:
raise ValueError("Environment variable not set: {}".format(name))
value = os.getenv(name)
if value is not None and self.cast is not None:
value = self.cast(value)
return value | function | python | 220 |
internal static BaseMock GetSolutionBuildManagerInstance()
{
if(solutionBuildManager == null)
{
solutionBuildManager = new GenericMockFactory("SolutionBuildManager", new Type[] { typeof(IVsSolutionBuildManager2), typeof(IVsSolutionBuildManager3) });
}
BaseMock buildManager = solutionBuildManager.GetInstance();
return buildManager;
} | function | c# | 221 |
def _reg_std(self, result, rank, demeaned_df):
if (len(self.clusters) == 0) & (self.robust is False):
std_error = result.bse * np.sqrt((result.nobs - len(self.covariants)) / (result.nobs - len(self.covariants)
- rank))
covariance_matrix = result.normalized_cov_params * result.scale * result.df_resid / result.df_resid
elif (len(self.clusters) == 0) & (self.robust is True):
covariance_matrix = robust_err(demeaned_df, self.covariants, result.nobs, len(self.covariants), rank)
std_error = np.sqrt(np.diag(covariance_matrix))
else:
nested = is_nested(demeaned_df, self.fixed_effects, self.clusters, self.covariants)
covariance_matrix = clustered_error(demeaned_df, self.covariants, self.clusters, result.nobs,
len(self.covariants), rank, nested=nested, c_method=self.cm,
psdef=self.ps_def)
std_error = np.sqrt(np.diag(covariance_matrix))
return std_error, covariance_matrix | function | python | 222 |
def live_migrate_instance(self, instance_id, dest_hostname,
block_migration=False, retry=120):
LOG.debug("Trying a live migrate of instance %s to host '%s'" % (
instance_id, dest_hostname))
instance = self.find_instance(instance_id)
if not instance:
LOG.debug("Instance not found: %s" % instance_id)
return False
else:
host_name = getattr(instance, 'OS-EXT-SRV-ATTR:host')
LOG.debug(
"Instance %s found on host '%s'." % (instance_id, host_name))
instance.live_migrate(host=dest_hostname,
block_migration=block_migration,
disk_over_commit=True)
while getattr(instance,
'OS-EXT-SRV-ATTR:host') != dest_hostname \
and retry:
instance = self.nova.servers.get(instance.id)
LOG.debug(
'Waiting the migration of {0} to {1}'.format(
instance,
getattr(instance,
'OS-EXT-SRV-ATTR:host')))
time.sleep(1)
retry -= 1
host_name = getattr(instance, 'OS-EXT-SRV-ATTR:host')
if host_name != dest_hostname:
return False
LOG.debug(
"Live migration succeeded : "
"instance %s is now on host '%s'." % (
instance_id, host_name))
return True | function | python | 223 |
function mainDogAnim (e) {
if(e.which!=1)return;
if($(the_dog).is(':animated')) { _no=true; return; }
$(the_dog).animate({
width:520,
height:350,
top:"+=10px",
left:"+=6px"
},33,null);
} | function | javascript | 224 |
public bool IliasLogin(string sUser, string sPassword)
{
if (bLoggedIn)
{
return true;
}
else
{
if (sUser != "" && sPassword != "")
{
config.SetUser(sUser);
try
{
sSessionId = client.loginLDAP(config.GetClient(), sUser, sPassword);
iUserId = client.getUserIdBySid(sSessionId);
bLoggedIn = true;
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
if (e.Message == "err_wrong_login")
{
}
bLoggedIn = false;
return false;
}
}
else
{
bLoggedIn = false;
return false;
}
}
} | function | c# | 225 |
def first_or_default(behaviors, request):
address = str(request.questions[0].qname)
if behaviors == None or len(behaviors) == 0:
return Behavior(address)
for behavior in behaviors:
if (behavior.handles(address)):
return behavior
return Behavior(address) | function | python | 226 |
@Data
@JsonInclude(value = JsonInclude.Include.NON_EMPTY, content = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MscsConfigData {
/**
* The type of connectivity that is requested to be provided to the virtualized networks in the NFVI-PoP and characterizes the connectivity service across the WAN. Permitted values: - L2 - L3
*/
public enum MscsTypeEnum {
L2("L2"),
L3("L3");
private String value;
MscsTypeEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static MscsTypeEnum fromValue(String value) {
for (MscsTypeEnum b : MscsTypeEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
}
private MscsTypeEnum mscsType;
private List<MscsConfigDataSiteAccessProtectionSchemes> siteAccessProtectionSchemes = null;
private BigDecimal mtuMscs;
private WanLayer2ProtocolData wanLayer2ProtocolData;
private WanLayer3ProtocolData wanLayer3ProtocolData;
} | class | java | 227 |
func rowsToTest(rows *sql.Rows) (*Test, error) {
var test *Test
tests, err := rowsToTests(rows)
if len(tests) >= 1 {
test = tests[0]
}
return test, err
} | function | go | 228 |
async createUpdateTierConfigRequest(configId, params) {
return this.createTierConfigRequest({
configuration: {
id: configId,
},
params,
});
} | function | javascript | 229 |
public unsafe int CompareOrdinal(string s)
{
fixed (cef_string_utf16_t* self = &Base)
{
return CompareOrdinal((cef_string_t*)self, s);
}
} | function | c# | 230 |
static int
check_authkeys_file(struct ssh *ssh, struct passwd *pw, FILE *f,
char *file, struct sshkey *key, struct sshauthopt **authoptsp)
{
char *cp, *line = NULL, loc[256];
size_t linesize = 0;
int found_key = 0;
u_long linenum = 0;
if (authoptsp != NULL)
*authoptsp = NULL;
while (getline(&line, &linesize, f) != -1) {
linenum++;
if (found_key)
continue;
cp = line;
skip_space(&cp);
if (!*cp || *cp == '\n' || *cp == '#')
continue;
snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
if (check_authkey_line(ssh, pw, key, cp, loc, authoptsp) == 0)
found_key = 1;
}
free(line);
return found_key;
} | function | c | 231 |
private
class UpdateParamGroupsOpen
implements ActionListener
{
public
UpdateParamGroupsOpen
(
String name,
JDrawer drawer
)
{
pName = name;
pDrawer = drawer;
}
/**
* Invoked when an action occurs.
*/
public void
actionPerformed
(
ActionEvent e
)
{
pParamGroupsOpen.put(pName, pDrawer.isOpen());
}
private String pName;
private JDrawer pDrawer;
} | class | java | 232 |
private void registerDynamicPTsWithStream(
CallPeerMediaHandler<?> callPeerMediaHandler,
MediaStream stream)
{
DynamicPayloadTypeRegistry dynamicPayloadTypes
= callPeerMediaHandler.getDynamicPayloadTypes();
StringBuffer dbgMessage = new StringBuffer("Dynamic PT map: ");
for (Map.Entry<MediaFormat, Byte> mapEntry
: dynamicPayloadTypes.getMappings().entrySet())
{
byte pt = mapEntry.getValue();
MediaFormat fmt = mapEntry.getKey();
dbgMessage.append(pt).append("=").append(fmt).append("; ");
stream.addDynamicRTPPayloadType(pt, fmt);
}
logger.info(dbgMessage);
dbgMessage = new StringBuffer("PT overrides [");
for (Map.Entry<Byte, Byte> overrideEntry
: dynamicPayloadTypes.getMappingOverrides().entrySet())
{
byte originalPt = overrideEntry.getKey();
byte overridePt = overrideEntry.getValue();
dbgMessage.append(originalPt).append("->")
.append(overridePt).append(" ");
stream.addDynamicRTPPayloadTypeOverride(originalPt, overridePt);
}
dbgMessage.append("]");
logger.info(dbgMessage);
} | function | java | 233 |
private void renderEpisodes(final TvShowViewModel tvShow) {
List<Renderer<EpisodeViewModel>> episodeRenderers =
new LinkedList<Renderer<EpisodeViewModel>>();
episodeRenderers.add(new EpisodeRenderer());
EpisodeRendererBuilder episodeRendererBuilder = new EpisodeRendererBuilder(episodeRenderers);
EpisodeRendererAdapter episodesAdapter =
new EpisodeRendererAdapter(getLayoutInflater(), episodeRendererBuilder,
tvShow.getEpisodes());
episodesListView.setAdapter(episodesAdapter);
} | function | java | 234 |
float4 LightSample(GBufferValues sample, VSOutput geo, SystemInputs sys)
{
float3 directionToEye = 0.0.xxx;
#if (OUTPUT_WORLD_VIEW_VECTOR==1)
directionToEye = normalize(geo.worldViewVector);
#endif
float4 result = float4(
ResolveLitColor(
sample, directionToEye, GetWorldPosition(geo),
LightScreenDest_Create(int2(geo.position.xy), GetSampleIndex(sys))), 1.f);
#if OUTPUT_FOG_COLOR == 1
result.rgb = geo.fogColor.rgb + result.rgb * geo.fogColor.a;
#endif
result.a = sample.blendingAlpha;
return result;
} | function | c | 235 |
public abstract class PluginEvent {
/**
* Name of event source when plugin event is passed to
* another tool as cross-tool event.
*/
public static final String EXTERNAL_SOURCE_NAME = "External Tool";
private String eventName;
private String sourceName;
private PluginEvent triggerEvent;
/**
* Returns the tool event name corresponding to the given pluginEventClass.
* If no corresponding tool event exists, null will be returned.
*/
public static String lookupToolEventName(Class<?> pluginEventClass) {
ToolEventName eventNameAnnotation = pluginEventClass.getAnnotation(ToolEventName.class);
if (eventNameAnnotation != null) {
return eventNameAnnotation.value();
}
return null;
}
/**
* Constructor
* @param sourceName source name of the event
* @param eventName name of event
*/
protected PluginEvent(String sourceName, String eventName) {
this.eventName = eventName;
this.sourceName = sourceName;
}
/**
* Determine if this event has been annotated with a {@link ToolEventName} which
* makes it available for passing to another tool via a {@link ToolConnection}.
* @return true if event can be utilized as a cross-tool event
*/
public boolean isToolEvent() {
return getToolEventName() != null;
}
/**
* Get the optional cross-tool event name which has been established via
* a {@link ToolEventName} annotation which makes it available for
* passing as an external tool via a {@link ToolConnection}.
* This name may differ from the {@link #getEventName()}.s
* @return tool event name or null if not permitted as a cross-tool event
*/
public final String getToolEventName() {
return lookupToolEventName(getClass());
}
/**
* Get the plugin event name.
*/
public final String getEventName() {
return eventName;
}
/**
* Returns the name of the plugin immediately responsible for firing this
* event.
*/
public final String getSourceName() {
return sourceName;
}
public void setSourceName(String s) {
sourceName = s;
}
public void setTriggerEvent(PluginEvent triggerEvent) {
this.triggerEvent = triggerEvent;
}
public PluginEvent getTriggerEvent() {
return triggerEvent;
}
@Override
public String toString() {
String details = getDetails();
StringBuilder builder = new StringBuilder();
builder.append("Event: ");
builder.append(eventName);
builder.append(" Source: ");
builder.append(sourceName);
if (details != null) {
builder.append("\n\tDetails: ");
builder.append(details);
}
return builder.toString();
}
protected String getDetails() {
return null;
}
} | class | java | 236 |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method)]
public class ManagedNameAttribute : Attribute
{
string name;
public string Name
{
get { return name ; }
}
public ManagedNameAttribute(string name)
{
this.name = name;
}
internal static string GetMemberName(MemberInfo member)
{
Object [] rg = member.GetCustomAttributes(typeof(ManagedNameAttribute), false);
if(rg.Length > 0)
{
ManagedNameAttribute attr = (ManagedNameAttribute)rg[0];
if(attr.name != null && attr.name.Length != 0)
return attr.name;
}
return member.Name;
}
internal static string GetBaseClassName(Type type)
{
InstrumentationClassAttribute attr = InstrumentationClassAttribute.GetAttribute(type);
string name = attr.ManagedBaseClassName;
if(name != null)
return name;
InstrumentationClassAttribute attrParent = InstrumentationClassAttribute.GetAttribute(type.BaseType);
if(null == attrParent)
{
switch(attr.InstrumentationType)
{
case InstrumentationType.Abstract:
return null;
case InstrumentationType.Instance:
return null;
case InstrumentationType.Event:
return "__ExtrinsicEvent";
default:
break;
}
}
return GetMemberName(type.BaseType);
}
} | class | c# | 237 |
public override string ToString()
{
if (string.IsNullOrWhiteSpace(Namespace))
{
return ClassName.ToString();
}
return $"{Namespace}.{ClassName}";
} | function | c# | 238 |
public bool HasDuplicateRings()
{
for (IEnumerator nodeIt = nodeGraph.NodeIterator();
nodeIt.MoveNext(); )
{
RelateNode node = (RelateNode) nodeIt.Current;
for (IEnumerator i = node.Edges.Iterator(); i.MoveNext(); )
{
EdgeEndBundle eeb = (EdgeEndBundle) i.Current;
if (eeb.EdgeEnds.Count > 1)
{
invalidPoint = eeb.Edge.GetCoordinate(0);
return true;
}
}
}
return false;
} | function | c# | 239 |
public long skip(long n) throws IOException {
if (vbits == 0) {
return in.skip(n);
} else {
int b = (vbits + 7) / 8;
in.skip(n - b);
int vbits = this.vbits;
resetBuffer();
fillBuffer(vbits);
return n;
}
} | function | java | 240 |
def optimize(self, bounds, tol=1.0e-6, verbose=False):
if len(bounds) != self.ndims + 1:
raise ValueError("Number of bounds (min, max) pairs not equal to N dimensions + 1")
self.normal_bounds = self._convert_bounds(bounds)
result = differential_evolution(lambda *args: -self._lnpost(*args), self.normal_bounds, tol=tol)
if verbose:
print(result)
self.normal = result["x"][:-1]
self.norm_scat = np.fabs(result["x"][-1])
self.norm_scat = self.bessel_cochran(self.norm_scat)
self.coords, self.vert_scat = self.compute_cartesian()
return self.coords, self.vert_scat, -np.atleast_1d(result["fun"])[0] | function | python | 241 |
def dispersion(x, y, bins, method):
d, k = [np.zeros(len(bins)-1) for i in range(2)]
for i in range(len(bins)-1):
m = (bins[i] < x) * (x < bins[i+1])
if method == "std":
d[i] = np.std(y[m])
if method == "mad":
d[i] = 1.5*np.median(np.abs(y[m] - np.median(y[m])))
k[i] = sps.kurtosis(y[m])
return d, k | function | python | 242 |
public class RuleMaintenanceActionRequestCodeValuesFinder extends ActionRequestCodeValuesFinder {
/**
* @see org.kuali.rice.krad.keyvalues.KeyValuesFinder#getKeyValues()
*/
@Override
public List<KeyValue> getKeyValues() {
final List<KeyValue> actionRequestCodes = new ArrayList<KeyValue>();
// Acquire the Kuali form, and return the super class' result if the form is not a Kuali maintenance form.
final KualiForm kForm = KNSGlobalVariables.getKualiForm();
if (!(kForm instanceof KualiMaintenanceForm)) {
return super.getKeyValues();
}
// Acquire the Kuali maintenance form's document and its rule template.
final MaintenanceDocument maintDoc = (MaintenanceDocument) ((KualiMaintenanceForm) kForm).getDocument();
final RuleTemplateBo ruleTemplate = ((RuleBaseValues) maintDoc.getNewMaintainableObject().getBusinessObject()).getRuleTemplate();
// Ensure that the rule template is defined.
if (ruleTemplate == null) {
throw new RuntimeException("Rule template cannot be null for document ID " + maintDoc.getDocumentNumber());
}
// get the options to check for, as well as their related KEW constants.
final RuleTemplateOptionBo[] ruleOpts = {ruleTemplate.getAcknowledge(), ruleTemplate.getComplete(),
ruleTemplate.getApprove(), ruleTemplate.getFyi()};
final String[] ruleConsts = {KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, KewApiConstants.ACTION_REQUEST_COMPLETE_REQ,
KewApiConstants.ACTION_REQUEST_APPROVE_REQ, KewApiConstants.ACTION_REQUEST_FYI_REQ};
// Add the rule options to the list if they are not defined (true by default) or if they are explicitly set to true.
for (int i = 0; i < ruleOpts.length; i++) {
if (ruleOpts[i] == null || ruleOpts[i].getValue() == null || "true".equals(ruleOpts[i].getValue())) {
actionRequestCodes.add(new ConcreteKeyValue(ruleConsts[i], KewApiConstants.ACTION_REQUEST_CODES.get(ruleConsts[i])));
}
}
return actionRequestCodes;
}
} | class | java | 243 |
def sierpinski_triangle(order, length, upper_left_x, upper_left_y):
pause(10)
line1 = GLine(upper_left_x, upper_left_y, upper_left_x+length, upper_left_y)
line2 = GLine(upper_left_x, upper_left_y, upper_left_x+length*0.5, upper_left_y+length*0.866)
line3 = GLine(upper_left_x+length, upper_left_y, upper_left_x+length*0.5, upper_left_y+length*0.866)
window.add(line1)
window.add(line2)
window.add(line3)
if order == 1:
return
else:
sierpinski_triangle(order-1, length*0.5, upper_left_x, upper_left_y)
sierpinski_triangle(order-1, length*0.5, upper_left_x+length*0.5, upper_left_y)
sierpinski_triangle(order-1, length*0.5, upper_left_x+length*0.25, upper_left_y+length*0.433) | function | python | 244 |
pub unsafe fn convert<X>(mut self) -> TwoUnorderedVecs<X> {
assert_eq!(core::mem::size_of::<X>(), core::mem::size_of::<T>());
assert_eq!(core::mem::align_of::<X>(), core::mem::align_of::<T>());
let ptr = self.inner.as_mut_ptr();
let len = self.inner.len();
let cap = self.inner.capacity();
let first_length = self.first_length;
core::mem::forget(self);
let inner = Vec::from_raw_parts(ptr as *mut _, len, cap);
TwoUnorderedVecs {
inner,
first_length,
}
} | function | rust | 245 |
def _check_finished(self, pr, build_number):
pr_number = str(pr.number)
log.info('CI for PR %s: FINISHED', pr_number)
project_name_full = self._ci_job_name + '/PR-' + pr_number
build_output = self._jenkins.get_build_console_output(project_name_full, build_number)
if _CI_BUILD_FAIL_MESSAGE not in build_output \
and _CI_BUILD_SUCCESS_MESSAGE not in build_output:
message = ('ONNX CI job for PR #{} finished but no tests success or fail '
'confirmation is present in console output!'.format(pr_number))
self._queue_message(message, message_severity='error', pr=pr) | function | python | 246 |
def _create_resource(
cls,
client: utils.MetadataClientWithOverride,
parent: str,
schema_title: str,
state: gca_execution.Execution.State = gca_execution.Execution.State.RUNNING,
resource_id: Optional[str] = None,
display_name: Optional[str] = None,
schema_version: Optional[str] = None,
description: Optional[str] = None,
metadata: Optional[Dict] = None,
) -> gca_execution.Execution:
gapic_execution = gca_execution.Execution(
schema_title=schema_title,
schema_version=schema_version,
display_name=display_name,
description=description,
metadata=metadata if metadata else {},
state=state,
)
return client.create_execution(
parent=parent,
execution=gapic_execution,
execution_id=resource_id,
) | function | python | 247 |
Node *NodeBody_new(NodeArray *node_array, int tokens) {
Node *node = (Node *)malloc(sizeof(Node));
node->type = NodeType_BODY;
node->body = node_array;
node->body_tokens = tokens;
return node;
} | function | c | 248 |
func (s *Server) JWTInterceptor() grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
authLock.RLock()
shouldAuthenticate := !noAuthPaths[info.FullMethod]
authLock.RUnlock()
if shouldAuthenticate {
if err := s.authorize(ctx); err != nil {
return nil, err
}
}
h, err := handler(ctx, req)
log.Debugf("Request - Method: %s, Error: %v\n", info.FullMethod, err)
return h, err
}
} | function | go | 249 |
private boolean hasLangPref() {
ContentResolver resolver = getContentResolver();
String language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG);
if ((language == null) || (language.length() < 1)) {
return false;
}
String country = Settings.Secure.getString(resolver, TTS_DEFAULT_COUNTRY);
if (country == null) {
return false;
}
String variant = Settings.Secure.getString(resolver, TTS_DEFAULT_VARIANT);
if (variant == null) {
return false;
}
return true;
} | function | java | 250 |
_setVisibilityObjects(layerId, objectIds, visibility = false) {
return new Ember.RSVP.Promise((resolve, reject) => {
if (Ember.isArray(objectIds)) {
let [layer, leafletObject] = this._getModelLeafletObject(layerId);
if (Ember.isNone(layer)) {
return reject(`Layer '${layerId}' not found.`);
}
if (!Ember.isNone(leafletObject) && typeof leafletObject._setVisibilityObjects === 'function') {
leafletObject._setVisibilityObjects(objectIds, visibility).then((result) => {
resolve(result);
});
} else {
return reject('Layer type not supported');
}
}
});
} | function | javascript | 251 |
public abstract class EffectMatricesEffect : Effect, IEffectMatrices
{
#region Private Fields
private Matrix _projection;
private Matrix _view;
private Matrix _world;
private Boolean _dirty;
private EffectParameter _worldViewProjectionParam;
#endregion
#region Public Properties
public Matrix Projection
{
get => _projection;
set
{
_projection = value;
_dirty = true;
}
}
public Matrix View
{
get => _view;
set
{
_view = value;
_dirty = true;
}
}
public Matrix World
{
get => _world;
set
{
_world = value;
_dirty = true;
}
}
#endregion
#region Constructor
public EffectMatricesEffect(GraphicsDevice graphicsDevice, Byte[] effectCode) : base(graphicsDevice, effectCode)
{
_worldViewProjectionParam = this.Parameters["WorldViewProjection"];
}
#endregion
#region Helper Methods
protected override void OnApply()
{
if (_dirty)
{
_worldViewProjectionParam.SetValue(
Matrix.Multiply(
Matrix.Multiply(
this.World,
this.View),
this.Projection));
_dirty = false;
}
}
#endregion
} | class | c# | 252 |
def _validate_permissions(self, block, prev_state_root):
block_header = BlockHeader()
block_header.ParseFromString(block.header)
if block_header.block_num != 0:
for batch in block.batches:
if not self._permission_verifier.is_batch_signer_authorized(
batch, prev_state_root, from_state=True):
return False
return True | function | python | 253 |
def command(self,
command,
timeout=60,
expected_prompt=None):
status = True
try:
if len(command) + 50 > self.command_width:
logging.debug(u'Resizing pty!')
self.command_width = len(command) + 50
self.shell.resize_pty(width=self.command_width)
self.shell.send(u'\n')
self.__receive(timeout=timeout)
if expected_prompt and expected_prompt not in self.prompts:
self.prompts.append(expected_prompt)
self.shell.send(command + u'\n')
logging.debug(u'command sent ({c})...'.format(c=command))
self.__receive(timeout=timeout)
resp = self.buffer.splitlines()
logging.debug(resp)
try:
resp.remove(command)
logging.debug(resp)
except ValueError:
pass
if self.log:
self.log_response(resp)
except socket.error as err:
logging.error(err)
resp = None
status = False
self.disconnect()
return resp, status | function | python | 254 |
public class MergeIntervals {
public static List<Interval> merge(List<Interval> intervals) {
List<Interval> mergedIntervals = new LinkedList<>();
if (intervals.size() < 2) {
return intervals;
}
intervals.sort(Comparator.comparingInt(a -> a.start));
Iterator<Interval> intervalsIterator = intervals.iterator();
Interval first = intervalsIterator.next();
int start = first.start;
int end = first.end;
while (intervalsIterator.hasNext()) {
Interval next = intervalsIterator.next();
if (next.start < end) {
end = Math.max(end, next.end);
} else {
mergedIntervals.add(new Interval(start, end));
start = next.start;
end = next.end;
}
}
mergedIntervals.add(new Interval(start, end));
return mergedIntervals;
}
public static void main(String[] args) {
List<Interval> input = new ArrayList<>();
input.add(new Interval(1, 4));
input.add(new Interval(2, 5));
input.add(new Interval(7, 9));
System.out.print("Merged intervals: ");
for (Interval interval : MergeIntervals.merge(input)) {
System.out.print("[" + interval.start + "," + interval.end + "] ");
}
System.out.println();
input = new ArrayList<>();
input.add(new Interval(6, 7));
input.add(new Interval(2, 4));
input.add(new Interval(5, 9));
System.out.print("Merged intervals: ");
for (Interval interval : MergeIntervals.merge(input)) {
System.out.print("[" + interval.start + "," + interval.end + "] ");
}
System.out.println();
input = new ArrayList<>();
input.add(new Interval(1, 4));
input.add(new Interval(2, 6));
input.add(new Interval(3, 5));
System.out.print("Merged intervals: ");
for (Interval interval : MergeIntervals.merge(input)) {
System.out.print("[" + interval.start + "," + interval.end + "] ");
}
System.out.println();
}
} | class | java | 255 |
public class PartCover:
ToolTask
{
protected override string GenerateFullPathToTool()
{
string versionValueName=null;
for (int i=0; i<_PartCoverComponentRegValues.Length; ++i)
if (_PartCoverComponentRegValues[i, 0]==ToolsVersion)
{
versionValueName=_PartCoverComponentRegValues[i, 1];
break;
}
if (versionValueName==null)
return ToolPath;
string subKeyName=string.Format(
CultureInfo.InvariantCulture,
@"{0}{1}\",
_PartCoverComponentRegKey,
versionValueName
);
RegistryKey key=Registry.LocalMachine.OpenSubKey(subKeyName);
if (key==null)
{
Log.LogError("PartCover {0} could not be found (registry key \"{1}\" is missing)", ToolsVersion, subKeyName);
return null;
}
string rd=(string)key.GetValue(versionValueName);
if (string.IsNullOrEmpty(rd))
{
Log.LogError("PartCover root directory could not be found");
return null;
}
return Path.Combine(rd, ToolName);
}
protected override string GenerateCommandLineCommands()
{
CommandLineBuilder builder=new CommandLineBuilder();
builder.AppendSwitchIfNotNull("--output ", Output);
builder.AppendSwitch("--register");
builder.AppendSwitchIfNotNull("--target ", Target);
builder.AppendSwitchIfNotNull("--target-work-dir ", TargetWorkingDir);
if (!string.IsNullOrEmpty(TargetArgs))
builder.AppendSwitch(
string.Concat(
"--target-args \"",
TargetArgs.Replace("\"", "\\\""),
"\""
)
);
if (Include!=null)
foreach (ITaskItem ti in Include)
builder.AppendSwitchUnquotedIfNotNull("--include ", ti);
if (Exclude!=null)
foreach (ITaskItem ti in Exclude)
builder.AppendSwitchUnquotedIfNotNull("--exclude ", ti);
return builder.ToString();
}
protected override string GetWorkingDirectory()
{
string ret=null;
if (TargetWorkingDir!=null)
ret=TargetWorkingDir.GetMetadata("FullPath");
if (string.IsNullOrEmpty(ret))
ret=base.GetWorkingDirectory();
return ret;
}
protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
{
if (_OutputRegex.IsMatch(singleLine))
{
base.LogEventsFromTextOutput(singleLine, MessageImportance.Low);
_ToolStarted=true;
return;
}
base.LogEventsFromTextOutput(singleLine, (_ToolStarted?MessageImportance.Normal:MessageImportance.Low));
}
public ITaskItem[] Include
{
get;
set;
}
public ITaskItem[] Exclude
{
get;
set;
}
public ITaskItem Output
{
get;
set;
}
[Required]
public ITaskItem Target
{
get;
set;
}
public ITaskItem TargetWorkingDir
{
get;
set;
}
public string TargetArgs
{
get;
set;
}
[Required]
public string ToolsVersion
{
get
{
return _ToolsVersion;
}
set
{
_ToolsVersion=value;
}
}
protected override string ToolName
{
get
{
return "PartCover.exe";
}
}
private string _ToolsVersion="4.0";
private bool _ToolStarted;
private static Regex _OutputRegex=new Regex(@"^(\[\d{5}\] \[\d{5}\] |\s*<)", RegexOptions.Compiled | RegexOptions.Multiline);
private const string _PartCoverComponentRegKey=@"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\";
private static readonly string[,] _PartCoverComponentRegValues={
{ "4.0", "82FDEC2C38A025247A99E66B5F26490D" },
{ "3.5", "22814841D06BA814A97DF67A13409D72" },
{ "3.0", "22814841D06BA814A97DF67A13409D72" },
{ "2.0", "22814841D06BA814A97DF67A13409D72" }
};
} | class | c# | 256 |
[Ignore("obsolete work, mark for removal")]
[Obsolete("marked for removal")]
[TestMethod]
public void PowerSpectrumDensityTest()
{
var inputPath = @"C:\Users\kholghim\Mahnoosh\Liz\TrainSet\";
var resultPsdPath = @"C:\Users\kholghim\Mahnoosh\Liz\PowerSpectrumDensity\train_LogPSD.bmp";
var resultNoiseReducedPsdPath = @"C:\Users\kholghim\Mahnoosh\Liz\PowerSpectrumDensity\train_LogPSD_NoiseReduced.bmp";
if (Directory.GetFiles(inputPath, "*", SearchOption.AllDirectories).Length == 0)
{
throw new ArgumentException("The folder of recordings is empty...");
}
int nq = new AudioRecording(Directory.GetFiles(inputPath, "*.wav")[0]).Nyquist;
int nyquist = nq;
int frameSize = 1024;
int finalBinCount = 512;
int hertzInterval = 1000;
FreqScaleType scaleType = FreqScaleType.Linear;
var settings = new SpectrogramSettings()
{
WindowSize = frameSize,
WindowOverlap = 0.1028,
MelBinCount = 256,
DoMelScale = (scaleType == FreqScaleType.Mel) ? true : false,
NoiseReductionType = NoiseReductionType.None,
NoiseReductionParameter = 0.0,
};
var attributes = new SpectrogramAttributes()
{
NyquistFrequency = nyquist,
Duration = TimeSpan.FromMinutes(1440),
};
List<double[]> psd = new List<double[]>();
foreach (string filePath in Directory.GetFiles(inputPath, "*.wav"))
{
FileInfo fileInfo = filePath.ToFileInfo();
if (fileInfo.Length != 0)
{
var recording = new AudioRecording(filePath);
settings.SourceFileName = recording.BaseName;
var spectrogram = new EnergySpectrogram(settings, recording.WavReader);
psd.Add(MatrixTools.GetColumnAverages(spectrogram.Data));
}
}
var psdMatrix = psd.ToArray().ToMatrix();
var logPsd = MatrixTools.Matrix2LogValues(psdMatrix);
Csv.WriteMatrixToCsv(new FileInfo(@"C:\Users\kholghim\Mahnoosh\Liz\PowerSpectrumDensity\logPsd.csv"), logPsd);
var image = DecibelSpectrogram.DrawSpectrogramAnnotated(logPsd, settings, attributes);
image.Save(resultPsdPath);
var noiseReducedLogPsd = PcaWhitening.NoiseReduction(logPsd);
Csv.WriteMatrixToCsv(new FileInfo(@"C:\Users\kholghim\Mahnoosh\Liz\PowerSpectrumDensity\logPsd_NoiseReduced.csv"), logPsd);
var image2 = DecibelSpectrogram.DrawSpectrogramAnnotated(noiseReducedLogPsd, settings, attributes);
image2.Save(resultNoiseReducedPsdPath);
} | function | c# | 257 |
func (c *Memory) Get(ctx context.Context, key string) ([]byte, time.Duration, error) {
c.mx.RLock()
v, ok := c.values[key]
c.mx.RUnlock()
if !ok {
return nil, 0, fmt.Errorf("key %q: %w", key, ErrNotFound)
}
var ttl time.Duration
if !v.expiresAt.IsZero() {
ttl = time.Until(v.expiresAt)
if ttl <= 0 {
c.forget(key)
return nil, 0, fmt.Errorf("key %q: %w", key, ErrNotFound)
}
}
value := make([]byte, len(v.value))
copy(value, v.value)
return value, ttl, nil
} | function | go | 258 |
def is_containers_started(self, pod_id, containers_counter,
namespace=DEFAULT_NAMESPACE):
events_list = self.client_core.list_namespaced_event(
namespace=namespace, field_selector=f"involvedObject.uid=={pod_id}")
for event in events_list.items:
if AUTHENTICATION_EXCEPTION in event.message:
raise K8sAuthenticationException(message=event.message)
if PULLING_EXCEPTION in event.message or PULLING_FAIL in event.message:
raise K8sPullingException(message=event.message)
if CREATED_SUCCESSFULLY in event.message:
containers_counter -= 1
return not containers_counter | function | python | 259 |
bool
CDs::reinsert(CDo *odesc, const BBox *nBB)
{
if (!odesc)
return (false);
if (odesc->type() == CDINSTANCE)
setInstNumValid(false);
CDtree *l = db_find_layer_head(odesc->ldesc());
if (l) {
if (l->is_deferred()) {
if (nBB && odesc->oBB() != *nBB)
odesc->set_oBB(*nBB);
if (l->insert(odesc))
CD()->ifObjectInserted(this, odesc);
return (true);
}
if (odesc->in_db()) {
if (!l->remove(odesc))
return (false);
}
if (nBB && odesc->oBB() != *nBB) {
odesc->set_oBB(*nBB);
setBBvalid(false);
}
if (l->insert(odesc)) {
CD()->ifObjectInserted(this, odesc);
return (true);
}
return (false);
}
if (nBB && odesc->oBB() != *nBB) {
odesc->set_oBB(*nBB);
setBBvalid(false);
}
if (db_insert(odesc)) {
CD()->ifObjectInserted(this, odesc);
return (true);
}
return (false);
} | function | c++ | 260 |
class OSCRecordSigReader:
"""Reads a recording made by OSCRecord as a sig tree with the same API as the OSCTosig class.
Reads at a steady 24 fps by default but supports external frame advance triggers."""
def __init__(self, foldername, framerate=24, trigsource=None, buffersize=None):
buffersize = framerate if buffersize is None else buffersize
# if this is constructed with an external trigsource, bypass the start method
self._needs_play = trigsource is None
self.trigsource = Metro(1/framerate) if trigsource is None else trigsource
self._root_node = _OSCNode(idle_timer=False, ramp=1/framerate)
self._reader = OSCRecordReader(foldername, buffersize)
def set_tree():
node = self._root_node
current_branch = self._reader.current_data
def set_node(branch, node):
if type(branch) in [int, list, float] :
node.setValue(branch)
else:
for k in branch:
set_node(branch[k], node[k])
set_node(current_branch, node)
if self._reader.next() == "ended":
self.end_trig.play()
self.tf = TrigFunc (self.trigsource, set_tree)
self.end_trig = Trig()
def start(self):
if self._needs_play:
self.trigsource.play()
def __getitem__(self, key):
key = str(key)
return self._root_node["/"][key] | class | python | 261 |
public static void ensureHasBackpackLayer(Class<? extends EntityLivingBase> entityClass) {
if (!_hasLayerChecked.add(entityClass)) return;
RenderManager manager = Minecraft.getMinecraft().getRenderManager();
Render<?> render = manager.getEntityClassRenderObject(entityClass);
if (!(render instanceof RenderLivingBase)) return;
((RenderLivingBase<?>)render).addLayer(new RendererBackpack.Layer((RenderLivingBase<?>)render));
} | function | java | 262 |
private final void checkStateBeforeMutator() {
if (this.closed.get()) {
throw new IllegalStateException("Already closed");
}
if (this.started.get()) {
throw new IllegalStateException("Already started");
}
} | function | java | 263 |
public abstract class AbstractServlet extends HttpServlet {
/**
* Logic layer object - validator.
*/
protected static final Validator<User> VALIDATOR = DatabaseValidator.getInstance();
/**
* Logic layer object - servlet actions dispatch.
*/
protected static final ActionsDispatch DISPATCH = new ActionsDispatch(VALIDATOR).init();
/**
* Logger.
*/
private static final Logger LOG = LogManager.getLogger(AbstractServlet.class);
/**
* Main directory where views are stored.
*/
private static final String VIEWS_DIR = "/WEB-INF/views";
/**
* Returns views directory path.
*
* @return Views directory path.
*/
protected String getViewsDir() {
return VIEWS_DIR;
}
/**
* Is called when servlet stops working.
* Closes connection to database.
*/
@Override
public void destroy() {
try {
VALIDATOR.close();
} catch (Exception e) {
LOG.error(e.getStackTrace());
}
}
} | class | java | 264 |
protected final MethodNode createMethod(int maxLocals, int maxStack) {
MethodNode method = this.info.getMethod();
MethodNode accessor = new MethodNode(ASM.API_VERSION, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name,
method.desc, null, null);
accessor.visibleAnnotations = new ArrayList<AnnotationNode>();
accessor.visibleAnnotations.add(this.info.getAnnotationNode());
accessor.maxLocals = maxLocals;
accessor.maxStack = maxStack;
return accessor;
} | function | java | 265 |
public class CreateVariables extends AirsJavaDatabaseApp implements Runnable {
private enum VariableCounters {
NORATINGS, NOTRAILINGRATINGS, PLAYERS, TOURNAMENTS, GAMES, NOTRAILING
}
private static final Log LOGGER = LogFactory.getLog(CreateVariables.class);
private static boolean f_incremental;
private Counter<VariableCounters> f_counter = new Counter<VariableCounters>(VariableCounters.class);
public CreateVariables(String[] p_args) {
super(p_args);
}
/**
* @param args
*/
public static void main(String[] p_args) {
CreateVariables l_variables = new CreateVariables(p_args);
setIncremental(l_variables.switchExists(p_args, "--incremental", "-i"));
ISqlConnection l_connection = RankConnection.getInstance();
l_variables.initializeDatabase(l_connection);
l_variables.loadModels();
LOGGER.info("Loading Values");
GameExtModel.getInstance().doBlockUpdate(l_variables);
l_variables.dumpStastics(System.out);
}
protected void dumpCounts() {
LOGGER.info(f_counter.toString());
}
/**
* Assign the rating of the player to every game they played in.
*/
protected void processRatingVariable() {
LOGGER.info("Process Rating Variable");
// create a variable that gives the strength of the opponent played by a player
for (RankPlayer l_player : PlayerModel.getInstance().getElements()) {
/*
* Process all game where this player is the player
*/
processRating(GameModel.getInstance().getContentAsList(l_player), l_player);
}
}
/**
* Determine the rating value for a player at each game.
*
* @param p_ratingVariable
* @param p_content
* @param p_gameStrengthVariable
* @param p_player
*/
protected void processRating(List<RankGame> p_content, RankPlayer p_player) {
List<RankRating> l_contentAsList = RatingModel.getInstance().getContentAsList(p_player);
l_contentAsList.sort((x, y) -> x.getDate().compareTo(y.getDate()));
p_content.sort(new RankGameOrder());
Deque<RankRating> l_ratingIterator = l_contentAsList.isEmpty()?null:new ArrayDeque<RankRating>(l_contentAsList);
// store the current rating/sigma tuple in l_current
Tuple<Double, Double> l_current = new Tuple<Double, Double>();
for (RankGame l_game : p_content) {
// get the reverse game associated with this game
RankGame l_reverseGame = GameReverseModel.getInstance().getElement(l_game.getId()).getReverse();
// get the ratings for the current game
l_current = getGameRating(l_current, l_game, l_ratingIterator);
/**
* Tuple of leading Rating, Sigma.
*
* If no rating exists for the player, the rank they played at is used.
*/
Tuple<Double, Double> l_actual = l_current.getPrimary()==null?new Tuple<Double, Double>(l_game.getRank().toRating(),0d):l_current;
/**
* Tuple of trailing Rating, Sigma
*/
Tuple<Double, Double> l_gameTrailingRating = l_ratingIterator==null || l_ratingIterator.isEmpty()?new Tuple<Double, Double>():l_ratingIterator.peekFirst().toTupleDouble();
if (l_actual.getPrimary()!=null) {
// Place players rating
modifyGame(l_game).setPlayersRating(l_actual.getPrimary());
modifyGame(l_game).setPlayersSigma(l_actual.getSecondary());
// update opponents rating for the reversed game
modifyGame(l_reverseGame).setOpponentRating(l_actual.getPrimary());
modifyGame(l_reverseGame).setOpponentSigma(l_actual.getSecondary());
modifyGame(l_reverseGame).setQuality(l_reverseGame.realRating(l_actual.getPrimary()));
check(l_game);
check(l_reverseGame);
// Place opponents rating for reversed game
if (l_gameTrailingRating.getPrimary()!=null) {
// Place players rating
modifyGame(l_game).setPlayersTrailingRating(l_gameTrailingRating.getPrimary());
modifyGame(l_game).setPlayersTrailingSigma(l_gameTrailingRating.getSecondary());
// update opponents rating for the reversed game
modifyGame(l_reverseGame).setOpponentsTrailingRating(l_gameTrailingRating.getPrimary());
modifyGame(l_reverseGame).setOpponentsTrailingSigma(l_gameTrailingRating.getSecondary());
modifyGame(l_reverseGame).setTrailingQuality(l_reverseGame.realRating(l_gameTrailingRating.getPrimary()));
checkTrailing(l_game);
checkTrailing(l_reverseGame);
} else {
f_counter.count(VariableCounters.NOTRAILING);
LOGGER.trace("Unknown trailing rating for game: "+l_reverseGame);
}
}
}
}
/**
* Check if the game has a rating for both players.
*
* If both players have a rating, then we can calculate the probability of the game.
*
* @param p_game
*/
protected void check(RankGame p_game) {
RankGameExt l_gameExt = GameExtModel.getInstance().getElement(p_game);
if (l_gameExt.getPlayersRating()!=null && l_gameExt.getOpponentRating()!=null) {
l_gameExt.setProbability(p_game.calculateProbability(
l_gameExt.getPlayersRating(), l_gameExt.getOpponentRating()));
}
}
/**
* Check if the game has a trailing rating for both players.
*
* If both players have a trailing rating, then we can calculate the trailing probability of the game.
*
* @param p_game
*/
protected void checkTrailing(RankGame p_game) {
RankGameExt l_gameExt = GameExtModel.getInstance().getElement(p_game);
if (l_gameExt.getPlayersTrailingRating()!=null && l_gameExt.getOpponentsTrailingRating()!=null) {
l_gameExt.setTrailingProbability(p_game.calculateProbability(
l_gameExt.getPlayersTrailingRating(), l_gameExt.getOpponentsTrailingRating()));
}
}
/**
* Helper function to get the RankGameExt associated with p_game.
*/
protected RankGameExt modifyGame(RankGame p_game) {
RankGameExt l_element = GameExtModel.getInstance().getElement(p_game);
return l_element;
}
/**
* Return a player's rating and sigma on the day a game is played.
*
* @param p_current not null, the player's current rating, sigma tuple
* @param p_game not null, the RankGame in question
* @param p_ratingQue can be null, a Deque<RankRating> that contains all the ratings that are left (in date order); if null no ratings exist for player
*
* @return a Tuple of Rating and Sigma.
*/
protected Tuple<Double, Double> getGameRating(Tuple<Double, Double> p_current,
RankGame p_game, Deque<RankRating> p_ratingQue) {
Tuple<Double, Double> l_retValue = p_current;
Date l_gameDate = p_game.getDate();
if (l_gameDate!=null && p_ratingQue!=null) {
while (!p_ratingQue.isEmpty() && isBefore(p_ratingQue.peekFirst().getDate(), l_gameDate)) {
l_retValue = p_ratingQue.pollFirst().toTupleDouble();
}
}
return l_retValue;
}
protected boolean isBefore(Date p_rankDate, Date p_gameDate) {
return p_rankDate==null || p_rankDate.before(p_gameDate);
}
protected RankRating getNextRating(Iterator<RankRating> p_ratingIterator) {
RankRating l_retVal = p_ratingIterator.hasNext()?p_ratingIterator.next():null;
if (l_retVal!=null && l_retVal.getDate()==null) {
l_retVal = getNextRating(p_ratingIterator);
}
return l_retVal;
}
protected void loadModels() {
LOGGER.info("Loading Players");
PlayerModel.getInstance().loadModel("");
LOGGER.info("Loading Tournament");
TournamentModel.getInstance().loadModel("");
LOGGER.info("Loading Game");
GameModel.getInstance().loadModel(null);
LOGGER.info("Load Game Links");
GameReverseModel.getInstance().loadModel(null);
LOGGER.info("Loading Rating");
RatingModel.getInstance().loadModel(null);
}
/**
* @return the f_incremental
*/
public static boolean isIncremental() {
return f_incremental;
}
/**
* @param p_f_incremental the f_incremental to set
*/
public static void setIncremental(boolean p_incremental) {
f_incremental = p_incremental;
}
@Override
public void run() {
processRatingVariable();
dumpCounts();
}
} | class | java | 266 |
public async Task<bool> EditCommentAsync(int id, string message)
{
IdValidator idValidator = new IdValidator();
idValidator.ValidateAndThrow(id);
CommentMessageValidator messageValidator = new CommentMessageValidator();
messageValidator.ValidateAndThrow(message);
using (Scope)
{
try
{
Scope.Begin();
bool result = await Scope.Comments.UpdateAsync(id, message);
Scope.Commit();
return result;
}
catch (Exception e)
{
Scope.Rollback();
throw e;
}
}
} | function | c# | 267 |
def segment_synchronization(pos_start, pos_end, vel_start, vel_end,
abs_max_pos, abs_max_vel, abs_max_acc, abs_max_jrk):
rospy.logdebug(">> pos_start:\n{}".format(pos_start))
rospy.logdebug(">> pos_end:\n{}".format(pos_end))
rospy.logdebug(">> vel_start:\n{}".format(vel_start))
rospy.logdebug(">> vel_end:\n{}".format(vel_end))
pos_diff = [pf-pi for pi, pf in zip(pos_start, pos_end)]
motion_dir = []
n_jts = len(pos_diff)
for jt in range(n_jts):
motion_dir.append(traj.motion_direction(vel_start[jt], vel_end[jt], pos_diff[jt]))
min_motion_time = [ ]
for jt in range(n_jts):
tj_2vf, ta_2vf, t_jrk, t_acc, t_vel = traj.traj_segment_planning(0.0, abs(pos_diff[jt]), abs(vel_start[jt]), abs(vel_end[jt]),
abs_max_vel[jt], abs_max_acc[jt], abs_max_jrk[jt])
min_time = 2*tj_2vf + ta_2vf + 4*t_jrk + 2*t_acc + t_vel
min_motion_time.append(min_time)
ref_jt = min_motion_time.index(max(min_motion_time))
min_sync_time = max(min_motion_time)
syn_t = min_sync_time
rospy.logdebug(">> syn_t : {} ".format(syn_t))
rospy.logdebug(">> ref_jt: {} ".format(ref_jt))
rospy.logdebug(">> min_T : {} ".format(min_motion_time))
phase_dur_jt = []
phase_jrk_jt = []
for jt in range(n_jts):
rospy.logdebug("\n\n>> jt:{}, PD: {}, v_start:{}, v_end:{}".format(jt, pos_diff[jt], vel_start[jt], vel_end[jt]))
p_diff = abs(pos_diff[jt])
v_start = abs(vel_start[jt])
v_end = abs(vel_end[jt])
if jt == ref_jt:
jrk_sign_dur = traj.calculate_jerk_sign_and_duration(0.0, p_diff, v_start, v_end,
abs_max_pos[jt], abs_max_vel[jt], abs_max_acc[jt], abs_max_jrk[jt])
else:
jrk_sign_dur = synchronize_joint_motion(syn_t, p_diff, v_start, v_end,
abs_max_pos[jt], abs_max_vel[jt], abs_max_acc[jt], abs_max_jrk[jt])
dur = [jsd[1] for jsd in jrk_sign_dur]
jrk = [motion_dir[jt]*jsd[0] for jsd in jrk_sign_dur]
phase_dur_jt.append(dur)
phase_jrk_jt.append(jrk)
rospy.logdebug(">> dur:{}".format(sum(dur)))
return min_sync_time, phase_dur_jt, phase_jrk_jt | function | python | 268 |
class ReceivedPing
{
public:
ReceivedPing()
{
throw std::logic_error{"ReceivedPing can't be default-constructed"};
}
ReceivedPing(QUdpSocket *pServerSocket, QHostAddress remoteAddress,
quint16 remotePort,
QSharedPointer<ServerLocation> pLocation)
: _pServerSocket{pServerSocket},
_remoteAddress{std::move(remoteAddress)},
_remotePort{remotePort},
_pLocation{std::move(pLocation)}
{
Q_ASSERT(_pServerSocket);
Q_ASSERT(_pLocation);
}
public:
HostPortKey getServerAddress() const
{
return {_pServerSocket->localAddress(), _pServerSocket->localPort()};
}
void echo() const {_pServerSocket->writeDatagram({1, 0x61}, _remoteAddress, _remotePort);}
QString getLocationId() const {return _pLocation->id();}
private:
QUdpSocket *_pServerSocket;
QHostAddress _remoteAddress;
quint16 _remotePort;
QSharedPointer<ServerLocation> _pLocation;
} | class | c++ | 269 |
private ScheduledFuture<?> handleInstantNull() {
LOGGER.debug("Handling Instant null");
ScheduledFuture<?> future = getDefaultFuture();
taskState = true;
if (taskName != null && taskLeaderElectionServiceMap.get(taskName) != null) {
taskLeaderElectionServiceMap.get(taskName).removeListener(taskLeaderChangeListener);
}
return future;
} | function | java | 270 |
def random_starts_goals_in_subsquare(n, width=10, sub_width=10):
assert n*2 <= sub_width*sub_width, f"can't place n distincts starts and goals in a sub square of size {sub_width}"
(top_x, top_y) = (random.randrange(0, width-sub_width+1), random.randrange(0, width-sub_width+1))
_start_bounds = ((top_x, top_x + sub_width), (top_y, top_y + sub_width))
_goal_bounds = ((top_x, top_x + sub_width), (top_y, top_y + sub_width))
starts = set()
while len(starts) < n:
starts.add((random.randrange(*_start_bounds[0]), random.randrange(*_start_bounds[1])))
goals = set()
while len(goals) < n:
goal = (random.randrange(*_goal_bounds[0]), random.randrange(*_goal_bounds[1]))
if goal not in starts:
goals.add(goal)
return list(starts), list(goals) | function | python | 271 |
function drupalgap_views_render_rows(variables, results, root, child, open_row, close_row) {
try {
var html = '';
for (var count in results[root]) {
if (!results[root].hasOwnProperty(count)) { continue; }
var object = results[root][count];
var row = object[child];
row._position = count;
var row_content = '';
if (variables.row_callback && function_exists(variables.row_callback)) {
row_callback = window[variables.row_callback];
row_content = row_callback(results.view, row);
}
else { row_content = JSON.stringify(row); }
html += open_row + row_content + close_row;
}
return html;
}
catch (error) { console.log('drupalgap_views_render_rows - ' + error); }
} | function | javascript | 272 |
public static Modifier makeTimedModifier(String id, Modifier template,
Turn start) {
Modifier modifier = new Modifier(id, template);
float inc = template.getIncrement();
int duration = template.getDuration();
modifier.setTemporary(template.isTemporary());
if (duration == 0) {
duration = (int)(template.getValue()/-inc);
}
modifier.setIncrement(template.getIncrementType(), inc, start,
new Turn(start.getNumber() + duration));
return modifier;
} | function | java | 273 |
public void save (FileHandle file, PixmapPacker packer, SaveParameters parameters) throws IOException {
Writer writer = file.writer(false);
int index = 0;
for (Page page : packer.pages) {
if (page.rects.size > 0) {
FileHandle pageFile = file.sibling(file.nameWithoutExtension() + "_" + (++index) + parameters.format.getExtension());
switch (parameters.format) {
case CIM:{
PixmapIO.writeCIM(pageFile, page.image);
break;
}
case PNG: {
PixmapIO.writePNG(pageFile, page.image);
break;
}
}
writer.write("\n");
writer.write(pageFile.name() + "\n");
writer.write("size: " + page.image.getWidth() + "," + page.image.getHeight() + "\n");
writer.write("format: " + packer.pageFormat.name() + "\n");
writer.write("filter: " + parameters.minFilter.name() + "," + parameters.magFilter.name() + "\n");
writer.write("repeat: none" + "\n");
for (String name : page.rects.keys()) {
writer.write(name + "\n");
Rectangle rect = page.rects.get(name);
writer.write("rotate: false" + "\n");
writer.write("xy: " + (int) rect.x + "," + (int) rect.y + "\n");
writer.write("size: " + (int) rect.width + "," + (int) rect.height + "\n");
writer.write("orig: " + (int) rect.width + "," + (int) rect.height + "\n");
writer.write("offset: 0, 0" + "\n");
writer.write("index: -1" + "\n");
}
}
}
writer.close();
} | function | java | 274 |
def send_signal(process_id, signal_to_send):
if process_id:
signal_name = signal_to_send.name
logging.info('Requested to send {} to process (id: {})'.format(signal_name, process_id))
if _send_signal_to_process_tree(process_id, signal_to_send):
logging.info('Successfully sent {} to process tree (id: {})'.format(signal_name, process_id))
elif _send_signal_to_process_group(process_id, signal_to_send):
logging.info('Successfully sent {} to group for process (id: {})'.format(signal_name, process_id))
elif _send_signal_to_process(process_id, signal_to_send):
logging.info('Successfully sent {} to process (id: {})'.format(signal_name, process_id))
else:
logging.info('Failed to send {} to process (id: {})'.format(signal_name, process_id)) | function | python | 275 |
impl<L, R> Sender for Either<L, R>
where
L: 'static + Sender,
R: 'static + Sender,
{
type Output = Either<L::Output, R::Output>;
type Scheduler = ImmediateScheduler;
fn start<Recv>(self, receiver: Recv)
where
Recv: 'static + Send + Receiver<Input = Self::Output>,
{
match self {
Either::Left(left) => left
.map(|v| -> Self::Output { Either::Left(v) })
.start(receiver),
Either::Right(right) => right
.map(|v| -> Self::Output { Either::Right(v) })
.start(receiver),
}
}
fn get_scheduler(&self) -> Self::Scheduler {
ImmediateScheduler
}
} | class | rust | 276 |
static bool checkFieldArrayStore1nr(RegType instrType, RegType targetType)
{
if (instrType == targetType)
return true;
if ((instrType == kRegTypeInteger && targetType == kRegTypeFloat) ||
(instrType == kRegTypeFloat && targetType == kRegTypeInteger))
{
return true;
}
return false;
} | function | c | 277 |
@Slf4j
public class ProfilerMiddleware implements Middleware {
/**
* Report execution of the said job
*
* @param job the running job
* @param executionTime execution time
*/
protected void report(Job job, Duration executionTime) {
log.info(
"Queue: {}, Job: {} took {}Ms",
job.getRqueueMessage().getQueueName(),
job.getId(),
executionTime.toMillis());
}
@Override
public void handle(Job job, Callable<Void> next) throws Exception {
long startTime = System.currentTimeMillis();
try {
next.call();
} finally {
report(job, Duration.ofMillis(System.currentTimeMillis() - startTime));
}
}
} | class | java | 278 |
public CourseAssistant retrieveCAById(int caID, int termForCA)
throws FileNotFoundException, NullPointerException, IOException, ParseException {
String fileToRetrieve = "SID" + caID + ".json";
CourseAssistant foundca = new CourseAssistant(caID);
boolean fileExists = false;
if (taschdCheck()) {
if (taschdTermFolderCheck()) {
if (termNumberFolderCheck(termForCA)) {
if (termNumberAssistantFolderCheck(termForCA)) {
File rootDir = new File(directory);
File taschdDirectory = new File(rootDir, TASCHDDIR);
File termsDirectory = new File(taschdDirectory, TERMS);
File termNumberDirectory = new File(termsDirectory, String.valueOf(termForCA));
File termNumberAssistantDirectory = new File(termNumberDirectory, ASSISTANTS);
String[] termNumberAssistantFolder = termNumberAssistantDirectory.list();
if (termNumberAssistantFolder != null) {
for (int i = 0; i < termNumberAssistantFolder.length; i++) {
SkillSet ss = new SkillSet();
Skill sk = null;
Course c = null;
String[] cEnroll = null;
CourseInstance ce = null;
String tInt = "";
TimeInterval ti;
WeeklySchedule ws = new WeeklySchedule();
Set<CourseInstance> sci = new HashSet<CourseInstance>();
if (FilenameUtils.getExtension(termNumberAssistantFolder[i]).equalsIgnoreCase("json")
&& termNumberAssistantFolder[i].startsWith("SID")
&& termNumberAssistantFolder[i].equalsIgnoreCase(fileToRetrieve)) {
JSONParser parser = new JSONParser();
File readFile = new File(termNumberAssistantDirectory,
termNumberAssistantFolder[i]);
Object ob1 = parser.parse(new FileReader(readFile));
JSONObject jsonObj = (JSONObject) ob1;
String firstName = (String) jsonObj.get("First Name");
String lastName = (String) jsonObj.get("Last Name");
JSONArray skillData = (JSONArray) jsonObj.get("Skills");
String email = (String) jsonObj.get("Email");
boolean grad = (boolean) jsonObj.get("Graduate Student");
JSONArray courseEnroll = (JSONArray) jsonObj.get("Course Enrolled");
JSONArray timeSched = (JSONArray) jsonObj.get("Time Schedule");
for (int j = 0; j < skillData.size(); j++) {
sk = new Skill((String) skillData.get(j));
ss.addSkill(sk);
}
for (int j = 0; j < timeSched.size(); j++) {
tInt = timeSched.get(j).toString();
ti = new TimeInterval(tInt);
ws.addInterval(ti);
}
if (courseEnroll != null) {
for (int k = 0; k < courseEnroll.size(); k++) {
cEnroll = courseEnroll.get(k).toString().split(" ");
c = new Course(cEnroll[0], cEnroll[1], cEnroll[2]);
ce = new CourseInstance(c, termForCA);
sci.add(ce);
cEnroll = null;
c = null;
ce = null;
}
}
foundca.setFirstName(firstName);
foundca.setLastName(lastName);
foundca.setEmailAddress(email);
foundca.setGraduateStudent(grad);
foundca.setPossessedSkillset(ss);
foundca.setCourseEnrolled(sci);
foundca.setWtps(ws);
}
}
} else if (!fileExists) {
System.out.println("Course Assistant file with ID number: " + caID + " does not exist.");
} else {
System.out.println("Course Assistant with ID number " + caID + " does not exist.");
}
} else {
System.out.println("ca_pool directory does not exist.");
}
} else {
System.out.println("taschd directory does not exist.");
}
}
}
return foundca;
} | function | java | 279 |
public final class Sequence<T> implements Generatable<T>
{
private final Generator<T> mInitialValue;
private final Function<? super T, ? extends T> mFunction;
public Sequence(Generator<T> initialValue, Function<? super T, ? extends T> function)
{
mInitialValue = initialValue;
mFunction = function;
}
public Sequence(T initialValue, Function<T, T> function)
{
this(() -> initialValue, function);
}
@Override
public Generator<T> generator()
{
return new org.dmfs.jems2.generator.Sequence<>(mInitialValue.next(), mFunction);
}
} | class | java | 280 |
def one_d_extract(self, data=[], file='', badpix=[], lenslet_profile='sim', rnoise=3.0):
if len(data)==0:
if len(file)==0:
print("ERROR: Must input data or file")
else:
data = pyfits.getdata(file).T
ny = self.x_map.shape[1]
nm = self.x_map.shape[0]
nx = self.sim.szx
no = self.square_profile.shape[1]
extracted_flux = np.zeros( (nm,ny,no) )
extracted_var = np.zeros( (nm,ny,no) )
pixel_inv_var = 1.0/(np.maximum(data,0) + rnoise**2)
pixel_inv_var[badpix]=0.0
for i in range(nm):
print("Extracting order: {0:d}".format(i))
if lenslet_profile == 'square':
offsets = self.square_offsets[:,i]
profile = self.square_profile
elif lenslet_profile == 'sim':
offsets = self.sim_offsets[:,i]
profile = self.sim_profile
nx_cutout = 2*int( (np.max(offsets) - np.min(offsets))/2 ) + 2
phi = np.empty( (nx_cutout,no) )
for j in range(ny):
if self.x_map[i,j] != self.x_map[i,j]:
extracted_var[i,j,:] = np.nan
continue
x_ix = int(self.x_map[i,j]) - nx_cutout//2 + np.arange(nx_cutout,dtype=int) + nx//2
for k in range(no):
phi[:,k] = np.interp(x_ix - self.x_map[i,j] - nx//2, offsets, profile[:,k])
phi[:,k] /= np.sum(phi[:,k])
ww = np.where( (x_ix >= nx) | (x_ix < 0) )[0]
x_ix[ww]=0
phi[ww,:]=0.0
col_data = data[j,x_ix]
col_inv_var = pixel_inv_var[j,x_ix]
col_inv_var_mat = np.reshape(col_inv_var.repeat(no), (nx_cutout,no) )
b_mat = phi * col_inv_var_mat
c_mat = np.dot(phi.T,phi*col_inv_var_mat)
pixel_weights = np.dot(b_mat,np.linalg.inv(c_mat))
extracted_flux[i,j,:] = np.dot(col_data,pixel_weights)
extracted_var[i,j,:] = np.dot(1.0/np.maximum(col_inv_var,1e-12),pixel_weights**2)
return extracted_flux, extracted_var | function | python | 281 |
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name="SYSTEM_CODES", uniqueConstraints = @UniqueConstraint(columnNames = "KEY_"))
public class SystemCodes extends BaseProtectedEntity
implements Serializable, Searchable, Auditable, Sortable {
private static final long serialVersionUID = -4142599915292096152L;
private static final int CATEGORY_LIST_LENGTH = 52;
@Column(name = "KEY_")
private String key;
@Column(name = "VALUE_", nullable=true)
private String value;
@Column(name = "NUMBER_VALUE", nullable=true)
private Long numberValue;
@Column (name="CATEGORY_")
private String category;
public SystemCodes() {
}
public SystemCodes(String key) {
super();
this.key = key;
}
public SystemCodes(String category, String key, String value) {
super();
setCategory(category);
this.key = key;
this.value = value;
}
public SystemCodes(String category, String key, String value, boolean skipAudit) {
super();
setCategory(category);
this.key = key;
this.value = value;
this.setSkipAudit(skipAudit);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return key +":"+value;
}
/**
* @return the key
*/
public String getKey() {
if(!StringUtil.isEmpty(key))
return key.trim();
else
return key;
}
/**
* @param key the key to set
*/
public void setKey(String key) {
if(!StringUtil.isEmpty(key))
this.key = key.trim();
}
/**
* @return the value
*/
public String getValue() {
if(!StringUtil.isEmpty(value))
return value.trim();
else
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
if(!StringUtil.isEmpty(value))
this.value = value.trim();
}
/**
* @return the category
*/
public String getCategory() {
return category;
}
/**
* @param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* @return the numberValue
*/
public synchronized Long getNumberValue() {
return this.numberValue;
}
/**
* @param numberValue the numberValue to set
*/
public synchronized void setNumberValue(Long numberValue) {
this.numberValue = numberValue;
}
public final synchronized void incrementNumberValue() {
if (numberValue == null)
numberValue = Long.valueOf(1l);
else
numberValue++;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final SystemCodes other = (SystemCodes) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
public String getTruncatedValue() {
if (value.length() > CATEGORY_LIST_LENGTH) {
return value.substring(0, CATEGORY_LIST_LENGTH - 4) + "...";
}
return value;
}
public List<String> getSearchProperties() {
List<String> props = new ArrayList<String>();
props.add("key");
props.add("value");
props.add("numberValue");
props.add("category");
props.add("owner");
props.add("ownerOffice");
return props;
}
public List<AuditableField> getAuditableFields() {
List<AuditableField> props = new ArrayList<AuditableField>();
props.add(new AuditableField("key","Key"));
props.add(new AuditableField("value","Value"));
props.add(new AuditableField("numberValue","Number Value"));
props.add(new AuditableField("category","Category"));
props.add(new AuditableField("owner","Access Owner"));
props.add(new AuditableField("ownerOffice","Access Office"));
return props;
}
public AuditableField getPrimaryField() {
return new AuditableField("value","Value");
}
public String getReference() {
// TODO Auto-generated method stub
return null;
}
} | class | java | 282 |
static void synthesizeTrivialGetter(FuncDecl *getter,
AbstractStorageDecl *storage,
TypeChecker &TC) {
auto &ctx = TC.Context;
Expr *result = createPropertyLoadOrCallSuperclassGetter(getter, storage, TC);
ASTNode returnStmt = new (ctx) ReturnStmt(SourceLoc(), result, IsImplicit);
SourceLoc loc = storage->getLoc();
getter->setBody(BraceStmt::create(ctx, loc, returnStmt, loc, true));
maybeMarkTransparent(getter, storage, TC);
if (needsToBeRegisteredAsExternalDecl(storage))
TC.Context.addedExternalDecl(getter);
} | function | c++ | 283 |
def Search(self, cls_type, list_id=-1):
options = {
"pre": self.prenotation,
"post": self.postnotation,
"wrap": self.wrap_notation}
if list_id in options:
for item in options[list_id]:
if type(item) == cls_type:
return item
else:
for item in self.prenotation:
if type(item) == cls_type:
return item
for item in self.wrap_notation:
if item.__class__.__name__ == cls_type.__name__:
return item
else:
print(item.__class__.__name__, cls_type.__name__)
for item in self.postnotation:
if type(item) == cls_type:
return item | function | python | 284 |
func (s routeStrategy) allocateHost(ctx context.Context, route *routeapi.Route) field.ErrorList {
hostSet := len(route.Spec.Host) > 0
certSet := route.Spec.TLS != nil && (len(route.Spec.TLS.CACertificate) > 0 || len(route.Spec.TLS.Certificate) > 0 || len(route.Spec.TLS.DestinationCACertificate) > 0 || len(route.Spec.TLS.Key) > 0)
if hostSet || certSet {
user, ok := apirequest.UserFrom(ctx)
if !ok {
return field.ErrorList{field.InternalError(field.NewPath("spec", "host"), fmt.Errorf("unable to verify host field can be set"))}
}
res, err := s.sarClient.Create(
authorizationutil.AddUserToSAR(
user,
&authorizationapi.SubjectAccessReview{
Spec: authorizationapi.SubjectAccessReviewSpec{
ResourceAttributes: &authorizationapi.ResourceAttributes{
Namespace: apirequest.NamespaceValue(ctx),
Verb: "create",
Group: routeapi.GroupName,
Resource: "routes",
Subresource: "custom-host",
},
},
},
),
)
if err != nil {
return field.ErrorList{field.InternalError(field.NewPath("spec", "host"), err)}
}
if !res.Status.Allowed {
if hostSet {
return field.ErrorList{field.Forbidden(field.NewPath("spec", "host"), "you do not have permission to set the host field of the route")}
}
return field.ErrorList{field.Forbidden(field.NewPath("spec", "tls"), "you do not have permission to set certificate fields on the route")}
}
}
if route.Spec.WildcardPolicy == routeapi.WildcardPolicySubdomain {
return nil
}
if len(route.Spec.Host) == 0 && s.RouteAllocator != nil {
shard, err := s.RouteAllocator.AllocateRouterShard(route)
if err != nil {
return field.ErrorList{field.InternalError(field.NewPath("spec", "host"), fmt.Errorf("allocation error: %v for route: %#v", err, route))}
}
route.Spec.Host = s.RouteAllocator.GenerateHostname(route, shard)
if route.Annotations == nil {
route.Annotations = map[string]string{}
}
route.Annotations[HostGeneratedAnnotationKey] = "true"
}
return nil
} | function | go | 285 |
public abstract class AbstractCommonAttributeInstance {
private final Long abstractFileObjectId;
private final String caseName;
private final String dataSource;
// Reference to the AbstractFile instance in the current case
// that matched on one of the common properties.
protected AbstractFile abstractFile;
/**
* Create a leaf node for attributes found in files in the current case db.
*
* @param abstractFileReference file from which the common attribute was
* found
* @param dataSource datasource where this attribute appears
* @param caseName case where this attribute appears
*/
AbstractCommonAttributeInstance(Long abstractFileReference, String dataSource, String caseName) {
this.abstractFileObjectId = abstractFileReference;
this.caseName = caseName;
this.dataSource = dataSource;
this.abstractFile = null;
}
/**
* Create a leaf node for attributes found in the central repo and not
* available in the current case db.
*/
AbstractCommonAttributeInstance() {
this(-1L, "", "");
}
/**
* Get the type of common attribute.
*
* @return
*/
public abstract CorrelationAttributeInstance.Type getCorrelationAttributeInstanceType();
/**
* Get an AbstractFile for this instance if it can be retrieved from the
* CaseDB.
*
* @return AbstractFile corresponding to this common attribute or null if it
* cannot be found (for example, in the event that this is a central
* repo file)
*/
abstract AbstractFile getAbstractFile();
/**
* Create a list of leaf nodes, to be used to display a row in the tree
* table
*
* @return leaf nodes for tree
*/
abstract DisplayableItemNode[] generateNodes();
/**
* The name of the case where this common attribute is found.
*
* @return case name
*/
String getCaseName() {
return this.caseName;
}
/**
* Get string name of the data source where this common attribute appears.
*
* @return data source name
*/
public String getDataSource() {
/**
* Even though we could get this from the CR record or the AbstractFile,
* we want to avoid getting it from the AbstractFile because it would be
* an extra database roundtrip.
*/
return this.dataSource;
}
/**
* ObjectId of the AbstractFile that is equivalent to the file from which
* this common attribute instance
*
* @return the abstractFileObjectId
*/
public Long getAbstractFileObjectId() {
return abstractFileObjectId;
}
/**
* Use this to create an AbstractCommonAttributeInstanceNode of the
* appropriate type. In any case, we'll get something which extends
* DisplayableItemNode which can be used to populate the tree.
*
* If the common attribute in question could be derived from an AbstractFile
* in the present SleuthkitCase, we can use an
* IntraCaseCommonAttributeInstanceNode which enables extended functionality
* in the context menu and in the content viewer.
*
* Otherwise, we will get an InterCaseCommonAttributeInstanceNode which
* supports only baseline functionality.
*
* @param attribute common file attribute instance form the central
* repo
* @param abstractFile an AbstractFile from which the attribute instance
* was found - applies to
* CaseDbCommonAttributeInstance only
* @param currentCaseName the name of the current case
* @param nodeType the type of the node to create for determining
* which columns to add
*
* @return the appropriate leaf node for the results tree
*
* @throws TskCoreException
*/
static DisplayableItemNode createNode(CorrelationAttributeInstance attribute, AbstractFile abstractFile, String currentCaseName, NODE_TYPE nodeType) throws TskCoreException {
DisplayableItemNode leafNode;
if (abstractFile == null) {
leafNode = new CentralRepoCommonAttributeInstanceNode(attribute, nodeType);
} else {
final String abstractFileDataSourceName = abstractFile.getDataSource().getName();
leafNode = new CaseDBCommonAttributeInstanceNode(abstractFile, currentCaseName, abstractFileDataSourceName, attribute.getCorrelationValue(), nodeType);
}
return leafNode;
}
/**
* Enum for type of results being displayed in nodes.
*/
public enum NODE_TYPE {
//depending on the type of results displayed different columns will be necessary to display complete information
CASE_NODE,
COUNT_NODE;
}
} | class | java | 286 |
public class ReadOneOrder {
public static void main(String[] args) {
try {
System.out.println("Reading order from server via rest service:");
Order order = fetchById("42");
if (order!=null) {
System.out.println(order);
}
}
catch (Exception x) {
System.err.println("check that server is running !");
x.printStackTrace();
}
}
public static Order fetchById(String id) throws Exception {
ClientResponse response = client
.resource("http://localhost:8080")
.path("orders")
.path(id)
.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus()==404) {
System.err.println("Order with id " + id + " not found (service return 404)");
return null;
}
else {
String s = response.getEntity(String.class);
return mapper.readValue(s, Order.class);
}
}
} | class | java | 287 |
def amplicon_range(self, popt=None, method='erf'):
if popt is None or np.isnan(popt[0]):
if self.success:
popt = self.popt[method]
if popt is not None:
shift = popt[-1]
if method == 'erf':
dist = scipy.stats.norm(loc=popt[2], scale=popt[3])
x = dist.rvs(size=100000)
x_scale = 10**(x + shift)
mean = np.exp(np.log(10)*popt[2] + 0.5 * np.log(10)**2 * popt[3]**2)
median = np.exp(np.log(10)*popt[2])
elif method == 'logis':
dist = scipy.stats.logistic(loc=popt[2], scale=popt[3])
x = dist.rvs(size=100000)
x_scale = 10**(x + shift)
mean = np.mean(x_scale)
median = np.median(x_scale)
elif method == 'gamma':
dist = scipy.stats.gamma(a=popt[2], scale=1/popt[3])
x = dist.rvs(size=100000)
x_scale = 10**(x + shift)
mean = np.mean(x_scale)
median = np.median(x_scale)
lower_95 = np.percentile(x_scale, 5)
upper_95 = np.percentile(x_scale, 95)
else:
print('pass')
mean = 0
median = 0
lower_95 = 0
upper_95 = 0
return [median, mean, lower_95, upper_95] | function | python | 288 |
static void insertModuleInit() {
forv_Vec(ModuleSymbol, mod, allModules) {
SET_LINENO(mod);
mod->initFn = new FnSymbol(astr("chpl__init_", mod->name));
mod->initFn->retType = dtVoid;
mod->initFn->addFlag(FLAG_MODULE_INIT);
mod->initFn->addFlag(FLAG_INSERT_LINE_FILE_INFO);
move module-level statements into module's init function
for_alist(stmt, mod->block->body) {
if (stmt->isModuleDefinition() == false) {
if (FnSymbol* deinitFn = toModuleDeinitFn(mod, stmt)) {
mod->deinitFn = deinitFn; the rest is in handleModuleDeinitFn()
} else {
mod->initFn->insertAtTail(stmt->remove());
}
}
}
mod->block->insertAtHead(new DefExpr(mod->initFn));
handleModuleDeinitFn(mod);
If the module has the EXPORT_INIT flag then
propagate it to the module's init function
if (mod->hasFlag(FLAG_EXPORT_INIT) == true ||
(fLibraryCompile == true && mod->modTag == MOD_USER)) {
mod->initFn->addFlag(FLAG_EXPORT);
mod->initFn->addFlag(FLAG_LOCAL_ARGS);
}
}
USR_STOP();
} | function | c++ | 289 |
func (c *Client) CreateDemoWAFRules(stack *Stack, site *Site) error {
reqBody := bytes.NewBuffer([]byte(`{
"name": "block access to blockme",
"description": "A simple path block to demo WAF capabilities",
"conditions": [
{
"url": {
"url": "/blockme",
"exactMatch": true
}
}
],
"action": "BLOCK",
"enabled": true
}`))
req, err := http.NewRequest(
http.MethodPost,
fmt.Sprintf(baseURL+"/waf/v1/stacks/%s/sites/%s/rules", stack.Slug, site.ID),
reqBody,
)
if err != nil {
return err
}
_, err = c.Do(req)
if err != nil {
return err
}
reqBody = bytes.NewBuffer([]byte(`{
"name": "allow access to anything",
"description": "Allow access to a path, regardless of other rules",
"conditions": [
{
"url": {
"url": "/anything",
"exactMatch": true
}
}
],
"action": "ALLOW",
"enabled": true
}`))
req, err = http.NewRequest(
http.MethodPost,
fmt.Sprintf(baseURL+"/waf/v1/stacks/%s/sites/%s/rules", stack.Slug, site.ID),
reqBody,
)
if err != nil {
return err
}
_, err = c.Do(req)
if err != nil {
return err
}
return nil
} | function | go | 290 |
void neoPointDetection(signed char* pointArr, int size){
if (size % 2 == 0) {
int numberOfPoints = (int)(size / 2);
strip.clear();
for (int i = 0; i < numberOfPoints; i++) {
signed char xPos = pointArr[(i * 2)];
signed char yPos = pointArr[(i * 2) + 1];
float theta = atan2(yPos, xPos);
float magnitude = sqrt((pow(xPos, 2) + pow(yPos, 2)));
int index = thetaToIndex(theta);
if (index > -1) {
float percentMagnitude = magnitude / maxMag;
setPixelGradient(strip, index, percentMagnitude, gradientChar, false);
}
}
strip.write();
}
} | function | c++ | 291 |
static int
dc_resume(device_t dev)
{
struct dc_softc *sc;
struct ifnet *ifp;
int s;
s = splimp();
sc = device_get_softc(dev);
ifp = &sc->arpcom.ac_if;
if (ifp->if_flags & IFF_UP)
dc_init(sc);
sc->suspended = 0;
splx(s);
return (0);
} | function | c | 292 |
def _train_epoch(self, data_batches):
def compute_epoch_average(vals, n):
weights = np.true_divide(n, np.sum(n))
avg = np.dot(weights, vals)
return avg
n_batches = len(data_batches)
batch_losses = np.zeros(n_batches)
batch_grad_norms = np.zeros(n_batches)
batch_sizes = np.zeros(n_batches)
for batch_idx in range(n_batches):
batch_data = data_batches[batch_idx]
batch_summary = self._train_batch(batch_data)
batch_losses[batch_idx] = batch_summary['loss']
batch_grad_norms[batch_idx] = batch_summary['grad_global_norm']
batch_sizes[batch_idx] = self._get_batch_size(batch_data)
epoch_loss = compute_epoch_average(batch_losses, batch_sizes)
if epoch_loss < self._ltl():
self._update_ltl(epoch_loss)
self.adaptive_learning_rate.update(epoch_loss)
epoch_grad_norm = compute_epoch_average(batch_grad_norms, batch_sizes)
self.adaptive_grad_norm_clip.update(epoch_grad_norm)
self._increment_epoch()
print('Epoch %d; loss: %.2e; learning rate: %.2e.'
% (self._epoch(), epoch_loss, self.adaptive_learning_rate()))
return epoch_loss | function | python | 293 |
protected Specification<ProductVersion> createSpecification(ProductVersionCriteria criteria) {
Specification<ProductVersion> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), ProductVersion_.id));
}
if (criteria.getVersion() != null) {
specification = specification.and(buildStringSpecification(criteria.getVersion(), ProductVersion_.version));
}
if (criteria.getReleaseNotes() != null) {
specification = specification.and(buildStringSpecification(criteria.getReleaseNotes(), ProductVersion_.releaseNotes));
}
if (criteria.getProductId() != null) {
specification = specification.and(buildSpecification(criteria.getProductId(),
root -> root.join(ProductVersion_.product, JoinType.LEFT).get(Product_.id)));
}
if (criteria.getBuildId() != null) {
specification = specification.and(buildSpecification(criteria.getBuildId(),
root -> root.join(ProductVersion_.build, JoinType.LEFT).get(Build_.id)));
}
if (criteria.getComponentId() != null) {
specification = specification.and(buildSpecification(criteria.getComponentId(),
root -> root.join(ProductVersion_.components, JoinType.LEFT).get(ProductComponentVersion_.id)));
}
}
return specification;
} | function | java | 294 |
public class ConfigurationItem
{
private const string FILE_EXTENSION = ".config";
private string folderPath = "";
private string name = "";
private readonly EventLog.EventLog eventLog = null;
private readonly bool readOnly = true;
public string FilePath
{
get
{
return FolderPath + Name + FILE_EXTENSION;
}
}
/
public string FolderPath
{
get
{
return folderPath;
}
set
{
if (Directory.Exists(value))
{
folderPath = value;
if (!folderPath.EndsWith(@"\"))
{
folderPath = folderPath + @"\";
}
}
else
{
throw new System.IO.DirectoryNotFoundException();
}
}
}
/
public String Name
{
get
{
return name;
}
set
{
if (!String.IsNullOrWhiteSpace(value))
{
name = value;
}
else
{
throw new ArgumentNullException();
}
}
}
public Boolean Encrypted { get; set; }
public String Value
{
get
{
if (Encrypted)
{
return SecureGet(eventLog);
}
else
{
return Get(eventLog);
}
}
set
{
if (value == null)
{
value = "";
}
if (Encrypted)
{
SecureWrite(value, eventLog);
}
else
{
Write(value, eventLog);
}
}
}
public ConfigurationItem(String folderPath, String name, Boolean encrypted, String value = null, EventLog.EventLog log = null, Boolean readOnly = true)
{
if (!String.IsNullOrWhiteSpace(folderPath) && !String.IsNullOrWhiteSpace(name))
{
FolderPath = folderPath;
Name = name;
Encrypted = encrypted;
eventLog = log;
this.readOnly = readOnly;
if (value != null)
{
Value = value;
}
}
}
public static bool Create(string folderPath, string name)
{
string fullPath = folderPath + name + FILE_EXTENSION;
if (!File.Exists(fullPath))
{
try
{
File file = new File(fullPath, false);
file.Close();
return true;
}
catch
{
return false;
}
}
else
{
return true;
}
}
public bool Delete()
{
if (File.Exists(FilePath))
{
return File.Delete(FilePath);
}
else
{
return true;
}
}
protected string Get(EventLog.EventLog log)
{
File file = null;
try
{
file = new File(FilePath, false, readOnly);
if (file.Exists())
{
return file.ReadAllAsText();
}
else
{
Return null.
return null;
}
}
catch (Exception e)
{
LogException(e, log);
return null;
}
finally
{
if (file != null)
{
file.Close();
}
}
}
private static bool LogException(Exception e, IEventLog log)
{
if (log != null)
{
log.Log(new Event(typeof(ConfigurationItem).FullName, DateTime.Now, Event.SeverityLevels.Error, e.GetType().FullName,
"Description:\n" +
e.Message + "\n" +
"Stack Trace:\n" +
e.StackTrace));
return true;
}
else
{
return false;
}
}
protected bool Write(string value, EventLog.EventLog log)
{
File file = null;
try
{
file = new File(FilePath, false);
return file.WriteLine(value);
}
catch (Exception e)
{
LogException(e, log);
return false;
}
finally
{
if (file != null)
{
file.Close();
}
}
}
protected string SecureGet(EventLog.EventLog log)
{
string value = Get(log);
if (!string.IsNullOrWhiteSpace(value))
{
StringReader reader = new StringReader(Get(log));
string encryptedValue = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(encryptedValue))
{
return AES256.DecryptConsolidatedString(encryptedValue);
}
}
return null;
}
protected bool SecureWrite(string value, EventLog.EventLog log)
{
string consolidatedString = AES256.CreateConsolidatedString(value);
if (!string.IsNullOrWhiteSpace(consolidatedString))
{
return Write(consolidatedString, log);
}
else
{
return false;
}
}
} | class | c# | 295 |
func Make(peers []*labrpc.ClientEnd, me int,
persister *Persister, applyCh chan ApplyMsg) *Raft {
rf := &Raft{}
rf.peers = peers
rf.persister = persister
rf.me = me
rf.Log = []Entry{Entry{}}
rf.CurrentTerm = 0
rf.ElectionTimeout = time.Duration(RandomInt(150, 300)) * time.Millisecond
rf.Role = "follower"
rf.VotedFor = -1
for range peers {
rf.MatchIndex = append(rf.MatchIndex, 0)
}
rf.ApplyCH = applyCh
log.Printf("%v init", rf)
log.Printf("instance attr: %v", StructToString(rf))
rf.readPersist(persister.ReadRaftState())
LogRunnerStart(rf.me)
go rf.Loop()
go rf.LeaderAppendEntries()
return rf
} | function | go | 296 |
static
seal_err_t
stop_then_clean_queue(seal_src_t* src)
{
seal_err_t err;
if ((err = change_state(src, alSourceStop)) != SEAL_OK)
return err;
return clean_queue(src);
} | function | c | 297 |
internal async static Task<string> ExecInPodAsync(IKubernetes ops, V1Pod pod, string @namespace, string[] commands)
{
var webSockTask = ops.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, @namespace, commands, pod.Spec.Containers[0].Name,
stderr: true, stdin: false, stdout: true, tty: false);
using (var webSock = await webSockTask)
using (var demux = new StreamDemuxer(webSock))
{
demux.Start();
using (var demuxStream = demux.GetStream(1, 1))
using (StreamReader reader = new StreamReader(demuxStream))
return await reader.ReadToEndAsync();
}
} | function | c# | 298 |
public async Task StartAsync(CancellationToken cancellationToken)
{
_cts?.Cancel();
await _syncTask;
_cts?.Dispose();
_cts = new CancellationTokenSource();
_syncTask = LoopSyncAsync(_cts.Token);
} | function | c# | 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.