file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
extractMenu.ts | // Extract menu still frames.
/// <reference path="../../references.ts" />
'use strict';
import path = require('path');
import serverUtils = require('../../server/utils/index');
import utils = require('../../utils');
import editMetadataFile = require('../../server/utils/editMetadataFile');
export = extractMenu;
... | (name: string): string {
return path.join(webPath, getJsonFileName(name));
}
}
/**
* Transform the file name of a JSON file.
*
* @param {string} name A file name.
* @return {string}
*/
function getJsonFileName(name: string): string {
return name.replace(/\.IFO$/i, '') + '.json';
}
| getWebName | identifier_name |
extractMenu.ts | // Extract menu still frames.
/// <reference path="../../references.ts" />
'use strict';
import path = require('path');
import serverUtils = require('../../server/utils/index');
import utils = require('../../utils');
import editMetadataFile = require('../../server/utils/editMetadataFile');
export = extractMenu;
... |
/**
* Return the file path for the web given a file.
* Used for naming both the IFO files and the metadata file.
*
* @param name A file name.
* @return {string}
*/
function getWebName(name: string): string {
return path.join(webPath, getJsonFileName(name));
}
}
/**
* Transform the file n... | {
ifoFile = path.join(webPath, '../', ifoFile);
var json = require(ifoFile);
menu[pointer] = {};
menu[pointer].menu = {};
extractMenuData();
function extractMenuData() {
if (!json.pgci_ut || !json.pgci_ut.lu || !Array.isArray(json.pgci_ut.lu)) {
callNext();
return;
... | identifier_body |
extractMenu.ts | // Extract menu still frames.
/// <reference path="../../references.ts" />
'use strict';
import path = require('path');
import serverUtils = require('../../server/utils/index');
import utils = require('../../utils');
import editMetadataFile = require('../../server/utils/editMetadataFile');
export = extractMenu;
... |
}
callNext();
function callNext() {
pointer++;
if (pointer < filesList.length) {
setTimeout(function() {
next(filesList[pointer].ifo);
}, 0);
} else {
// At the end of all iterations.
// Save a metadata file containing the ... | {
var pgci_srp = lu.pgcit.pgci_srp[j];
var pgcIndex = j + 1;
var vobID = null;
var cellID = null;
if (pgci_srp.pgc.cell_position && pgci_srp.pgc.cell_position.length) {
vobID = pgci_srp.pgc.cell_position[0].vob_id_nr;
cellID = pgci_srp.pgc.cell_p... | conditional_block |
extractMenu.ts | // Extract menu still frames.
/// <reference path="../../references.ts" />
'use strict';
import path = require('path'); |
export = extractMenu;
/**
* Extract menu still frames.
*
* @param {string} dvdPath
* @param {function} callback
*/
function extractMenu(dvdPath: string, callback) {
process.stdout.write('\nExtracting menu still frames:\n');
var webPath = serverUtils.getWebPath(dvdPath);
var ifoPath = getWebName('metadata... |
import serverUtils = require('../../server/utils/index');
import utils = require('../../utils');
import editMetadataFile = require('../../server/utils/editMetadataFile'); | random_line_split |
type_cameras.py | """Class to hold all camera accessories."""
import asyncio
from datetime import timedelta
import logging
from haffmpeg.core import HAFFmpeg
from pyhap.camera import (
VIDEO_CODEC_PARAM_LEVEL_TYPES,
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES,
Camera as PyhapCamera,
)
from pyhap.const import CATEGORY_CAMERA
from ho... |
async def run_handler(self):
"""Handle accessory driver started event.
Run inside the Home Assistant event loop.
"""
if self._char_motion_detected:
async_track_state_change_event(
self.hass,
[self.linked_motion_sensor],
s... | serv_doorbell = self.add_preload_service(SERV_DOORBELL)
self.set_primary_service(serv_doorbell)
self._char_doorbell_detected = serv_doorbell.configure_char(
CHAR_PROGRAMMABLE_SWITCH_EVENT, value=0,
)
serv_stateless_switch = self.add_pre... | conditional_block |
type_cameras.py | """Class to hold all camera accessories."""
import asyncio
from datetime import timedelta
import logging
from haffmpeg.core import HAFFmpeg
from pyhap.camera import (
VIDEO_CODEC_PARAM_LEVEL_TYPES,
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES,
Camera as PyhapCamera,
)
from pyhap.const import CATEGORY_CAMERA
from ho... | (self, new_state):
"""Handle link motion sensor state change to update HomeKit value."""
if not new_state:
return
detected = new_state.state == STATE_ON
if self._char_motion_detected.value == detected:
return
self._char_motion_detected.set_value(detected... | _async_update_motion_state | identifier_name |
type_cameras.py | """Class to hold all camera accessories."""
import asyncio
from datetime import timedelta
import logging
from haffmpeg.core import HAFFmpeg
from pyhap.camera import (
VIDEO_CODEC_PARAM_LEVEL_TYPES,
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES,
Camera as PyhapCamera,
)
from pyhap.const import CATEGORY_CAMERA
from ho... |
async def stop_stream(self, session_info):
"""Stop the stream for the given ``session_id``."""
session_id = session_info["id"]
stream = session_info.get("stream")
if not stream:
_LOGGER.debug("No stream for session ID %s", session_id)
return
self._a... | """Cleanup a streaming session after stopping."""
if FFMPEG_WATCHER not in self.sessions[session_id]:
return
self.sessions[session_id].pop(FFMPEG_WATCHER)() | identifier_body |
type_cameras.py | """Class to hold all camera accessories."""
import asyncio
from datetime import timedelta
import logging
from haffmpeg.core import HAFFmpeg
from pyhap.camera import (
VIDEO_CODEC_PARAM_LEVEL_TYPES,
VIDEO_CODEC_PARAM_PROFILE_ID_TYPES,
Camera as PyhapCamera,
)
from pyhap.const import CATEGORY_CAMERA
from ho... | def _async_stop_ffmpeg_watch(self, session_id):
"""Cleanup a streaming session after stopping."""
if FFMPEG_WATCHER not in self.sessions[session_id]:
return
self.sessions[session_id].pop(FFMPEG_WATCHER)()
async def stop_stream(self, session_info):
"""Stop the stream ... | @callback | random_line_split |
index.ts | import low from 'lowdb';
import FileSync from 'lowdb/adapters/FileSync';
import { v4 as uuidv4 } from 'uuid';
import { Game, LAN_PARTY_GAMES } from './games';
import { Event } from './events';
interface Database {
eventTypes: string[];
events: Event[];
games: Game[];
}
const getDb = () => {
const adapter = n... |
return db;
};
export default getDb; | ...game,
id: uuidv4(),
})),
],
}).write(); | random_line_split |
ViewInRoom.jest.tsx | import { graphql } from "relay-runtime"
import { setupTestWrapper } from "v2/DevTools/setupTestWrapper"
import { ViewInRoomFragmentContainer } from "../ViewInRoom"
jest.unmock("react-relay")
const { getWrapper } = setupTestWrapper({
Component: ViewInRoomFragmentContainer,
query: graphql`
query ViewInRoom_Test... | `,
})
describe("ViewInRoom", () => {
it("renders correctly", () => {
const wrapper = getWrapper({
Artwork: () => ({ widthCm: 33, heightCm: 66 }),
ResizedImageUrl: () => ({
src: "example.jpg",
srcSet: "example.jpg 1x",
}),
})
expect(wrapper.html()).toContain(
'sr... | } | random_line_split |
api.ts | }
}
export interface QueryRevisionResponse {
query: {
normalized: {
fromencoded: boolean
from: string
to: string
}
pages: Array<{
pageid: number
ns: number
title: string
revisions: Array<{
slots: {[slot: string]: {
contentmodel: string
... | export interface ParseResponse {
parse: {
title: string
pageid: number
text: string | random_line_split | |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... |
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
... | {
if !tree_in_doc {
return;
}
if self.upcast::<Element>().has_attribute(&atom!("href")) {
let document = document_from_node(self);
document.refresh_base_element();
}
} | identifier_body |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLBaseElement> {
let element = HTMLBaseElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap)
}
/// https://html.s... | new | identifier_name |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... | fn unbind_from_tree(&self, tree_in_doc: bool) {
self.super_type().unwrap().unbind_from_tree(tree_in_doc);
self.bind_unbind(tree_in_doc);
}
} | }
| random_line_split |
htmlbaseelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLBaseElementBinding;
use dom::bindings::inheritance:... |
if self.upcast::<Element>().has_attribute(&atom!("href")) {
let document = document_from_node(self);
document.refresh_base_element();
}
}
}
impl VirtualMethods for HTMLBaseElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElemen... | {
return;
} | conditional_block |
table_of_contents.py | #!/usr/bin/env python3
import os
from wsgiref.handlers import CGIHandler
import orjson
import sys
sys.path.append("..")
import custom_functions
try:
from custom_functions import generate_toc_object
except ImportError:
from philologic.runtime import generate_toc_object
try:
from custom_functions import ... | CGIHandler().run(table_of_contents) | conditional_block | |
table_of_contents.py | #!/usr/bin/env python3
import os
from wsgiref.handlers import CGIHandler
import orjson
import sys
sys.path.append("..")
import custom_functions
try:
from custom_functions import generate_toc_object
except ImportError:
from philologic.runtime import generate_toc_object
try:
from custom_functions import ... |
if __name__ == "__main__":
CGIHandler().run(table_of_contents)
| config = WebConfig(os.path.abspath(os.path.dirname(__file__)).replace("reports", ""))
request = WSGIHandler(environ, config)
headers = [("Content-type", "application/json; charset=UTF-8"), ("Access-Control-Allow-Origin", "*")]
start_response("200 OK", headers)
toc_object = generate_toc_object(request, ... | identifier_body |
table_of_contents.py | #!/usr/bin/env python3
import os
from wsgiref.handlers import CGIHandler
import orjson
import sys
sys.path.append("..")
import custom_functions
try:
from custom_functions import generate_toc_object
except ImportError:
from philologic.runtime import generate_toc_object
try:
from custom_functions import ... | (environ, start_response):
config = WebConfig(os.path.abspath(os.path.dirname(__file__)).replace("reports", ""))
request = WSGIHandler(environ, config)
headers = [("Content-type", "application/json; charset=UTF-8"), ("Access-Control-Allow-Origin", "*")]
start_response("200 OK", headers)
toc_object ... | table_of_contents | identifier_name |
table_of_contents.py | #!/usr/bin/env python3
import os
from wsgiref.handlers import CGIHandler
import orjson
import sys
sys.path.append("..")
import custom_functions
try:
from custom_functions import generate_toc_object
except ImportError:
from philologic.runtime import generate_toc_object
try:
from custom_functions import ... | CGIHandler().run(table_of_contents) | random_line_split | |
rot.rs | pub struct Rot {
pub s: f32,
pub c: f32
}
impl Rot {
pub fn new() -> Rot {
Rot {
s: 0.0,
c: 1.0
}
}
/// Initialize from an angle in radians
pub fn new_angle(angle: f32) -> Rot {
Rot {
s: angle.sin(),
c: angle.cos()
... | use super::Vec2;
/// Rotation
#[derive(Copy, Clone)] | random_line_split | |
rot.rs | use super::Vec2;
/// Rotation
#[derive(Copy, Clone)]
pub struct | {
pub s: f32,
pub c: f32
}
impl Rot {
pub fn new() -> Rot {
Rot {
s: 0.0,
c: 1.0
}
}
/// Initialize from an angle in radians
pub fn new_angle(angle: f32) -> Rot {
Rot {
s: angle.sin(),
c: angle.cos()
}
}
... | Rot | identifier_name |
check_with_sitemap_vpro.py | #!/usr/bin/env python3
import os
import re
import subprocess
import sys
import threading
import time
import urllib
from subprocess import Popen, PIPE
sys.path.append("..")
from check_with_sitemap import CheckWithSitemap
DEFAULT_JAVA_PATH = 'java'
class CheckWithSiteMapVpro(CheckWithSitemap):
"""
This specia... | (threading.Thread):
def __init__(self, log):
threading.Thread.__init__(self)
self.daemon = True # So that thread will exit when
# main non-daemon thread finishes
self.log = log
def run(self):
self.log.info("Setting up tunnel")... | SshTunnel | identifier_name |
check_with_sitemap_vpro.py | #!/usr/bin/env python3
import os
import re
import subprocess
import sys
import threading
import time
import urllib
from subprocess import Popen, PIPE
sys.path.append("..")
from check_with_sitemap import CheckWithSitemap
DEFAULT_JAVA_PATH = 'java'
class CheckWithSiteMapVpro(CheckWithSitemap):
"""
This specia... |
def _find_mid(self, url: str) -> list:
return self._find_by_regexp(".*?~(.*?)~.*", url)
def _find_update_uuid(self, url: str) -> list:
return self._find_by_regexp(".*?update~(.*?)~.*", url)
def _find_cinema_film_id(self, url: str) -> list:
return self._find_by_regexp(".*?film~(.*... | page_size = 20
self.log.info("Reindexing %d urls" % len(not_in_api))
for i in range(0, len(not_in_api), page_size ):
self._call_jmx_operation("nl.vpro.magnolia:name=IndexerMaintainerImpl", "reindexUrls", not_in_api[i: i + page_size ]) | identifier_body |
check_with_sitemap_vpro.py | #!/usr/bin/env python3
import os
import re
import subprocess
import sys
import threading
import time
import urllib
from subprocess import Popen, PIPE
sys.path.append("..")
from check_with_sitemap import CheckWithSitemap
DEFAULT_JAVA_PATH = 'java'
class CheckWithSiteMapVpro(CheckWithSitemap):
"""
This specia... | self.log = log
def run(self):
self.log.info("Setting up tunnel")
if subprocess.call([
'ssh', '-N', '-4',
'-L', '5000:localhost:5000',
'os2-magnolia-backend-prod-01'
]):
raise Exception ('ssh tunnel setup failed')
... | # main non-daemon thread finishes | random_line_split |
check_with_sitemap_vpro.py | #!/usr/bin/env python3
import os
import re
import subprocess
import sys
import threading
import time
import urllib
from subprocess import Popen, PIPE
sys.path.append("..")
from check_with_sitemap import CheckWithSitemap
DEFAULT_JAVA_PATH = 'java'
class CheckWithSiteMapVpro(CheckWithSitemap):
"""
This specia... |
def _get_jmx_term_if_necessary(self):
if self.jmx_url and not self.jmxterm_binary:
from_env = os.getenv('JMXTERM_BINARY')
if not from_env is None:
self.jmxterm_binary=from_env
else:
jmxtermversion = "1.0.2"
jmxterm = "jmxt... | self.log.info("Jmx reports that still busy. Let's wait a bit then")
time.sleep(20) | conditional_block |
personal.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
assert!(tester.accounts.sign(address, None, Default::default()).is_ok(), "Should unlock account.");
} | }"#; | random_line_split |
personal.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | () {
let tester = setup();
let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{
"jsonrpc": "2.0",
"method": "personal_unlockAccount",
"params": [
""#.to_owned() + &format!("0x{:?}", address) + r#"",
"password123",
"0x100"
],
"id": 1
}"#;
let response = r#"{"json... | should_unlock_account_temporarily | identifier_name |
index.js | 'use strict';
const debug = require('debug')('WechatController');
const EventEmitter = require('events').EventEmitter;
const Cache = require('../../service/Cache');
const Wechat = require('../../service/Wechat');
const config = require('../../config');
const _ = require('lodash');
const async = require('async');
/* 微... | if(log) {
let nextIndex = log.clickCount;
if(nextIndex > log.messageGroupsSnapshot.length-1) {
nextIndex = log.messageGroupsSnapshot.length-1;
} else {
ReplyQueueLog.findByIdAndUpdate(log._id, { clickCount: nextIndex + 1 }, { new: true }).exec();
}
... | e.type === 'text') {
return Wechat.sendText(openId, message.content).then((data) => {
setTimeout(callback, 1000);
}).catch(callback);
}
if(message.type === 'image') {
return Wechat.sendImage(openId, message.mediaId).then((data) => {
set... | identifier_body |
index.js | 'use strict';
const debug = require('debug')('WechatController');
const EventEmitter = require('events').EventEmitter;
const Cache = require('../../service/Cache');
const Wechat = require('../../service/Wechat');
const config = require('../../config');
const _ = require('lodash');
const async = require('async');
/* 微... | if(message.type === 'text') {
return Wechat.sendText(openId, message.content).then((data) => {
setTimeout(callback, 1000);
}).catch(callback);
}
if(message.type === 'image') {
return Wechat.sendImage(openId, message.mediaId).then((data) => {
... | back) {
| identifier_name |
index.js | 'use strict';
const debug = require('debug')('WechatController');
const EventEmitter = require('events').EventEmitter;
const Cache = require('../../service/Cache');
const Wechat = require('../../service/Wechat');
const config = require('../../config');
const _ = require('lodash');
const async = require('async');
/* 微... | .TemplateSendLog;
status = _.upperFirst(status);
TemplateSendLog.findOneAndUpdate({ msgId: msgId }, { status : status }, function(err, doc){
if (err) return console.log(err);
console.log(`[WechatController] TEMPLATESENDJOBFINISH: ${msgId}`);
});
}
} |
// 检查扫码标记
workflow.on('checkTicket', () => {
debug('Event: checkTicket');
if(ticket) return workflow.emit('findNewUser'); // 在数据库中寻找该"新"用户
return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情
});
// 在数据库中寻找该用户
workflow.on('findNewUser', () => {
debug('Event: findNewUser... | conditional_block |
index.js | 'use strict';
const debug = require('debug')('WechatController');
const EventEmitter = require('events').EventEmitter;
const Cache = require('../../service/Cache');
const Wechat = require('../../service/Wechat');
const config = require('../../config');
const _ = require('lodash');
const async = require('async');
/* 微... | } else {
Subscriber.findOne({ openId, subscribe: true }).exec((err, subscriberDoc) => {
if(err) return console.error(err);
if(subscriberDoc) return Wechat.sendText(openId, "你已经关注,不能被邀请");
});
}
}
});
}
}
if(name === 'click') {... | if(err) return console.error(err);
if(cardDoc && cardDoc.invitationTask.status === 'OPEN') {
if(cardDoc.openId === openId) {
return Wechat.sendText(openId, "你不能扫描自己的任务卡"); | random_line_split |
thread_share.rs | //thread_share.rs
//Copyright 2015 David Huddle
use std::thread;
use std::sync::{Arc,mpsc};
extern crate time;
/// takes a vector and modifies in on a different thread
pub fn do_amazing_things(data:Vec<i32>)->Vec<i32> |
/// Takes a vec and breaks it up to do calculations
pub fn do_calc(data: Vec<i32>)->Vec<i32>{
let mut package = vec![data];
let start = time::precise_time_ns();
for _ in 0..2 {
package = break_vec(package);
}
let stop = time::precise_time_ns();
println!("split time: {}", stop - start)... | {
let (tx, rx) = mpsc::channel();
let tx = tx.clone();
thread::spawn(move || {
let mut ret = Vec::new();
for x in data {
ret.push(x * 7);
}
tx.send(ret);
});
rx.recv().ok().expect("Could not receive answer")
} | identifier_body |
thread_share.rs | //thread_share.rs
//Copyright 2015 David Huddle
use std::thread;
use std::sync::{Arc,mpsc};
extern crate time;
/// takes a vector and modifies in on a different thread
pub fn do_amazing_things(data:Vec<i32>)->Vec<i32>{
let (tx, rx) = mpsc::channel();
let tx = tx.clone();
thread::spawn(move || {
l... | for _ in 0..10 {
let tx = tx.clone();
thread::spawn(move || {
let answer = 42;
tx.send(answer);
});
}
let mut ret:Vec<i32> = Vec::new();
for _ in 0..10 {
ret.push(rx.recv().ok().expect("Could not receive answer"));
}
ret
}
/// Simple examp... | }
/// Simple example of multi provider single consumer
pub fn simple_mpsc()->Vec<i32>{
let (tx, rx) = mpsc::channel(); | random_line_split |
thread_share.rs | //thread_share.rs
//Copyright 2015 David Huddle
use std::thread;
use std::sync::{Arc,mpsc};
extern crate time;
/// takes a vector and modifies in on a different thread
pub fn do_amazing_things(data:Vec<i32>)->Vec<i32>{
let (tx, rx) = mpsc::channel();
let tx = tx.clone();
thread::spawn(move || {
l... | (){
use std::thread;
let handle = thread::spawn(move || {
panic!("oops!");
});
let result = handle.join();
assert!(result.is_err());
}
| thread_handle | identifier_name |
mem_replace.rs | // run-rustfix
#![allow(unused_imports)]
#![warn(
clippy::all,
clippy::style,
clippy::mem_replace_option_with_none,
clippy::mem_replace_with_default
)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::mem;
fn replace_option_with_none() {
let ... | () {
let mut s = String::from("foo");
let _ = std::mem::replace(&mut s, String::default());
let s = &mut String::from("foo");
let _ = std::mem::replace(s, String::default());
let _ = std::mem::replace(s, Default::default());
let mut v = vec![123];
let _ = std::mem::replace(&mut v, Vec::def... | replace_with_default | identifier_name |
mem_replace.rs | // run-rustfix
#![allow(unused_imports)]
#![warn(
clippy::all,
clippy::style,
clippy::mem_replace_option_with_none,
clippy::mem_replace_with_default
)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::mem;
fn replace_option_with_none() |
fn replace_with_default() {
let mut s = String::from("foo");
let _ = std::mem::replace(&mut s, String::default());
let s = &mut String::from("foo");
let _ = std::mem::replace(s, String::default());
let _ = std::mem::replace(s, Default::default());
let mut v = vec![123];
let _ = std::mem:... | {
let mut an_option = Some(1);
let _ = mem::replace(&mut an_option, None);
let an_option = &mut Some(1);
let _ = mem::replace(an_option, None);
} | identifier_body |
mem_replace.rs | // run-rustfix
#![allow(unused_imports)]
#![warn(
clippy::all,
clippy::style,
clippy::mem_replace_option_with_none,
clippy::mem_replace_with_default
)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque};
use std::mem;
fn replace_option_with_none() { |
fn replace_with_default() {
let mut s = String::from("foo");
let _ = std::mem::replace(&mut s, String::default());
let s = &mut String::from("foo");
let _ = std::mem::replace(s, String::default());
let _ = std::mem::replace(s, Default::default());
let mut v = vec![123];
let _ = std::mem::... | let mut an_option = Some(1);
let _ = mem::replace(&mut an_option, None);
let an_option = &mut Some(1);
let _ = mem::replace(an_option, None);
} | random_line_split |
lib.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/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of ... | extern crate cssparser;
extern crate euclid;
extern crate rustc_serialize;
extern crate serde;
extern crate util;
#[macro_use]
pub mod values;
pub mod viewport;
use cssparser::{Parser, SourcePosition};
pub trait ParseErrorReporter {
fn report_error(&self, input: &mut Parser, position: SourcePosition, message: &st... | random_line_split | |
graph.rs |
use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Lin... |
}
true
}
pub fn remove_unconnected_nodes(&mut self) {
let mut remove = Vec::new();
for id in 0..self.node_count as ID {
if self.get_node_degree(id) == 0 {
remove.push(id);
}
}
self.remove_nodes(&remove);
}
pub fn node_count(&self) -> usize {
self.node_count
}
pub fn link_count(&self) -... | {
return false;
} | conditional_block |
graph.rs |
use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Lin... | (links: &[Link], node_count: usize) -> Graph {
let mut roots = Vec::with_capacity(node_count);
let mut mst = Vec::new();
// initial root of every node is itself
for i in 0..node_count {
roots.push(i as ID);
}
// find root of node
fn root(roots: &mut [ID], i: ID) -> usize {
let mut i = i as usize;
... | minimum_spanning_tree_impl | identifier_name |
graph.rs | use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Link... | while roots[i] != i as ID {
// Path halving optimization
let tmp = roots[roots[i] as usize];
roots[i] = tmp;
i = tmp as usize;
}
i
}
for link in links {
let x = root(&mut roots, link.from);
let y = root(&mut roots, link.to);
if x != y {
mst.push(link.clone());
roots[x] = r... |
// find root of node
fn root(roots: &mut [ID], i: ID) -> usize {
let mut i = i as usize; | random_line_split |
graph.rs |
use std::f32;
use std::u16;
use std::fmt;
use std::cmp::Ordering;
use crate::utils::vec_filter;
//TODO: rename to Links and GraphState to Graph
pub type ID = u32;
#[derive(Clone, PartialEq)]
pub struct Link
{
pub from: ID,
pub to: ID,
pub quality: u16,
//bandwidth: u16,
//channel: u8
cost: u16,
}
impl Lin... |
pub fn clear_links(&mut self) {
self.links.clear();
}
pub fn is_directed(&self) -> bool {
for link in &self.links {
if self.link_idx(link.to, link.from).is_none() {
return false;
}
}
true
}
pub fn remove_unconnected_nodes(&mut self) {
let mut remove = Vec::new();
for id in 0..self.node_co... | {
match self.links.binary_search_by(|link| link.from.cmp(&id)) {
Ok(idx) => {
let mut start = idx;
let mut end = idx;
for i in (0..idx).rev() {
if self.links[i].from == id {
start = i;
}
}
for i in idx..self.links.len() {
if self.links[i].from == id {
end = i;
}
... | identifier_body |
classes_70.js | var searchData=
[
['paperfigures',['PaperFigures',['../class_paper_figures.html',1,'']]],
['parameter',['Parameter',['../class_parameter.html',1,'']]],
['pathway',['Pathway',['../class_pathway.html',1,'']]],
['pdfutil',['PdfUtil',['../class_pdf_util.html',1,'']]], | ['population',['Population',['../class_population.html',1,'']]],
['posterfigures',['PosterFigures',['../class_poster_figures.html',1,'']]],
['process',['Process',['../class_process.html',1,'']]],
['processmetaboliteusage',['ProcessMetaboliteUsage',['../class_process_metabolite_usage.html',1,'']]],
['protein',... | ['physicalobject',['PhysicalObject',['../class_physical_object.html',1,'']]],
['polymer',['Polymer',['../class_polymer.html',1,'']]], | random_line_split |
_deprecated_schema_parser.py | """Parse the biothings schema"""
from .config import BIOTHINGS_SCHEMA_URL, PREFIX_TO_REMOVE
from .utils.dataload import load_json_or_yaml
from .utils.common import remove_prefix
class SchemaParser():
def __init__(self):
self.schema_json = remove_prefix(load_json_or_yaml(BIOTHINGS_SCHEMA_URL),
... | (self):
for rec in self.schema_json['@graph']:
if "rdfs:subPropertyOf" in rec and rec["rdfs:subPropertyOf"]["@id"] == "http://schema.org/identifier":
self.ids.append(rec["@id"])
elif rec["@type"] == "rdf:Property":
self.properties[rec["@id"]] = {"inverse_p... | process_schema | identifier_name |
_deprecated_schema_parser.py | """Parse the biothings schema"""
from .config import BIOTHINGS_SCHEMA_URL, PREFIX_TO_REMOVE
from .utils.dataload import load_json_or_yaml
from .utils.common import remove_prefix
class SchemaParser():
def __init__(self):
self.schema_json = remove_prefix(load_json_or_yaml(BIOTHINGS_SCHEMA_URL),
... | self.properties[rec["@id"]]["inverse_property"] = rec["schema:inverseOf"]["@id"]
elif rec["@type"] == "rdfs:Class":
self.clses.append(rec["@id"]) | random_line_split | |
_deprecated_schema_parser.py | """Parse the biothings schema"""
from .config import BIOTHINGS_SCHEMA_URL, PREFIX_TO_REMOVE
from .utils.dataload import load_json_or_yaml
from .utils.common import remove_prefix
class SchemaParser():
def __init__(self):
self.schema_json = remove_prefix(load_json_or_yaml(BIOTHINGS_SCHEMA_URL),
... | for rec in self.schema_json['@graph']:
if "rdfs:subPropertyOf" in rec and rec["rdfs:subPropertyOf"]["@id"] == "http://schema.org/identifier":
self.ids.append(rec["@id"])
elif rec["@type"] == "rdf:Property":
self.properties[rec["@id"]] = {"inverse_property": None}
... | identifier_body | |
_deprecated_schema_parser.py | """Parse the biothings schema"""
from .config import BIOTHINGS_SCHEMA_URL, PREFIX_TO_REMOVE
from .utils.dataload import load_json_or_yaml
from .utils.common import remove_prefix
class SchemaParser():
def __init__(self):
self.schema_json = remove_prefix(load_json_or_yaml(BIOTHINGS_SCHEMA_URL),
... |
elif rec["@type"] == "rdf:Property":
self.properties[rec["@id"]] = {"inverse_property": None}
if "schema:inverseOf" in rec:
self.properties[rec["@id"]]["inverse_property"] = rec["schema:inverseOf"]["@id"]
elif rec["@type"] == "rdfs:Class":
... | self.ids.append(rec["@id"]) | conditional_block |
transliterate.ts | import {
IntervalArray,
OptionReplaceArray,
OptionReplaceCombined,
OptionReplaceObject,
OptionsTransliterate,
} from '../types';
import { charmap, Charmap } from '../../data/charmap';
import {
deepClone,
escapeRegExp,
findStrOccurrences,
inRange,
hasChinese,
regexpReplaceCustom,
hasPunctuationO... |
lastCharHasChinese = !!s && hasChinese(char);
}
result += s;
index += char.length;
// If it's UTF-32 then skip next character
i += char.length - 1;
}
return result;
}
/**
* Convert the object version of the 'replace' option into tuple array one
* @param option r... | {
s = ' ' + s;
} | conditional_block |
transliterate.ts | import {
IntervalArray,
OptionReplaceArray,
OptionReplaceCombined,
OptionReplaceObject,
OptionsTransliterate,
} from '../types';
import { charmap, Charmap } from '../../data/charmap';
import {
deepClone,
escapeRegExp,
findStrOccurrences,
inRange,
hasChinese,
regexpReplaceCustom,
hasPunctuationO... |
/**
* Replace the source string using the code map
* @param str
* @param ignoreRanges
* @param unknown
*/
public codeMapReplace(
str: string,
ignoreRanges: IntervalArray = [],
opt: OptionsTransliterate,
): string {
let index = 0;
let result = '';
const strContainsChinese =... | {
if (reset) {
this.confOptions = {};
}
if (options && typeof options === 'object') {
this.confOptions = deepClone(options);
}
return this.confOptions;
} | identifier_body |
transliterate.ts | import {
IntervalArray,
OptionReplaceArray,
OptionReplaceCombined,
OptionReplaceObject,
OptionsTransliterate,
} from '../types';
import { charmap, Charmap } from '../../data/charmap';
import {
deepClone,
escapeRegExp,
findStrOccurrences,
inRange,
hasChinese,
regexpReplaceCustom,
hasPunctuationO... | /**
* Search and replace a list of strings(regexps) and return the result string
* @param source Source string
* @param searches Search-replace string(regexp) pairs
*/
public replaceString(
source: string,
searches: OptionReplaceArray,
ignore: string[] = [],
): string {
const clonedSea... | }
| random_line_split |
transliterate.ts | import {
IntervalArray,
OptionReplaceArray,
OptionReplaceCombined,
OptionReplaceObject,
OptionsTransliterate,
} from '../types';
import { charmap, Charmap } from '../../data/charmap';
import {
deepClone,
escapeRegExp,
findStrOccurrences,
inRange,
hasChinese,
regexpReplaceCustom,
hasPunctuationO... | {
get options(): OptionsTransliterate {
return deepClone({ ...defaultOptions, ...this.confOptions });
}
constructor(
protected confOptions: OptionsTransliterate = deepClone(defaultOptions),
protected map: Charmap = charmap,
) {}
/**
* Set default config
* @param options
*/
public con... | Transliterate | identifier_name |
TestHelper.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getCellMetadata = getCellMetadata;
var _initCellMetadata = require('./initCellMetadata');
var _initCellMetadata2 = _interopRequireDefault(_initCellMetadata);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? o... | () {
var cellSizes = [10, // 0: 0..0 (min)
20, // 1: 0..10
15, // 2: 0..30
10, // 3: 5..45
15, // 4: 20..55
30, // 5: 50..70
20, // 6: 70..100
10, // 7: 80..110
30 // 8: 110..110 (max)
];
return (0, _initCellMetadata2.default)({
cellCount: cellSizes.length,
size: function size(_ref) {
... | getCellMetadata | identifier_name |
TestHelper.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getCellMetadata = getCellMetadata;
var _initCellMetadata = require('./initCellMetadata');
var _initCellMetadata2 = _interopRequireDefault(_initCellMetadata);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? o... | 20, // 6: 70..100
10, // 7: 80..110
30 // 8: 110..110 (max)
];
return (0, _initCellMetadata2.default)({
cellCount: cellSizes.length,
size: function size(_ref) {
var index = _ref.index;
return cellSizes[index];
}
});
} | 15, // 2: 0..30
10, // 3: 5..45
15, // 4: 20..55
30, // 5: 50..70 | random_line_split |
TestHelper.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getCellMetadata = getCellMetadata;
var _initCellMetadata = require('./initCellMetadata');
var _initCellMetadata2 = _interopRequireDefault(_initCellMetadata);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? o... | {
var cellSizes = [10, // 0: 0..0 (min)
20, // 1: 0..10
15, // 2: 0..30
10, // 3: 5..45
15, // 4: 20..55
30, // 5: 50..70
20, // 6: 70..100
10, // 7: 80..110
30 // 8: 110..110 (max)
];
return (0, _initCellMetadata2.default)({
cellCount: cellSizes.length,
size: function size(_ref) {
... | identifier_body | |
test.py | from supervisorerrormiddleware import SupervisorErrorMiddleware
import os
import sys
import paste.fixture
class DummyOutput:
def __init__(self):
self._buffer = []
def write(self, data):
self._buffer.append(data)
def flush(self):
self._buffer = []
def bad_app(environ, start_respon... | app.get("/")
except:
failed = True
assert failed
output = "".join(sys.stdout._buffer)
sys.stdout.flush()
assert not "Bad Kitty" in output
assert not "GET" in output
response = app.get("/good")
output = "".join(sys.stdout._buffer)
... | random_line_split | |
test.py | from supervisorerrormiddleware import SupervisorErrorMiddleware
import os
import sys
import paste.fixture
class DummyOutput:
|
def bad_app(environ, start_response):
if environ['PATH_INFO'] != '/good':
raise Exception("Bad Kitty")
else:
start_response("200 OK", [('Content-type', 'text/html')])
return ["Good Kitty"]
def test_without_supervisor():
old_stdout = sys.stdout
try:
sys.stdout = DummyOu... | def __init__(self):
self._buffer = []
def write(self, data):
self._buffer.append(data)
def flush(self):
self._buffer = [] | identifier_body |
test.py | from supervisorerrormiddleware import SupervisorErrorMiddleware
import os
import sys
import paste.fixture
class DummyOutput:
def __init__(self):
self._buffer = []
def write(self, data):
self._buffer.append(data)
def flush(self):
self._buffer = []
def bad_app(environ, start_respon... |
def test_without_supervisor():
old_stdout = sys.stdout
try:
sys.stdout = DummyOutput()
app = bad_app
app = SupervisorErrorMiddleware(app)
app = paste.fixture.TestApp(app)
failed = False
try:
app.get("/")
except:
failed = True
... | start_response("200 OK", [('Content-type', 'text/html')])
return ["Good Kitty"] | conditional_block |
test.py | from supervisorerrormiddleware import SupervisorErrorMiddleware
import os
import sys
import paste.fixture
class DummyOutput:
def __init__(self):
self._buffer = []
def write(self, data):
self._buffer.append(data)
def flush(self):
self._buffer = []
def | (environ, start_response):
if environ['PATH_INFO'] != '/good':
raise Exception("Bad Kitty")
else:
start_response("200 OK", [('Content-type', 'text/html')])
return ["Good Kitty"]
def test_without_supervisor():
old_stdout = sys.stdout
try:
sys.stdout = DummyOutput()
... | bad_app | identifier_name |
applicationGatewaySslPolicy.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
... | () {
}
/**
* Defines the metadata of ApplicationGatewaySslPolicy
*
* @returns {object} metadata of ApplicationGatewaySslPolicy
*
*/
ApplicationGatewaySslPolicy.prototype.mapper = function () {
return {
required: false,
serializedName: 'ApplicationGatewaySslPolicy',
type: {
name: 'Composite',
... | ApplicationGatewaySslPolicy | identifier_name |
applicationGatewaySslPolicy.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
... | serializedName: 'disabledSslProtocols',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
}
... | className: 'ApplicationGatewaySslPolicy',
modelProperties: {
disabledSslProtocols: {
required: false, | random_line_split |
applicationGatewaySslPolicy.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
... |
/**
* Defines the metadata of ApplicationGatewaySslPolicy
*
* @returns {object} metadata of ApplicationGatewaySslPolicy
*
*/
ApplicationGatewaySslPolicy.prototype.mapper = function () {
return {
required: false,
serializedName: 'ApplicationGatewaySslPolicy',
type: {
name: 'Composite',
c... | {
} | identifier_body |
dry.js | 'use strict';
/* Controllers */
var app = angular.module('ng-dashboard.controllers.dry', []);
app.controller('DryController', ['$scope', 'DryFactory', function ($scope, DryFactory) {
DryFactory.query({}, function (data) {
$scope.numberOfWarnings = data.numberOfWarnings;
$scope.numberOfHighPriorityWarnings... | (data) {
var chartData = [
{
value: data.numberOfHighPriorityWarnings,
color:"#d9534f"
},
{
value : data.numberOfNormalPriorityWarnings,
color : "#f0ad4e"
},
{
value : data.numberOfLowPriorityWarnings,
c... | setupDryChart | identifier_name |
dry.js | 'use strict';
/* Controllers */
var app = angular.module('ng-dashboard.controllers.dry', []);
app.controller('DryController', ['$scope', 'DryFactory', function ($scope, DryFactory) {
DryFactory.query({}, function (data) {
$scope.numberOfWarnings = data.numberOfWarnings;
$scope.numberOfHighPriorityWarnings... |
$scope.done = true;
fn_computeSize();
}, function (error) {
$scope.error = true;
})
}]);
function setupDryChart(data) {
var chartData = [
{
value: data.numberOfHighPriorityWarnings,
color:"#d9534f"
},
{
value : data.numbe... | {
$scope.same = true;
} | conditional_block |
dry.js | 'use strict';
/* Controllers */
var app = angular.module('ng-dashboard.controllers.dry', []);
app.controller('DryController', ['$scope', 'DryFactory', function ($scope, DryFactory) {
DryFactory.query({}, function (data) {
$scope.numberOfWarnings = data.numberOfWarnings;
$scope.numberOfHighPriorityWarnings... | },
{
value : data.numberOfNormalPriorityWarnings,
color : "#f0ad4e"
},
{
value : data.numberOfLowPriorityWarnings,
color : "#5bc0de"
}
]
var ctx = document.getElementById("dry-chart").getContext("2d");
var dryChart... | value: data.numberOfHighPriorityWarnings,
color:"#d9534f" | random_line_split |
dry.js | 'use strict';
/* Controllers */
var app = angular.module('ng-dashboard.controllers.dry', []);
app.controller('DryController', ['$scope', 'DryFactory', function ($scope, DryFactory) {
DryFactory.query({}, function (data) {
$scope.numberOfWarnings = data.numberOfWarnings;
$scope.numberOfHighPriorityWarnings... | {
var chartData = [
{
value: data.numberOfHighPriorityWarnings,
color:"#d9534f"
},
{
value : data.numberOfNormalPriorityWarnings,
color : "#f0ad4e"
},
{
value : data.numberOfLowPriorityWarnings,
color : ... | identifier_body | |
Absorber.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ColorUtils_1 = require("./Utils/ColorUtils");
var Utils_1 = require("./Utils/Utils");
var Absorber = (function () {
function Absorber(container, options, position) {
var _a, _b;
this.container = container;
this.... |
};
Absorber.prototype.resize = function () {
var initialPosition = this.initialPosition;
this.position = initialPosition && Utils_1.Utils.isPointInside(initialPosition, this.container.canvas.size) ?
initialPosition :
this.calcPosition();
};
Absorber.prototype.dra... | {
particle.velocity.horizontal += Math.sin(angle * (Math.PI / 180)) * acceleration;
particle.velocity.vertical += Math.cos(angle * (Math.PI / 180)) * acceleration;
return true;
} | conditional_block |
Absorber.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ColorUtils_1 = require("./Utils/ColorUtils");
var Utils_1 = require("./Utils/Utils");
var Absorber = (function () {
function Absorber(container, options, position) |
Absorber.prototype.attract = function (particle) {
var container = this.container;
var dx = this.position.x - (particle.position.x + particle.offset.x);
var dy = this.position.y - (particle.position.y + particle.offset.y);
var distance = Math.sqrt(Math.abs(dx * dx + dy * dy));
... | {
var _a, _b;
this.container = container;
this.initialPosition = position;
this.options = options;
var size = options.size.value * container.retina.pixelRatio;
var random = typeof options.size.random === "boolean" ? options.size.random : options.size.random.enable;
... | identifier_body |
Absorber.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ColorUtils_1 = require("./Utils/ColorUtils");
var Utils_1 = require("./Utils/Utils");
var Absorber = (function () {
function | (container, options, position) {
var _a, _b;
this.container = container;
this.initialPosition = position;
this.options = options;
var size = options.size.value * container.retina.pixelRatio;
var random = typeof options.size.random === "boolean" ? options.size.random : opt... | Absorber | identifier_name |
Absorber.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ColorUtils_1 = require("./Utils/ColorUtils");
var Utils_1 = require("./Utils/Utils");
var Absorber = (function () {
function Absorber(container, options, position) {
var _a, _b;
this.container = container;
this.... | };
Absorber.prototype.calcPosition = function () {
var _a;
var container = this.container;
var percentPosition = (_a = this.options.position) !== null && _a !== void 0 ? _a : {
x: Math.random() * 100,
y: Math.random() * 100,
};
return {
... | random_line_split | |
test_scale.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 ... |
def testRegression(self):
inputSize = 1024
input = range(inputSize)
factor = 0.5
expected = [factor * n for n in input]
output = Scale(factor=factor, clipping=False)(input)
self.assertEqualVector(output, expected)
def testZero(self):
inputSize ... |
class TestScale(TestCase):
| random_line_split |
test_scale.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 ... | (self):
input = []
expected = input[:]
output = Scale()(input)
self.assertEqualVector(output, input)
def testClipping(self):
inputSize = 1024
maxAbsValue= 10
factor = 1
input = [n + maxAbsValue for n in range(inputSize)]
expected = ... | testEmpty | identifier_name |
test_scale.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 ... |
suite = allTests(TestScale)
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite)
| self.assertConfigureFails(Scale(), { 'maxAbsValue': -1 }) | identifier_body |
test_scale.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 ... | TextTestRunner(verbosity=2).run(suite) | conditional_block | |
index.js | import classnames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import telephonyStatuses from 'ringcentral-integration/enums/telephonyStatus';
import callDirections from 'ringcentral-integration/enums/callDirections';
import CloseIcon from '../../assets/images/CloseIco... |
}
}
renderLogSection() {
const {
formatPhone,
currentLocale,
logNotification,
showNotiLogButton,
onCloseNotification,
onSaveNotification,
onExpandNotification,
onDiscardNotification,
currentNotificationIdentify,
currentSession,
onReject,
... | {
onCloseNotification();
} | conditional_block |
index.js | import classnames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import telephonyStatuses from 'ringcentral-integration/enums/telephonyStatus';
import callDirections from 'ringcentral-integration/enums/callDirections';
import CloseIcon from '../../assets/images/CloseIco... |
renderLogSection() {
const {
formatPhone,
currentLocale,
logNotification,
showNotiLogButton,
onCloseNotification,
onSaveNotification,
onExpandNotification,
onDiscardNotification,
currentNotificationIdentify,
currentSession,
onReject,
onHang... | {
const {
logNotification,
onCloseNotification,
currentNotificationIdentify,
} = nextProps;
if (currentNotificationIdentify) {
const { call = {} } = logNotification;
const { result } = call;
if (result) {
onCloseNotification();
}
}
} | identifier_body |
index.js | import classnames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import telephonyStatuses from 'ringcentral-integration/enums/telephonyStatus';
import callDirections from 'ringcentral-integration/enums/callDirections';
import CloseIcon from '../../assets/images/CloseIco... | <div className={classnames(styles.root)}>
<div className={styles.notificationModal}>
<div className={styles.modalHeader}>
<div className={styles.modalTitle}>{statusI18n}</div>
<div className={styles.modalCloseBtn}>
<Button dataSign="closeButton" onClick={onC... | statusI18n = i18n.getString('ringing', currentLocale);
} else {
statusI18n = i18n.getString('callConnected', currentLocale);
}
return ( | random_line_split |
index.js | import classnames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import telephonyStatuses from 'ringcentral-integration/enums/telephonyStatus';
import callDirections from 'ringcentral-integration/enums/callDirections';
import CloseIcon from '../../assets/images/CloseIco... | () {
const {
formatPhone,
currentLocale,
logNotification,
showNotiLogButton,
onCloseNotification,
onSaveNotification,
onExpandNotification,
onDiscardNotification,
currentNotificationIdentify,
currentSession,
onReject,
onHangup,
shrinkNoti... | renderLogSection | identifier_name |
CumulusCI.py | import logging
from cumulusci.cli.config import CliConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.exceptions import TaskNotFoundError
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.tasks import CURRENT_TASK
from cumulusci.core.utils import import_class
from cumulusci... |
return self._sf
@property
def tooling(self):
if self._tooling is None:
self._tooling = self._init_api('tooling/')
return self._tooling
def set_login_url(self):
""" Sets the LOGIN_URL variable in the suite scope which will
automatically log ... | self._sf = self._init_api() | conditional_block |
CumulusCI.py | import logging
from cumulusci.cli.config import CliConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.exceptions import TaskNotFoundError
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.tasks import CURRENT_TASK
from cumulusci.core.utils import import_class
from cumulusci... |
def run_task(self, task_name, **options):
""" Runs a named CumulusCI task for the current project with optional
support for overriding task options via kwargs.
Examples:
| =Keyword= | =task_name= | =task_options= | =comment= ... | """ Returns the login url which will automatically log into the target
Salesforce org. By default, the org_name passed to the library
constructor is used but this can be overridden with the org option
to log into a different org.
"""
if org is None:
org =... | identifier_body |
CumulusCI.py | import logging
from cumulusci.cli.config import CliConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.exceptions import TaskNotFoundError
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.tasks import CURRENT_TASK
from cumulusci.core.utils import import_class
from cumulusci... | if base_url is not None:
rv.base_url += base_url
return rv
def _init_task(self, class_path, options, task_config):
task_class = import_class(class_path)
task_config = self._parse_task_options(options, task_class, task_config)
return task_class, task_config
d... | rv = Salesforce(
instance=self.org.instance_url.replace('https://', ''),
session_id=self.org.access_token,
version=api_version,
) | random_line_split |
CumulusCI.py | import logging
from cumulusci.cli.config import CliConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.exceptions import TaskNotFoundError
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.tasks import CURRENT_TASK
from cumulusci.core.utils import import_class
from cumulusci... | (self):
if self._org is None:
if CURRENT_TASK and isinstance(CURRENT_TASK, Robot):
# If CumulusCI is running a task, use that task's org
return CURRENT_TASK.org_config
else:
self._org = self.keychain.get_org(self.org_name)
return se... | org | identifier_name |
draw_texture_program_info.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... |
export function texCoords() {
return new Float32Array([
// clang-format off
0, 0,
0, 1,
1, 1,
1, 1,
0, 0,
1, 0,
// clang-format on
]);
}
| {
return new Float32Array([
// clang-format off
-1, -1,
-1, 1,
1, 1,
1, 1,
-1, -1,
1, -1,
// clang-format on
]);
} | identifier_body |
draw_texture_program_info.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | () {
return new Float32Array([
// clang-format off
-1, -1,
-1, 1,
1, 1,
1, 1,
-1, -1,
1, -1,
// clang-format on
]);
}
export function texCoords() {
return new Float32Array([
// clang-format off
0, 0,
0, 1,
1, 1,
1, 1,
0, 0,
1, 0,
// clang-format on
... | vertices | identifier_name |
draw_texture_program_info.ts | /**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | verticalScale}. * -1.), 0, 1);
}`;
}
export function fragmentShaderSource() {
return `#version 300 es
precision highp float;
uniform sampler2D inputTexture;
in vec2 uv;
out vec4 fragColor;
void main() {
vec4 texSample = texture(inputTexture, uv);
fragColor = texSample;
}`;
}
export function vertices() {
... | // Invert geometry to match the image orientation from the camera.
gl_Position = vec4(position * vec2(${horizontalScale}., ${ | random_line_split |
reftest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... |
let parts: ~[&str] = line.split(' ').filter(|p| !p.is_empty()).collect();
if parts.len() != 3 {
fail!("reftest line: '{:s}' doesn't match 'KIND LEFT RIGHT'", line);
}
let kind = match parts[0] {
"==" => Same,
"!=" => Diff... | if line.starts_with("#") {
continue;
} | random_line_split |
reftest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... |
fn capture(reftest: &Reftest, side: uint) -> png::Image {
let filename = format!("/tmp/servo-reftest-{:06u}-{:u}.png", reftest.id, side);
let mut args = reftest.servo_args.clone();
args.push_all_move(~[~"-f", ~"-o", filename.clone(), reftest.files[side].clone()]);
let retval = match Process::status("... | {
let name = reftest.name.clone();
TestDescAndFn {
desc: TestDesc {
name: DynTestName(name),
ignore: false,
should_fail: false,
},
testfn: DynTestFn(proc() {
check_reftest(reftest);
}),
}
} | identifier_body |
reftest.rs | // Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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 ... | (reftest: &Reftest, side: uint) -> png::Image {
let filename = format!("/tmp/servo-reftest-{:06u}-{:u}.png", reftest.id, side);
let mut args = reftest.servo_args.clone();
args.push_all_move(~[~"-f", ~"-o", filename.clone(), reftest.files[side].clone()]);
let retval = match Process::status("./servo", ar... | capture | identifier_name |
models.py | """
Database models for the badges app
"""
from importlib import import_module
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONF... | (image):
"""
Validates that a particular image is small enough to be a badge and square.
"""
if image.width != image.height:
raise ValidationError(_(u"The badge image must be square."))
if not image.size < (250 * 1024):
raise ValidationError(_(u"The badge image file size must be less... | validate_badge_image | identifier_name |
models.py | """
Database models for the badges app
"""
from importlib import import_module
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONF... |
class CourseBadgesDisabledError(Exception):
"""
Exception raised when Course Badges aren't enabled, but an attempt to fetch one is made anyway.
"""
class BadgeClass(models.Model):
"""
Specifies a badge class to be registered with a backend.
"""
slug = models.SlugField(max_length=255, va... | """
Validates that a string is lowercase.
"""
if not string.islower():
raise ValidationError(_(u"This value must be all lowercase.")) | identifier_body |
models.py | """
Database models for the badges app
"""
from importlib import import_module
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONF... | def __unicode__(self):
return u"<Badge '{slug}' for '{issuing_component}'>".format(
slug=self.slug, issuing_component=self.issuing_component
)
@classmethod
def get_badge_class(
cls, slug, issuing_component, display_name=None, description=None, criteria=None, image_fi... | random_line_split | |
models.py | """
Database models for the badges app
"""
from importlib import import_module
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONF... |
specs = [line.split(',', 1) for line in specs.splitlines()]
return {
slug.strip().lower(): [CourseKey.from_string(key.strip()) for key in keys.strip().split(',')]
for slug, keys in specs
}
def clean_fields(self, exclude=tuple()):
"""
Verify the setti... | return {} | conditional_block |
unsized3.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 ... | <T> {
f: [T],
}
struct Bar {
f1: usize,
f2: [usize],
}
struct Baz {
f1: usize,
f2: str,
}
trait Tr {
fn foo(&self) -> usize;
}
struct St {
f: usize
}
impl Tr for St {
fn foo(&self) -> usize {
self.f
}
}
struct Qux<'a> {
f: Tr+'a
}
pub fn main() {
let _: &Foo<f6... | Foo | identifier_name |
unsized3.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 ... | let x: &Baz = mem::transmute(slice::from_raw_parts(&*data, 5));
assert!(x.f1 == 42);
let chs: Vec<char> = x.f2.chars().collect();
assert!(chs.len() == 5);
assert!(chs[0] == 'a');
assert!(chs[1] == 'b');
assert!(chs[2] == 'c');
assert!(chs[3] == 'd');
... | let data: Box<_> = box Baz_ {
f1: 42, f2: ['a' as u8, 'b' as u8, 'c' as u8, 'd' as u8, 'e' as u8] }; | random_line_split |
rpc.rs | extern crate crypto;
use bytes::BytesMut;
use crypto::digest::Digest;
use encoding::{all::ISO_8859_1, DecoderTrap, EncoderTrap, Encoding};
use futures::SinkExt;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpStream,
stream::StreamExt,
};
use tokio_util::codec::{Decoder, Encoder, Framed};
use tracing::*;... | <Io> {
conn: Framed<Io, BoincCodec>,
}
impl DaemonStream<TcpStream> {
pub async fn connect(host: String, password: Option<String>) -> Result<Self, Error> {
Self::authenticate(TcpStream::connect(host).await?, password).await
}
}
impl<Io: AsyncRead + AsyncWrite + Unpin> DaemonStream<Io> {
async ... | DaemonStream | identifier_name |
rpc.rs | extern crate crypto;
use bytes::BytesMut;
use crypto::digest::Digest;
use encoding::{all::ISO_8859_1, DecoderTrap, EncoderTrap, Encoding};
use futures::SinkExt;
use tokio::{
io::{AsyncRead, AsyncWrite},
net::TcpStream,
stream::StreamExt,
};
use tokio_util::codec::{Decoder, Encoder, Framed};
use tracing::*;... |
pub(crate) async fn query(
&mut self,
request_data: Vec<treexml::Element>,
) -> Result<Vec<treexml::Element>, Error> {
self.conn.send(request_data).await?;
let data = self
.conn
.try_next()
.await?
.ok_or_else(|| Error::DaemonError... | random_line_split | |
app.component.ts | import { Component, OnInit, HostListener, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from "@angular/forms";
import { hexToHsl, rgbToHsl, hexToRgb } from '../common/color-conversion';
import { MdDialog, MdDialogRef, MdDialogConfig} from "@angular/material";
@Component({... | modalRef.componentInstance.hslArr2 = this.hslArr2;
modalRef.componentInstance.hslArr3 = this.hslArr3;
}
}
@Component({
selector: 'photo-modal',
templateUrl: './photo-modal.html',
styleUrls: ['./app.component.css']
})
export class PhotoModalComponent {
@Input() hslArr1: Array<any>;
@Input() hslArr2... | config.height = `400px`;
config.disableClose = true;
let modalRef: MdDialogRef<PhotoModalComponent> = this.modal.open(PhotoModalComponent, config);
modalRef.componentInstance.hslArr1 = this.hslArr1; | random_line_split |
app.component.ts | import { Component, OnInit, HostListener, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from "@angular/forms";
import { hexToHsl, rgbToHsl, hexToRgb } from '../common/color-conversion';
import { MdDialog, MdDialogRef, MdDialogConfig} from "@angular/material";
@Component({... | (public modalRef: MdDialogRef<PhotoModalComponent>) {
}
} | constructor | identifier_name |
app.component.ts | import { Component, OnInit, HostListener, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from "@angular/forms";
import { hexToHsl, rgbToHsl, hexToRgb } from '../common/color-conversion';
import { MdDialog, MdDialogRef, MdDialogConfig} from "@angular/material";
@Component({... |
}
openSnackBar(val) {
// Get the snackbar DIV
let x = document.getElementById("snackbar")
// Add the "show" class to DIV
x.className = "show";
this.selectedColor = val;
// After 2 seconds, remove the show class from DIV
setTimeout(function () {
x.className = x.className.replace... | {
tmpHue = Math.ceil((this.baseHslArr2[i][0] - 3.6) % 360);
tmpSaturation = this.baseHslArr2[i][1];
if ((this.baseHslArr2[i][1] + 1) <= 100) {
tmpSaturation = (this.baseHslArr2[i][1] + 1);
}
tmpLightness = this.baseHslArr2[i][2];
if ((this.baseHslArr2[i][2] - 13 ) >= 0) {
... | conditional_block |
app.component.ts | import { Component, OnInit, HostListener, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from "@angular/forms";
import { hexToHsl, rgbToHsl, hexToRgb } from '../common/color-conversion';
import { MdDialog, MdDialogRef, MdDialogConfig} from "@angular/material";
@Component({... |
ngOnInit(): void {
this.buildForm();
this.tmpHsl = [];
this.baseHsl = '';
this.baseHslArr2 = [];
this.hslArr1 = [];
this.hslArr2 = [];
this.hslArr3 = [];
this.row1ShowBtnCopy = [false, false, false, false, false, false, false, false, false];
this.row2ShowBtnCopy = [false, false, ... | {
this.hexToHsl = hexToHsl;
} | identifier_body |
placement-in-syntax.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 ... | //
// Compare with new-box-syntax.rs
use std::boxed::{Box, HEAP};
struct Structure {
x: isize,
y: isize,
}
pub fn main() {
let x: Box<isize> = in HEAP { 2 };
let b: Box<isize> = in HEAP { 1 + 2 };
let c = in HEAP { 3 + 4 };
let s: Box<Structure> = in HEAP {
Structure {
x:... |
// Tests that the new `in` syntax works with unique pointers. | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.