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 |
|---|---|---|---|---|
LoadoutEdit.tsx | {
loadout: Loadout;
store: DimStore;
stateDispatch: React.Dispatch<Action>;
onClickSubclass: (subclass: DimItem | undefined) => void;
onClickPlaceholder: (params: { bucket: InventoryBucket; equip: boolean }) => void;
onClickWarnItem: (item: DimItem) => void;
onRemoveItem: (item: DimItem) => void;
}) {
... | random_line_split | ||
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponsePermanentRedirect, Http404, HttpResponseRedirect
from django.views.decorators.http import require_GET
from django.contrib.auth import login, authenticate
from django.core.urlresolvers import reverse_lazy
from django.contrib... |
def user_url_list(user, page, limit=20):
"""
Returns a paginator of a queryset with users Url's.
"""
url_list = Url.objects.filter(user=user)
paginator = Paginator(url_list, limit)
try:
url_list = paginator.page(page)
except PageNotAnInteger:
url_list = paginator.page(1)
... | if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
username = request.POST['username']
password = request.POST['password1']
user = authenticate(username=username, password=password)
login(r... | identifier_body |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponsePermanentRedirect, Http404, HttpResponseRedirect
from django.views.decorators.http import require_GET
from django.contrib.auth import login, authenticate
from django.core.urlresolvers import reverse_lazy
from django.contrib... | (request, short_code):
"""
Redirects Url
"""
if short_code:
try:
url = Url.objects.get(short_code=short_code)
except Url.DoesNotExist:
raise Http404()
return HttpResponsePermanentRedirect(url.original_url)
def register_user(request):
if request.method == ... | redirect | identifier_name |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponsePermanentRedirect, Http404, HttpResponseRedirect
from django.views.decorators.http import require_GET
from django.contrib.auth import login, authenticate
from django.core.urlresolvers import reverse_lazy
from django.contrib... | 'user_login_form': AuthenticationForm(),
'user_register_form': UserCreationForm()
}
if request.method == "POST":
form = UrlCreateForm(request.POST)
if form.is_valid():
form.instance.user = (
request.user if request.user.is_authenticated() ... | 'absolute_uri': request.build_absolute_uri(),
'user': request.user
}
else:
context = { | random_line_split |
views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponsePermanentRedirect, Http404, HttpResponseRedirect
from django.views.decorators.http import require_GET
from django.contrib.auth import login, authenticate
from django.core.urlresolvers import reverse_lazy
from django.contrib... |
context['change_form'] = form
return render(request, 'index.html', context)
| form = UrlCreateForm() | conditional_block |
workshopsEntry.js | 'use strict'
let immstruct = require('immstruct')
let ReactDom = require('react-dom')
let router = require('./router')
let Logger = require('@arve.knudsen/js-logger')
let ajax = require('./ajax')
let routeMap = require('./workshopsRouteMap')
require('./styles/fonts.css')
Logger.useDefaults({
formatter: (messages, ... |
Logger.getDefaultHandler()(messages, context)
})
let logger = Logger.get('entry')
window.onerror = (message, url, line) => {
// TODO: Show dialog?
logger.error(`Uncaught exception, at ${url}:${line}:\n${message}`)
}
let initialState = JSON.parse(document.getElementById('initial-state').getAttribute('data-jso... | {
ajax.postJson('/api/logError', {
error: messages[0],
})
} | conditional_block |
workshopsEntry.js | 'use strict'
let immstruct = require('immstruct')
let ReactDom = require('react-dom')
let router = require('./router')
let Logger = require('@arve.knudsen/js-logger')
let ajax = require('./ajax')
let routeMap = require('./workshopsRouteMap')
require('./styles/fonts.css')
Logger.useDefaults({
formatter: (messages, ... | let render = () => {
ReactDom.render(router.Router(structure.cursor()), document.getElementById('container'))
}
render()
structure.on('swap', render) | Stripe.setPublishableKey(initialState.stripeKey)
let structure = immstruct('state', initialState)
router.performInitial(structure.cursor(), routeMap)
| random_line_split |
client.rs | use std;
import core::result::*;
import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str |
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port);
let r = connect(sock, sockaddr);
if failure(r) {
fail #fmt("cannot connect to %s:%u", host, port as uint);
}
... | {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
} | identifier_body |
client.rs | use std;
import core::result::*;
import socket::*;
fn | (bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port)... | from_bytes_n | identifier_name |
client.rs | import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = ne... | use std;
import core::result::*; | random_line_split | |
client.rs | use std;
import core::result::*;
import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet... |
send_str(sock, "HELLO", 0u);
let buf = vec::init_elt_mut(1024u, 0u8);
let size = recv(sock, buf, 0u);
let s = from_bytes_n(buf, size as uint);
std::io::println(s);
}
| {
fail #fmt("cannot connect to %s:%u", host, port as uint);
} | conditional_block |
position.mako.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 http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Position", inherited=False) %>
%... | (_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_integer(input)
}
</%helpers:longhand>
${helpers.predefined_type("flex-basis",
"LengthOrPercentageOrAutoOrContent",
"computed::LengthOrPercentageOrAutoOrContent... | parse | identifier_name |
position.mako.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 http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Position", inherited=False) %>
%... | ${helpers.predefined_type("flex-grow", "Number", "0.0", "parse_non_negative", experimental=True)}
${helpers.predefined_type("flex-shrink", "Number", "1.0", "parse_non_negative", experimental=True)}
${helpers.single_keyword("align-self", "auto stretch flex-start flex-end center baseline",
expe... | // Flex item properties | random_line_split |
remakerings.py | #!/home/mjwtom/install/python/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
from nodes import storage_nodes as ips
def | ():
print (os.environ["PATH"])
os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.environ["PATH"]
print (os.environ["PATH"])
dev = 'sdb1'
ETC_SWIFT='/etc/swift'
if not os.path.exists(ETC_SWIFT):
os.makedirs(ETC_SWIFT)
if os.path.exists(ETC_SWIFT+'/backups'):
c... | generate_rings | identifier_name |
remakerings.py | #!/home/mjwtom/install/python/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
from nodes import storage_nodes as ips
def generate_rings():
print (os.environ["PATH"])
os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.environ["PATH"]
print (os.environ["PATH"])
dev = 'sdb... |
cmd = ['swift-ring-builder',
'%s' % builder,
'rebalance']
subprocess.call(cmd)
if __name__ == '__main__':
generate_rings() | cmd = ['swift-ring-builder',
'%s' % builder,
'add',
'r%dz%d-%s:%d/%s' % (i, i, ip, port, dev),
'1']
subprocess.call(cmd)
i += 1 | conditional_block |
remakerings.py | #!/home/mjwtom/install/python/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
from nodes import storage_nodes as ips
def generate_rings():
print (os.environ["PATH"])
os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.environ["PATH"]
print (os.environ["PATH"])
dev = 'sdb... | subprocess.call(cmd)
if __name__ == '__main__':
generate_rings() | random_line_split | |
remakerings.py | #!/home/mjwtom/install/python/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
from nodes import storage_nodes as ips
def generate_rings():
| continue
shotname, extentsion = os.path.splitext(file)
if (extentsion == '.builder') or (extentsion == '.gz'):
try:
os.remove(path)
except Exception as e:
print e
for builder, port in [('object.builder', 6000),
... | print (os.environ["PATH"])
os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.environ["PATH"]
print (os.environ["PATH"])
dev = 'sdb1'
ETC_SWIFT='/etc/swift'
if not os.path.exists(ETC_SWIFT):
os.makedirs(ETC_SWIFT)
if os.path.exists(ETC_SWIFT+'/backups'):
cmd = ['r... | identifier_body |
functools_lru_cache.py | # backports.functools_lru_cache v1.5
# https://github.com/jaraco/backports.functools_lru_cache
# Copyright (c) 2014-2018 Jason R. Coombs
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software wit... | # cache while the lock was released. since the link
# update is already done, we need only return the
# computed result and update the count of misses.
pass
elif _len(cache) >= maxsize:
... | key = make_key(args, kwds, typed) if kwds or typed else args
with lock:
link = cache_get(key)
if link is not None:
# record recent use of the key by moving it to the front of the list
root, = nonlocal_root
... | identifier_body |
functools_lru_cache.py | # backports.functools_lru_cache v1.5
# https://github.com/jaraco/backports.functools_lru_cache
# Copyright (c) 2014-2018 Jason R. Coombs
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software wit... | (*args, **kwds):
# no caching, just do a statistics update after a successful call
result = user_function(*args, **kwds)
stats[MISSES] += 1
return result
elif maxsize is None:
def wrapper(*args, **kwds):
# simple cachi... | wrapper | identifier_name |
functools_lru_cache.py | # backports.functools_lru_cache v1.5
# https://github.com/jaraco/backports.functools_lru_cache
# Copyright (c) 2014-2018 Jason R. Coombs
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software wit... |
else:
# put result in a new link at the front of the list
last = root[PREV]
link = [last, root, key, result]
last[NEXT] = root[PREV] = cache[key] = link
stats[MISSES] += 1
... | oldroot = root
oldroot[KEY] = key
oldroot[RESULT] = result
# empty the oldest link and make it the new root
root = nonlocal_root[0] = oldroot[NEXT]
oldkey = root[KEY]
root[KEY]... | conditional_block |
functools_lru_cache.py | # backports.functools_lru_cache v1.5
# https://github.com/jaraco/backports.functools_lru_cache
# Copyright (c) 2014-2018 Jason R. Coombs
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software wit... | # put result in a new link at the front of the list
last = root[PREV]
link = [last, root, key, result]
last[NEXT] = root[PREV] = cache[key] = link
stats[MISSES] += 1
return result
... | del cache[oldkey]
cache[key] = oldroot
else: | random_line_split |
keyring_demo.py | """
keyring_demo.py
This demo shows how to create a new keyring and enable it in keyring lib.
Created by Kang Zhang on 2009-07-12
"""
import os
KEYRINGRC = "keyringrc.cfg"
def load_keyring_by_config():
"""This function shows how to enable a keyring using config file
"""
# create the config file
co... | ():
"""This function shows how to create a keyring manully and use it
in runtime
"""
# define a new keyring class which extends the KeyringBackend
import keyring.backend
class TestKeyring(keyring.backend.KeyringBackend):
"""A test keyring which always outputs same password
"""
... | set_keyring_in_runtime | identifier_name |
keyring_demo.py | """
keyring_demo.py
This demo shows how to create a new keyring and enable it in keyring lib.
Created by Kang Zhang on 2009-07-12
"""
import os
KEYRINGRC = "keyringrc.cfg"
def load_keyring_by_config():
"""This function shows how to enable a keyring using config file
"""
# create the config file
co... | # import the keyring lib, the lib will automaticlly load the
# config file and load the user defined module
import keyring
# invoke the keyring to store and fetch the password
try:
keyring.set_password("demo-service", "tarek", "passexample")
print "password stored sucessfully"
e... | "default-keyring=simplekeyring.SimpleKeyring\n" ])
config_file.close()
| random_line_split |
keyring_demo.py | """
keyring_demo.py
This demo shows how to create a new keyring and enable it in keyring lib.
Created by Kang Zhang on 2009-07-12
"""
import os
KEYRINGRC = "keyringrc.cfg"
def load_keyring_by_config():
| except keyring.backend.PasswordSetError:
print "failed to store password"
print "password", keyring.get_password("demo-service", "tarek")
os.remove(KEYRINGRC)
def set_keyring_in_runtime():
"""This function shows how to create a keyring manully and use it
in runtime
"""
# define a... | """This function shows how to enable a keyring using config file
"""
# create the config file
config_file = open(KEYRINGRC,'w')
config_file.writelines(["[backend]\n",
# the path for the user created keyring
"keyring-path= %s\n" % str(os.path.abspath(__file__))[:-16],... | identifier_body |
keyring_demo.py | """
keyring_demo.py
This demo shows how to create a new keyring and enable it in keyring lib.
Created by Kang Zhang on 2009-07-12
"""
import os
KEYRINGRC = "keyringrc.cfg"
def load_keyring_by_config():
"""This function shows how to enable a keyring using config file
"""
# create the config file
co... | main() | conditional_block | |
jquery.sentinel.js | /*
* sentinel
* https://github.com/jaredhoyt/jquery-sentinel
*
* Copyright (c) 2015 Jared Hoyt
* Licensed under the MIT license.
*/
(function($) {
| // Collection method.
$.fn.sentinel = function() {
return this.each(function(i) {
// Do something awesome to each selected element.
$(this).html('awesome' + i);
});
};
// Static method.
$.sentinel = function(options) {
// Override default options with passed-in options.
options = ... | random_line_split | |
method-ambig-one-trait-unknown-int-type.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | // distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we couldn't infer the type of the vector just based on calling foo()...
let mut x = Vec::new(); //~ ERROR type annotations required
x.foo();
}
fn m2() {
let mut x = Vec::new();
// ...but we s... | }
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into | random_line_split |
method-ambig-one-trait-unknown-int-type.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () { }
| main | identifier_name |
method-ambig-one-trait-unknown-int-type.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl foo for Vec<isize> {
fn foo(&self) -> isize {2}
}
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we cou... | {1} | identifier_body |
union-derive-rpass.rs | // run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions. | )]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn eq(&self, rhs: &Self) -> bool { true } }
#[derive(
Clone,
Copy,
Eq
)]
union W<T: Copy> {
a: T,
}
impl<T: Copy> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } }
fn main() {
let u = U { b: 0 };
let u1 = u;
let ... |
#[derive(
Copy,
Clone,
Eq, | random_line_split |
union-derive-rpass.rs | // run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions.
#[derive(
Copy,
Clone,
Eq,
)]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn eq(&self, rhs: &Self) ... | {
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
assert!(u1 == u2);
let w = W { a: 0 };
let w1 = w.clone();
assert!(w == w1);
} | identifier_body | |
union-derive-rpass.rs | // run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions.
#[derive(
Copy,
Clone,
Eq,
)]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn | (&self, rhs: &Self) -> bool { true } }
#[derive(
Clone,
Copy,
Eq
)]
union W<T: Copy> {
a: T,
}
impl<T: Copy> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } }
fn main() {
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
assert!(u1 == u2);
let w = W { a: 0 };
... | eq | identifier_name |
account_banking_uk_hsbc.py | ##############################################################################
#
# Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
# Copyright (C) 2011 credativ Ltd (<http://www.credativ.co.uk>).
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# i... |
def info_partner(self, cr, uid, ids, name=None, args=None, context=None):
if not ids:
return {}
result = {}
info = ''
for line in self.browse(cr, uid, ids, context=context):
partner = line.bank_id
name = partner.owner_name or partner.partner_id... | if not ids:
return {}
result = {}
info = ''
for line in self.browse(cr, uid, ids, context=context):
owner = line.order_id.mode.bank_id
name = owner.owner_name or owner.partner_id.name
st = owner.street and owner.street or ''
st1 = '' ... | identifier_body |
account_banking_uk_hsbc.py | ##############################################################################
#
# Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
# Copyright (C) 2011 credativ Ltd (<http://www.credativ.co.uk>).
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# i... |
return result
# Define the info_partner and info_owner so we can override the methods
_columns = {
'info_owner': fields.function(
info_owner,
string="Owner Account",
type="text",
help='Address of the Main Partner',
),
'info_partn... | partner = line.bank_id
name = partner.owner_name or partner.partner_id.name
st = partner.street and partner.street or ''
st1 = '' # no street2 in res.partner.bank
zip = partner.zip and partner.zip or ''
city = partner.city and partner.city or ''
... | conditional_block |
account_banking_uk_hsbc.py | ##############################################################################
#
# Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
# Copyright (C) 2011 credativ Ltd (<http://www.credativ.co.uk>).
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# i... | (self, cr, uid, ids, name=None, args=None, context=None):
if not ids:
return {}
result = {}
info = ''
for line in self.browse(cr, uid, ids, context=context):
partner = line.bank_id
name = partner.owner_name or partner.partner_id.name
st =... | info_partner | identifier_name |
account_banking_uk_hsbc.py | ##############################################################################
#
# Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
# Copyright (C) 2011 credativ Ltd (<http://www.credativ.co.uk>).
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# i... | ##############################################################################
from datetime import date
from openerp.osv import orm, fields
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as OE_DATEFORMAT
class hsbc_export(orm.Model):
"""HSBC Export"""
_name = 'banking.export.hsbc'
_description = ... | # along with this program. If not, see <http://www.gnu.org/licenses/>.
# | random_line_split |
anon_db.py | """Remove any personally identifying information from the database"""
from django.core.management.base import BaseCommand
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django_openid_auth.models import UserOpenID
from rest_framework.authtoken.models import Token
from reversion.mo... | (BaseCommand):
"""Django command to anonymize the database"""
@staticmethod
def get_main_user():
"""Return the only user remaining in the DB"""
return User.objects.first()
@staticmethod
def delete_tokens():
"""Remove all auth tokens (OpenID, DRF, ...)"""
res = UserO... | Command | identifier_name |
anon_db.py | """Remove any personally identifying information from the database"""
from django.core.management.base import BaseCommand
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django_openid_auth.models import UserOpenID
from rest_framework.authtoken.models import Token
from reversion.mo... | from accounts.models import User
from common.models import Upload, News
class Command(BaseCommand):
"""Django command to anonymize the database"""
@staticmethod
def get_main_user():
"""Return the only user remaining in the DB"""
return User.objects.first()
@staticmethod
def delet... | InstallerIssueReply,
InstallerHistory,
Screenshot,
GameSubmission,
) | random_line_split |
anon_db.py | """Remove any personally identifying information from the database"""
from django.core.management.base import BaseCommand
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django_openid_auth.models import UserOpenID
from rest_framework.authtoken.models import Token
from reversion.mo... |
self.delete_tokens()
user = self.get_main_user()
res = InstallerIssue.objects.all().update(submitted_by=user)
print("Updated %s issues" % res)
res = InstallerIssueReply.objects.all().update(submitted_by=user)
print("Updated %s issue replies" % res)
res = Ins... | raise RuntimeError("Never run this in production") | conditional_block |
anon_db.py | """Remove any personally identifying information from the database"""
from django.core.management.base import BaseCommand
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django_openid_auth.models import UserOpenID
from rest_framework.authtoken.models import Token
from reversion.mo... |
@staticmethod
def delete_tokens():
"""Remove all auth tokens (OpenID, DRF, ...)"""
res = UserOpenID.objects.all().delete()
print("Deleted %s openids" % res[0])
res = Token.objects.all().delete()
print("Deleted %s tokens" % res[0])
res = LogEntry.objects.all().... | """Return the only user remaining in the DB"""
return User.objects.first() | identifier_body |
gruntfile.js | module.exports = function(grunt) {
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
// watch for changes and trigger compass, jshint, uglify and livereload
watch: {
js: {
files: ['jquery.accrue.js'... | },
}
},
// we use the Sass
sass: {
dist: {
options: {
// nested, compact, compressed, expanded
style: 'compressed'
},
files: {
'example.css': 'exam... | css: {
files: 'example.scss',
tasks: ['sass'],
options: {
livereload: true, | random_line_split |
regression_slope_validator.ts | import {ListWrapper} from '@angular/facade';
import {OpaqueToken} from '@angular/core/src/di';
import {Validator} from '../validator';
import {Statistic} from '../statistic';
import {MeasureValues} from '../measure_values';
/**
* A validator that checks the regression slope of a specific metric.
* Waits for the reg... | (): {[key: string]: any} {
return {'sampleSize': this._sampleSize, 'regressionSlopeMetric': this._metric};
}
validate(completeSample: MeasureValues[]): MeasureValues[] {
if (completeSample.length >= this._sampleSize) {
var latestSample = ListWrapper.slice(completeSample, completeSample.length - this.... | describe | identifier_name |
regression_slope_validator.ts | import {ListWrapper} from '@angular/facade';
import {OpaqueToken} from '@angular/core/src/di';
import {Validator} from '../validator';
import {Statistic} from '../statistic';
import {MeasureValues} from '../measure_values';
/**
* A validator that checks the regression slope of a specific metric.
* Waits for the reg... |
var regressionSlope = Statistic.calculateRegressionSlope(
xValues, Statistic.calculateMean(xValues), yValues, Statistic.calculateMean(yValues));
return regressionSlope >= 0 ? latestSample : null;
} else {
return null;
}
}
}
var _SAMPLE_SIZE = new OpaqueToken('RegressionSlopeValid... | {
// For now, we only use the array index as x value.
// TODO(tbosch): think about whether we should use time here instead
xValues.push(i);
yValues.push(latestSample[i].values[this._metric]);
} | conditional_block |
regression_slope_validator.ts | import {ListWrapper} from '@angular/facade';
import {OpaqueToken} from '@angular/core/src/di';
import {Validator} from '../validator';
import {Statistic} from '../statistic';
import {MeasureValues} from '../measure_values';
/**
* A validator that checks the regression slope of a specific metric.
* Waits for the reg... | ]; | {provide: _SAMPLE_SIZE, useValue: 10},
{provide: _METRIC, useValue: 'scriptTime'} | random_line_split |
regression_slope_validator.ts | import {ListWrapper} from '@angular/facade';
import {OpaqueToken} from '@angular/core/src/di';
import {Validator} from '../validator';
import {Statistic} from '../statistic';
import {MeasureValues} from '../measure_values';
/**
* A validator that checks the regression slope of a specific metric.
* Waits for the reg... |
_sampleSize: number;
_metric: string;
constructor(sampleSize, metric) {
super();
this._sampleSize = sampleSize;
this._metric = metric;
}
describe(): {[key: string]: any} {
return {'sampleSize': this._sampleSize, 'regressionSlopeMetric': this._metric};
}
validate(completeSample: Measur... | { return _PROVIDERS; } | identifier_body |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
annotatable: Annotatable)
-> Annotatable {
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpec... | expand_derive | identifier_name |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
if !(is_builtin_trait(tname) || cx.ecfg.enable_custom_derive()) {
feature_gate::emit_feature_err(&cx.parse_sess.span_diagnostic,
"custom_derive",
titem.span,
... | {
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpected value in `derive`");
}
let traits = mitem.meta_item_list().unwrap_or(&[]);
if traits.is_empty() {
cx.... | identifier_body |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
for titem in traits.iter().rev() {
let tname = match titem.node {
MetaWord(ref tname) => tname,
_ => {
cx.span_err(titem.span, "malformed `derive` entry");
continue;
}
... | {
cx.span_warn(mitem.span, "empty trait list in `derive`");
} | conditional_block |
mod.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
//! The compiler code necessary to implement the `#[derive]` extensions.
//!
//! FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is
//! the standard library, and "std" is the core library.
use ast::{MetaItem, MetaWord};
use attr::AttrMetaMethods;
use ext::base::{ExtCtxt, S... | // except according to those terms. | random_line_split |
i18n-router.http-loader.ts | // angular
import { HttpClient } from '@angular/common/http';
import { Routes } from '@angular/router';
// libs
import * as _ from 'lodash';
import { I18NRouterLoader, I18NRouterSettings } from '@ngx-i18n-router/core';
export class I18NRouterHttpLoader implements I18NRouterLoader {
private _translations: any;
ge... |
constructor(private readonly http: HttpClient,
private readonly path: string = '/routes.json',
private readonly providedSettings: I18NRouterSettings = {}) {
}
loadTranslations(): any {
return new Promise((resolve, reject) => {
this.http.get(this.path)
.subscribe(re... | {
return this._translations;
} | identifier_body |
i18n-router.http-loader.ts | // angular
import { HttpClient } from '@angular/common/http';
import { Routes } from '@angular/router';
// libs
import * as _ from 'lodash';
import { I18NRouterLoader, I18NRouterSettings } from '@ngx-i18n-router/core';
export class I18NRouterHttpLoader implements I18NRouterLoader {
private _translations: any;
ge... | return this._translations;
}
constructor(private readonly http: HttpClient,
private readonly path: string = '/routes.json',
private readonly providedSettings: I18NRouterSettings = {}) {
}
loadTranslations(): any {
return new Promise((resolve, reject) => {
this.http.ge... | random_line_split | |
i18n-router.http-loader.ts | // angular
import { HttpClient } from '@angular/common/http';
import { Routes } from '@angular/router';
// libs
import * as _ from 'lodash';
import { I18NRouterLoader, I18NRouterSettings } from '@ngx-i18n-router/core';
export class | implements I18NRouterLoader {
private _translations: any;
get routes(): Routes {
return _.map(this.providedSettings.routes, _.cloneDeep);
}
get translations(): any {
return this._translations;
}
constructor(private readonly http: HttpClient,
private readonly path: string = '/routes... | I18NRouterHttpLoader | identifier_name |
imp.py | _imp import create_dynamic
except ImportError:
# Platform doesn't support dynamic loading.
create_dynamic = None
from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
from importlib._bootstrap_external import SourcelessFileLoader
from importlib import machinery
from importlib import uti... |
else:
path = sys.path
for entry in path:
package_directory = os.path.join(entry, name)
for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
package_file_name = '__init__' + suffix
file_path = os.path.join(package_directory, package_file_name)
... | return None, None, ('', '', PY_FROZEN) | conditional_block |
imp.py | _imp import create_dynamic
except ImportError:
# Platform doesn't support dynamic loading.
create_dynamic = None
from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
from importlib._bootstrap_external import SourcelessFileLoader
from importlib import machinery
from importlib import uti... | (name, path):
"""**DEPRECATED**"""
if os.path.isdir(path):
extensions = (machinery.SOURCE_SUFFIXES[:] +
machinery.BYTECODE_SUFFIXES[:])
for extension in extensions:
path = os.path.join(path, '__init__'+extension)
if os.path.exists(path):
... | load_package | identifier_name |
imp.py | _imp import create_dynamic
except ImportError:
# Platform doesn't support dynamic loading.
create_dynamic = None
from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
from importlib._bootstrap_external import SourcelessFileLoader
from importlib import machinery
from importlib import uti... |
def get_magic():
"""**DEPRECATED**
Return the magic number for .pyc files.
"""
return util.MAGIC_NUMBER
def get_tag():
"""Return the magic tag for .pyc files."""
return sys.implementation.cache_tag
def cache_from_source(path, debug_override=None):
"""**DEPRECATED**
Given the pat... | """**DEPRECATED**
Create a new module.
The module is not entered into sys.modules.
"""
return types.ModuleType(name) | identifier_body |
imp.py | from _imp import create_dynamic
except ImportError:
# Platform doesn't support dynamic loading.
create_dynamic = None
from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
from importlib._bootstrap_external import SourcelessFileLoader
from importlib import machinery
from importlib impor... | def find_module(self, fullname):
"""Always returns None."""
return None
class _HackedGetData:
"""Compatibility support for 'file' arguments of various load_*()
functions."""
def __init__(self, fullname, path, file=None):
super().__init__(fullname, path)
self.file = fi... | random_line_split | |
group.ts | * this filter is applied to all layers within this group.
* If clustering is enabled all features in all layers are grouped together | title: string;
description: string;
layers: Array<ProjectLayer>;
filters: Array<GroupFilter>;
/* Including styles in (projectgroups in) project.json files is probably not a good idea, in case the layers
in the group have properties (attributes), as for example in geojs... | */
export class ProjectGroup {
id: string; | random_line_split |
group.ts | this filter is applied to all layers within this group.
* If clustering is enabled all features in all layers are grouped together
*/
export class ProjectGroup {
id: string;
title: string;
description: string;
layers: Array<ProjectLayer>;
filters: Array<GroupFilter... |
return res;
}
public loadLayersFromOWS($injector: ng.auto.IInjectorService = null): void {
this.layers = []; // add some layers here...
this.isLoading = true;
if ($injector == null) { // create an injector if not given
$injector = an... | {
res.layers.forEach(layer => {
if (!layer.opacity) layer.opacity = 100;
});
} | conditional_block |
group.ts | * this filter is applied to all layers within this group.
* If clustering is enabled all features in all layers are grouped together
*/
export class | {
id: string;
title: string;
description: string;
layers: Array<ProjectLayer>;
filters: Array<GroupFilter>;
/* Including styles in (projectgroups in) project.json files is probably not a good idea, in case the layers
in the group have properties (attributes), ... | ProjectGroup | identifier_name |
group.ts | * this filter is applied to all layers within this group.
* If clustering is enabled all features in all layers are grouped together
*/
export class ProjectGroup {
id: string;
title: string;
description: string;
layers: Array<ProjectLayer>;
filters: Array<GroupFilt... | });
$translate('WHITE_BLUE').then((translation) => {
this.colorScales[translation] = ['white', 'blue'];
});
$translate('BLUE_WHITE').then((translation) => {
this.colorScales[translation] = ['blue', 'white'];
});
$tra... | {
this.availableAspects = ['strokeColor', 'fillColor', 'strokeWidth', 'height'];
this.colorScales = {};
this.legends = {};
this.fixedColorRange = false;
$translate('WHITE_RED').then((translation) => {
this.colorScales[translation] = ['white', ... | identifier_body |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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 http://mozilla.org/MPL/2.0/.
//! Fast and lightweight Slab Allocator.
extern cra... | unsafe {
let elem_ptr = self.mem.offset(x as isize);
ptr::drop_in_place(elem_ptr);
}
}
unsafe { libc::free(self.mem as *mut _ as *mut libc::c_void) };
}
}
impl<T> Index<usize> for Slab<T> {
type Output = T;
fn index(&self, index: usiz... | for x in 0..self.len() { | random_line_split |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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 http://mozilla.org/MPL/2.0/.
//! Fast and lightweight Slab Allocator.
extern cra... |
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: usize) -> T {
assert!(offset < self.len, "Offset out of bounds");
let elem: T;
let last_elem: T;
let elem_ptr: *mut T;
... | {
if self.len == self.capacity {
self.reallocate();
}
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
} | identifier_body |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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 http://mozilla.org/MPL/2.0/.
//! Fast and lightweight Slab Allocator.
extern cra... | (&self, index: usize) -> &Self::Output {
assert!(index < self.len, "Index out of bounds");
unsafe { &(*(self.mem.offset(index as isize))) }
}
}
impl<'a, T> Iterator for SlabIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
while self.current_offset < self.slab.l... | index | identifier_name |
lib.rs | // Copyright 2016 Nathan Sizemore <nathanrsizemore@gmail.com>
//
// 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 http://mozilla.org/MPL/2.0/.
//! Fast and lightweight Slab Allocator.
extern cra... |
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
}
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: us... | {
self.reallocate();
} | conditional_block |
ezmenu.py | #! /usr/bin/env python
# I found this file inside Super Mario Bros python
# written by HJ https://sourceforge.net/projects/supermariobrosp/
# the complete work is licensed under GPL3 although I can not determine# license of this file | import pygame
class EzMenu:
def __init__(self, *options):
self.options = options
self.x = 0
self.y = 0
self.font = pygame.font.Font(None, 32)
self.option = 0
self.width = 1
self.color = [0, 0, 0]
self.hcolor = [255, 0, 0]
self.height = len(... | # maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html
| random_line_split |
ezmenu.py | #! /usr/bin/env python
# I found this file inside Super Mario Bros python
# written by HJ https://sourceforge.net/projects/supermariobrosp/
# the complete work is licensed under GPL3 although I can not determine# license of this file
# maybe this is the original author, we can contact him/her http://www.pygame.org/pro... | (self, color):
self.hcolor = color
def set_normal_color(self, color):
self.color = color
def center_at(self, x, y):
self.x = x-(self.width/2)
self.y = y-(self.height/2)
| set_highlight_color | identifier_name |
ezmenu.py | #! /usr/bin/env python
# I found this file inside Super Mario Bros python
# written by HJ https://sourceforge.net/projects/supermariobrosp/
# the complete work is licensed under GPL3 although I can not determine# license of this file
# maybe this is the original author, we can contact him/her http://www.pygame.org/pro... |
surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4)))
i+=1
def update(self, events):
for e in events:
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_DOWN:
self.option += 1... | self.width = ren.get_width() | conditional_block |
ezmenu.py | #! /usr/bin/env python
# I found this file inside Super Mario Bros python
# written by HJ https://sourceforge.net/projects/supermariobrosp/
# the complete work is licensed under GPL3 although I can not determine# license of this file
# maybe this is the original author, we can contact him/her http://www.pygame.org/pro... |
def draw(self, surface):
i=0
for o in self.options:
if i==self.option:
clr = self.hcolor
else:
clr = self.color
text = o[0]
ren = self.font.render(text, 2, clr)
if ren.get_width() > self.width:
... | self.options = options
self.x = 0
self.y = 0
self.font = pygame.font.Font(None, 32)
self.option = 0
self.width = 1
self.color = [0, 0, 0]
self.hcolor = [255, 0, 0]
self.height = len(self.options)*self.font.get_height()
for o in self.options:
... | identifier_body |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
fn f<T:Quux>(a: &T) {
assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| { 30 } | identifier_body |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
} | impl Bar for A { fn g(&self) -> int { 20 } }
impl Baz for A { fn h(&self) -> int { 30 } }
fn f<T:Quux>(a: &T) { | random_line_split |
trait-inheritance-auto.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> int { 30 } }
fn f<T:Quux>(a: &T) {
assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
| h | identifier_name |
sound.js | 'use strict';
define([
'three',
'explorer',
'underscore'
], function(
THREE,
Explorer,
_
) {
var mp3names = ['crystalCenter', 'cellCollision', 'atomCollision', 'popOutOfAtom', 'dollHolder', 'atomUnderDoll', 'navCube', 'dollArrived', 'leapGrab', 'leapNoGrab'];
function Sound(animationMachine) | this.procced = false;
alert('Web Audio API not supported in this browser.');
}
if(this.procced === true){
this.universalGainNode = this.context.createGain();
this.universalGainNode.gain.value = 0.75;
this.universalGainNode.connect(this.context.destination);
}
}
;
... | {
this.procced = true, this.context ;
this.animationMachine = animationMachine ;
this.mute = true ;
this.buffers = [] ;
this.crystalHold ;
this.crystalCameraOrbit ;
this.crysCentrSource = {panner: undefined , dryGain: undefined , panX : 0, panZ : 0, gain : 0 };
this.steredLoops = {};... | identifier_body |
sound.js | 'use strict';
define([
'three',
'explorer',
'underscore'
], function(
THREE,
Explorer,
_
) {
var mp3names = ['crystalCenter', 'cellCollision', 'atomCollision', 'popOutOfAtom', 'dollHolder', 'atomUnderDoll', 'navCube', 'dollArrived', 'leapGrab', 'leapNoGrab'];
function Sound(animationMachine) {
... | data = this.calculatePanning(sourcePos);
var dryGain = this.context.createGain();
var panner = this.context.createPanner();
panner.setPosition(data.panX, data.panY, data.panZ);
dryGain.gain.value = data.gain;
voice.connect(dryGain);
dryGain.connect(pa... | var data;
var voice = this.context.createBufferSource();
voice.buffer = this.buffers[sampleName] ;
if(calcPanning){ | random_line_split |
sound.js | 'use strict';
define([
'three',
'explorer',
'underscore'
], function(
THREE,
Explorer,
_
) {
var mp3names = ['crystalCenter', 'cellCollision', 'atomCollision', 'popOutOfAtom', 'dollHolder', 'atomUnderDoll', 'navCube', 'dollArrived', 'leapGrab', 'leapNoGrab'];
function Sound(animationMachine) {
... |
};
Sound.prototype.play = function(sampleName, sourcePos, calcPanning) {
if(!this.mute && mp3names.length === Object.keys(this.buffers).length){
var data;
var voice = this.context.createBufferSource();
voice.buffer = this.buffers[sampleName] ;
if(calcPanning){
data = this.ca... | {
voice = this.context.createBufferSource();
voice.buffer = this.buffers[sampleName] ;
voice.connect(this.universalGainNode);
this.steredLoops[sampleName] = voice ;
voice.start(0);
} | conditional_block |
sound.js | 'use strict';
define([
'three',
'explorer',
'underscore'
], function(
THREE,
Explorer,
_
) {
var mp3names = ['crystalCenter', 'cellCollision', 'atomCollision', 'popOutOfAtom', 'dollHolder', 'atomUnderDoll', 'navCube', 'dollArrived', 'leapGrab', 'leapNoGrab'];
function | (animationMachine) {
this.procced = true, this.context ;
this.animationMachine = animationMachine ;
this.mute = true ;
this.buffers = [] ;
this.crystalHold ;
this.crystalCameraOrbit ;
this.crysCentrSource = {panner: undefined , dryGain: undefined , panX : 0, panZ : 0, gain : 0 };
thi... | Sound | identifier_name |
0003_auto_20150128_0800.py | # -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
# Can't use the callable because the app registry is not ready yet.
# Really trusting users her... | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(DJSTRIPE_UNSAFE_SUBSCRIBER_MODEL),
('djstripe', '0002_auto_20150122_2000'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='subscriber',
field=models.On... | Migration | identifier_name |
0003_auto_20150128_0800.py | # -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
# Can't use the callable because the app registry is not ready yet.
# Really trusting users her... | dependencies = [
migrations.swappable_dependency(DJSTRIPE_UNSAFE_SUBSCRIBER_MODEL),
('djstripe', '0002_auto_20150122_2000'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='subscriber',
field=models.OneToOneField(null=True, on_del... | identifier_body | |
0003_auto_20150128_0800.py | # -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import django.db.models.deletion
from django.conf import settings |
# Can't use the callable because the app registry is not ready yet.
# Really trusting users here... bad idea? probably.
DJSTRIPE_UNSAFE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL)
class Migration(migrations.Migration):
dependencies = [
migrations.swappabl... | from django.db import migrations, models | random_line_split |
tmi.js-tests.ts | import * as tmi from "tmi.js";
const options: tmi.Options = {
channels: ['#channel1', '#channel2'],
connection: {
maxReconnectAttempts: 2,
maxReconnectInverval: 10,
port: 100,
reconnect: true,
reconnectDecay: 20,
reconnectInterval: 10,
secure: true,
... | options: {
clientId: "xxxapiidherexxx",
debug: true
}
};
const client: tmi.Client = tmi.Client(options);
client.connect().then(() => {
client.on("subscription", (channel: string, username: string, methods: tmi.SubMethods, msg: string, userstate: tmi.SubUserstate) => {
client.say(ch... | info: (message) => { },
}, | random_line_split |
tmi.js-tests.ts | import * as tmi from "tmi.js";
const options: tmi.Options = {
channels: ['#channel1', '#channel2'],
connection: {
maxReconnectAttempts: 2,
maxReconnectInverval: 10,
port: 100,
reconnect: true,
reconnectDecay: 20,
reconnectInterval: 10,
secure: true,
... |
userstate["display-name"];
userstate["emotes-raw"];
userstate["badges-raw"];
userstate["message-type"];
userstate["msg-param-cumulative-months"];
userstate["msg-param-should-share-streak"];
userstate["msg-param-streak-months"];
userstate["msg-param-sub-pl... | {
const { admin, turbo, subscriber, bits, broadcaster, global_mod, moderator, premium, staff, vip, partner, founder } = badges;
} | conditional_block |
app_blink_stm32f4.rs | #![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)] | zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
function: pin::GPIOOut
};
led1.setup();
led2.setup();
let timer = timer::Timer::new(timer::Timer2, 25u32);
... | pub unsafe fn main() {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack(); | random_line_split |
app_blink_stm32f4.rs | #![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
pub unsafe fn | () {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
functi... | main | identifier_name |
app_blink_stm32f4.rs | #![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
pub unsafe fn main() |
loop {
led1.set_high();
led2.set_low();
timer.wait_ms(300);
led1.set_low();
led2.set_high();
timer.wait_ms(300);
}
}
| {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
function:... | identifier_body |
reduxUtils.ts | /*
* 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 http://mozilla.org/MPL/2.0/.
*
* @Author: JB (jb@codecorsair.com)
* @Date: 2016-08-29 17:31:15
* @Last Modified by: JB (jb@codecorsair.com)
... | return next(action)
} catch (err) {
console.error('Caught an exception!', err)
console.log('state', store.getState());
throw err
}
}
}
export function thunkMiddleware(store: any) {
return (next: any) => (action: any) => {
return typeof action === 'function' ? action(store.dispat... | return (next: (action: BaseAction) => BaseAction) => (action: BaseAction) => {
try { | random_line_split |
reduxUtils.ts | /*
* 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 http://mozilla.org/MPL/2.0/.
*
* @Author: JB (jb@codecorsair.com)
* @Date: 2016-08-29 17:31:15
* @Last Modified by: JB (jb@codecorsair.com)
... | (store: any) {
return (next: any) => (action: any) => {
return typeof action === 'function' ? action(store.dispatch, store.getState) : next(action);
}
}
export interface Action<STATETYPE> {
(state: STATETYPE, action: any): STATETYPE;
}
export function createReducer<STATETYPE>(defaultState: STATETYPE, action... | thunkMiddleware | identifier_name |
reduxUtils.ts | /*
* 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 http://mozilla.org/MPL/2.0/.
*
* @Author: JB (jb@codecorsair.com)
* @Date: 2016-08-29 17:31:15
* @Last Modified by: JB (jb@codecorsair.com)
... |
export function thunkMiddleware(store: any) {
return (next: any) => (action: any) => {
return typeof action === 'function' ? action(store.dispatch, store.getState) : next(action);
}
}
export interface Action<STATETYPE> {
(state: STATETYPE, action: any): STATETYPE;
}
export function createReducer<STATETYPE... | {
return (next: (action: BaseAction) => BaseAction) => (action: BaseAction) => {
try {
return next(action)
} catch (err) {
console.error('Caught an exception!', err)
console.log('state', store.getState());
throw err
}
}
} | identifier_body |
adsr.rs | // Copyright 2017 Google Inc. All rights reserved.
//
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | Adsr {
value: -24.0,
state: Quiet,
}
}
}
impl Module for Adsr {
fn n_ctrl_out(&self) -> usize { 1 }
fn handle_note(&mut self, _midi_num: f32, _velocity: f32, on: bool) {
if on {
self.state = Attack;
} else {
self.state = Relea... | pub fn new() -> Adsr { | random_line_split |
adsr.rs | // Copyright 2017 Google Inc. All rights reserved.
//
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | () -> Adsr {
Adsr {
value: -24.0,
state: Quiet,
}
}
}
impl Module for Adsr {
fn n_ctrl_out(&self) -> usize { 1 }
fn handle_note(&mut self, _midi_num: f32, _velocity: f32, on: bool) {
if on {
self.state = Attack;
} else {
self.... | new | identifier_name |
grading_record.py | #!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
else:
# no ProjectSurveyRecord on file while there is a survey to be taken
grade_decision = 'fail'
fields['grade_decision'] = grade_decision
# return the fields that should be set for a GradingRecord
return fields
logic = Logic()
| grade_decision = 'pass' if grading_survey_record.grade else 'fail' | conditional_block |
grading_record.py | #!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | (self,
model=soc.modules.gsoc.models.grading_record.GradingRecord,
base_model=None, scope_logic=None):
"""Defines the name, key_name and model for this entity.
"""
super(Logic, self).__init__(model=model, base_model=base_model,
scope_logic=scope... | __init__ | identifier_name |
grading_record.py | #!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | survey_group,
record_entity)
if not record_entity and project_entity.status in ['failed', 'invalid'] \
and not record_fields['mentor_record'] \
and not record_fields['student_record']:
... | """Updates or creates a GradingRecord in a batch.
Args:
survey_group: GradingSurveyGroup entity
project_entities: list of project_entities which to process
"""
records_to_store = []
query_fields = {'grading_survey_group': survey_group}
for project_entity in project_entities:
# ... | identifier_body |
grading_record.py | #!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | query_fields['project'] = project_entity
# try to retrieve an existing record
record_entity = self.getForFields(query_fields, unique=True)
# retrieve the fields that should be set
record_fields = self.getFieldsForGradingRecord(project_entity,
... |
query_fields = {'grading_survey_group': survey_group}
for project_entity in project_entities:
# set a new project to query for | random_line_split |
console.rs | use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console;
impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn new() -> Console {
... | }
println!(" timer_data:");
for (key, values) in buckets.timer_data().iter() {
println!(" {}: {:?}", key, values);
}
}
}
| {
let now = time::get_time();
println!("Flushing metrics: {}", time::at(now).rfc822().to_string());
println!(" bad_messages: {}", buckets.bad_messages());
println!(" total_messages: {}", buckets.total_messages());
println!(" counters:");
for (key, value) in buckets.c... | identifier_body |
console.rs | use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console; | impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn new() -> Console {
Console
}
}
/// Print a single stats line.
fn fmt_line(key: &str, value: &f64) {
println!(" {}: {}", key... | random_line_split | |
console.rs | use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console;
impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn | () -> Console {
Console
}
}
/// Print a single stats line.
fn fmt_line(key: &str, value: &f64) {
println!(" {}: {}", key, value)
}
impl Backend for Console {
fn flush_buckets(&mut self, buckets: &Buckets) {
let now = time::get_time();
println!("Flushing metrics: {}", time::at(n... | new | identifier_name |
main.py | import sys
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'gae.settings.settings' | # https://developers.google.com/appengine/docs/python/tools/libraries27
# ===========
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
# ===========
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
import django.core.handlers.wsgi
import django.core.signal... |
# ===========
# Add any python 3rd party module that doesnt exist at | random_line_split |
main.py | import sys
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'gae.settings.settings'
# ===========
# Add any python 3rd party module that doesnt exist at
# https://developers.google.com/appengine/docs/python/tools/libraries27
# ===========
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
# ===========
#... | (*args, **kwargs):
logging.exception('Exception in request:')
django.dispatch.Signal.connect(
django.core.signals.got_request_exception, log_exception)
# Unregister the rollback event handler.
#django.dispatch.Signal.disconnect(
# django.core.signals.got_request_exception,
# django.db._rollback_on_excep... | log_exception | identifier_name |
main.py | import sys
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'gae.settings.settings'
# ===========
# Add any python 3rd party module that doesnt exist at
# https://developers.google.com/appengine/docs/python/tools/libraries27
# ===========
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
# ===========
#... |
django.dispatch.Signal.connect(
django.core.signals.got_request_exception, log_exception)
# Unregister the rollback event handler.
#django.dispatch.Signal.disconnect(
# django.core.signals.got_request_exception,
# django.db._rollback_on_exception)
app = django.core.handlers.wsgi.WSGIHandler()
| logging.exception('Exception in request:') | identifier_body |
bundle.js | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.ex... | () {
// add any functionality and listeners you want here
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var saveTask = document.getElementById("saveTask");
// Get the <span> element that closes the modal
var... | initializePage | identifier_name |
bundle.js | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.ex... |
/*
* Function that is called when the document is ready.
*/
function initializePage() {
// add any functionality and listeners you want here
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var saveTask = docu... | {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data2.json", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.