code stringlengths 0 30.8k | source stringclasses 6
values | language stringclasses 9
values | __index_level_0__ int64 0 100k |
|---|---|---|---|
def generate_from_dict(obj: Any):
if isinstance(obj, list):
return [generate_from_dict(value) for value in obj]
if "_type" not in obj:
return {key: generate_from_dict(value) for key, value in obj.items()}
class_type = globals()[obj.pop("_type")]
if class_type == Sequence:
return ... | function | python | 99,900 |
def palindrome(a):
if len(a) == 0:
return ("", "", 0)
cache = {}
def inner(i, j):
if (i, j) in cache: return cache[(i, j)]
if i == j:
value = a[i]
elif a[i] == a[j]:
if i + 1 == j:
value = (a[i] + a[j])
else:
... | function | python | 99,901 |
@Override
protected void execute() {
if(Robot.m_oi.getTriggerLeft() < .3 && Robot.m_oi.getTriggerRight() < .3)
{
if(!(Robot.intakePan.getLimitLeft() || Robot.intakePan.getLimitRight())){
Robot.intakePan.set(Robot.m_oi.getJoy2TriggerRight() - Robot.m_oi.getJoy2TriggerLeft());
}
else if... | function | java | 99,902 |
void CAnimObject::SetPropSheetPos(CPropertySheet *pSheet,CxAnimObjectList *pList)
{
if (!m_pPosPage)
m_pPosPage = new CAnimObjPosPage();
m_pPosPage->m_sCpntList.RemoveAll();
if (pList)
{
BOOL bFound = FALSE;
int nbC = pList->GetSize();
for (int i=0;i<nbC && !bFound;i++)
{
CAnimObject *pObj = pList->Get... | function | c++ | 99,903 |
func FanOutUntil[A any](done <-chan interface{}, buffer int, c <-chan A, size int) []<-chan A {
outs := make([]chan A, size)
for i := range outs {
outs[i] = make(chan A, buffer)
}
go func() {
defer func() {
for _, o := range outs {
close(o)
}
}()
for e := range c {
select {
case <-done:
... | function | go | 99,904 |
def request_password_hash(hash_head: str) -> requests.Response:
url = "https://api.pwnedpasswords.com/range/" + hash_head
logger.debug("Requesting {}".format(url))
res = requests.get(url, headers=default_headers)
if res.status_code >= 400:
if res.status_code in [
400, 403, 404
... | function | python | 99,905 |
static int
check_buffers (st_parameter_dt *dtp)
{
int c;
c = '\0';
if (dtp->u.p.current_unit->last_char != EOF - 1)
{
dtp->u.p.at_eol = 0;
c = dtp->u.p.current_unit->last_char;
dtp->u.p.current_unit->last_char = EOF - 1;
goto done;
}
if (dtp->u.p.line_buffer_enabled)
{
... | function | c | 99,906 |
[JsonObject(MemberSerialization.OptOut)]
public class Training2Lesson
{
[Key]
[JsonIgnore]
public int Training2LessonId { get; set; }
public Guid LessonIdForExport { get; set; }
[Required]
public string Name { get; set; }
[AllowHtml]
public string ... | class | c# | 99,907 |
bool initialize_nondet_string_fields(
struct_exprt &struct_expr,
code_blockt &code,
const std::size_t &min_nondet_string_length,
const std::size_t &max_nondet_string_length,
const source_locationt &loc,
const irep_idt &function_id,
symbol_table_baset &symbol_table,
bool printable)
{
if(!java_string_li... | function | c++ | 99,908 |
public class SAMLBearerRequest extends TokenRequest {
// x-www-urlencoded keys / values sent to OAuth server for SAML grant flow
static final String CLIENT_ASSERTION_TYPE_KEY = "client_assertion_type";
static final String CLIENT_ASSERTION_TYPE_VALUE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer... | class | java | 99,909 |
static int
disk_write_block_aligned_base(int fd, int is_base_disk, const void* data,
size_t bytecount, disk_blockptr_t* block,
struct disk_info *info, int align, off_t *offset)
{
blocknum_t current_block;
blocknum_t blocknum;
off_t current_pos;
if (align == 0)
align = info->phy_block_size;
curr... | function | c | 99,910 |
def _global_grid_recorder(
global_processing_map, quad_database_path, database_command_queue,
global_report_queue):
try:
while True:
payload = global_report_queue.get()
LOGGER.debug(f'_global_grid_recorder payload {payload}')
if payload == 'STOP':
... | function | python | 99,911 |
static inline nat_mt
nat_normalize(struct natrep *n)
{
while (n->nlimbs && !n->limbs[n->nlimbs-1])
n->nlimbs--;
return n;
} | function | c | 99,912 |
public abstract class OperationVisitor<TResult>
{
public virtual TResult Visit(Operation operation)
{
if (operation != null)
{
return operation.Accept(this);
}
return default(TResult);
}
public virtual TResult DefaultVis... | class | c# | 99,913 |
public static void CastDisc<T>(this Navmesh navmesh, T discCast, NativeList<IntPtr> open, NativeHashSet<int> closed) where T : IDiscCast
{
var o = discCast.Origin;
var r = discCast.Radius;
var tri = navmesh.FindTriangleContainingPoint(o);
open.Clear();
... | function | c# | 99,914 |
private static class ExtendedKeyUsagePKIXCertPathChecker extends PKIXCertPathChecker {
private static final String EKU_OID = "2.5.29.37";
private static final String EKU_anyExtendedKeyUsage = "2.5.29.37.0";
private static final String EKU_clientAuth = "1.3.6.1.5.5.7.3.2";
private stati... | class | java | 99,915 |
class CutConcatenate:
"""
A transform on batch of cuts (``CutSet``) that concatenates the cuts to minimize the total amount of padding;
e.g. instead of creating a batch with 40 examples, we will merge some of the examples together
adding some silence between them to avoid a large number of padding frame... | class | python | 99,916 |
[SetUpFixture]
public class TestRunSetup
{
public static IHost TestWebHost { get; private set; }
public static SeleniumWebDriverService WebDriverService { get; private set; }
[OneTimeSetUp]
public async Task RunBeforeAnyTestsAsync()
{
LoggingHelper.ClearLogs()... | class | c# | 99,917 |
def parse(file_name, user_id):
with open(file_name, 'rb') as data_file:
data = data_file.read()
rows = re.split(b'spotify:[pse]', data)
folder = {'type': 'folder', 'children': []}
stack = []
for row in rows:
chunks = row.split(b'\r', 1)
row = chunks[0]
if row.startswi... | function | python | 99,918 |
def generate_x(c, a, b, num_x, random_seed):
raise NotImplementedError("No functioning implementation finished yet.")
np.random.seed(random_seed)
get the optimal solution
optimal_x = solve_lp(c, a, b)
use twice the optimal solution (of course invalid) as upper bound for randomly generated inst... | function | python | 99,919 |
func (q *Query) Exec(ctx context.Context) (*QueryResult, error) {
var r QueryResult
if q.client == nil || !q.client.Started() {
return &r, fmt.Errorf("client or db is nil")
}
switch q.action {
case "select":
rows, err := q.execSelect(ctx)
r.Rows = rows
return &r, err
case "insert":
rows, err := q.execIn... | function | go | 99,920 |
protected override void SolveInstance(IGH_DataAccess DA)
{
Drawing drawing = new Drawing();
if (!DA.GetData<Drawing>(0, ref drawing)) return;
Sm.DrawingVisual dwg = drawing.ToGeometryVisual();
int dpi = 96;
DA.GetData(1, ref dpi);
if (dpi <... | function | c# | 99,921 |
public class SimpleDemoScenario extends Scenario {
public static final String TYPE = "SimpleDemo";
private static ScenarioNode rootNode;
private static void init() throws Exception {
if (rootNode != null) {
return;
}
ScenarioNode START = rootNode = new NodeBuilder().ad... | class | java | 99,922 |
private Component CheckAndGetUniqueResultTypeFromRoot(GameObject targetedRootGameObject, FieldInfo componentField, IEnumerable<Component> componentsFound)
{
int nbFound = componentsFound.Count();
if (nbFound > 1)
{
throw new NixiAttributeException($"Multiple c... | function | c# | 99,923 |
public static String encode(String username, List<String> warmupChallenges, String officialChallenge) {
List<String> allChallenges = new ArrayList<>(warmupChallenges);
allChallenges.add(officialChallenge);
String challengeCSV = allChallenges.stream().collect(Collectors.joining(","));
Str... | function | java | 99,924 |
public synchronized void build(Resource packagerResource, Map<String, String> properties) throws IOException {
if (this.built) {
throw new IllegalStateException("build in directory `" + this.dir
+ "' already completed");
}
if (this.dir.exists()) {
if (... | function | java | 99,925 |
public final void assemble(@Nonnull AssemblyBuilder builder) throws IOException {
if (builder == null) {
throw new NullPointerException("builder");
}
final SourceNode sourceNode = builder.getStep().getLocation().getSourceLocation().getSourceNode();
if (this != sourceNode) {
... | function | java | 99,926 |
@NonNull
public PendingRecording withEventListener(@NonNull Executor callbackExecutor,
@NonNull Consumer<VideoRecordEvent> listener) {
Preconditions.checkNotNull(callbackExecutor, "CallbackExecutor can't be null.");
Preconditions.checkNotNull(listener, "Event listener can't be null");
... | function | java | 99,927 |
pub fn add_unique<T: Send + Sync + Component>(
&self,
component: T,
) -> Result<(), error::Borrow> {
self.all_storages.borrow()?.add_unique(component);
Ok(())
} | function | rust | 99,928 |
class DelayedRewards:
"""
Environment intended to incentivize the agent to delay acknowledging
every other reward. For example, if the first three rewards are
1, 3, 7, then the agent is incentivized to act as if the first three
rewards are 1, 0, 10 (the reward of 3 being delayed and added onto the
... | class | python | 99,929 |
class RelayInputStream extends InputStream
{
private InputStream mInputStream = null;
private OutputStream mOutputStream = null;
private long total = 0L;
RelayInputStream(InputStream is, OutputStream os)
{
mInputStream = is;
mOutputStream = os;
}
@Override
public int av... | class | java | 99,930 |
int
ms_rlog_free (MSLogParam *logp)
{
MSLogEntry *logentry = NULL;
int freed = 0;
if (!logp)
logp = &gMSLogParam;
logentry = logp->registry.messages;
while (logentry)
{
freed++;
logp->registry.messages = logentry->next;
free (logentry);
logentry = logp->registry.messages;
}
return fr... | function | c | 99,931 |
def _remove_empty_dicts(data: MutableMapping, factory=dict) -> MutableMapping:
d = factory()
for key, value in data.items():
if value is None:
pass
elif isinstance(value, Dict):
sub_dict = _remove_empty_dicts(value, factory=factory)
if sub_dict:
... | function | python | 99,932 |
static void __bnx2x_vlan_mac_h_read_unlock(struct bnx2x *bp,
struct bnx2x_vlan_mac_obj *o)
{
if (!o->head_reader) {
BNX2X_ERR("Need to release vlan mac reader lock, but lock isn't taken\n");
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
#endif
} else {
o->head_reader--;
DP(BNX2X_MSG_SP, "vlan_mac_lock - de... | function | c | 99,933 |
ulint first_page_t::write(trx_id_t trxid, const byte *&data, ulint &len) {
byte *ptr = data_begin();
ulint written = (len > max_space_available()) ? max_space_available() : len;
mlog_write_string(ptr, data, written, m_mtr);
set_data_len(written);
set_trx_id(trxid);
data += written;
len -= written;
retur... | function | c++ | 99,934 |
static void
mark_dies (dw_die_ref die)
{
dw_die_ref c;
gcc_assert (!die->die_mark);
die->die_mark = 1;
FOR_EACH_CHILD (die, c, mark_dies (c));
} | function | c | 99,935 |
private void InitializeComponent()
{
this.valSize = new Desktop.Skinning.SkinnedNumericUpDown();
this.radPt = new Desktop.Skinning.SkinnedRadioButton();
this.radPx = new Desktop.Skinning.SkinnedRadioButton();
((System.ComponentModel.ISupportInitialize)(this.valSize)).BeginInit();
this.SuspendLayout();
... | function | c# | 99,936 |
def check_majorana_and_flip_flow(self, found_majorana,
wavefunctions,
diagram_wavefunctions,
external_wavefunctions,
wf_number, force_flip_flow=False,
... | function | python | 99,937 |
public void start(Path inputDir, Path outputDir) throws IOException {
FileSystem fs = FileSystem.get(this.conf);
JobConf uniqueListenersConf = getUniqueListenersJobConf(inputDir);
Path listenersOutputDir = FileOutputFormat.getOutputPath(uniqueListenersConf);
Job listenersJob = new Job(un... | function | java | 99,938 |
public class UserDefinedUniverseAlgorithm : QCAlgorithm
{
private static readonly IReadOnlyList<string> Symbols = new List<string>
{
"SPY", "GOOG", "IBM", "AAPL", "MSFT", "CSCO", "ADBE", "WMT",
};
public override void Initialize()
{
UniverseSettings.Re... | class | c# | 99,939 |
public void addJoin( String joinField1, String joinField2, Predicate.Op pred) throws ParsingException {
joinField1 = disambiguateName(joinField1);
joinField2 = disambiguateName(joinField2);
String table1Alias = joinField1.split("[.]")[0];
String table2Alias = joinField2.split("[.]")[0];
... | function | java | 99,940 |
def render_hunspell_word_error(
data,
fields=["filename", "word", "line_number", "word_line_index"],
sep=":",
):
values = []
for field in fields:
value = data.get(field)
if value is not None:
values.append(str(value))
return (sep).join(values) | function | python | 99,941 |
async def execute(self, query, variables=None):
msg_id = await self.start(query, variables=variables)
try:
resp = await self.receive(wait_id=msg_id)
finally:
await self.receive(wait_id=msg_id)
return resp | function | python | 99,942 |
function updateInventory(arr1, arr2) {
var add;
for (var i = 0; i < arr2.length; i++) {
add = true;
for (var x = 0; x < arr1.length; x++) {
if (arr1[x][1] == arr2[i][1]) {
arr1[x][0] = arr1[x][0] + arr2[i][0];
add = false;
break;
}
}
if (add) {
arr1.push([ar... | function | javascript | 99,943 |
@Override
public SearchResponse<DatasetSearchResult, DatasetSearchParameter> search(DatasetSearchRequest request) {
SolrQuery solrQuery = queryBuilder.build(request);
QueryResponse solrResp = query(solrQuery);
SearchResponse<DatasetSearchResult, DatasetSearchParameter> resp = responseBuilder.buildSearch(r... | function | java | 99,944 |
def _create_collect_logs_handler(iterations=1, systemd_present=True):
original_file_exists = os.path.exists
def mock_file_exists(filepath):
if filepath == SYSTEMD_RUN_PATH:
return systemd_present
return original_file_exists(filepath)
with mock_wire_protocol(DATA_FILE) as protocol... | function | python | 99,945 |
def create_env_var(session: requests.Session, slug: str, name: str,
value: str, public: bool = False) -> None:
endpoint = f'{_BASE}/repo/{urllib.parse.quote_plus(slug)}/env_vars'
response = session.post(endpoint, json={
'env_var.name': name,
'env_var.value': value,
'en... | function | python | 99,946 |
private static bool SlowCompare(string str1, string str2)
{
if (str1 == null || str2 == null)
{
throw new InvalidOperationException("The parameter cannot be null");
}
var diff = str1.Length ^ str2.Length;
for (int i = Math.Min(str1.Leng... | function | c# | 99,947 |
[TestMethod]
public async Task TestContactRepositoryThrowsExceptionShouldReturnErrorCode()
{
var interactor = new DeclineContactInteractor(new ExceptionContactRepository());
var response = await interactor.ExecuteAsync(
new DeclineContactRequest
{
... | function | c# | 99,948 |
private void run_for_n_elaboration_cycles(long n)
{
Arguments.check(n >= 0, "n must be non-negative");
startTopLevelTimers();
stop_soar = false;
reason_for_stopping = null;
long d_cycles_at_start = d_cycle_count.value.get();
int elapsed_cycles = 0;
GoType save... | function | java | 99,949 |
def _force_consistent_uids(data_dir: Union[str, PathLike],
target_uid: str = None):
data_dir = pathlib.Path(data_dir).resolve()
for n, fn in enumerate(data_dir.rglob('*dcm')):
img = dcm.read_file(str(fn))
if target_uid is None and n == 0:
target_uid = str(i... | function | python | 99,950 |
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "atomisedName", propOrder = {
"genusOrUninomial",
"infragenericEpithet",
"specificEpithet",
"infraspecificEpithet"
})
public class AtomisedName {
@XmlElement(required = true)
protected String genusOrUninomial;
protected String infragener... | class | java | 99,951 |
_onDeviceListChange(devices) {
const newDeviceLists = this._getDefaultDeviceListState();
devices.forEach(({ deviceId, kind, label }) => {
const formatted = {
deviceId,
label,
value: label
};
switch (kind) {
c... | function | javascript | 99,952 |
public void testGetNodesNamePattern()
throws NotExecutableException, RepositoryException {
Node node = testRootNode;
if (!node.hasNodes()) {
throw new NotExecutableException("Workspace does not have sufficient content for this test. " +
"Root node must have at... | function | java | 99,953 |
def diff(
self, n=1, prepend: List = [], append: List = [], new_name: Optional[str] = None
) -> "HTable":
cat = prepend + append
if len(cat) > n or n > len(cat) > 0:
raise ValueError(
f"You must prepend or append exactly n ({n}) values or 0 values"
)
... | function | python | 99,954 |
filterAllJournalposts() {
this.filteredJournalPosts = this.journalposts.filter(
(journalpost) =>
(this.availableThemes == null || this.availableThemes.includes(journalpost.tema)) &&
(this.selectedCase == null ||
this.selectedCase === journalpost.sa... | function | javascript | 99,955 |
@GuardedBy("monitor")
private void serviceFinishedStarting(Service service, boolean currentlyHealthy) {
checkState(unstartedServices > 0,
"All services should have already finished starting but %s just finished.", service);
unstartedServices--;
if (currentlyHealthy && unstartedServices ... | function | java | 99,956 |
def sync(self, session=None) -> None:
with self.connector as connection:
_, stdout, stderr = connection.exec_command("source /etc/profile.d/lsf.sh && bjobs -aW")
for bjob in [RemoteLsfExecutor._parse_bjob(line) for line in stdout if line[0].isdigit()]:
if bjob.lsf_id in s... | function | python | 99,957 |
private int[] pickForcedLocalAddress() {
int[] ret = null;
String aux = System.getProperty(FTPKeys.ACTIVE_DT_HOST_ADDRESS);
if (aux != null) {
boolean valid = false;
StringTokenizer st = new StringTokenizer(aux, ".");
if (st.countTokens() == 4) {
valid = true;
int[] arr = new int[4];
for (int... | function | java | 99,958 |
class GridProEditColumn extends GridColumn {
static get is() {
return 'vaadin-grid-pro-edit-column';
}
static get properties() {
return {
/**
* Custom function for rendering the cell content in edit mode.
* Receives three arguments:
*
* - `root` The cell content DOM elem... | class | javascript | 99,959 |
@Getter @Setter @ToString @EqualsAndHashCode
@Accessors(fluent = true)
public class ConfigsBuilder {
/**
* Either the name of the stream to consume records from
* Or MultiStreamTracker for all the streams to consume records from
*/
private Either<MultiStreamTracker, String> appStreamTracker;
... | class | java | 99,960 |
func (cc *ConnectionCache) CleanOld(older_than time.Duration) {
cc.mx.Lock()
defer cc.mx.Unlock()
for h, cls := range cc.cache {
if cls == nil || cls.Len() == 0 {
delete(cc.cache, h)
}
for cl := cls.Front(); cl != nil; cl = cl.Next() {
if time.Now().Sub(cl.Value.(*Client).last_sent) > older_than {
cl... | function | go | 99,961 |
public abstract class AbstractDate {
public final static String DAY = "day";
public final static String IS_OUT_OF_RANGE = "is out of range!";
public final static String NOT_IMPLEMENTED_YET = "not implemented yet!";
public final static String MONTH = "month";
public final static String YEAR_0_IS_INV... | class | java | 99,962 |
private void checkCryptoWalletBalance() throws CantLoadWalletException, CantCalculateBalanceException, CryptoWalletBalanceInsufficientException {
if (this.bitcoinWalletBalance == null) {
BitcoinWalletWallet bitcoinWalletWallet = this.bitcoinWalletManager.loadWallet(this.walletPublicKey);
... | function | java | 99,963 |
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1021:AvoidOutParameters",
MessageId = "2#",
Justification = "We allow this in a 'Try' method.")]
bool TryCreate(
ConfigurationBehaviorType behaviorType,
ILifetimeDetai... | function | c# | 99,964 |
def _match_indicators(gt_is_present, pr_is_present,
match_pairs, match_occurs):
num_gt, num_frames = gt_is_present.shape
num_pr, _ = pr_is_present.shape
match_occurs = match_occurs.astype(bool)
match_indicators = {}
match_indicators['occurs'] = match_occurs
gt_has_some_match = np.zeros... | function | python | 99,965 |
def wait_for_answer(self, device, request_message, timeout=30, block=True):
self.wait_api_lock.acquire()
wait_start_time = time.perf_counter()
if device is None:
raise ValueError
if request_message is None:
raise ValueError
message = None
if timeou... | function | python | 99,966 |
@Test
public void databaseStorageInMemoryDB() {
Log.i(TAG, "Testing Database Storage switch over to in-memory database");
/* Get instance to access database. */
DatabaseStorage databaseStorage = DatabaseStorage.getDatabaseStorage("test-databaseStorageInMemoryDB", "test.databaseStorageInMemor... | function | java | 99,967 |
func (mng *Manager) correlate(r *base.Response) {
tx, ok := mng.getTx(r)
if !ok {
log.Warn("Failed to correlate response to active transaction. Dropping it.")
return
}
tx.Receive(r)
} | function | go | 99,968 |
private class CompilerResultConsumer implements IConsumer<CompilerResult>, Serializable {
/**
* the compilerMarkersContainer
*/
private final WebMarkupContainer compilerMarkersContainer;
/**
* Constructor.
* @param compilerMarkersContainer the container for the markers list
*/
public CompilerRe... | class | java | 99,969 |
public void writeDiffAsXMLFile(String filePath, String pathToXSLT) {
if (pathToXSLT.isEmpty() || pathToXSLT == null) {
pathToXSLT = "bubastis_style_info.xslt";
}
try {
XMLRenderer xmlRenderer = new XMLRenderer();
xmlRenderer.writeDiffAsXMLFile(filePath, this.c... | function | java | 99,970 |
func (h *Hash) HKDF(secret, salt, info []byte, length int) []byte {
if length == 0 {
length = h.OutputSize()
}
kdf := hkdf.New(h.f, secret, salt, info)
dst := make([]byte, length)
_, _ = io.ReadFull(kdf, dst)
return dst
} | function | go | 99,971 |
func mapRunesToClusterIndices(runes []rune, glyphs []shaping.Glyph) []int {
mapping := make([]int, len(runes))
glyphCursor := 0
if len(runes) == 0 {
return nil
}
rtl := len(glyphs) > 0 && glyphs[len(glyphs)-1].ClusterIndex < glyphs[0].ClusterIndex
if rtl {
glyphCursor = len(glyphs) - 1
}
for i := range rune... | function | go | 99,972 |
def reset_as_parent(self):
self.identifier.pop()
self.scope_depth = self.scope_depth - 1
self._set_pattern_id()
self._find_parent_module()
self.module_name = Scope.scope_to_module_name(self.identifier)
self._node_structs = list()
self._module_structs = list()
... | function | python | 99,973 |
static class CommandId
{
public const int icmdSccCommand = 0x101;
public const int icmdViewToolWindow = 0x102;
public const int icmdToolWindowToolbarCommand = 0x103;
public const int imnuToolWindowToolbarMenu = 0x200;
public const int iiconProductIcon = 400;
public co... | class | c# | 99,974 |
public class Notification {
private String payload;
private String token;
private UUID uuid;
private int expiration;
/**
* Default priority is set to be 10
*/
private int priority = Constants.HIGH_PRIORITY;
private String topic;
private String collapseId;
/**
* Constructor always takes valid payload
... | class | java | 99,975 |
@Test
public void testMarkerMapping() {
setTestFile("short-sample-drop.flextext");
setProperties("properties/map-annotation.properties");
start();
SDocumentGraph graph = getFixture().getSaltProject().getCorpusGraphs().get(0).getDocuments().get(0)
.getDocumentGraph();
assertNotNull(graph);
/*
* Chec... | function | java | 99,976 |
public class DoubleLabel implements PropertyRenderer {
public Component getRendererComponent(final Property property, Annotation annotation) {
final ValueModel model = new PropertyAdapter(property, "value", true);
JPanel panel = new JPanel(new BorderLayout());
final JLabel label = new ... | class | java | 99,977 |
@Component("blSkuRestrictionFactory")
public class SkuRestrictionFactoryImpl implements RestrictionFactory {
@Resource(name="blRestrictionFactory")
protected RestrictionFactory delegate;
protected static final String DEFAULT_SKU_PATH_PREFIX = "product.defaultSku.";
protected String skuPropertyPrefix;... | class | java | 99,978 |
func bgRun(cmd *exec.Cmd) {
cmd.Stdin = nil
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stderr
if err := cmd.Start(); err != nil {
log.Fatalf("%+v: %s", cmd.Args, err)
}
if _, err := cmd.Process.Wait(); err != nil {
log.Fatalf("%+v: %s", cmd.Args, err)
}
} | function | go | 99,979 |
def check_conflict_on_del(self, session, _id, db_content):
if session["force"]:
return
_filter = self._get_project_filter(session)
_filter["_admin.nst-id"] = _id
if self.db.get_list("nsis", _filter):
raise EngineException("there is at least one Netslice Instance u... | function | python | 99,980 |
def print_forecast(forecaster: 'Forecaster') -> None:
forecast: 'Forecast' = forecaster.get_forecast()
location = forecast.get_location()
ansi_bold: str = '\033[1m'
ansi_yellow: str = '\033[33m'
ansi_reset: str = '\033[0m'
for weather in forecast:
rain_length, rainfall = len(weather.get_... | function | python | 99,981 |
public string ImageinfoToCsv(TW_IMAGEINFO a_twimageinfo)
{
try
{
CSV csv = new CSV();
csv.Add(((double)a_twimageinfo.XResolution.Whole + ((double)a_twimageinfo.XResolution.Frac / 65536.0)).ToString());
csv.Add(((double)a_twimageinfo.YResolu... | function | c# | 99,982 |
long
wtimer_granularity (void)
{
#ifdef TIMER_GETTIMEOFDAY
return (1);
#endif
#ifdef TIMER_TIME
return (1000);
#endif
#ifdef TIMER_WINDOWS
return (1);
#endif
} | function | c | 99,983 |
private void ReadRecordTable(int pos, int numEntries, BinaryReader reader, StreamWriter outStream)
{
this.recordInfo = new Dictionary<string, RecordInfo>((int)Math.Round(numEntries * 1.2));
reader.BaseStream.Seek(pos, SeekOrigin.Begin);
if (outStream != null)
{
outStream.WriteLine("RecordTable located... | function | c# | 99,984 |
public class SpaceAlreadyStoppedException extends SpaceUnavailableException {
private static final long serialVersionUID = 3487826802841980532L;
/**
* Constructs a <code>SpaceAlreadyStoppedException</code> with the specified detail message.
*
* @param s - the detail message
*/
public Sp... | class | java | 99,985 |
def seek(self,offset,whence=0):
assert whence in (0, 1, 2)
if whence == 0:
realoffset = self.firstbyte + offset
elif whence == 1:
realoffset = self.realpos + offset
elif whence == 2:
raise IOError('seek from end of file not supported.')
if... | function | python | 99,986 |
int nsm_monitor(const struct nlm_host *host)
{
struct nsm_handle *nsm = host->h_nsmhandle;
struct nsm_res res;
int status;
dprintk("lockd: nsm_monitor(%s)\n", nsm->sm_name);
if (nsm->sm_monitored)
return 0;
nsm->sm_mon_name = nsm_use_hostnames ? nsm->sm_name : nsm->sm_addrbuf;
status = nsm_mon_unmon(nsm, NSMP... | function | c | 99,987 |
func IsTryingToTraverseUp(s string) bool {
sep := string(filepath.Separator)
for _, fragment := range strings.Split(s, sep) {
if ".." == fragment {
return true
}
}
return false
} | function | go | 99,988 |
fn search(&self, chars: &[char]) -> bool {
let mut cur = self;
// let mut chs:Vec<char> = word.chars().collect();
for id in 0..chars.len() {
// let next = cur.child.get(&i);
if chars[id] != '.' {
let i = chars[id] as usize - 'a' as usize;
/... | function | rust | 99,989 |
func (iac *InstanceAdminClient) UpdateAppProfile(ctx context.Context, instanceID, profileID string, updateAttrs ProfileAttrsToUpdate) error {
ctx = mergeOutgoingMetadata(ctx, withGoogleClientInfo(), iac.md)
profile := &btapb.AppProfile{
Name: "projects/" + iac.project + "/instances/" + instanceID + "/appProfiles/" ... | function | go | 99,990 |
async function verifyResults(library) {
const { metaPath, resultsPath } = library;
if (!fs.existsSync(join(metaPath, "issues.json")))
throw new Error("Missing issues.json");
if (!fs.existsSync(join(metaPath, "summary.md")))
throw new Error("Missing summary.md");
if (!fs.existsSync(join(resultsPath, "res... | function | javascript | 99,991 |
def extract_model(self, program_name):
_method_name = 'extract_model'
self.__logger.entering(program_name, class_name=self.__class_name, method_name=_method_name)
try:
tmp_model_dir = FileUtils.createTempDirectory(program_name)
tmp_model_file = None
for archiv... | function | python | 99,992 |
static Oid
GetOperatorByType(Oid typeId, Oid accessMethodId, int16 strategyNumber)
{
Oid operatorClassId = GetDefaultOpClass(typeId, accessMethodId);
Oid operatorFamily = get_opclass_family(operatorClassId);
Oid operatorId = get_opfamily_member(operatorFamily, typeId, typeId, strategyNumber);
return operatorId;
} | function | c | 99,993 |
def define_fc_layer(fc_dict, last_block=False):
in_features = fc_dict["in_features"]
out_features = fc_dict["out_features"]
if last_block:
fc_block = [nn.Linear(in_features, out_features)]
else:
fc_block = [
nn.Linear(in_features, out_features),
... | function | python | 99,994 |
function obify_(str, pack) {
var ob = null;
try {
ob = str ? JSON.parse(str) : null;
}
catch (err) {
ns.errify(false, ns.settings.errors.INTERNAL, "data in exchange was invalid" + str, pack);
}
return ob;
} | function | javascript | 99,995 |
private List<MarketDataNode> dependencyNodes(MarketDataRequirements requirements) {
List<MarketDataNode> observableNodes =
buildNodes(requirements.getObservables(), MarketDataNode.DataType.SINGLE_VALUE);
List<MarketDataNode> nonObservableNodes =
buildNodes(requirements.getNonObservables(), Marke... | function | java | 99,996 |
def interpret(marker, execution_context=None):
try:
expr, rest = parse_marker(marker)
except Exception as e:
raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e))
if rest and rest[0] != '#':
raise SyntaxError('unexpected trailing data in marker: %s: %s' % (mark... | function | python | 99,997 |
@Override
public boolean isAllowedToAllocateMips(List<Double> vmRequestedMipsShare) {
final double pmMips = getPeCapacity();
double totalRequestedMips = 0;
for (final double vmMips : vmRequestedMipsShare) {
if (vmMips > pmMips) {
return false;
}
... | function | java | 99,998 |
func InstallOrUpdateApp(ctx context.Context, a *arc.ARC, d *ui.Device, pkgName string, tryLimit int) error {
installed, err := a.PackageInstalled(ctx, pkgName)
if err != nil {
return err
}
if !installed {
return InstallApp(ctx, a, d, pkgName, tryLimit)
}
testing.ContextLog(ctx, "App has already been installed... | function | go | 99,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.