file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
simd_add.rs | #![feature(test)]
#![feature(core)]
use std::simd::f32x4;
macro_rules! assert_equal_len {
($a:ident, $b: ident) => {
assert!($a.len() == $b.len(),
"add_assign: dimension mismatch: {:?} += {:?}",
($a.len(),),
($b.len(),));
}
}
// element-wise addition
fn... | (xs: &mut Vec<f32>, ys: &Vec<f32>) {
assert_equal_len!(xs, ys);
let size = xs.len() as isize;
let chunks = size / 4;
// pointer to the start of the vector data
let p_x: *mut f32 = xs.as_mut_ptr();
let p_y: *const f32 = ys.as_ptr();
// sum excess elements that don't fit in the simd vector
... | simd_add_assign | identifier_name |
simd_add.rs | #![feature(test)]
#![feature(core)]
use std::simd::f32x4;
macro_rules! assert_equal_len {
($a:ident, $b: ident) => {
assert!($a.len() == $b.len(),
"add_assign: dimension mismatch: {:?} += {:?}",
($a.len(),),
($b.len(),));
}
}
// element-wise addition
fn... |
// simd accelerated addition
fn simd_add_assign(xs: &mut Vec<f32>, ys: &Vec<f32>) {
assert_equal_len!(xs, ys);
let size = xs.len() as isize;
let chunks = size / 4;
// pointer to the start of the vector data
let p_x: *mut f32 = xs.as_mut_ptr();
let p_y: *const f32 = ys.as_ptr();
// sum e... | {
assert_equal_len!(xs, ys);
for (x, y) in xs.iter_mut().zip(ys.iter()) {
*x += *y;
}
} | identifier_body |
simd_add.rs | #![feature(test)]
#![feature(core)]
use std::simd::f32x4;
macro_rules! assert_equal_len {
($a:ident, $b: ident) => {
assert!($a.len() == $b.len(),
"add_assign: dimension mismatch: {:?} += {:?}",
($a.len(),),
($b.len(),));
}
}
// element-wise addition
fn... | }
}
}
mod bench {
extern crate test;
use self::test::Bencher;
use std::iter;
static BENCH_SIZE: usize = 10_000;
macro_rules! bench {
($name:ident, $func:ident) => {
#[bench]
fn $name(b: &mut Bencher) {
let mut x: Vec<_> = iter::repeat(1.0... | // sum "simd vector"
for i in 0..chunks {
unsafe {
*simd_p_x.offset(i) += *simd_p_y.offset(i); | random_line_split |
item_store.ts | stone',
shortAlias: 'tombstone',
},
};
export interface ItemState {
uuid: string;
revision: string;
deleted: boolean;
}
/** A convenience interface for passing around an item
* and its contents together.
*/
export interface ItemAndContent {
item: Item;
content: ItemContent;
}
export... | /** Create a new item. @p store is the store
* to associate the new item with. This can
* be changed later via saveTo().
*
* When importing an existing item or loading
* an existing item from the store, @p uuid may be non-null.
* Otherwise a random new UUID will be allocated for
*... | * via setContent() or decrypted on-demand by
* getContent()
*/
private content: ItemContent;
| random_line_split |
item_store.ts | ',
shortAlias: 'tombstone',
},
};
export interface ItemState {
uuid: string;
revision: string;
deleted: boolean;
}
/** A convenience interface for passing around an item
* and its contents together.
*/
export interface ItemAndContent {
item: Item;
content: ItemContent;
}
export inte... | (): string {
if (ITEM_TYPES[<string>this.typeName]) {
return ITEM_TYPES[<string>this.typeName].name;
} else {
return <string>this.typeName;
}
}
/** Returns true if this item has been saved to a store. */
isSaved(): boolean {
return this.store && this.... | typeDescription | identifier_name |
item_store.ts | ',
shortAlias: 'tombstone',
},
};
export interface ItemState {
uuid: string;
revision: string;
deleted: boolean;
}
/** A convenience interface for passing around an item
* and its contents together.
*/
export interface ItemAndContent {
item: Item;
content: ItemContent;
}
export inte... | else if (!this.store) {
this.content = ContentUtil.empty();
return Promise.resolve(this.content);
}
return this.store.getContent(this);
}
setContent(content: ItemContent) {
this.content = content;
}
/** Return the raw decrypted JSON data for an item.
... | {
return Promise.resolve(this.content);
} | conditional_block |
payment.py | import json
from collections import OrderedDict
from django import forms
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from pretix.base.payment import BasePaymentProvider
class BankTransfer(BasePaymentProvider):
| def checkout_prepare(self, request, total):
return True
def payment_is_valid_session(self, request):
return True
def checkout_confirm_render(self, request):
form = self.payment_form(request)
template = get_template('pretixplugins/banktransfer/checkout_payment_confirm.html')... | identifier = 'banktransfer'
verbose_name = _('Bank transfer')
@property
def settings_form_fields(self):
return OrderedDict(
list(super().settings_form_fields.items()) + [
('bank_details',
forms.CharField(
widget=forms.Textarea,
... | identifier_body |
payment.py | import json
from collections import OrderedDict
from django import forms
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from pretix.base.payment import BasePaymentProvider
class BankTransfer(BasePaymentProvider):
identifier = 'banktransfer'
verbose_na... | (self, request, order) -> str:
if order.payment_info:
payment_info = json.loads(order.payment_info)
else:
payment_info = None
template = get_template('pretixplugins/banktransfer/control.html')
ctx = {'request': request, 'event': self.event, 'settings': self.settin... | order_control_render | identifier_name |
payment.py | import json
from collections import OrderedDict
from django import forms
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from pretix.base.payment import BasePaymentProvider
class BankTransfer(BasePaymentProvider):
identifier = 'banktransfer'
verbose_na... | payment_info = None
template = get_template('pretixplugins/banktransfer/control.html')
ctx = {'request': request, 'event': self.event, 'settings': self.settings,
'payment_info': payment_info, 'order': order}
return template.render(ctx) | else: | random_line_split |
payment.py | import json
from collections import OrderedDict
from django import forms
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from pretix.base.payment import BasePaymentProvider
class BankTransfer(BasePaymentProvider):
identifier = 'banktransfer'
verbose_na... |
template = get_template('pretixplugins/banktransfer/control.html')
ctx = {'request': request, 'event': self.event, 'settings': self.settings,
'payment_info': payment_info, 'order': order}
return template.render(ctx)
| payment_info = None | conditional_block |
0110_add_default_contract_discount.py | # Generated by Django 2.2.14 on 2020-09-03 02:09
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('enterprise', '0109_remove_use_enterprise_catalog_sample'),
]
operations = [
migrations.AddField(
model_name='enterprisecustomer',
name='default_contract_discount',
field=models.DecimalField(blank=True, decimal_places=5, help_text='Specifies... | identifier_body | |
0110_add_default_contract_discount.py | # Generated by Django 2.2.14 on 2020-09-03 02:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('enterprise', '0109_remove_use_enterprise_catalog_sample'),
]
operations = [
migrations.AddField(
model_name='enterprisecustomer... | migrations.AddField(
model_name='historicalenterprisecustomer',
name='default_contract_discount',
field=models.DecimalField(blank=True, decimal_places=5, help_text='Specifies the discount percent used for enrollments from the enrollment API where capturing the discount per or... | field=models.DecimalField(blank=True, decimal_places=5, help_text='Specifies the discount percent used for enrollments from the enrollment API where capturing the discount per order is not possible. This is passed to ecommerce when creating orders for financial data reporting.', max_digits=8, null=True),
... | random_line_split |
0110_add_default_contract_discount.py | # Generated by Django 2.2.14 on 2020-09-03 02:09
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('enterprise', '0109_remove_use_enterprise_catalog_sample'),
]
operations = [
migrations.AddField(
model_name='enterprisecustomer',
name='default_contract_discount',
field=models.DecimalField(blank=True, decimal_p... | Migration | identifier_name |
send.py | # Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribut... | (target_branch, revision, public_branch, remember,
format, no_bundle, no_patch, output, from_, mail_to, message, body,
to_file, strict=None):
possible_transports = []
tree, branch = controldir.ControlDir.open_containing_tree_or_branch(
from_, possible_transports=possible_transports)[:2... | send | identifier_name |
send.py | # Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribut... |
def _send_0_9(branch, revision_id, submit_branch, public_branch,
no_patch, no_bundle, message,
base_revision_id, local_target_branch=None):
if not no_bundle:
if not no_patch:
patch_type = 'bundle'
else:
raise errors.BzrCommandError(gettext('Form... | from bzrlib import merge_directive
return merge_directive.MergeDirective2.from_objects(
branch.repository, revision_id, time.time(),
osutils.local_time_offset(), target_branch,
public_branch=public_branch,
include_patch=not no_patch,
include_bundle=not no_bundle, message=mess... | identifier_body |
send.py | # Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribut... | if (not getattr(mail_client, 'supports_body', False)
and body is not None):
raise errors.BzrCommandError(gettext(
'Mail client "%s" does not support specifying body') %
mail_client.__class__.__name__)
if remember and target_bran... | if output is None:
config_stack = branch.get_config_stack()
if mail_to is None:
mail_to = config_stack.get('submit_to')
mail_client = config_stack.get('mail_client')(config_stack) | random_line_split |
send.py | # Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribut... |
for (filename, lines) in directive.to_files():
path = os.path.join(output, filename)
outfile = open(path, 'wb')
try:
outfile.writelines(lines)
finally:
outfile.close()
... | os.mkdir(output, 0755) | conditional_block |
0005_auto_20160905_1853.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-05 16:53
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
('organization_network', '0004_organizationaudio_organizationblock_organizationimage_organizationlink_organizationvideo'),
]
operations = [
migrations.CreateModel(
name='UMR',
fields=[
('id', models.AutoField(... | Migration | identifier_name |
0005_auto_20160905_1853.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-05 16:53
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| migrations.RemoveField(
model_name='personactivity',
name='function',
),
migrations.RemoveField(
model_name='personactivity',
name='rd_quota',
),
migrations.AddField(
model_name='personactivity',
name='is_per... | dependencies = [
('organization_network', '0004_organizationaudio_organizationblock_organizationimage_organizationlink_organizationvideo'),
]
operations = [
migrations.CreateModel(
name='UMR',
fields=[
('id', models.AutoField(auto_created=True, primary_ke... | identifier_body |
0005_auto_20160905_1853.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-05 16:53
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('organization_network', '000... | field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='user'),
),
migrations.AddField(
model_name='personactivity',
name='umr',
field=models.ForeignKey(blank=True, null=Tru... | field=models.CharField(blank=True, max_length=128, null=True, verbose_name='R&D quota (text)'),
),
migrations.AlterField(
model_name='person',
name='user', | random_line_split |
index.story.js | import React from 'react';
import {
header,
tabs,
tab,
description,
importExample,
title,
divider,
example,
playground,
api,
testkit,
} from 'wix-storybook-utils/Sections';
import { storySettings } from '../test/storySettings';
import Star from 'wix-ui-icons-common/Star';
import * as examples fr... | ],
}; | { title: 'Testkit', sections: [testkit()] },
{ title: 'Playground', sections: [playground()] },
].map(tab),
]), | random_line_split |
Test_db_BKTree_Compare.py | import unittest
import time
import pprint
import logging
import scanner.logSetup as logSetup
import pyximport
print("Have Cython")
pyximport.install()
import dbPhashApi
class TestCompareDatabaseInterface(unittest.TestCase):
def __init__(self, *args, **kwargs):
logSetup.initLogging()
super().__init__(*args, ... | def setUp(self):
# We set up and tear down the tree a few times to validate the dropTree function
self.log = logging.getLogger("Main.TestCompareDatabaseInterface")
self.tree = dbPhashApi.PhashDbApi()
self.tree.forceReload()
def dist_check(self, distance, dbid, phash):
qtime1 = time.time()
have1 = self.... | random_line_split | |
Test_db_BKTree_Compare.py |
import unittest
import time
import pprint
import logging
import scanner.logSetup as logSetup
import pyximport
print("Have Cython")
pyximport.install()
import dbPhashApi
class TestCompareDatabaseInterface(unittest.TestCase):
|
# print(dbid, have1)
if have1 != have2:
self.log.error("Mismatch!")
for line in pprint.pformat(have1).split("\n"):
self.log.error(line)
for line in pprint.pformat(have2).split("\n"):
self.log.error(line)
self.assertTrue(dbid in have1)
self.assertTrue(dbid in have2)
self.assertEqual(have1, h... | def __init__(self, *args, **kwargs):
logSetup.initLogging()
super().__init__(*args, **kwargs)
def setUp(self):
# We set up and tear down the tree a few times to validate the dropTree function
self.log = logging.getLogger("Main.TestCompareDatabaseInterface")
self.tree = dbPhashApi.PhashDbApi()
self.tree.f... | identifier_body |
Test_db_BKTree_Compare.py |
import unittest
import time
import pprint
import logging
import scanner.logSetup as logSetup
import pyximport
print("Have Cython")
pyximport.install()
import dbPhashApi
class TestCompareDatabaseInterface(unittest.TestCase):
def __init__(self, *args, **kwargs):
logSetup.initLogging()
super().__init__(*args,... |
self.assertTrue(dbid in have1)
self.assertTrue(dbid in have2)
self.assertEqual(have1, have2)
self.log.info('Dist %s %s, %s', distance, qtime2-qtime1, qtime4-qtime3)
def test_0(self):
rand_r = self.tree.getRandomPhashRows(0.001)
self.log.info("Have %s items to test with", len(rand_r))
stepno = 0
f... | self.log.error("Mismatch!")
for line in pprint.pformat(have1).split("\n"):
self.log.error(line)
for line in pprint.pformat(have2).split("\n"):
self.log.error(line) | conditional_block |
Test_db_BKTree_Compare.py |
import unittest
import time
import pprint
import logging
import scanner.logSetup as logSetup
import pyximport
print("Have Cython")
pyximport.install()
import dbPhashApi
class TestCompareDatabaseInterface(unittest.TestCase):
def __init__(self, *args, **kwargs):
logSetup.initLogging()
super().__init__(*args,... | (self):
rand_r = self.tree.getRandomPhashRows(0.001)
self.log.info("Have %s items to test with", len(rand_r))
stepno = 0
for dbid, phash in rand_r:
self.dist_check(1, dbid, phash)
self.dist_check(2, dbid, phash)
self.dist_check(3, dbid, phash)
self.dist_check(4, dbid, phash)
self.dist_check(5, d... | test_0 | identifier_name |
calculator.py | for the deskbar applet.
#
# Copyright (C) 2008 by Johannes Buchner
# Copyright (C) 2007 by Michael Hofmann
# Copyright (C) 2006 by Callum McKenzie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fo... | (self, text = None):
"""Because the text variable for history entries contains the text
typed for the history search (and not the text of the orginal action),
we store the original text seperately."""
result = CopyToClipboardAction.get_name (self, text)
result["origtext"] = self.... | get_name | identifier_name |
calculator.py | for the deskbar applet.
#
# Copyright (C) 2008 by Johannes Buchner
# Copyright (C) 2007 by Michael Hofmann
# Copyright (C) 2006 by Callum McKenzie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fo... | except TypeError:
return hex (int (c))
def lenient_oct (c):
try:
return oct (c)
except TypeError:
return oct (int (c))
def lenient_bin (c):
try:
return bin (c)
except TypeError:
return bin (int (c))
class CalculatorAction (CopyToClipboardAction):
def _... | try:
return hex (c) | random_line_split |
calculator.py | for the deskbar applet.
#
# Copyright (C) 2008 by Johannes Buchner
# Copyright (C) 2007 by Michael Hofmann
# Copyright (C) 2006 by Callum McKenzie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fo... |
def _hexsub (self, match):
"""Parse the hex literal ourselves. We could let python do it, but
since we have a generic parser we use that instead."""
return self._number_parser (match, 16)
def run_query (self, query):
"""We evaluate the equation by first replacing hex and binary... | """Because python doesn't handle binary literals, we parse it
ourselves and replace it with a decimal representation."""
return self._number_parser (match, 2) | identifier_body |
calculator.py | for the deskbar applet.
#
# Copyright (C) 2008 by Johannes Buchner
# Copyright (C) 2007 by Michael Hofmann
# Copyright (C) 2006 by Callum McKenzie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fo... |
# We need this check because the eval can return function objects
# when we are halfway through typing the expression.
if isinstance (answer, (float, int, long, str)):
return answer
else:
return None
except Exception, e... | return None | conditional_block |
models.py | # Define a custom User class to work with django-social-auth
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
name = models.CharField(max_length=200)
owner = models.ForeignKey(User)
finished = models.BooleanField(default=False)
shared ... |
class CustomUser(models.Model):
username = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
objects = CustomUserManager()
def is_authenticated(self):
return True
| return self.model._default_manager.create(username=username) | identifier_body |
models.py | # Define a custom User class to work with django-social-auth
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
name = models.CharField(max_length=200)
owner = models.ForeignKey(User)
finished = models.BooleanField(default=False) | shared = models.BooleanField(default=False)
class Viewer(models.Model):
name = models.ForeignKey(User)
tasks = models.ForeignKey(Task)
class Friends(models.Model):
created = models.DateTimeField(auto_now_add=True, editable=False)
creator = models.ForeignKey(User, related_name="fr... | random_line_split | |
models.py | # Define a custom User class to work with django-social-auth
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
name = models.CharField(max_length=200)
owner = models.ForeignKey(User)
finished = models.BooleanField(default=False)
shared ... | (models.Manager):
def create_user(self, username, email):
return self.model._default_manager.create(username=username)
class CustomUser(models.Model):
username = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
objects = CustomUserManager()
... | CustomUserManager | identifier_name |
plugin.js | /* global editor */
/* global caselaw */
/* global _ */
/* global CKEDITOR */
/* global $ */
/* global moment */
/* global console */
(function() {
"use strict";
var pluginName = 'basic';
CKEDITOR.plugins.add(pluginName, {
init: function(editor) {
var formats = [{
label: "Bold",
command: "bold",
... | this.style = style;
this.allowedContent = style;
this.requiredContent = style;
this.contextSensitive = true;
};
styleCommand.prototype = {
exec: function(editor) {
editor.focus();
if (this.state === CKEDITOR.TRISTATE_OFF) {
editor.applyStyle(this.style);... |
var styleCommand = function(style) { | random_line_split |
plugin.js | /* global editor */
/* global caselaw */
/* global _ */
/* global CKEDITOR */
/* global $ */
/* global moment */
/* global console */
(function() {
"use strict";
var pluginName = 'basic';
CKEDITOR.plugins.add(pluginName, {
init: function(editor) {
var formats = [{
label: "Bold",
command: "bold",
... |
try {
switch (editor.getCommand(f.command).state) {
case CKEDITOR.TRISTATE_DISABLED:
// $("[rel='" + editor.getCommand(f.command).name + "']").addClass("disabled");
break;
case CKEDITOR.TRISTATE_OFF:
$("[rel='" + editor.getCommand(f.command).name + "']"... | {
editor.getCommand(f.command).setState(state);
} | conditional_block |
inventory.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... |
multisite_icons.append({
'host_columns': [ "name" ],
'paint': paint_icon_inventory,
})
| return link_to_view(html.render_icon('inv', _("Show Hardware/Software-Inventory of this host")),
row, 'inv_host' ) | conditional_block |
inventory.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | # the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received ... | # under the terms of the GNU General Public License as published by | random_line_split |
inventory.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... |
multisite_icons.append({
'host_columns': [ "name" ],
'paint': paint_icon_inventory,
})
| if (what == "host" or row.get("service_check_command","").startswith("check_mk_active-cmk_inv!")) \
and inventory.has_inventory(row["host_name"]):
return link_to_view(html.render_icon('inv', _("Show Hardware/Software-Inventory of this host")),
row, 'inv_host' ) | identifier_body |
inventory.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | (what, row, tags, customer_vars):
if (what == "host" or row.get("service_check_command","").startswith("check_mk_active-cmk_inv!")) \
and inventory.has_inventory(row["host_name"]):
return link_to_view(html.render_icon('inv', _("Show Hardware/Software-Inventory of this host")),
row, 'in... | paint_icon_inventory | identifier_name |
context.rs | ://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Context data structure used by rustpkg
use std::{io, os};
use extra::workcache;
use rustc::driver::session::{OptLevel, No};
#[deriving(Clone)]
pub struct Context {
// C... |
impl RustcFlags {
fn flag_strs(&self) -> ~[~str] {
let linker_flag = match self.linker {
Some(ref l) => ~[~"--linker", l.clone()],
None => ~[]
};
let link_args_flag = match self.link_args {
Some(ref l) => ~[~"--link-args", l.clone()],
None... | {
debug2!("Checking whether {} is in target", sysroot.display());
let mut p = sysroot.dir_path();
p.set_filename("rustc");
os::path_is_dir(&p)
} | identifier_body |
context.rs | ://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Context data structure used by rustpkg
use std::{io, os};
use extra::workcache;
use rustc::driver::session::{OptLevel, No};
#[deriving(Clone)]
pub struct | {
// Config strings that the user passed in with --cfg
cfgs: ~[~str],
// Flags to pass to rustc
rustc_flags: RustcFlags,
// If use_rust_path_hack is true, rustpkg searches for sources
// in *package* directories that are in the RUST_PATH (for example,
// FOO/src/bar-0.1 instead of FOO). The... | Context | identifier_name |
context.rs | ://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Context data structure used by rustpkg
use std::{io, os}; |
#[deriving(Clone)]
pub struct Context {
// Config strings that the user passed in with --cfg
cfgs: ~[~str],
// Flags to pass to rustc
rustc_flags: RustcFlags,
// If use_rust_path_hack is true, rustpkg searches for sources
// in *package* directories that are in the RUST_PATH (for example,
/... | use extra::workcache;
use rustc::driver::session::{OptLevel, No}; | random_line_split |
ComplexLine.py | .parentObject.getGraphUtils()
self.shapeMap = {}
self.lastmousex = 0
self.lastmousey = 0
self.buttonpressed = False
self.firstdrag=False
def show ( self ):
self.theRoot = self.parentObject.theCanvas.getRoot()
self.shapeDescriptorList = self.parentObject.get... | aLine = self.theRoot.add( gnomecanvas.CanvasLine,points=[X1,Y1,X2,Y2], width_units=lineSpec[ 6 ], fill_color_gdk = aGdkColor, first_arrowhead = firstArrow, last_arrowhead = secondArrow,arrow_shape_a=5, arrow_shape_b=5, arrow_shape_c=5 )
self.addHandlers( aLine, aDescriptor[ SD_NAME ] )
self.shap... |
aGdkColor = self.getGdkColor( aDescriptor )
firstArrow = lineSpec[4]
secondArrow = lineSpec[5]
| random_line_split |
ComplexLine.py | Object.getGraphUtils()
self.shapeMap = {}
self.lastmousex = 0
self.lastmousey = 0
self.buttonpressed = False
self.firstdrag=False
def show ( self ):
self.theRoot = self.parentObject.theCanvas.getRoot()
self.shapeDescriptorList = self.parentObject.getPropert... |
elif aDescriptor[SD_TYPE] == CV_LINE:
self.redrawLine( aDescriptor )
elif aDescriptor[SD_TYPE] == CV_BPATH:
self.redrawBpath( aDescriptor )
def reName( self ):
self.shapeDescriptorList = self.parentObject.getProperty( OB_SHAPEDESCRIPTORLIST ... | self.redrawText( aDescriptor ) | conditional_block |
ComplexLine.py | Object.getGraphUtils()
self.shapeMap = {}
self.lastmousex = 0
self.lastmousey = 0
self.buttonpressed = False
self.firstdrag=False
def show ( self ):
self.theRoot = self.parentObject.theCanvas.getRoot()
self.shapeDescriptorList = self.parentObject.getPropert... | (self, aDescriptor):
aSpecific= aDescriptor[SD_SPECIFIC]
# get pathdef
pathdef= aSpecific[BPATH_PATHDEF]
pd = gnomecanvas.path_def_new(pathdef)
aGdkColor = self.getGdkColor( aDescriptor )
#cheCk: 1starg > the Bpath, 2ndarg > Bpath width(def 3), 3rdarg > Color of Bpath(d... | createBpath | identifier_name |
ComplexLine.py | Object.getGraphUtils()
self.shapeMap = {}
self.lastmousex = 0
self.lastmousey = 0
self.buttonpressed = False
self.firstdrag=False
def show ( self ):
self.theRoot = self.parentObject.theCanvas.getRoot()
self.shapeDescriptorList = self.parentObject.getPropert... |
def selected( self ):
self.isSelected = True
def unselected( self ):
self.isSelected = False
def outlineColorChanged( self ):
self.fillColorChanged()
def fillColorChanged( self ):
# find shapes with outline color
anRGB = copyValue( self.parentObje... | for aShapeName in self.shapeMap.keys():
self.shapeMap[ aShapeName ].destroy() | identifier_body |
acceptor.rs | //! Future for mediating the processing of commands received from the
//! CtlGateway in the Supervisor.
use super::handler::CtlHandler;
use crate::{ctl_gateway::server::MgrReceiver,
manager::{action::ActionSender,
ManagerState}};
use futures::{channel::oneshot,
future::F... |
Poll::Pending => {
match futures::ready!(self.mgr_receiver.poll_next_unpin(cx)) {
Some(cmd) => {
let task =
CtlHandler::new(cmd, self.state.clone(), self.action_sender.clone());
Poll::Ready(Some(... | {
error!("Error polling CtlAcceptor shutdown trigger: {}", e);
Poll::Ready(None)
} | conditional_block |
acceptor.rs | //! Future for mediating the processing of commands received from the
//! CtlGateway in the Supervisor.
use super::handler::CtlHandler;
use crate::{ctl_gateway::server::MgrReceiver,
manager::{action::ActionSender,
ManagerState}};
use futures::{channel::oneshot,
future::F... | (mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
match self.shutdown_trigger.poll_unpin(cx) {
Poll::Ready(Ok(())) => {
info!("Signal received; stopping CtlAcceptor");
Poll::Ready(None)
}
Poll::Ready(Err(e)) => {
... | poll_next | identifier_name |
acceptor.rs | //! Future for mediating the processing of commands received from the
//! CtlGateway in the Supervisor.
use super::handler::CtlHandler;
use crate::{ctl_gateway::server::MgrReceiver,
manager::{action::ActionSender,
ManagerState}};
use futures::{channel::oneshot,
future::F... | shutdown_trigger: oneshot::Receiver<()>,
action_sender: ActionSender)
-> Self {
CtlAcceptor { mgr_receiver,
state,
shutdown_trigger,
action_sender }
}
}
impl Stream for CtlAcceptor {
type Item... | mgr_receiver: MgrReceiver, | random_line_split |
makegrid.py | from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure(figsize=(9, 3))
map = Basemap(width=12000000,height=8000000,
resolution='l',projection='stere',
lat_ts=50,lat_0=50,lon_0=-107.)
| ax.set_title('The regular grid')
map.scatter(x, y, marker='o')
map.drawcoastlines()
ax = fig.add_subplot(122)
ax.set_title('Projection changed')
map = Basemap(width=12000000,height=9000000,projection='aeqd',
lat_0=50.,lon_0=-105.)
x, y = map(lons, lats)
map.scatter(x, y, marker='o')
map.drawcoastlines()
... | lons, lats, x, y = map.makegrid(30, 30, returnxy=True)
ax = fig.add_subplot(121) | random_line_split |
tar.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (directory: str, destination: str) -> subprocess.CompletedProcess:
"""Compress the given directory into the tarfile at destination."""
# Note: we don't use the stdlib's "tarfile" module for performance reasons.
# While it can handle creating tarfiles, its not as efficient on large
# numbers of files lik... | compress | identifier_name |
tar.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | """Decompress the given tarfile to the destination."""
# Note: we don't use the stdlib's "tarfile" module for performance reasons.
# While it can handle creating tarfiles, its not as efficient on large
# numbers of files like the tar command.
return shell.run(
[
"tar",
"-... | identifier_body | |
tar.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Note: we don't use the stdlib's "tarfile" module for performance reasons.
# While it can handle creating tarfiles, its not as efficient on large
# numbers of files like the tar command.
return shell.run(
[
"tar",
"--extract",
f"--directory={destination}",
... |
def decompress(archive: str, destination: str) -> subprocess.CompletedProcess:
"""Decompress the given tarfile to the destination.""" | random_line_split |
clean_data_for_academic_analysis.py | #!/usr/bin/python
# This file is part of OpenHatch.
# Copyright (C) 2010 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your ... |
### delete all WebResponse objects
for wr in mysite.customs.models.WebResponse.objects.all():
wr.delete()
| citation.delete() | conditional_block |
clean_data_for_academic_analysis.py | #!/usr/bin/python
# This file is part of OpenHatch.
# Copyright (C) 2010 OpenHatch, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your ... | ### * delete (from the database) any PortfolioEntry that is_deleted
### * delete (from the database) any Citation that is_deleted
### * delete all WebResponse objects
import mysite.profile.models
import django.contrib.auth.models
### set the email and password columns to the empty string
for user in django.contrib.au... |
### To protect our users' privacy, we:
### * set the password column to the empty string
### * set the email column to the empty string | random_line_split |
node.js | /*jshint unused:false */
function NodeController( $scope ){
this.initialize= function () {
$scope.calculateImagePosition();
};
$scope.calculateImagePosition = function(){
var depth = $scope.node.depth; | else { width++; }
//console.log( "depth:" + depth + " width:" + width );
$scope.cx = width * 40;
$scope.cy = 30 + depth * 40;
$scope.r = 14;
$scope.x = $scope.cx - 15;
$scope.y = $scope.cy + 2;
$scope.lineColor = '#FF0000';
//$scope.test = 1;
... | var width = $scope.treeWidth[depth];
if( width === undefined ) { width = 1; } | random_line_split |
node.js | /*jshint unused:false */
function NodeController( $scope ){
this.initialize= function () {
$scope.calculateImagePosition();
};
$scope.calculateImagePosition = function(){
var depth = $scope.node.depth;
var width = $scope.treeWidth[depth];
if( width === undefined ) { width ... |
//console.log( "depth:" + depth + " width:" + width );
$scope.cx = width * 40;
$scope.cy = 30 + depth * 40;
$scope.r = 14;
$scope.x = $scope.cx - 15;
$scope.y = $scope.cy + 2;
$scope.lineColor = '#FF0000';
//$scope.test = 1;
console.log( $scope.... | { width++; } | conditional_block |
node.js | /*jshint unused:false */
function NodeController( $scope ) |
console.log( $scope.cx );
$scope.treeWidth[depth] = width;
};
this.initialize();
}
| {
this.initialize= function () {
$scope.calculateImagePosition();
};
$scope.calculateImagePosition = function(){
var depth = $scope.node.depth;
var width = $scope.treeWidth[depth];
if( width === undefined ) { width = 1; }
else { width++; }
//console.log( "de... | identifier_body |
node.js | /*jshint unused:false */
function | ( $scope ){
this.initialize= function () {
$scope.calculateImagePosition();
};
$scope.calculateImagePosition = function(){
var depth = $scope.node.depth;
var width = $scope.treeWidth[depth];
if( width === undefined ) { width = 1; }
else { width++; }
//consol... | NodeController | identifier_name |
workspace-stacks.controller.ts | /*
* Copyright (c) 2015-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Coden... | }
/**
* Detects machine source from pointed stack.
*
* @param stack {object} to retrieve described source
* @returns {source} machine source config
*/
getSourceFromStack(stack: any): any {
let source: any = {};
source.type = 'dockerfile';
switch (stack.source.type.toLowerCase()) {
... | {
let stackWorkspaceConfig;
if (this.stack) {
stackWorkspaceConfig = this.stack.workspaceConfig;
} else if (!this.stack) {
let stackTemplate = this.cheStack.getStackTemplate(),
defEnvName = stackTemplate.workspaceConfig.defaultEnv,
defEnvironment = stackTemplate.workspac... | identifier_body |
workspace-stacks.controller.ts | /*
* Copyright (c) 2015-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Coden... |
});
$scope.$watch(() => { return this.workspaceImportedRecipe; }, () => {
if (!this.workspaceImportedRecipe) {
return;
}
this.initStackSelecter();
}, true);
}
/**
* Initialize stack selector widget.
*/
initStackSelecter(): void {
let type = this.workspaceImported... | {
this.cheStackLibrarySelecter(null);
} | conditional_block |
workspace-stacks.controller.ts | /*
* Copyright (c) 2015-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Coden... | ($scope: ng.IScope, cheWorkspace: CheWorkspace, cheEnvironmentRegistry: CheEnvironmentRegistry, cheStack: CheStack) {
this.cheWorkspace = cheWorkspace;
this.cheStack = cheStack;
this.composeEnvironmentManager = cheEnvironmentRegistry.getEnvironmentManager('compose');
$scope.$watch(() => { return this.r... | constructor | identifier_name |
workspace-stacks.controller.ts | /*
* Copyright (c) 2015-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Coden... | cheStack: CheStack;
cheWorkspace: CheWorkspace;
composeEnvironmentManager: ComposeEnvironmentManager;
recipeUrl: string;
recipeScript: string;
recipeFormat: string;
stack: any = null;
isCustomStack: boolean = false;
selectSourceOption: string;
tabName: string;
environmentName: string;
workspa... |
const DEFAULT_WORKSPACE_RAM: number = 2 * Math.pow(1024, 3);
export class WorkspaceStacksController {
$scope: ng.IScope; | random_line_split |
nir_opt_algebraic.py | (('ieq', a, a), True),
(('ine', a, a), False),
(('ult', a, a), False),
(('uge', a, a), True),
# Logical and bit operations
(('fand', a, 0.0), 0.0),
(('iand', a, a), a),
(('iand', a, 0), 0),
(('ior', a, a), a),
(('ior', a, 0), a),
(('fxor', a, a), 0.0),
(('ixor', a, a), 0),
(('inot',... | optimizations += [
((op, ('bcsel', 'a', '#b', '#c'), '#d'),
('bcsel', 'a', (op, 'b', 'd'), (op, 'c', 'd'))),
((op, '#d', ('bcsel', a, '#b', '#c')),
('bcsel', 'a', (op, 'd', 'b'), (op, 'd', 'c'))),
] | conditional_block | |
nir_opt_algebraic.py | b = 'b'
c = 'c'
d = 'd'
# Written in the form (<search>, <replace>) where <search> is an expression
# and <replace> is either an expression or a value. An expression is
# defined as a tuple of the form (<op>, <src0>, <src1>, <src2>, <src3>)
# where each source is either an expression or a value. A value can be
# eit... | import nir_algebraic
# Convenience variables
a = 'a' | random_line_split | |
class_passed_message.js | var class_passed_message =
[
[ "direction_t", "class_passed_message.html#a11c83e74aa007c495b32ec3ed4953a50", [
[ "INCOMING", "class_passed_message.html#a11c83e74aa007c495b32ec3ed4953a50a43c42d4afa45cd04736e0d59167260a4", null ],
[ "OUTGOING", "class_passed_message.html#a11c83e74aa007c495b32ec3ed4953a50a... | [ "LOWER_DATA", "class_passed_message.html#a7738b6f08855f784d1012de87fbfd9e6a97265ac51f333c88508670c5d3f5ded9", null ],
[ "LOWER_CONTROL", "class_passed_message.html#a7738b6f08855f784d1012de87fbfd9e6afb379d2a15495f1ef2f290dc9ac97299", null ]
] ],
[ "direction", "class_passed_message.html#af55219a6ed... | random_line_split | |
ParserFactory.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
... | }); | random_line_split | |
database_backup.py | #!/usr/bin/python
""" | where {hostname} and {port} are as they are below
"""
import sys
sys.path.append("/next_backend")
import time
import traceback
import next.utils as utils
import subprocess
import next.constants as constants
import os
NEXT_BACKEND_GLOBAL_HOST = os.environ.get('NEXT_BACKEND_GLOBAL_HOST', 'localhost')
AWS_BUCKET_NAME... | Every 30 minutes backs up database to S3. To recover the database, (i.e. reverse the process)
simply download the file from S3, un-tar it, and use the command:
(./)mongorestore --host {hostname} --port {port} path/to/dump/mongodump
| random_line_split |
main.rs | extern crate rustc_serialize;
extern crate docopt;
extern crate glob;
use docopt::Docopt;
use std::io::Write;
use std::path::PathBuf;
use glob::glob;
#[cfg_attr(rustfmt, rustfmt_skip)] | Kibar imager. Helper utils to download, format, install and manage raspbery
pi images for the kibar project.
Usage:
img install <device>
img mount <device> <location>
img unmount (<device> | <location>)
img chroot <device>
img (-h | --help | --version)
Options:
-h --help Show this screen.
--version ... | const USAGE: &'static str = " | random_line_split |
main.rs | extern crate rustc_serialize;
extern crate docopt;
extern crate glob;
use docopt::Docopt;
use std::io::Write;
use std::path::PathBuf;
use glob::glob;
#[cfg_attr(rustfmt, rustfmt_skip)]
const USAGE: &'static str = "
Kibar imager. Helper utils to download, format, install and manage raspbery
pi images for the kibar pro... | {
arg_device: String,
arg_location: String,
cmd_install: bool,
cmd_mount: bool,
cmd_unmount: bool,
cmd_chroot: bool,
}
#[derive(Debug)]
struct Device {
device_file: PathBuf,
partitions: Vec<PathBuf>,
}
impl Device {
// TODO pass errors up rather then just panicing
fn new(devic... | Args | identifier_name |
main.rs | extern crate rustc_serialize;
extern crate docopt;
extern crate glob;
use docopt::Docopt;
use std::io::Write;
use std::path::PathBuf;
use glob::glob;
#[cfg_attr(rustfmt, rustfmt_skip)]
const USAGE: &'static str = "
Kibar imager. Helper utils to download, format, install and manage raspbery
pi images for the kibar pro... | }
| {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
println!("{:?}", args);
if args.cmd_install {
unimplemented!()
} else if args.cmd_mount {
let d = Device::new(args.arg_device);
printl... | identifier_body |
main.rs | extern crate rustc_serialize;
extern crate docopt;
extern crate glob;
use docopt::Docopt;
use std::io::Write;
use std::path::PathBuf;
use glob::glob;
#[cfg_attr(rustfmt, rustfmt_skip)]
const USAGE: &'static str = "
Kibar imager. Helper utils to download, format, install and manage raspbery
pi images for the kibar pro... | else if args.cmd_mount {
let d = Device::new(args.arg_device);
println!("{:?}", d);
} else if args.cmd_unmount {
unimplemented!();
writeln!(&mut std::io::stderr(), "Error!").unwrap();
::std::process::exit(1)
} else if args.cmd_chroot {
unimplemented!()
} else... | {
unimplemented!()
} | conditional_block |
JavascriptSerializer.ts | import { JavascriptFileSystem } from './JavascriptFileSystem'
import { v2 as webdav } from 'webdav-server'
export class JavascriptSerializer extends webdav.VirtualSerializer
{
uid() : string
{
return 'JavascriptSerializer-1.0.0';
}
serialize(fs : JavascriptFileSystem, callback : webdav.ReturnC... | }
} | random_line_split | |
JavascriptSerializer.ts | import { JavascriptFileSystem } from './JavascriptFileSystem'
import { v2 as webdav } from 'webdav-server'
export class JavascriptSerializer extends webdav.VirtualSerializer
{
uid() : string
|
serialize(fs : JavascriptFileSystem, callback : webdav.ReturnCallback<any>) : void
{
super.serialize(fs, (e, data) => {
if(e)
return callback(e);
data.options = fs.options;
callback(null, data);
})
}
unserialize(serializ... | {
return 'JavascriptSerializer-1.0.0';
} | identifier_body |
JavascriptSerializer.ts | import { JavascriptFileSystem } from './JavascriptFileSystem'
import { v2 as webdav } from 'webdav-server'
export class JavascriptSerializer extends webdav.VirtualSerializer
{
| () : string
{
return 'JavascriptSerializer-1.0.0';
}
serialize(fs : JavascriptFileSystem, callback : webdav.ReturnCallback<any>) : void
{
super.serialize(fs, (e, data) => {
if(e)
return callback(e);
data.options = fs.options;
... | uid | identifier_name |
microtask.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Implementation of [microtasks](https://html.spec.whatwg.org/multipage/#microtask) and
//! microtask queues. I... | match *job {
Microtask::Promise(ref job) => {
if let Some(target) = target_provider(job.pipeline) {
let _ = job.callback.Call_(&*target, ExceptionHandling::Report);
}
},
... | {
if self.performing_a_microtask_checkpoint.get() {
return;
}
// Step 1
self.performing_a_microtask_checkpoint.set(true);
debug!("Now performing a microtask checkpoint");
// Steps 2
while !self.microtask_queue.borrow().is_empty() {
roote... | identifier_body |
microtask.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Implementation of [microtasks](https://html.spec.whatwg.org/multipage/#microtask) and
//! microtask queues. I... | (&self, job: Microtask, cx: JSContext) {
self.microtask_queue.borrow_mut().push(job);
unsafe { JobQueueMayNotBeEmpty(*cx) };
}
/// <https://html.spec.whatwg.org/multipage/#perform-a-microtask-checkpoint>
/// Perform a microtask checkpoint, executing all queued microtasks until the queue is ... | enqueue | identifier_name |
microtask.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Implementation of [microtasks](https://html.spec.whatwg.org/multipage/#microtask) and
//! microtask queues. I... | },
Microtask::CustomElementReaction => {
ScriptThread::invoke_backup_element_queue();
},
Microtask::NotifyMutationObservers => {
MutationObserver::notify_mutation_observers();
... | task.handler();
},
Microtask::ImageElement(ref task) => {
task.handler(); | random_line_split |
microtask.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Implementation of [microtasks](https://html.spec.whatwg.org/multipage/#microtask) and
//! microtask queues. I... |
},
Microtask::MediaElement(ref task) => {
task.handler();
},
Microtask::ImageElement(ref task) => {
task.handler();
},
Microtask::CustomElementReaction... | {
let _ = job.callback.Call_(&*target, ExceptionHandling::Report);
} | conditional_block |
ExportFileJob.py | # Copyright (c) 2021 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import io
from typing import List, Optional, Union
from UM.FileHandler.FileHandler import FileHandler
from UM.FileHandler.FileWriter import FileWriter
from UM.FileHandler.WriteFileJob import WriteFileJob
from UM.Logger imp... | """Get the job result as bytes as that is what we need to upload to the Digital Factory Library."""
output = self.getStream().getvalue()
if isinstance(output, str):
output = output.encode("utf-8")
return output
def getMimeType(self) -> str:
"""Get the mime type ... | """Job that exports the build plate to the correct file format for the Digital Factory Library project."""
def __init__(self, file_handler: FileHandler, nodes: List[SceneNode], job_name: str, extension: str) -> None:
file_types = file_handler.getSupportedFileTypesWrite()
if len(file_types) == 0:
... | identifier_body |
ExportFileJob.py | # Copyright (c) 2021 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import io
from typing import List, Optional, Union
from UM.FileHandler.FileHandler import FileHandler
from UM.FileHandler.FileWriter import FileWriter
from UM.FileHandler.WriteFileJob import WriteFileJob
from UM.Logger imp... |
mode = None
file_writer = None
for file_type in file_types:
if file_type["extension"] == extension:
file_writer = file_handler.getWriter(file_type["id"])
mode = file_type.get("mode")
super().__init__(file_writer, self.createStream(mode = mode... | Logger.log("e", "There are no file types available to write with!")
raise OutputDeviceError.WriteRequestFailedError("There are no file types available to write with!") | conditional_block |
ExportFileJob.py | # Copyright (c) 2021 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import io
from typing import List, Optional, Union
from UM.FileHandler.FileHandler import FileHandler
from UM.FileHandler.FileWriter import FileWriter
from UM.FileHandler.WriteFileJob import WriteFileJob
from UM.Logger imp... | (self) -> str:
"""Get the mime type of the selected export file type."""
return MimeTypeDatabase.getMimeTypeForFile(self.getFileName()).name
@staticmethod
def createStream(mode) -> Union[io.BytesIO, io.StringIO]:
"""Creates the right kind of stream based on the preferred format."""
... | getMimeType | identifier_name |
ExportFileJob.py | # Copyright (c) 2021 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import io
from typing import List, Optional, Union
from UM.FileHandler.FileHandler import FileHandler
from UM.FileHandler.FileWriter import FileWriter
from UM.FileHandler.WriteFileJob import WriteFileJob
from UM.Logger imp... |
class ExportFileJob(WriteFileJob):
"""Job that exports the build plate to the correct file format for the Digital Factory Library project."""
def __init__(self, file_handler: FileHandler, nodes: List[SceneNode], job_name: str, extension: str) -> None:
file_types = file_handler.getSupportedFileTypesWri... | random_line_split | |
fn_to_numeric_cast_any.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use super::FN_TO_NUMERIC_CAST_ANY;
pub(super) fn | (cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
// We allow casts from any function type to any function type.
match cast_to.kind() {
ty::FnDef(..) | ty::FnPtr(..) => return,
_ => { /* continue to checks */ },
}
match cast_from.kind() ... | check | identifier_name |
fn_to_numeric_cast_any.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability; | use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use super::FN_TO_NUMERIC_CAST_ANY;
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
// We allow casts from any function type to... | random_line_split | |
fn_to_numeric_cast_any.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use super::FN_TO_NUMERIC_CAST_ANY;
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, ca... | ,
}
}
| {} | conditional_block |
fn_to_numeric_cast_any.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use rustc_errors::Applicability;
use rustc_hir::Expr;
use rustc_lint::LateContext;
use rustc_middle::ty::{self, Ty};
use super::FN_TO_NUMERIC_CAST_ANY;
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, ca... | );
},
_ => {},
}
}
| {
// We allow casts from any function type to any function type.
match cast_to.kind() {
ty::FnDef(..) | ty::FnPtr(..) => return,
_ => { /* continue to checks */ },
}
match cast_from.kind() {
ty::FnDef(..) | ty::FnPtr(_) => {
let mut applicability = Applicability::May... | identifier_body |
JoinAttributes.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
JoinAttributes.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... | self.tr('Input layer')))
self.addParameter(ParameterTable(self.INPUT_LAYER_2,
self.tr('Input layer 2'), False))
self.addParameter(ParameterTableField(self.TABLE_FIELD,
self.tr... | self.name, self.i18n_name = self.trAlgorithm('Join attributes table')
self.group, self.i18n_group = self.trAlgorithm('Vector general tools')
self.addParameter(ParameterVector(self.INPUT_LAYER, | random_line_split |
JoinAttributes.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
JoinAttributes.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... |
# Create output vector layer with additional attribute
outFeat = QgsFeature()
features = vector.features(layer)
total = 100.0 / len(features)
for current, feat in enumerate(features):
outFeat.setGeometry(feat.geometry())
attrs = feat.attributes()
... | attrs = feat.attributes()
joinValue2 = str(attrs[joinField2Index])
if joinValue2 not in cache:
cache[joinValue2] = attrs
feedback.setProgress(int(current * total)) | conditional_block |
JoinAttributes.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
JoinAttributes.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... | def processAlgorithm(self, feedback):
input = self.getParameterValue(self.INPUT_LAYER)
input2 = self.getParameterValue(self.INPUT_LAYER_2)
output = self.getOutputFromName(self.OUTPUT_LAYER)
field = self.getParameterValue(self.TABLE_FIELD)
field2 = self.getParameterValue(self.... | OUTPUT_LAYER = 'OUTPUT_LAYER'
INPUT_LAYER = 'INPUT_LAYER'
INPUT_LAYER_2 = 'INPUT_LAYER_2'
TABLE_FIELD = 'TABLE_FIELD'
TABLE_FIELD_2 = 'TABLE_FIELD_2'
def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Join attributes table')
self.group, self.i18n_group = ... | identifier_body |
JoinAttributes.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
JoinAttributes.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... | (self):
self.name, self.i18n_name = self.trAlgorithm('Join attributes table')
self.group, self.i18n_group = self.trAlgorithm('Vector general tools')
self.addParameter(ParameterVector(self.INPUT_LAYER,
self.tr('Input layer')))
self.addParameter(Pa... | defineCharacteristics | identifier_name |
LogInPage.tsx | import * as React from 'react';
import { Provider } from 'react-redux';
// import { Office } from 'Office';
export class LogInPage extends React.Component<{}, {}> {
public render(): React.ReactElement<Provider> {
var style_img = {
align: 'center'
};
var style_button = {
backgroundcolor: 'rg... | <h1 style = {style_section}> Create work items </h1>
<p style = {style_text2}> Do you have an email thread that should be turned into a work item or has your boss sent you a list of things to do? Create work items directly from your email.</p>
<h2 style = {style_section}>Respon... | <div> | random_line_split |
fields.py | ative extension
if args:
col_kw['name'], col_kw['type_'] = args
# Column init when defining a schema
else:
col_kw['type_'] = self._sqla_type_cls(*type_args, **type_kw)
super(BaseField, self).__init__(**col_kw)
def __setattr__(self, key, value):
""" St... | (self, kwargs):
""" Process/extract/rename Column arguments.
http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#column-table-metadata-api
Changed:
required -> nullable
help_text -> doc
"""
col_kw = kwargs.copy()
col_kw['nullable'] = not col... | process_column_args | identifier_name |
fields.py | ative extension
if args:
col_kw['name'], col_kw['type_'] = args
# Column init when defining a schema
else:
col_kw['type_'] = self._sqla_type_cls(*type_args, **type_kw)
super(BaseField, self).__init__(**col_kw)
def __setattr__(self, key, value):
""" St... |
class BinaryField(ProcessableMixin, BaseField):
_sqla_type_cls = LargeBinary
_type_unchanged_kwargs = ('length',)
# Since SQLAlchemy 1.0.0
# class MatchField(BooleanField):
# _sqla_type_cls = MatchType
class DecimalField(ProcessableMixin, BaseField):
_sqla_type_cls = LimitedNumeric
_type_uncha... | _sqla_type_cls = Interval
_type_unchanged_kwargs = (
'native', 'second_precision', 'day_precision') | identifier_body |
fields.py | /extract/rename Column arguments.
http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#column-table-metadata-api
Changed:
required -> nullable
help_text -> doc
"""
col_kw = kwargs.copy()
col_kw['nullable'] = not col_kw.pop('required', False)
... | 'ondelete', 'deferrable', 'initially', 'link_to_name', 'match')
def __init__(self, *args, **kwargs):
""" Override to determine `self._sqla_type_cls`.
| random_line_split | |
fields.py | col_kw['type_'] = self._sqla_type_cls(*type_args, **type_kw)
super(BaseField, self).__init__(**col_kw)
def __setattr__(self, key, value):
""" Store column name on 'self.type'
This allows error messages in custom types' validation be more
explicit.
"""
if... | column_kw['type_'] = self._sqla_type_cls(*type_args, **type_kw) | conditional_block | |
bootstrap.js | /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free ... | }
},
// Overridden javafx.application.Application.stop();
stop: function() {
// Call the global stop function if present.
if ($GLOBAL.stop) {
stop();
}
}
// No arguments passed to application (handled thru $ARG.)
})).class, new (Java.type("java.lang.Stri... | } else {
stage.show(); | random_line_split |
bootstrap.js | /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free ... |
// Extend the javafx.application.Application class overriding init, start and stop.
com.sun.javafx.application.LauncherImpl.launchApplication((Java.extend(javafx.application.Application, {
// Overridden javafx.application.Application.init();
init: function() {
// Java FX packages and classes must be d... | {
print("JavaFX is not available.");
exit(1);
} | conditional_block |
sample_file_parser.py | import json
import logging
from os import listdir, path
from typing import Dict, List
from tqdm import tqdm
TELEM_DIR_PATH = "../envs/monkey_zoo/blackbox/tests/performance/telemetry_sample"
MAX_SAME_TYPE_TELEM_FILES = 10000
LOGGER = logging.getLogger(__name__)
class SampleFileParser:
@staticmethod
def save_... |
with open(path.join(TELEM_DIR_PATH, telem_filename), "w") as file:
file.write(json.dumps(telem))
@staticmethod
def read_telem_files() -> List[str]:
telems = []
try:
file_paths = [
path.join(TELEM_DIR_PATH, f)
for f in listdir(TELE... | telem_filename = str(i) + telem_filename
break | conditional_block |
sample_file_parser.py | import json
import logging
from os import listdir, path
from typing import Dict, List
from tqdm import tqdm
TELEM_DIR_PATH = "../envs/monkey_zoo/blackbox/tests/performance/telemetry_sample"
MAX_SAME_TYPE_TELEM_FILES = 10000
LOGGER = logging.getLogger(__name__)
class SampleFileParser:
@staticmethod
def save_... | for f in listdir(TELEM_DIR_PATH)
if path.isfile(path.join(TELEM_DIR_PATH, f))
]
except FileNotFoundError:
raise FileNotFoundError(
"Telemetries to send not found. "
"Refer to readme to figure out how to generate telemetries ... | random_line_split | |
sample_file_parser.py | import json
import logging
from os import listdir, path
from typing import Dict, List
from tqdm import tqdm
TELEM_DIR_PATH = "../envs/monkey_zoo/blackbox/tests/performance/telemetry_sample"
MAX_SAME_TYPE_TELEM_FILES = 10000
LOGGER = logging.getLogger(__name__)
class SampleFileParser:
@staticmethod
def save_... |
@staticmethod
def read_telem_files() -> List[str]:
telems = []
try:
file_paths = [
path.join(TELEM_DIR_PATH, f)
for f in listdir(TELEM_DIR_PATH)
if path.isfile(path.join(TELEM_DIR_PATH, f))
]
except FileNotFoundErr... | telem_filename = telem["name"] + telem["method"]
for i in range(MAX_SAME_TYPE_TELEM_FILES):
if not path.exists(path.join(TELEM_DIR_PATH, (str(i) + telem_filename))):
telem_filename = str(i) + telem_filename
break
with open(path.join(TELEM_DIR_PATH, telem_filen... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.