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 |
|---|---|---|---|---|
main.rs | //! # Synacor Challenge
//!
//! A Rust based runtime for the Synacor challenge architecture.
#![warn(missing_docs)]
extern crate byteorder;
extern crate termion;
#[macro_use] extern crate chan;
extern crate chan_signal;
extern crate libc;
extern crate synacor;
mod command;
mod debugger;
use debugger::Debugger;
use s... | else {
Vec::new()
};
let injections = if let Some(val) = args().nth(3) {
let mut buffer = String::new();
let mut injection_file = File::open(val)
.expect("Failed to open injection file");
injection_file.read_to_string(&mut buffer)
.expect("Failed to read... | {
let mut buffer = String::new();
let mut replay_file = File::open(val)
.expect("Failed to open replay file");
replay_file.read_to_string(&mut buffer)
.expect("Failed to read in replay file");
let mut buffer: Vec<_> = buffer.chars().collect();
buffer.rever... | conditional_block |
main.rs | //! # Synacor Challenge
//!
//! A Rust based runtime for the Synacor challenge architecture.
#![warn(missing_docs)]
extern crate byteorder;
extern crate termion;
#[macro_use] extern crate chan;
extern crate chan_signal;
extern crate libc;
extern crate synacor;
mod command;
mod debugger;
use debugger::Debugger;
use s... | buffer
} else {
Vec::new()
};
let injections = if let Some(val) = args().nth(3) {
let mut buffer = String::new();
let mut injection_file = File::open(val)
.expect("Failed to open injection file");
injection_file.read_to_string(&mut buffer)
.ex... | random_line_split | |
main.rs | //! # Synacor Challenge
//!
//! A Rust based runtime for the Synacor challenge architecture.
#![warn(missing_docs)]
extern crate byteorder;
extern crate termion;
#[macro_use] extern crate chan;
extern crate chan_signal;
extern crate libc;
extern crate synacor;
mod command;
mod debugger;
use debugger::Debugger;
use s... | buffer.reverse();
println!("Replay buffer loaded");
buffer
} else {
Vec::new()
};
let injections = if let Some(val) = args().nth(3) {
let mut buffer = String::new();
let mut injection_file = File::open(val)
.expect("Failed to open injection file")... | {
let binary = if let Some(val) = args().nth(1) {
let mut buffer = Vec::new();
let mut in_file = File::open(val)
.expect("Failed to open challenge binary.");
in_file.read_to_end(&mut buffer)
.expect("Failed to read in binary contents.");
buffer
} else {
... | identifier_body |
erlang_views.js | // 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 law or agreed to in writing, software
// distributed un... | },
views: {
simple_view : {
map: mfun,
reduce: rfun
}
}
};
T(db.save(designDoc).ok);
var url = "/test_suite_db/_design/erlview/_show/simple/1";
var xhr = CouchDB.request("GET", url);
T(xhr.status == 200, "standard get sho... | random_line_split | |
erlang_views.js | // 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 law or agreed to in writing, software
// distributed un... |
T(db.bulkSave(docs).length, 250, "Saved big doc set.");
var mfun = 'fun({Doc}) -> ' +
'Words = couch_util:get_value(<<"words">>, Doc), ' +
'lists:foreach(fun({Word}) -> ' +
'WordString = couch_util:get_value(<<"word">>, Word), ' +
'Count = couch_util:get_valu... | {
var body = [];
for(var j = 0; j < 100; j++) {
body.push({
word: words[j%words.length],
count: j
});
}
docs.push({
"_id": "test-" + i,
"words": body
});
} | conditional_block |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
} | top_left: top_left,
bottom_right: Point {
x: top_left.x + width as i16,
y: top_left.y + height as i16,
}
}
}
pub fn centre(&self) -> Point<i16> {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
... |
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle { | random_line_split |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right:... |
if self.top_left.y < top {
let diff = top - self.top_left.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
if self.bottom_right.x > right {
let diff = right - self.bottom_right.x;
self.top_left.x += diff;
self.bo... | {
let diff = left - self.top_left.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
} | conditional_block |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right:... |
pub fn is_intersecting(&self, other: &Rectangle) -> bool {
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
pub fn clamp_to(&mut self, (left, top): (i16, i16), (ri... | {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
y: ((self.top_left.y + self.bottom_right.y) / 2),
}
} | identifier_body |
rectangle.rs | use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right:... | (&self, other: &Rectangle) -> bool {
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) {
... | is_intersecting | identifier_name |
dep-graph-caller-callee.rs | // Copyright 2012-2014 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... | }
mod z {
use y;
// These are expected to yield errors, because changes to `x`
// affect the BODY of `y`, but not its signature.
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path
pub fn z() {
y::y();
}
} | random_line_split | |
dep-graph-caller-callee.rs | // Copyright 2012-2014 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... |
}
mod y {
use x;
// These dependencies SHOULD exist:
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
pub fn y() {
x::x();
}
}
mod z {
use y;
// These are expected to yield errors, because changes to `x`
// affect the BODY of `y`, but not its signature.
#[rustc_t... | { } | identifier_body |
dep-graph-caller-callee.rs | // Copyright 2012-2014 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... | () {
y::y();
}
}
| z | identifier_name |
for-options.directive.ts | import { NgForOf, NgForOfContext } from '@angular/common';
import { ChangeDetectorRef, Directive, forwardRef, Input, IterableDiffers, OnDestroy, TemplateRef, TrackByFunction, ViewContainerRef } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { ALuOptionOperator, ILuOptionOperator } from '.... | <T> extends NgForOf<T> implements ILuOptionOperator<T>, OnDestroy {
outOptions$;
protected _subs = new Subscription();
set inOptions$(options$: Observable<T[]>) {
this._subs.add(
options$.subscribe((options) => {
this.ngForOf = options;
this._changeDetectionRef.markForCheck();
}),
);
this.outOpti... | LuForOptionsDirective | identifier_name |
for-options.directive.ts | import { NgForOf, NgForOfContext } from '@angular/common';
import { ChangeDetectorRef, Directive, forwardRef, Input, IterableDiffers, OnDestroy, TemplateRef, TrackByFunction, ViewContainerRef } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { ALuOptionOperator, ILuOptionOperator } from '.... |
constructor(_viewContainer: ViewContainerRef, _template: TemplateRef<NgForOfContext<T>>, _differs: IterableDiffers, protected _changeDetectionRef: ChangeDetectorRef) {
super(_viewContainer, _template, _differs);
}
ngOnDestroy() {
this._subs.unsubscribe();
}
}
| {
this.ngForTrackBy = fn;
} | identifier_body |
for-options.directive.ts | import { NgForOf, NgForOfContext } from '@angular/common';
import { ChangeDetectorRef, Directive, forwardRef, Input, IterableDiffers, OnDestroy, TemplateRef, TrackByFunction, ViewContainerRef } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import { ALuOptionOperator, ILuOptionOperator } from '.... | providers: [
{
provide: ALuOptionOperator,
useExisting: forwardRef(() => LuForOptionsDirective),
multi: true,
},
],
})
export class LuForOptionsDirective<T> extends NgForOf<T> implements ILuOptionOperator<T>, OnDestroy {
outOptions$;
protected _subs = new Subscription();
set inOptions$(options$: Obser... | random_line_split | |
BSPTree.py | from random import randint, seed, choice, random
from numpy import zeros, uint8, cumsum, floor, ceil
from math import sqrt, log
from collections import namedtuple
from PIL import Image
from logging import info, getLogger
class Tree:
def __init__(self, leaf):
|
def get_leafs(self):
if self.lchild == None and self.rchild == None:
return [self.leaf]
else:
return self.lchild.get_leafs()+self.rchild.get_leafs()
def get_level(self, level, queue):
if queue == None:
queue = []
if level == 1:
queue.push(self)
else:
if self.lchild != None:
self.lchild.g... | self.leaf = leaf
self.lchild = None
self.rchild = None | identifier_body |
BSPTree.py | from random import randint, seed, choice, random
from numpy import zeros, uint8, cumsum, floor, ceil
from math import sqrt, log
from collections import namedtuple
from PIL import Image
from logging import info, getLogger
class Tree:
def __init__(self, leaf):
self.leaf = leaf
self.lchild = None
self.rchild = Non... |
class Container():
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
self.center = (self.x+int(self.w/2),self.y+int(self.h/2))
self.distance_from_center = sqrt((self.center[0]-MAP_WIDTH/2)**2 + (self.center[1]-MAP_HEIGHT/2)**2)
def paint(self, c):
c.stroke_rectangle(self.x, s... | self.rchild.paint(c) | conditional_block |
BSPTree.py | from random import randint, seed, choice, random
from numpy import zeros, uint8, cumsum, floor, ceil
from math import sqrt, log
from collections import namedtuple
from PIL import Image
from logging import info, getLogger
class Tree:
def __init__(self, leaf):
self.leaf = leaf
self.lchild = None
self.rchild = Non... | if tree.lchild == None or tree.rchild == None:
return
tree.lchild.leaf.draw_path(c, tree.rchild.leaf)
draw_paths(c, tree.lchild)
draw_paths(c, tree.rchild)
MAP_WIDTH = 0
MAP_HEIGHT = 0
N_ITERATIONS = 0
H_RATIO = 0
W_RATIO = 0
MIN_ROOM_SIDE = 0
CENTER_HUB_HOLE = 0
CENTER_HUB_RADIO = 0
MAP_NAME = 0
def init(num_p... |
def draw_paths(c, tree): | random_line_split |
BSPTree.py | from random import randint, seed, choice, random
from numpy import zeros, uint8, cumsum, floor, ceil
from math import sqrt, log
from collections import namedtuple
from PIL import Image
from logging import info, getLogger
class Tree:
def __init__(self, leaf):
self.leaf = leaf
self.lchild = None
self.rchild = Non... | (container, iter):
root = Tree(container)
if iter != 0:
sr = random_split(container)
if sr!=None:
root.lchild = split_container(sr[0], iter-1)
root.rchild = split_container(sr[1], iter-1)
return root
def draw_paths(c, tree):
if tree.lchild == None or tree.rchild == None:
return
tree.lchild.leaf.draw_p... | split_container | identifier_name |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn newgame_con() -> Context {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PA... | f.home == f.away || f.home_score > 10 || f.away_score > 10 {
let mut context = newgame_con();
context.insert("fejl",
&"Den indtastede kamp er ikke lovlig 😜");
return Resp::cont(respond_page("newgame_fejl", context));
}
let res = lock_database().execute("I... |
if !(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score || | random_line_split |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn newgame_con() -> Context {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PA... | if !(f.home_score == 10 || f.away_score == 10) || f.home_score == f.away_score ||
f.home == f.away || f.home_score > 10 || f.away_score > 10 {
let mut context = newgame_con();
context.insert("fejl",
&"Den indtastede kamp er ikke lovlig 😜");
return Resp::cont(re... | {
let mut context = newgame_con();
context.insert("fejl", &"Det indtastede kodeord er forkert 💩");
return Resp::cont(respond_page("newgame_fejl", context));
}
| conditional_block |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn newgame_con() -> Context | })
.unwrap()
.map(Result::unwrap)
.collect();
let mut context = create_context("games");
context.insert("names", &names);
context.insert("balls", &balls);
context
}
#[derive(FromForm)]
pub struct NewGame {
home: i32,
away: i32,
home_score: i32,
away_score: i32... | {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| {
Named {
id: row.get(0),
name: row.get(1)
}
})
.unwrap()
... | identifier_body |
games.rs | use crate::*;
#[get("/newgame")]
pub fn newgame<'a>() -> ContRes<'a> {
respond_page("newgame", newgame_con())
}
pub fn | () -> Context {
let conn = lock_database();
let mut stmt = conn.prepare("SELECT id, name FROM players order by random()").unwrap();
let names: Vec<_> = stmt.query_map(NO_PARAMS, |row| {
Named {
id: row.get(0),
name: row.get(1)
}
})
.unw... | newgame_con | identifier_name |
cari.ts | import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Http } from '@angular/http';
import { ActionSheetController } from 'ionic-angular';
import { NotifikasiPage } from '../notifikasi/notifikasi';
import { ArtikelBacaPage } from '../artikel-baca/artikel-bac... | (idArtikel){
this.navCtrl.push(ArtikelBacaPage, idArtikel);
}
presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
title: 'Pilihan',
buttons: [
{
text: 'Tulis Artikel',
role: 'tulisArtikel',
handler: () => {
console.log('Tulis A... | baca | identifier_name |
cari.ts | import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Http } from '@angular/http';
import { ActionSheetController } from 'ionic-angular';
import { NotifikasiPage } from '../notifikasi/notifikasi';
import { ArtikelBacaPage } from '../artikel-baca/artikel-bac... | else{
let toast = this.toastCtrl.create({
message: 'Tidak dapat menyambungkan ke server. Mohon muat kembali halaman ini.',
position: 'bottom',
showCloseButton: true,
closeButtonText: 'X'
});
toast.present();
}
this.httpErr = true;
}
}
| {
let toast = this.toastCtrl.create({
message: 'Tidak ada koneksi. Cek kembali sambungan Internet perangkat Anda.',
position: 'bottom',
showCloseButton: true,
closeButtonText: 'X'
});
toast.present();
} | conditional_block |
cari.ts | import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Http } from '@angular/http';
import { ActionSheetController } from 'ionic-angular';
import { NotifikasiPage } from '../notifikasi/notifikasi';
import { ArtikelBacaPage } from '../artikel-baca/artikel-bac... | console.log('Begin async operation');
setTimeout(() => {
this.limit = this.limit+5;
this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => {
this.posts = this.posts.concat(res.json());
});
console.log('Async operat... | }
doInfinite(infiniteScroll) { | random_line_split |
cari.ts | import { Component } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Http } from '@angular/http';
import { ActionSheetController } from 'ionic-angular';
import { NotifikasiPage } from '../notifikasi/notifikasi';
import { ArtikelBacaPage } from '../artikel-baca/artikel-bac... |
getData() {
this.limit = 0;
this.http.get('http://cybex.ipb.ac.id/api/search.php?search='+this.searchQuery+'&limit='+this.limit).subscribe(res => {
this.posts = res.json();
console.log('dapet data');
this.httpErr = false;
}, err => {this.showAlert(err.status)});
}
getItems(searchba... | {
this.navCtrl.push(NotifikasiPage);
} | identifier_body |
models.py | browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
salt, hash = generate_sha1(instance.id)
return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH,
'hash': hash[:10],
... | (self):
"""
Sends an email to confirm the new email address.
This method sends out two emails. One to the new email address that
contains the ``email_confirmation_key`` which is used to verify this
this email address with :func:`UserenaUser.objects.confirm_email`.
The o... | send_confirmation_email | identifier_name |
models.py | browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
salt, hash = generate_sha1(instance.id)
return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH,
'hash': hash[:10],
... |
email_confirmation_key_created = models.DateTimeField(_('creation date of email confirmation key'),
blank=True,
null=True)
objects = UserenaManager()
class Meta:
verbose_name = _('... | email_confirmation_key = models.CharField(_('unconfirmed email verification key'),
max_length=40,
blank=True) | random_line_split |
models.py | browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
salt, hash = generate_sha1(instance.id)
return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH,
'hash': hash[:10],
... |
def change_email(self, email):
"""
Changes the email address for a user.
A user needs to verify this new email address before it becomes
active. By storing the new email address in a temporary field --
``temporary_email`` -- we are able to set this email address after the
... | return '%s' % self.user.username | identifier_body |
models.py | browse through the mugshot directory.
"""
extension = filename.split('.')[-1].lower()
salt, hash = generate_sha1(instance.id)
return '%(path)s%(hash)s.%(extension)s' % {'path': userena_settings.USERENA_MUGSHOT_PATH,
'hash': hash[:10],
... |
else:
auto_join_key = hashlib.md5(self.activation_key +
settings.AGORA_API_AUTO_ACTIVATION_SECRET).hexdigest()
activation_url = reverse('auto_join_activate', args=(self.user.username, auto_join_key))
context= {'user': self.user,
'p... | auto_join_key = auto_join_secret | conditional_block |
control.py | #!/usr/bin/env python
# coding:utf-8
import sys, os
from twisted.internet import reactor
from bottle import Bottle
from bottle import request
from bottle import response
from bottle import redirect
from bottle import static_file
from bottle import abort
from hashlib import md5
from urlparse import urljoin
from toughrad... | (render):
return render("index", **locals())
| index | identifier_name |
control.py | #!/usr/bin/env python
# coding:utf-8
import sys, os
from twisted.internet import reactor
from bottle import Bottle
from bottle import request
from bottle import response
from bottle import redirect
from bottle import static_file
from bottle import abort
from hashlib import md5
from urlparse import urljoin
from toughrad... |
@app.get('/', apply=auth_ctl)
def control_index(render):
return render("index")
@app.route('/dashboard', apply=auth_ctl)
def index(render):
return render("index", **locals())
| static_path = os.path.join(os.path.split(os.path.split(__file__)[0])[0], 'static')
return static_file(path, root=static_path) | identifier_body |
html_completions.py | # Only trigger within HTML
if not view.match_selector(locations[0],
"text.html - source - meta.tag, punctuation.definition.tag.begin"):
return []
# Get the contents of each line, from the beginning of the line to
# each point
lines = [view.substr(subl... | # It expands these simple expressions:
# tag.class
# tag#id
class HtmlCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations): | random_line_split | |
html_completions.py | 0}>$0".format(tag, arg)
else:
|
return [(expr, snippet)]
# Provide completions that match just after typing an opening angle bracket
class TagCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
# Only trigger within HTML
if not view.match_selector(locations[0],
... | snippet = "<{0} id=\"{1}\">$1</{0}>$0".format(tag, arg) | conditional_block |
html_completions.py | (sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
# Only trigger within HTML
if not view.match_selector(locations[0],
"text.html - source - meta.tag, punctuation.definition.tag.begin"):
return []
# Get the contents of each l... | HtmlCompletions | identifier_name | |
html_completions.py | for i in xrange(1, len(lines)):
ex = match(rex, lines[i])
if ex != expr:
return []
# Return the completions
arg, op, tag = rex.match(expr).groups()
arg = arg[::-1]
tag = tag[::-1]
expr = expr[::-1]
if op == '.':
... | if not view.match_selector(locations[0],
"text.html - source - meta.tag, punctuation.definition.tag.begin"):
return []
# Get the contents of each line, from the beginning of the line to
# each point
lines = [view.substr(sublime.Region(view.line(l).a, l))
... | identifier_body | |
ch4_ex4.1.4.py | #!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph)... | self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
| def setUp(self):
self.graph = UnigraphExtra(random.randrange(10, 15))
for edge in range(2 * self.graph.vertices()):
f, t = (random.randrange(self.graph.vertices()) for x in range(2))
self.graph.add_edge(f, t)
def test_edge(self):
for vertex in range(self.graph.vertic... | identifier_body |
ch4_ex4.1.4.py | #!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph)... | self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main() | for vertex in range(self.graph.vertices()): | random_line_split |
ch4_ex4.1.4.py | #!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph)... | (self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
| test_self_loop | identifier_name |
ch4_ex4.1.4.py | #!/usr/bin/env python
#
# Created by Samvel Khalatyan on Mar 23, 2014
# Copyright (c) 2014 Samvel Khalatyan. All rights reserved
#
# Use of this source code is governed by a license that can be found in
# the LICENSE file.
import random
import unittest
from lib import unigraph
class UnigraphExtra(unigraph.Unigraph)... |
def test_self_loop(self):
for vertex in range(self.graph.vertices()):
self.assertTrue(self.graph.has_edge(vertex, vertex))
if "__main__" == __name__:
unittest.main()
| self.assertFalse(self.graph.has_edge(vertex, adj_vertex)) | conditional_block |
util.rs | #![allow(dead_code)]
use std::env;
use std::fs::{self, File};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::symlink as symlink_file;
#[cfg(windows)]
use std::os::windows::fs::symlink_file;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8;
#[macro_export]
macro_rules! ... |
pub fn symlink(src: &str, dst: &str) {
symlink_file(src, dst).unwrap();
}
pub fn is_symlink(path: &str) -> bool {
match fs::symlink_metadata(path) {
Ok(m) => m.file_type().is_symlink(),
Err(_) => false
}
}
pub fn resolve_link(path: &str) -> String {
match fs::read_link(path) {
... | {
File::create(Path::new(file)).unwrap();
} | identifier_body |
util.rs | #![allow(dead_code)]
use std::env;
use std::fs::{self, File};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::symlink as symlink_file;
#[cfg(windows)]
use std::os::windows::fs::symlink_file;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8;
#[macro_export]
macro_rules! ... | pub fn touch(file: &str) {
File::create(Path::new(file)).unwrap();
}
pub fn symlink(src: &str, dst: &str) {
symlink_file(src, dst).unwrap();
}
pub fn is_symlink(path: &str) -> bool {
match fs::symlink_metadata(path) {
Ok(m) => m.file_type().is_symlink(),
Err(_) => false
}
}
pub fn res... | }
| random_line_split |
util.rs | #![allow(dead_code)]
use std::env;
use std::fs::{self, File};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::symlink as symlink_file;
#[cfg(windows)]
use std::os::windows::fs::symlink_file;
use std::path::Path;
use std::process::{Command, Stdio};
use std::str::from_utf8;
#[macro_export]
macro_rules! ... | (path: &str) -> fs::Metadata {
match fs::metadata(path) {
Ok(m) => m,
Err(e) => panic!("{}", e)
}
}
pub fn file_exists(path: &str) -> bool {
match fs::metadata(path) {
Ok(m) => m.is_file(),
Err(_) => false
}
}
pub fn dir_exists(path: &str) -> bool {
match fs::metada... | metadata | identifier_name |
cssMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (uri: string, documentVersion: number, edits: TextEdit[]) {
let textEditor = window.activeTextEditor;
if (textEditor && textEditor.document.uri.toString() === uri) {
if (textEditor.document.version !== documentVersion) {
window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.... | applyCodeAction | identifier_name |
cssMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | // If the extension is launch in debug mode the debug server options are use
// Otherwise the run options are used
let serverOptions: ServerOptions = {
run: { module: serverModule, transport: TransportKind.ipc },
debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
};
// Option... | // The debug options for the server
let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] };
| random_line_split |
cssMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | initializationOptions: {
}
};
// Create the language client and start the client.
let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions);
let disposable = client.start();
// Push the disposable to the context's subscriptions so that the
// cli... | {
// The server is implemented in node
let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js'));
// The debug options for the server
let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] };
// If the extension is launch in debug mode the debug server options are use
// Oth... | identifier_body |
cssMain.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
});
}
}
}
| {
window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.');
} | conditional_block |
stream.py | S"]))
class QueuedStanza:
def __init__(self, s):
self.task_set = set()
self.stanza = s
class ParserTask(asyncio.Task):
def __init__(self, stream, loop=None):
super().__init__(self._run(), loop=loop)
self._parser = Parser()
self._data_queue = asyncio.Queue()
se... | (asyncio.Protocol):
"""Base class for XMPP streams."""
def __init__(self, creds, state_callbacks=None, mixins=None,
default_timeout=None):
self.creds = creds
self._transport = None
self._waiter_futures = []
self._tls_active = False
self._callbacks = stat... | Stream | identifier_name |
stream.py | _TIMEOUTS"]))
class QueuedStanza:
def __init__(self, s):
self.task_set = set()
self.stanza = s
class ParserTask(asyncio.Task):
def __init__(self, stream, loop=None):
super().__init__(self._run(), loop=loop)
self._parser = Parser()
self._data_queue = asyncio.Queue()
... |
self._stanza_queue = deque(maxlen=10)
@property
def connected(self):
if not self._transport:
return False
else:
if (getattr(self._transport, "_closing") and
self._transport._closing):
# SSL transport
return Fa... | self.creds = creds
self._transport = None
self._waiter_futures = []
self._tls_active = False
self._callbacks = state_callbacks
self._mixins = mixins or []
for mixin in self._mixins:
for name, obj in mixin._exports:
if name in self.__dict__:
... | identifier_body |
stream.py | ValueError("Mixin '%s' exports ambiguous "
"data named '%s'" % (str(mixin), name))
else:
# Add the symbol to the stream's namespace
self.__dict__[name] = obj
self._parser_task = ParserTask(self)
self.default_t... | log.debug("MatchStanza: matched") | random_line_split | |
stream.py | S"]))
class QueuedStanza:
def __init__(self, s):
self.task_set = set()
self.stanza = s
class ParserTask(asyncio.Task):
def __init__(self, stream, loop=None):
super().__init__(self._run(), loop=loop)
self._parser = Parser()
self._data_queue = asyncio.Queue()
se... |
await self._stream._handleStanza(stanza)
except asyncio.CancelledError:
pass
except Exception as ex:
log.exception(ex)
class Stream(asyncio.Protocol):
"""Base class for XMPP streams."""
def __init__(self, creds, state_callbacks=None... | log.verbose("[STANZA IN]:\n%s" %
stanza.toXml(pprint=True).decode("utf-8")) | conditional_block |
app.js | var express = require('express');
var swig = require('swig');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression');
var cluster = require('cluster');
var app = express();
var env = app.get('env') || 'development';
app.set('env', env);
var boot... |
} else {
boot();
//require('./utils/functions').swig(swig); //swig extension
}
| {
cluster.fork();
} | conditional_block |
app.js | var express = require('express');
var swig = require('swig');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression');
var cluster = require('cluster');
var app = express();
var env = app.get('env') || 'development';
app.set('env', env);
var boot... |
if (cluster.isMaster && app.get('env') == 'production') { // Add cluster support
var cpuCount = require('os').cpus().length;
for (var i = 0; i < cpuCount; i++) {
cluster.fork();
}
} else {
boot();
//require('./utils/functions').swig(swig); //swig extension
} | console.log('Application Started on http://localhost:' + app.get('port'));
};
| random_line_split |
canvasgradient.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 canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use ... | let color = CSSColor::parse(&mut parser);
let color = if parser.is_exhausted() {
match color {
Ok(CSSColor::RGBA(rgba)) => rgba,
Ok(CSSColor::CurrentColor) => RGBA::new(0, 0, 0, 255),
_ => return Err(Error::Syntax)
}
} else ... | }
let mut input = ParserInput::new(&color);
let mut parser = Parser::new(&mut input); | random_line_split |
canvasgradient.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 canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use ... | {
Linear(LinearGradientStyle),
Radial(RadialGradientStyle),
}
impl CanvasGradient {
fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient {
CanvasGradient {
reflector_: Reflector::new(),
style: style,
stops: DOMRefCell::new(Vec::new()),
}
}
... | CanvasGradientStyle | identifier_name |
canvasgradient.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 canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use ... |
CanvasGradientStyle::Radial(ref gradient) => {
FillOrStrokeStyle::RadialGradient(RadialGradientStyle::new(gradient.x0,
gradient.y0,
gradient.... | {
FillOrStrokeStyle::LinearGradient(LinearGradientStyle::new(gradient.x0,
gradient.y0,
gradient.x1,
... | conditional_block |
prerender.js | 'use strict';
import optimist from 'optimist';
import fs from 'fs';
import { resolve } from 'path';
// import { renderPath } from '../dist/server-bundle';
// nginx will look for $uri with the .html extension
const prerenderRoutes = [
{
path: '/',
filename: 'index.html'
},
{
path: '/counters',
fil... | /*
prerenderRoutes.forEach((route) => {
fs.writeFile(
resolve(__dirname, argv.out + route.filename), resolvePath(route.path),
(err) => {
if(err) {
return console.log(err); // eslint-disable-line
}
console.log(`${route.filename} saved...`); //eslint-disable-line
});
});
*/ | let argv = optimist
.alias('o', 'out')
.default('o', 'site/')
.argv; | random_line_split |
FluxUtils.tsx | import { Dispatcher } from "flux";
import { ReduceStore, Container } from "flux/utils";
import * as React from "react";
interface Payload {
type: string;
}
const basicDispatcher = new Dispatcher<Payload>();
// Sample Reduce Store
class CounterStore extends ReduceStore<number, any> {
getInitialState(): number... | (): Container.StoresList {
return [Store];
}
static calculateState(prevState: State, props: Props): State {
return {
counter: Store.getState() - (props.b ? 0 : 1)
};
}
render() {
return <div>
{this.state.counter}
</div>;
}
}
const Co... | getStores | identifier_name |
FluxUtils.tsx | import { Dispatcher } from "flux";
import { ReduceStore, Container } from "flux/utils";
import * as React from "react";
interface Payload {
type: string;
}
const basicDispatcher = new Dispatcher<Payload>();
// Sample Reduce Store
class CounterStore extends ReduceStore<number, any> {
getInitialState(): number... | case 'square':
return state * state;
default:
return state;
}
}
}
const Store = new CounterStore(basicDispatcher);
// Sample Flux container with Store
interface Props {
a: string;
b: boolean;
}
interface State {
counter: number;
}
class ... | switch (action.type) {
case 'increment':
return state + 1; | random_line_split |
FluxUtils.tsx | import { Dispatcher } from "flux";
import { ReduceStore, Container } from "flux/utils";
import * as React from "react";
interface Payload {
type: string;
}
const basicDispatcher = new Dispatcher<Payload>();
// Sample Reduce Store
class CounterStore extends ReduceStore<number, any> {
getInitialState(): number... |
}
const Store = new CounterStore(basicDispatcher);
// Sample Flux container with Store
interface Props {
a: string;
b: boolean;
}
interface State {
counter: number;
}
class CounterContainer extends React.Component<Props, State> {
static getStores(): Container.StoresList {
return [Store];
... | {
switch (action.type) {
case 'increment':
return state + 1;
case 'square':
return state * state;
default:
return state;
}
} | identifier_body |
lib.rs | //! A Rust crate to connect a HD44780 lcd display
//!
//! # Example
//! ```no_run
//! use pi_lcd::*;
//!
//! // create a new lcd
//! let lcd = HD44780::new(11,10,[6,5,4,1],20,4);
//!
//! // send a String to the lcd at row 0
//! lcd.send_string("Hello World".to_string(),0);
//! ```
extern crate cupi;
extern crate regex... | }
if bits & 0x04 == 0x04 {
self.data[2].borrow_mut().high().unwrap();
}
if bits & 0x08 == 0x08 {
self.data[3].borrow_mut().high().unwrap();
}
e_wait();
self.e.borrow_mut().high().unwrap();
e_wait();
self.e.borrow_mut().low()... | random_line_split | |
lib.rs | //! A Rust crate to connect a HD44780 lcd display
//!
//! # Example
//! ```no_run
//! use pi_lcd::*;
//!
//! // create a new lcd
//! let lcd = HD44780::new(11,10,[6,5,4,1],20,4);
//!
//! // send a String to the lcd at row 0
//! lcd.send_string("Hello World".to_string(),0);
//! ```
extern crate cupi;
extern crate regex... | () {
std::thread::sleep(Duration::new(0, 50));
}
| e_wait | identifier_name |
lib.rs | //! A Rust crate to connect a HD44780 lcd display
//!
//! # Example
//! ```no_run
//! use pi_lcd::*;
//!
//! // create a new lcd
//! let lcd = HD44780::new(11,10,[6,5,4,1],20,4);
//!
//! // send a String to the lcd at row 0
//! lcd.send_string("Hello World".to_string(),0);
//! ```
extern crate cupi;
extern crate regex... |
fn select_row(&self, row: u32) {
// select the row where the String should be printed at
self.send_byte(self.lines[row as usize], COMMAND);
}
fn write(&self, charlist: Vec<u8>) {
// send every single char to send_byte
for x in charlist {
self.send_byte(x, DATA)... | {
// send new custom character to cgram address
match address {
0...7 => {
self.command(CGRAM_ADDRESS | address << 3);
for row in &bitmap {
self.send_byte(bitmap[*row as usize], DATA);
}
Ok(address)
... | identifier_body |
constellation_msg.rs | . See `PagePx` documentation for details.
pub visible_viewport: TypedSize2D<PagePx, f32>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>,
}
#[derive(PartialEq, Eq, Copy, Clone, Deserialize, Serialize)]
pub ... | detail | identifier_name | |
constellation_msg.rs | Eq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum IFrameSandboxState {
IFrameSandboxed,
IFrameUnsandboxed
}
// We pass this info to various tasks, so it lives in a separate, cloneable struct.
#[derive(Clone, Copy, Deserialize, Serialize)]
pub struct Failure {
pub pipeline_id: PipelineId,
pu... | /// Requests that the constellation retrieve the current contents of the clipboard
GetClipboardContents(IpcSender<String>),
/// Requests that the constellation set the contents of the clipboard
SetClipboardContents(String),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
... | /// with the provided parent pipeline id and subpage id
GetFrame(PipelineId, SubpageId, IpcSender<Option<FrameId>>),
/// Notifies the constellation that this frame has received focus.
Focus(PipelineId), | random_line_split |
copyProperties.js | /**
* Copyright 2013-2014 Facebook, Inc.
*
* 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 law or agree... |
}
return obj;
}
module.exports = copyProperties;
| {
obj.toString = v.toString;
} | conditional_block |
copyProperties.js | /**
* Copyright 2013-2014 Facebook, Inc.
*
* 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 law or agree... | }
// IE ignores toString in object iteration.. See:
// webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html
if (v.hasOwnProperty && v.hasOwnProperty('toString') &&
(typeof v.toString !== 'undefined') && (obj.toString !== v.toString)) {
obj.toString = v.toString;
}
... | for (var k in v) {
obj[k] = v[k]; | random_line_split |
copyProperties.js | /**
* Copyright 2013-2014 Facebook, Inc.
*
* 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 law or agree... | (typeof v.toString !== 'undefined') && (obj.toString !== v.toString)) {
obj.toString = v.toString;
}
}
return obj;
}
module.exports = copyProperties;
| {
obj = obj || {};
if (process.env.NODE_ENV !== 'production') {
if (f) {
throw new Error('Too many arguments passed to copyProperties');
}
}
var args = [a, b, c, d, e];
var ii = 0, v;
while (args[ii]) {
v = args[ii++];
for (var k in v) {
obj[k] = v[k];
}
// IE ignores ... | identifier_body |
copyProperties.js | /**
* Copyright 2013-2014 Facebook, Inc.
*
* 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 law or agree... | (obj, a, b, c, d, e, f) {
obj = obj || {};
if (process.env.NODE_ENV !== 'production') {
if (f) {
throw new Error('Too many arguments passed to copyProperties');
}
}
var args = [a, b, c, d, e];
var ii = 0, v;
while (args[ii]) {
v = args[ii++];
for (var k in v) {
obj[k] = v[k];
... | copyProperties | identifier_name |
update-downloads.rs | #![deny(warnings)]
#![feature(std_misc, core, os, io, env)]
extern crate "cargo-registry" as cargo_registry;
extern crate postgres;
extern crate semver;
extern crate time;
extern crate env_logger;
use std::env;
use std::collections::HashMap;
use std::time::Duration;
use cargo_registry::{VersionDownload, Version, Mod... | tx.execute("INSERT INTO version_downloads \
(version_id, downloads, counted, date, processed)
VALUES ($1, 1, 0, current_date, false)",
&[&version.id]).unwrap();
::update(&tx).unwrap();
assert_eq!(Version::find(&tx, version.id).unwrap().d... | random_line_split | |
update-downloads.rs | #![deny(warnings)]
#![feature(std_misc, core, os, io, env)]
extern crate "cargo-registry" as cargo_registry;
extern crate postgres;
extern crate semver;
extern crate time;
extern crate env_logger;
use std::env;
use std::collections::HashMap;
use std::time::Duration;
use cargo_registry::{VersionDownload, Version, Mod... | (conn: &postgres::Transaction) -> User{
User::find_or_insert(conn, "login", None, None, None,
"access_token", "api_token").unwrap()
}
fn crate_downloads(tx: &postgres::Transaction, id: i32, expected: usize) {
let stmt = tx.prepare("SELECT * FROM crate_downloads
... | user | identifier_name |
update-downloads.rs | #![deny(warnings)]
#![feature(std_misc, core, os, io, env)]
extern crate "cargo-registry" as cargo_registry;
extern crate postgres;
extern crate semver;
extern crate time;
extern crate env_logger;
use std::env;
use std::collections::HashMap;
use std::time::Duration;
use cargo_registry::{VersionDownload, Version, Mod... | assert_eq!(Crate::find(&tx, krate.id).unwrap().downloads, 2);
crate_downloads(&tx, krate.id, 2);
::update(&tx).unwrap();
assert_eq!(Version::find(&tx, version.id).unwrap().downloads, 2);
}
}
| {
let conn = conn();
let tx = conn.transaction().unwrap();
let user = user(&tx);
let krate = Crate::find_or_insert(&tx, "foo", user.id, &None,
&None, &None, &None, &[], &None,
&None, &None).unwrap();
... | identifier_body |
TextOutput.js | import {appendHtml, combine} from './../util';
const ELEMENT_NAMES = {
frameName: 'text-frame',
messageName: 'text-message',
indicatorName: 'text-indicator'
};
let createElements = (container, names) => {
const elements = '\
<div class="text-frame" id="' + names.frameName + '">\
<span class="text-me... | ) {
this._textMessages = [];
this.textMessageFrame.classList.remove("in");
this.textMessage.innerHTML = "";
this.textIndicator.classList.remove("in");
this.engine.unpause();
}
displayText (text) {
this._textMessages = this._textMessages.concat(text);
}
drawMessages () {
if (this._t... | earText ( | identifier_name |
TextOutput.js | import {appendHtml, combine} from './../util';
const ELEMENT_NAMES = {
frameName: 'text-frame',
messageName: 'text-message',
indicatorName: 'text-indicator'
};
let createElements = (container, names) => {
const elements = '\
<div class="text-frame" id="' + names.frameName + '">\
<span class="text-me... | createElements(parent, elementNames);
}
this._textMessages = [];
this.engine = engine;
this.textMessageFrame = document.getElementById(elementNames.frameName);
this.textMessage = document.getElementById(elementNames.messageName);
this.textIndicator = document.getElementById(elementNames.... | let elementNames = Object.assign(ELEMENT_NAMES, engine.overrides.customElementNames);
if (!engine.overrides.useCustomElements) { | random_line_split |
TextOutput.js | import {appendHtml, combine} from './../util';
const ELEMENT_NAMES = {
frameName: 'text-frame',
messageName: 'text-message',
indicatorName: 'text-indicator'
};
let createElements = (container, names) => {
const elements = '\
<div class="text-frame" id="' + names.frameName + '">\
<span class="text-me... | } else {
this.clearText();
}
}
}
| this.textIndicator.classList.remove("in");
}
| conditional_block |
artistphoto.py | #################################################################
# This file is part of glyr
# + a command-line tool and library to download various sort of music related metadata.
# + Copyright (C) [2011-2012] [Christopher Pahl]
# + Hosted at: https://github.com/sahib/glyr
#
# glyr is free software: you can redistri... | 'expect': len_equal_0
}],
}, {
# }}}
# {{{
'name': 'singerpictures',
'data': [{
'options': {
'get_type': 'artistphoto',
'artist': 'Equilibrium'
},
'expect': len_greater_0
}, {
'options': not_found_options,
'e... | 'options': not_found_options, | random_line_split |
issue-5791.rs | // Copyright 2013 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 |
issue-5791.rs | // Copyright 2013 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 malloc2(len: libc::c_int, foo: libc::c_int) -> *const libc::c_void;
}
pub fn main () {} | #[link_name = "malloc"]
fn malloc1(len: libc::c_int) -> *const libc::c_void;
#[link_name = "malloc"] | random_line_split |
issue-5791.rs | // Copyright 2013 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 ... | {} | identifier_body | |
manager.py | # Copyright 2012 OpenStack Foundation
#
# 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 law ... | (self):
crypto.ensure_ca_filesystem()
def revoke_certs_by_user(self, context, user_id):
"""Revoke all user certs."""
return crypto.revoke_certs_by_user(user_id)
def revoke_certs_by_project(self, context, project_id):
"""Revoke all project certs."""
return crypto.revoke_... | init_host | identifier_name |
manager.py | # Copyright 2012 OpenStack Foundation
# | # 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# ... | # Licensed under the Apache License, Version 2.0 (the "License"); you may | random_line_split |
manager.py | # Copyright 2012 OpenStack Foundation
#
# 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 law ... |
def init_host(self):
crypto.ensure_ca_filesystem()
def revoke_certs_by_user(self, context, user_id):
"""Revoke all user certs."""
return crypto.revoke_certs_by_user(user_id)
def revoke_certs_by_project(self, context, project_id):
"""Revoke all project certs."""
re... | super(CertManager, self).__init__(service_name='cert',
*args, **kwargs) | identifier_body |
lib.rs | // this module adds some functionality based on the required implementations
// here like: `LinkedList::pop_back` or `Clone for LinkedList<T>`
// You are free to use anything in it, but it's mainly for the test framework.
mod pre_implemented;
pub struct LinkedList<T>(std::marker::PhantomData<T>);
pub struct Cursor<'a... |
}
// the cursor is expected to act as if it is at the position of an element
// and it also has to work with and be able to insert into an empty list.
impl<T> Cursor<'_, T> {
/// Take a mutable reference to the current element
pub fn peek_mut(&mut self) -> Option<&mut T> {
unimplemented!()
}
... | {
unimplemented!()
} | identifier_body |
lib.rs | // this module adds some functionality based on the required implementations
// here like: `LinkedList::pop_back` or `Clone for LinkedList<T>`
// You are free to use anything in it, but it's mainly for the test framework.
mod pre_implemented;
pub struct LinkedList<T>(std::marker::PhantomData<T>);
pub struct Cursor<'a... | /// return a reference to the new position
pub fn prev(&mut self) -> Option<&mut T> {
unimplemented!()
}
/// Remove and return the element at the current position and move the cursor
/// to the neighboring element that's closest to the back. This can be
/// either the next or previous p... | /// Move one position backward (towards the front) and | random_line_split |
lib.rs | // this module adds some functionality based on the required implementations
// here like: `LinkedList::pop_back` or `Clone for LinkedList<T>`
// You are free to use anything in it, but it's mainly for the test framework.
mod pre_implemented;
pub struct LinkedList<T>(std::marker::PhantomData<T>);
pub struct Cursor<'a... | (&mut self) -> Cursor<'_, T> {
unimplemented!()
}
/// Return a cursor positioned on the back element
pub fn cursor_back(&mut self) -> Cursor<'_, T> {
unimplemented!()
}
/// Return an iterator that moves from front to back
pub fn iter(&self) -> Iter<'_, T> {
unimplemente... | cursor_front | identifier_name |
temporary_page.rs | //! Temporarily map a page
//! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html)
use memory::Frame;
use super::{ActivePageTable, Page, VirtualAddress};
use super::entry::EntryFlags;
use super::table::{Table, Level1};
pub struct TemporaryPage {
page: Page,
}
impl TemporaryPage {
pub fn | (page: Page) -> TemporaryPage {
TemporaryPage {
page: page,
}
}
pub fn start_address (&self) -> VirtualAddress {
self.page.start_address()
}
/// Maps the temporary page to the given frame in the active table.
/// Returns the start address of the temporary page.
... | new | identifier_name |
temporary_page.rs | //! Temporarily map a page
//! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html)
use memory::Frame;
use super::{ActivePageTable, Page, VirtualAddress};
use super::entry::EntryFlags;
use super::table::{Table, Level1};
pub struct TemporaryPage {
page: Page,
}
impl TemporaryPage {
pub fn new... |
/// Maps the temporary page to the given frame in the active table.
/// Returns the start address of the temporary page.
pub fn map(&mut self, frame: Frame, flags: EntryFlags, active_table: &mut ActivePageTable) -> VirtualAddress {
assert!(active_table.translate_page(self.page).is_none(), "tempora... | {
self.page.start_address()
} | identifier_body |
temporary_page.rs | //! Temporarily map a page
//! From [Phil Opp's Blog](http://os.phil-opp.com/remap-the-kernel.html)
use memory::Frame;
use super::{ActivePageTable, Page, VirtualAddress};
use super::entry::EntryFlags;
use super::table::{Table, Level1};
pub struct TemporaryPage {
page: Page,
}
impl TemporaryPage {
pub fn new... | }
/// Unmaps the temporary page in the active table.
pub fn unmap(&mut self, active_table: &mut ActivePageTable) {
active_table.unmap(self.page)
}
} | unsafe { &mut *(self.map(frame, flags, active_table).get() as *mut Table<Level1>) } | random_line_split |
borrow-tuple-fields.rs | // Copyright 2014 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 ... | (isize, isize);
fn main() {
let x: (Box<_>, _) = (box 1, 2);
let r = &x.0;
let y = x; //~ ERROR cannot move out of `x` because it is borrowed
let mut x = (1, 2);
let a = &x.0;
let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as
let mut x = (1, 2);
... | Bar | identifier_name |
borrow-tuple-fields.rs | // Copyright 2014 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 ... |
struct Foo(Box<isize>, isize);
struct Bar(isize, isize);
fn main() {
let x: (Box<_>, _) = (box 1, 2);
let r = &x.0;
let y = x; //~ ERROR cannot move out of `x` because it is borrowed
let mut x = (1, 2);
let a = &x.0;
let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is al... | #![feature(box_syntax)] | random_line_split |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... |
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let nbuf = CString::new(n.as_bytes())?;
unsafe {
let _guard = env_lock();
cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
}
}
pub fn temp_dir() -> PathBuf {
panic!("no filesystem on wasm")
}
pub fn home_dir() -> Option<PathBuf> {
None
... | {
let k = CString::new(k.as_bytes())?;
let v = CString::new(v.as_bytes())?;
unsafe {
let _guard = env_lock();
cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
}
} | identifier_body |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... | else {
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(libc::ERANGE) {
return Err(error);
}
}
// Trigger the internal buffer resizing logic of `Vec` by requiring
// more space than the curre... | {
let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
buf.set_len(len);
buf.shrink_to_fit();
return Ok(PathBuf::from(OsString::from_vec(buf)));
} | conditional_block |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... | }
}
pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let k = CString::new(k.as_bytes())?;
let v = CString::new(v.as_bytes())?;
unsafe {
let _guard = env_lock();
cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
}
}
pub fn unsetenv(n: &OsStr) -> io::Result<()> {
let... | if s.is_null() {
None
} else {
Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
} | random_line_split |
os.rs | #![deny(unsafe_op_in_unsafe_fn)]
use crate::any::Any;
use crate::error::Error as StdError;
use crate::ffi::{CStr, CString, OsStr, OsString};
use crate::fmt;
use crate::io;
use crate::marker::PhantomData;
use crate::os::wasi::prelude::*;
use crate::path::{self, PathBuf};
use crate::str;
use crate::sys::memchr;
use crat... | () -> io::Result<PathBuf> {
unsupported()
}
pub struct Env {
iter: vec::IntoIter<(OsString, OsString)>,
}
impl !Send for Env {}
impl !Sync for Env {}
impl Iterator for Env {
type Item = (OsString, OsString);
fn next(&mut self) -> Option<(OsString, OsString)> {
self.iter.next()
}
fn siz... | current_exe | identifier_name |
atom.rs | use joker::word::{Atom, Name};
use tristate::TriState;
pub trait AtomExt {
fn is_strict_reserved(&self) -> TriState;
fn is_illegal_strict_binding(&self) -> bool;
}
| match self {
&Name::Atom(ref atom) => atom.is_strict_reserved(),
_ => TriState::No
}
}
fn is_illegal_strict_binding(&self) -> bool {
match *self {
Name::Atom(ref atom) => atom.is_illegal_strict_binding(),
_ => false
}
}
}
impl... | impl AtomExt for Name {
fn is_strict_reserved(&self) -> TriState { | random_line_split |
atom.rs | use joker::word::{Atom, Name};
use tristate::TriState;
pub trait AtomExt {
fn is_strict_reserved(&self) -> TriState;
fn is_illegal_strict_binding(&self) -> bool;
}
impl AtomExt for Name {
fn is_strict_reserved(&self) -> TriState {
match self {
&Name::Atom(ref atom) => atom.is_strict_re... | (&self) -> bool {
match *self {
Name::Atom(ref atom) => atom.is_illegal_strict_binding(),
_ => false
}
}
}
impl AtomExt for Atom {
fn is_strict_reserved(&self) -> TriState {
match *self {
// 11.6.2.2
Atom::Await => TriState::Unknown,
... | is_illegal_strict_binding | identifier_name |
atom.rs | use joker::word::{Atom, Name};
use tristate::TriState;
pub trait AtomExt {
fn is_strict_reserved(&self) -> TriState;
fn is_illegal_strict_binding(&self) -> bool;
}
impl AtomExt for Name {
fn is_strict_reserved(&self) -> TriState {
match self {
&Name::Atom(ref atom) => atom.is_strict_re... |
// 12.1.1
fn is_illegal_strict_binding(&self) -> bool {
match *self {
Atom::Arguments
| Atom::Eval => true,
_ => false
}
}
}
| {
match *self {
// 11.6.2.2
Atom::Await => TriState::Unknown,
// 12.1.1
Atom::Implements
| Atom::Interface
| Atom::Let
| Atom::Package
| Atom::Private
| Atom::Protected
| Atom::Public
... | identifier_body |
main.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// aux-build:crate_with_invalid_spans.rs
// pretty-expanded FIXME #23616
extern crate crate_with_invalid_spans;
fn main() {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
/... | // 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 http://opensource.org/licenses/MIT>, at your | random_line_split |
main.rs | // Copyright 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-MIT or ... | () {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo() > span.hi().
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.