file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mo...
appearance?: boolean|AppearancePageVisibility, autofill?: boolean, defaultBrowser?: boolean, downloads?: boolean, extensions?: boolean, languages?: boolean, onStartup?: boolean, people?: boolean, privacy?: boolean|PrivacyPageVisibility, reset?: boolean, safetyCheck?: boolean, }; export type Appea...
a11y?: boolean, advancedSettings?: boolean,
random_line_split
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mo...
(testVisibility: PageVisibility) { pageVisibility = testVisibility; }
setPageVisibilityForTesting
identifier_name
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mo...
{ pageVisibility = testVisibility; }
identifier_body
page_visibility.ts
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; /** * Specifies page visibility based on incognito status and Chrome OS guest mo...
export function setPageVisibilityForTesting(testVisibility: PageVisibility) { pageVisibility = testVisibility; }
{ // All pages are visible when not in chromeos. Since polymer only notifies // after a property is set. // <if expr="chromeos"> pageVisibility = { autofill: true, people: true, onStartup: true, reset: true, safetyCheck: true, appearance: { setTheme: true, homeButton: true, ...
conditional_block
classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.js
var classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y = [ [ "swizzleSelf", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#af2e3962f186209cd2f0ff04f2f029a7c", null ], [ "xd", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#a8d5c658a8bea39b4f67274776893005f", null ], [ "xf", "classwblut_1_1geom_1_1_w_...
[ "yf", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#aee38087663cb9738af856f9168b48920", null ], [ "zd", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#a98665092c02747ae5787ea4a2c368c37", null ], [ "zf", "classwblut_1_1geom_1_1_w_b___swizzle_1_1_x_z_y.html#a7784563cf410e2f7bff9576e800961b4", n...
random_line_split
models.py
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from churchill.apps.core.models import BaseModel from churchill.apps.currencies.services import get_default_currency_id class StatsCalculationStrategy(model...
return self.user.email
) verification_token = models.CharField(max_length=16, null=True, blank=True) def __str__(self):
random_line_split
models.py
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from churchill.apps.core.models import BaseModel from churchill.apps.currencies.services import get_default_currency_id class StatsCalculationStrategy(model...
user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name="profile", ) image = models.FileField( upload_to=settings.PROFILE_IMAGE_DIRECTORY, null=True, blank=True ) language = models.CharField( max_length=5, blank...
identifier_body
models.py
from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from churchill.apps.core.models import BaseModel from churchill.apps.currencies.services import get_default_currency_id class
(models.TextChoices): LAST_SHOT = "LAST_SHOT", _("From the last shot") WEEKLY = "WEEKLY", _("Weekly") MONTHLY = "MONTHLY", _("Monthly") ALL_TIME = "ALL_TIME", _("For the all time") class Profile(BaseModel): user = models.OneToOneField( User, on_delete=models.CASCADE, primar...
StatsCalculationStrategy
identifier_name
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus>
pub fn type_info(&self) -> Result<CodeObjectType, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Type, x)) } pub fn isa(&self) -> Result<ISA, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::ISA, x)) } pub fn machine_model(&self) -> Result<MachineModel, ErrorS...
{ get_info(|x| self.get_info(CodeObjectInfo::Version, x)).map(|x: [u8; 64]| { let x = x.splitn(2, |c| *c == 0).next().unwrap_or(&[]); String::from_utf8_lossy(x).to_string() }) }
identifier_body
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Version,...
pub fn profile(&self) -> Result<Profile, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Profile, x)) } pub fn default_float_rounding_mode(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, ...
} pub fn machine_model(&self) -> Result<MachineModel, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::MachineModel, x)) }
random_line_split
code_object.rs
use std::os::raw::c_void; use native::*; use native::CodeObject as CodeObjectHandle; use super::{get_info, ErrorStatus}; pub struct CodeObject { pub handle: CodeObjectHandle, } impl CodeObject { pub fn version(&self) -> Result<String, ErrorStatus> { get_info(|x| self.get_info(CodeObjectInfo::Version,...
(&self) -> Result<DefaultFloatRoundingMode, ErrorStatus> { get_info(|x| { self.get_info(CodeObjectInfo::DefaultFloatRoundingMode, x) }) } fn get_info(&self, attr: CodeObjectInfo, v: *mut c_void) -> HSAStatus { unsafe { hsa_code_object_get_info(self.handle, attr, v) } } }...
default_float_rounding_mode
identifier_name
IElement.ts
/// <reference path="../IElement.ts" /> module xlib.ui.element.elements.small { import IEvent = elements.IEvent; export interface IElement<T> extends elements.IElement<T> { getTitle(): string; setTitle(value: any): void; getLang(): string; setLang(value: any): void; getXmlLang(): string;
onMouseDown(listener: (event?: IEvent<T>) => void): void; onMouseUp(listener: (event?: IEvent<T>) => void): void; onMouseOver(listener: (event?: IEvent<T>) => void): void; onMouseMove(listener: (event?: IEvent<T>) => void): void; onMouseOut(listener: (event?: IEvent<T>) => void): void; onKeyPres...
setXmlLang(value: any): void; getDir(): string; setDir(value: any): void; onClick(listener: (event?: IEvent<T>) => void): void; onDblClick(listener: (event?: IEvent<T>) => void): void;
random_line_split
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.dat...
def mock_fetch_ladder(self, status=200, fetch_time=None, members=None, **kwargs): self.bnet.fetch_ladder = \ Mock(return_value=LadderResponse(status, gen_api_ladder(members, **kwargs), fetch_time or utcnow(), 0)) def mock_fetch_league(self, status=200, fetch_time=None, season_id=N...
self.bnet.fetch_current_season = \ Mock(return_value=SeasonResponse(status, ApiSeason({'seasonId': season_id or self.db.season.id, 'startDate': to_unix(start_time or utcnow())}, ...
identifier_body
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.dat...
self.cpp.update_with_ladder(0, # bid 0, # source_id region, mode, league, tier, version, ...
self.load()
conditional_block
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.dat...
(self, **kwargs): return self.now + timedelta(**kwargs) @classinstancemethod def unix_time(self, **kwargs): return to_unix(self.now + timedelta(**kwargs)) def assert_team_ranks(self, ranking_id, *ranks, skip_len=False, sort=True): """ Get all team ranks using the current ranking id...
datetime
identifier_name
base.py
import inspect import os import sys from datetime import timedelta from io import StringIO from unittest.mock import Mock from urllib.error import HTTPError import django import django.db import django.test.runner import django.test.testcases import django.test.utils from django.test import TestCase from aid.test.dat...
class MockBnetTestMixin(object): """ Class to help with common mockings. """ def setUp(self): super().setUp() self.bnet = BnetClient() def mock_raw_get(self, status=200, content=""): self.bnet.raw_get = Mock(side_effect=HTTPError('', status, '', '', StringIO(content))) ...
for tr in team_ranks])) raise
random_line_split
test_cron.py
import datetime import os from django.conf import settings from olympia.amo.tests import TestCase from olympia.addons.models import Addon from olympia.devhub.cron import update_blog_posts from olympia.devhub.tasks import convert_purified from olympia.devhub.models import BlogPost class TestRSS(TestCase): def t...
self.addon.the_reason = 'foo <script>foo</script>' self.addon.save() convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3615) assert addon.the_reason.localized_string_clean
identifier_body
test_cron.py
import datetime import os from django.conf import settings from olympia.amo.tests import TestCase from olympia.addons.models import Addon from olympia.devhub.cron import update_blog_posts from olympia.devhub.tasks import convert_purified from olympia.devhub.models import BlogPost class TestRSS(TestCase): def t...
(self): super(TestPurify, self).setUp() self.addon = Addon.objects.get(pk=3615) def test_no_html(self): self.addon.the_reason = 'foo' self.addon.save() last = Addon.objects.get(pk=3615).modified convert_purified([self.addon.pk]) addon = Addon.objects.get(pk=3...
setUp
identifier_name
test_cron.py
import datetime import os from django.conf import settings from olympia.amo.tests import TestCase from olympia.addons.models import Addon from olympia.devhub.cron import update_blog_posts from olympia.devhub.tasks import convert_purified from olympia.devhub.models import BlogPost class TestRSS(TestCase): def t...
class TestPurify(TestCase): fixtures = ['base/addon_3615'] def setUp(self): super(TestPurify, self).setUp() self.addon = Addon.objects.get(pk=3615) def test_no_html(self): self.addon.the_reason = 'foo' self.addon.save() last = Addon.objects.get(pk=3615).modified ...
assert bp.title == 'Test!' assert bp.date_posted == datetime.date(2011, 6, 10) assert bp.permalink == url
random_line_split
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn
(state: &GameState, render_args: RenderArgs, context: Context, graphics: &mut G2d, glyphs: &mut Glyphs) { let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border,...
draw
identifier_name
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn draw(state: &GameState, render_args: RenderArgs, co...
}, border + ascent as Scalar + shake); draw("Copyright 1942", &|bounding_box| border - bounding_box.min.x as Scalar, render_args.height as Scalar - border + descent as Scalar + shake); draw(&fps_text, &|bounding_box| { ren...
draw("This is some text.", &|bounding_box| { render_args.width as Scalar - border - bounding_box.max.x as Scalar
random_line_split
mod.rs
use piston_window; use piston_window::{Context, G2d, Glyphs, RenderArgs, Transformed}; use piston_window::types::Scalar; use rusttype::{Rect, Scale, VMetrics}; use {GameState, InnerState, Progress}; mod text; /// Draws the game state. pub fn draw(state: &GameState, render_args: RenderArgs, co...
{ let black = [0.0, 0.0, 0.0, 1.0]; let white = [1.0, 1.0, 1.0, 1.0]; piston_window::clear(black, graphics); let border = 32.0; // thickness of border, in pixels let (title, shake) = match state.state { InnerState::Falling(progress) => { ((render_args.height as Scalar - border)...
identifier_body
generic.py
# (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your opti...
def __init__(self, cpu_factory, registers): for group, register_list in registers.iteritems(): registers[group] = [Register(x) for x in register_list] super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): return Architecture.Generic ...
identifier_body
generic.py
# (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your opti...
super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): return Architecture.Generic def stack_pointer(self): return self.register('sp') def program_counter(self): return self.register('pc')
registers[group] = [Register(x) for x in register_list]
conditional_block
generic.py
# (void)walker CPU architecture support
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # b...
# Copyright (C) 2013 David Holm <dholmster@gmail.com>
random_line_split
generic.py
# (void)walker CPU architecture support # Copyright (C) 2013 David Holm <dholmster@gmail.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your opti...
(self, cpu_factory, registers): for group, register_list in registers.iteritems(): registers[group] = [Register(x) for x in register_list] super(GenericCpu, self).__init__(cpu_factory, registers) @classmethod def architecture(cls): return Architecture.Generic def stack_...
__init__
identifier_name
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two co...
return '<Gist Comment [{0}]>'.format(self.user.login)
identifier_body
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two co...
if comment.get('user'): self.user = User(comment.get('user'), self) # (No coverage) def _repr(self): return '<Gist Comment [{0}]>'.format(self.user.login)
#: Unless it is not associated with an account self.user = None
random_line_split
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two co...
def _repr(self): return '<Gist Comment [{0}]>'.format(self.user.login)
self.user = User(comment.get('user'), self) # (No coverage)
conditional_block
comment.py
# -*- coding: utf-8 -*- """ github3.gists.comment --------------------- Module containing the logic for a GistComment """ from __future__ import unicode_literals from ..models import BaseComment from ..users import User class GistComment(BaseComment): """This object represents a comment on a gist. Two co...
(self, comment): self._api = comment.get('url') #: :class:`User <github3.users.User>` who made the comment #: Unless it is not associated with an account self.user = None if comment.get('user'): self.user = User(comment.get('user'), self) # (No coverage) def _re...
_update_attributes
identifier_name
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bo...
y.push(x[i as usize] & mask[i as usize]); } }, None => y = x.to_vec(), } if y.iter().eq(rule.val.iter()) { return true; } } } false } /// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, ...
random_line_split
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bo...
else { //println!("\tRegion == {}", rule.region_len); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.start_off); // Define our testing slice let ref x: Vec<u8> = file.iter().take(file.len()).map(|&x| x).collect(); let testarea: Vec<u8> = x.iter().skip(bound_min).take(bound_max - bound_min...
{ //println!("Region == 0"); match rule.mask { None => { //println!("\tMask == None"); let x: Vec<u8> = file.iter().skip(bound_min).take(bound_max - bound_min).map(|&x| x).collect(); //println!("\t{:?} / {:?}", x, rule.val); //println!("\tIndent: {}, Start: {}", rule.indent_level, rule.star...
conditional_block
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn from_u8_singlerule(file: &[u8], rule: &super::MagicRule) -> bool
/// Test every given rule by walking graph /// TODO: Not loving the code duplication here. pub fn from_u8_walker( file: &[u8], mimetype: MIME, graph: &DiGraph<super::MagicRule, u32>, node: NodeIndex, isroot: bool ) -> bool { let n = graph.neighbors_directed(node, Outgoing); if isroot { let ref rule = grap...
{ // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //println!("Region == 0"); match rule.mask { ...
identifier_body
check.rs
use petgraph::prelude::*; use crate::{MIME}; fn
(file: &[u8], rule: &super::MagicRule) -> bool { // Check if we're even in bounds let bound_min = rule.start_off as usize; let bound_max = rule.start_off as usize + rule.val_len as usize + rule.region_len as usize; if (file.len()) < bound_max { return false; } if rule.region_len == 0 { //pr...
from_u8_singlerule
identifier_name
stats.py
import bench class Stats(bench.Bench): def __init__(self, league): bench.Bench.__init__(self) self.league = league self.type = 'stats' def list(self, team=False, player=False): """ Lists all stats for the current season to date. Can be filtered by team or by player. De...
""" Lists the stat breakdown by week for a given player. Can also be filtered to only return a specific week or a range of weeks :param player: Unique ID of the player to filter for :param week: Optional. Can be a single week or a range ex: 1-4. If blank will default to season t...
:return: """ def get_player_stats(self, player, week=False):
random_line_split
stats.py
import bench class Stats(bench.Bench):
def __init__(self, league): bench.Bench.__init__(self) self.league = league self.type = 'stats' def list(self, team=False, player=False): """ Lists all stats for the current season to date. Can be filtered by team or by player. Default will return stat dump for whole...
identifier_body
stats.py
import bench class Stats(bench.Bench): def __init__(self, league): bench.Bench.__init__(self) self.league = league self.type = 'stats' def
(self, team=False, player=False): """ Lists all stats for the current season to date. Can be filtered by team or by player. Default will return stat dump for whole league :param team: Unique ID of the team to filter for :param player: Unique ID of the player to filter for ...
list
identifier_name
lifetime.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 ...
mc::cat_deref(_, _, mc::UnsafePtr(..)) => { ty::ReStatic } mc::cat_deref(_, _, mc::BorrowedPtr(_, r)) | mc::cat_deref(_, _, mc::Implicit(_, r)) => { r } mc::cat_downcast(ref cmt, _) | mc::cat_deref(ref c...
{ ty::ReScope(self.bccx.tcx.region_maps.var_scope(local_id)) }
conditional_block
lifetime.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 scope(&self, cmt: &mc::cmt) -> ty::Region { //! Returns the maximal region scope for the which the //! lvalue `cmt` is guaranteed to be valid without any //! rooting etc, and presuming `cmt` is not mutated. match cmt.cat { mc::cat_rvalue(temp_scope) => { ...
{ //! Reports an error if `loan_region` is larger than `max_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } }
identifier_body
lifetime.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 ...
(&self, max_scope: ty::Region) -> R { //! Reports an error if `loan_region` is larger than `max_scope` if !self.bccx.is_subregion_of(self.loan_region, max_scope) { Err(self.report_error(err_out_of_scope(max_scope, self.loan_region))) } else { Ok(()) } } ...
check_scope
identifier_name
lifetime.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 ...
cmt_original: cmt.clone()}; ctxt.check(&cmt, None) } /////////////////////////////////////////////////////////////////////////// // Private struct GuaranteeLifetimeContext<'a, 'tcx: 'a> { bccx: &'a BorrowckCtxt<'a, 'tcx>, // the scope of the function body for the ...
random_line_split
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } }...
assert!(NotClone.foo() == "generic"); assert!(0u8.foo() == "generic Clone"); assert!(vec![NotClone].foo() == "generic"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!((()...
struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() {
random_line_split
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } }...
(&self) -> &'static str { "(u8, u8)" } } impl<T: Clone> Foo for Vec<T> { default fn foo(&self) -> &'static str { "generic Vec" } } impl Foo for Vec<i32> { fn foo(&self) -> &'static str { "Vec<i32>" } } impl Foo for String { fn foo(&self) -> &'static str { "Stri...
foo
identifier_name
specialization-basics.rs
// run-pass #![feature(specialization)] //~ WARN the feature `specialization` is incomplete // Tests a variety of basic specialization scenarios and method // dispatch for them. trait Foo { fn foo(&self) -> &'static str; } impl<T> Foo for T { default fn foo(&self) -> &'static str { "generic" } }...
} struct NotClone; trait MyMarker {} impl<T: Clone + MyMarker> Foo for T { default fn foo(&self) -> &'static str { "generic Clone + MyMarker" } } #[derive(Clone)] struct MarkedAndClone; impl MyMarker for MarkedAndClone {} fn main() { assert!(NotClone.foo() == "generic"); assert!(0u8.foo() ...
{ "i32" }
identifier_body
setup.py
from __future__ import print_function from setuptools import setup import sys if sys.version_info < (2, 6): print('google-api-python-client requires python version >= 2.6.', file = sys.stderr) sys.exit(1) install_requires = ['google-api-python-client==1.3.1'] if sys.version_info < (2, 7): install_requir...
keywords = ['android', 'automation', 'google'], classifiers = [], install_requires = install_requires, scripts = ['bin/android-publish'] )
random_line_split
setup.py
from __future__ import print_function from setuptools import setup import sys if sys.version_info < (2, 6):
install_requires = ['google-api-python-client==1.3.1'] if sys.version_info < (2, 7): install_requires.append('argparse') setup( name = 'android-publish-cli', packages = [], version = '0.1.2', description = 'A simple CLI for Google Play Publish API', ...
print('google-api-python-client requires python version >= 2.6.', file = sys.stderr) sys.exit(1)
conditional_block
Opacity.js
/* =============================================================================================== Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com ==================================================================...
var mod = this.__mod; var anim = this.__anim; this._widget.setStyle({ opacity: (mod + anim * percent) }); } } });
{ return; }
conditional_block
Opacity.js
/* =============================================================================================== Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com ==================================================================...
__resetPoint: null, _setup : function() { var to = this.getValue(); var from = this.__resetPoint = parseFloat(this._widget.getStyle("opacity")) || 1; this.__mod = from; this.__anim = to - from }, _reset : function(value) { this._widget.setStyle({ opacity: value||"1" }); }, ...
__anim : null,
random_line_split
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
if __name__ == '__main__': main()
try: config.parse_cache_args() logging.setup(CONF, 'glance') glance_store.register_opts(config.CONF) glance_store.create_stores(config.CONF) glance_store.verify_default_store() app = prefetcher.Prefetcher() app.run() except RuntimeError as e: sys.exi...
identifier_body
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
config.parse_cache_args() logging.setup(CONF, 'glance') glance_store.register_opts(config.CONF) glance_store.create_stores(config.CONF) glance_store.verify_default_store() app = prefetcher.Prefetcher() app.run() except RuntimeError as e: sys.exit("ER...
try:
random_line_split
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
main()
conditional_block
cache_prefetcher.py
#!/usr/bin/env python # Copyright 2011-2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
(): try: config.parse_cache_args() logging.setup(CONF, 'glance') glance_store.register_opts(config.CONF) glance_store.create_stores(config.CONF) glance_store.verify_default_store() app = prefetcher.Prefetcher() app.run() except RuntimeError as e: ...
main
identifier_name
checkJSPluginExist.js
/* * This code it's help you to check JS plugin function (e.g. jQuery) exist. * When function not exist, the code will auto reload JS plugin from your setting. * * plugin_name: It's your plugin function name (e.g. jQuery). The type is string. * reload_url: It's your reload plugin function URL. The type is string....
return true; };
var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } }
random_line_split
checkJSPluginExist.js
/* * This code it's help you to check JS plugin function (e.g. jQuery) exist. * When function not exist, the code will auto reload JS plugin from your setting. * * plugin_name: It's your plugin function name (e.g. jQuery). The type is string. * reload_url: It's your reload plugin function URL. The type is string....
return true; };
{ if (typeof window[plugin_name] !== "function") { var tag = document.createElement('script'); tag.src = reload_url; var headerElementTag = document.getElementsByTagName('head')[0]; headerElementTag.appendChild(tag); return false; } }
conditional_block
Navigation.tsx
import React, {useEffect} from "react"; import {HomeView} from "./Home"; import Resume from "./Resume"; import {NavLink, Route} from "react-router-dom"; import Contact from "./Contact"; type RouteDef = { title: string; path: string; component: React.ReactNode } const routeDefs: RouteDef[] = [ { title: "Ho...
() { return <div className="flex flex-row justify-center gap-2 text-xl mb-8"> {navLinks} </div> } function useDocumentTitle(title: string): void { useEffect(() => { window.document.title = (title ? `${title} - mattbague` : "mattbague") }, [title]); }
Navigation
identifier_name
Navigation.tsx
import React, {useEffect} from "react"; import {HomeView} from "./Home"; import Resume from "./Resume"; import {NavLink, Route} from "react-router-dom"; import Contact from "./Contact"; type RouteDef = { title: string; path: string; component: React.ReactNode
title: "Home", path: "/", component: HomeView }, { title: "Resume", path: "/resume", component: Resume }, { title: "Contact", path: "/contact", component: Contact } ] export const routes = routeDefs.map(rd => { return <Route key={rd.title} exact path={rd.path...
} const routeDefs: RouteDef[] = [ {
random_line_split
Navigation.tsx
import React, {useEffect} from "react"; import {HomeView} from "./Home"; import Resume from "./Resume"; import {NavLink, Route} from "react-router-dom"; import Contact from "./Contact"; type RouteDef = { title: string; path: string; component: React.ReactNode } const routeDefs: RouteDef[] = [ { title: "Ho...
{ useEffect(() => { window.document.title = (title ? `${title} - mattbague` : "mattbague") }, [title]); }
identifier_body
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Samp...
(&self) -> Option<Buffer>{ unsafe{ let buffer = gst_sample_get_buffer(mem::transmute(self.gst_sample())); if buffer != ptr::null_mut(){ Buffer::new(gst_mini_object_ref(buffer as *mut GstMiniObject) as *mut GstBuffer) }else{ None } } } /...
buffer
identifier_name
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Samp...
/// Get the segment associated with sample pub fn segment(&self) -> GstSegment{ unsafe{ (*gst_sample_get_segment(mem::transmute(self.gst_sample()))) } } /// Get a video frame from this sample if it contains one pub fn video_frame(&self) -> Option<VideoFrame>{ l...
{ unsafe{ let caps = gst_sample_get_caps(mem::transmute(self.gst_sample())); if caps != ptr::null_mut(){ Caps::new(gst_mini_object_ref(caps as *mut GstMiniObject) as *mut GstCaps) }else{ None } } }
identifier_body
sample.rs
use ffi::*; use caps::Caps; use buffer::Buffer; use videoframe::VideoFrame; use std::mem; use std::ptr; use reference::Reference; use miniobject::MiniObject; unsafe impl Send for Sample {} #[derive(Clone)] pub struct Sample{ sample: MiniObject } impl Sample{ pub unsafe fn new(sample: *mut GstSample) -> Option<Samp...
impl Reference for Sample{ fn reference(&self) -> Sample{ Sample{ sample: self.sample.reference() } } }
self.sample.transfer() as *mut GstSample } }
random_line_split
user-permissions.action.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export class SetProjectsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_PROJECTS_PERMISSIONS; public constructor(public payload: {permissions: AllowedPermissionsMap}) {} } export cla...
export class SetOrganizationsPermissions implements Action { public readonly type = UserPermissionsActionType.SET_ORGANIZATIONS_PERMISSIONS;
random_line_split
user-permissions.action.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
implements Action { public readonly type = UserPermissionsActionType.CLEAR; } export type All = | SetOrganizationPermissions | SetOrganizationsPermissions | SetProjectPermissions | SetProjectsPermissions | SetCollectionsPermissions | SetLinkTypesPermissions | SetViewsPermissions ...
Clear
identifier_name
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode { Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_re...
(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::PermissionDenied, ...
to_i32
identifier_name
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode { Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_re...
pub fn to_i32(&self) -> i32 { -(*self as i32) } } impl From<::std::io::ErrorKind> for ErrorCode { fn from(other: ::std::io::ErrorKind) -> ErrorCode { use std::io::ErrorKind::*; match other { NotFound => ErrorCode::NotFound, PermissionDenied => ErrorCode::P...
{ Value::I32(self.to_i32()) }
identifier_body
error.rs
use wasm_core::value::Value; #[allow(dead_code)] #[repr(i32)] #[derive(Debug, Copy, Clone)] pub enum ErrorCode {
Success = 0, Generic = 1, Eof = 2, Shutdown = 3, PermissionDenied = 4, OngoingIo = 5, InvalidInput = 6, BindFail = 7, NotFound = 8 } impl ErrorCode { pub fn to_ret(&self) -> Value { Value::I32(self.to_i32()) } pub fn to_i32(&self) -> i32 { -(*self as ...
random_line_split
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); ...
return defer.promise; } export function readDirectory(directory: string, includeFiles: boolean, includeFolders: boolean): Q.Promise<string[]> { var results: string[] = []; var deferred = Q.defer<string[]>(); if (includeFolders) { results.push(directory); } Q.nfcall(fs.readdir, direct...
});
random_line_split
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); ...
export function readFileContents(filePath: string, encoding: string) : Q.Promise<string> { var defer = Q.defer<string>(); fs.readFile(filePath, encoding, (err, data) => { if(err) { defer.reject(new Error('Could not read file (' + filePath + '): ' + err.message)); } else { ...
{ var defer = Q.defer<void>(); if (fs.exists(path, (exists) => { if (!exists) { shell.mkdir('-p', path); var errMsg = shell.error(); if (errMsg) { defer.reject(new Error('Could not create path (' + path + '): ' + errMsg)); } ...
identifier_body
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); ...
} else { defer.resolve(null); } })); return defer.promise; } export function readFileContents(filePath: string, encoding: string) : Q.Promise<string> { var defer = Q.defer<string>(); fs.readFile(filePath, encoding, (err, data) => { if(err) { de...
{ defer.resolve(null); }
conditional_block
utilities.ts
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /// <reference path="./definitions/Q.d.ts" /> import Q = require('q'); import ctxm = require('./context'); import fs = require('fs'); var shell = require('shelljs'); ...
{ constructor(context: ctxm.Context) { this.ctx = context; } private ctx: ctxm.Context; // // '-a -b "quoted b value" -c -d "quoted d value"' becomes // [ '-a', '-b', '"quoted b value"', '-c', '-d', '"quoted d value"' ] // public argStringToArray(argString: string): string[] {...
Utilities
identifier_name
formatting.ts
// // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless requ...
///<reference path='formattingManager.ts' /> ///<reference path='formattingRequestKind.ts' /> ///<reference path='rule.ts' /> ///<reference path='ruleAction.ts' /> ///<reference path='ruleDescriptor.ts' /> ///<reference path='ruleFlag.ts' /> ///<reference path='ruleOperation.ts' /> ///<reference path='ruleOperat...
///<reference path='textSnapshot.ts' /> ///<reference path='textSnapshotLine.ts' /> ///<reference path='snapshotPoint.ts' /> ///<reference path='formattingContext.ts' />
random_line_split
RecentHistory-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
(save as jest.Mock).mockClear(); }); it('should get existing history', () => { const history = [{ key: 'foo', name: 'Foo', icon: 'TRK' }]; (get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); expect(RecentHistory.get()).toEqual(history); expect(get).toBeCalledWith('sonar_recent_history'); }); it...
(get as jest.Mock).mockClear(); (remove as jest.Mock).mockClear();
random_line_split
RecentHistory-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
(get as jest.Mock).mockReturnValueOnce(JSON.stringify(history)); RecentHistory.remove('key-5'); expect(save).toBeCalledWith( 'sonar_recent_history', JSON.stringify([...history.slice(0, 5), ...history.slice(6)]) ); });
{ history.push({ key: `key-${i}`, name: `name-${i}`, icon: 'TRK' }); }
conditional_block
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str>
pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer",...
{ (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() }
identifier_body
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() } pub fn
(display: *mut xlib::Display) { let mut ndevices = 0; let devices_ptr = unsafe { xinput2::XIQueryDevice(display, xinput2::XIAllDevices, &mut ndevices) }; let xi_devices = unsafe { slice::from_raw_parts(devices_ptr, ndevices as usize) }; let dev_use = ["unk", "XIMasterPointer", "XIMasterKeyboard", "XISl...
enumerate_devices
identifier_name
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() } pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; ...
println!("-- device {} {:?} is a {} (paired with {})", dev.deviceid, name, dev_use[dev._use as usize], dev.attachment); for i in 0 .. dev.num_classes as isize { let class = unsafe { *dev.classes.offset(i) }; let _type = unsafe { (*class)._type }; let ci_str =...
let dev_class = ["XIKeyClass", "XIButtonClass", "XIValuatorClass", "XIScrollClass", "4", "5", "6", "7", "XITouchClass"]; for dev in xi_devices { let name = unsafe{ CStr::from_ptr(dev.name) };
random_line_split
stuff.rs
use x11::{xlib, xinput2}; use std::{mem, slice}; use std::ffi::{CStr, CString}; pub fn desc_flags<'a>(flags: i32, desc: &'a [&str]) -> Vec<&'a str> { (0 .. desc.len()).filter(|i| flags & (1 << i) != 0).map(|i| desc[i]).collect() } pub fn enumerate_devices(display: *mut xlib::Display) { let mut ndevices = 0; ...
else { CString::new("(null)").unwrap() }; format!("number {}, name {:?}, min {}, max {}, res {}, mode {}", val_c.number, name, val_c.min, val_c.max, val_c.resolution, val_c.mode) }, xinput2::XIScrollClass => { ...
{ unsafe { let ptr = xlib::XGetAtomName(display, val_c.label); let val = CStr::from_ptr(ptr).to_owned(); xlib::XFree(ptr as *mut _); val } }
conditional_block
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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/lice...
(self, request): # Generate the initial context. This may be updated by other middleware # as we learn more information about the Request. ctxt = context.DesignateContext.get_admin_context(all_tenants=True) try: message = dns.message.from_wire(request['payload'], ...
__call__
identifier_name
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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/lice...
return rrset def bind_tcp(host, port, tcp_backlog): # Bind to the TCP port LOG.info(_LI('Opening TCP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_R...
rr = objects.Record(data=rdata.to_text()) rrset.records.append(rr)
conditional_block
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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/lice...
rrset = dnspythonrecord_to_recordset(rname, rdataset) if rrset is None: continue rrsets.append(rrset) return rrsets def dnspythonrecord_to_recordset(rname, rdataset): record_type = rdatatype.to_text(rdataset.rdtype) # Create the other recordsets v...
def dnspyrecords_to_recordsetlist(dnspython_records): rrsets = objects.RecordList() for rname in six.iterkeys(dnspython_records): for rdataset in dnspython_records[rname]:
random_line_split
dnsutils.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Endre Karlson <endre.karlson@hp.com> # # 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/lice...
def bind_udp(host, port): # Bind to the UDP port LOG.info(_LI('Opening UDP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # NOTE: Linux...
LOG.info(_LI('Opening TCP Listening Socket on %(host)s:%(port)d') % {'host': host, 'port': port}) sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) # NOT...
identifier_body
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. ...
(msg=None): if msg is not None: print(msg) exit(-1) def brk(s, e): """ Used for debugging, just break the script, dumping data. """ dmpdat(s, e) exit(-1) def chkdat(t, s, e, rtol=1e-05, atol=1e-08): """ Check this matrix against data dumped by octave, with given tolerance ...
hbrk
identifier_name
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. ...
def brk(s, e): """ Used for debugging, just break the script, dumping data. """ dmpdat(s, e) exit(-1) def chkdat(t, s, e, rtol=1e-05, atol=1e-08): """ Check this matrix against data dumped by octave, with given tolerance """ mat = loadmat(os.path.join('check_data', t, s) + '.mat')['...
if msg is not None: print(msg) exit(-1)
identifier_body
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. ...
return is_equal
dmpdat(s + '<matlab>', mat) np.savetxt(os.path.join("check_data", t, s) + '_python_err', e) np.savetxt(os.path.join("check_data", t, s) + '_matlab_err', mat) print("FAILED check on expr: %s, signal: %s" % (s, t)) #hbrk()
random_line_split
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. ...
exit(-1) def brk(s, e): """ Used for debugging, just break the script, dumping data. """ dmpdat(s, e) exit(-1) def chkdat(t, s, e, rtol=1e-05, atol=1e-08): """ Check this matrix against data dumped by octave, with given tolerance """ mat = loadmat(os.path.join('check_data', t, s...
print(msg)
conditional_block
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAM...
if line.startswith('proxyPassword='): proxy_password = line.strip().split('=')[1] if hostname: proxy = None if proxy_enabled == "1": proxy = "http://" if proxy_user != "" and proxy_password != "": logger.de...
proxy_user = line.strip().split('=')[1]
conditional_block
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAM...
def _read_systemid_file(path): with open(path, "r") as systemid: data = systemid.read().replace('\n', '') return data def _try_satellite5_configuration(): """ Attempt to determine Satellite 5 Configuration """ logger.debug("Trying Satellite 5 auto_config") rhn_config = '/etc/sys...
""" Try to autoconfigure for Satellite 6 """ try: from rhsm.config import initConfig rhsm_config = initConfig() logger.debug('Trying to autoconf Satellite 6') cert = file(rhsmCertificate.certpath(), 'r').read() key = file(rhsmCertificate.keypath(), 'r').read() ...
identifier_body
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAM...
hostname = None for line in rhn_conf_file: if line.startswith('serverURL='): url = urlparse(line.split('=')[1]) hostname = url.netloc + '/redhat_access' logger.debug("Found hostname %s", hostname) if line.startswith('sslCACert='): ...
rhn_conf_file = file(rhn_config, 'r')
random_line_split
auto_config.py
""" Auto Configuration Helper """ import logging import os import requests from urlparse import urlparse from constants import InsightsConstants as constants from cert_auth import rhsmCertificate from connection import InsightsConnection from config import CONFIG as config logger = logging.getLogger(__name__) APP_NAM...
(): """ Try to autoconfigure for Satellite 6 """ try: from rhsm.config import initConfig rhsm_config = initConfig() logger.debug('Trying to autoconf Satellite 6') cert = file(rhsmCertificate.certpath(), 'r').read() key = file(rhsmCertificate.keypath(), 'r').read(...
_try_satellite6_configuration
identifier_name
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object): """ 文本转向量 """ def __init__(self): """ :param keep_val: 设定的阈值 """ ...
title.append({"_id": int(idx) + 1, "data": list(title_vect)}) self.mongo_db.insert("content_vector", content) self.mongo_db.insert("title_vector", title) print("finished") if __name__ == '__main__': doc2vect = Doc2Vector() doc2vect.doc2vect()
content.append({"_id": int(idx) + 1, "data": list(content_vect)})
random_line_split
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object): """ 文本转向量 """ def __init__(s
""" :param keep_val: 设定的阈值 """ self.mongo_db = MongoDBManager() def doc2vect(self): """ 所有文档转成向量存储到数据库 :return: """ model = gensim.models.Doc2Vec.load('./models/doc2vec_v1.model') df_data = pd.read_excel("./data/new_prd.xlsx", names=["S...
elf):
identifier_name
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object): """ 文本转向量 """ def __init__(self): """ :param keep_val: 设定的阈值 """ ...
nt) self.mongo_db.insert("title_vector", title) print("finished") if __name__ == '__main__': doc2vect = Doc2Vector() doc2vect.doc2vect()
ontent = segment(row.Content) # 转向量 content_vect = sent2vec(model, ' '.join(seg_content)) title_vect = sent2vec(model, ' '.join(seg_title)) content_vect = map(str, content_vect.tolist()) title_vect = map(str, title_vect.tolist()) content.append({"_...
conditional_block
doc2vector.py
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object):
r() doc2vect.doc2vect()
""" 文本转向量 """ def __init__(self): """ :param keep_val: 设定的阈值 """ self.mongo_db = MongoDBManager() def doc2vect(self): """ 所有文档转成向量存储到数据库 :return: """ model = gensim.models.Doc2Vec.load('./models/doc2vec_v1.model') df_data...
identifier_body
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { ...
) { if( $("#map-canvas").length ) { var lat = '-8.0618743';//-8.055967'; //Set your latitude. var lon = '-34.8734548';//'-34.896303'; //Set your longitude. var centerLon = lon - 0.0105; var myOptions = { scrollwheel: false, draggable: false, ...
nitializeMap(
identifier_name
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { ...
//analytics (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.asyn...
{ $.ajax({ type: "POST", url: "php/phpscripts/infocurso.php", async: true, data: $('form.informacao').serialize(), }); alert('Entraremos em breve em contato com você'); }
identifier_body
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { ...
var toggleClick = $(this); var toggleDiv = $(this).attr('rel'); $(toggleDiv).slideToggle(options.speed, options.easing, function () { if (options.changeText == 1) { $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text...
hideText: 'Hide' }; var options = $.extend(defaults, options); $(this).click(function () { $('.toggleDiv').slideUp(options.speed, options.easing);
random_line_split
app.js
'use strict'; jQuery(document).ready(function ($) { var lastId, topMenu = $("#top-navigation"), topMenuHeight = topMenu.outerHeight(), // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function () { ...
}); }); //Initialize google map for contact setion with your location. function initializeMap() { if( $("#map-canvas").length ) { var lat = '-8.0618743';//-8.055967'; //Set your latitude. var lon = '-34.8734548';//'-34.896303'; //Set your longitude. var centerLon = lon - 0...
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) + ']'); var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false; if ( $target ) { $(this).click(function (e) { ...
conditional_block
receta-medica.component.ts
import { HTMLComponent } from '../../model/html-component.class'; export class RecetaMedicaComponent extends HTMLComponent { template = `
</div> <table class="table table-bordered"> <thead> <tr> <th>Medicamento</th> <th>Presentación</th> <th>Cantidad</th> <th>Dosis diaria</th> <th>Diagnóstico</th> <th>Observaciones</th> ...
<div class="nivel-1"> <p> {{#if registro.valor.medicamentos}}<b>RECETA MÉDICA</b>{{/if}} </p>
random_line_split
receta-medica.component.ts
import { HTMLComponent } from '../../model/html-component.class'; export class RecetaMedicaComponent extends HTMLComponent { template = ` <div class="nivel-1"> <p> {{#if registro.valor.medicamentos}}<b>RECETA MÉDICA</b>{{/if}} </p> </div> <table class="table table-bordered"> <th...
vate prestacion, private registro, private params, private depth) { super(); } async process() { this.data = { registro: this.registro }; } }
tructor(pri
identifier_name
receta-medica.component.ts
import { HTMLComponent } from '../../model/html-component.class'; export class RecetaMedicaComponent extends HTMLComponent { template = ` <div class="nivel-1"> <p> {{#if registro.valor.medicamentos}}<b>RECETA MÉDICA</b>{{/if}} </p> </div> <table class="table table-bordered"> <th...
this.data = { registro: this.registro }; } }
identifier_body
conf.py
# -*- coding: utf-8 -*- # # dolphintools documentation build configuration file, created by # sphinx-quickstart on Mon Oct 12 22:39:14 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. ...
#html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same a...
# further. For a list of options available for each theme, see the # documentation.
random_line_split