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 |
|---|---|---|---|---|
074_First_Bad_Version.py | #class SVNRepo:
# @classmethod
# def isBadVersion(cls, id)
# # Run unit tests to check whether verison `id` is a bad version
# # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a
# bad version.
class Solution:
"""
@param n:... | (self, n):
# write your code here
start, end = 1, n
if (n == 1):
return 1
while (start <= end):
i = (start + end) / 2
if (not SVNRepo.isBadVersion(i)):
start = i + 1
else:
end = i - 1
return start
| findFirstBadVersion | identifier_name |
074_First_Bad_Version.py | #class SVNRepo:
# @classmethod
# def isBadVersion(cls, id)
# # Run unit tests to check whether verison `id` is a bad version
# # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a
# bad version.
class Solution:
| """
@param n: An integers.
@return: An integer which is the first bad version.
"""
def findFirstBadVersion(self, n):
# write your code here
start, end = 1, n
if (n == 1):
return 1
while (start <= end):
i = (start + end) / 2
if (not SVNR... | identifier_body | |
rustoleum.rs | use std::io::{stdin, File};
use std::io::buffered::BufferedReader;
use std::str::{from_utf8};
use std::os;
| println("Usage: rustoleum [arguments] path/to/input/file");
println("-i (I)nteractive mode");
println("-wpm N Display N words per (m)inute (default: 300)");
println("-wpl N Display N words per (l)ine (default: 1)");
println("-h Display this (h)elp");
}
fn get_args_interactive () -> (uint, uint, Path) {
let mut r... | fn print_usage () {
println("A tool to keep your reading skills bright and shiny."); | random_line_split |
rustoleum.rs | use std::io::{stdin, File};
use std::io::buffered::BufferedReader;
use std::str::{from_utf8};
use std::os;
fn print_usage () {
println("A tool to keep your reading skills bright and shiny.");
println("Usage: rustoleum [arguments] path/to/input/file");
println("-i (I)nteractive mode");
println("-wpm N Display N wor... |
fn main () {
if os::args().contains(&~"-h"){
print_usage();
} else {
let (WPM, WPL, p) = get_vals(os::args());
print_file(WPM, WPL, p);
}
}
| {
if p.exists(){
let contents = File::open(&p).read_to_end();
let mut string_iter = from_utf8(contents).words();
let string_vec = string_iter.to_owned_vec();
let sleep_time = (60000 / WPM * WPL) as u64;
for words in string_vec.chunks(WPL) {
println("\x1bc".into_owned().append(words.connect(" ")));
std:... | identifier_body |
rustoleum.rs | use std::io::{stdin, File};
use std::io::buffered::BufferedReader;
use std::str::{from_utf8};
use std::os;
fn print_usage () {
println("A tool to keep your reading skills bright and shiny.");
println("Usage: rustoleum [arguments] path/to/input/file");
println("-i (I)nteractive mode");
println("-wpm N Display N wor... | (args: &~[~str], flag: &~str, default: uint) -> uint {
from_str::<uint>(args[1 + args.position_elem(flag).unwrap_or(-1)]).unwrap_or(default)
}
fn print_file(WPM: uint, WPL: uint, p: Path){
if p.exists(){
let contents = File::open(&p).read_to_end();
let mut string_iter = from_utf8(contents).words();
let string... | get_arg | identifier_name |
rustoleum.rs | use std::io::{stdin, File};
use std::io::buffered::BufferedReader;
use std::str::{from_utf8};
use std::os;
fn print_usage () {
println("A tool to keep your reading skills bright and shiny.");
println("Usage: rustoleum [arguments] path/to/input/file");
println("-i (I)nteractive mode");
println("-wpm N Display N wor... |
}
fn get_arg (args: &~[~str], flag: &~str, default: uint) -> uint {
from_str::<uint>(args[1 + args.position_elem(flag).unwrap_or(-1)]).unwrap_or(default)
}
fn print_file(WPM: uint, WPL: uint, p: Path){
if p.exists(){
let contents = File::open(&p).read_to_end();
let mut string_iter = from_utf8(contents).words()... | {
let fallbackfile = &~"data/example.txt";
let path = args.tail().last_opt().unwrap_or(fallbackfile);
let p = Path::new(path.as_slice());
let WPM = get_arg(&args, &~"-wpm", 300);
let WPL = get_arg(&args, &~"-wpl", 300);
(WPM,WPL,p)
} | conditional_block |
launcher.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011
# Drakmail < drakmail@gmail.com >
# NomerUNO < uno.kms@gmail.com >
# Platon Peacel☮ve <platonny@ngs.ru>
# Elec.Lomy.RU <Elec.Lomy.RU@gmail.com>
# ADcomp <david.madbox@gmail.com>
#
# This program is free software: you can redistribute it and/... | def stop():
while not q.empty():
q.get()
q.task_done()
q.join()
def check_programs():
programs = []
while not q.empty():
program = q.get()
if program.poll() == None:
programs.append(program)
q.task_done()
for program in programs:
q.put(pro... | obal q
q = Queue()
| identifier_body |
launcher.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011
# Drakmail < drakmail@gmail.com >
# NomerUNO < uno.kms@gmail.com >
# Platon Peacel☮ve <platonny@ngs.ru>
# Elec.Lomy.RU <Elec.Lomy.RU@gmail.com>
# ADcomp <david.madbox@gmail.com>
#
# This program is free software: you can redistribute it and/... | :
while not q.empty():
q.get()
q.task_done()
q.join()
def check_programs():
programs = []
while not q.empty():
program = q.get()
if program.poll() == None:
programs.append(program)
q.task_done()
for program in programs:
q.put(program)
... | op() | identifier_name |
launcher.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011
# Drakmail < drakmail@gmail.com >
# NomerUNO < uno.kms@gmail.com >
# Platon Peacel☮ve <platonny@ngs.ru>
# Elec.Lomy.RU <Elec.Lomy.RU@gmail.com>
# ADcomp <david.madbox@gmail.com>
#
# This program is free software: you can redistribute it and/... | program = q.get()
if program.poll() == None:
programs.append(program)
q.task_done()
for program in programs:
q.put(program)
return True
def launch_command(cmd):
try:
p = Popen(cmd, stdout = devnull, stderr = devnull )
q.put(p)
except OSError, ... | random_line_split | |
launcher.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011
# Drakmail < drakmail@gmail.com >
# NomerUNO < uno.kms@gmail.com >
# Platon Peacel☮ve <platonny@ngs.ru>
# Elec.Lomy.RU <Elec.Lomy.RU@gmail.com>
# ADcomp <david.madbox@gmail.com>
#
# This program is free software: you can redistribute it and/... | for program in programs:
q.put(program)
return True
def launch_command(cmd):
try:
p = Popen(cmd, stdout = devnull, stderr = devnull )
q.put(p)
except OSError, e:
logINFO("unable to execute a command: %s : %s" % (repr(cmd), repr(e) ))
| ogram = q.get()
if program.poll() == None:
programs.append(program)
q.task_done()
| conditional_block |
local_image_cache.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/. */
/*!
An adapter for ImageCacheTask that does local caching to avoid
extra message traffic, it also avoids waiting o... | (&self, url: &Url) {
let state = self.get_state(url);
if !state.decoded {
self.image_cache_task.send(Decode((*url).clone()));
state.decoded = true;
}
}
// FIXME: Should return a Future
pub fn get_image(&self, url: &Url) -> Port<ImageResponseMsg> {
let... | decode | identifier_name |
local_image_cache.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/. */
/*!
An adapter for ImageCacheTask that does local caching to avoid
extra message traffic, it also avoids waiting o... | }
struct ImageState {
prefetched: bool,
decoded: bool,
last_request_round: uint,
last_response: ImageResponseMsg
}
impl LocalImageCache {
/// The local cache will only do a single remote request for a given
/// URL in each 'round'. Layout should call this each time it begins
pub fn next_ro... | pub struct LocalImageCache {
priv image_cache_task: ImageCacheTask,
priv round_number: uint,
priv on_image_available: Option<~fn() -> ~fn(ImageResponseMsg)>,
priv state_map: UrlMap<@mut ImageState> | random_line_split |
table.component.spec.ts | /*
* Copyright 2019-2020 Crown Copyright
*
* 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 a... | {
get = () => {
return fullResultsData;
}
}
describe('TableComponent', () => {
let component: TableComponent;
let fixture: ComponentFixture<TableComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TableComponent],
imports: [
BrowserAnimationsModu... | ResultsServiceStub | identifier_name |
table.component.spec.ts | /*
* Copyright 2019-2020 Crown Copyright
*
* 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 a... | component.selected = ['2'];
component.refineColumns();
fixture.detectChanges();
expect(component.displayedColumns).toEqual(['2']);
});
});
it('should get the results at initialisation', () => {
const resultsService = TestBed.get(ResultsService);
const spy = spyOn(resultsService,... | component.displayedColumns = ['1', '2', '3']; | random_line_split |
transaction.js | 'use strict';
/**
* @ngdoc function
* @name argentumWebApp.service:transactionService
* @description
* # transactionService
* Service that gets Transaction info from the Api
* @requires commonService
* @author Daniel Hoyos <dhoyosm@gmail.com>
*/
angular.module('argentumWebApp') | null, {
'get': { method: 'GET' },
'query': { method: 'GET', isArray: true },
'save': { method: 'POST' }
});
};
this.composeTransaction = function() {
return $resource(commonService.getBaseURL() + "/TransactionComposers/compose",
... |
.service('transactionService', ['$resource', 'commonService', function($resource, commonService) {
this.getTransactions = function() {
return $resource(commonService.getBaseURL() + "/Accounts/:id/transactions", | random_line_split |
register.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { AlertService } from "../../services/alert.service";
import { UserService } from "../../services/user.service";
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./regi... | implements OnInit {
model: any = {};
loading = false;
constructor(
private _router: Router,
private _user: UserService,
private _alert: AlertService
) { }
ngOnInit() {
}
register() {
this.loading = true;
this._user.register(this.model)
.subscribe(
data => {
// set... | RegisterComponent | identifier_name |
register.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";
import { AlertService } from "../../services/alert.service";
import { UserService } from "../../services/user.service";
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./regi... |
} | );
} | random_line_split |
TestWeakPtrFromStdModule.py | """
Test basic std::weak_ptr functionality.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestSharedPtr(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories(["libc++"])
@skipIf(compiler=no_match("clang"))
... | self.build()
lldbutil.run_to_source_breakpoint(self,
"// Set break point at this line.", lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
self.expect("expr (int)*w.lock()", substrs=['(int) $0 = 3'])
self.expect("expr (int)(*w.lock() = ... | identifier_body | |
TestWeakPtrFromStdModule.py | """
Test basic std::weak_ptr functionality.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestSharedPtr(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories(["libc++"])
@skipIf(compiler=no_match("clang"))
... | (self):
self.build()
lldbutil.run_to_source_breakpoint(self,
"// Set break point at this line.", lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
self.expect("expr (int)*w.lock()", substrs=['(int) $0 = 3'])
self.expect("expr (i... | test | identifier_name |
TestWeakPtrFromStdModule.py | """
Test basic std::weak_ptr functionality.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestSharedPtr(TestBase):
mydir = TestBase.compute_mydir(__file__) | @skipIf(compiler=no_match("clang"))
def test(self):
self.build()
lldbutil.run_to_source_breakpoint(self,
"// Set break point at this line.", lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
self.expect("expr (int)*w.lock()", su... |
@add_test_categories(["libc++"]) | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-04 05:22
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| ('messages_new_loyalty_item', models.TextField(blank=True, null=True)),
('messages_winner', models.TextField(blank=True, null=True)),
('last_update_datetime', models.DateTimeField(blank=True, null=True)),
('claiming_method', models.CharField(blank=True, ma... | initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Policy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-04 05:22
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Policy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, seri... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-04 05:22
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
depe... | ('news_duration_date_start', models.DateTimeField(blank=True, null=True)),
('news_duration_date_end', models.DateTimeField(blank=True, null=True)),
('contests_duration_date_start', models.DateTimeField(blank=True, null=True)),
('contests_duration_date_end'... | random_line_split | |
execution.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, 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 requir... | abort(400, e.message)
return Execution.from_dict(values)
@wsme_pecan.wsexpose(None, wtypes.text, wtypes.text, status_code=204)
def delete(self, workbook_name, id):
LOG.debug("Delete execution [workbook_name=%s, id=%s]" %
(workbook_name, id))
db_api.execut... | #TODO(nmakhotkin) we should use thing such a decorator here | random_line_split |
execution.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, 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 requir... |
@wsme_pecan.wsexpose(None, wtypes.text, wtypes.text, status_code=204)
def delete(self, workbook_name, id):
LOG.debug("Delete execution [workbook_name=%s, id=%s]" %
(workbook_name, id))
db_api.execution_delete(workbook_name, id)
@wsme_pecan.wsexpose(Executions, wtypes.te... | LOG.debug("Create execution [workbook_name=%s, execution=%s]" %
(workbook_name, execution))
try:
context = None
if execution.context:
context = json.loads(execution.context)
values = engine.start_workflow_execution(execution.workbook_name,
... | identifier_body |
execution.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, 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 requir... |
setattr(e, key, val)
return e
class Executions(resource.Resource):
"""A collection of Execution resources."""
executions = [Execution]
class ExecutionsController(rest.RestController):
tasks = task.TasksController()
@wsme_pecan.wsexpose(Execution, wtypes.text, wtypes.text... | val = json.dumps(val) | conditional_block |
execution.py | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, 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 requir... | (resource.Resource):
"""Execution resource."""
id = wtypes.text
workbook_name = wtypes.text
task = wtypes.text
state = wtypes.text
# Context is a JSON object but since WSME doesn't support arbitrary
# dictionaries we have to use text type convert to json and back manually.
context = wty... | Execution | identifier_name |
mod.rs | macro_rules! os_required {
() => {
panic!("mio must be compiled with `os-poll` to run.")
};
}
mod selector;
pub(crate) use self::selector::{event, Event, Events, Selector};
mod waker;
pub(crate) use self::waker::Waker;
cfg_net! {
pub(crate) mod tcp;
pub(crate) mod udp;
#[cfg(unix)]
pu... | pub(crate) struct IoSourceState;
impl IoSourceState {
pub fn new() -> IoSourceState {
IoSourceState
}
pub fn do_io<T, F, R>(&self, f: F, io: &T) -> io::Result<R>
where
F: FnOnce(&T) -> io::Result<R>,
{
// We don't hold state, so we ca... | use crate::{Registry, Token, Interest};
| random_line_split |
tokenizer_exceptions.py | utf8
from __future__ import unicode_literals
import regex as re
from ._tokenizer_exceptions_list import FR_BASE_EXCEPTIONS
from .punctuation import ELISION, HYPHENS
from ..tokenizer_exceptions import URL_PATTERN
from ..char_classes import ALPHA_LOWER
from ...symbols import ORTH, LEMMA, TAG, NORM, PRON_LEMMA
def up... |
return text[0].upper() + text[1:]
def lower_first_letter(text):
if len(text) == 0:
return text
if len(text) == 1:
return text.lower()
return text[0].lower() + text[1:]
_exc = {
"J.-C.": [
{LEMMA: "Jésus", ORTH: "J."},
{LEMMA: "Christ", ORTH: "-C."}]
}
for exc_d... | return text.upper() | conditional_block |
tokenizer_exceptions.py | : utf8
from __future__ import unicode_literals
import regex as re
from ._tokenizer_exceptions_list import FR_BASE_EXCEPTIONS
from .punctuation import ELISION, HYPHENS
from ..tokenizer_exceptions import URL_PATTERN
from ..char_classes import ALPHA_LOWER
from ...symbols import ORTH, LEMMA, TAG, NORM, PRON_LEMMA
def u... | 'indo', 'infra', 'inter', 'intra', 'islamo', 'italo', 'jean', 'labio',
'latino', 'live', 'lot', 'louis', 'm[ai]cro', 'mesnil', 'mi(?:ni)?', 'mono',
'mont?s?', 'moyen', 'multi', 'm[ée]cano', 'm[ée]dico', 'm[ée]do', 'm[ée]ta',
'mots?', 'noix', 'non', 'nord', 'notre', 'n[ée]o', 'ouest', 'outre', 'ouvre',
... | 'co(?:de|ca)?', 'compte', 'contre', 'cordon', 'coupe?', 'court', 'crash',
'crise', 'croche', 'cross', 'cyber', 'côte', 'demi', 'di(?:sney)?',
'd[ée]s?', 'double', 'dys', 'entre', 'est', 'ethno', 'extra', 'extrême',
'[ée]co', 'fil', 'fort', 'franco?s?', 'gallo', 'gardes?', 'gastro',
'grande?', 'gratt... | random_line_split |
tokenizer_exceptions.py | utf8
from __future__ import unicode_literals
import regex as re
from ._tokenizer_exceptions_list import FR_BASE_EXCEPTIONS
from .punctuation import ELISION, HYPHENS
from ..tokenizer_exceptions import URL_PATTERN
from ..char_classes import ALPHA_LOWER
from ...symbols import ORTH, LEMMA, TAG, NORM, PRON_LEMMA
def up... | (text):
if len(text) == 0:
return text
if len(text) == 1:
return text.lower()
return text[0].lower() + text[1:]
_exc = {
"J.-C.": [
{LEMMA: "Jésus", ORTH: "J."},
{LEMMA: "Christ", ORTH: "-C."}]
}
for exc_data in [
{LEMMA: "avant", ORTH: "av."},
{LEMMA: "janvie... | lower_first_letter | identifier_name |
tokenizer_exceptions.py | : utf8
from __future__ import unicode_literals
import regex as re
from ._tokenizer_exceptions_list import FR_BASE_EXCEPTIONS
from .punctuation import ELISION, HYPHENS
from ..tokenizer_exceptions import URL_PATTERN
from ..char_classes import ALPHA_LOWER
from ...symbols import ORTH, LEMMA, TAG, NORM, PRON_LEMMA
def u... |
_exc = {
"J.-C.": [
{LEMMA: "Jésus", ORTH: "J."},
{LEMMA: "Christ", ORTH: "-C."}]
}
for exc_data in [
{LEMMA: "avant", ORTH: "av."},
{LEMMA: "janvier", ORTH: "janv."},
{LEMMA: "février", ORTH: "févr."},
{LEMMA: "avril", ORTH: "avr."},
{LEMMA: "juillet", ORTH: "juill."},
... | if len(text) == 0:
return text
if len(text) == 1:
return text.lower()
return text[0].lower() + text[1:] | identifier_body |
spatialFiltering.py | # Mustafa Hussain
# Digital Image Processing with Dr. Anas Salah Eddin
# FL Poly, Spring 2015
#
# Homework 3: Spatial Filtering
#
# USAGE NOTES:
#
# Written in Python 2.7
#
# Please ensure that the script is running as the same directory as the images
# directory!
import cv2
import copy
#import matplotlib.pyplot as p... |
def openImage(fileName):
"""Opens the image in the input directory with the filename given.
"""
return cv2.imread(INPUT_DIRECTORY + fileName + IMAGE_FILE_EXTENSION, 0)
# Input images
inputForSharpening = 'testImage1'
# Import image.
imageForSharpening = openImage(inputForSharpening)
print("Laplacian Filte... | """Saves the image in the output directory with the filename given.
"""
cv2.imwrite(OUTPUT_DIRECTORY + filename + IMAGE_FILE_EXTENSION, image) | identifier_body |
spatialFiltering.py | # Mustafa Hussain
# Digital Image Processing with Dr. Anas Salah Eddin
# FL Poly, Spring 2015
#
# Homework 3: Spatial Filtering
#
# USAGE NOTES:
#
# Written in Python 2.7
#
# Please ensure that the script is running as the same directory as the images
# directory!
import cv2
import copy
#import matplotlib.pyplot as p... | total += -1 * float(image[i - 1][j])
total += 4 * float(image[i][j])
total += -1 * float(image[i + 1][j])
total += -1 * float(image[i][j - 1])
filteredImage[i][j] = total / 9.0
filteredImage = (filteredImage / numpy.max(filteredImage)) * MAX_INTENSITY
return filteredImage
de... | # Mask from homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm
total = 0.0
total += -1 * float(image[i][j + 1]) | random_line_split |
spatialFiltering.py | # Mustafa Hussain
# Digital Image Processing with Dr. Anas Salah Eddin
# FL Poly, Spring 2015
#
# Homework 3: Spatial Filtering
#
# USAGE NOTES:
#
# Written in Python 2.7
#
# Please ensure that the script is running as the same directory as the images
# directory!
import cv2
import copy
#import matplotlib.pyplot as p... |
filteredImage = (filteredImage / numpy.max(filteredImage)) * MAX_INTENSITY
return filteredImage
def saveImage(image, filename):
"""Saves the image in the output directory with the filename given.
"""
cv2.imwrite(OUTPUT_DIRECTORY + filename + IMAGE_FILE_EXTENSION, image)
def openImage(fileName):
"""Ope... | for j in range(height - 1):
# Mask from homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm
total = 0.0
total += -1 * float(image[i][j + 1])
total += -1 * float(image[i - 1][j])
total += 4 * float(image[i][j])
total += -1 * float(image[i + 1][j])
total += -1 * float(image[i][j - 1... | conditional_block |
spatialFiltering.py | # Mustafa Hussain
# Digital Image Processing with Dr. Anas Salah Eddin
# FL Poly, Spring 2015
#
# Homework 3: Spatial Filtering
#
# USAGE NOTES:
#
# Written in Python 2.7
#
# Please ensure that the script is running as the same directory as the images
# directory!
import cv2
import copy
#import matplotlib.pyplot as p... | (image):
"""Approximates the second derivative, bringing out edges.
Referencing below zero wraps around, so top and left sides will be sharpened.
We are not bothering with the right and bottom edges, because referencing
above the image size results in a boundary error.
"""
width, height = image.shape... | laplacianFilter | identifier_name |
utils.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::mem;
use std::sync::Arc;
use super::error::*;
use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState};
use crate::utils::Async... |
});
*state = XhciTransferState::Submitted { cancel_callback };
return Ok(());
}
}
}
XhciTransferState::Cancelled => {
warn!("Transfer is already cancelled");
... | {
usb_debug!("fail to cancel: {}", e);
} | conditional_block |
utils.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::mem;
use std::sync::Arc;
use super::error::*;
use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState};
use crate::utils::Async... | }
}
Ok(())
}
/// Helper function to submit usb_transfer to device handle.
pub fn submit_transfer(
fail_handle: Arc<dyn FailHandle>,
job_queue: &Arc<AsyncJobQueue>,
xhci_transfer: Arc<XhciTransfer>,
device: &mut Device,
usb_transfer: Transfer,
) -> Result<()> {
let transfer_stat... | {
let status = usb_transfer.status();
let mut state = xhci_transfer.state().lock();
if status == TransferStatus::Cancelled {
*state = XhciTransferState::Cancelled;
return Ok(());
}
match *state {
XhciTransferState::Cancelling => {
*state = XhciTransferState::Can... | identifier_body |
utils.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::mem;
use std::sync::Arc;
use super::error::*;
use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState};
use crate::utils::Async... | (
fail_handle: Arc<dyn FailHandle>,
job_queue: &Arc<AsyncJobQueue>,
xhci_transfer: Arc<XhciTransfer>,
device: &mut Device,
usb_transfer: Transfer,
) -> Result<()> {
let transfer_status = {
// We need to hold the lock to avoid race condition.
// While we are trying to submit the t... | submit_transfer | identifier_name |
utils.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::mem;
use std::sync::Arc;
use super::error::*;
use crate::usb::xhci::xhci_transfer::{XhciTransfer, XhciTransferState};
use crate::utils::Async... | // trying to cancel it.
// Completed: A completed transfer should not be submitted again.
error!("xhci trasfer state is invalid");
return Err(Error::BadXhciTransferState);
}
}
};
// We are holding locks to of backends, we want t... | }
_ => {
// The transfer could not be in the following states:
// Submitted: A transfer should only be submitted once.
// Cancelling: Transfer is cancelling only when it's submitted and someone is | random_line_split |
hamtask.py | # -*- coding: utf-8 -*-
from ..provider.g5k import G5K
from constants import SYMLINK_NAME
from functools import wraps
import os
import yaml
import logging
def load_env():
env = {
'config' : {}, # The config
'resultdir': '', # Path to the result directory
'config_file' : '', # The i... | (fn):
fn.__doc__ = doc
@wraps(fn)
def decorated(*args, **kwargs):
# TODO: Dynamically loads the provider
if kwargs.has_key('--provider'):
provider_name = kwargs['--provider']
kwargs['provider'] = G5K()
# Loads the environment &... | decorator | identifier_name |
hamtask.py | # -*- coding: utf-8 -*-
from ..provider.g5k import G5K
from constants import SYMLINK_NAME
from functools import wraps
import os
import yaml
import logging
def load_env():
env = {
'config' : {}, # The config
'resultdir': '', # Path to the result directory
'config_file' : '', # The i... |
# Loads the environment & set the config
env = load_env()
kwargs['env'] = env
# Proceeds with the function executio
fn(*args, **kwargs)
# Save the environment
save_env(env)
return decorated
return decorator
| provider_name = kwargs['--provider']
kwargs['provider'] = G5K() | conditional_block |
hamtask.py | # -*- coding: utf-8 -*-
from ..provider.g5k import G5K
from constants import SYMLINK_NAME
from functools import wraps
import os
import yaml
import logging
def load_env():
env = {
'config' : {}, # The config
'resultdir': '', # Path to the result directory
'config_file' : '', # The i... | logging.debug("Reloaded config %s", env['config'])
return env
def save_env(env):
env_path = os.path.join(env['resultdir'], 'env')
if os.path.isdir(env['resultdir']):
with open(env_path, 'w') as f:
yaml.dump(env, f)
def hamtask(doc):
"""Decorator for a Ham Task."""
... | with open(env['config_file'], 'r') as f:
env['config'].update(yaml.load(f)) | random_line_split |
hamtask.py | # -*- coding: utf-8 -*-
from ..provider.g5k import G5K
from constants import SYMLINK_NAME
from functools import wraps
import os
import yaml
import logging
def load_env():
| with open(env['config_file'], 'r') as f:
env['config'].update(yaml.load(f))
logging.debug("Reloaded config %s", env['config'])
return env
def save_env(env):
env_path = os.path.join(env['resultdir'], 'env')
if os.path.isdir(env['resultdir']):
with open(env_path, 'w... | env = {
'config' : {}, # The config
'resultdir': '', # Path to the result directory
'config_file' : '', # The initial config file
'nodes' : {}, # Roles with nodes
'phase' : '', # Last phase that have been run
'user' : '', # User id for this job
... | identifier_body |
open_dataset.ts | import {Statement} from "./_statement";
import {verNot, str, seq, alt, per, opt, IStatementRunnable} from "../combi";
import {Target, Source} from "../expressions";
import {Version} from "../../version";
export class OpenDataset extends Statement {
public | (): IStatementRunnable {
const mode = seq(str("IN"),
opt(str("LEGACY")),
alt(str("BINARY MODE"),
str("TEXT MODE")));
const code = seq(str("CODE PAGE"), new Source());
const direction = seq(str("FOR"), alt(str("OUTPUT"), str("INPUT"), str("... | getMatcher | identifier_name |
open_dataset.ts | import {Statement} from "./_statement";
import {verNot, str, seq, alt, per, opt, IStatementRunnable} from "../combi";
import {Target, Source} from "../expressions";
import {Version} from "../../version";
export class OpenDataset extends Statement {
public getMatcher(): IStatementRunnable {
const mode = seq(str(... | }
} | per(direction, type, mode, wbom, replacement, encoding, pos, message, ignoring, bom, code, feed, windows));
return verNot(Version.Cloud, ret); | random_line_split |
xcore.rs | //! Contains xcore-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
// XXX todo(tmfink): create rusty versions
pub use capstone_sys::xcore_insn_group as XcoreInsnGroup;
pub use capstone_sys::xcore_insn as XcoreInsn;
pub use capstone_sys::xcore_reg as XcoreReg;
use capstone_sys::{cs_xcore, cs_xcore... |
/// Index register
pub fn index(&self) -> RegId {
RegId(RegIdInt::from(self.0.index))
}
/// Disp value
pub fn disp(&self) -> i32 {
self.0.disp
}
/// Direct value
pub fn direct(&self) -> i32 {
self.0.direct
}
}
impl_PartialEq_repr_fields!(XcoreOpMem;
b... | {
RegId(RegIdInt::from(self.0.base))
} | identifier_body |
xcore.rs | //! Contains xcore-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
// XXX todo(tmfink): create rusty versions
pub use capstone_sys::xcore_insn_group as XcoreInsnGroup;
pub use capstone_sys::xcore_insn as XcoreInsn;
pub use capstone_sys::xcore_reg as XcoreReg;
use capstone_sys::{cs_xcore, cs_xcore... | /// Invalid
Invalid,
}
impl Default for XcoreOperand {
fn default() -> Self {
XcoreOperand::Invalid
}
}
/// XCORE memory operand
#[derive(Debug, Copy, Clone)]
pub struct XcoreOpMem(pub(crate) xcore_op_mem);
impl XcoreOpMem {
/// Base register
pub fn base(&self) -> RegId {
RegI... | random_line_split | |
xcore.rs | //! Contains xcore-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
// XXX todo(tmfink): create rusty versions
pub use capstone_sys::xcore_insn_group as XcoreInsnGroup;
pub use capstone_sys::xcore_insn as XcoreInsn;
pub use capstone_sys::xcore_reg as XcoreReg;
use capstone_sys::{cs_xcore, cs_xcore... | (pub(crate) xcore_op_mem);
impl XcoreOpMem {
/// Base register
pub fn base(&self) -> RegId {
RegId(RegIdInt::from(self.0.base))
}
/// Index register
pub fn index(&self) -> RegId {
RegId(RegIdInt::from(self.0.index))
}
/// Disp value
pub fn disp(&self) -> i32 {
... | XcoreOpMem | identifier_name |
deriving-via-extension-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
x: isize,
y: isize,
z: isize,
}
pub fn main() {
let a = Foo { x: 1, y: 2, z: 3 };
let b = Foo { x: 1, y: 2, z: 3 };
assert_eq!(a, b);
assert!(!(a != b));
assert!(a.eq(&b));
assert!(!a.ne(&b));
}
| Foo | identifier_name |
deriving-via-extension-struct.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!(a, b);
assert!(!(a != b));
assert!(a.eq(&b));
assert!(!a.ne(&b));
} |
pub fn main() {
let a = Foo { x: 1, y: 2, z: 3 };
let b = Foo { x: 1, y: 2, z: 3 }; | random_line_split |
About_author.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui,QtCore
from Ui_about_author import Ui_About
_IME = "<p>Author: Bojan Ili""ć</p>"
_FAKULTET = "Faculty of Electrical Engineering, University of Belgrade - ETF"
_MAIL = "https.rs@gmail.com"
_URL = "<a href = ""https://www.... | self.ui=Ui_About()
self.ui.setupUi(self)
self.ui.lblVersion.setText("{}".format(_IME))
self.ui.lblVersion2.setText("{}".format(_FAKULTET))
self.ui.lblVersion3.setText("E-mail: {}".format(_MAIL))
self.ui.lblURL.setText(_URL)
#-----------------------------------------... |
def setupUI(self):
#create window from ui
| random_line_split |
About_author.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui,QtCore
from Ui_about_author import Ui_About
_IME = "<p>Author: Bojan Ili""ć</p>"
_FAKULTET = "Faculty of Electrical Engineering, University of Belgrade - ETF"
_MAIL = "https.rs@gmail.com"
_URL = "<a href = ""https://www.... |
if __name__ == "__main__":
main()
| app = QtGui.QApplication(sys.argv)
form = AboutWindow2()
form.show()
sys.exit(app.exec_()) | identifier_body |
About_author.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui,QtCore
from Ui_about_author import Ui_About
_IME = "<p>Author: Bojan Ili""ć</p>"
_FAKULTET = "Faculty of Electrical Engineering, University of Belgrade - ETF"
_MAIL = "https.rs@gmail.com"
_URL = "<a href = ""https://www.... | ():
app = QtGui.QApplication(sys.argv)
form = AboutWindow2()
form.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
| main | identifier_name |
About_author.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui,QtCore
from Ui_about_author import Ui_About
_IME = "<p>Author: Bojan Ili""ć</p>"
_FAKULTET = "Faculty of Electrical Engineering, University of Belgrade - ETF"
_MAIL = "https.rs@gmail.com"
_URL = "<a href = ""https://www.... | main() | conditional_block | |
cog_selector.py | with ETE. If not, see <http://www.gnu.org/licenses/>.
#
#
# ABOUT THE ETE PACKAGE
# =====================
#
# ETE is distributed under the GPL copyleft license (2008-2015).
#
# If you make use of ETE in published work, please cite:
#
# Jaime Huerta-Cepas, Joaquin Dopazo and... |
else:
return r
def sort_cogs_by_sp_repr(c1, c2):
c1_repr = _min([sp2cogs[_sp] for _sp, _seq in c1])
c2_repr = _min([sp2cogs[_sp] for _sp, _seq in c2])
r = cmp(c1_repr, c2_repr)
if r == 0:
r = -1 * cmp(len(c1), len(c2))... | c1_repr = _min([sp2cogs[_sp] for _sp, _seq in c1])
c2_repr = _min([sp2cogs[_sp] for _sp, _seq in c2])
r = cmp(c1_repr, c2_repr)
if r == 0:
return cmp(sorted(c1), sorted(c2))
else:
return r | conditional_block |
cog_selector.py | with ETE. If not, see <http://www.gnu.org/licenses/>.
#
#
# ABOUT THE ETE PACKAGE
# =====================
#
# ETE is distributed under the GPL copyleft license (2008-2015).
#
# If you make use of ETE in published work, please cite:
#
# Jaime Huerta-Cepas, Joaquin Dopazo and... |
def sort_cogs_by_sp_repr(c1, c2):
c1_repr = _min([sp2cogs[_sp] for _sp, _seq in c1])
c2_repr = _min([sp2cogs[_sp] for _sp, _seq in c2])
r = cmp(c1_repr, c2_repr)
if r == 0:
r = -1 * cmp(len(c1), len(c2))
if r == 0:
... | '''
sort cogs by descending size. If two cogs are the same size, sort
them keeping first the one with the less represented
species. Otherwise sort by sequence name sp_seqid.'''
r = -1 * cmp(len(c1), len(c2))
if r == 0:
# finds the ... | identifier_body |
cog_selector.py | with ETE. If not, see <http://www.gnu.org/licenses/>.
#
#
# ABOUT THE ETE PACKAGE
# =====================
#
# ETE is distributed under the GPL copyleft license (2008-2015).
#
# If you make use of ETE in published work, please cite:
#
# Jaime Huerta-Cepas, Joaquin Dopazo and... | else:
return r
else:
return r
def sort_cogs_by_sp_repr(c1, c2):
c1_repr = _min([sp2cogs[_sp] for _sp, _seq in c1])
c2_repr = _min([sp2cogs[_sp] for _sp, _seq in c2])
r = cmp(c1_repr, c2_repr)
if r ==... | r = cmp(c1_repr, c2_repr)
if r == 0:
return cmp(sorted(c1), sorted(c2)) | random_line_split |
cog_selector.py | ETE. If not, see <http://www.gnu.org/licenses/>.
#
#
# ABOUT THE ETE PACKAGE
# =====================
#
# ETE is distributed under the GPL copyleft license (2008-2015).
#
# If you make use of ETE in published work, please cite:
#
# Jaime Huerta-Cepas, Joaquin Dopazo and Toni... | (c1, c2):
c1_repr = _min([sp2cogs[_sp] for _sp, _seq in c1])
c2_repr = _min([sp2cogs[_sp] for _sp, _seq in c2])
r = cmp(c1_repr, c2_repr)
if r == 0:
r = -1 * cmp(len(c1), len(c2))
if r == 0:
return cmp(sorted(c1), sorted... | sort_cogs_by_sp_repr | identifier_name |
dynamic_lib.rs | (&mut self) {
match dl::check_for_errors_in(|| {
unsafe {
dl::close(self.handle)
}
}) {
Ok(()) => {},
Err(str) => panic!("{}", str)
}
}
}
impl DynamicLibrary {
// FIXME (#12938): Until DST lands, we cannot decompose &str in... | drop | identifier_name | |
dynamic_lib.rs | lib search path.
pub fn create_path(path: &[PathBuf]) -> OsString {
let mut newvar = OsString::new();
for (i, path) in path.iter().enumerate() {
if i > 0 { newvar.push(DynamicLibrary::separator()); }
newvar.push(path);
}
return newvar;
}
/// Returns t... | unsafe {
if use_thread_mode {
SetThreadErrorMode(prev_error_mode, ptr::null_mut());
} else {
SetErrorMode(prev_error_mode); | random_line_split | |
dynamic_lib.rs | ::create_path(&search_path));
}
/// From a slice of paths, create a new vector which is suitable to be an
/// environment variable for this platforms dylib search path.
pub fn create_path(path: &[PathBuf]) -> OsString {
let mut newvar = OsString::new();
for (i, path) in path.iter().enum... | {
let mut handle = ptr::null_mut();
let succeeded = unsafe {
GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle)
};
if succeeded == libc::FALSE {
let errno = os::errno();
Err(os::error_... | conditional_block | |
code-tabs.component.spec.ts | import { Component, ViewChild, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Logger } from 'app/shared/logger.service';
import { MockLogger } from 'testing/logger.service';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';... | const matTabs = fixture.nativeElement.querySelectorAll('.mat-tab-label');
expect(matTabs.length).toBe(2);
expect(matTabs[0].textContent.trim()).toBe('header-A');
expect(matTabs[0].querySelector('.class-A')).toBeTruthy();
expect(matTabs[1].textContent.trim()).toBe('header-B');
expect(matTabs[1]... | random_line_split | |
code-tabs.component.spec.ts | import { Component, ViewChild, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Logger } from 'app/shared/logger.service';
import { MockLogger } from 'testing/logger.service';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';... | {
@ViewChild(CodeTabsComponent) codeTabsComponent: CodeTabsComponent;
}
| HostComponent | identifier_name |
multiset.rs | a [Segment],
a_i: usize,
b_i: usize,
a_consumed: usize,
b_consumed: usize,
pub consumed: usize,
}
/// See `Subset::zip`
#[derive(Clone, Debug)]
pub struct ZipSegment {
len: usize,
a_count: usize,
b_count: usize,
}
impl<'a> Iterator for ZipIter<'a> {
type Item = ZipSegment;
///... | transform | identifier_name | |
multiset.rs | <N: NodeInfo>(&self, s: &Node<N>) -> Node<N> {
let mut b = TreeBuilder::new();
for (beg, end) in self.range_iter(CountMatcher::Zero) {
s.push_subseq(&mut b, Interval::new(beg, end));
}
b.build()
}
/// The length of the resulting sequence after deleting this subset. A... |
/// Count the total length of all the segments matching `matcher`.
pub fn count(&self, matcher: CountMatcher) -> usize {
self.segments.iter().filter(|seg| matcher.matches(seg)).map(|seg| seg.len).sum()
}
/// Convenience alias for `self.count(CountMatcher::All)`
pub fn len(&self) -> usize ... | {
self.count(CountMatcher::Zero)
} | identifier_body |
multiset.rs | <N: NodeInfo>(&self, s: &Node<N>) -> Node<N> {
let mut b = TreeBuilder::new();
for (beg, end) in self.range_iter(CountMatcher::Zero) {
s.push_subseq(&mut b, Interval::new(beg, end));
}
b.build()
}
/// The length of the resulting sequence after deleting this subset. A... |
// consume as much of the segment as possible and necessary
let to_consume = cmp::min(cur_seg.len, to_be_consumed);
sb.push_segment(to_consume, cur_seg.count);
to_be_consumed -= to_consume;
cur_seg.len -= to_consume;
... | {
cur_seg = seg_iter
.next()
.expect("self must cover all 0-regions of other")
.clone();
} | conditional_block |
multiset.rs | self.segments.push(Segment { len, count });
}
pub fn build(self) -> Subset {
Subset { segments: self.segments }
}
}
/// Determines which elements of a `Subset` a method applies to
/// based on the count of the element.
#[derive(Clone, Copy, Debug)]
pub enum CountMatcher {
Zero,
Non... | random_line_split | ||
AppDescriptorCommand.qunit.js | /* global QUnit */
sap.ui.define([
"sap/ui/fl/Layer",
"sap/ui/fl/write/_internal/appVariant/AppVariantInlineChangeFactory",
"sap/ui/fl/descriptorRelated/api/DescriptorChangeFactory",
"sap/ui/rta/command/CommandFactory",
"sap/m/Button",
"sap/ui/base/ManagedObject",
"sap/ui/thirdparty/sinon-4",
"test-resources/s... | assert.equal(mPropertyBag.content, this.mParameters, "parameters are properly passed to the 'createDescriptorInlineChange' function");
assert.equal(mPropertyBag.texts, this.mTexts, "texts are properly passed to the 'createDescriptorInlineChange' function");
this.createDescriptorInlineChangeStub.restore();
... | assert.equal(mPropertyBag.changeType, this.sChangeType, "change type is properly passed to the 'createDescriptorInlineChange' function"); | random_line_split |
renderer.js | //This file just deals with drawing things.
//It is probably cludgy as, don't look in here for good coding advice! :)s
var stage;
var gfxResources = {};
function init() {
stage = new createjs.Stage('canvas');
createjs.DisplayObject.suppressCrossDomainErrors = true;
loadingComplete();
}
function createCenteredBit... | stage.addChild(targetShape);
obstaclesShape = new createjs.Shape();
obstaclesShape.graphics.beginFill('#f00');
for (var i = 0; i < obstacles.length; i++) {
var o = obstacles[i];
obstaclesShape.graphics.rect(o.x * gridPx, o.y * gridPx, gridPx, gridPx);
}
stage.addChild(obstaclesShape);
weightsAndFieldShape ... | random_line_split | |
renderer.js | //This file just deals with drawing things.
//It is probably cludgy as, don't look in here for good coding advice! :)s
var stage;
var gfxResources = {};
function init() {
stage = new createjs.Stage('canvas');
createjs.DisplayObject.suppressCrossDomainErrors = true;
loadingComplete();
}
function createCenteredBit... | () {
weightsAndFieldShape.removeAllChildren();
//Draw the weights
for (x = 0; x < gridWidth; x++) {
for (y = 0; y < gridHeight; y++) {
var d = dijkstraGrid[x][y];
if (d == 0 || d === Number.MAX_VALUE) {
continue;
}
var text = new createjs.Text('' + d, '16px Arial', '#000');
text.x = (x + 0.5) *... | updateWeightsAndFieldVisuals | identifier_name |
renderer.js | //This file just deals with drawing things.
//It is probably cludgy as, don't look in here for good coding advice! :)s
var stage;
var gfxResources = {};
function init() {
stage = new createjs.Stage('canvas');
createjs.DisplayObject.suppressCrossDomainErrors = true;
loadingComplete();
}
function createCenteredBit... |
function rendererTick() {
targetShape.x = (destination.x + 0.5) * gridPx;
targetShape.y = (destination.y + 0.5) * gridPx;
//Create new enemy bitmaps as required
//Update enemy positions
//Mark bitmaps as alive
for (var i = 0; i < agents.length; i++) {
var e = agents[i];
if (!e._id) {
e._id = (agentId++)... | {
var shape = new createjs.Shape();
shape.graphics.beginStroke('#000');
shape.graphics.drawCircle(0, 0, agent.radius * gridPx);
shape.graphics.moveTo(0, 0);
shape.graphics.lineTo(0, -agent.radius * gridPx);
return shape;
} | identifier_body |
renderer.js | //This file just deals with drawing things.
//It is probably cludgy as, don't look in here for good coding advice! :)s
var stage;
var gfxResources = {};
function init() {
stage = new createjs.Stage('canvas');
createjs.DisplayObject.suppressCrossDomainErrors = true;
loadingComplete();
}
function createCenteredBit... |
var bitmap = agentBitmaps[e._id];
var forceLine = agentForceLines[e._id];
if (!bitmap) {
bitmap = agentBitmaps[e._id] = createAgentShape(e);
forceLine = agentForceLines[e._id] = new createjs.Shape();
stage.addChild(bitmap);
stage.addChild(forceLine);
}
bitmap.x = gridPx * (e.position().x + 0.5... | {
e._id = (agentId++);
} | conditional_block |
run_electrum_creditbit_server.py | import logging
import socket
import sys
import time
import threading
import json
import os
import imp
if os.path.dirname(os.path.realpath(__file__)) == os.getcwd():
imp.load_module('electrumcreditbitserver', *imp.find_module('src'))
from electrumcreditbitserver import storage, networks, utils
from electrumcredit... |
def cmd_debug(s):
import traceback
from guppy import hpy;
hp = hpy()
if s:
try:
result = str(eval(s))
except:
err_lines = traceback.format_exc().splitlines()
result = '%s | %s' % (err_lines[-3], err_lines[-1])
return result
def get_port(co... | return len(server_proc.peers) | identifier_body |
run_electrum_creditbit_server.py | import logging
import socket
import sys
import time
import threading
import json
import os
import imp
if os.path.dirname(os.path.realpath(__file__)) == os.getcwd():
imp.load_module('electrumcreditbitserver', *imp.find_module('src'))
from electrumcreditbitserver import storage, networks, utils
from electrumcredit... | (config, filename):
try:
with open(filename, 'r') as f:
config.readfp(f)
except IOError:
pass
def load_banner(config):
try:
with open(config.get('server', 'banner_file'), 'r') as f:
config.set('server', 'banner', f.read())
except IOError:
pass
de... | attempt_read_config | identifier_name |
run_electrum_creditbit_server.py | import logging
import socket
import sys
import time
import threading
import json
import os
import imp
if os.path.dirname(os.path.realpath(__file__)) == os.getcwd():
imp.load_module('electrumcreditbitserver', *imp.find_module('src'))
from electrumcreditbitserver import storage, networks, utils
from electrumcredit... | if sys.maxsize <= 2**32:
print "Warning: it looks like you are using a 32bit system. You may experience crashes caused by mmap"
if os.getuid() == 0:
print "Do not run this program as root!"
print "Run the install script to create a non-privileged user."
sys.exit()
def attempt_read_config(config, filen... | random_line_split | |
run_electrum_creditbit_server.py | import logging
import socket
import sys
import time
import threading
import json
import os
import imp
if os.path.dirname(os.path.realpath(__file__)) == os.getcwd():
imp.load_module('electrumcreditbitserver', *imp.find_module('src'))
from electrumcreditbitserver import storage, networks, utils
from electrumcredit... |
def cmd_banner_update():
load_banner(dispatcher.shared.config)
return True
def cmd_getinfo():
return {
'blocks': chain_proc.storage.height,
'peers': len(server_proc.peers),
'sessions': len(dispatcher.request_dispatcher.get_sessions()),
'watched': len(chain_proc.watched_ad... | print json.dumps(r, indent=4, sort_keys=True) | conditional_block |
confdel.py | # This file is part of Booktype.
# Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>
#
# Booktype 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 Li... | if not settings.BOOKTYPE_CONFIG.has_key(options['<key>'][0]):
raise CommandError("There is no such variable.")
del settings.BOOKTYPE_CONFIG[options['<key>'][0]]
config.save_configuration() | random_line_split | |
confdel.py | # This file is part of Booktype.
# Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>
#
# Booktype 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 Li... |
def handle(self, *args, **options):
if not hasattr(settings, 'BOOKTYPE_CONFIG'):
raise CommandError('Does not have BOOKTYPE_CONFIG in settings.py file.')
if not options['<key>'][0]:
raise CommandError("You must specify variable name")
if not settings.BOOKTYPE_CONF... | parser.add_argument("<key>", nargs=1, type=str) | identifier_body |
confdel.py | # This file is part of Booktype.
# Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>
#
# Booktype 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 Li... | (self, parser):
parser.add_argument("<key>", nargs=1, type=str)
def handle(self, *args, **options):
if not hasattr(settings, 'BOOKTYPE_CONFIG'):
raise CommandError('Does not have BOOKTYPE_CONFIG in settings.py file.')
if not options['<key>'][0]:
raise CommandError("... | add_arguments | identifier_name |
confdel.py | # This file is part of Booktype.
# Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>
#
# Booktype 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 Li... |
del settings.BOOKTYPE_CONFIG[options['<key>'][0]]
config.save_configuration()
| raise CommandError("There is no such variable.") | conditional_block |
test_map_reduce.rs | use std::thread;
fn main () | result
}));
}
//Reduce
let mut intermediate_sums = vec![];
for child in children {
let intermediate_sum = child.join().unwrap();
intermediate_sums.push(intermediate_sum);
}
let final_result = intermediate_sums.iter().sum::<u32>();
println!("Fin... | {
let data = "86967897737416471853297327050364959
11861322575564723963297542624962850
70856234701860851907960690014725639
38397966707106094172783238747669219
52380795257888236525459303330302837
58495327135744041048897885734297812
69920216438980873548808413720956532
16278424637452... | identifier_body |
test_map_reduce.rs | use std::thread;
fn | () {
let data = "86967897737416471853297327050364959
11861322575564723963297542624962850
70856234701860851907960690014725639
38397966707106094172783238747669219
52380795257888236525459303330302837
58495327135744041048897885734297812
69920216438980873548808413720956532
1627842463... | main | identifier_name |
test_map_reduce.rs | use std::thread;
fn main () {
let data = "86967897737416471853297327050364959
11861322575564723963297542624962850
70856234701860851907960690014725639
38397966707106094172783238747669219
52380795257888236525459303330302837
58495327135744041048897885734297812
69920216438980873548808413... | intermediate_sums.push(intermediate_sum);
}
let final_result = intermediate_sums.iter().sum::<u32>();
println!("Final sum result: {}", final_result);
} | //Reduce
let mut intermediate_sums = vec![];
for child in children {
let intermediate_sum = child.join().unwrap(); | random_line_split |
actionpicker.ts | /// <reference path="../jquery.d.ts" />
/// <reference path="../model/actiondb.ts" />
/// <reference path="../model/action.ts" />
/// <reference path="../util/util.ts" />
/// <reference path="picker.ts" />
class ActionPicker extends ObservableObject{
classPicker:Picker;
subjectPicker:Picker;
repetitionPick... |
this.notify('actionUnselected');
}
} | {
this.repetitionPicker.selectNone();
this.repetitionPicker.showElements([]);
this.notify('invalidFilter');
} | conditional_block |
actionpicker.ts | /// <reference path="../jquery.d.ts" />
/// <reference path="../model/actiondb.ts" />
/// <reference path="../model/action.ts" />
/// <reference path="../util/util.ts" />
/// <reference path="picker.ts" />
class ActionPicker extends ObservableObject{
classPicker:Picker;
subjectPicker:Picker;
repetitionPick... | (actionDB:ActionDB){
super();
this.actionDB=actionDB;
this.classPicker=new Picker( $('#classPicker'),false) ;
this.classPicker.setNumbersAsElements(actionDB.classCount());
this.classPicker.setTooltips(KinectDatabase.classNames());
this.classPicker.setColors( KinectDatabas... | constructor | identifier_name |
actionpicker.ts | /// <reference path="../jquery.d.ts" />
/// <reference path="../model/actiondb.ts" />
/// <reference path="../model/action.ts" />
/// <reference path="../util/util.ts" />
/// <reference path="picker.ts" />
class ActionPicker extends ObservableObject{
classPicker:Picker;
subjectPicker:Picker;
repetitionPick... | this.repetitionPicker.setColors(colors);
this.repetitionPicker.selectNone();
this.notify('filterChanged');
}else{
this.repetitionPicker.selectNone();
this.repetitionPicker.showElements([]);
this.notify('invalidFilter');
}
th... | var classColors:string[]=KinectDatabase.classColors();
var colors = actionIdentifiers.map( id => {return classColors[id.type-1 ]; debugger;}) | random_line_split |
actionpicker.ts | /// <reference path="../jquery.d.ts" />
/// <reference path="../model/actiondb.ts" />
/// <reference path="../model/action.ts" />
/// <reference path="../util/util.ts" />
/// <reference path="picker.ts" />
class ActionPicker extends ObservableObject{
classPicker:Picker;
subjectPicker:Picker;
repetitionPick... |
filterRepetitions():void{
var classes:number[]=this.classPicker.selectedElements();
var subjects:number[]=this.subjectPicker.selectedElements();
if ( classes.length>0 && subjects.length>0){
//var indices:number[]= this.indicesOfActionsFor(classes,subjects);
var actio... | {
var selected:number[]=this.repetitionPicker.selectedIndices();
if (selected.length>0){
var li:JQuery= $(this.repetitionPicker.getElements()[selected[0]]);
this.repetitionPicker.list.scrollTop(li.position().top);
}
} | identifier_body |
callee.rs | _ty_param(*) |
ast::def_self_ty(*) => {
bcx.tcx().sess.span_bug(
ref_expr.span,
fmt!("Cannot translate def %? \
to a callable thing!", def));
}
}
}
}
pub fn trans_fn_ref_to_callee(bcx: block,
... | ~"method call expr wasn't in \
method map")
}
}
},
args,
dest,
DontAutorefArg)
}
pub fn trans_lang_call(bcx: block,
did: ast::def_id,
... | {
let _icx = in_cx.insn_ctxt("trans_method_call");
trans_call_inner(
in_cx,
call_ex.info(),
node_id_type(in_cx, call_ex.callee_id),
expr_ty(in_cx, call_ex),
|cx| {
match cx.ccx().maps.method_map.find(&call_ex.id) {
Some(origin) => {
... | identifier_body |
callee.rs | &fn(block) -> Callee,
args: CallArgs,
dest: expr::Dest,
autoref_arg: AutorefArg) -> block {
do base::with_scope(in_cx, call_info, ~"call") |cx| {
let ret_in_loop = match args {
ArgExprs(args) => {
args.len() > 0u && match vec::last(args).node {
ast::expr_loop... | random_line_split | ||
callee.rs | _ty_param(*) |
ast::def_self_ty(*) => {
bcx.tcx().sess.span_bug(
ref_expr.span,
fmt!("Cannot translate def %? \
to a callable thing!", def));
}
}
}
}
pub fn trans_fn_ref_to_callee(bcx: block,
... | (in_cx: block,
call_ex: @ast::expr,
rcvr: @ast::expr,
args: CallArgs,
dest: expr::Dest)
-> block {
let _icx = in_cx.insn_ctxt("trans_method_call");
trans_call_inner(
in_cx,
c... | trans_method_call | identifier_name |
test_bigip_vcmp_guest.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
i... |
def test_module_parameters_mgmt_bridged_without_subnet(self):
args = dict(
mgmt_network='bridged',
mgmt_address='1.2.3.4'
)
p = Parameters(params=args)
assert p.mgmt_network == 'bridged'
assert p.mgmt_address == '1.2.3.4/32'
def test_module_par... | args = dict(
initial_image='BIGIP-12.1.0.1.0.1447-HF1.iso',
mgmt_network='bridged',
mgmt_address='1.2.3.4/24',
vlans=[
'vlan1',
'vlan2'
]
)
p = Parameters(params=args)
assert p.initial_image == 'BIGIP-12... | identifier_body |
test_bigip_vcmp_guest.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
i... | (self):
self.spec = ArgumentSpec()
self.patcher1 = patch('time.sleep')
self.patcher1.start()
def tearDown(self):
self.patcher1.stop()
def test_create_vlan(self, *args):
set_module_args(dict(
name="guest1",
mgmt_network="bridged",
mgmt... | setUp | identifier_name |
test_bigip_vcmp_guest.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
i... |
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
initial_image='BIGIP-12.1.0.1.0.1447-HF1.iso',
mgmt_network='bridged',... | random_line_split | |
test_bigip_vcmp_guest.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
i... |
with open(path) as f:
data = f.read()
try:
data = json.loads(data)
except Exception:
pass
fixture_data[path] = data
return data
class TestParameters(unittest.TestCase):
def test_module_parameters(self):
args = dict(
initial_image='BIGIP-12.1.0.1.... | return fixture_data[path] | conditional_block |
pytorch.py | import klampt.math.autodiff.ad as ad
import torch,numpy as np
class TorchModuleFunction(ad.ADFunctionInterface):
"""Converts a PyTorch function to a Klamp't autodiff function class."""
def __init__(self,module):
self.module=module
self._eval_params=[]
torch.set_default_dtype(torch.float... |
def ad_to_torch(func,terminals=None):
"""Converts a Klamp't autodiff function call or function instance to a
PyTorch Function. If terminals is provided, this is the list of arguments
that PyTorch will expect. Otherwise, the variables in the expression
will be automatically determined by the forward... | """Converts a PyTorch function applied to args (list of scalars or numpy
arrays) to a Klamp't autodiff function call on those arguments."""
wrapper=TorchModuleFunction(module)
return wrapper(*args) | identifier_body |
pytorch.py | import klampt.math.autodiff.ad as ad
import torch,numpy as np
class TorchModuleFunction(ad.ADFunctionInterface):
"""Converts a PyTorch function to a Klamp't autodiff function class."""
def __init__(self,module):
self.module=module
self._eval_params=[]
torch.set_default_dtype(torch.float... |
else:
if isinstance(func,ad.ADFunctionCall):
fterminals = func.terminals()
if len(terminals) != len(fterminals):
raise ValueError("The number of terminals provided is incorrect")
for t in terminals:
if isinstance(t,ad.ADTerminal):
... | n_args = func.n_args()
terminals = [func.argname(i) for i in range(n_args)] | conditional_block |
pytorch.py | import klampt.math.autodiff.ad as ad
import torch,numpy as np
class TorchModuleFunction(ad.ADFunctionInterface):
"""Converts a PyTorch function to a Klamp't autodiff function class."""
def __init__(self,module):
self.module=module
self._eval_params=[]
torch.set_default_dtype(torch.float... | return ADModule(func,terminals) | except NotImplementedError:
pass | random_line_split |
pytorch.py | import klampt.math.autodiff.ad as ad
import torch,numpy as np
class TorchModuleFunction(ad.ADFunctionInterface):
"""Converts a PyTorch function to a Klamp't autodiff function class."""
def __init__(self,module):
self.module=module
self._eval_params=[]
torch.set_default_dtype(torch.float... | (torch.autograd.Function):
"""Converts a Klamp't autodiff function call or function instance to a
PyTorch Function. The class must be created with the terminal symbols
corresponding to the PyTorch arguments to which this is called.
"""
@staticmethod
def forward(ctx,func,terminals,*args):
... | ADModule | identifier_name |
index_spec.js | import {
cachedData,
getCurrentHoverElement,
setCurrentHoverElement,
addInteractionClass,
} from '~/code_navigation/utils';
afterEach(() => {
if (cachedData.has('current')) {
cachedData.delete('current');
}
});
describe('getCurrentHoverElement', () => {
it.each`
value
${'test'}
${undefin... |
expect(getCurrentHoverElement()).toEqual(value);
});
});
describe('setCurrentHoverElement', () => {
it('sets cached current key', () => {
setCurrentHoverElement('test');
expect(getCurrentHoverElement()).toEqual('test');
});
});
describe('addInteractionClass', () => {
beforeEach(() => {
setF... | {
cachedData.set('current', value);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.