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 |
|---|---|---|---|---|
avatar.view.js | import React, { Component, PropTypes } from 'react'
import cx from 'classnames'
import { capitalize } from 'utils'
import './avatar.view.styl'
const DEFAULT_AVATAR_URL = require('./assets/default-avator@2x.png')
export class Avatar extends Component {
static propTypes = {
className: PropTypes.string,
url... | () {
return cx(
'avatarView',
[`size${capitalize(this.props.size)}`],
this.props.className
)
}
getAvatarUrl () {
const avatarUrl = this.props.url || DEFAULT_AVATAR_URL
return {
backgroundImage: `url(${avatarUrl})`
}
}
render () {
return (
<div
cl... | getRootClassnames | identifier_name |
vec_box_sized.rs | // run-rustfix
#![allow(dead_code)]
struct SizedStruct(i32);
struct UnsizedStruct([i32]);
struct BigStruct([i32; 10000]);
/// The following should trigger the lint
mod should_trigger {
use super::SizedStruct;
const C: Vec<Box<i32>> = Vec::new();
static S: Vec<Box<i32>> = Vec::new();
struct StructWit... | () -> Vec<Box<S>> {
vec![]
}
}
}
fn main() {}
| f | identifier_name |
vec_box_sized.rs | // run-rustfix
#![allow(dead_code)]
struct SizedStruct(i32);
struct UnsizedStruct([i32]);
struct BigStruct([i32; 10000]);
/// The following should trigger the lint
mod should_trigger {
use super::SizedStruct;
const C: Vec<Box<i32>> = Vec::new();
static S: Vec<Box<i32>> = Vec::new();
struct StructWit... | unsized_type: Vec<Box<UnsizedStruct>>,
}
struct TraitVec<T: ?Sized> {
// Regression test for #3720. This was causing an ICE.
inner: Vec<Box<T>>,
}
}
mod inner_mod {
mod inner {
pub struct S;
}
mod inner2 {
use super::inner::S;
pub fn f() -> Vec... | struct StructWithVecBoxButItsUnsized { | random_line_split |
upgrade.rs | use header::{Header, HeaderFormat};
use std::fmt;
use std::str::FromStr;
use header::parsing::{from_comma_delimited, fmt_comma_delimited};
use unicase::UniCase;
use self::Protocol::{WebSocket, ProtocolExt}; | pub struct Upgrade(pub Vec<Protocol>);
deref!(Upgrade => Vec<Protocol>);
/// Protocol values that can appear in the Upgrade header.
#[derive(Clone, PartialEq, Debug)]
pub enum Protocol {
/// The websocket protocol.
WebSocket,
/// Some other less common protocol.
ProtocolExt(String),
}
impl FromStr fo... |
/// The `Upgrade` header.
#[derive(Clone, PartialEq, Debug)] | random_line_split |
upgrade.rs | use header::{Header, HeaderFormat};
use std::fmt;
use std::str::FromStr;
use header::parsing::{from_comma_delimited, fmt_comma_delimited};
use unicase::UniCase;
use self::Protocol::{WebSocket, ProtocolExt};
/// The `Upgrade` header.
#[derive(Clone, PartialEq, Debug)]
pub struct Upgrade(pub Vec<Protocol>);
deref!(Upg... |
fn parse_header(raw: &[Vec<u8>]) -> Option<Upgrade> {
from_comma_delimited(raw).map(|vec| Upgrade(vec))
}
}
impl HeaderFormat for Upgrade {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Upgrade(ref parts) = *self;
fmt_comma_delimited(fmt, &parts[..])
}
}
... | {
"Upgrade"
} | identifier_body |
upgrade.rs | use header::{Header, HeaderFormat};
use std::fmt;
use std::str::FromStr;
use header::parsing::{from_comma_delimited, fmt_comma_delimited};
use unicase::UniCase;
use self::Protocol::{WebSocket, ProtocolExt};
/// The `Upgrade` header.
#[derive(Clone, PartialEq, Debug)]
pub struct Upgrade(pub Vec<Protocol>);
deref!(Upg... | () -> &'static str {
"Upgrade"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Upgrade> {
from_comma_delimited(raw).map(|vec| Upgrade(vec))
}
}
impl HeaderFormat for Upgrade {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let Upgrade(ref parts) = *self;
f... | header_name | identifier_name |
upgrade.rs | use header::{Header, HeaderFormat};
use std::fmt;
use std::str::FromStr;
use header::parsing::{from_comma_delimited, fmt_comma_delimited};
use unicase::UniCase;
use self::Protocol::{WebSocket, ProtocolExt};
/// The `Upgrade` header.
#[derive(Clone, PartialEq, Debug)]
pub struct Upgrade(pub Vec<Protocol>);
deref!(Upg... |
}
}
impl fmt::Display for Protocol {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", match *self {
WebSocket => "websocket",
ProtocolExt(ref s) => s.as_ref()
})
}
}
impl Header for Upgrade {
fn header_name() -> &'static str {
... | {
Ok(ProtocolExt(s.to_string()))
} | conditional_block |
simd-intrinsic-float-math.rs | // run-pass
// ignore-emscripten
// ignore-android
// FIXME: this test fails on arm-android because the NDK version 14 is too old.
// It needs at least version 18. We disable it on all android build bots because
// there is no way in compile-test to disable it for an (arch,os) pair.
// Test that the simd floating-poi... | assert_approx_eq!(x, r);
let r = simd_fexp(z);
assert_approx_eq!(x, r);
let r = simd_fexp2(z);
assert_approx_eq!(x, r);
let r = simd_fma(x, h, h);
assert_approx_eq!(x, r);
let r = simd_fsqrt(x);
assert_approx_eq!(x, r);
let r = simd_fl... | let r = simd_fcos(z); | random_line_split |
simd-intrinsic-float-math.rs | // run-pass
// ignore-emscripten
// ignore-android
// FIXME: this test fails on arm-android because the NDK version 14 is too old.
// It needs at least version 18. We disable it on all android build bots because
// there is no way in compile-test to disable it for an (arch,os) pair.
// Test that the simd floating-poi... | (pub f32, pub f32, pub f32, pub f32);
extern "platform-intrinsic" {
fn simd_fsqrt<T>(x: T) -> T;
fn simd_fabs<T>(x: T) -> T;
fn simd_fsin<T>(x: T) -> T;
fn simd_fcos<T>(x: T) -> T;
fn simd_fexp<T>(x: T) -> T;
fn simd_fexp2<T>(x: T) -> T;
fn simd_fma<T>(x: T, y: T, z: T) -> T;
fn simd_fl... | f32x4 | identifier_name |
datepicker-input.directive.ts | import { Directive, ElementRef, Renderer2, HostListener, OnDestroy } from '@angular/core';
import { NglDatepickerInput } from './datepicker-input';
import { IDatepickerInput } from './datepicker-input.interface';
@Directive({
selector: 'input[nglDatepickerInput]',
exportAs: 'nglDatepickerInput'
})
export class Ngl... | (evt) {
this.datepickerInput.onKeyboardInput(evt);
}
@HostListener('input')
onInput() {
setTimeout(() => this.datepickerInput.onInputChange(), 0);
}
@HostListener('blur')
onBlur() {
this.datepickerInput.onBlur();
}
setPlaceholder(placeholder: string) {
this.renderer.setAttribute(this.... | onKeydown | identifier_name |
datepicker-input.directive.ts | import { Directive, ElementRef, Renderer2, HostListener, OnDestroy } from '@angular/core';
import { NglDatepickerInput } from './datepicker-input';
import { IDatepickerInput } from './datepicker-input.interface';
@Directive({
selector: 'input[nglDatepickerInput]',
exportAs: 'nglDatepickerInput'
})
export class Ngl... |
setPlaceholder(placeholder: string) {
this.renderer.setAttribute(this.element.nativeElement, 'placeholder', placeholder);
}
setDisabled(disabled: boolean) {
this.renderer.setProperty(this.element.nativeElement, 'disabled', disabled);
}
ngOnDestroy() {
this.datepickerInput.inputEl = null;
}
}... | {
this.datepickerInput.onBlur();
} | identifier_body |
datepicker-input.directive.ts | import { Directive, ElementRef, Renderer2, HostListener, OnDestroy } from '@angular/core';
import { NglDatepickerInput } from './datepicker-input';
import { IDatepickerInput } from './datepicker-input.interface';
@Directive({
selector: 'input[nglDatepickerInput]',
exportAs: 'nglDatepickerInput'
})
export class Ngl... | onKeydown(evt) {
this.datepickerInput.onKeyboardInput(evt);
}
@HostListener('input')
onInput() {
setTimeout(() => this.datepickerInput.onInputChange(), 0);
}
@HostListener('blur')
onBlur() {
this.datepickerInput.onBlur();
}
setPlaceholder(placeholder: string) {
this.renderer.setAttr... |
@HostListener('keydown', ['$event']) | random_line_split |
realign.py | """Perform realignment of BAM files around indels using the GATK toolkit.
"""
import os
import shutil
from contextlib import closing
import pysam
from bcbio import bam, broad
from bcbio.bam import ref
from bcbio.log import logger
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_trans... | else:
for item in cur_bam:
if not item.is_unmapped:
return True
return False
| """Check if the aligned BAM file has any reads in the region.
region can be a chromosome string ("chr22"),
a tuple region (("chr22", 1, 100)) or a file of regions.
"""
import pybedtools
if region is not None:
if isinstance(region, basestring) and os.path.isfile(region):
regions ... | identifier_body |
realign.py | """Perform realignment of BAM files around indels using the GATK toolkit.
"""
import os
import shutil
from contextlib import closing
import pysam
from bcbio import bam, broad
from bcbio.bam import ref
from bcbio.log import logger
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_trans... | out_file = "%s-realign.intervals" % os.path.splitext(align_bam)[0]
# check only for file existence; interval files can be empty after running
# on small chromosomes, so don't rerun in those cases
if not os.path.exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
... | else: | random_line_split |
realign.py | """Perform realignment of BAM files around indels using the GATK toolkit.
"""
import os
import shutil
from contextlib import closing
import pysam
from bcbio import bam, broad
from bcbio.bam import ref
from bcbio.log import logger
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_trans... |
return False
| for item in cur_bam:
if not item.is_unmapped:
return True | conditional_block |
realign.py | """Perform realignment of BAM files around indels using the GATK toolkit.
"""
import os
import shutil
from contextlib import closing
import pysam
from bcbio import bam, broad
from bcbio.bam import ref
from bcbio.log import logger
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_trans... | (runner, align_bam, ref_file, intervals,
tmp_dir, region=None, deep_coverage=False,
known_vrns=None):
"""Prepare input arguments for GATK indel realignment.
"""
if not known_vrns:
known_vrns = {}
params = ["-T", "IndelRealigner",
... | gatk_indel_realignment_cl | identifier_name |
GMS2Script.spec.ts | import {
Expect,
Test,
TestFixture,
} from "alsatian";
import GMS2Script from "../../../../src/gm_project/gms2/GMS2Script";
/* tslint:disable:max-classes-per-file completed-docs */
@TestFixture("GMS2Script")
export class GMS2ScriptFixture {
@Test("should load a script and get the script content and name through... | () {
const script = new GMS2Script("my-name", false);
const arr = Array.from(script.subScripts("/// Hi"));
Expect(arr.length).toBe(1);
Expect(arr[0].name).toBe("my-name");
Expect(arr[0].text).toBe("/**\n * Hi\n */\n");
}
@Test("should convert triple slash comments into JSdoc comments and strip initial spac... | subScripts_triple_slash | identifier_name |
GMS2Script.spec.ts | import {
Expect,
Test,
TestFixture,
} from "alsatian";
import GMS2Script from "../../../../src/gm_project/gms2/GMS2Script";
/* tslint:disable:max-classes-per-file completed-docs */
@TestFixture("GMS2Script")
export class GMS2ScriptFixture {
@Test("should load a script and get the script content and name through... | }
@Test("should get the filepath of the gml file of a non-compatibility script")
public filepath_NonCompatibility() {
const script = new GMS2Script("my-name", false);
Expect(script.filepath).toBe("scripts/my-name/my-name.gml");
}
@Test("should get the filepath of the gml file of a compatibility script")
pub... | Expect(arr[0].name).toBe("my-name");
Expect(arr[0].text).toBe("//// Hi"); | random_line_split |
GMS2Script.spec.ts | import {
Expect,
Test,
TestFixture,
} from "alsatian";
import GMS2Script from "../../../../src/gm_project/gms2/GMS2Script";
/* tslint:disable:max-classes-per-file completed-docs */
@TestFixture("GMS2Script")
export class GMS2ScriptFixture {
@Test("should load a script and get the script content and name through... |
}
| {
const script = new GMS2Script("my-name", true);
Expect(script.filepath).toBe("scripts/@my-name/my-name.gml");
} | identifier_body |
temporal_analysis_widget.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from view.analysis_widget import AnalysisWidget
# noinspection PyPep8Naming
class | (AnalysisWidget):
# noinspection PyArgumentList
def __init__(self, mplCanvas):
"""
Construct the Temporal Analysis page in the main window. |br|
A ``ScatterPlot.mplCanvas`` will be shown on this page.
:param mplCanvas: The ``ScatterPlot.mplCanvas`` widget.
"""
... | TemporalAnalysisWidget | identifier_name |
temporal_analysis_widget.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from view.analysis_widget import AnalysisWidget
# noinspection PyPep8Naming
class TemporalAnalysisWidget(AnalysisWidget):
# noinspection PyArgumentList
| mainLayout.addWidget(mplCanvas)
mainLayout.addWidget(lowerLabel)
mainLayout.addWidget(self.tableWidget)
self.setLayout(mainLayout)
| def __init__(self, mplCanvas):
"""
Construct the Temporal Analysis page in the main window. |br|
A ``ScatterPlot.mplCanvas`` will be shown on this page.
:param mplCanvas: The ``ScatterPlot.mplCanvas`` widget.
"""
super().__init__()
upperLabel = QtWidgets.QLabel... | identifier_body |
temporal_analysis_widget.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
from view.analysis_widget import AnalysisWidget
# noinspection PyPep8Naming
class TemporalAnalysisWidget(AnalysisWidget):
# noinspection PyArgumentList
def __init__(self, mplCanvas):
"""
Construct the Temporal Analys... | mainLayout.addWidget(upperLabel)
mainLayout.addWidget(mplCanvas)
mainLayout.addWidget(lowerLabel)
mainLayout.addWidget(self.tableWidget)
self.setLayout(mainLayout) | random_line_split | |
edseq.py | #!/usr/bin/env python3
#
# (c) Christian Sommerfeldt OEien
# All rights reserved
import itertools
import sys, os
def extrapatt(patt):
if "%" in patt: return patt
else: return patt + "%d.jpeg"
class FileSeq:
def __init__(self, patt):
self.patt = extrapatt(patt)
self.count = sel... |
elif sys.argv[2] == "rev":
orig = FileSeq(sys.argv[3])
for i in reversed(range(orig.count)):
os.symlink(orig.path(i), target.newpath())
# improve: where symlink is used, could follow to target
# so that max vfs (6 in linux) symlink not hit.
elif sys.argv[2] == "ste":
orig = FileSeq... | if s + 1 < len(slds) and slds[s].count == j + x:
print("xfade", slds[s].patt)
j = 0
s += 1
j += 1
if j > x or s == 0:
os.symlink(slds[s].path(j), target.newpath())
else:
fade(j, slds[s - 1], slds[s], target) | conditional_block |
edseq.py | #!/usr/bin/env python3
#
# (c) Christian Sommerfeldt OEien
# All rights reserved
import itertools
import sys, os
def extrapatt(patt):
if "%" in patt: return patt
else: return patt + "%d.jpeg"
class FileSeq:
def __init__(self, patt):
self.patt = extrapatt(patt)
self.count = sel... | startn, endn = sys.argv[3].split(",")
for _ in range(int(startn)):
os.symlink(orig.path(0), target.newpath())
for i in range(orig.count):
os.symlink(orig.path(i), target.newpath())
for _ in range(int(endn)):
os.symlink(orig.path(orig.count - 1), target.newpath())
elif sys.argv[2]... | elif sys.argv[2] == "pad":
orig = FileSeq(sys.argv[4]) | random_line_split |
edseq.py | #!/usr/bin/env python3
#
# (c) Christian Sommerfeldt OEien
# All rights reserved
import itertools
import sys, os
def extrapatt(patt):
if "%" in patt: return patt
else: return patt + "%d.jpeg"
class FileSeq:
def __init__(self, patt):
self.patt = extrapatt(patt)
self.count = sel... | (self):
i = self.count
self.count += 1
return self.path(i)
def fade(cents, prev, cur, target):
os.system("composite -blend %d %s %s %s" % (
cents,
cur.path(cents),
prev.path(prev.count - 100 + cents),
target.newpath()))
def rgb(i, r, g, b, target):
os.sy... | newpath | identifier_name |
edseq.py | #!/usr/bin/env python3
#
# (c) Christian Sommerfeldt OEien
# All rights reserved
import itertools
import sys, os
def extrapatt(patt):
if "%" in patt: return patt
else: return patt + "%d.jpeg"
class FileSeq:
def __init__(self, patt):
self.patt = extrapatt(patt)
self.count = sel... |
def newpath(self):
i = self.count
self.count += 1
return self.path(i)
def fade(cents, prev, cur, target):
os.system("composite -blend %d %s %s %s" % (
cents,
cur.path(cents),
prev.path(prev.count - 100 + cents),
target.newpath()))
def rgb(i, r, g, b, t... | return os.path.abspath(self.patt % (i,)) | identifier_body |
views.py | """ API v0 views. """
import logging
from django.http import Http404
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_... |
class UserGradeView(GradeViewMixin, GenericAPIView):
"""
**Use Case**
* Get the current course grades for users in a course.
Currently, getting the grade for only an individual user is supported.
**Example Request**
GET /api/grades/v0/course_grade/{course_id}/users/?username=... | raise AuthenticationFailed | conditional_block |
views.py | """ API v0 views. """
import logging
from django.http import Http404
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_... | course = self._get_course(course_id, request.user, 'staff')
if isinstance(course, Response):
return course
return Response(GradingPolicySerializer(course.raw_grader, many=True).data) | identifier_body | |
views.py | """ API v0 views. """
import logging
from django.http import Http404
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_... | If the request for information about the course grade
is successful, an HTTP 200 "OK" response is returned.
The HTTP 200 response has the following values.
* username: A string representation of a user's username passed in the request.
* course_id: A string representation of a... | random_line_split | |
views.py | """ API v0 views. """
import logging
from django.http import Http404
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_... | (self, request):
"""
Ensures that the user is authenticated (e.g. not an AnonymousUser), unless DEBUG mode is enabled.
"""
super(GradeViewMixin, self).perform_authentication(request)
if request.user.is_anonymous():
raise AuthenticationFailed
class UserGradeView(Grad... | perform_authentication | identifier_name |
scroll-mask.tsx | import React, { FC, useRef, RefObject, useEffect } from 'react'
import classNames from 'classnames'
import { animated, useSpring } from '@react-spring/web'
import { useThrottleFn } from 'ahooks'
const classPrefix = `adm-scroll-mask`
export type ScrollMaskProps = {
scrollTrackRef: RefObject<HTMLElement>
}
export co... |
useEffect(() => {
const scrollEl = props.scrollTrackRef.current
if (!scrollEl) return
scrollEl.addEventListener('scroll', updateMask)
return () => scrollEl.removeEventListener('scroll', updateMask)
}, [])
return (
<>
<animated.div
ref={maskRef}
className={classNames(cl... | }, []) | random_line_split |
number.js | /*
* Should
* Copyright(c) 2010-2014 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
module.exports = function(should, Assertion) {
/**
* Assert given object is NaN
* @name NaN
* @memberOf Assertion
* @category assertion numbers
* @example
*
* (10).should.not.be.NaN();
* NaN.should... | *
* (10).should.be.within(0, 20);
*/
Assertion.add('within', function(start, finish, description) {
this.params = { operator: 'to be within ' + start + '..' + finish, message: description };
this.assert(this.obj >= start && this.obj <= finish);
});
/**
* Assert given number near some other `... | * @param {number} start Start number
* @param {number} finish Finish number
* @param {string} [description] Optional message
* @example | random_line_split |
validators.ts | import {isBlank, isPresent, CONST_EXPR, isString} from 'angular2/src/facade/lang';
import {PromiseWrapper} from 'angular2/src/facade/promise';
import {ObservableWrapper} from 'angular2/src/facade/async';
import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {OpaqueToken} from 'angular2/co... | (obj: any): any {
return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj);
}
function _executeValidators(control: modelModule.AbstractControl, validators: Function[]): any[] {
return validators.map(v => v(control));
}
function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} {
var ... | _convertToPromise | identifier_name |
validators.ts | import {isBlank, isPresent, CONST_EXPR, isString} from 'angular2/src/facade/lang';
import {PromiseWrapper} from 'angular2/src/facade/promise';
import {ObservableWrapper} from 'angular2/src/facade/async';
import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {OpaqueToken} from 'angular2/co... |
/**
* Validator that requires controls to have a value of a minimum length.
*/
static minLength(minLength: number): Function {
return (control: modelModule.Control): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
retur... | {
return isBlank(control.value) || (isString(control.value) && control.value == "") ?
{"required": true} :
null;
} | identifier_body |
validators.ts | import {isBlank, isPresent, CONST_EXPR, isString} from 'angular2/src/facade/lang';
import {PromiseWrapper} from 'angular2/src/facade/promise';
import {ObservableWrapper} from 'angular2/src/facade/async';
import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {OpaqueToken} from 'angular2/co... | return _mergeErrors(_executeValidators(control, presentValidators));
};
}
static composeAsync(validators: Function[]): Function {
if (isBlank(validators)) return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0) return null;
return function(co... |
return function(control: modelModule.AbstractControl) { | random_line_split |
xyz-pixels-to-rgbm.js | var xyz = require('xyz-utils')
var tmp = [0, 0, 0]
var tmp1 = [0, 0, 0]
var tmpRGBM = [0, 0, 0, 0]
const clamp = require('clamp')
module.exports = xyzToRGBM
function | (xyzArray) {
var pixelCount = xyzArray.length / 3
var ret = new Uint8Array(pixelCount * 4)
for (var i = 0; i < pixelCount; i++) {
tmp[0] = xyzArray[i * 3]
tmp[1] = xyzArray[i * 3 + 1]
tmp[2] = xyzArray[i * 3 + 2]
xyz.toRGB(tmp, tmp1) // xyz to rgb
encode(tmp1, tmpRGBM) // rgb to rgbm
ret... | xyzToRGBM | identifier_name |
xyz-pixels-to-rgbm.js | var xyz = require('xyz-utils')
var tmp = [0, 0, 0]
var tmp1 = [0, 0, 0]
var tmpRGBM = [0, 0, 0, 0]
const clamp = require('clamp')
module.exports = xyzToRGBM
function xyzToRGBM (xyzArray) {
var pixelCount = xyzArray.length / 3
var ret = new Uint8Array(pixelCount * 4)
for (var i = 0; i < pixelCount; i++) |
return ret
}
function encode (color, out) {
if (!out) out = [ 0, 0, 0, 0 ]
var minB = 0.000001
var coeff = 1 / 6
var r = color[0] * coeff
var g = color[1] * coeff
var b = color[2] * coeff
var a = clamp(Math.max(Math.max(r, g), Math.max(b, minB)), 0.0, 1.0)
a = Math.ceil(a * 255.0) / 255.0
out[0] =... | {
tmp[0] = xyzArray[i * 3]
tmp[1] = xyzArray[i * 3 + 1]
tmp[2] = xyzArray[i * 3 + 2]
xyz.toRGB(tmp, tmp1) // xyz to rgb
encode(tmp1, tmpRGBM) // rgb to rgbm
ret[i * 4] = tmpRGBM[0]
ret[i * 4 + 1] = tmpRGBM[1]
ret[i * 4 + 2] = tmpRGBM[2]
ret[i * 4 + 3] = tmpRGBM[3]
} | conditional_block |
xyz-pixels-to-rgbm.js | var xyz = require('xyz-utils')
var tmp = [0, 0, 0]
var tmp1 = [0, 0, 0] |
module.exports = xyzToRGBM
function xyzToRGBM (xyzArray) {
var pixelCount = xyzArray.length / 3
var ret = new Uint8Array(pixelCount * 4)
for (var i = 0; i < pixelCount; i++) {
tmp[0] = xyzArray[i * 3]
tmp[1] = xyzArray[i * 3 + 1]
tmp[2] = xyzArray[i * 3 + 2]
xyz.toRGB(tmp, tmp1) // xyz to rgb
... | var tmpRGBM = [0, 0, 0, 0]
const clamp = require('clamp') | random_line_split |
xyz-pixels-to-rgbm.js | var xyz = require('xyz-utils')
var tmp = [0, 0, 0]
var tmp1 = [0, 0, 0]
var tmpRGBM = [0, 0, 0, 0]
const clamp = require('clamp')
module.exports = xyzToRGBM
function xyzToRGBM (xyzArray) {
var pixelCount = xyzArray.length / 3
var ret = new Uint8Array(pixelCount * 4)
for (var i = 0; i < pixelCount; i++) {
tmp... | {
if (!out) out = [ 0, 0, 0, 0 ]
var minB = 0.000001
var coeff = 1 / 6
var r = color[0] * coeff
var g = color[1] * coeff
var b = color[2] * coeff
var a = clamp(Math.max(Math.max(r, g), Math.max(b, minB)), 0.0, 1.0)
a = Math.ceil(a * 255.0) / 255.0
out[0] = clamp(Math.ceil(r / a * 255), 0, 255)
out[1... | identifier_body | |
system-service.ts | 'use strict';
export default class SystemService {
static _instance;
_pollPromise;
_pollSuccessCallback;
_pollInterval;
static create($http, $timeout, config, authService) {
this._instance = new this($http, $timeout, config, authService);
return this._instance;
}
static getInstance() {
ret... | private _doRestart() {
const restartAPI = 'api/rest/system/restart';
return this.$http({
method: 'POST',
url: this.config.root + restartAPI,
headers: {'Content-Type': 'application/json'}
});
}
private _startPollUserInfo(successCallback, interval, initialInterval) {
const pollUse... | }
| random_line_split |
system-service.ts | 'use strict';
export default class SystemService {
static _instance;
_pollPromise;
_pollSuccessCallback;
_pollInterval;
static create($http, $timeout, config, authService) {
this._instance = new this($http, $timeout, config, authService);
return this._instance;
}
static getInstance() {
ret... |
private _startPollUserInfo(successCallback, interval, initialInterval) {
const pollUserInfo = () => this._pollUserInfo();
initialInterval = initialInterval || interval;
this._pollSuccessCallback = successCallback;
this._pollInterval = interval;
this._nextPoll(pollUserInfo, initialInterval);
}
... | {
const restartAPI = 'api/rest/system/restart';
return this.$http({
method: 'POST',
url: this.config.root + restartAPI,
headers: {'Content-Type': 'application/json'}
});
} | identifier_body |
system-service.ts | 'use strict';
export default class SystemService {
static _instance;
_pollPromise;
_pollSuccessCallback;
_pollInterval;
static create($http, $timeout, config, authService) {
this._instance = new this($http, $timeout, config, authService);
return this._instance;
}
static getInstance() {
ret... | else {
this._pollSuccessCallback();
this._pollPromise = undefined;
this._pollInterval = undefined;
this._pollSuccessCallback = undefined;
}
}).catch( () => {
this._nextPoll(pollUserInfo, this._pollInterval);
});
};
private _nextPoll(pollCallback, interval) {
... | {
this._nextPoll(pollUserInfo, this._pollInterval);
} | conditional_block |
system-service.ts | 'use strict';
export default class SystemService {
static _instance;
_pollPromise;
_pollSuccessCallback;
_pollInterval;
static create($http, $timeout, config, authService) {
this._instance = new this($http, $timeout, config, authService);
return this._instance;
}
static getInstance() {
ret... | () {
return this._doRestart();
}
checkForLife(successCallback, pollInterval, initialInterval) {
this._startPollUserInfo(successCallback, pollInterval, initialInterval);
}
fetchHQ() {
const api = this.config.root + 'api/rest/hq';
return this.$http.get(api, { withCredentials: true, cache: false ... | doRestart | identifier_name |
omega.js | /* omega - node.js server
http://code.google.com/p/theomega/ |
var http=require("http");var om=require("./omlib");
var Omega={Request:function(req){var req;req={api:null};req._sock=req;req._answer=function(){return"foo!"};return req},Response:function(res){var resp;resp={_sock:res,data:null,result:false,encoding:"json",headers:{"Content-Type":"text/plain","Cache-Control":"no-cach... |
Copyright 2011, Jonathon Fillmore
Licensed under the MIT license. See LICENSE file.
http://www.opensource.org/licenses/mit-license.php */ | random_line_split |
image_cache_task.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/. */
use image::base::Image;
use ipc_channel::ipc::{self, IpcSender};
use url::Url;
use std::sync::Arc;
use util::mem::... | {
sender: IpcSender<ImageResponse>,
}
impl ImageResponder {
pub fn new(sender: IpcSender<ImageResponse>) -> ImageResponder {
ImageResponder {
sender: sender,
}
}
pub fn respond(&self, response: ImageResponse) {
self.sender.send(response).unwrap()
}
}
/// The c... | ImageResponder | identifier_name |
image_cache_task.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/. */
use image::base::Image;
use ipc_channel::ipc::{self, IpcSender};
use url::Url;
use std::sync::Arc;
use util::mem::... | self.chan.send(ImageCacheCommand::Exit(response_chan)).unwrap();
response_port.recv().unwrap();
}
} | random_line_split | |
jquery-google-map.js | 7,
longitude: -73.983307
},
styles: null,
zoom: 14,
markers: [],
infowindow: {
borderBottomSpacing: 6,
height: 150,
width: 340,
offsetX: -21,
offsetY: -21
},
marker: {
height: 40,
width: 40
},
cluster: {
heigh... | (cluster) {
// Hide all cluster's markers
$.each(cluster.getMarkers(), (function () {
if (this.marker.isHidden == false) {
this.marker.isHidden = true;
this.marker.close();
}
}));
var newCluster = new InfoBox({
markers: cluster.getMarkers(),
draggable: true,
content: '<div class="cluster... | addClusterOnMap | identifier_name |
jquery-google-map.js | 7,
longitude: -73.983307
},
styles: null,
zoom: 14,
markers: [],
infowindow: {
borderBottomSpacing: 6,
height: 150,
width: 340,
offsetX: -21,
offsetY: -21
},
marker: {
height: 40,
width: 40
},
cluster: {
heigh... |
var marker = new google.maps.Marker(markerSettings);
// Create infobox for infowindow
if (markerObject.content) {
marker.infobox = new InfoBox({
content: markerObject.content,
disableAutoPan: true,
pixelOffset: new google.maps.Size(settings.infowindow.offsetX, settings.infowindow.offsetY,... | {
markerSettings['icon'] = {
size: new google.maps.Size(settings.marker.width, settings.marker.height),
url: settings.transparentMarkerImage
};
} | conditional_block |
jquery-google-map.js | 7,
longitude: -73.983307
},
styles: null,
zoom: 14,
markers: [],
infowindow: {
borderBottomSpacing: 6,
height: 150,
width: 340,
offsetX: -21,
offsetY: -21
},
marker: {
height: 40,
width: 40
},
cluster: {
heigh... |
function thisTouchMove(e) {
if (!dragFlag) {
return
}
end = e.touches[0].pageY;
window.scrollBy(0, (start - end));
}
var el = element[0];
if (el.addEventListener) {
el.addEventListener('touchstart', thisTouchStart, true);
el.addEventListener('touchend', thisTouchEnd, true);
el.addE... | {
dragFlag = false;
} | identifier_body |
jquery-google-map.js | 7,
longitude: -73.983307
},
styles: null,
zoom: 14,
markers: [],
infowindow: {
borderBottomSpacing: 6,
height: 150,
width: 340,
offsetX: -21,
offsetY: -21
},
marker: {
height: 40,
width: 40
},
cluster: {
heigh... |
mapOptions.center = new google.maps.LatLng(settings.center.latitude, settings.center.longitude);
map = new google.maps.Map($(element)[0], mapOptions);
var dragFlag = false;
var start = 0;
var end = 0;
function thisTouchStart(e) {
dragFlag = true;
start = e.touches[0].pageY;
}
function thisTouc... | }; | random_line_split |
prometheus.py | # 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 option) any later version.
#
# This program is distributed in the hope that it will be usefu... | def run(self) -> None:
events_gauge = \
nemesis_metrics_obj().create_gauge("sct_events_gauge",
"Gauge for SCT events",
["event_type", "type", "subtype", "severity", "node", ])
for event_tuple in se... | identifier_body | |
prometheus.py | # 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 option) any later version.
#
# This program is distributed in the hope that it will be usefu... | (BaseEventsProcess[Tuple[str, Any], None], threading.Thread):
def run(self) -> None:
events_gauge = \
nemesis_metrics_obj().create_gauge("sct_events_gauge",
"Gauge for SCT events",
["event_type", "type"... | PrometheusDumper | identifier_name |
prometheus.py | # 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 option) any later version.
#
# This program is distributed in the hope that it will be usefu... |
from sdcm.prometheus import nemesis_metrics_obj
from sdcm.sct_events.events_processes import BaseEventsProcess, verbose_suppress
LOGGER = logging.getLogger(__name__)
class PrometheusDumper(BaseEventsProcess[Tuple[str, Any], None], threading.Thread):
def run(self) -> None:
events_gauge = \
n... | import threading
from typing import Tuple, Any | random_line_split |
prometheus.py | # 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 option) any later version.
#
# This program is distributed in the hope that it will be usefu... | with verbose_suppress("PrometheusDumper failed to process %s", event_tuple):
event_class, event = event_tuple # try to unpack event from EventsDevice
events_gauge.labels(event_class, # pylint: disable=no-member
getattr(event, "type", ""),
... | conditional_block | |
utils.py | import time
def wait_for_transaction(blockchain_client, txn_hash, max_wait=60, sleep_time=5):
start = time.time()
while True:
txn_receipt = blockchain_client.get_transaction_receipt(txn_hash)
if txn_receipt is not None:
break
elif time.time() > start + max_wait:
... |
def get_max_gas(blockchain_client):
latest_block = blockchain_client.get_block_by_number('latest')
max_gas_hex = latest_block['gasLimit']
max_gas = int(max_gas_hex, 16)
return max_gas
def get_transaction_params(_from=None, to=None, gas=None, gas_price=None,
value=0, data=... | start = time.time()
while time.time() < start + max_wait:
latest_block_number = blockchain_client.get_block_number()
if latest_block_number >= block_number:
break
time.sleep(sleep_time)
else:
raise ValueError("Did not reach block")
return blockchain_client.get_blo... | identifier_body |
utils.py | import time
def wait_for_transaction(blockchain_client, txn_hash, max_wait=60, sleep_time=5):
start = time.time()
while True:
txn_receipt = blockchain_client.get_transaction_receipt(txn_hash)
if txn_receipt is not None:
break
elif time.time() > start + max_wait:
... | return blockchain_client.get_block_by_number(block_number)
def get_max_gas(blockchain_client):
latest_block = blockchain_client.get_block_by_number('latest')
max_gas_hex = latest_block['gasLimit']
max_gas = int(max_gas_hex, 16)
return max_gas
def get_transaction_params(_from=None, to=None, gas=N... | raise ValueError("Did not reach block") | random_line_split |
utils.py | import time
def wait_for_transaction(blockchain_client, txn_hash, max_wait=60, sleep_time=5):
start = time.time()
while True:
txn_receipt = blockchain_client.get_transaction_receipt(txn_hash)
if txn_receipt is not None:
break
elif time.time() > start + max_wait:
... | (from_block=None, to_block=None, address=None,
topics=None):
params = {}
if from_block is not None:
params["fromBlock"] = from_block
if to_block is not None:
params["toBlock"] = to_block
if address is not None:
params["address"] = address
if topics i... | construct_filter_args | identifier_name |
utils.py | import time
def wait_for_transaction(blockchain_client, txn_hash, max_wait=60, sleep_time=5):
start = time.time()
while True:
txn_receipt = blockchain_client.get_transaction_receipt(txn_hash)
if txn_receipt is not None:
break
elif time.time() > start + max_wait:
... |
time.sleep(sleep_time)
else:
raise ValueError("Did not reach block")
return blockchain_client.get_block_by_number(block_number)
def get_max_gas(blockchain_client):
latest_block = blockchain_client.get_block_by_number('latest')
max_gas_hex = latest_block['gasLimit']
max_gas = int(m... | break | conditional_block |
most_calls.py | #!/usr/bin/env python3
import collections
import os
import sys
from librarytrader.librarystore import LibraryStore
s = LibraryStore()
s.load(sys.argv[1])
n = 20
if len(sys.argv) > 2:
n = int(sys.argv[2])
outgoing_calls = set()
incoming_calls = collections.defaultdict(int)
for l in s.get_library_objects():
... |
print('')
print('Top {} incoming calls (direct)'.format(n))
in_sorted = sorted(incoming_calls.items(), key=lambda x:x[1])
for tp in in_sorted[-n:]:
print(tp[0], tp[1])
| print(tp[0], tp[1]) | conditional_block |
most_calls.py | #!/usr/bin/env python3
import collections
import os
import sys
from librarytrader.librarystore import LibraryStore
s = LibraryStore()
s.load(sys.argv[1])
n = 20
if len(sys.argv) > 2:
n = int(sys.argv[2])
outgoing_calls = set()
incoming_calls = collections.defaultdict(int)
for l in s.get_library_objects():
... |
for f, names in l.local_functions.items():
s = 0
name = '{}:LOCAL_{}'.format(l.fullname, names[0])
s += len(l.internal_calls.get(f, []))
s += len(l.external_calls.get(f, []))
s += len(l.local_calls.get(f, []))
outgoing_calls.add((name, s))
for source, targets in... | s += len(l.local_calls.get(f, []))
outgoing_calls.add((name, s)) | random_line_split |
setup.py | from setuptools import find_packages
from setuptools import setup
setup(
name='svs',
version='1.0.0',
description='The InAcademia Simple validation Service allows for the easy validation of affiliation (Student,'
'Faculty, Staff) of a user in Academia',
license='Apache 2.0',
classif... | url='http://www.inacademia.org',
packages=find_packages('src'),
package_dir={'': 'src'},
package_data={
'svs': [
'data/i18n/locale/*/LC_MESSAGES/*.mo',
'templates/*.mako',
'site/static/*',
],
},
message_extractors={
'src/svs': [
... | zip_safe=False, | random_line_split |
DeleteFinished.py | # -*- coding: utf-8 -*-
from module.database import style
from module.plugins.internal.Addon import Addon
class DeleteFinished(Addon):
__name__ = "DeleteFinished"
__type__ = "hook"
__version__ = "1.14"
__status__ = "testing"
__config__ = [("interval" , "int" , "Check interval in hours" ... |
def activate(self):
self.info['sleep'] = True
# interval = self.get_config('interval')
# self.plugin_config_changed(self.__name__, 'interval', interval)
self.interval = max(self.MIN_CHECK_INTERVAL, self.get_config('interval') * 60 * 60)
self.add_event('package_finished', sel... | random_line_split | |
DeleteFinished.py | # -*- coding: utf-8 -*-
from module.database import style
from module.plugins.internal.Addon import Addon
class DeleteFinished(Addon):
__name__ = "DeleteFinished"
__type__ = "hook"
__version__ = "1.14"
__status__ = "testing"
__config__ = [("interval" , "int" , "Check interval in hours" ... | (self):
if not self.info['sleep']:
deloffline = self.get_config('deloffline')
mode = "0,1,4" if deloffline else "0,4"
msg = _('delete all finished packages in queue list (%s packages with offline links)')
self.log_info(msg % (_('including') if deloffline else _('e... | periodical | identifier_name |
DeleteFinished.py | # -*- coding: utf-8 -*-
from module.database import style
from module.plugins.internal.Addon import Addon
class DeleteFinished(Addon):
__name__ = "DeleteFinished"
__type__ = "hook"
__version__ = "1.14"
__status__ = "testing"
__config__ = [("interval" , "int" , "Check interval in hours" ... |
else:
self.manager.events[event] = [func]
| self.manager.events[event].append(func) | conditional_block |
DeleteFinished.py | # -*- coding: utf-8 -*-
from module.database import style
from module.plugins.internal.Addon import Addon
class DeleteFinished(Addon):
__name__ = "DeleteFinished"
__type__ = "hook"
__version__ = "1.14"
__status__ = "testing"
__config__ = [("interval" , "int" , "Check interval in hours" ... |
def periodical(self):
if not self.info['sleep']:
deloffline = self.get_config('deloffline')
mode = "0,1,4" if deloffline else "0,4"
msg = _('delete all finished packages in queue list (%s packages with offline links)')
self.log_info(msg % (_('including') if... | self.interval = self.MIN_CHECK_INTERVAL | identifier_body |
netfilter.py | import sys
import threading
from netfilterqueue import NetfilterQueue
import dpkt
import socket
import config
logger = config.logger
class FlowControlQueue:
''' The class creates a NetfilterQueue that blocks/releases IP packets of
given types.
'''
def __init__(self, worker, queue_num=config.WorkerCo... | (self, dip, dport, proto):
bname = self._block_name(dip, dport, proto)
with self.lck:
if bname not in self.block_table:
self.block_table[bname] = []
self.worker_already_informed[bname] = False
self._debug("block {0}".format(bname))
def release(sel... | block | identifier_name |
netfilter.py | import sys
import threading
from netfilterqueue import NetfilterQueue
import dpkt
import socket
import config
logger = config.logger
class FlowControlQueue:
''' The class creates a NetfilterQueue that blocks/releases IP packets of
given types.
'''
def __init__(self, worker, queue_num=config.WorkerCo... |
@classmethod
def _block_name(cls, dip, dport, proto):
return "{0}:{1}.{2}".format(dip, dport, proto)
# need parameter to say whether you should inform us based on this rule
# because that callback should only be called once
def block(self, dip, dport, proto):
bname = self._block_name(dip,... | self.worker = worker
self.queue_num = queue_num
self.nfqueue = None
self.thread_recv_pkt = None
self.lck = threading.Lock()
self.block_table = {} # map "$dip:$dport.$proto" -> [blocked_pkts]
self.worker_already_informed = {}
self._debug_flag = True # nfqueue is ... | identifier_body |
netfilter.py | import sys
import threading
from netfilterqueue import NetfilterQueue
import dpkt
import socket
import config
logger = config.logger
class FlowControlQueue:
''' The class creates a NetfilterQueue that blocks/releases IP packets of
given types.
'''
def __init__(self, worker, queue_num=config.WorkerCo... |
if bname in self.worker_already_informed:
already_informed = self.worker_already_informed[bname]
if (blocked and (not already_informed)):
self.inform_worker(dip, dport, proto)
self.worker_already_informed[bname] = True
else:
pkt.ac... | self.block_table[bname].append(pkt)
blocked = True | conditional_block |
netfilter.py | import sys
import threading
from netfilterqueue import NetfilterQueue |
logger = config.logger
class FlowControlQueue:
''' The class creates a NetfilterQueue that blocks/releases IP packets of
given types.
'''
def __init__(self, worker, queue_num=config.WorkerConfig.queue_num):
self.worker = worker
self.queue_num = queue_num
self.nfqueue = None
... | import dpkt
import socket
import config | random_line_split |
EnemyFormation.ts | ";
import Enemy, {IEnemyConfig} from "./Enemy";
import {addListener, emit, Events} from "./EventListener";
import {dt, player} from "./game";
import {images} from "./imageLoader";
import {PI2, randRange, SimpleHarmonicMotion as HarmonicMotion} from "./math";
export interface IFormationSubProcessor {
process(f: Forma... | }
u.x = x + this.hm.getX(t);
u.y = y + this.hm.getY(t);
}
}
}
export class StraightLineEPP implements IFormationSubProcessor {
constructor(public offset = 100) {
}
public process(f: Formation) {
let angle = Math.PI;
let bound = true;
if (f.selfPositionProcessor instanceof Stra... | const u = f.enemyList[i];
if (!u) {
continue; | random_line_split |
EnemyFormation.ts | ";
import Enemy, {IEnemyConfig} from "./Enemy";
import {addListener, emit, Events} from "./EventListener";
import {dt, player} from "./game";
import {images} from "./imageLoader";
import {PI2, randRange, SimpleHarmonicMotion as HarmonicMotion} from "./math";
export interface IFormationSubProcessor {
process(f: Forma... |
}
}
export class PyramidEPP implements IFormationSubProcessor {
constructor(public offset = 100) {}
public process(f: Formation) {
let maxLine = 0;
while ((maxLine + 1) * maxLine / 2 < f.enemyList.length) {
++maxLine;
}
const s = (maxLine - 1) * this.offset;
// tslint:disable prefer-co... | {
for (let j = this.enemyPerLine; j--; ) {
const u = f.enemyList[i * this.enemyPerLine + j];
if (u) {
u.x = x + i * this.offset;
u.y = y + j * this.offset;
}
}
} | conditional_block |
EnemyFormation.ts | ";
import Enemy, {IEnemyConfig} from "./Enemy";
import {addListener, emit, Events} from "./EventListener";
import {dt, player} from "./game";
import {images} from "./imageLoader";
import {PI2, randRange, SimpleHarmonicMotion as HarmonicMotion} from "./math";
export interface IFormationSubProcessor {
process(f: Forma... |
public process(f: Formation) {
let angle = Math.PI;
let bound = true;
if (f.selfPositionProcessor instanceof StraightForwardSPP) {
angle = f.selfPositionProcessor.angle;
bound = f.selfPositionProcessor.bound;
}
const px = -this.offset * Math.cos(angle);
let py = -this.offset * Mat... | {
} | identifier_body |
EnemyFormation.ts | ";
import Enemy, {IEnemyConfig} from "./Enemy";
import {addListener, emit, Events} from "./EventListener";
import {dt, player} from "./game";
import {images} from "./imageLoader";
import {PI2, randRange, SimpleHarmonicMotion as HarmonicMotion} from "./math";
export interface IFormationSubProcessor {
process(f: Forma... | () {
return this.numEnemy === 0;
}
public forceDead() {
for (const u of this.enemyList) {
if (u && u.x < -2 * images[u.config.imageId].width) {
u.live = 0;
}
}
}
}
// Every class name with postfix "SPP" is used as selfPositionProcessor in Formation.
// Every class name with postf... | isDead | identifier_name |
views.py | from django.http import HttpResponse
from django.template.loader import get_template
from rapp.article.models import Article
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
def | (request):
return request.user.username if request.user.is_authenticated() else "everyone"
def _get_default_common_data():
return {
'common_data': {
'title': 'Developer blog',
'keywords': 'c++, python, society life',
'description': 'Developer blog',
'aut... | _get_greeting | identifier_name |
views.py | from django.http import HttpResponse
from django.template.loader import get_template
from rapp.article.models import Article
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
def _get_greeting(request):
|
def _get_default_common_data():
return {
'common_data': {
'title': 'Developer blog',
'keywords': 'c++, python, society life',
'description': 'Developer blog',
'author': 'K. Kulikov'
}
}
def index(request):
template = get_template('index.ht... | return request.user.username if request.user.is_authenticated() else "everyone" | identifier_body |
views.py | from django.http import HttpResponse
from django.template.loader import get_template
from rapp.article.models import Article
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
def _get_greeting(request):
return request.user.username if request.user.is_authenticated()... | def code_404_view(request):
template = get_template('404.html')
context = {
'greeting': _get_greeting(request),
'article': _get_default_common_data()
}
return HttpResponse(template.render(context, request))
class ArticleDetailView(DetailView):
model = Article
context_object_nam... | }
return HttpResponse(template.render(context, request))
| random_line_split |
main.py | # -*- coding: utf-8 -*-
"""
Date: 2/2/2017
Team: Satoshi Nakamoto
@Authors: Alex Levering and Hector Muro
Non-standard dependencies:
* Twython
* NLTK
* Folium
* Geocoder
* psycopg2
TO DO BEFOREHAND:
The following steps are non-automatable and have to be performed manually.
* Have the NLTK vader lexicon locally (nltk... | import tweetAnalysisWrapper
tweetAnalysisWrapper.performTweetResearch(folder_path = r"/home/user/git/SatoshiNakamotoGeoscripting/Final_assignment",
defaultdb = "postgres", # Making a new database requires connecting to an existing database
... | """ | random_line_split |
main.py | # -*- coding: utf-8 -*-
"""
Date: 2/2/2017
Team: Satoshi Nakamoto
@Authors: Alex Levering and Hector Muro
Non-standard dependencies:
* Twython
* NLTK
* Folium
* Geocoder
* psycopg2
TO DO BEFOREHAND:
The following steps are non-automatable and have to be performed manually.
* Have the NLTK vader lexicon locally (nltk... | """
The tool is not supplied with Tweets out-of-the-box. Set 'gather_data' to True and leave it
running for a while. If loop is false it will terminate in a minute or so and create a map from the results automatically
This tool was tested and intended for OSGeo Live installs used in the... | conditional_block | |
$zip-all.js | import { $isAsync, $async, $await, $iteratorSymbol } from '../generate/async.macro'
import { $ensureIterable } from './internal/$iterable'
import map from './map'
$async; function * $zipAll (...iterables) {
const iters = iterables.map(arg => $ensureIterable(arg)[$iteratorSymbol]())
const itersDone = iters.map(ite... |
} finally {
for (const { iter, done } of itersDone) {
if (!done && typeof iter.return === 'function') $await(iter.return())
}
}
}
export default $zipAll
| {
const results = map(iter => iter.next(), iters)
const syncResults = $isAsync ? $await(Promise.all(results)) : results
const zipped = new Array(iters.length)
let i = 0
let allDone = true
for (const { value, done } of syncResults) {
allDone = allDone && done
itersDo... | conditional_block |
$zip-all.js | import { $isAsync, $async, $await, $iteratorSymbol } from '../generate/async.macro'
import { $ensureIterable } from './internal/$iterable'
import map from './map'
$async; function * $zipAll (...iterables) {
const iters = iterables.map(arg => $ensureIterable(arg)[$iteratorSymbol]())
const itersDone = iters.map(ite... |
export default $zipAll | } | random_line_split |
cgmath_augment.rs | use cgmath::{Point2, Vector2};
pub trait Cross<T, S> { | pub trait Dot<T, S> {
fn dot(&self, other: &T) -> S;
}
//stupid type rules won't let me add std::ops::Add for f32/f64
pub trait AddScalar<T, S> {
fn add_scalar(self, rhs: S) -> T;
}
impl<S> Cross<Point2<S>, S> for Point2<S> where S: cgmath::BaseFloat {
fn cross(&self, other: &Point2<S>) -> S {
(se... | fn cross(&self, other: &T) -> S;
}
| random_line_split |
cgmath_augment.rs | use cgmath::{Point2, Vector2};
pub trait Cross<T, S> {
fn cross(&self, other: &T) -> S;
}
pub trait Dot<T, S> {
fn dot(&self, other: &T) -> S;
}
//stupid type rules won't let me add std::ops::Add for f32/f64
pub trait AddScalar<T, S> {
fn add_scalar(self, rhs: S) -> T;
}
impl<S> Cross<Point2<S>, S> for ... |
}
impl<S> Dot<Point2<S>, S> for Point2<S> where S: cgmath::BaseFloat {
fn dot(&self, other: &Point2<S>) -> S {
(self.x * other.x) + (self.y * other.y)
}
}
impl<S> Dot<Vector2<S>, S> for Vector2<S> where S: cgmath::BaseFloat {
fn dot(&self, other: &Vector2<S>) -> S {
(self.x * other.x) + (... | {
(self.x * other.y) - (self.y * other.x)
} | identifier_body |
cgmath_augment.rs | use cgmath::{Point2, Vector2};
pub trait Cross<T, S> {
fn cross(&self, other: &T) -> S;
}
pub trait Dot<T, S> {
fn dot(&self, other: &T) -> S;
}
//stupid type rules won't let me add std::ops::Add for f32/f64
pub trait AddScalar<T, S> {
fn add_scalar(self, rhs: S) -> T;
}
impl<S> Cross<Point2<S>, S> for ... | (&self, other: &Point2<S>) -> S {
(self.x * other.y) - (self.y * other.x)
}
}
impl<S> Cross<Vector2<S>, S> for Vector2<S> where S: cgmath::BaseFloat {
fn cross(&self, other: &Vector2<S>) -> S {
(self.x * other.y) - (self.y * other.x)
}
}
impl<S> Dot<Point2<S>, S> for Point2<S> where S: cgm... | cross | identifier_name |
create.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
// | // This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; withou... | random_line_split | |
create.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (inner: TagStoreIdIter, store: &'a Store) -> CreateTimeTrackIter<'a> {
CreateTimeTrackIter {
inner: inner,
store: store,
}
}
pub fn set_end_time(self, datetime: NDT) -> SetEndTimeIter<'a> {
SetEndTimeIter::new(self, datetime)
}
}
impl<'a> Iterator for Create... | new | identifier_name |
0009_auto_20160623_1141.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-06-23 15:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| ),
migrations.AlterUniqueTogether(
name='review',
unique_together=set([('context', 'keyword_proposed', 'category', 'user', 'status')]),
),
]
| dependencies = [
('mendel', '0008_auto_20160613_1911'),
]
operations = [
migrations.RenameField(
model_name='context',
old_name='keyword',
new_name='keyword_given',
),
migrations.RenameField(
model_name='review',
old_na... | identifier_body |
0009_auto_20160623_1141.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-06-23 15:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
('mendel', '0008_auto_20160613_1911'),
]
operations = [
migrations.RenameField(
model_name='context',
old_name='keyword',
new_name='keyword_given',
),
migrations.RenameField(
model_name... | Migration | identifier_name |
0009_auto_20160623_1141.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-06-23 15:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mendel', '0008_auto_20160613_1911'),
]
operations =... | model_name='review',
old_name='keyword',
new_name='keyword_given',
),
migrations.AddField(
model_name='review',
name='keyword_proposed',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='k... | model_name='context',
old_name='keyword',
new_name='keyword_given',
),
migrations.RenameField( | random_line_split |
blockstore_field_data.py | , just attempting to use
# the block as a dict key here will trigger infinite recursion. So
# instead we key the dict on an arbitrary object,
# block key = BlockInstanceUniqueKey() which we create here. That way
# the weak reference will still cause the entry in the WeakKeyDictionary to
# be freed a... | Reset the value of the field named `name` to the default
"""
self.set(block, name, DELETED)
def default(self, block, name):
"""
Get the default value for block's field 'name'.
The XBlock class will provide the default if KeyError is raised; this is
mostly for... | def delete(self, block, name):
""" | random_line_split |
blockstore_field_data.py | a field, raises a KeyError.
"""
# First, get the field from the class, if defined
block_field = getattr(block.__class__, name, None)
if block_field is not None and isinstance(block_field, Field):
return block_field
# Not in the class, so name really doesn't name a fi... | raise RuntimeError(
"This runtime does not allow changing .children directly - use runtime.add_child_include instead."
) | conditional_block | |
blockstore_field_data.py | , just attempting to use
# the block as a dict key here will trigger infinite recursion. So
# instead we key the dict on an arbitrary object,
# block key = BlockInstanceUniqueKey() which we create here. That way
# the weak reference will still cause the entry in the WeakKeyDictionary to
# be freed a... | (self, block, name):
"""
Get the default value for block's field 'name'.
The XBlock class will provide the default if KeyError is raised; this is
mostly for the purpose of context-specific overrides.
"""
raise KeyError(name)
def cache_fields(self, block):
"""... | default | identifier_name |
blockstore_field_data.py | a dict where the key is the hash of the XBlock's
# olx file (as stated by the Blockstore API), and the values is the
# dict of field data as loaded from that OLX file. The field data dicts
# in this should be considered immutable, and never modified.
self.loaded_definitions = {}
... | """
Given a block and the name of one of its fields, check that we will be
able to read/write it.
"""
if name != 'children':
raise InvalidScopeError("BlockstoreChildrenData can only read/write from a field named 'children'") | identifier_body | |
sample-simulator.py | # -*- Mode:Python; -*-
# /*
# * Copyright (c) 2010 INRIA
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation;
# *
# * This program is distributed in the hope that it will b... | import sys
main(sys.argv) | conditional_block | |
sample-simulator.py | # -*- Mode:Python; -*-
# /*
# * Copyright (c) 2010 INRIA
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation;
# *
# * This program is distributed in the hope that it will b... | ## \return None.
def ExampleFunction(model):
print ("ExampleFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s")
model.Start()
## Example function - triggered at a random time.
## \param [in] model The instance of MyModel
## \return None.
def RandomFunction(model):
print ("RandomFunction... | ## Example function - starts MyModel.
## \param [in] model The instance of MyModel | random_line_split |
sample-simulator.py | # -*- Mode:Python; -*-
# /*
# * Copyright (c) 2010 INRIA
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation;
# *
# * This program is distributed in the hope that it will b... |
## Example function - starts MyModel.
## \param [in] model The instance of MyModel
## \return None.
def ExampleFunction(model):
print ("ExampleFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s")
model.Start()
## Example function - triggered at a random time.
## \param [in] model The insta... | """Simple model object to illustrate event handling."""
## \return None.
def Start(self):
"""Start model execution by scheduling a HandleEvent."""
ns.core.Simulator.Schedule(ns.core.Seconds(10.0), self.HandleEvent, ns.core.Simulator.Now().GetSeconds())
## \param [in] self This instance of ... | identifier_body |
sample-simulator.py | # -*- Mode:Python; -*-
# /*
# * Copyright (c) 2010 INRIA
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License version 2 as
# * published by the Free Software Foundation;
# *
# * This program is distributed in the hope that it will b... | (model):
print ("ExampleFunction received event at", ns.core.Simulator.Now().GetSeconds(), "s")
model.Start()
## Example function - triggered at a random time.
## \param [in] model The instance of MyModel
## \return None.
def RandomFunction(model):
print ("RandomFunction received event at", ns.core.Simulat... | ExampleFunction | identifier_name |
bs-alert.tsx | import { Component, Prop, State } from '@stencil/core';
@Component({
tag: 'bs-alert'
})
export class BsAlert {
@State() hidden: boolean = false;
@Prop() color: string;
@Prop() dismissable: boolean = false;
render() {
let classes = {
alert: true
};
if (this.color) |
if (this.dismissable) {
classes['alert-dismissible'] = classes['show'] = classes['fade'] = true;
}
console.log(classes);
return (
!this.hidden && <div class={classes} role="alert">
{this.dismissable && <button type="button" class="close" data-dismiss="alert" aria-label="Close">
... | {
classes['alert-' + this.color] = true;
} | conditional_block |
bs-alert.tsx | import { Component, Prop, State } from '@stencil/core';
@Component({
tag: 'bs-alert'
})
export class BsAlert {
@State() hidden: boolean = false;
@Prop() color: string;
@Prop() dismissable: boolean = false;
render() {
let classes = {
alert: true
};
if (this.color) {
classes['alert... | )
}
} | <span aria-hidden="true">×</span>
</button>}
<slot />
</div> | random_line_split |
bs-alert.tsx | import { Component, Prop, State } from '@stencil/core';
@Component({
tag: 'bs-alert'
})
export class BsAlert {
@State() hidden: boolean = false;
@Prop() color: string;
@Prop() dismissable: boolean = false;
| () {
let classes = {
alert: true
};
if (this.color) {
classes['alert-' + this.color] = true;
}
if (this.dismissable) {
classes['alert-dismissible'] = classes['show'] = classes['fade'] = true;
}
console.log(classes);
return (
!this.hidden && <div class={classes} r... | render | identifier_name |
bootstrap_commands.py | " % env["LD_LIBRARY_PATH"])
@Command('bootstrap',
description='Install required packages for building.',
category='bootstrap')
@CommandArgument('--force', '-f',
action='store_true',
help='Boostrap without confirmation')
def bootstrap(self,... | tarball = "rustc-%s-%s.tar.gz" % (version, host_triple())
rustc_url = "https://static-rust-lang-org.s3.amazonaws.com/dist/" + tarball
else:
tarball = "%s/rustc-nightly-%s.tar.gz" % (version, host_triple())
base_url = "https://s3.amazonaws.com/r... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.