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 |
|---|---|---|---|---|
MagicMeter.ts | import Game from '../../Game';
import GuiItem from './GuiItem';
import Hud from '../Hud';
export default class MagicMeter extends GuiItem {
background: Phaser.Sprite;
valueSprite: Phaser.Sprite;
maxHeight: number;
constructor(game: Game, parent: Hud, x: number, y: number, value: number = 0) {
... |
}
| {
super.setValue(val);
this.valueSprite.height = this.maxHeight * val;
this.valueSprite.position.y = (this.maxHeight - this.valueSprite.height) + (4 * this.valueSprite.scale.y);
return this;
} | identifier_body |
user32.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
#![feature(test)]
#![cfg(windows)]
extern crate user32;
extern crate test;
use user32::*;
use test::black_box as bb;
#[cfg(target_arch = "x86_64")]
#[test]
fn functions_x64() {
bb(GetClassLongPtrA);
bb(GetClassLongPtrW);
bb(G... | bb(ClipCursor);
bb(CloseClipboard);
bb(CloseDesktop);
bb(CloseWindow);
bb(CloseWindowStation);
bb(CountClipboardFormats);
bb(CreateCaret);
bb(CreateCursor);
bb(CreateWindowExW);
bb(DefWindowProcW);
bb(DeferWindowPos);
bb(DeleteMenu);
bb(DeregisterShellHookWindow);
... |
bb(ActivateKeyboardLayout);
// bb(AddClipboardFormatListener);
bb(AdjustWindowRect);
bb(AdjustWindowRectEx);
bb(AllowSetForegroundWindow);
bb(AnimateWindow);
bb(AnyPopup);
bb(ArrangeIconicWindows);
bb(AttachThreadInput);
bb(BeginPaint);
bb(BlockInput);
bb(BringWindowToTo... | identifier_body |
user32.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
#![feature(test)]
#![cfg(windows)]
extern crate user32;
extern crate test;
use user32::*;
use test::black_box as bb;
#[cfg(target_arch = "x86_64")]
#[test]
fn functions_x64() {
bb(GetClassLongPtrA);
bb(GetClassLongPtrW);
bb(G... | bb(SetWindowLongPtrA);
bb(SetWindowLongPtrW);
}
#[test]
fn functions() {
bb(ActivateKeyboardLayout);
// bb(AddClipboardFormatListener);
bb(AdjustWindowRect);
bb(AdjustWindowRectEx);
bb(AllowSetForegroundWindow);
bb(AnimateWindow);
bb(AnyPopup);
bb(ArrangeIconicWindows);
bb(At... | bb(SetClassLongPtrA);
bb(SetClassLongPtrW); | random_line_split |
user32.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
#![feature(test)]
#![cfg(windows)]
extern crate user32;
extern crate test;
use user32::*;
use test::black_box as bb;
#[cfg(target_arch = "x86_64")]
#[test]
fn functions_x64() {
bb(GetClassLongPtrA);
bb(GetClassLongPtrW);
bb(G... | ) {
bb(ActivateKeyboardLayout);
// bb(AddClipboardFormatListener);
bb(AdjustWindowRect);
bb(AdjustWindowRectEx);
bb(AllowSetForegroundWindow);
bb(AnimateWindow);
bb(AnyPopup);
bb(ArrangeIconicWindows);
bb(AttachThreadInput);
bb(BeginPaint);
bb(BlockInput);
bb(BringWindowT... | unctions( | identifier_name |
test.rs | // Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed unde... | () {
let mut reg = Register::new("/home/flaper87/workspace/personal/rust-drops/build");
reg.load("drops_console");
reg.call("info", Some(json::Decoder::new(json::from_str("\"My String\"").unwrap())));
reg.call("info", None);
}
| test_register_console | identifier_name |
test.rs | // Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed unde... | {
let mut reg = Register::new("/home/flaper87/workspace/personal/rust-drops/build");
reg.load("drops_console");
reg.call("info", Some(json::Decoder::new(json::from_str("\"My String\"").unwrap())));
reg.call("info", None);
} | identifier_body | |
test.rs | // 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 | //
// Unless required by applicable law or agreed to in writing, software
// 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 Licen... | //
// http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
ini.py | from __future__ import absolute_import, unicode_literals
import logging
import os
from ...platformdirs import user_config_dir
from ..info import PY3
from ..util import ConfigParser
from ..util.path import Path
from ..util.six import ensure_str
from .convert import convert
class IniConfig(object):
VIRTUALENV_C... |
def _load(self):
with self.config_file.open("rt") as file_handler:
reader = getattr(self.config_parser, "read_file" if PY3 else "readfp")
reader(file_handler)
def get(self, key, as_type):
cache_key = key, as_type
if cache_key in self._cache:
return ... | logging.error("failed to read config file %s because %r", config_file, exception) | conditional_block |
ini.py | from __future__ import absolute_import, unicode_literals
import logging
import os
from ...platformdirs import user_config_dir
from ..info import PY3
from ..util import ConfigParser
from ..util.path import Path
from ..util.six import ensure_str
from .convert import convert
class IniConfig(object):
VIRTUALENV_C... | (self, env=None):
env = os.environ if env is None else env
config_file = env.get(self.VIRTUALENV_CONFIG_FILE_ENV_VAR, None)
self.is_env_var = config_file is not None
config_file = (
Path(config_file)
if config_file is not None
else Path(user_config_dir... | __init__ | identifier_name |
ini.py | from __future__ import absolute_import, unicode_literals
import logging
import os
from ...platformdirs import user_config_dir
from ..info import PY3
from ..util import ConfigParser
from ..util.path import Path
from ..util.six import ensure_str
from .convert import convert
class IniConfig(object):
VIRTUALENV_C... | self.config_parser = ConfigParser.ConfigParser()
try:
self._load()
self.has_virtualenv_section = self.config_parser.has_section(self.section)
except Exception as exc:
exception = exc
if exception is not N... | env = os.environ if env is None else env
config_file = env.get(self.VIRTUALENV_CONFIG_FILE_ENV_VAR, None)
self.is_env_var = config_file is not None
config_file = (
Path(config_file)
if config_file is not None
else Path(user_config_dir(appname="virtualenv", app... | identifier_body |
ini.py | from __future__ import absolute_import, unicode_literals
import logging
import os
from ...platformdirs import user_config_dir
from ..info import PY3
from ..util import ConfigParser
from ..util.path import Path
from ..util.six import ensure_str
from .convert import convert
class IniConfig(object):
VIRTUALENV_C... | def get(self, key, as_type):
cache_key = key, as_type
if cache_key in self._cache:
return self._cache[cache_key]
# noinspection PyBroadException
try:
source = "file"
raw_value = self.config_parser.get(self.section, key.lower())
value = ... | reader = getattr(self.config_parser, "read_file" if PY3 else "readfp")
reader(file_handler)
| random_line_split |
slide-toggle-harness-example.spec.ts | import {ComponentFixture, TestBed} from '@angular/core/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatSlideToggleHarness} from '@angular/material/slide-toggle/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {MatSlideToggleModule} from '@angular/material... | });
it('should get disabled state', async () => {
const [enabledToggle, disabledToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
expect(await enabledToggle.isDisabled()).toBe(false);
expect(await disabledToggle.isDisabled()).toBe(true);
});
it('should get label text', async () => {
... | expect(await slideToggles[0].getLabelText()).toBe('First'); | random_line_split |
stack.py | from functools import partial
from xml.sax.saxutils import quoteattr
from navmazing import NavigateToSibling, NavigateToAttribute
from selenium.common.exceptions import NoSuchElementException
import cfme.fixtures.pytest_selenium as sel
from cfme import web_ui as ui
from cfme.exceptions import DestinationNotFound, Sta... | elif from_dest == 'Details':
cfg_btn("Remove this Orchestration Stack", invokes_alert=True)
sel.handle_alert()
# The delete initiated message may get missed if the delete is fast
try:
flash.assert_message_contain("Delete initiated for 1 Orchestration Stacks")
... | random_line_split | |
stack.py | from functools import partial
from xml.sax.saxutils import quoteattr
from navmazing import NavigateToSibling, NavigateToAttribute
from selenium.common.exceptions import NoSuchElementException
import cfme.fixtures.pytest_selenium as sel
from cfme import web_ui as ui
from cfme.exceptions import DestinationNotFound, Sta... |
@navigator.register(Stack, 'Details')
class Details(CFMENavigateStep):
prerequisite = NavigateToSibling('All')
def am_i_here(self):
return match_page(summary='{} (Summary)'.format(self.obj.name))
def step(self):
sel.click(self.obj.find_quadicon())
@navigator.register(Stack, 'EditTags'... | prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn')
def am_i_here(self):
return match_page(summary='Orchestration Stacks')
def step(self):
self.prerequisite_view.navigation.select('Compute', 'Clouds', 'Stacks')
def resetter(self):
tb.select('Grid View')
sel.... | identifier_body |
stack.py | from functools import partial
from xml.sax.saxutils import quoteattr
from navmazing import NavigateToSibling, NavigateToAttribute
from selenium.common.exceptions import NoSuchElementException
import cfme.fixtures.pytest_selenium as sel
from cfme import web_ui as ui
from cfme.exceptions import DestinationNotFound, Sta... |
elif from_dest == 'Details':
cfg_btn("Remove this Orchestration Stack", invokes_alert=True)
sel.handle_alert()
# The delete initiated message may get missed if the delete is fast
try:
flash.assert_message_contain("Delete initiated for 1 Orchestration Stacks")
... | sel.check(Quadicon(self.name, self.quad_name).checkbox())
cfg_btn("Remove Orchestration Stacks", invokes_alert=True) | conditional_block |
stack.py | from functools import partial
from xml.sax.saxutils import quoteattr
from navmazing import NavigateToSibling, NavigateToAttribute
from selenium.common.exceptions import NoSuchElementException
import cfme.fixtures.pytest_selenium as sel
from cfme import web_ui as ui
from cfme.exceptions import DestinationNotFound, Sta... | (CFMENavigateStep):
prerequisite = NavigateToSibling('Details')
def am_i_here(self):
return match_page(summary='{} (Parameters)'.format(self.obj.name))
def step(self):
accordion.click('Relationships')
# Click by anchor title since text contains a dynamic component
sel.click... | RelationshipParameters | identifier_name |
test_example_config.py | from __future__ import unicode_literals
import os
from twisted.trial import unittest
example_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
os.path.pardir,
os.path.pardir,
"share",
"example-tilde.ini",
)
from tilde.loader import load_config
from tilde.commands import ubun... | (unittest.TestCase):
def setUp(self):
self.cfg = load_config(example_file_path)
def test_resulting_config(self):
srv = self.cfg["servers"]
self.assertIn("foo", srv)
self.assertIn("bar", srv)
foo = srv["foo"]
bar = srv["bar"]
self.assertEquals("foo.domai... | LoadTest | identifier_name |
test_example_config.py | from __future__ import unicode_literals
import os
from twisted.trial import unittest
example_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
os.path.pardir,
os.path.pardir,
"share",
"example-tilde.ini",
)
from tilde.loader import load_config
from tilde.commands import ubun... | cmds = self.cfg["commands"]
self.assertIn("ubuntu", cmds)
self.assertIn("custom", cmds)
| def setUp(self):
self.cfg = load_config(example_file_path)
def test_resulting_config(self):
srv = self.cfg["servers"]
self.assertIn("foo", srv)
self.assertIn("bar", srv)
foo = srv["foo"]
bar = srv["bar"]
self.assertEquals("foo.domain", foo.hostname)
... | identifier_body |
test_example_config.py | from __future__ import unicode_literals
import os
from twisted.trial import unittest
example_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
os.path.pardir,
os.path.pardir,
"share",
"example-tilde.ini",
)
from tilde.loader import load_config
from tilde.commands import ubun... | srv = self.cfg["servers"]
self.assertIn("foo", srv)
self.assertIn("bar", srv)
foo = srv["foo"]
bar = srv["bar"]
self.assertEquals("foo.domain", foo.hostname)
self.assertEquals("/backup/homes", foo.archive_root)
self.assertEquals("bar", bar.hostname, "Sh... | def setUp(self):
self.cfg = load_config(example_file_path)
def test_resulting_config(self): | random_line_split |
studio_mixin.py | ": self.ALLOWED_FILE_EXTENSIONS,
"FILE_EXT_BLACK_LIST": self.FILE_EXT_BLACK_LIST,
}
fragment.initialize_js('OpenAssessmentEditor', js_context_dict)
return fragment
def editor_context(self):
"""
Update the XBlock's XML.
Returns:
dict with keys... | self.prompts_type = data['prompts_type']
self.rubric_criteria = data['criteria']
self.rubric_assessments = data['assessments']
self.editor_assessments_order = data['editor_assessments_order']
self.rubric_feedback_prompt = data['feedback_prompt']
self.rubric_feedback_defau... | random_line_split | |
studio_mixin.py | ,
'msg': self._("Error: Text Response and File Upload Response cannot both be disabled")
}
if not data['text_response'] and data['file_upload_response'] == 'optional':
return {'success': False,
'msg': self._("Error: When Text Response is disabled, File... | return None | conditional_block | |
studio_mixin.py | (self, context=None): # pylint: disable=unused-argument
"""
Render the OpenAssessment XBlock for editing in Studio.
Args:
context: Not actively used for this view.
Returns:
(Fragment): An HTML fragment for editing the configuration of this XBlock.
"""
... | studio_view | identifier_name | |
studio_mixin.py | with
# an empty default option.
criteria = copy.deepcopy(self.rubric_criteria_with_labels)
if not criteria:
criteria = self.DEFAULT_CRITERIA
# To maintain backwards compatibility, if there is no
# feedback_default_text configured for the xblock, use the default text... | """
Transform the rubric assessments list into the context
we will pass to the Django template.
Args:
assessment_dates: List of assessment date ranges (tuples of start/end datetimes).
Returns:
dict
"""
assessments = {}
for asmnt, date_ra... | identifier_body | |
fetch_sra_files.py | #(c) 2014 Emory University. All Rights Reserved
# Code written by: Michael Sauria (mgehrin@emory.edu)
import sys
import os
import subprocess
file_list, tmp_dir, out_dir, fastq_dump = sys.argv[1:5]
files = []
for line in open(file_list, 'r'):
line = line.strip()
if not line or line.startswith('#'):
co... | #!/usr/bin/env python | random_line_split | |
fetch_sra_files.py | #!/usr/bin/env python
#(c) 2014 Emory University. All Rights Reserved
# Code written by: Michael Sauria (mgehrin@emory.edu)
import sys
import os
import subprocess
file_list, tmp_dir, out_dir, fastq_dump = sys.argv[1:5]
files = []
for line in open(file_list, 'r'):
line = line.strip()
if not line or line.start... |
for file in files:
srr, srx = file
if (not os.path.exists("%s/%s_1.fastq" % (out_dir, srr)) or
not os.path.exists("%s/%s_2.fastq" % (out_dir, srr))):
subprocess.call('cd %s; %s %s.sra --split-3' % (tmp_dir, fastq_dump, srr), shell=True)
subprocess.call('mv %s/%s_1.fastq %s/... | if not os.path.exists("%s/%s.sra" % (tmp_dir, srr)):
subprocess.call('wget ftp://ftp-trace.ncbi.nlm.nih.gov/sra/sra-instant/reads/ByExp/sra/%s/%s/%s/%s/%s.sra -O %s' % (srx[:3], srx[:6], srx, srr, srr, "%s/%s.sra" % (tmp_dir, srr)), shell=True) | conditional_block |
lib.rs | wResize,
NsResize,
NeswResize,
NwseResize,
ColResize,
RowResize,
AllScroll,
ZoomIn,
ZoomOut,
}
/// Sends messages to the embedder.
pub struct EmbedderProxy {
pub sender: Sender<(Option<TopLevelBrowsingContextId>, EmbedderMsg)>,
pub event_loop_waker: Box<dyn EventLoopWaker>,
}
i... | Self {
title,
artist: "".to_owned(),
album: "".to_owned(),
}
}
}
| identifier_body | |
lib.rs | (Clone, Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)]
pub enum Cursor {
None, | ContextMenu,
Help,
Progress,
Wait,
Cell,
Crosshair,
Text,
VerticalText,
Alias,
Copy,
Move,
NoDrop,
NotAllowed,
Grab,
Grabbing,
EResize,
NResize,
NeResize,
NwResize,
SResize,
SeResize,
SwResize,
WResize,
EwResize,
NsResiz... | Default,
Pointer, | random_line_split |
lib.rs | , Copy, Deserialize, Eq, FromPrimitive, PartialEq, Serialize)]
pub enum | {
None,
Default,
Pointer,
ContextMenu,
Help,
Progress,
Wait,
Cell,
Crosshair,
Text,
VerticalText,
Alias,
Copy,
Move,
NoDrop,
NotAllowed,
Grab,
Grabbing,
EResize,
NResize,
NeResize,
NwResize,
SResize,
SeResize,
SwResize,... | Cursor | identifier_name |
karma.conf.js | // Karma configuration
// Generated on Mon Jun 22 2015 15:35:14 GMT+0200 (SAST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/... | // start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
}; | random_line_split | |
arrays.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
/// Array containing sign public key bytes.
pub type SignPublicKey = [u8; SIGN_PUBLIC_KEY_LEN];
/// Array containing sign private key bytes.
pub type SignSecretKey = [u8; SIGN_SECRET_KEY_LEN];
/// Array containing `XorName` bytes.
pub type XorNameArray = [u8; XOR_NAME_LEN]; |
/// Array containing BLS public key.
pub type BlsPublicKey = [u8; BLS_PUBLIC_KEY_LEN]; | random_line_split |
instr_kandw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn kandw_1() {
run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K1))... | () {
run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K7)), operand2: Some(Direct(K2)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 236, 65, 255], OperandSize::Qword)
}
| kandw_2 | identifier_name |
instr_kandw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn kandw_1() {
run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K1))... | {
run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K7)), operand2: Some(Direct(K2)), operand3: Some(Direct(K7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 236, 65, 255], OperandSize::Qword)
} | identifier_body | |
instr_kandw.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn kandw_1() {
run_test(&Instruction { mnemonic: Mnemonic::KANDW, operand1: Some(Direct(K1))... | } | random_line_split | |
context.rs | _time_ms: 0.0,
is_parallel: None,
is_large: None,
}
}
}
/// Format the statistics in a way that the performance test harness understands.
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2
impl fmt::Display for TraversalStatistics {
fn fmt(&self, f: &mut fmt::Format... | random_line_split | ||
context.rs | Currently we use an OpaqueNode since we
/// only use this for identity checks, but we could use SendElement if there
/// were a good reason to.
element: OpaqueNode,
/// Whether the element is being styled for the first time.
is_initial_style: bool,
/// A Vec of possibly expired animations. Used... | {
unsafe { el.update_animations(before_change_style, tasks) };
} | conditional_block | |
context.rs | ancestor link.
pub visited_rules: Option<StrongRuleNode>,
}
impl CascadeInputs {
/// Construct inputs from previous cascade results, if any.
pub fn new_from_style(style: &ComputedValues) -> Self {
CascadeInputs {
rules: style.rules.clone(),
visited_rules: style.visited_styl... | (&self) -> Self {
if self.0.is_none() {
return EagerPseudoCascadeInputs(None)
}
let self_inputs = self.0.as_ref().unwrap();
let mut inputs: [Option<CascadeInputs>; EAGER_PSEUDO_COUNT] = Default::default();
for i in 0..EAGER_PSEUDO_COUNT {
inputs[i] = self_... | clone | identifier_name |
context.rs | &'a TraversalStatistics {
type Output = TraversalStatistics;
fn add(self, other: Self) -> TraversalStatistics {
debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0,
"traversal_time_ms should be set at the end by the caller");
debug_assert!(self.se... | {
SelectorFlagsMap {
map: FnvHashMap::default(),
cache: LRUCache::default(),
}
} | identifier_body | |
person-edit.component.ts | import { IPerson } from '../person.model';
import { PersonService } from '../person.service';
import { ActivatedRoute, ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { Component, Injectable, OnDestroy, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Co... | (
private route: ActivatedRoute,
private service: PersonService,
private router: Router) {}
ngOnInit(): void {
// const s = this.route.params.subscribe((x) => {
// const id = x.id;
// if(id) {
// this.service.get(id).then((x) => {
// this.person = x;
// });
... | constructor | identifier_name |
person-edit.component.ts | import { IPerson } from '../person.model';
import { PersonService } from '../person.service';
import { ActivatedRoute, ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { Component, Injectable, OnDestroy, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Co... |
ngOnInit(): void {
// const s = this.route.params.subscribe((x) => {
// const id = x.id;
// if(id) {
// this.service.get(id).then((x) => {
// this.person = x;
// });
// } else {
// this.person = {
// id: null,
// name: null
// };
... | {} | identifier_body |
person-edit.component.ts | import { IPerson } from '../person.model';
import { PersonService } from '../person.service'; | @Component({
templateUrl: './person-edit.component.html',
})
export class PersonEditComponent implements OnInit, OnDestroy {
subscriptions = new Array<any>();
person: IPerson = { id: null, name: null };
constructor(
private route: ActivatedRoute,
private service: PersonService,
private router: Rout... | import { ActivatedRoute, ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { Component, Injectable, OnDestroy, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
| random_line_split |
sticker.py | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... |
class _GuildStickerOptional(TypedDict, total=False):
user: User
class GuildSticker(BaseSticker, _GuildStickerOptional):
type: Literal[2]
available: bool
guild_id: Snowflake
Sticker = Union[BaseSticker, StandardSticker, GuildSticker]
class StickerPack(TypedDict):
id: Snowflake
stickers: L... | sort_value: int
pack_id: Snowflake | random_line_split |
sticker.py | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... | (BaseSticker, _GuildStickerOptional):
type: Literal[2]
available: bool
guild_id: Snowflake
Sticker = Union[BaseSticker, StandardSticker, GuildSticker]
class StickerPack(TypedDict):
id: Snowflake
stickers: List[StandardSticker]
name: str
sku_id: Snowflake
cover_sticker_id: Snowflake
... | GuildSticker | identifier_name |
sticker.py | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... |
class StandardSticker(BaseSticker):
type: Literal[1]
sort_value: int
pack_id: Snowflake
class _GuildStickerOptional(TypedDict, total=False):
user: User
class GuildSticker(BaseSticker, _GuildStickerOptional):
type: Literal[2]
available: bool
guild_id: Snowflake
Sticker = Union[BaseSt... | id: Snowflake
name: str
description: str
tags: str
format_type: StickerFormatType | identifier_body |
security-group.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map } from 'rxjs/operators';
import { Rules } from '../../shared/components/security-group-builder/rules';
import { BackendResource } from '../../shared/decorators';
im... | map(result => {
if (!result || result.success !== 'true') {
return throwError(result);
}
}),
);
}
} | public deleteGroup(securityGroup: SecurityGroup): Observable<any> {
return this.remove({ id: securityGroup.id }).pipe( | random_line_split |
security-group.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map } from 'rxjs/operators';
import { Rules } from '../../shared/components/security-group-builder/rules';
import { BackendResource } from '../../shared/decorators';
im... |
}),
);
}
}
| {
return throwError(result);
} | conditional_block |
security-group.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map } from 'rxjs/operators';
import { Rules } from '../../shared/components/security-group-builder/rules';
import { BackendResource } from '../../shared/decorators';
im... | extends BaseBackendService<SecurityGroup> {
constructor(
protected http: HttpClient,
private privateSecurityGroupCreation: PrivateSecurityGroupCreationService,
private sharedSecurityGroupCreation: SharedSecurityGroupCreationService,
private templateSecurityGroupCreation: TemplateSecurityGroupCreation... | SecurityGroupService | identifier_name |
security-group.service.ts | import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map } from 'rxjs/operators';
import { Rules } from '../../shared/components/security-group-builder/rules';
import { BackendResource } from '../../shared/decorators';
im... |
}
| {
return this.remove({ id: securityGroup.id }).pipe(
map(result => {
if (!result || result.success !== 'true') {
return throwError(result);
}
}),
);
} | identifier_body |
itemdemo.js | import * as React from 'react';
import {Row,Col,Table,Code,Items,Item} from 'yrui';
import thead from './thead';
let items=[{
key:'style',
expr:'设置items样式',
type:'object',
values:'-',
default:'-',
}];
let item=[{
key:'border',
expr:'设置border样式',
type:'string',
values:'-',
default:'-',
}];
const c... | }
| ms>
<Item>
<h2>代码示例</h2>
<Code title="input" code={code} />
</Item>
<Item>
<Row gutter={8}>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={items} noBorder={true} />
</Col>
<Col span={6... | identifier_body |
itemdemo.js | import * as React from 'react';
import {Row,Col,Table,Code,Items,Item} from 'yrui';
import thead from './thead';
let items=[{
key:'style',
expr:'设置items样式',
type:'object',
values:'-',
default:'-',
}];
let item=[{
key:'border',
expr:'设置border样式',
type:'string',
values:'-',
default:'-',
}];
const c... | tems>
<Item>
<h2>代码示例</h2>
<Code title="input" code={code} />
</Item>
<Item>
<Row gutter={8}>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={items} noBorder={true} />
</Col>
<Col span=... | <I | identifier_name |
itemdemo.js | import * as React from 'react';
import {Row,Col,Table,Code,Items,Item} from 'yrui';
import thead from './thead';
let items=[{
key:'style',
expr:'设置items样式',
type:'object',
values:'-',
default:'-',
}]; | expr:'设置border样式',
type:'string',
values:'-',
default:'-',
}];
const code=`
<Items>
<Item>
<h2>items配置</h2>
<Table thead={thead} tbody={items} />
</Item>
<Item>
<h2>item配置</h2>
<Table thead={thead} tbody={item} />
</Item>
</Items>
`;
export default class ItemsDemo extends React.Compone... | let item=[{
key:'border', | random_line_split |
card.js | Template.card.created = function() {
// TODO: Ugly hack, make it beautiful and safe
var cardType = this.view.parentView.name.split(".")[1];
if(Template[cardType + "Details"] === undefined) {
console.error("Card details template '" + cardType + "Details', doesn't exist");
} else {
Templat... | });
Template.card.events({
"click #showDetails": function(e, template) {
TemplateVar.set(template, "showDetails", !TemplateVar.get("showDetails"));
}
}); | return Template[TemplateVar.get("cardType") + "Details"];
},
cardType: function() {
return TemplateVar.get("cardType");
} | random_line_split |
card.js | Template.card.created = function() {
// TODO: Ugly hack, make it beautiful and safe
var cardType = this.view.parentView.name.split(".")[1];
if(Template[cardType + "Details"] === undefined) | else {
TemplateVar.set(this, "cardType", cardType);
}
};
Template.card.helpers({
error: "",
showDetails: function() {
return this.singleCard ? true : TemplateVar.get("showDetails");
},
detailsTemplate: function() {
return Template[TemplateVar.get("cardType") + "Details"];
... | {
console.error("Card details template '" + cardType + "Details', doesn't exist");
} | conditional_block |
ngtools_api2.d.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
*/
/// <amd-module name="@angular/compiler-cli/src/ngtools_api2" />
/**
* This is a private API for @ngtools/webpack. T... | i18nOutFile?: string;
i18nInFormat?: string;
i18nInLocale?: string;
i18nInFile?: string;
i18nInMissingTranslations?: 'error' | 'warning' | 'ignore';
preserveWhitespaces?: boolean;
disableTypeScriptVersionCheck?: boolean;
}
export interface CompilerHost extends ts.CompilerHost {
moduleNam... | disableExpressionLowering?: boolean;
i18nOutLocale?: string;
i18nOutFormat?: string; | random_line_split |
db-restore.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use backup_cli::{
backup_types::{
epoch_ending::restore::{EpochEndingRestoreController, EpochEndingRestoreOpt},
state_snapshot::restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt},
... | EpochEnding {
#[structopt(flatten)]
opt: EpochEndingRestoreOpt,
#[structopt(subcommand)]
storage: StorageOpt,
},
StateSnapshot {
#[structopt(flatten)]
opt: StateSnapshotRestoreOpt,
#[structopt(subcommand)]
storage: StorageOpt,
},
Transa... | random_line_split | |
db-restore.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use backup_cli::{
backup_types::{
epoch_ending::restore::{EpochEndingRestoreController, EpochEndingRestoreOpt},
state_snapshot::restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt},
... | () -> Result<()> {
main_impl().await.map_err(|e| {
error!("main_impl() failed: {}", e);
e
})
}
async fn main_impl() -> Result<()> {
Logger::new().level(Level::Info).read_env().init();
let _mp = MetricsPusher::start();
let opt = Opt::from_args();
let global_opt: GlobalRestoreOpt... | main | identifier_name |
db-restore.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use backup_cli::{
backup_types::{
epoch_ending::restore::{EpochEndingRestoreController, EpochEndingRestoreOpt},
state_snapshot::restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt},
... |
async fn main_impl() -> Result<()> {
Logger::new().level(Level::Info).read_env().init();
let _mp = MetricsPusher::start();
let opt = Opt::from_args();
let global_opt: GlobalRestoreOptions = opt.global.clone().try_into()?;
match opt.restore_type {
RestoreType::EpochEnding { opt, storage }... | {
main_impl().await.map_err(|e| {
error!("main_impl() failed: {}", e);
e
})
} | identifier_body |
yf.py | #!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgp... |
# parse command line
p = OptionParser(usage="""usage: %prog [options] <vtk_file>
Inserts yield function values into <vtk_file>.
Only 3D input is accepted: this program assumes that the individual yield functions are functions of x, y, z.
""")
p.add_option("-v", action="store_true", dest="verbose", help="Verb... | yfs = []
if opts.twoD_example:
yfs += [- x, - y, y - 1.0, - y - 0.5 + 0.5 * x]
if opts.twoD_example_alternative:
yfs += [y - 1.0, - y - 0.5 + 0.5 * x, - x, - y]
if opts.dp:
yfs += [y + x * dp_sinphi - dp_c * dp_cosphi, x - dp_t, -x - dp_tc]
if opts.tensile:
yfs += [x - opts.tensile_s... | identifier_body |
yf.py | #!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgp... | (f_diff):
if (abs(f_diff) >= opts.smoothing_tol):
return 0.0
return 0.5 * (opts.smoothing_tol - abs(f_diff)) - opts.smoothing_tol / math.pi * math.cos(0.5 * math.pi * f_diff / opts.smoothing_tol)
def yield_function_2(yf1, yf2):
return max(yf1, yf2) + ismoother(yf1 - yf2)
def yield_function(x, y, z):
... | ismoother | identifier_name |
yf.py | #!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgp... | in_file = args[0]
if opts.verbose: print "Reading", in_file
if in_file.endswith(".vtp"):
indata = vtk.vtkXMLPolyDataReader()
writer = vtk.vtkXMLPolyDataWriter()
elif in_file.endswith(".vtu"):
indata = vtk.vtkXMLUnstructuredGridReader()
writer = vtk.vtkXMLUnstructuredGridWriter()
elif in_file.endswith(".vtr... | # get the com filename
if len(args) != 1:
p.print_help()
sys.exit(1) | random_line_split |
yf.py | #!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgp... |
if opts.tensile:
yfs += [x - opts.tensile_strength, y - opts.tensile_strength, z - opts.tensile_strength]
if opts.mc:
yfs += [0.5 * (x - z) + 0.5 * (x + z) * sinphi - cohcos,
0.5 * (y - z) + 0.5 * (y + z) * sinphi - cohcos,
0.5 * (x - y) + 0.5 * (x + y) * sinphi - cohcos,
... | yfs += [y + x * dp_sinphi - dp_c * dp_cosphi, x - dp_t, -x - dp_tc] | conditional_block |
moviefinder.service.ts | import { Injectable } from '@angular/core';
import { Jsonp } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class | {
api_key: string;
now: Date = new Date();
nowless7: Date = new Date();
constructor(private _jsonp: Jsonp) {
this.api_key = '9a30790369ff04aab86bf2e697c42be0';
this.nowless7.setDate(this.now.getDate() - 7);
}
getPopular() {
let url = 'https://api.themoviedb.org/3/discov... | MoviesService | identifier_name |
moviefinder.service.ts | import { Injectable } from '@angular/core';
import { Jsonp } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class MoviesService {
api_key: string;
now: Date = new Date();
nowless7: Date = new Date();
constructor(private _jsonp: Jsonp) {
this.api_key = '9a30790369ff04aab86bf2e697c... | console.log(obj.getMonth(), 'obj');
return obj.getFullYear().toString() + '-' + (obj.getMonth() + 1) + '-' + obj.getDate().toString();
}
serachMovie(searchStr: string) {
let url = 'https://api.themoviedb.org/3/search/movie?callback=JSONP_CALLBACK&query='
+ searchStr + '&sort... | random_line_split | |
course_search.py | from bs4 import BeautifulSoup
from models.course import Course
import requests
default_postdata = {
'CAMPUS': '0',
'TERMYEAR': '201709',
'CORE_CODE': 'AR%',
'subj_code': '',
'CRSE_NUMBER': '',
'crn': '',
'open_only': 'on',
'BTN_PRESSED': 'FIND class sections',
}
url = 'https://banweb.b... | """ Get the open course that matches the crn passed in
:param crn: The course request number of the course section
:return: Returns a list of the open courses that are matched
"""
postdata = default_postdata.copy()
postdata['crn'] = crn.strip()
postdata['TERMYEAR'] = semester
return _... | def get_open_courses_by_crn(crn, semester): | random_line_split |
course_search.py | from bs4 import BeautifulSoup
from models.course import Course
import requests
default_postdata = {
'CAMPUS': '0',
'TERMYEAR': '201709',
'CORE_CODE': 'AR%',
'subj_code': '',
'CRSE_NUMBER': '',
'crn': '',
'open_only': 'on',
'BTN_PRESSED': 'FIND class sections',
}
url = 'https://banweb.b... | professor = cells_text[6].strip()
open_courses.append(Course(crn, label, title, professor))
return open_courses
def get_open_courses_by_course(subj, num, semester):
""" Get the open courses that match the course subject and number passed in
:param subj: The subject abbreviation
... | req = requests.post(url, data=data)
soup = BeautifulSoup(req.content, 'html5lib')
rows = soup.select('table.dataentrytable tbody tr')
open_courses = list()
# The first row is the header row with the column labels
# If there's only one row, the rest of the table is empty, so there are no results
... | identifier_body |
course_search.py | from bs4 import BeautifulSoup
from models.course import Course
import requests
default_postdata = {
'CAMPUS': '0',
'TERMYEAR': '201709',
'CORE_CODE': 'AR%',
'subj_code': '',
'CRSE_NUMBER': '',
'crn': '',
'open_only': 'on',
'BTN_PRESSED': 'FIND class sections',
}
url = 'https://banweb.b... | (crn, semester):
""" Get the open course that matches the crn passed in
:param crn: The course request number of the course section
:return: Returns a list of the open courses that are matched
"""
postdata = default_postdata.copy()
postdata['crn'] = crn.strip()
postdata['TERMYEAR'] = semes... | get_open_courses_by_crn | identifier_name |
course_search.py | from bs4 import BeautifulSoup
from models.course import Course
import requests
default_postdata = {
'CAMPUS': '0',
'TERMYEAR': '201709',
'CORE_CODE': 'AR%',
'subj_code': '',
'CRSE_NUMBER': '',
'crn': '',
'open_only': 'on',
'BTN_PRESSED': 'FIND class sections',
}
url = 'https://banweb.b... |
return open_courses
def get_open_courses_by_course(subj, num, semester):
""" Get the open courses that match the course subject and number passed in
:param subj: The subject abbreviation
:param num: The course number
:return: Returns a list of the open courses that are matched
"""
postd... | rows = rows[1:]
for row in rows:
cells = row.select('td')
cells_text = list(map(lambda x: x.get_text(), cells))
crn = cells_text[0].strip()
label = cells_text[1].strip()
title = cells_text[2].strip()
professor = cells_text[6].strip()
... | conditional_block |
main.rs | #![warn(rust_2018_idioms)] // while we're getting used to 2018
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::explicit_iter_loop)]
#![allow(clippy::redundant_closure)]
#![allow(clippy::blocks_in_if_conditions)] // clippy doesn't agree with rustfmt 😂
#![allo... | mod shell_quoting;
mod standard_lib;
mod test;
mod timings;
mod tool_paths;
mod tree;
mod tree_graph_features;
mod unit_graph;
mod update;
mod vendor;
mod verify_project;
mod version;
mod warn_on_failure;
mod weak_dep_features;
mod workspaces;
mod yank;
#[cargo_test]
fn aaa_trigger_cross_compile_disabled_check() {
... | mod rustdocflags;
mod rustflags;
mod search; | random_line_split |
main.rs | #![warn(rust_2018_idioms)] // while we're getting used to 2018
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::explicit_iter_loop)]
#![allow(clippy::redundant_closure)]
#![allow(clippy::blocks_in_if_conditions)] // clippy doesn't agree with rustfmt 😂
#![allo... | // This triggers the cross compile disabled check to run ASAP, see #5141
cargo_test_support::cross_compile::disabled();
}
| identifier_body | |
main.rs | #![warn(rust_2018_idioms)] // while we're getting used to 2018
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::explicit_iter_loop)]
#![allow(clippy::redundant_closure)]
#![allow(clippy::blocks_in_if_conditions)] // clippy doesn't agree with rustfmt 😂
#![allo... | {
// This triggers the cross compile disabled check to run ASAP, see #5141
cargo_test_support::cross_compile::disabled();
}
| _trigger_cross_compile_disabled_check() | identifier_name |
game-data.service.ts | import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { from, Observable } from 'rxjs';
import { ResourceManager } from '../../../game/pow-core/resource-manager';
import { AppState } from '../../app.model';
import { GameDataAddSheetAction } from './game-data.actions';
import { SPREADSH... |
/** Load game data from google spreadsheet */
loadGameData(spreadsheetId: string = SPREADSHEET_ID): Observable<void> {
return from(
this.loader.loadAsType(spreadsheetId, GameDataResource).then((resource) => {
this.store.dispatch(
new GameDataAddSheetAction('weapons', resource.data.weapo... |
@Injectable()
export class GameDataService {
constructor(public loader: ResourceManager, public store: Store<AppState>) {} | random_line_split |
game-data.service.ts | import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { from, Observable } from 'rxjs';
import { ResourceManager } from '../../../game/pow-core/resource-manager';
import { AppState } from '../../app.model';
import { GameDataAddSheetAction } from './game-data.actions';
import { SPREADSH... | (spreadsheetId: string = SPREADSHEET_ID): Observable<void> {
return from(
this.loader.loadAsType(spreadsheetId, GameDataResource).then((resource) => {
this.store.dispatch(
new GameDataAddSheetAction('weapons', resource.data.weapons)
);
this.store.dispatch(new GameDataAddSheet... | loadGameData | identifier_name |
RectInternalRepresentation.js | (function(window) {
var RectInternalRepresentation = function(primitive) {
var me = new ArmContext.InternalRepresentation(primitive);
this._width = 10;
this._height = 10;
me.GetWidth = function() {
return this._width;
};
me.SetWidth = f... | ;
};
break;
};
};
this._points = new $M( [
[0 ,0 ,1],
[this._width,0 ,1],
[this._width,this._height,1],
[0 ,this._height,1]
]... | {
this._onChanged.call(primitive);
} | conditional_block |
RectInternalRepresentation.js | (function(window) {
var RectInternalRepresentation = function(primitive) {
var me = new ArmContext.InternalRepresentation(primitive);
this._width = 10;
this._height = 10;
|
me.SetWidth = function(O) {
gizmo.Filter(O, "Number");
this.Update({ width: O, height: this.GetHeight() });
};
me.GetHeight = function() {
return this._height;
};
me.SetHeight = function(O) {
gizmo.Filter(O, "Numb... | me.GetWidth = function() {
return this._width;
}; | random_line_split |
unboxed-closure-sugar-region.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // except according to those terms.
// Test interaction between unboxed closure sugar and region
// parameters (should be exactly as if angle brackets were used
// and regions omitted).
#![feature(unboxed_closures)]
#![allow(dead_code)]
use std::marker;
trait Foo<'a,T> {
type Output;
fn dummy(&'a self) -> &... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
unboxed-closure-sugar-region.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test<'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(isize,),Output=()>, Foo(isize) >();
// Here we specify 'static explicitly in angle-bracket version.
// Parenthesized winds up getting inferred.
eq::< Foo<'static, (isize,),Outpu... | { } | identifier_body |
unboxed-closure-sugar-region.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, x: &X) -> bool { true } }
impl<X: ?Sized> Eq<X> for X { }
fn eq<A: ?Sized,B: ?Sized +Eq<A>>() { }
fn same_type<A,B:Eq<A>>(a: A, b: B) { }
fn test<'a,'b>() {
// Parens are equivalent to omitting default in angle.
eq::< Foo<(isize,),Output=()>, Foo(isize) >();
// ... | is_of_eq_type | identifier_name |
example_automl_nl_text_sentiment.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
dataset_id = create_dataset_task.output['dataset_id']
import_dataset_task = AutoMLImportDataOperator(
task_id="import_dataset_task",
dataset_id=dataset_id,
location=GCP_AUTOML_LOCATION,
input_config=IMPORT_INPUT_CONFIG,
)
MODEL["dataset_id"] = dataset_id
create_mo... | create_dataset_task = AutoMLCreateDatasetOperator(
task_id="create_dataset_task", dataset=DATASET, location=GCP_AUTOML_LOCATION
) | random_line_split |
cptn-dflt-b-fall-thru-nrml.js | // Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 13.12.11
description: >
Completion value when execution continues through multiple cases and ends
with a normal completion
info: |
SwitchStatement : switch (... | 10. If R.[[value]] is not empty, let V = R.[[value]].
11. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
12. Repeat for each CaseClause C in B (NOTE this is another complete
iteration of the second CaseClauses)
a. Let R be the result of evaluating CaseClause C.
b... | random_line_split | |
compiler.js | ify } from './emojify';
import { getAndRemoveConfig } from './utils';
import { imageCompiler } from './compiler/image';
import { highlightCodeCompiler } from './compiler/code';
import { paragraphCompiler } from './compiler/paragraph';
import { taskListCompiler } from './compiler/taskList';
import { taskListItemCompiler... |
_initRenderer() {
const renderer = new marked.Renderer();
const { linkTarget, linkRel, router, contentBase } = this;
const _self = this;
const origin = {};
/**
* Render anchor tag
* @link https://github.com/markedjs/marked#overriding-renderer-methods
* @param {String} text Text c... | {
const links = this.config.noCompileLinks || [];
for (let i = 0; i < links.length; i++) {
const n = links[i];
const re = cachedLinks[n] || (cachedLinks[n] = new RegExp(`^${n}$`));
if (re.test(link)) {
return link;
}
}
} | identifier_body |
compiler.js | ojify } from './emojify';
import { getAndRemoveConfig } from './utils';
import { imageCompiler } from './compiler/image';
import { highlightCodeCompiler } from './compiler/code';
import { paragraphCompiler } from './compiler/paragraph';
import { taskListCompiler } from './compiler/taskList';
import { taskListItemCompil... | (url, title) {
return {
html: `<video src="${url}" ${title || 'controls'}>Not Support</video>`,
};
},
audio(url, title) {
return {
html: `<audio src="${url}" ${title || 'controls'}>Not Support</audio>`,
};
},
code(url, title) {
let lang = url.match(/\.(\w+)$/);
lang = title ... | video | identifier_name |
compiler.js | ify } from './emojify';
import { getAndRemoveConfig } from './utils';
import { imageCompiler } from './compiler/image';
import { highlightCodeCompiler } from './compiler/code';
import { paragraphCompiler } from './compiler/paragraph';
import { taskListCompiler } from './compiler/taskList';
import { taskListItemCompiler... |
let media;
if (config.type && (media = compileMedia[config.type])) {
embed = media.call(this, href, title);
embed.type = config.type;
} else {
let type = 'code';
if (/\.(md|markdown)/.test(href)) {
type = 'markdown';
} else if (/\.mmd/.test(href)) {
... | {
href = getPath(
process.env.SSR ? '' : this.contentBase,
getParentPath(this.router.getCurrentPath()),
href
);
} | conditional_block |
compiler.js | ojify } from './emojify';
import { getAndRemoveConfig } from './utils';
import { imageCompiler } from './compiler/image';
import { highlightCodeCompiler } from './compiler/code';
import { paragraphCompiler } from './compiler/paragraph';
import { taskListCompiler } from './compiler/taskList';
import { taskListItemCompil... | if (config.type && (media = compileMedia[config.type])) {
embed = media.call(this, href, title);
embed.type = config.type;
} else {
let type = 'code';
if (/\.(md|markdown)/.test(href)) {
type = 'markdown';
} else if (/\.mmd/.test(href)) {
type = 'm... | }
let media; | random_line_split |
recursion.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 n = test(1, 0, Nil, Nil);
println!("{}", n);
}
| main | identifier_name |
recursion.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 n = test(1, 0, Nil, Nil);
println!("{}", n); | random_line_split |
recursion.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 ... |
}
fn test<T:Dot> (n:int, i:int, first:T, second:T) ->int {
match n {
0 => {first.dot(second)}
// Error message should be here. It should be a type error
// to instantiate `test` at a type other than T. (See #4287)
_ => {test (n-1, i+1, Cons {head:2*i+1, tail:first}, Cons{head:i*i, tail:second})}
... | {
self.head * other.head + self.tail.dot(other.tail)
} | identifier_body |
echoserver.py | import asyncio
import logging
import concurrent.futures
class EchoServer(object):
"""Echo server class"""
def __init__(self, host, port, loop=None):
self._loop = loop or asyncio.get_event_loop()
self._server = asyncio.start_server(self.handle_connection, host=host, port=port)
def start(s... |
def stop(self, and_loop=True):
self._server.close()
if and_loop:
self._loop.close()
@asyncio.coroutine
def handle_connection(self, reader, writer):
peername = writer.get_extra_info('peername')
logging.info('Accepted connection from {}'.format(peername))
... | self._loop.run_forever() | conditional_block |
echoserver.py | import asyncio
import logging
import concurrent.futures
class EchoServer(object):
"""Echo server class"""
def __init__(self, host, port, loop=None):
self._loop = loop or asyncio.get_event_loop()
self._server = asyncio.start_server(self.handle_connection, host=host, port=port)
| self._server = self._loop.run_until_complete(self._server)
logging.info('Listening established on {0}'.format(self._server.sockets[0].getsockname()))
if and_loop:
self._loop.run_forever()
def stop(self, and_loop=True):
self._server.close()
if and_loop:
... | def start(self, and_loop=True): | random_line_split |
echoserver.py | import asyncio
import logging
import concurrent.futures
class EchoServer(object):
"""Echo server class"""
def __init__(self, host, port, loop=None):
self._loop = loop or asyncio.get_event_loop()
self._server = asyncio.start_server(self.handle_connection, host=host, port=port)
def start(s... |
@asyncio.coroutine
def handle_connection(self, reader, writer):
peername = writer.get_extra_info('peername')
logging.info('Accepted connection from {}'.format(peername))
while not reader.at_eof():
try:
data = yield from asyncio.wait_for(reader.readline(), ti... | self._server.close()
if and_loop:
self._loop.close() | identifier_body |
echoserver.py | import asyncio
import logging
import concurrent.futures
class EchoServer(object):
"""Echo server class"""
def __init__(self, host, port, loop=None):
self._loop = loop or asyncio.get_event_loop()
self._server = asyncio.start_server(self.handle_connection, host=host, port=port)
def start(s... | (self, reader, writer):
peername = writer.get_extra_info('peername')
logging.info('Accepted connection from {}'.format(peername))
while not reader.at_eof():
try:
data = yield from asyncio.wait_for(reader.readline(), timeout=10.0)
writer.write(data)
... | handle_connection | identifier_name |
gitsetup.py | sys
from errors import Errors
from general import (
exists_and_is_directory, shellquote, print_stderr
)
from githelpers import has_objects_and_refs
class OptionFrom:
'''enum-like values to indicate the source of different options, used in
directory_to_backup_from, git_directory_from and branch_from'''
... |
def check_ref(self,ref):
'''Returns True if a ref can be resolved to a commit and False
otherwise.'''
return 0 == call(
self.git(["rev-parse","--verify",ref]),
stdout=open('/dev/null','w'),
stderr=STDOUT
)
def check_tree(self,tree):
... | '''Check that the git repository exists and exit otherwise'''
if not self.git_initialized():
message = "You don't seem to have initialized {} for backup."
print_stderr(message.format(self.directory_to_backup))
message = "Please use '{} init' to initialize it"
prin... | identifier_body |
gitsetup.py | sys
from errors import Errors
from general import (
exists_and_is_directory, shellquote, print_stderr
)
from githelpers import has_objects_and_refs
class OptionFrom:
'''enum-like values to indicate the source of different options, used in
directory_to_backup_from, git_directory_from and branch_from'''
... |
else:
message = "The {} config option was not set, setting to {}"
print_stderr(message.format(key,required_value))
self.set_config_value(key,required_value)
def abort_unless_no_auto_gc(self):
'''Exit unless git config has gc.auto set to "0"'''
self.abort... | if current_value != required_value:
message = "The current value for {} is {}, should be: {}"
print_stderr(message.format(
key,
current_value,
required_value
))
sys.exit(Errors.GIT_CONFIG_ERROR) | conditional_block |
gitsetup.py | sys
from errors import Errors
from general import (
exists_and_is_directory, shellquote, print_stderr
)
from githelpers import has_objects_and_refs
class OptionFrom:
'''enum-like values to indicate the source of different options, used in
directory_to_backup_from, git_directory_from and branch_from'''
... | (self):
'''Exit unless git config has gc.auto set to "0"'''
self.abort_unless_particular_config("gc | abort_unless_no_auto_gc | identifier_name |
gitsetup.py | import re
from subprocess import call, check_call, Popen, PIPE, STDOUT
import sys
from errors import Errors
from general import (
exists_and_is_directory, shellquote, print_stderr
)
from githelpers import has_objects_and_refs
class OptionFrom:
'''enum-like values to indicate the source of different options, u... | random_line_split | ||
get_global_account_data.rs | //! `GET /_matrix/client/*/user/{userId}/account_data/{type}`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3useruseridaccount_datatype
use ruma_common::{api::ruma_api, events::AnyGlobalAccountDataEventContent, UserId};
use ruma_s... | } | random_line_split | |
get_global_account_data.rs | //! `GET /_matrix/client/*/user/{userId}/account_data/{type}`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3useruseridaccount_datatype
use ruma_common::{api::ruma_api, events::AnyGlobalAccountDataEventContent, UserId};
use ruma_s... |
}
impl Response {
/// Creates a new `Response` with the given account data.
pub fn new(account_data: Raw<AnyGlobalAccountDataEventContent>) -> Self {
Self { account_data }
}
}
}
| {
Self { user_id, event_type }
} | identifier_body |
get_global_account_data.rs | //! `GET /_matrix/client/*/user/{userId}/account_data/{type}`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#get_matrixclientv3useruseridaccount_datatype
use ruma_common::{api::ruma_api, events::AnyGlobalAccountDataEventContent, UserId};
use ruma_s... | (account_data: Raw<AnyGlobalAccountDataEventContent>) -> Self {
Self { account_data }
}
}
}
| new | identifier_name |
index-tests.tsx | import * as React from "react";
import { Timeline, TimelineEvent, TimelineBlip } from ".";
export const UseTimelineBlip = (
<Timeline>
<TimelineBlip
title="Remove PropTypes warning"
iconStyle={{ marginLeft: 1, marginTop: 0 }}
icon={<i className="material-icons md-18">assignment_late</i>}
... | if you are on track already!
</TimelineEvent>
</Timeline>
); | Like we talked, you said that you would share the shipment details? This
is an urgent order and so I am losing patience. Can you expedite the
process and pls do share the details asap. Consider this a gentle reminder | random_line_split |
setup.py | # -*- coding: utf-8 -*-
import re
import sys |
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
def find_version(fname):
'''Att... | from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand | random_line_split |
setup.py | # -*- coding: utf-8 -*-
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run... |
if not version:
raise RuntimeError('Cannot find version information')
return version
__version__ = find_version("mfr_code_pygments/__init__.py")
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name='mfr_code_pygments',
version=__version__,
... | m = reg.match(line)
if m:
version = m.group(1)
break | conditional_block |
setup.py | # -*- coding: utf-8 -*-
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run... |
__version__ = find_version("mfr_code_pygments/__init__.py")
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name='mfr_code_pygments',
version=__version__,
install_requires=[
'mfr==0.1.0',
'Pygments',
],
description='code_pygment... | '''Attempts to find the version number in the file names fname.
Raises RuntimeError if not found.
'''
version = ''
with open(fname, 'r') as fp:
reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]')
for line in fp:
m = reg.match(line)
if m:
version... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.