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 |
|---|---|---|---|---|
values.rs | unwrap();
s
}
}
impl<'a, T> ToCss for &'a T where T: ToCss + ?Sized {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write |
}
impl ToCss for str {
#[inline]
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
serialize_string(self, dest)
}
}
impl ToCss for String {
#[inline]
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write {
serialize_string(self, dest... | {
(*self).to_css(dest)
} | identifier_body |
values.rs | .take() {
// See comment in `write_str`.
if !prefix.is_empty() {
self.inner.write_str(prefix)?;
}
}
self.inner.write_char(c)
}
}
#[macro_export]
macro_rules! serialize_function {
($dest: expr, $name: ident($( $arg: expr, )+)) => {
seri... | }
}
impl<T> ToCss for Box<T> where T: ?Sized + ToCss {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result | random_line_split | |
contact.ts | import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { TripDetailsPage } from '../trip-details/trip-details';
@Component({
selector: 'page-contact',
templateUrl: 'contact.html'
})
export class ContactPage {
items;
http;
items... |
}
}
| {
this.items = this.items.filter((item) => {
return (item['address-to'].toLowerCase().indexOf(val.toLowerCase()) > -1);
})
} | conditional_block |
contact.ts | import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { TripDetailsPage } from '../trip-details/trip-details'; | templateUrl: 'contact.html'
})
export class ContactPage {
items;
http;
itemsFromWS: any;
constructor(public navController: NavController, private httpParam: Http) {
this.http = httpParam;
this.initializeItems();
}
initializeItems() {
this.http.get("http://87.98.212.102:8080/WorkshopI5/ws/tri... |
@Component({
selector: 'page-contact', | random_line_split |
contact.ts | import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { TripDetailsPage } from '../trip-details/trip-details';
@Component({
selector: 'page-contact',
templateUrl: 'contact.html'
})
export class ContactPage {
items;
http;
items... |
getItems(ev) {
// reset the set
this.items = this.itemsFromWS;
// set val to the value of the ev target
var val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item[... | {
this.navController.push(TripDetailsPage, {
tripObjectSend: trip
});
} | identifier_body |
contact.ts | import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { NavController } from 'ionic-angular';
import { TripDetailsPage } from '../trip-details/trip-details';
@Component({
selector: 'page-contact',
templateUrl: 'contact.html'
})
export class ContactPage {
items;
http;
items... | (refresher) {
this.initializeItems();
refresher.complete();
}
goTripDetails(trip) {
this.navController.push(TripDetailsPage, {
tripObjectSend: trip
});
}
getItems(ev) {
// reset the set
this.items = this.itemsFromWS;
// set val to the value of the ev target
var val = e... | doRefresh | identifier_name |
regress-223535.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | ()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
testRegExp(statusmessages, patterns, strings, actualmatches, expectedmatches);
exitFunc ('test');
}
| test | identifier_name |
regress-223535.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | addThis();
status = inSection(3);
pattern = /|/;
actualmatch = string.match(pattern);
expectedmatch = Array('');
addThis();
status = inSection(4);
pattern = /(a|)/;
actualmatch = string.match(pattern);
expectedmatch = Array('a', 'a');
addThis();
status = inSection(5);
pattern = /(a||)/;
actualmatch = string.match(pa... |
status = inSection(2);
pattern = /|a/;
actualmatch = string.match(pattern);
expectedmatch = Array(''); | random_line_split |
regress-223535.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
testRegExp(statusmessages, patterns, strings, actualmatches, expectedmatches);
exitFunc ('test');
}
| {
statusmessages[i] = status;
patterns[i] = pattern;
strings[i] = string;
actualmatches[i] = actualmatch;
expectedmatches[i] = expectedmatch;
i++;
} | identifier_body |
help.rs | use super::{cd, ls, echo};
pub fn | (args: Vec<String>) {
if args.len() > 0 {
match args[0].as_ref() {
"cd" => cd::help(),
"ls" => ls::help(),
"echo" => echo::help(),
_ => println!("Command not found")
}
} else {
println!("
I wrote this program to learn Rust.\n\n
use help... | exec | identifier_name |
help.rs | use super::{cd, ls, echo};
pub fn exec(args: Vec<String>) | Anything that's not an option, is a parameter\n\n
Complex things like pipes are not implemented.\n
Commands:\n
cd, ls, pwd\n");
}
}
| {
if args.len() > 0 {
match args[0].as_ref() {
"cd" => cd::help(),
"ls" => ls::help(),
"echo" => echo::help(),
_ => println!("Command not found")
}
} else {
println!("
I wrote this program to learn Rust.\n\n
use help <command> for info ... | identifier_body |
help.rs | use super::{cd, ls, echo};
pub fn exec(args: Vec<String>) {
if args.len() > 0 {
match args[0].as_ref() {
"cd" => cd::help(),
"ls" => ls::help(),
"echo" => echo::help(),
_ => println!("Command not found")
}
} else {
println!("
I wrote th... | Commands:\n
cd, ls, pwd\n");
}
} | Parameters:\n
Anything that's not an option, is a parameter\n\n
Complex things like pipes are not implemented.\n | random_line_split |
ComboChartDemoWebPart.ts | import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
} from '@microsoft/sp-webpart-base';
import { PropertyPaneWebPartInformation } from '@pnp/spfx-property-controls/lib/PropertyPaneWe... | }
]
}
]
};
}
} | key: 'webPartInfoId'
})
] | random_line_split |
ComboChartDemoWebPart.ts | import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
} from '@microsoft/sp-webpart-base';
import { PropertyPaneWebPartInformation } from '@pnp/spfx-property-controls/lib/PropertyPaneWe... | (): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
groups: [
{
groupFields: [
PropertyPaneWebPartInformation({
description: strings.WebPar... | dataVersion | identifier_name |
ComboChartDemoWebPart.ts | import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
} from '@microsoft/sp-webpart-base';
import { PropertyPaneWebPartInformation } from '@pnp/spfx-property-controls/lib/PropertyPaneWe... |
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
groups: [
{
groupFields: [
PropertyPaneWebPartInformation({
description: strings.WebPartDescription,
moreInfoLink: stri... | {
return Version.parse('1.0');
} | identifier_body |
main.js | import Koa from 'koa';
import convert from 'koa-convert';
import webpack from 'webpack';
import webpackConfig from '../build/webpack.config';
import historyApiFallback from 'koa-connect-history-api-fallback';
import serve from 'koa-static';
import _debug from 'debug';
import config from '../config';
import webpackProxy... |
// Serving ~/dist by default. Ideally these files should be served by
// the web server and not the app server, but this helps to demo the
// server in production.
app.use(convert(serve(paths.base(config.dir_dist))));
}
export default app; | 'Server is being run outside of live development mode. This starter kit ' +
'does not provide any production-ready server functionality. To learn ' +
'more about deployment strategies, check out the "deployment" section ' +
'in the README.'
); | random_line_split |
main.js | import Koa from 'koa';
import convert from 'koa-convert';
import webpack from 'webpack';
import webpackConfig from '../build/webpack.config';
import historyApiFallback from 'koa-connect-history-api-fallback';
import serve from 'koa-static';
import _debug from 'debug';
import config from '../config';
import webpackProxy... |
export default app;
| {
debug(
'Server is being run outside of live development mode. This starter kit ' +
'does not provide any production-ready server functionality. To learn ' +
'more about deployment strategies, check out the "deployment" section ' +
'in the README.'
);
// Serving ~/dist by default. Ideally these ... | conditional_block |
topic-domain.constants.ts | // Copyright 2018 The Oppia Authors. 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 ap... | SUBTOPIC_PAGE_PROPERTY_PAGE_CONTENTS_AUDIO: 'page_contents_audio'
} as const; | SUBTOPIC_PROPERTY_THUMBNAIL_BG_COLOR: 'thumbnail_bg_color',
SUBTOPIC_PROPERTY_TITLE: 'title',
SUBTOPIC_PROPERTY_URL_FRAGMENT: 'url_fragment',
SUBTOPIC_PAGE_PROPERTY_PAGE_CONTENTS_HTML: 'page_contents_html', | random_line_split |
animation.rs | use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection};
use crate::radians::Radians;
use crate::{Distance, Point};
use super::HandlerError;
use super::super::{
event_loop_notifier::EventLoopNotifier,
state::TurtleState,
app::{TurtleId, App},
animation::{MoveAnimation, RotateA... |
Ok(())
}
pub(crate) fn rotate_in_place(
conn: ServerOneshotSender,
app: &mut App,
event_loop: &EventLoopNotifier,
anim_runner: &AnimationRunner,
id: TurtleId,
angle: Radians,
direction: RotationDirection,
) -> Result<(), HandlerError> {
let turtle = app.turtle_mut(id);
let an... | {
// Instant animations complete right away and don't need to be queued
// Signal the main thread that the image has changed
event_loop.request_redraw()?;
conn.send(ServerResponse::AnimationComplete(id))?;
} | conditional_block |
animation.rs | use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection};
use crate::radians::Radians;
use crate::{Distance, Point};
use super::HandlerError;
use super::super::{
event_loop_notifier::EventLoopNotifier,
state::TurtleState,
app::{TurtleId, App},
animation::{MoveAnimation, RotateA... | event_loop.request_redraw()?;
conn.send(ServerResponse::AnimationComplete(id))?;
}
Ok(())
}
pub(crate) fn rotate_in_place(
conn: ServerOneshotSender,
app: &mut App,
event_loop: &EventLoopNotifier,
anim_runner: &AnimationRunner,
id: TurtleId,
angle: Radians,
directi... | // Instant animations complete right away and don't need to be queued
// Signal the main thread that the image has changed | random_line_split |
animation.rs | use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection};
use crate::radians::Radians;
use crate::{Distance, Point};
use super::HandlerError;
use super::super::{
event_loop_notifier::EventLoopNotifier,
state::TurtleState,
app::{TurtleId, App},
animation::{MoveAnimation, RotateA... | (
conn: ServerOneshotSender,
app: &mut App,
display_list: &mut DisplayList,
event_loop: &EventLoopNotifier,
anim_runner: &AnimationRunner,
id: TurtleId,
distance: Distance,
) -> Result<(), HandlerError> {
let turtle = app.turtle_mut(id);
let TurtleState {position, heading, ..} = tur... | move_forward | identifier_name |
animation.rs | use crate::ipc_protocol::{ServerOneshotSender, ServerResponse, RotationDirection};
use crate::radians::Radians;
use crate::{Distance, Point};
use super::HandlerError;
use super::super::{
event_loop_notifier::EventLoopNotifier,
state::TurtleState,
app::{TurtleId, App},
animation::{MoveAnimation, RotateA... |
pub(crate) fn rotate_in_place(
conn: ServerOneshotSender,
app: &mut App,
event_loop: &EventLoopNotifier,
anim_runner: &AnimationRunner,
id: TurtleId,
angle: Radians,
direction: RotationDirection,
) -> Result<(), HandlerError> {
let turtle = app.turtle_mut(id);
let anim = RotateAni... | {
let turtle = app.turtle_mut(id);
let anim = MoveAnimation::new(turtle, display_list, target_pos);
if anim.is_running() {
anim_runner.play(id, anim, conn.client_id());
} else {
// Instant animations complete right away and don't need to be queued
// Signal the main thread tha... | identifier_body |
add.js | //# sourceURL=add.js
$(function () {
$("#frm").jValidate({
rules:{
name:{
required:true,
minlength:2,
maxlength:32,
stringCheck:true
},
code:{
required:true,
minlength:2,
... | email:{
email:true,
minlength:8,
maxlength:32
},
remark:{
minlength:2,
maxlength:128
}
},
messages:{
code:{
checkRepeat1:"快递公司编码已经存在",
... | random_line_split | |
add.js | //# sourceURL=add.js
$(function () {
$("#frm").jValidate({
rules:{
name:{
required:true,
minlength:2,
maxlength:32,
stringCheck:true
},
code:{
required:true,
minlength:2,
... | lick(function(){
$('#frm').resetForm();
})
}) | 保存成功');
$('#frm').resetForm();
}
}
})
});
$('#reset').c | conditional_block |
ScoreCaculating.py | import math
import sys
sys.path.append('..')
import Analyse.AFX as AFX
class State:
def __init__(self):
self.SenShifterState = True
self.MoodStrength = 1.0
self.positive = 0.0
self.negative = 0.0
def Process(self, score):
|
def Clear(self):
self.SenShifterState = True
self.MoodStrength = 1.0
self.positive = 0.0
self.negative = 0.0
def ChangeMood(self,mood):
if mood.startswith('I'):
self.MoodStrength *= 2
if mood.startswith('D'):
self.MoodStrength /= 2
def returnScore(self):
score = self.positive - self.negative
... | if self.SenShifterState is True:
self.positive += score
else:
self.negative += score | identifier_body |
ScoreCaculating.py | import math
import sys
sys.path.append('..')
import Analyse.AFX as AFX
class State:
def __init__(self):
self.SenShifterState = True
self.MoodStrength = 1.0
self.positive = 0.0
self.negative = 0.0
def Process(self, score):
if self.SenShifterState is True:
self.positive += score
else:
self.negative ... | (self):
self.SenShifterState = True
self.MoodStrength = 1.0
self.positive = 0.0
self.negative = 0.0
def ChangeMood(self,mood):
if mood.startswith('I'):
self.MoodStrength *= 2
if mood.startswith('D'):
self.MoodStrength /= 2
def returnScore(self):
score = self.positive - self.negative
score *= sel... | Clear | identifier_name |
ScoreCaculating.py | import math
import sys
sys.path.append('..')
import Analyse.AFX as AFX
class State:
def __init__(self):
self.SenShifterState = True
self.MoodStrength = 1.0
self.positive = 0.0
self.negative = 0.0
def Process(self, score):
if self.SenShifterState is True:
self.positive += score
else:
self.negative ... | #if the word has no orientation or it is a boring word, just ignore it
if tag == 0.0 or tag is "Bor":
continue
if tag is "Con":
S.Clear()
elif tag is "Neg":
#if there is a negative tagged here, change the state of Sentiment Shifter
S.SenShifterState = -S.SenShifterState
elif tag is "Inc" or tag is... | S = State()
for word in Sentence:
tag = AFX.GetWord(word,'Tag') | random_line_split |
ScoreCaculating.py | import math
import sys
sys.path.append('..')
import Analyse.AFX as AFX
class State:
def __init__(self):
self.SenShifterState = True
self.MoodStrength = 1.0
self.positive = 0.0
self.negative = 0.0
def Process(self, score):
if self.SenShifterState is True:
self.positive += score
else:
self.negative ... |
pass
#Most people don't like rainy, even if I like the weather quite much.
| if Sen != []:
if AFX.GetWord(Sen[0],'Tag') is "Con":
word = AFX.GetWord(Sen[0],'Word')
print Sen
print CaculateASentence(Sen)
++counter | conditional_block |
dialog-preset.d.ts | import { Type } from '@angular/core'; | import { VEXModalContext, VEXModalContextBuilder } from '../modal-context';
import { Modal } from '../modal';
import { VEXButtonHandler, VEXButtonConfig } from '../dialog-form-modal';
/**
* Data definition
*/
export declare class DialogPreset extends VEXModalContext {
defaultResult: any;
content: Type<any>;
... | import { FluentAssignMethod } from 'angular2-modal'; | random_line_split |
dialog-preset.d.ts | import { Type } from '@angular/core';
import { FluentAssignMethod } from 'angular2-modal';
import { VEXModalContext, VEXModalContextBuilder } from '../modal-context';
import { Modal } from '../modal';
import { VEXButtonHandler, VEXButtonConfig } from '../dialog-form-modal';
/**
* Data definition
*/
export declare cla... | <T extends DialogPreset> extends VEXModalContextBuilder<T> {
/**
* the message to display on the modal.
*/
content: FluentAssignMethod<Type<any>, this>;
constructor(modal: Modal, defaultValues?: T, initialSetters?: string[], baseType?: new () => T);
addButton(css: string, caption: string, onCl... | DialogPresetBuilder | identifier_name |
reframe.js | /**
reframe.js - Reframe.js: responsive iframes for embedded content
@version v3.0.0
@link https://github.com/yowainwright/reframe.ts#readme
@author Jeff Wainwright <yowainwright@gmail.com> (http://jeffry.in)
@license MIT
**/
(function (global, factory) {
typeof exports === 'object' && typeof module !== '... | var divStyles = div.style;
divStyles.position = 'relative';
divStyles.width = '100%';
divStyles.paddingTop = padding + "%";
// set necessary styles of targeted <element>
var frameStyle = frame.style;
frameStyle.position = 'absolute';
... | var _a, _b;
if (cName === void 0) { cName = 'js-reframe'; }
var frames = __spreadArrays((typeof target === 'string' ? document.querySelectorAll(target) : target));
var c = cName || 'js-reframe';
for (var i = 0; i < frames.length; i += 1) {
var frame = frames[i];
... | identifier_body |
reframe.js | /**
reframe.js - Reframe.js: responsive iframes for embedded content
@version v3.0.0
@link https://github.com/yowainwright/reframe.ts#readme
@author Jeff Wainwright <yowainwright@gmail.com> (http://jeffry.in)
@license MIT
**/
(function (global, factory) {
typeof exports === 'object' && typeof module !== '... | rget, cName) {
var _a, _b;
if (cName === void 0) { cName = 'js-reframe'; }
var frames = __spreadArrays((typeof target === 'string' ? document.querySelectorAll(target) : target));
var c = cName || 'js-reframe';
for (var i = 0; i < frames.length; i += 1) {
var frame = f... | rame(ta | identifier_name |
reframe.js | /**
reframe.js - Reframe.js: responsive iframes for embedded content
@version v3.0.0
@link https://github.com/yowainwright/reframe.ts#readme
@author Jeff Wainwright <yowainwright@gmail.com> (http://jeffry.in)
@license MIT
**/ | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.reframe = factory());
}(this, (function () { 'use strict';
/*! **********************... | random_line_split | |
07_kudo.js | exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('kudo').del()
.then(function () {
// Inserts seed entries
return knex('kudo').insert([
{
body: "Hey thanks for help on the ERD's",
to_user_id: 2,
from_user_id: 1,
votes: 5,
... | votes: 5,
created_at: "Today",
from: "devin-h",
to: "jordan-f"
}
]);
});
}; | {
body: "Hey thanks for help on the ERD'sn",
to_user_id: 3,
from_user_id: 2, | random_line_split |
add_video.py | # encoding: utf-8
from django.core.management.base import NoArgsCommand
from optparse import make_option
from video.management.commands.sub_commands.AddVideo import AddVideo
class Command(NoArgsCommand):
| print av.ans
| option_list = NoArgsCommand.option_list + (
make_option('--video-link',action='store',dest='video-link',
help="link to the video, use --list-types to see a list of supported link types"),
make_option('--list-types',action='store_true',dest='list-types',
help="list supported video... | identifier_body |
add_video.py | # encoding: utf-8
from django.core.management.base import NoArgsCommand
from optparse import make_option
from video.management.commands.sub_commands.AddVideo import AddVideo
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--video-link',action='store',dest='video-lin... | (self, **options):
if options.get('list-types',False):
print """Supported link formats:
youtube - http://www.youtube.com/watch?v=2sASREICzqY"""
else:
av=AddVideo(options)
av.run()
print av.ans
| handle_noargs | identifier_name |
add_video.py | # encoding: utf-8
from django.core.management.base import NoArgsCommand
from optparse import make_option
from video.management.commands.sub_commands.AddVideo import AddVideo
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--video-link',action='store',dest='video-lin... | make_option('--object-id',action='store',dest='object-id',
help="set the object id that the video will be related to"),
make_option('--sticky',action='store_true',dest='is_sticky',
help="set the video as sticky"),
)
def handle_noargs(self, **options):
if options.... | make_option('--list-types',action='store_true',dest='list-types',
help="list supported video link types and formats"),
make_option('--object-type',action='store',dest='object-type',
help="set the object type, currently only member is supported"), | random_line_split |
add_video.py | # encoding: utf-8
from django.core.management.base import NoArgsCommand
from optparse import make_option
from video.management.commands.sub_commands.AddVideo import AddVideo
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--video-link',action='store',dest='video-lin... |
else:
av=AddVideo(options)
av.run()
print av.ans
| print """Supported link formats:
youtube - http://www.youtube.com/watch?v=2sASREICzqY""" | conditional_block |
disk_usage_test.py | # Copyright 2016 The TensorFlow Authors. 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 applica... | googletest.main() | conditional_block | |
disk_usage_test.py | # Copyright 2016 The TensorFlow Authors. 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 applica... |
def testHookExceedingLimit(self):
def _watch_fn(fetches, feeds):
del fetches, feeds
return "DebugIdentity", r".*delta.*", r".*"
dumping_hook = hooks.DumpingDebugHook(
self.session_root, watch_fn=_watch_fn, log_usage=False)
mon_sess = monitored_session._HookedSession(self.sess, [dumpi... | def _watch_fn(fetches, feeds):
del fetches, feeds
return "DebugIdentity", r".*delta.*", r".*"
dumping_hook = hooks.DumpingDebugHook(
self.session_root, watch_fn=_watch_fn, log_usage=False)
mon_sess = monitored_session._HookedSession(self.sess, [dumping_hook])
mon_sess.run(self.inc_v) | identifier_body |
disk_usage_test.py | # Copyright 2016 The TensorFlow Authors. 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 applica... | self.sess.run(self.v.initializer)
def testWrapperSessionNotExceedingLimit(self):
def _watch_fn(fetches, feeds):
del fetches, feeds
return "DebugIdentity", r"(.*delta.*|.*inc_v.*)", r".*"
sess = dumping_wrapper.DumpingDebugWrapperSession(
self.sess, session_root=self.session_root,
... | self.dec_v = state_ops.assign_add(self.v, self.eta, name="dec_v")
self.sess = session.Session() | random_line_split |
disk_usage_test.py | # Copyright 2016 The TensorFlow Authors. 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 applica... | (fetches, feeds):
del fetches, feeds
return "DebugIdentity", r"(.*delta.*|.*inc_v.*)", r".*"
sess = dumping_wrapper.DumpingDebugWrapperSession(
self.sess, session_root=self.session_root,
watch_fn=_watch_fn, log_usage=False)
sess.run(self.inc_v)
def testWrapperSessionExceedingLimit... | _watch_fn | identifier_name |
container.py | # This program 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 later version.
#
# This program is distributed in the hope that it will be... | def __init__(self, bulk, max_bulk):
self.bulk = bulk
self.max_bulk = max_bulk
def __str__(self):
return "Item would exceed the bulk limit of the container."
class NoFreeSlotError(Exception):
"""Error that gets raised when the container has no free slots."""
def __str__(s... |
class BulkLimitError(Exception):
"""Error that gets raised when the item would exceed the
bulk limit of the container."""
| random_line_split |
container.py | # This program 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 later version.
#
# This program is distributed in the hope that it will be... | """Puts the item at the given slot in the container.
Returns the item previously at the slot."""
if slot == -1:
slot = get_free_slot(container)
total_bulk = get_total_bulk(container)
total_bulk += item.bulk
old_item = get_item(container, slot)
if old_item:
total_bulk -= old_item.... | identifier_body | |
container.py | # This program 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 later version.
#
# This program is distributed in the hope that it will be... | (container):
"""Returns the first slot of the container that is not occupied."""
index = 0
for child in container.children:
if not child:
return index
index += 1
raise NoFreeSlotError
def get_total_bulk(container):
"""Returns the bulk of all items in the container."""
... | get_free_slot | identifier_name |
container.py | # This program 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 later version.
#
# This program is distributed in the hope that it will be... |
return item
def put_item(container, item, slot=-1):
"""Puts the item at the given slot in the container.
Returns the item previously at the slot."""
if slot == -1:
slot = get_free_slot(container)
total_bulk = get_total_bulk(container)
total_bulk += item.bulk
old_item = get_item(con... | remove_item(container, slot_or_type) | conditional_block |
DataSourceFilter.d.ts | export = DataSourceFilter;
declare function DataSourceFilter(name: string, type: string): void;
declare class | {
constructor(name: string, type: string);
onAfterLoadDefaultValue: Event;
propertiesToAssign_: any;
group: string;
size: number;
rangeLimit: typeof Limit;
value: any;
private normalizeValue_;
newFiltersToRange(): DataSourceFilter[];
newFilterToRange(rangeSuffix: string): DataSo... | DataSourceFilter | identifier_name |
DataSourceFilter.d.ts | export = DataSourceFilter;
declare function DataSourceFilter(name: string, type: string): void;
declare class DataSourceFilter {
constructor(name: string, type: string);
onAfterLoadDefaultValue: Event;
propertiesToAssign_: any;
group: string;
size: number;
rangeLimit: typeof Limit;
value: an... | DDMM: number;
MMYYYY: number;
WWYYYY: number;
YYYYWW: number;
MMMYYYY: number;
}
| {
DDD_DDDDD: number;
DDD_MM_MMM_DIR: number;
DDD_MM_SS_S_DIR: number;
}
| {
... | classKey: number;
lookupType: number;
displayFormat:
| {
DDMMYYYY: number; | random_line_split |
reflection_capabilities.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {global, isFunction, isPresent, stringify} from '../facade/lang';
import {Type} from '../type';
import {Plat... | (type: any): string {
// StaticSymbol
if (typeof type === 'object' && type['filePath']) {
return type['filePath'];
}
// Runtime type
return `./${stringify(type)}`;
}
resolveIdentifier(name: string, moduleUrl: string, runtime: any): any { return runtime; }
resolveEnum(enumIdentifier: any... | importUri | identifier_name |
reflection_capabilities.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {global, isFunction, isPresent, stringify} from '../facade/lang';
import {Type} from '../type';
import {Plat... |
for (var i = 0; i < result.length; i++) {
// TS outputs Object for parameters without types, while Traceur omits
// the annotations. For now we preserve the Traceur behavior to aid
// migration, but this can be revisited.
if (typeof paramTypes === 'undefined') {
result[i] = [];
... | {
result = new Array(paramTypes.length);
} | conditional_block |
reflection_capabilities.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {global, isFunction, isPresent, stringify} from '../facade/lang';
import {Type} from '../type';
import {Plat... | var annotations = this._reflect.getMetadata('annotations', typeOrFunc);
if (isPresent(annotations)) return annotations;
}
return [];
}
propMetadata(typeOrFunc: any): {[key: string]: any[]} {
// Prefer the direct API.
if (isPresent((<any>typeOrFunc).propMetadata)) {
var propMetadat... | }
// API for metadata created by invoking the decorators.
if (isPresent(this._reflect) && isPresent(this._reflect.getMetadata)) { | random_line_split |
theme-icon-styles.component.ts | /*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... |
}
get selectedStyle(): IconStyle {
return this._selectedStyle;
}
set selectedStyle(style: IconStyle) {
this._selectedStyle = style;
}
onClick(style: IconStyle) {
this.selectStyle.emit(style);
}
}
| {
this.fontFamily = ds.icons;
const { family } = this.fontFamily;
this.selectedStyle = ICON_FONT_FAMILY_STYLE_MAP[family];
} | conditional_block |
theme-icon-styles.component.ts | /*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | ICON_FONT_FAMILY_CLASS_MAP,
ICON_FONT_FAMILY_STYLE_MAP,
MATERIAL_ICONS,
} from 'cd-themes';
@Component({
selector: 'app-theme-icon-styles',
templateUrl: './theme-icon-styles.component.html',
styleUrls: ['./theme-icon-styles.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export clas... | ICON_STYLE_CLASSES, | random_line_split |
theme-icon-styles.component.ts | /*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... |
set selectedStyle(style: IconStyle) {
this._selectedStyle = style;
}
onClick(style: IconStyle) {
this.selectStyle.emit(style);
}
}
| {
return this._selectedStyle;
} | identifier_body |
theme-icon-styles.component.ts | /*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | (ds: cd.IDesignSystem | undefined) {
if (ds && ds.icons) {
this.fontFamily = ds.icons;
const { family } = this.fontFamily;
this.selectedStyle = ICON_FONT_FAMILY_STYLE_MAP[family];
}
}
get selectedStyle(): IconStyle {
return this._selectedStyle;
}
set selectedStyle(style: IconStyl... | designSystem | identifier_name |
statistics.rs | /* Copyright 2013 Leon Sixt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wr... | }
}
fn leafs(&self) -> uint {
self.leafs.load(Relaxed)
}
fn inc_leafs(&self) {
unsafe {
cast::transmute_mut(&self.leafs).fetch_add(1, Relaxed);
}
}
fn dec_leafs(&self){
unsafe {
cast::transmute_mut(&self.leafs).fetch_sub(1, Relaxed... | unsafe {
cast::transmute_mut(&self.inodes).fetch_sub(1, Relaxed); | random_line_split |
statistics.rs | /* Copyright 2013 Leon Sixt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wr... |
fn inc_elements(&self){
unsafe {
cast::transmute_mut(&self.elements).fetch_add(1, Relaxed);
}
}
fn dec_elements(&self){
unsafe {
cast::transmute_mut(&self.elements).fetch_sub(1, Relaxed);
}
}
fn insertions(&self) -> uint {
self.inserti... | {
self.elements.load(Relaxed)
} | identifier_body |
statistics.rs | /* Copyright 2013 Leon Sixt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in wr... | (&self) {
unsafe {
cast::transmute_mut(&self.insertions).fetch_add(1, Relaxed);
}
}
fn deletions(&self) -> uint {
self.deletions.load(Relaxed)
}
fn inc_deletions(&self) {
unsafe {
cast::transmute_mut(&self.deletions).fetch_add(1, Relaxed);
... | inc_insertions | identifier_name |
main.rs | #[derive(Debug)]
struct Item {
name: String,
price: usize,
damage: usize,
armor: usize,
}
impl Item {
fn | (name: &str, price: usize, damage: usize, armor: usize) -> Item {
Item { name: name.to_string(), price: price, damage: damage, armor: armor }
}
}
fn players_wins(inventory: &[&Item]) -> bool {
let enemy_hit_points = 109;
let enemy_damage = 8;
let enemy_armor = 2;
let player_hit_points = 10... | new | identifier_name |
main.rs | #[derive(Debug)]
struct Item {
name: String,
price: usize,
damage: usize,
armor: usize,
}
impl Item {
fn new(name: &str, price: usize, damage: usize, armor: usize) -> Item {
Item { name: name.to_string(), price: price, damage: damage, armor: armor }
}
}
fn players_wins(inventory: &[&It... | println!("Smallest amount to win: {}", min_price);
println!("Biggest amount to lose: {}", max_price);
} | }
}
| random_line_split |
main.rs | #[derive(Debug)]
struct Item {
name: String,
price: usize,
damage: usize,
armor: usize,
}
impl Item {
fn new(name: &str, price: usize, damage: usize, armor: usize) -> Item {
Item { name: name.to_string(), price: price, damage: damage, armor: armor }
}
}
fn players_wins(inventory: &[&It... | ;
let rounds_for_player_to_win = 1 + (enemy_hit_points - 1) / actual_player_damage;
let rounds_for_enemy_to_win = 1 + (player_hit_points - 1) / actual_enemy_damage;
rounds_for_player_to_win <= rounds_for_enemy_to_win
}
fn total_price(inventory: &[&Item]) -> usize {
inventory.iter().map(|item| item.pr... | { 1 } | conditional_block |
main.rs | #[derive(Debug)]
struct Item {
name: String,
price: usize,
damage: usize,
armor: usize,
}
impl Item {
fn new(name: &str, price: usize, damage: usize, armor: usize) -> Item |
}
fn players_wins(inventory: &[&Item]) -> bool {
let enemy_hit_points = 109;
let enemy_damage = 8;
let enemy_armor = 2;
let player_hit_points = 100;
let player_damage = inventory.iter().map(|item| item.damage).fold(0, |acc, x| acc + x);
let player_armor = inventory.iter().map(|item| item.armo... | {
Item { name: name.to_string(), price: price, damage: damage, armor: armor }
} | identifier_body |
htmlframeelement.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::bindings::codegen::Bindings::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrame... | <'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
| reflector | identifier_name |
htmlframeelement.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::bindings::codegen::Bindings::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrame... | self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId))
}
}
impl HTMLFrameElement {
pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLFrameElement {
HTMLFrameElement {
htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, loc... | impl HTMLFrameElementDerived for EventTarget {
fn is_htmlframeelement(&self) -> bool { | random_line_split |
htmlframeelement.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::bindings::codegen::Bindings::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrame... |
}
impl HTMLFrameElement {
pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLFrameElement {
HTMLFrameElement {
htmlelement: HTMLElement::new_inherited(HTMLFrameElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JSRef<... | {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFrameElementTypeId))
} | identifier_body |
repeater.js | import ComponentView from '../Base/ComponentView';
/**
* The repeater component creates a component for each model in a collection (its model property)
* modelComponent option is the constructor for the component to make
* modelOptions is the options to pass to each new component
* @constructor
*/
var RepeaterCom... |
if (currentLength < actualLength) {
//there aren't enough components on the repeater
for (var j = smallestLength; j < actualLength; j++) {
//create a new component
componentList[j] = this.makeNewComponent({
model: this.getModelAt(j)
});
}
} else if (actualLe... | {
if(componentList[i] && !this.alwaysFresh) componentList[i].setModel(this.getModelAt(i));
else componentList[i] = this.makeNewComponent({
model: this.getModelAt(i)
});
} | conditional_block |
repeater.js | import ComponentView from '../Base/ComponentView';
/**
* The repeater component creates a component for each model in a collection (its model property)
* modelComponent option is the constructor for the component to make
* modelOptions is the options to pass to each new component
* @constructor
*/
var RepeaterCom... | var componentList = this.components[this.getTagName()],
actualLength = this.model.length,
currentLength = componentList ? componentList.length : 0,
smallestLength = actualLength < currentLength ? actualLength : currentLength;
//update the model for each component (important if the collection'... |
updateComponents: function() { | random_line_split |
rocksdb_engine.rs | _inspected_env;
use engine_rocks::raw::DBOptions;
use engine_rocks::raw_util::CFOptions;
use engine_rocks::{RocksEngine as BaseRocksEngine, RocksEngineIterator};
use engine_traits::CfName;
use engine_traits::{
Engines, IterOptions, Iterable, Iterator, KvEngine, Peekable, ReadOptions, SeekKey,
};
use kvproto::kvrpcp... | ///
/// This is intended for **testing use only**.
#[derive(Clone)]
pub struct RocksEngine {
core: Arc<Mutex<RocksEngineCore>>,
sched: Scheduler<Task>,
engines: Engines<BaseRocksEngine, BaseRocksEngine>,
not_leader: Arc<AtomicBool>,
}
impl RocksEngine {
pub fn new(
path: &str,
cfs: ... | }
}
/// The RocksEngine is based on `RocksDB`. | random_line_split |
rocksdb_engine.rs | _inspected_env;
use engine_rocks::raw::DBOptions;
use engine_rocks::raw_util::CFOptions;
use engine_rocks::{RocksEngine as BaseRocksEngine, RocksEngineIterator};
use engine_traits::CfName;
use engine_traits::{
Engines, IterOptions, Iterable, Iterator, KvEngine, Peekable, ReadOptions, SeekKey,
};
use kvproto::kvrpcp... |
fn async_write_ext(
&self,
_: &Context,
batch: WriteData,
cb: Callback<()>,
proposed_cb: Option<ExtCallback>,
committed_cb: Option<ExtCallback>,
) -> Result<()> {
fail_point!("rockskv_async_write", |_| Err(box_err!("write failed")));
if batch.mo... | {
self.async_write_ext(ctx, batch, cb, None, None)
} | identifier_body |
rocksdb_engine.rs | _inspected_env;
use engine_rocks::raw::DBOptions;
use engine_rocks::raw_util::CFOptions;
use engine_rocks::{RocksEngine as BaseRocksEngine, RocksEngineIterator};
use engine_traits::CfName;
use engine_traits::{
Engines, IterOptions, Iterable, Iterator, KvEngine, Peekable, ReadOptions, SeekKey,
};
use kvproto::kvrpcp... | (&mut self, t: Task) {
match t {
Task::Write(modifies, cb) => {
cb((CbContext::new(), write_modifies(&self.0.kv, modifies)))
}
Task::Snapshot(cb) => cb((CbContext::new(), Ok(Arc::new(self.0.kv.snapshot())))),
Task::Pause(dur) => std::thread::sleep(... | run | identifier_name |
error.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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
// later version.
// Th... | {
/// Code
pub code: ErrorCode,
/// Message
pub message: String,
/// Optional data
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl Error {
/// Wraps given `ErrorCode`
pub fn new(code: ErrorCode) -> Self {
Error {
message: code.d... | Error | identifier_name |
error.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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
// later version.
// Th... | /// JSONRPC error code
#[derive(Debug, PartialEq, Clone)]
pub enum ErrorCode {
/// Invalid JSON was received by the server.
/// An error occurred on the server while parsing the JSON text.
ParseError,
/// The JSON sent is not a valid Request object.
InvalidRequest,
/// The method does not exist ... | random_line_split | |
actionsURLs.ts | import { WindowType } from "./api.js";
import { doBackgroundAction } from "./doBackgroundAction.js";
import { tabToWindow } from "./actionsTabs.js";
import { getNeighbouringWindowId } from "./getNeighbouringWindowId.js";
import { unhighlightTabs } from "./unhighlightTabs.js";
import { getTabsToUnhighlight } from "./get... | windowType: WindowType | undefined,
moveToNextDisplay = false,
) => {
doBackgroundAction(() => {
chrome.tabs.create({ url, active: true }, () => {
tabToWindow(windowType, moveToNextDisplay);
});
});
};
export const urlToNeighbouringWindow = (url: string, windowDistance: number) => {
doBackgroun... | random_line_split | |
actionsURLs.ts | import { WindowType } from "./api.js";
import { doBackgroundAction } from "./doBackgroundAction.js";
import { tabToWindow } from "./actionsTabs.js";
import { getNeighbouringWindowId } from "./getNeighbouringWindowId.js";
import { unhighlightTabs } from "./unhighlightTabs.js";
import { getTabsToUnhighlight } from "./get... |
unhighlightTabs(await getTabsToUnhighlight(nextWindowId));
const opts = { windowId: nextWindowId, url };
chrome.tabs.create(opts);
});
};
export const urlToWindowNormal = (url: string) => urlToWindow(url, "normal");
export const urlToWindowPopup = (url: string) => urlToWindow(url, "popup");
export con... | {
return;
} | conditional_block |
族語辭典1轉檔.py | from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseComma... | 式.channels(1)
目標聲音格式.frequence(16000)
原始檔案 = Input(來源)
網頁檔案 = Output(目標).overwrite()
指令 = AVConv('avconv', 原始檔案, 目標聲音格式, NO_VIDEO, 網頁檔案)
程序 = 指令.run()
程序.wait()
| conditional_block | |
族語辭典1轉檔.py | from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseComma... | ):
# 檢查avconv有裝無
代碼 = 代碼對應[參數['語言']]
語料目錄 = join(settings.BASE_DIR, '語料', '族語辭典', 代碼)
目標目錄 = join(settings.BASE_DIR, '語料', '族語辭典wav', 代碼)
makedirs(目標目錄, exist_ok=True)
for 檔名 in sorted(listdir(語料目錄)):
if 檔名.endswith('.mp3'):
來源 = join(語料目錄, 檔名)... |
'語言',
type=str,
help='選擇的族語'
)
def handle(self, *args, **參數 | identifier_body |
族語辭典1轉檔.py | from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseComma... | vconv有裝無
代碼 = 代碼對應[參數['語言']]
語料目錄 = join(settings.BASE_DIR, '語料', '族語辭典', 代碼)
目標目錄 = join(settings.BASE_DIR, '語料', '族語辭典wav', 代碼)
makedirs(目標目錄, exist_ok=True)
for 檔名 in sorted(listdir(語料目錄)):
if 檔名.endswith('.mp3'):
來源 = join(語料目錄, 檔名)
... | # 檢查a | identifier_name |
族語辭典1轉檔.py | from os import makedirs
from os.path import join
from posix import listdir
from django.conf import settings
from django.core.management.base import BaseCommand
from libavwrapper.avconv import Input, Output, AVConv
from libavwrapper.codec import AudioCodec, NO_VIDEO
from 匯入.族語辭典 import 代碼對應
class Command(BaseComma... | 程序 = 指令.run()
程序.wait() | 指令 = AVConv('avconv', 原始檔案, 目標聲音格式, NO_VIDEO, 網頁檔案) | random_line_split |
glacier_push.py | #!/usr/bin/python2.7
from boto.glacier.layer1 import Layer1
from boto.glacier.concurrent import ConcurrentUploader
import sys
import os.path
from time import gmtime, strftime
access_key_id = "xxx"
secret_key = "xxx"
target_vault_name = "xxx"
inventory = "xxx"
# the file to be uploaded into the vault as an archive
... |
# glacier uploader
glacier_layer1 = Layer1(aws_access_key_id=access_key_id, aws_secret_access_key=secret_key, is_secure=True)
uploader = ConcurrentUploader(glacier_layer1, target_vault_name, part_size=128*1024*1024, num_threads=1)
archive_id = uploader.upload(fname, fdes)
# write an inventory file
f = open(inventor... | print("Can't find the file to upload")
sys.exit(-1); | conditional_block |
glacier_push.py | #!/usr/bin/python2.7
from boto.glacier.layer1 import Layer1
from boto.glacier.concurrent import ConcurrentUploader
import sys
import os.path
from time import gmtime, strftime
access_key_id = "xxx"
secret_key = "xxx"
target_vault_name = "xxx"
inventory = "xxx"
# the file to be uploaded into the vault as an archive
... | uploader = ConcurrentUploader(glacier_layer1, target_vault_name, part_size=128*1024*1024, num_threads=1)
archive_id = uploader.upload(fname, fdes)
# write an inventory file
f = open(inventory, 'a+')
f.write(archive_id+'\t'+fdes+'\n')
f.close()
sys.exit(0); | glacier_layer1 = Layer1(aws_access_key_id=access_key_id, aws_secret_access_key=secret_key, is_secure=True) | random_line_split |
description.py | also
# referenced from the control section.
'aggregationInfo': {
'fields': [ (u'timestamp', 'first'),
(u'gym', 'first'),
(u'consumption', 'sum')],
'days': 0,
'hours': 1,
'microseconds': 0,
'milliseconds': 0,
'minutes': 0,
'months': 0,
'secon... | predictionSteps = int(round(aggregationDivide(
config['predictAheadTime'], config['aggregationInfo'])))
assert (predictionSteps >= 1)
config['modelParams']['clParams']['steps'] = str(predictionSteps) | conditional_block | |
description.py | imported
# from a sub-experiment.
#
# These fields might be modified by a sub-experiment; this dict is passed
# between the sub-experiment and base experiment
#
#
# NOTE: Use of DEFERRED VALUE-GETTERs: dictionary fields and list elements
# within the config dictionary may be assigned futures derived from the
# Val... | # choose coincInputPoolPct * (2*coincInputRadius+1)^2
'coincInputPoolPct': 0.5,
# The default connected threshold. Any synapse whose
# permanence value is above the connected threshold is
# a "connected synapse", meaning it can contribute to the
#... | 'seed': 1956,
# coincInputPoolPct
# What percent of the columns's receptive field is available
# for potential synapses. At initialization time, we will | random_line_split |
profile.rs | //! # profile
//!
//! Profile related utility functions
//!
#[cfg(test)]
#[path = "profile_test.rs"]
mod profile_test;
use envmnt;
static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE";
static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES";
pub(crate) static DEFAULT_PROFILE: &str = "development";... | envmnt::get_or(PROFILE_ENV_KEY, DEFAULT_PROFILE)
}
pub(crate) fn set(profile: &str) -> String {
let mut profile_normalized = normalize_profile(&profile);
if profile_normalized.len() == 0 {
profile_normalized = DEFAULT_PROFILE.to_string();
}
envmnt::set(PROFILE_ENV_KEY, &profile_normalized... | random_line_split | |
profile.rs | //! # profile
//!
//! Profile related utility functions
//!
#[cfg(test)]
#[path = "profile_test.rs"]
mod profile_test;
use envmnt;
static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE";
static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES";
pub(crate) static DEFAULT_PROFILE: &str = "development";... |
envmnt::set(PROFILE_ENV_KEY, &profile_normalized);
get()
}
pub(crate) fn set_additional(profiles: &Vec<String>) {
let nomralized_profiles = normalize_additional_profiles(&profiles);
envmnt::set_list(ADDITIONAL_PROFILES_ENV_KEY, &nomralized_profiles);
}
| {
profile_normalized = DEFAULT_PROFILE.to_string();
} | conditional_block |
profile.rs | //! # profile
//!
//! Profile related utility functions
//!
#[cfg(test)]
#[path = "profile_test.rs"]
mod profile_test;
use envmnt;
static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE";
static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES";
pub(crate) static DEFAULT_PROFILE: &str = "development";... | (profile: &str) -> String {
let mut profile_normalized = normalize_profile(&profile);
if profile_normalized.len() == 0 {
profile_normalized = DEFAULT_PROFILE.to_string();
}
envmnt::set(PROFILE_ENV_KEY, &profile_normalized);
get()
}
pub(crate) fn set_additional(profiles: &Vec<String>) {
... | set | identifier_name |
profile.rs | //! # profile
//!
//! Profile related utility functions
//!
#[cfg(test)]
#[path = "profile_test.rs"]
mod profile_test;
use envmnt;
static PROFILE_ENV_KEY: &str = "CARGO_MAKE_PROFILE";
static ADDITIONAL_PROFILES_ENV_KEY: &str = "CARGO_MAKE_ADDITIONAL_PROFILES";
pub(crate) static DEFAULT_PROFILE: &str = "development";... | {
let nomralized_profiles = normalize_additional_profiles(&profiles);
envmnt::set_list(ADDITIONAL_PROFILES_ENV_KEY, &nomralized_profiles);
} | identifier_body | |
p_1_2_3_04.rs | // P_1_2_3_04
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | color_count: usize,
hue_values: Vec<f32>,
saturation_values: Vec<f32>,
brightness_values: Vec<f32>,
alpha_value: f32,
act_random_seed: u64,
clicked: bool,
clicked_frame: u64,
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.size(1280, 720)
.v... | el {
| identifier_name |
p_1_2_3_04.rs | // P_1_2_3_04
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | // how many fragments
let mut part_count = i + 1;
let mut parts = Vec::new();
for _ in 0..part_count {
// sub fragment of not?
if rng.gen::<f32>() < 0.075 {
// take care of big values
let fragments =... | let row_count = rng.gen_range(5, 30);
let row_height = (app.window_rect().h() as i32 / row_count) as i32;
// seperate each line in parts
for i in (0..=row_count).rev() { | random_line_split |
p_1_2_3_04.rs | // P_1_2_3_04
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.... | app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
| conditional_block | |
LoadTestGroupReportFilter.js | Ext.define('OppUI.view.loadtestDashboard.loadtestsummary.groupreportfilter.LoadTestGroupReportFilter', {
extend: 'Ext.form.FieldContainer',
alias: 'widget.groupreportfilter',
requires: [
'OppUI.view.loadtestDashboard.loadtestsummary.groupreportfilter.LoadTestGroupReportFilterController',
'O... | fieldDefaults: {
padding: 5
},
items: [{
xtype: 'combobox',
itemId: 'filterCombobox',
store: {
type: 'array',
fields: ['column_name'],
data: [
['appUnderTest'],
['appUnderTestVersion'],
['comm... | align: 'middle' // Child items are stretched to full width
}, | random_line_split |
bomb_enemy.py | """
Given a 2D grid, each cell is either a wall 'W',
an enemy 'E' or empty '0' (the number zero),
return the maximum enemies you can kill using one bomb.
The bomb kills all the enemies in the same row and column from
the planted point until it hits the wall since the wall is too strong
to be destroyed.
Note that you ca... | (grid, i, j):
num = 0
len_col = len(grid)
while i < len_col and grid[i][j] != 'W':
if grid[i][j] == 'E':
num += 1
i += 1
return num
# ----------------- TESTS -------------------------
"""
Testsuite for the project
"""
import unittest
class TestBombEnemy(unittest.Tes... | col_kills | identifier_name |
bomb_enemy.py | """
Given a 2D grid, each cell is either a wall 'W',
an enemy 'E' or empty '0' (the number zero),
return the maximum enemies you can kill using one bomb.
The bomb kills all the enemies in the same row and column from
the planted point until it hits the wall since the wall is too strong
to be destroyed.
Note that you ca... | if grid[i][j] == '0':
# updates the variable
max_killed = max(max_killed, row_e + col_e[j])
return max_killed
# calculate killed enemies for row i from column j
def row_kills(grid, i, j):
num = 0
len_row = len(grid[0])
while j < len_row and grid[i][j] != 'W... | col_e[j] = col_kills(grid, i, j)
# makes sure the cell contains a 0 | random_line_split |
bomb_enemy.py | """
Given a 2D grid, each cell is either a wall 'W',
an enemy 'E' or empty '0' (the number zero),
return the maximum enemies you can kill using one bomb.
The bomb kills all the enemies in the same row and column from
the planted point until it hits the wall since the wall is too strong
to be destroyed.
Note that you ca... |
if __name__ == "__main__":
unittest.main()
| grid1 = [
["0", "E", "0", "E"],
["E", "E", "E", "0"],
["E", "0", "W", "E"],
["0", "E", "0", "0"]]
grid2 = [
["0", "0", "0", "E"],
["E", "0", "0", "0"],
["E", "0", "W", "E"],
["0", "E", "0", "0"]]
self.assertE... | identifier_body |
bomb_enemy.py | """
Given a 2D grid, each cell is either a wall 'W',
an enemy 'E' or empty '0' (the number zero),
return the maximum enemies you can kill using one bomb.
The bomb kills all the enemies in the same row and column from
the planted point until it hits the wall since the wall is too strong
to be destroyed.
Note that you ca... |
return max_killed
# calculate killed enemies for row i from column j
def row_kills(grid, i, j):
num = 0
len_row = len(grid[0])
while j < len_row and grid[i][j] != 'W':
if grid[i][j] == 'E':
num += 1
j += 1
return num
# calculate killed enemies for column j from row... | for j in range(n):
# makes sure we are next to a wall.
if j == 0 or grid[i][j - 1] == 'W':
row_e = row_kills(grid, i, j)
# makes sure we are next to a wall.
if i == 0 or grid[i - 1][j] == 'W':
col_e[j] = col_kills(grid, i, j)
# ... | conditional_block |
conf.py | # -*- coding: utf-8 -*-
#
# GitComponentVersion documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 11 10:51:23 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated... | # 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'GitComponentVersion.tex', u'GitComponentVersion Documentation',
u'Kevin Johnson', '... |
# Latex figure (float) alignment
# | random_line_split |
inspector_runtime.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import exceptions
class InspectorRuntime(object):
def __init__(self, inspector_backend):
self._inspector_backend = inspector_backe... | (self):
"""Allow access to iframes."""
if not self._contexts_enabled:
self._contexts_enabled = True
self._inspector_backend.SyncRequest({'method': 'Runtime.enable'},
timeout=30)
return self._max_context_id
| EnableAllContexts | identifier_name |
inspector_runtime.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import exceptions
class InspectorRuntime(object):
def __init__(self, inspector_backend):
self._inspector_backend = inspector_backe... |
return res['result']['result']['value']
def EnableAllContexts(self):
"""Allow access to iframes."""
if not self._contexts_enabled:
self._contexts_enabled = True
self._inspector_backend.SyncRequest({'method': 'Runtime.enable'},
timeout=30)
return ... | return None | conditional_block |
inspector_runtime.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import exceptions
class InspectorRuntime(object):
def __init__(self, inspector_backend):
self._inspector_backend = inspector_backe... | if 'error' in res:
raise exceptions.EvaluateException(res['error']['message'])
if 'wasThrown' in res['result'] and res['result']['wasThrown']:
# TODO(nduca): propagate stacks from javascript up to the python
# exception.
raise exceptions.EvaluateException(res['result']['result']['descri... | random_line_split | |
inspector_runtime.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import exceptions
class InspectorRuntime(object):
def __init__(self, inspector_backend):
self._inspector_backend = inspector_backe... |
def Evaluate(self, expr, context_id, timeout):
request = {
'method': 'Runtime.evaluate',
'params': {
'expression': expr,
'returnByValue': True
}
}
if context_id is not None:
self.EnableAllContexts()
request['params']['contextId'] = context_id
res = s... | self.Evaluate(expr + '; 0;', context_id, timeout) | identifier_body |
test_wait4.py | """This test checks for correct wait4() behavior.
"""
import os
import time
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children, get_attribute
# If either of these do not exist, skip this test.
get_attribute(os, 'fork')
get_attribute(os, 'wait4')
class Wait4Test(ForkWait):
... | test_main() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.