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
relations.py
and child classes in order to try to cover the general case. If you're overriding this method you'll probably want something much simpler, eg: @classmethod def many_init(cls, *args, **kwargs): kwargs['child'] = cls() return CustomManyRelatedField(*args, **kwargs...
class HyperlinkedIdentityField(HyperlinkedRelatedField): """
random_line_split
relations.py
(self, value): if self.pk_field is not None: return self.pk_field.to_representation(value.pk) return value.pk class HyperlinkedRelatedField(RelatedField): lookup_field = 'pk' view_name = None default_error_messages = { 'required': _('This field is required.'), ...
return []
conditional_block
relations.py
occurs on ModelSerializer fields, # as it allows us to generate a more expressive 'repr' output # for the field. # Eg: 'MyRelationship(queryset=ExampleModel.objects.all())' queryset = queryset.all() return queryset def use_pk_only_optimization(self): ...
__init__
identifier_name
relations.py
class HyperlinkedRelatedField(RelatedField): lookup_field = 'pk' view_name = None default_error_messages = { 'required': _('This field is required.'), 'no_match': _('Invalid hyperlink - No URL match.'), 'incorrect_match': _('Invalid hyperlink - Incorrect URL match.'), 'does_...
if hasattr(instance, 'pk') and instance.pk is None: return [] relationship = get_attribute(instance, self.source_attrs) return relationship.all() if (hasattr(relationship, 'all')) else relationship
identifier_body
syntax.js
function(m, doctype, comment, ptarget, pcontents, cdata, sprefix, sattr, scontent, tagName, attrs, bl){ if (doctype) { return "<span style=\"color:gray\">&lt;!doctype" + doctype.replace(/</g, "&lt;") + "&gt;</span>"; } else if (comment) {
return "<span style=\"color:green\">&lt;!--" + comment.replace(/</g, "&lt;") + "--&gt;</span>"; } else if (ptarget) { return "<span style=\"color:orange\">&lt;?" + ptarget + "</span>" + apf.highlightJs(pcontents, true) ...
random_line_split
syntax.js
function(m, doctype, comment, ptarget, pcontents, cdata, sprefix, sattr, scontent, tagName, attrs, bl){ if (doctype) { return "<span style=\"color:gray\">&lt;!doctype" + doctype.replace(/</g, "&lt;") + "&gt;</span>"; } else if (comment) { return ...
if (c) { output.push(pre + " " + "childNodes".pad(max, " ", apf.PAD_RIGHT) + ": ["); output.push(c.substr(0, c.length - 1)); output.push(pre + " ]"); } if (childLength || !depth) output.push(pre...
{ output.push(pre + " " + aout[j].pad(max, " ", apf.PAD_RIGHT) + ": " + aout[j+1] + (j != jl - 2 || c ? "," : "")); }
conditional_block
background.js
ActiveNavigation = { bootstrap: function() { this.create_main_menu(); this.create_sub_menus(); this.attach_events(); }, create_main_menu: function() { chrome.contextMenus.removeAll(); chrome.contextMenus.create({ id: 'active_navigation_content_menu', title: 'Active Navigation', contexts: ['page'] ...
chrome.contextMenus.create(context_menu_item); } }); return this; }, attach_events: function() { this.attach_context_menu_item_clicked(); this.attach_tab_highlighted(); }, attach_context_menu_item_clicked: function() { chrome.contextMenus.onClicked.addListener(function(info, tab) { chrome.tabs....
{ context_menu_item.type = "checkbox"; context_menu_item.checked = true; }
conditional_block
background.js
ActiveNavigation = { bootstrap: function() { this.create_main_menu(); this.create_sub_menus(); this.attach_events(); }, create_main_menu: function() { chrome.contextMenus.removeAll(); chrome.contextMenus.create({ id: 'active_navigation_content_menu', title: 'Active Navigation', contexts: ['page'] ...
}, attach_context_menu_item_clicked: function() { chrome.contextMenus.onClicked.addListener(function(info, tab) { chrome.tabs.update(parseInt(info.menuItemId), {highlighted: true}); }); }, attach_tab_highlighted: function() { chrome.tabs.onHighlighted.addListener(function(tab) { ActiveNavigation.create_...
this.attach_tab_highlighted();
random_line_split
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { ...
.and_then(|p1| p1[page.p1_index()].pointed_frame()) } }
pub fn translate_page(&self, page: Page) -> Option<Frame> { self.p4().next_table(page.p4_index()) .and_then(|p3| p3.next_table(page.p3_index())) .and_then(|p2| p2.next_table(page.p2_index()))
random_line_split
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { ...
pub fn translate(&self, virtual_address: VirtualAddress) -> Option<PhysicalAddress> { let offset = virtual_address.get() % PAGE_SIZE; self.translate_page(Page::containing_address(virtual_address)) .map(|frame| PhysicalAddress::new(frame.start_address().get() + offset)) } pub f...
{ unsafe { self.p4.as_mut() } }
identifier_body
mapper.rs
use super::table::{self, Table, Level4}; use super::{VirtualAddress, PhysicalAddress, PAGE_SIZE, Page}; use super::entry::{EntryFlags}; use memory::{Frame, FrameAllocator}; use core::ptr::Unique; pub struct Mapper { p4: Unique<Table<Level4>>, } impl Mapper { pub unsafe fn new() -> Mapper { Mapper { ...
<A>(&mut self, frame: Frame, flags: EntryFlags, allocator: &mut A) where A: FrameAllocator { let page = Page::containing_address(VirtualAddress::new(frame.start_address().get())); self.map_to(page, frame, flags, allocator) } pub fn unmap<A>(&mut self, page: Page, allocator: &mut A) where A: Fra...
identity_map
identifier_name
transfer.py
import logging import multiprocessing import os from mimetypes import guess_type from django.conf import settings from django.core.cache import cache from django.db import connection from zerver.lib.avatar_hash import user_avatar_path from zerver.lib.upload import S3UploadBackend, upload_image_to_s3 from zerver.model...
def _transfer_avatar_to_s3(user: UserProfile) -> None: avatar_path = user_avatar_path(user) file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, "avatars", avatar_path) + ".original" try: with open(file_path, "rb") as f: s3backend.upload_avatar_image(f, user, user) logging...
transfer_avatars_to_s3(processes) transfer_message_files_to_s3(processes) transfer_emoji_to_s3(processes)
identifier_body
transfer.py
import logging import multiprocessing import os from mimetypes import guess_type from django.conf import settings from django.core.cache import cache from django.db import connection from zerver.lib.avatar_hash import user_avatar_path from zerver.lib.upload import S3UploadBackend, upload_image_to_s3 from zerver.model...
def _transfer_emoji_to_s3(realm_emoji: RealmEmoji) -> None: if not realm_emoji.file_name or not realm_emoji.author: return # nocoverage emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format( realm_id=realm_emoji.realm.id, emoji_file_name=realm_emoji.file_name, ) emoji_path = os.pat...
connection.close() cache._cache.disconnect_all() with multiprocessing.Pool(processes) as p: for out in p.imap_unordered(_transfer_message_files_to_s3, attachments): pass
conditional_block
transfer.py
import logging import multiprocessing import os from mimetypes import guess_type from django.conf import settings from django.core.cache import cache from django.db import connection from zerver.lib.avatar_hash import user_avatar_path from zerver.lib.upload import S3UploadBackend, upload_image_to_s3 from zerver.model...
s3backend.upload_avatar_image(f, user, user) logging.info("Uploaded avatar for %s in realm %s", user.id, user.realm.name) except FileNotFoundError: pass def transfer_avatars_to_s3(processes: int) -> None: users = list(UserProfile.objects.all()) if processes == 1: fo...
def _transfer_avatar_to_s3(user: UserProfile) -> None: avatar_path = user_avatar_path(user) file_path = os.path.join(settings.LOCAL_UPLOADS_DIR, "avatars", avatar_path) + ".original" try: with open(file_path, "rb") as f:
random_line_split
transfer.py
import logging import multiprocessing import os from mimetypes import guess_type from django.conf import settings from django.core.cache import cache from django.db import connection from zerver.lib.avatar_hash import user_avatar_path from zerver.lib.upload import S3UploadBackend, upload_image_to_s3 from zerver.model...
(processes: int) -> None: users = list(UserProfile.objects.all()) if processes == 1: for user in users: _transfer_avatar_to_s3(user) else: # nocoverage connection.close() cache._cache.disconnect_all() with multiprocessing.Pool(processes) as p: for out...
transfer_avatars_to_s3
identifier_name
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
result.push(parts.last().unwrap()); match resolve(&result) { Err(e) => { if can_mode == CanonicalizeMode::Existing { return Err(e); } } Ok(path) => { result.pop(); result.push(path); ...
{ for part in parts[..parts.len() - 1].iter() { result.push(part); if can_mode == CanonicalizeMode::None { continue; } match resolve(&result) { Err(e) => match can_mode { CanonicalizeMode::Missing => continue, ...
conditional_block
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
result = p; } result.pop(); } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { result.push(comp.as_os_str()) } } } result.into() } #[derive(C...
random_line_split
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
() -> bool { termion::is_tty(&io::stderr()) }
is_stderr_interactive
identifier_name
fs.rs
// This file is part of the uutils coreutils package. // // (c) Joseph Crail <jbcrail@gmail.com> // (c) Jian Zeng <anonymousknight96 AT gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. #[cfg(target_os = "redox")] extern crate t...
result.into() } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CanonicalizeMode { None, Normal, Existing, Missing, } fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> { const MAX_LINKS_FOLLOWED: u32 = 255; let mut followed = 0; let mut result = original.as_ref().to_p...
{ if path.components().all(|e| e != Component::ParentDir) { return path.into(); } let root = Component::RootDir.as_os_str(); let mut result = env::current_dir().unwrap_or(PathBuf::from(root)); for comp in path.components() { match comp { Component::ParentDir => { ...
identifier_body
toggle-routing.module.ts
/** * @license * Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ import { NgModule } from '@angular/core'; import { RouterModule, Route} from '@angular/router'; import { ToggleDisabledComponent } from './toggle-disabled.compone...
{}
ToggleRoutingModule
identifier_name
toggle-routing.module.ts
/** * @license
import { RouterModule, Route} from '@angular/router'; import { ToggleDisabledComponent } from './toggle-disabled.component'; import { ToggleFormComponent } from './toggle-form.component'; import { ToggleLabelPositionComponent } from './toggle-label-position.component'; import { ToggleShowcaseComponent } from './toggle-...
* Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ import { NgModule } from '@angular/core';
random_line_split
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
Ok(Self { x: parts[0] .parse() .map_err(|err| format!("Could not parse x coordinate: {:?}", err))?, y: parts[1] .parse() .map_err(|err| format!("Could not parse y coordinate: {:?}", err))?, z: parts[2] ...
{ return Err("Invalid point -- must contain 3 comma-separated coordinates".to_owned()); }
conditional_block
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
(&self) -> bool { self.x == 0 && self.y == 0 && self.z == 0 } pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::...
is_default
identifier_name
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
pub fn to_vec(&self) -> Vector3D { Vector3D::new(self.x, self.y, self.z) } } impl<T> ops::Sub<T> for Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow...
{ self.x == 0 && self.y == 0 && self.z == 0 }
identifier_body
point3d.rs
use serde::de::{self, Deserialize, Deserializer, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeTupleStruct, Serializer}; use std::borrow::Borrow; use std::{fmt, ops}; use crate::vector3d::Vector3D; #[derive(Clone, Debug, Default)] pub struct Point3D { pub x: i32, pub y: i32, pub z: i32, } imp...
impl<T> ops::Sub<T> for &Point3D where T: Borrow<Self>, { type Output = Vector3D; fn sub(self, rhs: T) -> Self::Output { Vector3D::new( self.x - rhs.borrow().x, self.y - rhs.borrow().y, self.z - rhs.borrow().z, ) } } impl<'de> Deserialize<'de> for P...
random_line_split
auto_rest_report_service_for_azure.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._clien...
header_parameters.update(custom_headers)
conditional_block
auto_rest_report_service_for_azure.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
:param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: dict :...
"""Test Infrastructure for AutoRest :param config: Configuration for client. :type config: AutoRestReportServiceForAzureConfiguration """ def __init__(self, config): self._client = ServiceClient(config.credentials, config) client_models = {k: v for k, v in models.__dict__.items() if ...
identifier_body
auto_rest_report_service_for_azure.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(object): """Test Infrastructure for AutoRest :param config: Configuration for client. :type config: AutoRestReportServiceForAzureConfiguration """ def __init__(self, config): self._client = ServiceClient(config.credentials, config) client_models = {k: v for k, v in models.__dict...
AutoRestReportServiceForAzure
identifier_name
auto_rest_report_service_for_azure.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
:param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :rtype: dict :...
""" Get test coverage report
random_line_split
vm.py
. 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 use this file except in compliance # with the License. You may obtain a copy of the License at # # ...
(self, mod, ctx, target): if mod is None: raise RuntimeError("Must provide module to get VM executor.") self.mod = mod self.ctx = ctx self.target = target self.executable = compile(mod, target) self.vm = vm_rt.VirtualMachine(self.executable, ctx) def _mak...
__init__
identifier_name
vm.py
. 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 use this file except in compliance # with the License. You may obtain a copy of the License at # # ...
return self._optimize(mod, target, target_host), self.get_params() def get_exec(self): """Get the VM executable. Returns ------- exec : tvm.runtime.vm.Executable The VM executable that contains both library code and bytecode. """ return vm_rt.Ex...
self.set_params(params)
conditional_block
vm.py
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 use this file except in compliance # with the License. You may obtain a copy of the Licens...
------- exec : tvm.runtime.vm.Executable The VM executable that contains both library code and bytecode. """ return vm_rt.Executable(self._get_exec()) def _update_target(self, target): """Update target.""" target = target if target else tvm.target.Target....
random_line_split
vm.py
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 use this file except in compliance # with the License. You may obtain a copy of the Licens...
class VMExecutor(Executor): """ An implementation of the executor interface for the Relay VM. Useful interface for experimentation and debugging the VM can also be used directly from the API. supported by `tvm.runtime.vm`. Parameters ---------- mod : :py:class:`~tvm.IRModule` ...
"""Get the autotvm context.""" # If current dispatch context is fallback context (the default root context), # then load pre-tuned parameters from TopHub if isinstance(autotvm.DispatchContext.current, autotvm.FallbackContext): tophub_context = autotvm.tophub.context(list(target.value...
identifier_body
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer,...
pub fn new_output_handle<'a, T: Timestamp, D, P: Push<(T, Content<D>)>>(push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>) -> OutputHandle<'a, T, D, P> { OutputHandle { push_buffer: push_buffer, } }
} /// Constructs an output handle. /// Declared separately so that it can be kept private when `OutputHandle` is re-exported.
random_line_split
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer,...
} /// Constructs an output handle. /// Declared separately so that it can be kept private when `OutputHandle` is re-exported. pub fn new_output_handle<'a, T: Timestamp, D, P: Push<(T, Content<D>)>>(push_buffer: &'a mut Buffer<T, D, PushCounter<T, D, P>>) -> OutputHandle<'a, T, D, P> { OutputHandle { push_...
{ self.push_buffer.session(cap) }
identifier_body
handles.rs
//! Handles to an operator's input and output streams. use std::rc::Rc; use std::cell::RefCell; use progress::Timestamp; use progress::count_map::CountMap; use dataflow::channels::pullers::Counter as PullCounter; use dataflow::channels::pushers::Counter as PushCounter; use dataflow::channels::pushers::buffer::{Buffer,...
<'a, T: Timestamp, D: 'a> { pull_counter: &'a mut PullCounter<T, D>, internal: Rc<RefCell<CountMap<T>>>, } impl<'a, T: Timestamp, D> InputHandle<'a, T, D> { /// Reads the next input buffer (at some timestamp `t`) and a corresponding capability for `t`. /// The timestamp `t` of the input buffer can be r...
InputHandle
identifier_name
fixedColumns.js
/* eslint-disable no-console,func-names,react/no-multi-comp */ const React = require('react'); const ReactDOM = require('react-dom'); const Table = require('table-v7'); require('table-v7/assets/index.less'); const columns = [ { title: '表头1', dataIndex: 'a', key: 'a', width: 100, fixed: 'left' }, { title: '表头2', da...
/> </div> , document.getElementById('__react-content'));
scroll={{ x: 1200 }} data={data}
random_line_split
App.js
/** * Sample React Native App * https://github.com/facebook/react-native *
* Documentation: https://akveo.github.io/react-native-ui-kitten/docs * * @format */ import React from 'react'; import { StyleSheet } from 'react-native'; import { ApplicationProvider, Button, Icon, IconRegistry, Layout, Text, } from '@ui-kitten/components'; import { EvaIconsPack } from '@ui-kitten/eva-...
* Generated with the UI Kitten template * https://github.com/akveo/react-native-ui-kitten *
random_line_split
views.py
"""Prepare rendering of popular smart grid actions widget""" from apps.widgets.smartgrid import smartgrid def supply(request, page_name): """Supply view_objects content, which are the popular actions from the smart grid game.""" _ = request num_results = 5 if page_name != "status" else None #cont...
"range": count, }
random_line_split
views.py
"""Prepare rendering of popular smart grid actions widget""" from apps.widgets.smartgrid import smartgrid def
(request, page_name): """Supply view_objects content, which are the popular actions from the smart grid game.""" _ = request num_results = 5 if page_name != "status" else None #contruct a dictionary containing the most popular tasks. #The keys are the type of the task and the values are a list of ...
supply
identifier_name
views.py
"""Prepare rendering of popular smart grid actions widget""" from apps.widgets.smartgrid import smartgrid def supply(request, page_name):
"""Supply view_objects content, which are the popular actions from the smart grid game.""" _ = request num_results = 5 if page_name != "status" else None #contruct a dictionary containing the most popular tasks. #The keys are the type of the task and the values are a list of tasks.""" popular_task...
identifier_body
settings.py
# Django settings for babynames project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'data_m...
# http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars acco...
TIME_ZONE = 'America/Detroit' # Language code for this installation. All choices can be found here:
random_line_split
jquery.highlight-3.js
/* highlight v3 Highlights arbitrary terms. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html> MIT license. Johann Burkard <http://johannburkard.de> <mailto:jb@eaio.com> */ jQuery.fn.highlight = function(pat) { function
(node, pat) { var skip = 0; if (node.nodeType == 3) { var pos = node.data.toUpperCase().indexOf(pat); if (pos >= 0) { var spannode = document.createElement('span'); spannode.className = 'term'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(pat.length); var middleclo...
innerHighlight
identifier_name
jquery.highlight-3.js
/* highlight v3 Highlights arbitrary terms. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html> MIT license. Johann Burkard <http://johannburkard.de> <mailto:jb@eaio.com> */ jQuery.fn.highlight = function(pat) { function innerHighlight(node, pat) { va...
} return skip; } return this.each(function() { innerHighlight(this, pat.toUpperCase()); }); }; jQuery.fn.removeHighlight = function() { return this.find("span.term").each(function() { $(this).contents().unwrap(); }); };
{ i += innerHighlight(node.childNodes[i], pat); }
conditional_block
jquery.highlight-3.js
/* highlight v3 Highlights arbitrary terms. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html> MIT license. Johann Burkard <http://johannburkard.de> <mailto:jb@eaio.com> */ jQuery.fn.highlight = function(pat) { function innerHighlight(node, pat)
return skip; } return this.each(function() { innerHighlight(this, pat.toUpperCase()); }); }; jQuery.fn.removeHighlight = function() { return this.find("span.term").each(function() { $(this).contents().unwrap(); }); };
{ var skip = 0; if (node.nodeType == 3) { var pos = node.data.toUpperCase().indexOf(pat); if (pos >= 0) { var spannode = document.createElement('span'); spannode.className = 'term'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(pat.length); var middleclone = middleb...
identifier_body
jquery.highlight-3.js
/* highlight v3 Highlights arbitrary terms. <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html> MIT license. Johann Burkard <http://johannburkard.de> <mailto:jb@eaio.com> */ jQuery.fn.highlight = function(pat) { function innerHighlight(node, pat) { va...
} } return skip; } return this.each(function() { innerHighlight(this, pat.toUpperCase()); }); }; jQuery.fn.removeHighlight = function() { return this.find("span.term").each(function() { $(this).contents().unwrap(); }); };
} else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { for (var i = 0; i < node.childNodes.length; ++i) { i += innerHighlight(node.childNodes[i], pat);
random_line_split
partition.py
# Copyright 2014, Doug Wiegley, A10 Networks. # # 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 appli...
def active(self, name='shared'): if self.client.current_partition != name: self._post("system.partition.active", {'name': name}) self.client.current_partition = name def create(self, name): params = { 'partition': { 'max_aflex_file': 32, ...
if name == 'shared': return True try: self._post("system.partition.search", {'name': name}) return True except acos_errors.NotFound: return False
identifier_body
partition.py
# Copyright 2014, Doug Wiegley, A10 Networks. # # 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 appli...
try: self._post("system.partition.search", {'name': name}) return True except acos_errors.NotFound: return False def active(self, name='shared'): if self.client.current_partition != name: self._post("system.partition.active", {'name': name}) ...
return True
conditional_block
partition.py
# Copyright 2014, Doug Wiegley, A10 Networks. # # 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 appli...
self._post("system.partition.delete", {"name": name})
random_line_split
partition.py
# Copyright 2014, Doug Wiegley, A10 Networks. # # 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 appli...
(self, name='shared'): if self.client.current_partition != name: self._post("system.partition.active", {'name': name}) self.client.current_partition = name def create(self, name): params = { 'partition': { 'max_aflex_file': 32, 'ne...
active
identifier_name
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
pub fn set_enable(&mut self, enable: bool) { if !self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
random_line_split
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
() -> Timer { Timer::default() } /// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; ...
new
identifier_name
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
} pub fn set_enable(&mut self, enable: bool) { if !self.enabled && enable { self.stage2 = 0; self.val = 0; } self.enabled = enable; } pub fn enabled(&mut self) -> bool { self.enabled } }
{ let real_div: u16 = if self.div == 0 { 256 } else { self.div as u16 }; self.val += (self.stage2 / real_div) as u8; self.stage2 %= real_div; self.val &= 0x0f; // It's a 4-bit counter }
conditional_block
timer.rs
//! APU timer implementation. #[derive(Copy, Clone, Debug)] pub struct Timer { /// Divider of this timer pub div: u8, /// Current value of the counter. Limited to 4 bits (the upper 4 bits are always 0) pub val: u8, enabled: bool, /// Counted up at the same speed as the APU runs. When it reaches...
/// Update the timer, applying a base-divisor (128 for Timer 0/1, 16 for Timer 2) pub fn update(&mut self, base_div: u8, cy: u8) { self.stage1 += cy; if self.enabled { self.stage2 += self.stage1 as u16 / base_div as u16; } self.stage1 %= base_div; if self.enabled { ...
{ Timer::default() }
identifier_body
network-throttle.js
var Immutable = require("immutable"); module.exports.init = function (ui) { var optPath = ["network-throttle"]; var serverOptPath = optPath.concat(["servers"]); ui.servers = {}; ui.setOptionIn(optPath, Immutable.fromJS({ name: "network-throttle", title: "Network Throttle", ac...
args.server = require("./throttle-server")(args); require('server-destroy')(args.server); args.server.listen(port); saveThrottleInfo(args); } /** * Try for a free port */ ui.bs.utils.portsca...
{ var httpsOpts = require("browser-sync/lib/server/utils").getHttpsOptions(ui.bs.options); args.key = httpsOpts.key; args.cert = httpsOpts.cert; }
conditional_block
network-throttle.js
var Immutable = require("immutable"); module.exports.init = function (ui) { var optPath = ["network-throttle"]; var serverOptPath = optPath.concat(["servers"]); ui.servers = {}; ui.setOptionIn(optPath, Immutable.fromJS({ name: "network-throttle", title: "Network Throttle", ac...
(opts) { var list = []; var bsLocal = require("url").parse(opts.urls.local); list.push([bsLocal.protocol + "//", bsLocal.hostname, ":", opts.port].join("")); if (opts.urls.external) { var external = require("url").parse(opts.urls.external); list.push([bsLocal.protocol + "//", ext...
getUrls
identifier_name
network-throttle.js
var Immutable = require("immutable"); module.exports.init = function (ui) { var optPath = ["network-throttle"]; var serverOptPath = optPath.concat(["servers"]); ui.servers = {}; ui.setOptionIn(optPath, Immutable.fromJS({ name: "network-throttle", title: "Network Throttle", ac...
}, 300); } /** * @param err * @param port */ function createThrottle (err, port) { var target = getTargetUrl(); var args = { port: port, target: target,...
{ var urls = getUrls(ui.bs.options.set("port", opts.port).toJS()); ui.setOptionIn(serverOptPath.concat([opts.port]), Immutable.fromJS({ urls: urls, speed: opts.speed })); setTimeout(function () { ...
identifier_body
network-throttle.js
var Immutable = require("immutable"); module.exports.init = function (ui) { var optPath = ["network-throttle"]; var serverOptPath = optPath.concat(["servers"]); ui.servers = {}; ui.setOptionIn(optPath, Immutable.fromJS({ name: "network-throttle", title: "Network Throttle", ac...
/** * @param err * @param port */ function createThrottle (err, port) { var target = getTargetUrl(); var args = { port: port, target: target, speed: data.speed ...
}
random_line_split
align.py
_dir) names1_npy = os.path.abspath('%s/name1.npy' % base_dir) names2_npy = os.path.abspath('%s/name2.npy' % base_dir) sort1_npy = os.path.abspath('%s/sort1.npy' % base_dir) sort2_npy = os.path.abspath('%s/sort2.npy' % base_dir) ant_dir = '%s/ant' % base_dir idx_dir = '%s/index' % base_dir ...
(file_path): """ guess string size """ # determine name size. with open(file_path, "rb") as fin: for line1 in fin: if line1[0] == '@': continue name_size = len(line1.split("\t")[0]) + 10 break return name_size def _extract_names(file_name, name_size, key_siz...
_name_size
identifier_name
align.py
_dir) names1_npy = os.path.abspath('%s/name1.npy' % base_dir) names2_npy = os.path.abspath('%s/name2.npy' % base_dir) sort1_npy = os.path.abspath('%s/sort1.npy' % base_dir) sort2_npy = os.path.abspath('%s/sort2.npy' % base_dir) ant_dir = '%s/ant' % base_dir idx_dir = '%s/index' % base_dir ...
# seek to it. sam1.seek(u1['row']) sam2.seek(u2['row']) out1.write(sam1.readline()) out2.write(sam2.readline()) # change both. u1 = itr1.next() u2 = itr2.next() else: # pop smaller. if u1[...
""" extract unique alignments, pairs them and annotate repeats""" # open SAM files. sam1 = open(in1_sam, "rb") sam2 = open(in2_sam, "rb") out1 = open(out1_sam, "wb") out2 = open(out2_sam, "wb") # create iterators. itr1 = _uniq_gen(sort1_npy, sam1, annotes) itr2 = _uniq_gen(sort2_npy, s...
identifier_body
align.py
_dir) names1_npy = os.path.abspath('%s/name1.npy' % base_dir) names2_npy = os.path.abspath('%s/name2.npy' % base_dir) sort1_npy = os.path.abspath('%s/sort1.npy' % base_dir) sort2_npy = os.path.abspath('%s/sort2.npy' % base_dir) ant_dir = '%s/ant' % base_dir idx_dir = '%s/index' % base_dir ...
else: # pop smaller. if u1['name'] > u2['name']: u2 = itr2.next() else: u1 = itr1.next() # die after 5 cnt += 1 #if cnt > 5: break # close them. sam1.close() sam2.close() out1.close() out2.close(...
sam1.seek(u1['row']) sam2.seek(u2['row']) out1.write(sam1.readline()) out2.write(sam2.readline()) # change both. u1 = itr1.next() u2 = itr2.next()
conditional_block
align.py
_dir) names1_npy = os.path.abspath('%s/name1.npy' % base_dir) names2_npy = os.path.abspath('%s/name2.npy' % base_dir) sort1_npy = os.path.abspath('%s/sort1.npy' % base_dir) sort2_npy = os.path.abspath('%s/sort2.npy' % base_dir) ant_dir = '%s/ant' % base_dir idx_dir = '%s/index' % base_dir ...
# pop smaller. if u1['name'] > u2['name']: u2 = itr2.next() else: u1 = itr1.next() # die after 5 cnt += 1 #if cnt > 5: break # close them. sam1.close() sam2.close() out1.close() out2.close() def _names(f...
# change both. u1 = itr1.next() u2 = itr2.next() else:
random_line_split
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters...
/// Initialize and generate the i-th position constraints to enforce, e.g., joint limits. fn position_constraint( &self, _i: usize, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _handle: BodyPartHandle<()>, _dof_id: usize, _jacobians: &mut [N], ...
{ 0 }
identifier_body
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters...
/// The maximum number of impulses needed by this joints for /// its constraints. fn nimpulses(&self) -> usize { // FIXME: keep this? self.ndofs() * 3 } /// Maximum number of velocity constrains that can be generated by this joint. fn num_velocity_constraints(&self) -> usize { ...
random_line_split
joint.rs
#![allow(missing_docs)] // For downcast. use downcast_rs::Downcast; use na::{DVectorSliceMut, RealField}; use crate::math::{Isometry, JacobianSliceMut, Vector, Velocity}; use crate::object::{BodyPartHandle, Multibody, MultibodyLink}; use crate::solver::{ConstraintSet, GenericNonlinearConstraint, IntegrationParameters...
(&self) -> usize { 0 } /// Initialize and generate velocity constraints to enforce, e.g., joint limits and motors. fn velocity_constraints( &self, _params: &IntegrationParameters<N>, _multibody: &Multibody<N>, _link: &MultibodyLink<N>, _assembly_id: usize, ...
num_velocity_constraints
identifier_name
TestDarwinNSLogOutput.py
""" Test DarwinLog "source include debug-level" functionality provided by the StructuredDataDarwinLog plugin. These tests are currently only supported when running against Darwin targets. """ import lldb import platform import re from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lld...
# Disable showing of source lines at our breakpoint. # This is necessary for the logging tests, because the very # text we want to match for output from the running inferior # will show up in the source as well. We don't want the source # output to erroneously make a match wit...
child.logfile_read = sys.stdout
conditional_block
TestDarwinNSLogOutput.py
""" Test DarwinLog "source include debug-level" functionality provided by the StructuredDataDarwinLog plugin. These tests are currently only supported when running against Darwin targets. """ import lldb import platform import re from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lld...
def expect_prompt(self, exactly=True): self.expect(self.child_prompt, exactly=exactly) def expect(self, pattern, exactly=False, *args, **kwargs): if exactly: return self.child.expect_exact(pattern, *args, **kwargs) return self.child.expect(pattern, *args, **kwargs) de...
if self.child: self.child.sendline(cmd)
identifier_body
TestDarwinNSLogOutput.py
""" Test DarwinLog "source include debug-level" functionality provided by the StructuredDataDarwinLog plugin. These tests are currently only supported when running against Darwin targets. """ import lldb import platform import re from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lld...
self.runCmd("process continue") self.expect(expect_regexes) def test_nslog_output_is_displayed(self): """Test that NSLog() output shows up in the command-line debugger.""" self.do_test(expect_regexes=[ re.compile(r"(This is a message from NSLog)"), re.compile...
self.run_lldb_to_breakpoint(exe, self.source, self.line, settings_commands=settings_commands) self.expect_prompt() # Now go.
random_line_split
TestDarwinNSLogOutput.py
""" Test DarwinLog "source include debug-level" functionality provided by the StructuredDataDarwinLog plugin. These tests are currently only supported when running against Darwin targets. """ import lldb import platform import re from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lld...
(self): """Test that NSLog() output shows up in the command-line debugger.""" self.do_test(expect_regexes=[ re.compile(r"(This is a message from NSLog)"), re.compile(r"Process \d+ exited with status") ]) self.assertIsNotNone(self.child.match) self.assertGr...
test_nslog_output_is_displayed
identifier_name
type-param-constraints.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<Box<_>>(box 10); u_foo(10); }
{ r { i: i } }
identifier_body
type-param-constraints.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<T:Send>(_unique: T) { } struct r { i: isize, } impl Drop for r { fn drop(&mut self) {} } fn r(i:isize) -> r { r { i: i } } pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<B...
u_foo
identifier_name
type-param-constraints.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
i: isize, } impl Drop for r { fn drop(&mut self) {} } fn r(i:isize) -> r { r { i: i } } pub fn main() { p_foo(r(10)); p_foo::<Box<_>>(box r(10)); p_foo::<Box<_>>(box 10); p_foo(10); s_foo::<Box<_>>(box 10); s_foo(10); u_foo::<Box<_>>(box 10); u_foo(10); }
struct r {
random_line_split
reconnectiontimers.py
from time import sleep import math __author__ = 'sergio' ## @package clitellum.endpoints.channels.reconnectiontimers # Este paquete contiene las clases para los temporizadores de reconexion # ## Metodo factoria que crea una instancia de un temporizador # instantaneo def CreateInstantTimer(): return InstantRecon...
ReconnectionTimer.__init__(self) ## Convierte la instancia a string def __str__(self): return "Instant Reconnection Timer" ## Define un temporizador de reconexion en el que el tiempo de espera entre un ciclo # y el siguiente es logaritmico, . class LogarithmicReconnectionTimer(ReconnectionTim...
# no hay tiempo de espera entre un ciclo y el siguiente class InstantReconnectionTimer(ReconnectionTimer): ## Crea una instancia del temporizador instantaneo def __init__(self):
random_line_split
reconnectiontimers.py
from time import sleep import math __author__ = 'sergio' ## @package clitellum.endpoints.channels.reconnectiontimers # Este paquete contiene las clases para los temporizadores de reconexion # ## Metodo factoria que crea una instancia de un temporizador # instantaneo def CreateInstantTimer(): return InstantRecon...
## Clase base que proporciona la estructura basica de un temporizador de reconexion class ReconnectionTimer: ## Crea una instancia del temporizador de reconexion def __init__(self): pass ## Se espera una vuelta del ciclo antes de continuar def wait(self): pass ## Reinicia el te...
return CreateLogarithmicTimer()
conditional_block
reconnectiontimers.py
from time import sleep import math __author__ = 'sergio' ## @package clitellum.endpoints.channels.reconnectiontimers # Este paquete contiene las clases para los temporizadores de reconexion # ## Metodo factoria que crea una instancia de un temporizador # instantaneo def CreateInstantTimer(): return InstantRecon...
(ReconnectionTimer): ## Crea una instancia del temporizador instantaneo def __init__(self): ReconnectionTimer.__init__(self) ## Convierte la instancia a string def __str__(self): return "Instant Reconnection Timer" ## Define un temporizador de reconexion en el que el tiempo de espera ...
InstantReconnectionTimer
identifier_name
reconnectiontimers.py
from time import sleep import math __author__ = 'sergio' ## @package clitellum.endpoints.channels.reconnectiontimers # Este paquete contiene las clases para los temporizadores de reconexion # ## Metodo factoria que crea una instancia de un temporizador # instantaneo def CreateInstantTimer(): return InstantRecon...
def wait(self): waitingTime = ((1 + (1 / self.__seed)) ^ self.__seed) * (1 + math.log10(self.__seed)) if waitingTime < 0: waitingTime = 0 sleep(waitingTime) self.__seed += 1 def reset(self): self.__seed = 1 ## Convierte la instancia a string def __...
ReconnectionTimer.__init__(self) self.__seed = 1
identifier_body
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a projec...
{ debug!("executing; cmd=cargo-generate-lockfile; args={:?}", env::args().collect::<Vec<_>>()); config.shell().set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); ops::generate_lockfile(&root, config) .map(|_| None).map_err(|err| CliError:...
identifier_body
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, }
pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for -v, --verbose Use verbose output "; pub fn execute(optio...
random_line_split
generate_lockfile.rs
use std::env; use cargo::ops; use cargo::util::{CliResult, CliError, Config}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct
{ flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for ...
Options
identifier_name
app.routing.ts
import { Routes, RouterModule } from '@angular/router'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { GameLobbyComponent } from './components/game-lobby/game-lobby.component'; import { GamePlayComponent } from './components/game-play/game-play.component'; import { GameCreati...
path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent }, { path: 'game/create', component: GameCreationComponent }, { path: 'game/:id/lobby', component: GameLobbyComponent }, { path: 'game/:id/play', compon...
import { PlayerLoginComponent } from "./components/player-login/player-login.component"; const appRoutes: Routes = [ {
random_line_split
structure.rs
0, 2.0, 3.0); /// # let p1 = Point3::new(-3.0, 1.0, 2.0); /// # /// let dv: Vector3<f32> = p1 - p0; /// let half_dv: Vector3<f32> = dv * 0.5; /// let midpoint: Point3<f32> = p0 + half_dv; /// ``` /// /// ## Converting between points and vectors /// /// Points can be converted to and from displacement vectors using the ...
self.diagonal().sum() }
identifier_body
structure.rs
3.0); /// let p1 = Point3::new(-3.0, 1.0, 2.0); /// let midpoint: Point3<f32> = p0 + (p1 - p0) * 0.5; /// ``` /// /// Breaking the expression up, and adding explicit types makes it clearer /// to see what is going on: /// /// ```rust /// # use cgmath::{Point3, Vector3}; /// # /// # let p0 = Point3::new(1.0, 2.0, 3.0); ...
entity()
identifier_name
structure.rs
Point3::new(3.0, 1.0, 2.0), /// ); /// ``` #[inline] fn midpoint(self, other: Self) -> Self { self + (other - self) / (Self::Scalar::one() + Self::Scalar::one()) } /// Returns the average position of all points in the slice. /// /// ```rust /// use cgmath::prelude::*; ...
rem }
conditional_block
structure.rs
trait VectorSpace: Copy + Clone where Self: Zero, Self: Add<Self, Output = Self>, Self: Sub<Self, Output = Self>, Self: iter::Sum<Self>, // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Mul<<Self as VectorSpace>::Scalar, Output = Self>, Self: Div<<Self as VectorSpace...
/// pub trait EuclideanSpace: Copy + Clone where // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092 Self: Array<Element = <Self as EuclideanSpace>::Scalar>, Self: Add<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<<Self as EuclideanSpace>::Diff, Output = Self>, Self: Sub<Se...
/// - [What is the difference between a point and a vector](http://math.stackexchange.com/q/645827)
random_line_split
mnist.py
__author__ = 'igor' """ 构建 mnist network 构建 Graph 1.inference() - Builds the model as far as is required for running the network forward to make predictions. 2.loss() -Adds to the inference model the layers required to generate loss 3.training() - Adds to the loss model the Ops required to generate and apply gradient...
den2_units): ''' 构建 MNIST model,向前传播 :param images: Image placeholder,输入 :param hidden1_units: 第一个隐藏层的大小 :param hidden2_units: 第二个隐藏层的大小 :return: softmax_linear:Output tensor with the computed logits. ''' # Hidden 1 with tf.name_scope("hidden1"): weights = tf.Variabl...
nits, hid
identifier_name
mnist.py
__author__ = 'igor' """ 构建 mnist network 构建 Graph 1.inference() - Builds the model as far as is required for running the network forward to make predictions. 2.loss() -Adds to the inference model the layers required to generate loss 3.training() - Adds to the loss model the Ops required to generate and apply gradient...
def evalution(logits, labels): correct = tf.nn.in_top_k(logits, labels, 1) return tf.reduce_sum(tf.cast(correct, tf.int32)) if __name__ == '__main__': pass
global_step = tf.Variable(0, name='global_step', trainable=False) train_op = optimizer.minimize(loss, global_step=global_step) return train_op
random_line_split
mnist.py
__author__ = 'igor' """ 构建 mnist network 构建 Graph 1.inference() - Builds the model as far as is required for running the network forward to make predictions. 2.loss() -Adds to the inference model the layers required to generate loss 3.training() - Adds to the loss model the Ops required to generate and apply gradient...
identifier_body
mnist.py
__author__ = 'igor' """ 构建 mnist network 构建 Graph 1.inference() - Builds the model as far as is required for running the network forward to make predictions. 2.loss() -Adds to the inference model the layers required to generate loss 3.training() - Adds to the loss model the Ops required to generate and apply gradient...
conditional_block
sslutils.py
# Copyright 2013 IBM Corp. # # 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 t...
def wrap(sock): ssl_kwargs = { 'server_side': True, 'certfile': CONF.ssl.cert_file, 'keyfile': CONF.ssl.key_file, 'cert_reqs': ssl.CERT_NONE, } if CONF.ssl.ca_file: ssl_kwargs['ca_certs'] = CONF.ssl.ca_file ssl_kwargs['cert_reqs'] = ssl.CERT_REQUIRED ...
cert_file = CONF.ssl.cert_file key_file = CONF.ssl.key_file ca_file = CONF.ssl.ca_file use_ssl = cert_file or key_file if cert_file and not os.path.exists(cert_file): raise RuntimeError(_("Unable to find cert_file : %s") % cert_file) if ca_file and not os.path.exists(ca_file): rais...
identifier_body
sslutils.py
# Copyright 2013 IBM Corp. # # 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 t...
return ssl.wrap_socket(sock, **ssl_kwargs) _SSL_PROTOCOLS = { "tlsv1": ssl.PROTOCOL_TLSv1, "sslv23": ssl.PROTOCOL_SSLv23, "sslv3": ssl.PROTOCOL_SSLv3 } try: _SSL_PROTOCOLS["sslv2"] = ssl.PROTOCOL_SSLv2 except AttributeError: pass def validate_ssl_version(version): key = version.lower(...
ssl_kwargs['ca_certs'] = CONF.ssl.ca_file ssl_kwargs['cert_reqs'] = ssl.CERT_REQUIRED
conditional_block
sslutils.py
# Copyright 2013 IBM Corp. # # 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 t...
raise RuntimeError(_("Unable to find ca_file : %s") % ca_file) if key_file and not os.path.exists(key_file): raise RuntimeError(_("Unable to find key_file : %s") % key_file) if use_ssl and (not cert_file or not key_file): raise RuntimeError(_("When running server in SSL mode, you must ...
if ca_file and not os.path.exists(ca_file):
random_line_split
sslutils.py
# Copyright 2013 IBM Corp. # # 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 t...
(sock): ssl_kwargs = { 'server_side': True, 'certfile': CONF.ssl.cert_file, 'keyfile': CONF.ssl.key_file, 'cert_reqs': ssl.CERT_NONE, } if CONF.ssl.ca_file: ssl_kwargs['ca_certs'] = CONF.ssl.ca_file ssl_kwargs['cert_reqs'] = ssl.CERT_REQUIRED return ssl....
wrap
identifier_name
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
(&self) -> &[u8] { &self.bytes[self.bytes_start..self.bytes_end] } /// Get length of sliced bytes pub fn size(&self) -> u64 { (self.bytes_end as u64) - (self.bytes_start as u64) } } // https://w3c.github.io/FileAPI/#blob #[dom_struct] pub struct Blob { reflector_: Reflector, #...
get_bytes
identifier_name
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
let relativeStart: i64 = match start { None => 0, Some(start) => { if start < 0 { max(size + start, 0) } else { min(start, size) } } }; let relativeEnd: i64 = match end { ...
impl DataSlice { /// Construct DataSlice from reference counted bytes pub fn new(bytes: Arc<Vec<u8>>, start: Option<i64>, end: Option<i64>) -> DataSlice { let size = bytes.len() as i64;
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
, } }).collect::<Vec<u8>>() } impl BlobMethods for Blob { // https://w3c.github.io/FileAPI/#dfn-size fn Size(&self) -> u64 { self.data.size() } // https://w3c.github.io/FileAPI/#dfn-type fn Type(&self) -> DOMString { DOMString::from(self.typeString.clone()) ...
{ b.get_data().get_bytes().to_vec() }
conditional_block
queryBuilder.js
function
(dictionary, minSubset) { if (!(this instanceof QueryBuilder)) { return new QueryBuilder(dictionary, minSubset); } var queries = combine(dictionary, minSubset); var self = this; this.queryList = queries; QueryBuilder.prototype.getQueryList = function(){ return this.q...
QueryBuilder
identifier_name
queryBuilder.js
function QueryBuilder(dictionary, minSubset) { if (!(this instanceof QueryBuilder)) { return new QueryBuilder(dictionary, minSubset); } var queries = combine(dictionary, minSubset); var self = this; this.queryList = queries; QueryBuilder.prototype.getQueryList = function(){ ...
return; } for (var j = 0; j < src.length; j++) { fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all); } return; } var all = []; for (var i = min; i < a.length; i++) { fn(i, a, [], all); } all.push(a); return all; } module.expor...
{ all[all.length] = got; }
conditional_block
queryBuilder.js
function QueryBuilder(dictionary, minSubset)
var combine = function (a, min) { var fn = function (n, src, got, all) { if (n === 0) { if (got.length > 0) { all[all.length] = got; } return; } for (var j = 0; j < src.length; j++) { fn(n - 1, src.slice(j + 1), got.concat([sr...
{ if (!(this instanceof QueryBuilder)) { return new QueryBuilder(dictionary, minSubset); } var queries = combine(dictionary, minSubset); var self = this; this.queryList = queries; QueryBuilder.prototype.getQueryList = function(){ return this.queryList; }; }
identifier_body
queryBuilder.js
function QueryBuilder(dictionary, minSubset) { if (!(this instanceof QueryBuilder)) { return new QueryBuilder(dictionary, minSubset); } var queries = combine(dictionary, minSubset); var self = this; this.queryList = queries; QueryBuilder.prototype.getQueryList = function(){ ...
} all.push(a); return all; } module.exports = QueryBuilder;
var all = []; for (var i = min; i < a.length; i++) { fn(i, a, [], all);
random_line_split
nosy.py
"""Watch for changes in a collection of source files. If changes, run the specified test runner (nosetests, by default). """ from argparse import ArgumentParser import ConfigParser import glob import os import stat import subprocess import sys import time class Nosy(object): """Watch for changes in all source fil...
return checksum def _calc_exclusions(self, root): """Return a set of file paths to be excluded from the checksum calculation. """ exclusions = set() for pattern in self.exclude_patterns: for file_path in glob.iglob(os.path.join(root, pattern)): ...
for file_path in glob.iglob(path): stats = os.stat(file_path) checksum += stats[stat.ST_SIZE] + stats[stat.ST_MTIME]
conditional_block