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
wav.rs
use std::{fs::File, path::PathBuf, usize}; use structopt::StructOpt; use vtx::{player::PrecisePlayer, Vtx}; #[derive(StructOpt)] pub struct ConvertWav { /// `*.vtx` input file path #[structopt(short, long)] input: PathBuf, /// `*.wav` output file path #[structopt(short, long)] output: PathBuf, ...
pos += samples_generated; buffer.resize(pos + CHUNK_SIZE, 0); } buffer.truncate(pos); let wav_header = wav::Header::new( wav::WAV_FORMAT_PCM, CHANNEL_COUNT as u16, SAMPLE_RATE as u32, BITS_PER_SAMPLE as u16, ); ...
{ break; }
conditional_block
wav.rs
use std::{fs::File, path::PathBuf, usize}; use structopt::StructOpt; use vtx::{player::PrecisePlayer, Vtx}; #[derive(StructOpt)] pub struct ConvertWav { /// `*.vtx` input file path #[structopt(short, long)] input: PathBuf, /// `*.wav` output file path #[structopt(short, long)] output: PathBuf, ...
let wav_header = wav::Header::new( wav::WAV_FORMAT_PCM, CHANNEL_COUNT as u16, SAMPLE_RATE as u32, BITS_PER_SAMPLE as u16, ); let mut output_file = File::create(self.output)?; wav::write( wav_header, &wav::BitDepth:...
random_line_split
wav.rs
use std::{fs::File, path::PathBuf, usize}; use structopt::StructOpt; use vtx::{player::PrecisePlayer, Vtx}; #[derive(StructOpt)] pub struct
{ /// `*.vtx` input file path #[structopt(short, long)] input: PathBuf, /// `*.wav` output file path #[structopt(short, long)] output: PathBuf, } impl ConvertWav { pub fn execute(self) -> Result<(), anyhow::Error> { const CHUNK_SIZE: usize = 16 * 64000; const SAMPLE_RATE: u...
ConvertWav
identifier_name
wav.rs
use std::{fs::File, path::PathBuf, usize}; use structopt::StructOpt; use vtx::{player::PrecisePlayer, Vtx}; #[derive(StructOpt)] pub struct ConvertWav { /// `*.vtx` input file path #[structopt(short, long)] input: PathBuf, /// `*.wav` output file path #[structopt(short, long)] output: PathBuf, ...
let mut pos = 0; loop { let samples_generated = player.play(&mut buffer[pos..pos + CHUNK_SIZE]); if samples_generated == 0 { break; } pos += samples_generated; buffer.resize(pos + CHUNK_SIZE, 0); } buffer.trunca...
{ const CHUNK_SIZE: usize = 16 * 64000; const SAMPLE_RATE: usize = 44100; const CHANNEL_COUNT: usize = 2; const BITS_PER_SAMPLE: usize = 16; println!("Parsing vtx file..."); let input_file = File::open(self.input)?; let vtx = Vtx::load(input_file)?; prin...
identifier_body
graph-create.component.ts
import { Component, OnInit } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import * as fromGraphDescriptions from '../../+state/selectors/'; import { GraphDescriptionsState } from '../../+state/reducers/graphDescription.reducers'; import { GraphTypeDescription } f...
@Component({ selector: 'eg-graph-create', templateUrl: './graph-create.component.html', styleUrls: ['./graph-create.component.scss'] }) export class GraphCreateComponent implements OnInit { graphTypes: Observable<GraphTypeDescription[]>; logger: ILogger; constructor(private store: Store<GraphDescriptionsS...
random_line_split
graph-create.component.ts
import { Component, OnInit } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import * as fromGraphDescriptions from '../../+state/selectors/'; import { GraphDescriptionsState } from '../../+state/reducers/graphDescription.reducers'; import { GraphTypeDescription } f...
implements OnInit { graphTypes: Observable<GraphTypeDescription[]>; logger: ILogger; constructor(private store: Store<GraphDescriptionsState>, readonly loggerFactory: LoggerFactory) { this.logger = loggerFactory.create('GraphCreateComponent'); this.graphTypes = this.store.pipe(select(fromGraphDescriptio...
GraphCreateComponent
identifier_name
graph-create.component.ts
import { Component, OnInit } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import * as fromGraphDescriptions from '../../+state/selectors/'; import { GraphDescriptionsState } from '../../+state/reducers/graphDescription.reducers'; import { GraphTypeDescription } f...
public showDescription(graphType: GraphTypeDescription) { this.logger.debug('Show Description'); //this.router.navigate(['/graph/description', graphType.id]); } }
{ this.store.dispatch(new AddGraph(graphType)); }
identifier_body
model.ts
import { IDisposable } from '@lumino/disposable'; import { ISignal, Signal } from '@lumino/signaling'; import { Git } from '../../tokens'; /** * Base DiffModel class */ export class DiffModel implements IDisposable, Git.Diff.IModel { constructor(props: Omit<Git.Diff.IModel, 'changed' | 'hasConflict'>) { this._...
/** * Reference description */ get reference(): Git.Diff.IContent { return this._reference; } set reference(v: Git.Diff.IContent) { const emitSignal = this._didContentChange(this._reference, v); if (emitSignal) { this._reference = v; this._changed.emit({ type: 'reference' }); ...
{ return this._filename; }
identifier_body
model.ts
import { IDisposable } from '@lumino/disposable'; import { ISignal, Signal } from '@lumino/signaling'; import { Git } from '../../tokens'; /** * Base DiffModel class */ export class DiffModel implements IDisposable, Git.Diff.IModel { constructor(props: Omit<Git.Diff.IModel, 'changed' | 'hasConflict'>) { this._...
this._isDisposed = true; Signal.clearData(this); } protected _reference: Git.Diff.IContent; protected _challenger: Git.Diff.IContent; protected _base?: Git.Diff.IContent; private _changed: Signal<DiffModel, Git.Diff.IModelChange>; private _isDisposed = false; private _filename: string; privat...
{ return; }
conditional_block
model.ts
import { IDisposable } from '@lumino/disposable'; import { ISignal, Signal } from '@lumino/signaling'; import { Git } from '../../tokens'; /** * Base DiffModel class */ export class DiffModel implements IDisposable, Git.Diff.IModel { constructor(props: Omit<Git.Diff.IModel, 'changed' | 'hasConflict'>) { this._...
(v: Git.Diff.IContent) { const emitSignal = this._didContentChange(this._reference, v); if (emitSignal) { this._reference = v; this._changed.emit({ type: 'reference' }); } } /** * Git repository path * * Note: This path is relative to the server root */ get repositoryPath(): ...
reference
identifier_name
model.ts
import { IDisposable } from '@lumino/disposable'; import { ISignal, Signal } from '@lumino/signaling'; import { Git } from '../../tokens'; /** * Base DiffModel class */ export class DiffModel implements IDisposable, Git.Diff.IModel { constructor(props: Omit<Git.Diff.IModel, 'changed' | 'hasConflict'>) { this._...
} set reference(v: Git.Diff.IContent) { const emitSignal = this._didContentChange(this._reference, v); if (emitSignal) { this._reference = v; this._changed.emit({ type: 'reference' }); } } /** * Git repository path * * Note: This path is relative to the server root */ get...
/** * Reference description */ get reference(): Git.Diff.IContent { return this._reference;
random_line_split
jillpaginate_core.js
/* * jillpaginate_core.js */ var el; (function($) { module("jillpaginate: core"); test("jillpaginate rerenders with new current page", function() { expect(2); $("#paginate").jillpaginate({ currentPage: 6, totalPages: 11 }); ok($('#paginate em').html() == 6);
test("windows merge left", function() { expect(4); $("#paginate").jillpaginate({ currentPage: 5, totalPages: 10, innerWindow: 1 }); var nextElements = $('#paginate em').nextAll(); ok(nextElements.eq(0).is("a")); ok(nextElements.eq(1).is("span")); var prevElements = $('#paginate em').prevAll()...
$('#paginate em').next().click(); ok($('#paginate em').html() == 7); });
random_line_split
example.rs
const SMALL: &'static [&'static str] = &["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "se...
(n: u64) -> String { if n < 20 { SMALL[n as usize].to_string() } else if n < 100 { let small = n % 10; let mut out = String::from(TENS[n as usize / 10]); if small > 0 { out.push('-'); out.push_str(SMALL[small as usize]); } out } else if...
encode
identifier_name
example.rs
const SMALL: &'static [&'static str] = &["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "se...
out.push('-'); out.push_str(SMALL[small as usize]); } out } else if n < 1000 { let mut out = String::from(SMALL[n as usize / 100]); out.push_str(" hundred"); let ones = n % 100; if ones > 0 { out.push(' '); out.push_str(...
SMALL[n as usize].to_string() } else if n < 100 { let small = n % 10; let mut out = String::from(TENS[n as usize / 10]); if small > 0 {
random_line_split
example.rs
const SMALL: &'static [&'static str] = &["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "se...
} } out } }
{ let mut sets: Vec<u64> = Vec::new(); let mut val = n; while val >= 1 { sets.push(val % 1000); val /= 1000; } let mut out = String::new(); while let Some(modu) = sets.pop() { let len = sets.len(); if modu == 0 { ...
conditional_block
example.rs
const SMALL: &'static [&'static str] = &["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "se...
} else { let mut sets: Vec<u64> = Vec::new(); let mut val = n; while val >= 1 { sets.push(val % 1000); val /= 1000; } let mut out = String::new(); while let Some(modu) = sets.pop() { let len = sets.len(); if modu == 0 { ...
{ if n < 20 { SMALL[n as usize].to_string() } else if n < 100 { let small = n % 10; let mut out = String::from(TENS[n as usize / 10]); if small > 0 { out.push('-'); out.push_str(SMALL[small as usize]); } out } else if n < 1000 { ...
identifier_body
job.py
# -*- coding: utf-8 -*- from ..base import ComponentAPI class CollectionsJOB(object): """Collections of JOB APIS""" def __init__(self, client):
description=u'查询作业模板详情', ) self.get_task_ip_log = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi/job/get_task_ip_log/', description=u'根据作业实例ID查询作业执行日志', ) self.get_task_result = ComponentAPI( client=self.client, method...
self.client = client self.execute_task = ComponentAPI( client=self.client, method='POST', path='/api/c/compapi/job/execute_task/', description=u'根据作业模板ID启动作业', ) self.fast_execute_script = ComponentAPI( client=self.client, method='POST', path='/api/c/compapi/...
identifier_body
job.py
# -*- coding: utf-8 -*- from ..base import ComponentAPI class CollectionsJOB(object): """Collections of JOB APIS""" def __init__(self, client): self.client = client self.execute_task = ComponentAPI( client=self.client, method='POST', path='/api/c/compapi/job/execute_task/', ...
) self.get_task_ip_log = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi/job/get_task_ip_log/', description=u'根据作业实例ID查询作业执行日志', ) self.get_task_result = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi/job/get_...
description=u'查询Agent状态', ) self.get_task_detail = ComponentAPI( client=self.client, method='GET', path='/api/c/compapi/job/get_task_detail/', description=u'查询作业模板详情',
random_line_split
job.py
# -*- coding: utf-8 -*- from ..base import ComponentAPI class CollectionsJOB(object): """Collections of JOB APIS""" def
(self, client): self.client = client self.execute_task = ComponentAPI( client=self.client, method='POST', path='/api/c/compapi/job/execute_task/', description=u'根据作业模板ID启动作业', ) self.fast_execute_script = ComponentAPI( client=self.client, method='POST...
__init__
identifier_name
list-harness.ts
/** * @license * Copyright Google LLC 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 {HarnessPredicate} from '@angular/cdk/testing'; import {MatListHarnessBase} from './list-harness-base'; import...
* Gets a `HarnessPredicate` that can be used to search for a `MatListItemHarness` that meets * certain criteria. * @param options Options for filtering which list item instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: ListItemHar...
export class MatListItemHarness extends MatListItemHarnessBase { /** The selector for the host element of a `MatListItem` instance. */ static hostSelector = `${MatListHarness.hostSelector} .mat-list-item`; /**
random_line_split
list-harness.ts
/** * @license * Copyright Google LLC 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 {HarnessPredicate} from '@angular/cdk/testing'; import {MatListHarnessBase} from './list-harness-base'; import...
(options: ListHarnessFilters = {}): HarnessPredicate<MatListHarness> { return new HarnessPredicate(MatListHarness, options); } _itemHarness = MatListItemHarness; } /** Harness for interacting with a list item. */ export class MatListItemHarness extends MatListItemHarnessBase { /** The selector for the host ...
with
identifier_name
list-harness.ts
/** * @license * Copyright Google LLC 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 {HarnessPredicate} from '@angular/cdk/testing'; import {MatListHarnessBase} from './list-harness-base'; import...
_itemHarness = MatListItemHarness; } /** Harness for interacting with a list item. */ export class MatListItemHarness extends MatListItemHarnessBase { /** The selector for the host element of a `MatListItem` instance. */ static hostSelector = `${MatListHarness.hostSelector} .mat-list-item`; /** * Gets a ...
{ return new HarnessPredicate(MatListHarness, options); }
identifier_body
repeatableMovement.test.ts
"use strict"; import { ModeHandler } from "../../src/mode/modeHandler"; import { setupWorkspace, cleanUpWorkspace, assertEqualLines } from '../testUtils'; import { getTestingFunctions } from '../testSimplifier'; suite("register", () => { let modeHandler: ModeHandler = new ModeHandler(); let { newTest, ...
});
title: "Can repeat N times reversed t<character>", start: ['|abc abc abc abc'], keysPressed: 'tc$3,', end: ['abc| abc abc abc'], });
random_line_split
builtin.torrent.onstart.settorrentlabels.py
from torrentstatus.plugin import iTorrentAction from torrentstatus.utorrent.connection import Connection from contextlib import contextmanager from torrentstatus.bearlang import BearLang from torrentstatus.settings import config, labels_config from torrentstatus.utils import intTryParse @contextmanager def utorrent...
else: print("Not trying to connect to webui") return False
print("Connection to utorrent web ui ok") print ("Got torrent '{0}' with hash {1} and tracker {2}. \n Setting new_labels: {3}" .format(utorrentargs.torrentname, utorrentargs.hash, utorrentargs.tracker, new_labels)) if utorrentargs.debug: ...
conditional_block
builtin.torrent.onstart.settorrentlabels.py
from torrentstatus.plugin import iTorrentAction from torrentstatus.utorrent.connection import Connection from contextlib import contextmanager from torrentstatus.bearlang import BearLang from torrentstatus.settings import config, labels_config from torrentstatus.utils import intTryParse @contextmanager def
(host, username, password): try: conn = Connection(host, username, password).utorrent(None) except Exception as err: yield None, err else: try: yield conn, None finally: pass def get_new_torrent_labels(labels, args): """Transforms torrent labels ...
utorrent_connection
identifier_name
builtin.torrent.onstart.settorrentlabels.py
from torrentstatus.plugin import iTorrentAction from torrentstatus.utorrent.connection import Connection from contextlib import contextmanager from torrentstatus.bearlang import BearLang from torrentstatus.settings import config, labels_config from torrentstatus.utils import intTryParse @contextmanager def utorrent...
return new_labels settings = config.getSettingsAsDict() class SetLabelsOnStart(iTorrentAction): def onstart(self, pluginconfig, utorrentargs): tempargs = vars(utorrentargs) # Use labels definition from config file and match them up against # provided input to the main script ...
new_labels.append(label)
random_line_split
builtin.torrent.onstart.settorrentlabels.py
from torrentstatus.plugin import iTorrentAction from torrentstatus.utorrent.connection import Connection from contextlib import contextmanager from torrentstatus.bearlang import BearLang from torrentstatus.settings import config, labels_config from torrentstatus.utils import intTryParse @contextmanager def utorrent...
print("\nrule:{0}, label:{1}, ismatch: {2}\n".format(rule, label, is_match)) if is_match: new_labels.append(label) return new_labels settings = config.getSettingsAsDict() class SetLabelsOnStart(iTorrentAction): def onstart(self, pluginconfig, utorrentargs): ...
"""Transforms torrent labels and args passing them into a BearLang Instance Parameters: labels (Dict) A dict of label and rules for that label args (Dict) A dict of arguments, will be passed to Bearlang Returns: a list of labels that match the rules defined. """ new_labels = []...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-14 17:20 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class
(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('headline', mod...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-14 17:20 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration):
), ]
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('headline', models.CharField(max_length=255,...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-14 17:20 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateMode...
]
random_line_split
pouchdb.js
const url = require('url'); const _ = require('lodash'); const fetch = require('node-fetch'); const PouchDB = require('pouchdb'); const logout = require('../../logout')(); PouchDB.plugin(require('pouchdb-adapter-node-websql')); PouchDB.plugin(require('pouchdb-find')); module.exports = { createPouchDB: _.memoize(crea...
(environment){ return new PouchDB(`${environment}.db`, {adapter: 'websql', auto_compaction: true}); } function sync(environment, syncDbUrl, continuous_sync){ if(!environment) return; if(!syncDbUrl) return; const syncDbUri = url.parse(syncDbUrl); const syncDbNamedUrl = ((!syncDbUri.path) || (syncDbUri.path =...
createPouchDB
identifier_name
pouchdb.js
const url = require('url'); const _ = require('lodash'); const fetch = require('node-fetch'); const PouchDB = require('pouchdb'); const logout = require('../../logout')(); PouchDB.plugin(require('pouchdb-adapter-node-websql')); PouchDB.plugin(require('pouchdb-find')); module.exports = { createPouchDB: _.memoize(crea...
.on('active', () => logout.log(`Active - ${syncDbUri.host} - ${environment}`)) .on('denied', info => logout.error(`Denied - ${syncDbUri.host} - ${environment}`)) .on('complete', info => logout.log(`Complete - ${syncDbUri.host} - ${environment}`)) .on('error', error => logout.error(`Error...
{ if(!environment) return; if(!syncDbUrl) return; const syncDbUri = url.parse(syncDbUrl); const syncDbNamedUrl = ((!syncDbUri.path) || (syncDbUri.path === '/')) ? url.resolve(syncDbUrl, environment) : url.resolve(syncDbUrl.replace(syncDbUri.path, ''), `${syncDbUri.path.replace(/\//g, '')}-$...
identifier_body
pouchdb.js
const url = require('url'); const _ = require('lodash'); const fetch = require('node-fetch'); const PouchDB = require('pouchdb'); const logout = require('../../logout')(); PouchDB.plugin(require('pouchdb-adapter-node-websql')); PouchDB.plugin(require('pouchdb-find')); module.exports = { createPouchDB: _.memoize(crea...
return createPouchDB(environment) .sync(syncDbNamedUrl, { live: continuous_sync, retry: continuous_sync, }) .on('change', info => logout.log(`Change - ${syncDbUri.host} - ${environment}`)) .on('paused', () => logout.log(`Paused - ${syncDbUri.host} - ${environmen...
return fetch(syncDbNamedUrl, {method: 'PUT'}) .catch(error => error) .then(data => data.json()) .then(data => {
random_line_split
test_s3_store.py
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests the S3 backend store""" import StringIO import hashlib ...
loc = get_location_from_uri(expected_location) (new_image_s3, new_image_size) = self.store.get(loc) new_image_contents = StringIO.StringIO() for chunk in new_image_s3: new_image_contents.write(chunk) new_image_s3_size = new_image_contents.len self.assertEqua...
"""Test that we can add an image via the s3 backend""" expected_image_id = utils.generate_uuid() expected_s3_size = FIVE_KB expected_s3_contents = "*" * expected_s3_size expected_checksum = hashlib.md5(expected_s3_contents).hexdigest() expected_location = format_s3_location( ...
identifier_body
test_s3_store.py
, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests the S3 backend store""" import StringIO import hashlib import httplib import sys import unittest import urlparse import stubout import boto.s3.connection from glance.com...
test_no_access_key
identifier_name
test_s3_store.py
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests the S3 backend store""" import StringIO import hashl...
'get_bucket', fake_get_bucket) def format_s3_location(user, key, authurl, bucket, obj): """ Helper method that returns a S3 store URI given the component pieces. """ scheme = 's3' if authurl.startswith('https://'): scheme = 's3+https' authurl = authurl[8:] eli...
return bucket stubs.Set(boto.s3.connection.S3Connection, '__init__', fake_connection_constructor) stubs.Set(boto.s3.connection.S3Connection,
random_line_split
test_s3_store.py
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests the S3 backend store""" import StringIO import hashlib ...
authurl = authurl.strip('/') return "%s://%s:%s@%s/%s/%s" % (scheme, user, key, authurl, bucket, obj) class TestStore(unittest.TestCase): def setUp(self): """Establish a clean test environment""" self.stubs = stubout.StubOutForTesting() stub_ou...
authurl = authurl[7:]
conditional_block
extern-crosscrate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(n: uint) -> uint { unsafe { debug!("n = %?", n); externcallback::rustrt::rust_dbg_call(externcallback::cb, n) } } pub fn main() { let result = fact(10u); debug!("result = %?", result); assert!(result == 3628800u); }
fact
identifier_name
extern-crosscrate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let result = fact(10u); debug!("result = %?", result); assert!(result == 3628800u); }
identifier_body
extern-crosscrate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { let result = fact(10u); debug!("result = %?", result); assert!(result == 3628800u); }
externcallback::rustrt::rust_dbg_call(externcallback::cb, n) }
random_line_split
FormEditorItemPreview.tsx
import { useContext } from 'react'; import { Link, useParams } from 'react-router-dom'; import classnames from 'classnames'; import { useConfirm, ButtonWithTooltip, ErrorDisplay, useDeleteMutationWithReferenceArrayUpdater, } from '@neinteractiveliterature/litform'; import { useSortable } from '@dnd-kit/sortable...
if (formItem.item_type === 'static_text') { return 'this static text item'; } return `the custom item “${formItem.identifier}”`; } export type FormEditorItemPreviewProps = { formSection: FormEditorForm['form_sections'][number]; formItem: TypedFormItem; }; function FormEditorItemPreview({ formSection, for...
{ return `the “${standardItem.description}” item`; }
conditional_block
FormEditorItemPreview.tsx
import { useContext } from 'react'; import { Link, useParams } from 'react-router-dom'; import classnames from 'classnames'; import { useConfirm, ButtonWithTooltip, ErrorDisplay, useDeleteMutationWithReferenceArrayUpdater, } from '@neinteractiveliterature/litform'; import { useSortable } from '@dnd-kit/sortable...
{standardItem ? ( <> <i className="bi-wrench" /> {standardItem.description} </> ) : ( <> <i className="bi-tag-fill" /> {formItem.identifier} </> )} </div> )...
to={`/admin_forms/${params.id}/edit/section/${params.sectionId}/item/${formItem.id}`} > {formItem.identifier && ( <div className="form-editor-item-identifier">
random_line_split
FormEditorItemPreview.tsx
import { useContext } from 'react'; import { Link, useParams } from 'react-router-dom'; import classnames from 'classnames'; import { useConfirm, ButtonWithTooltip, ErrorDisplay, useDeleteMutationWithReferenceArrayUpdater, } from '@neinteractiveliterature/litform'; import { useSortable } from '@dnd-kit/sortable...
(formItem: TypedFormItem, standardItem: StandardItem | undefined) { if (standardItem) { return `the “${standardItem.description}” item`; } if (formItem.item_type === 'static_text') { return 'this static text item'; } return `the custom item “${formItem.identifier}”`; } export type FormEditorItemPre...
describeFormItemForDelete
identifier_name
FormEditorItemPreview.tsx
import { useContext } from 'react'; import { Link, useParams } from 'react-router-dom'; import classnames from 'classnames'; import { useConfirm, ButtonWithTooltip, ErrorDisplay, useDeleteMutationWithReferenceArrayUpdater, } from '@neinteractiveliterature/litform'; import { useSortable } from '@dnd-kit/sortable...
type FormEditorItemPreviewProps = { formSection: FormEditorForm['form_sections'][number]; formItem: TypedFormItem; }; function FormEditorItemPreview({ formSection, formItem }: FormEditorItemPreviewProps): JSX.Element { const confirm = useConfirm(); const params = useParams<{ id: string; sectionId: string }>()...
{ if (standardItem) { return `the “${standardItem.description}” item`; } if (formItem.item_type === 'static_text') { return 'this static text item'; } return `the custom item “${formItem.identifier}”`; } export
identifier_body
reusePaths.js
'use strict'; /** * @typedef {import('../lib/types').XastElement} XastElement * @typedef {import('../lib/types').XastParent} XastParent * @typedef {import('../lib/types').XastNode} XastNode */ const JSAPI = require('../lib/svgo/jsAPI.js'); exports.type = 'visitor'; exports.name = 'reusePaths'; exports.active = f...
};
} }, }, };
random_line_split
reusePaths.js
'use strict'; /** * @typedef {import('../lib/types').XastElement} XastElement * @typedef {import('../lib/types').XastParent} XastParent * @typedef {import('../lib/types').XastNode} XastNode */ const JSAPI = require('../lib/svgo/jsAPI.js'); exports.type = 'visitor'; exports.name = 'reusePaths'; exports.active = f...
/** * @type {XastElement} */ const reusablePath = new JSAPI(rawPath, defsTag); defsTag.children.push(reusablePath); // convert paths to <use> for (const pathNode of list) { pathNode.name = 'use'; ...
{ id = rawPath.attributes.id; delete list[0].attributes.id; }
conditional_block
mock-spine-web-client.ts
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR...
<T>(added: T[], changed: T[], removed: T[], unsubscribe: () => void) : Promise<EntitySubscriptionObject<T>> { return Promise.resolve({ itemAdded: observableOf(added), itemChanged: observableOf...
subscriptionDataOf
identifier_name
mock-spine-web-client.ts
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR...
export function subscriptionDataOf<T>(added: T[], changed: T[], removed: T[], unsubscribe: () => void) : Promise<EntitySubscriptionObject<T>> { return Promise.resolve({ itemAdded: observableOf(a...
{ return Observable.create(observer => { if (items.length > 0) { items.forEach(item => observer.next(item)); } observer.complete(); }); }
identifier_body
mock-spine-web-client.ts
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR...
}); } export function mockSpineWebClient() { return jasmine.createSpyObj<Client>( 'Client', ['sendCommand', 'subscribe', 'fetch'] ); }
itemAdded: added, itemChanged: observableOf([]), itemRemoved: observableOf([]), unsubscribe
random_line_split
mock-spine-web-client.ts
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR...
observer.complete(); }); } export function subscriptionDataOf<T>(added: T[], changed: T[], removed: T[], unsubscribe: () => void) : Promise<EntitySubscriptionObject<T>> { return Promise.resolv...
{ items.forEach(item => observer.next(item)); }
conditional_block
account.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_required from pytz import common_timezones import settings from tekton import router from tekton.gae....
(_logged_user): _logged_user.locale = _logged_user.locale or settings.DEFAULT_LOCALE _logged_user.timezone = _logged_user.timezone or settings.DEFAULT_TIMEZONE context = {'user': _logged_user, 'timezones': common_timezones, 'save_path': router.to_path(edit)} return Template...
index
identifier_name
account.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_required from pytz import common_timezones import settings from tekton import router from tekton.gae....
@login_not_required @no_csrf def index(_logged_user): _logged_user.locale = _logged_user.locale or settings.DEFAULT_LOCALE _logged_user.timezone = _logged_user.timezone or settings.DEFAULT_TIMEZONE context = {'user': _logged_user, 'timezones': common_timezones, 'save_path': ...
if name: _logged_user.name = name _logged_user.locale = user_locale _logged_user.timezone = timezone _logged_user.put() return RedirectResponse('/')
identifier_body
account.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_required from pytz import common_timezones import settings from tekton import router from tekton.gae....
_logged_user.locale = user_locale _logged_user.timezone = timezone _logged_user.put() return RedirectResponse('/') @login_not_required @no_csrf def index(_logged_user): _logged_user.locale = _logged_user.locale or settings.DEFAULT_LOCALE _logged_user.timezone = _logged_user.timezone or settin...
_logged_user.name = name
conditional_block
account.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_required from pytz import common_timezones import settings from tekton import router from tekton.gae....
return RedirectResponse('/') @login_not_required @no_csrf def index(_logged_user): _logged_user.locale = _logged_user.locale or settings.DEFAULT_LOCALE _logged_user.timezone = _logged_user.timezone or settings.DEFAULT_TIMEZONE context = {'user': _logged_user, 'timezones': common_timezon...
_logged_user.put()
random_line_split
listnewconfig.py
#!/usr/bin/env python3 # Copyright (c) 2018-2019, Ulf Magnusson # SPDX-License-Identifier: ISC """ Lists all user-modifiable symbols that are not given a value in the configuration file. Usually, these are new symbols that have been added to the Kconfig files. The default configuration filename is '.config'. A diffe...
print(kconf.load_config(), file=sys.stderr) for sym in kconf.unique_defined_syms: # Only show symbols that can be toggled. Choice symbols are a special # case in that sym.assignable will be (2,) (length 1) for visible # symbols in choices in y mode, but they can still be toggled by ...
parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__) parser.add_argument( "--show-help", "-l", action="store_true", help="Show any help texts as well") parser.add_argument( "kconfig", metavar="KCONF...
identifier_body
listnewconfig.py
#!/usr/bin/env python3 # Copyright (c) 2018-2019, Ulf Magnusson # SPDX-License-Identifier: ISC """ Lists all user-modifiable symbols that are not given a value in the configuration file. Usually, these are new symbols that have been added to the Kconfig files. The default configuration filename is '.config'. A diffe...
print("\n".join(" " + line for line in node.help.split("\n"))) break if __name__ == "__main__": main()
if sym.user_value is None and \ (len(sym.assignable) > 1 or (sym.visibility and (sym.orig_type in (INT, HEX, STRING) or sym.choice))): # Don't reuse the 'config_string' format for bool/tristate symbols, # to show n-valued symbols as 'CONFI...
conditional_block
listnewconfig.py
#!/usr/bin/env python3 # Copyright (c) 2018-2019, Ulf Magnusson # SPDX-License-Identifier: ISC """ Lists all user-modifiable symbols that are not given a value in the configuration file. Usually, these are new symbols that have been added to the Kconfig files. The default configuration filename is '.config'. A diffe...
(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__) parser.add_argument( "--show-help", "-l", action="store_true", help="Show any help texts as well") parser.add_argument( "kconfig", metava...
main
identifier_name
listnewconfig.py
#!/usr/bin/env python3 # Copyright (c) 2018-2019, Ulf Magnusson # SPDX-License-Identifier: ISC """ Lists all user-modifiable symbols that are not given a value in the configuration file. Usually, these are new symbols that have been added to the Kconfig files. The default configuration filename is '.config'. A diffe...
# Don't reuse the 'config_string' format for bool/tristate symbols, # to show n-valued symbols as 'CONFIG_FOO=n' instead of # '# CONFIG_FOO is not set'. This matches the C tools. if sym.orig_type in (BOOL, TRISTATE): s = "{}{}={}\n".format(kconf.config_pre...
(len(sym.assignable) > 1 or (sym.visibility and (sym.orig_type in (INT, HEX, STRING) or sym.choice))):
random_line_split
index.rs
/// Index into a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) enum Index { /// Index starting from the beginning of the vector, where `Forward(0)` /// is the first element Forward(usize), /// Index starting from the end of the vector, where `Backward(0)` is the /// last ele...
}
{ if input < 0 { Index::Backward((input.abs() as usize) - 1) } else { Index::Forward(input.abs() as usize) } }
identifier_body
index.rs
/// Index into a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) enum Index { /// Index starting from the beginning of the vector, where `Forward(0)` /// is the first element Forward(usize), /// Index starting from the end of the vector, where `Backward(0)` is the /// last ele...
} /// Construct an index using the following convetions: /// - A positive value `n` represents `Forward(n)` /// - A negative value `-n` reprents `Backwards(n - 1)` such that: /// ```ignore,rust /// assert_eq!(Index::new(-1), Index::Backward(0)) /// ``` pub(crate) fn new(input: isize) ->...
}
random_line_split
index.rs
/// Index into a vector-like object #[derive(Debug, PartialEq, Copy, Clone)] pub(crate) enum Index { /// Index starting from the beginning of the vector, where `Forward(0)` /// is the first element Forward(usize), /// Index starting from the end of the vector, where `Backward(0)` is the /// last ele...
(&self, vector_length: usize) -> Option<usize> { match *self { Index::Forward(n) => Some(n), Index::Backward(n) => if n >= vector_length { None } else { Some(vector_length - (n + 1)) }, } } /// Construct an index us...
resolve
identifier_name
xid.py
# Copyright (C) 2008-2009 Mark A. Matienzo # # This file is part of worldcat, the Python WorldCat API module. # # worldcat 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 # ...
OCLC Work Identifiers. """ def __init__(self, rec_num=None, numtype='oclcnum', **kwargs): """Constructor method for xISBNRequests.""" xIDRequest.__init__(self, rec_num, **kwargs) self.numtype = numtype self._validators = { 'method': ('getVariants', 'getMetadata'...
random_line_split
xid.py
# Copyright (C) 2008-2009 Mark A. Matienzo # # This file is part of worldcat, the Python WorldCat API module. # # worldcat 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 # ...
else: return True class xISSNRequest(xIDRequest): """request.xid.xISSNRequest: Class for xISSN requests For more information on the xISSN API, see <http://xissn.worldcat.org/xissnadmin/doc/api.htm>. Example of an xISSNRequest: >>> from worldcat.request.xid import xISSNR...
raise EmptyRecordNumberError
conditional_block
xid.py
# Copyright (C) 2008-2009 Mark A. Matienzo # # This file is part of worldcat, the Python WorldCat API module. # # worldcat 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 # ...
(self, rec_num=None, **kwargs): """Constructor for xIDRequests.""" if 'method' not in kwargs: kwargs['method'] = 'getEditions' if 'format' not in kwargs: kwargs['format'] = 'python' if 'fl' not in kwargs: kwargs['fl'] = '*' WorldCatRequest.__in...
__init__
identifier_name
xid.py
# Copyright (C) 2008-2009 Mark A. Matienzo # # This file is part of worldcat, the Python WorldCat API module. # # worldcat 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 # ...
self.rec_num = rec_num def get_response(self): self.http_get() return xIDResponse(self) def subclass_validator(self, quiet=False): """Validator method for xIDRequests. Does not validate ISSN or ISBN values; this should be handled by the xID APIs. """ ...
"""request.xid.xIDRequest: Base class for requests from xID APIs. All xIDRequests require a record number ('rec_num') to be passed when a class is instantiated. Depending on the request, this will either be an ISBN, an ISSN, or an OCLC record number. xIDRequests by default have their 'method' set as '...
identifier_body
cp-widget-datetimepicker-patch.directive.js
/** * Created by rg12 on 02/05/2016. */ /** * @desc Add to uib-timepicker to fix timezone issues * @example <uib-timepicker cp-widget-datetimepicker-patch></uib-timepicker> */ (function () { 'use strict'; angular .module('app.widgets') .directive('cpWidgetDatetimepickerPatch', cpWidgetDatetimepicker...
() { return { restrict: 'A', priority: 1, require: 'ngModel', link: function (scope, element, attrs, ctrl) { ctrl.$formatters.push(function (value) { var date = new Date(value); date = new Date(date.getTime() + (60000 * date.getTimezoneOffset())); return...
cpWidgetDatetimepickerPatch
identifier_name
cp-widget-datetimepicker-patch.directive.js
/** * Created by rg12 on 02/05/2016. */ /** * @desc Add to uib-timepicker to fix timezone issues * @example <uib-timepicker cp-widget-datetimepicker-patch></uib-timepicker> */ (function () { 'use strict'; angular .module('app.widgets') .directive('cpWidgetDatetimepickerPatch', cpWidgetDatetimepicker...
})();
} }; }
random_line_split
cp-widget-datetimepicker-patch.directive.js
/** * Created by rg12 on 02/05/2016. */ /** * @desc Add to uib-timepicker to fix timezone issues * @example <uib-timepicker cp-widget-datetimepicker-patch></uib-timepicker> */ (function () { 'use strict'; angular .module('app.widgets') .directive('cpWidgetDatetimepickerPatch', cpWidgetDatetimepicker...
})();
{ return { restrict: 'A', priority: 1, require: 'ngModel', link: function (scope, element, attrs, ctrl) { ctrl.$formatters.push(function (value) { var date = new Date(value); date = new Date(date.getTime() + (60000 * date.getTimezoneOffset())); return da...
identifier_body
javascript.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): RegExp { return JSMode.JS_WORD_DEFINITION; } public get filter() { return void 0; } }
getWordDefinition
identifier_name
javascript.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
private static JS_WORD_DEFINITION = createWordRegExp('$'); public getWordDefinition(): RegExp { return JSMode.JS_WORD_DEFINITION; } public get filter() { return void 0; } }
{ return { lineCommentTokens: ['//'], blockCommentStartToken: '/*', blockCommentEndToken: '*/' }; }
identifier_body
javascript.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
else { return winjs.Promise.as(this); } } // ---- specialize by override protected _getProjectResolver(): AsyncDescriptor<typescript.IProjectResolver2>|typescript.IProjectResolver2 { return extensions.Extensions.getProjectResolver() || extensions.Defaults.ProjectResolver; } _shouldBeValidated(model: Edi...
{ return new winjs.Promise((c, e, p) => { // TODO@Alex: workaround for missing `bundles` config, before instantiating the javascriptWorker, we ensure the typescriptWorker has been loaded (<any>require)(['vs/languages/typescript/common/typescriptWorker2'], (worker:any) => { c(this); }); }); }
conditional_block
javascript.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
protected _getWorkerDescriptor(): AsyncDescriptor2<Modes.IMode, Modes.IWorkerParticipant[], javascriptWorker.JavaScriptWorker> { return createAsyncDescriptor2('vs/languages/javascript/common/javascriptWorker', 'JavaScriptWorker'); } public getCommentsConfiguration(): Modes.ICommentsConfiguration { return { line...
_shouldBeValidated(model: EditorCommon.IModel): boolean { return model.getMode() === this || /\.(d\.ts|js)$/.test(model.getAssociatedResource().fsPath); }
random_line_split
template_texture.js
g_en_template_texture = { // common tplNoPlatform : "none", tplWarning : "Warning", tplSearchFilter : "SearchFilter", tplSearchTitle : "Search", tplSearchBtn : "Search", tplSearchResultTitle : "Search Result", tplCheckNon : "No Check", tplCheckEnableOnly : "Enable Only", tplCheckDisableOnly : ...
tplCondition : "Condition", tplAddConditionBtn : "Add condition", tplDelConditionBtn : "delete", tplFileInclude : "If filepath includes below words", tplFileExclude : "If filepath doesn't include below words", // specific tplCondBasic : "Basic", tplCondFormat : "Format", tplCondImportType : "Impo...
random_line_split
restor.py
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from pyramid.view import view_config from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.default_behavior import Cancel from p...
body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result class RestorFormView(FormView): title = _('Restore') behaviors = [Restor, Cancel] formid = 'formresto...
random_line_split
restor.py
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from pyramid.view import view_config from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.default_behavior import Cancel from p...
(self): result = {} values = {'context': self.context} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result class RestorFormView(FormView): title ...
update
identifier_name
restor.py
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from pyramid.view import view_config from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.default_behavior import Cancel from p...
class RestorFormView(FormView): title = _('Restore') behaviors = [Restor, Cancel] formid = 'formrestor' name = 'formrestor' def before_update(self): self.action = self.request.resource_url( self.context, 'novaideoapi', query={'op': 'update_action_view', ...
result = {} values = {'context': self.context} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
identifier_body
mod.rs
implements the `Vertex` trait, you can build an array of vertices and upload it to the video memory by creating a `VertexBuffer`. ```no_run # let display: glium::Display = unsafe { ::std::mem::uninitialized() }; # #[derive(Copy, Clone)] # struct MyVertex { # position: [f32; 3], # texcoords: [f32; 2], # } # im...
} macro_rules! impl_for_tuple { ($t:ident) => ( impl<'a, $t> MultiVerticesSource<'a> for ($t,) where $t: IntoVerticesSource<'a> { type Iterator = IntoIter<VerticesSource<'a>>; fn iter(self) -> IntoIter<VerticesSource<'a>> { Some(self.0.into_vert...
{ Some(self.into_vertices_source()).into_iter() }
identifier_body
mod.rs
0.0, 0.4] }, ]; let vertex_buffer = glium::vertex::VertexBuffer::new(&display, data); ``` ## Drawing When you draw, you can pass either a single vertex source or a tuple of multiple sources. Each source can be: - A reference to a `VertexBuffer`. - A slice of a vertex buffer, by calling `vertex_buffer.slice(st...
fn iter(self) -> Chain<<($t1,) as MultiVerticesSource<'a>>::Iterator, <($($t2),+) as MultiVerticesSource<'a>>::Iterator> {
random_line_split
mod.rs
implements the `Vertex` trait, you can build an array of vertices and upload it to the video memory by creating a `VertexBuffer`. ```no_run # let display: glium::Display = unsafe { ::std::mem::uninitialized() }; # #[derive(Copy, Clone)] # struct MyVertex { # position: [f32; 3], # texcoords: [f32; 2], # } # im...
<'a>(BufferViewAnySlice<'a>, &'a VertexFormat); impl<'a> IntoVerticesSource<'a> for PerInstance<'a> { fn into_vertices_source(self) -> VerticesSource<'a> { VerticesSource::VertexBuffer(self.0, self.1, true) } } /// Objects that describe multiple vertex sources. pub trait MultiVerticesSource<'a> { ...
PerInstance
identifier_name
views.py
from django import http from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist def shortcut(request, content_type_id, object_id):
# relation to the Site object object_domain = None opts = obj._meta # First, look for an many-to-many relationship to Site. for field in opts.many_to_many: if field.rel.to is Site: try: # Caveat: In the case of multiple related Sites, this just # ...
"Redirect to an object's page based on a content-type ID and an object ID." # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNot...
identifier_body
views.py
from django import http from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist def shortcut(request, content_type_id, object_id): "Redirect to an object's page based on a content-type ID and an object ID." # ...
# Fall back to the current site (if possible). if object_domain is None: try: object_domain = Site.objects.get_current().domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute_u...
random_line_split
views.py
from django import http from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist def shortcut(request, content_type_id, object_id): "Redirect to an object's page based on a content-type ID and an object ID." # ...
# Fall back to the current site (if possible). if object_domain is None: try: object_domain = Site.objects.get_current().domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute...
break
conditional_block
views.py
from django import http from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist def
(request, content_type_id, object_id): "Redirect to an object's page based on a content-type ID and an object ID." # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) obj = content_type.get_object_for_this_...
shortcut
identifier_name
on-message.ts
import { MetaClass } from '@tdm/core/tdm'; import { ServerProtocol, ClientResponse, ServerRequest } from '@tdm/service-mocker/shared'; import { OnMessageMetadata } from '../metadata'; const onMessage = MetaClass.decorator(OnMessageMetadata, 'method'); export type OnMessageHandler<T extends keyof ServerProtocol> = (...
{ if (!metaArgs) { return (...args: any[]) => (<any> onMessage)(args[1])(args[0], args[1], args[2]); } else { return onMessage(metaArgs); } }
identifier_body
on-message.ts
import { MetaClass } from '@tdm/core/tdm'; import { ServerProtocol, ClientResponse, ServerRequest } from '@tdm/service-mocker/shared'; import { OnMessageMetadata } from '../metadata'; const onMessage = MetaClass.decorator(OnMessageMetadata, 'method'); export type OnMessageHandler<T extends keyof ServerProtocol> = (...
) => any; export type OnMessageHandlerDecoratorLoose = <T extends keyof ServerProtocol>( target: Object, propertyKey: any, descriptor: TypedPropertyDescriptor<OnMessageHandler<T>> ) => any; /** * Declares a handler for an incoming message from the client. */ export function OnMessage(): OnMessageHandlerDecora...
propertyKey: T, descriptor: TypedPropertyDescriptor<OnMessageHandler<T>>
random_line_split
on-message.ts
import { MetaClass } from '@tdm/core/tdm'; import { ServerProtocol, ClientResponse, ServerRequest } from '@tdm/service-mocker/shared'; import { OnMessageMetadata } from '../metadata'; const onMessage = MetaClass.decorator(OnMessageMetadata, 'method'); export type OnMessageHandler<T extends keyof ServerProtocol> = (...
<T extends keyof ServerProtocol>(metaArgs?: T): any { if (!metaArgs) { return (...args: any[]) => (<any> onMessage)(args[1])(args[0], args[1], args[2]); } else { return onMessage(metaArgs); } }
OnMessage
identifier_name
on-message.ts
import { MetaClass } from '@tdm/core/tdm'; import { ServerProtocol, ClientResponse, ServerRequest } from '@tdm/service-mocker/shared'; import { OnMessageMetadata } from '../metadata'; const onMessage = MetaClass.decorator(OnMessageMetadata, 'method'); export type OnMessageHandler<T extends keyof ServerProtocol> = (...
}
{ return onMessage(metaArgs); }
conditional_block
issue-2631-b.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
request::<isize>(&m); }
let mut m: req::header_map = HashMap::new(); m.insert("METHOD".to_string(), Rc::new(RefCell::new(v)));
random_line_split
issue-2631-b.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let v = vec!(Rc::new("hi".to_string())); let mut m: req::header_map = HashMap::new(); m.insert("METHOD".to_string(), Rc::new(RefCell::new(v))); request::<isize>(&m); }
main
identifier_name
issue-2631-b.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let v = vec!(Rc::new("hi".to_string())); let mut m: req::header_map = HashMap::new(); m.insert("METHOD".to_string(), Rc::new(RefCell::new(v))); request::<isize>(&m); }
identifier_body
initramfs.rs
use std::process::Command; use ask; pub fn rebuild() -> bool
} } true }
{ println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") .arg("-p").arg("linux").status().expect("Failed to run mk...
identifier_body
initramfs.rs
use std::process::Command; use ask; pub fn
() -> bool { println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") .arg("-p").arg("linux").status().expect("Faile...
rebuild
identifier_name
initramfs.rs
use std::process::Command; use ask; pub fn rebuild() -> bool { println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") ...
true }
{ if !ask::yesno("Done?") { println!("Aborted."); return false; } }
conditional_block
initramfs.rs
use std::process::Command;
pub fn rebuild() -> bool { println!(); println!("Step 4: Update initramfs"); let mut skip_ask = false; if ask::yesno("Are you using mkinitcpio with the default kernel ('linux')?") { let status = Command::new("/usr/bin/sudo").arg("/usr/bin/mkinitcpio") .arg("-p").arg("linux").status()...
use ask;
random_line_split
background.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Background", inherited=False) %> ...
allow_quirks=True, flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER", )} ${helpers.predefined_type("background-image", "ImageLayer", initial_value="Either::First(None_)", initial_specified_value="Either::First(None_)", spec="https://drafts.csswg.org/css-backgrounds/#the-b...
initial_specified_value="SpecifiedValue::transparent()", spec="https://drafts.csswg.org/css-backgrounds/#background-color", animation_value_type="AnimatedColor", ignored_when_colors_disabled=True,
random_line_split
regions-bounds.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a,'b>(e: an_enum<'a>) -> an_enum<'b> { return e; //~ ERROR mismatched types } fn a_fn3<'a,'b>(e: a_class<'a>) -> a_class<'b> { return e; //~ ERROR mismatched types } fn main() { }
a_fn1
identifier_name
regions-bounds.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Check that explicit region bounds are allowed on the various // nominal types (but not on other types) and that they are type // checked. struct an_en...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
main.rs
. pub struct CurrencySchema<'a> { view: &'a mut Fork, } /// Declare layout of the data. Use an instance of [`MapIndex`][2] /// [2]: https://github.com/exonum/exonum-doc/blob/master/src/architecture/storage.md#mapindex /// to keep wallets in storage. Index values are serialized `Wallet` structs. /// /// Isolate the...
fn get_wallets(&self) -> Option<Vec<Wallet>> { let mut view = self.blockchain.fork(); let mut schema = CurrencySchema { view: &mut view }; let idx = schema.wallets(); let wallets: Vec<Wallet> = idx.values().collect(); if wallets.is_empty() { None } else ...
{ let mut view = self.blockchain.fork(); let mut schema = CurrencySchema { view: &mut view }; schema.wallet(pub_key) }
identifier_body
main.rs
. pub struct CurrencySchema<'a> { view: &'a mut Fork, } /// Declare layout of the data. Use an instance of [`MapIndex`][2] /// [2]: https://github.com/exonum/exonum-doc/blob/master/src/architecture/storage.md#mapindex /// to keep wallets in storage. Index values are serialized `Wallet` structs. /// /// Isolate the...
(&self) -> Option<Vec<Wallet>> { let mut view = self.blockchain.fork(); let mut schema = CurrencySchema { view: &mut view }; let idx = schema.wallets(); let wallets: Vec<Wallet> = idx.values().collect(); if wallets.is_empty() { None } else { Some(w...
get_wallets
identifier_name
main.rs
} } // // // // // // // // // // DATA LAYOUT // // // // // // // // // // /// Create schema of the key-value storage implemented by `MemoryDB`. In the /// present case a `Fork` of the database is used. pub struct CurrencySchema<'a> { view: &'a mut Fork, } /// Declare layout of the data. Use an instance of ...
pub fn decrease(self, amount: u64) -> Self { let balance = self.balance() - amount; Self::new(self.pub_key(), self.name(), balance)
random_line_split