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
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.r...
@app.route('/add/<modelname>/', methods=['GET', 'POST']) def add(modelname): kwargs = listAndEdit(modelname) return render_template('editpage.html', **kwargs) @app.route('/add/<modelname>/to/<foreign_table>/<foreign_key>', methods=['GET', 'POST']) def addto(modelname, foreign_table, foreign_key): ...
Form = forms.ManualRegisterForm(request.values) if request.method == 'POST': if Form.submit.data: saveFormsToModels(Form) return redirect(url_for('register')) return render_template('frontpage.html', form = Form, )
identifier_body
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.r...
def getFields(model, exclude=['id']): foreignKeys = {x.column : x.dest_table for x in models.db.get_foreign_keys(model.__name__)} #fields = [(x, type(model._meta.fields[x]).__name__, foreignKeys) for x in model._meta.sorted_field_names if not x in exclude] #print foreignKeys fields = [] for...
editedModels[model].save()
conditional_block
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.r...
except: pass finally: entry = model() form = modelForm(obj = entry) kwargs = dict( links = [x.__name__ for x in models.ALL_MODELS], header = model.__name__, form=form, entry=entry, entri...
try: model.get(model.id == int(entryid)).delete_instance(recursive = True) #redirect(url_for('add', modelname = modelname))
random_line_split
views.py
from frontend import app from flask import render_template from flask import send_from_directory from flask import request from flask import redirect from flask import url_for from flask import flash from flask import abort import os import models import forms from wtfpeewee.orm import model_form @app.r...
(entry): entries = {} models = [] try: for query, fk in reversed(list(entry.dependencies())): #for x in dir(fk): #print x for x in fk.model_class.select().where(query): #print 'here:' #print x modelname...
getRelatedModels
identifier_name
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="...
} } $(window).unbind('resize'); $('div.map_window').fadeOut(); return false; }); $('a.save').click(function(e){ $('#project_coordinates li').each(function(){ $(this).remove(); }); for(var i=0;i<markers_position.length;i++){ ...
if (point == markers_position[i]) { markers_position.splice(i);
random_line_split
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="...
{ var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds); ...
identifier_body
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="...
() { var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.bounds);...
searchPlace
identifier_name
project_map.js
/* Unused, experimental code for adding project locations via * clickable google map_ */ var markers_position = []; var map; var geocoder = new google.maps.Geocoder(); var first = true; $(document).ready( function() { //change geolocate input value $('div.outer_map form input[type="...
$(window).unbind('resize'); $('div.map_window').fadeOut(); }); }); function searchPlace() { var address = $('div.outer_map form input[type="text"]').attr('value'); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.Geocoder...
{ $('#project_coordinates').append('<li><p>'+markers_position[i]+'</p><input type="hidden" name="project[points][]" value="'+markers_position[i]+'" /><a href="javascript:void(null)" class="close"></a></li>'); }
conditional_block
usbiodef.rs
developers // 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 http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // excep...
pub const USB_GET_DEVICE_HANDLE_EX: ULONG = 269; pub const USB_GET_TT_DEVICE_HANDLE: ULONG = 270; pub const USB_GET_TOPOLOGY_ADDRESS: ULONG = 271; pub const USB_IDLE_NOTIFICATION_EX: ULONG = 272; pub const USB_REQ_GLOBAL_SUSPEND: ULONG = 273; pub const USB_REQ_GLOBAL_RESUME: ULONG = 274; pub const USB_GET_HUB_CONFIG_IN...
random_line_split
usbiodef.rs
developers // 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 http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // excep...
id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) } #[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context:...
SB_KERNEL_CTL(
identifier_name
usbiodef.rs
developers // 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 http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // excep...
#[inline] pub fn USB_KERNEL_CTL_BUFFERED(id: ULONG) -> ULONG { CTL_CODE!(FILE_DEVICE_USB, id, METHOD_BUFFERED, FILE_ANY_ACCESS) } // No calling convention was specified in the code FN!{stdcall USB_IDLE_CALLBACK( Context: PVOID, ) -> ()} STRUCT!{struct USB_IDLE_CALLBACK_INFO {
CTL_CODE!(FILE_DEVICE_USB, id, METHOD_NEITHER, FILE_ANY_ACCESS) }
identifier_body
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) ...
def routes_directions(self, **kwargs): expected = ('route.id', 'provider.id') missing = [x for x in expected if x not in kwargs] if missing: raise APIError('missing attributes: ' + ','.join(missing), 422) provider = self._providers[kwargs['provider.id']] route =...
raise APIError('missing attributes: ' + ','.join( x for x in expected if x not in kwargs), 422)
conditional_block
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) ...
limit = int(limit) if limit <= 0: raise ValueError() except ValueError: raise APIError('_limit must be a positive integer', 422) response['request']['limit'] = limit if 'realtime' in kwargs: ...
if entity is None: return self.help() response = { 'request': { 'status': 'ok', 'entity': entity, 'params': kwargs, } } try: to_expand = (kwargs.pop('_expand').split(',') if...
identifier_body
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) ...
response['request']['action'] = action if (entity, action) in self._entity_actions: func, entity = self._entity_actions[(entity, action)] result = func(**kwargs) else: raise EndpointNotFoundError(entity, action) ...
random_line_split
web.py
import busbus from busbus.entity import BaseEntityJSONEncoder from busbus.provider import ProviderBase from busbus.queryable import Queryable import cherrypy import collections import itertools import types def json_handler(*args, **kwargs): value = cherrypy.serving.request._json_inner_handler(*args, **kwargs) ...
(self, **kwargs): expected = ('route.id', 'provider.id') missing = [x for x in expected if x not in kwargs] if missing: raise APIError('missing attributes: ' + ','.join(missing), 422) provider = self._providers[kwargs['provider.id']] route = provider.get(busbus.Route,...
routes_directions
identifier_name
macros.rs
// Bloom // // HTTP REST API caching middleware // Copyright: 2017, Valerian Saliou <valerian@valeriansaliou.name> // License: Mozilla Public License v2.0 (MPL v2.0) macro_rules! get_cache_store_client_try { ($pool:expr, $error:expr, $client:ident $code:block) => { // In the event of a Redis failure, 'try_...
// an operation succeeds (eg. for cache purges). match $pool.get() { Ok(mut $client) => $code, Err(err) => { error!( "failed getting a cache store client from pool (wait mode), because: {}", err ); ...
random_line_split
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension):
def start_program(self, program): self.program = program def end_program(self, _): self.program = None def start_section(self, section): last_paragraph = section.get_children()[-1] if 'paragraph' == last_paragraph.get_kind(): child...
def __init__(self): self.program = None
random_line_split
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension): def __init__(self): self.program = None def start_program(self, program): self.program = program def
(self, _): self.program = None def start_section(self, section): last_paragraph = section.get_children()[-1] if 'paragraph' == last_paragraph.get_kind(): children = last_paragraph.get_children() if len(children) > 1: # vi...
end_program
identifier_name
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension):
kind = children[0].get_kind() if kind not in ['exit', 'stop_run', 'goback']: self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) else: # violation test_ko1 self.program.save_...
def __init__(self): self.program = None def start_program(self, program): self.program = program def end_program(self, _): self.program = None def start_section(self, section): last_paragraph = section.get_children()[-1] if 'paragraph' == last_para...
identifier_body
empty_paragraph_end.py
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension): def __init__(self): self.program = None def start_program(self, program): self.program = program def end_program(self, _): self.program = None def start_section(self...
elif len(children) == 1: kind = children[0].get_kind() if kind not in ['exit', 'stop_run', 'goback']: self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) else: ...
self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position())
conditional_block
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(...
} } else { error!("Plugin not found: {:?}", library); std::process::exit(123); } }); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(libra...
{ error!("Init function not found: {:?}", initializer); std::process::exit(123); }
conditional_block
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(...
}); } #[cfg(all(unix, test, not(target_os = "android")))] fn _load_lib(library: &str) -> libloading::Result<libloading::Library> { libloading::os::unix::Library::open(Some(library), libc::RTLD_NOW | libc::RTLD_NODELETE) .map(libloading::Library::from) } #[cfg(any(not(unix), not(test), target_os = "and...
} } else { error!("Plugin not found: {:?}", library); std::process::exit(123); }
random_line_split
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn
(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(library) { unsafe { if let Ok(init_func) = lib.get(initializer.as_bytes()) { ...
init_plugin
identifier_name
plugins.rs
use settings; use indy::ErrorCode; static INIT_PLUGIN: std::sync::Once = std::sync::Once::new(); pub fn init_plugin(library: &str, initializer: &str) { settings::set_config_value(settings::CONFIG_PAYMENT_METHOD, settings::DEFAULT_PAYMENT_METHOD); INIT_PLUGIN.call_once(|| { if let Ok(lib) = _load_lib(...
{ libloading::Library::new(library) }
identifier_body
index.js
"use strict"; var ArrayCollection_1 = require('./ArrayCollection'); exports.ArrayCollection = ArrayCollection_1.ArrayCollection; var ArrayList_1 = require('./ArrayList'); exports.ArrayList = ArrayList_1.ArrayList; var SequenceBase_1 = require('./SequenceBase'); exports.SequenceBase = SequenceBase_1.SequenceBase; var Bu...
var Iterable_1 = require('./Iterable'); exports.Iterable = Iterable_1.Iterable; var LinkedList_1 = require('./LinkedList'); exports.LinkedList = LinkedList_1.LinkedList; var Native_1 = require('./Native'); exports.NativeIndex = Native_1.NativeIndex; exports.NativeMap = Native_1.NativeMap; var Sequence_1 = require('./Se...
random_line_split
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the Euro...
(self): # default list of name lo_name = strFunctions.list_of_name(self.class_object['name']) # check that we have not specified this should be different if 'lo_class_name' in self.class_object and \ len(self.class_object['lo_class_name']) > 0: lo_name = self....
create_list_of_description
identifier_name
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the Euro...
def write_header(self, class_desc): fileout = CppHeaderFile.CppHeaderFile(class_desc) if self.verbose: print('Writing file {0}'.format(fileout.filename)) fileout.write_file() fileout.close_file() def write_code(self, class_desc): fileout = CppCodeFile.CppCo...
self.write_header(self.class_object) self.write_code(self.class_object) if self.class_object['hasListOf']: lo_working_class = self.create_list_of_description() self.write_header(lo_working_class) self.write_code(lo_working_class)
identifier_body
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the Euro...
else: descrip['baseClass'] = strFunctions.prefix_name('ListOf') descrip['list_of_name'] = lo_name descrip['lo_child'] = self.class_object['name'] descrip['name'] = lo_name return descrip def test_func(self): self.write_files()
descrip['baseClass'] = 'ListOf'
conditional_block
CppFiles.py
#!/usr/bin/env python # # @file CppFiles.py # @brief class for generating cpp files # @author Frank Bergmann # @author Sarah Keating # # <!-------------------------------------------------------------------------- # # Copyright (c) 2013-2015 by the California Institute of Technology # (California, USA), the Euro...
# Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED ...
random_line_split
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def...
else: __HOOK_REGISTRY[category].append(func) def override_command(command, func): global __COMMANDS_OVERRIDE local_dir = os.path.dirname(compat_inspect.stack()[2][1]) if __COMMANDS_OVERRIDE.has_key(command): __COMMANDS_OVERRIDE[command].append((func, local_dir)) else: __CO...
__HOOK_REGISTRY[category] = [func]
conditional_block
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def...
(cmd_name): global __POST_HOOK_REGISTRY return __POST_HOOK_REGISTRY.get(cmd_name, []) def get_command_override(cmd_name): global __COMMANDS_OVERRIDE return __COMMANDS_OVERRIDE.get(cmd_name, []) def _make_hook_decorator(command_name, kind): name = "%s_%s" % (kind, command_name) help_bypass = Fa...
get_post_hooks
identifier_name
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def...
else: __POST_HOOK_REGISTRY[cmd_name].append(func) def get_registry_categories(): global __HOOK_REGISTRY return __HOOK_REGISTRY.keys() def get_registry_category(categorie): global __HOOK_REGISTRY return __HOOK_REGISTRY[categorie] def get_pre_hooks(cmd_name): global __PRE_HOOK_REGISTR...
if not cmd_name in __POST_HOOK_REGISTRY: __POST_HOOK_REGISTRY[cmd_name] = [func]
random_line_split
hooks.py
import os import sys import re from bento.compat \ import \ inspect as compat_inspect from bento.commands.core \ import \ command SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]") __HOOK_REGISTRY = {} __PRE_HOOK_REGISTRY = {} __POST_HOOK_REGISTRY = {} __COMMANDS_OVERRIDE = {} __INIT_FUNCS = {} def...
def get_registry_categories(): global __HOOK_REGISTRY return __HOOK_REGISTRY.keys() def get_registry_category(categorie): global __HOOK_REGISTRY return __HOOK_REGISTRY[categorie] def get_pre_hooks(cmd_name): global __PRE_HOOK_REGISTRY return __PRE_HOOK_REGISTRY.get(cmd_name, []) def get_p...
global __POST_HOOK_REGISTRY if not cmd_name in __POST_HOOK_REGISTRY: __POST_HOOK_REGISTRY[cmd_name] = [func] else: __POST_HOOK_REGISTRY[cmd_name].append(func)
identifier_body
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import...
return location } const NearbyGalleryCard: React.FC<NearbyGalleryCardProps> = ({ partner, city, ...rest }) => { const { user } = useSystemContext() if (!partner) { return null } const { name, slug, profile, type, locationsConnection } = partner const canFollow = type !== "Auction House" con...
{ const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity } else { location = cities[0] } if (cities.length > 1) { location += ` & ${cities.length - 1} other ...
conditional_block
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import...
} return location } const NearbyGalleryCard: React.FC<NearbyGalleryCardProps> = ({ partner, city, ...rest }) => { const { user } = useSystemContext() if (!partner) { return null } const { name, slug, profile, type, locationsConnection } = partner const canFollow = type !== "Auction House" ...
{ let location if (cities.length > 0) { const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity } else { location = cities[0] } if (cities.length > 1) { ...
identifier_body
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import...
(cities: Array<string>, preferredCity?: string | null) { let location if (cities.length > 0) { const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity } else { location...
getLocation
identifier_name
NearbyGalleryCard.tsx
import { ContextModule } from "@artsy/cohesion" import { Box, BoxProps, ResponsiveBox, Image, Flex, Text } from "@artsy/palette" import { capitalize, compact, uniq } from "lodash" import React from "react" import { createFragmentContainer, graphql } from "react-relay" import { useSystemContext } from "v2/System" import...
} function getLocation(cities: Array<string>, preferredCity?: string | null) { let location if (cities.length > 0) { const normalizedPreferredCity = preferredCity && normalizeCityName(preferredCity) if (cities.some(c => c === normalizedPreferredCity)) { location = normalizedPreferredCity ...
city?: string | null } function normalizeCityName(city: string) { return capitalize(city.trim())
random_line_split
playerwrapper.js
var PlayerWrapper = function() { this.underlyingPlayer = 'aurora'; this.aurora = {}; this.sm2 = {}; this.duration = 0; this.volume = 100; return this; }; PlayerWrapper.prototype = _.extend({}, OC.Backbone.Events); PlayerWrapper.prototype.play = function() { switch(this.underlyingPlayer) { case 'sm2': thi...
}, onfinish: function() { self.trigger('end'); }, onload: function(success) { if (success) { self.trigger('ready'); } else { console.log('SM2: sound load error'); } } }); break; case 'aurora': this.aurora = AV.Player.fromURL(url); this.aurora.asset.sourc...
// Show the buffering status according the last buffered position. var bufCount = this.buffered.length; var bufEnd = (bufCount > 0) ? this.buffered[bufCount-1].end : 0; self.trigger('buffer', bufEnd / this.durationEstimate * 100);
random_line_split
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>,...
#[cfg(test)] mod tests { use super::*; #[test] fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(...
{ image::DynamicImage::new_rgba8(w, h).to_rgba() }
identifier_body
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>,...
<T: Location + Draw + MinMax>(list: &[T]) -> (Coordinate, Coordinate) { let mut size: i16 = consts::DEFAULT_SIZE as i16; let mut min = coordinate!(); let mut max = coordinate!(); for item in list { size = cmp::max(size, item.size() as i16); let (imin, imax) = item.min_max(); ma...
min_max
identifier_name
mod.rs
/*! Functions to manage large numbers of placable entities. */ extern crate image; use super::*; use image::Rgba; use std::cmp; pub mod gif; pub mod network; /** Returns the underlaying image used for the Map struct. */ pub fn gen_map<T: Location + Draw + MinMax>( list: &[T], ) -> (image::ImageBuffer<Rgba<u8>,...
fn test_gen_canvas() { let image = gen_canvas(50, 50); assert_eq!(image.width(), 50); assert_eq!(image.height(), 50); } #[test] fn test_gen_canvas_2() { let image = gen_canvas(0, 0); assert_eq!(image.width(), 0); assert_eq!(image.height(), 0); } ...
random_line_split
__init__.py
else: table_args.append(table_arg) if len(table_dict) > 0: table_args.append(table_dict) return tuple(table_args,) class ChangeTracked(object): """A model with fields to tracked the last user to modify the model, the creation time of the model, and the last time the model was updated...
table_dict.update(table_arg)
conditional_block
__init__.py
from sqlalchemy import event from sqlalchemy import orm from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.session import Session from ggrc import builder from ggrc import db from ggrc.models import reflection...
from uuid import uuid1 import datetime
random_line_split
__init__.py
created_at", "updated_at"), orm.Load(cls).joinedload( "modified_by" ).load_only( "name", "email", "id" ), ) class Titled(object): """Mixin that defines `title` field. Strips title on update and defines optional UNIQUE constraint on it. """ @validates('titl...
class Hierarchical(object): """Mixin that defines `parent` and `child` fields to organize hierarchy.""" @declared_attr def parent_id(cls): return deferred(db.Column( db.Integer, db.ForeignKey('{0}.id'.format(cls.__tablename__))), cls.__name__) @declared_attr def children(cls): ret...
return super(Hyperlinked, cls).indexed_query().options( orm.Load(cls).load_only("url", "reference_url"), )
identifier_body
__init__.py
"Verified"} DONE_STATES = {} # pylint: disable=method-hidden # because validator only sets date per model instance @declared_attr def verified_date(cls): return deferred( db.Column(db.DateTime, nullable=True), cls.__name__ ) @hybrid_property def verified(self): return self.ve...
generate_slug_prefix_for
identifier_name
pcValidation.js
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may ...
} return { controller: Controller, require: { ngModel: 'ngModel' }, bindToController: { items: '<pcInCollection', pluck: '@?pcInCollectionPluck' } }; }) .directive('pcPowerOfTwo'...
{ this.ngModel.$validate(); }
identifier_body
pcValidation.js
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may ...
/** @type {ng.INgModelController} */ ngModel; /** @type {Array} */ items; $onInit() { this.ngModel.$validators.notInCollection = (item) => { if (!this.items) return true; return !this.items.includes(item...
class Controller {
random_line_split
pcValidation.js
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may ...
{ static animName = 'ignite-form-field__error-blink'; static eventName = 'webkitAnimationEnd oAnimationEnd msAnimationEnd animationend'; static $inject = ['$element', '$scope']; constructor($element, $scope) { Object.assign(this, {$element}); this.$scope = $scope; } $postLink() ...
IgniteFormField
identifier_name
EnterLeaveEventPlugin.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {accumulateEnterLeaveDispatches} from 'events/EventPropagators'; import { TOP_MOUSE_OUT, TOP_MOUSE_OVER, TOP_POINTER_OUT, ...
nativeEventTarget, ); enter.type = eventTypePrefix + 'enter'; enter.target = toNode; enter.relatedTarget = fromNode; accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; }, }; export default EnterLeaveEventPlugin;
random_line_split
EnterLeaveEventPlugin.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {accumulateEnterLeaveDispatches} from 'events/EventPropagators'; import { TOP_MOUSE_OUT, TOP_MOUSE_OVER, TOP_POINTER_OUT, ...
else { win = window; } } let from; let to; if (isOutEvent) { from = targetInst; const related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window....
{ win = doc.defaultView || doc.parentWindow; }
conditional_block
vega.schema.ts
NumericValueRef | ColorValueRef>; export type MapExcludeValueRefAndReplaceSignalWith<T, S extends ExprRef | SignalRef> = MapExcludeAndKeepSignalAs< T, ScaledValueRef<any> | NumericValueRef | ColorValueRef, S >; export interface VgData { name: string; source?: string; values?: any; format?: { type?:...
// xc'|'yc' // clip: 1,
random_line_split
vega.schema.ts
as VgUnionSortField } from 'vega'; import {isArray} from 'vega-util'; import {Value} from './channeldef'; import {ExprRef} from './expr'; import {SortOrder} from './sort'; import {Dict, Flag, keys} from './util'; export type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef}; ...
return false; } export function isFieldRefUnionDomain(domain: VgDomain): domain is VgMultiFieldsRefWithSort { if (!isArray(domain)) { return 'fields' in domain && 'data' in domain; } return false; } export function isDataRefDomain(domain: VgDomain | any): domain is VgScaleDataRefWithSort { if (!isArray...
{ return 'fields' in domain && !('data' in domain); }
conditional_block
vega.schema.ts
as VgUnionSortField } from 'vega'; import {isArray} from 'vega-util'; import {Value} from './channeldef'; import {ExprRef} from './expr'; import {SortOrder} from './sort'; import {Dict, Flag, keys} from './util'; export type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef}; ...
(range: VgRange): range is VgRangeStep { return !!range['step']; } export interface VgRangeStep { step: number | SignalRef; } // Domains that are not a union of domains export type VgNonUnionDomain = (null | string | number | boolean | SignalRef)[] | VgScaleDataRefWithSort | SignalRef; export type VgDomain = Base...
isVgRangeStep
identifier_name
vega.schema.ts
as VgUnionSortField } from 'vega'; import {isArray} from 'vega-util'; import {Value} from './channeldef'; import {ExprRef} from './expr'; import {SortOrder} from './sort'; import {Dict, Flag, keys} from './util'; export type {VgSortField, VgUnionSortField, VgCompare, VgTitle, LayoutAlign, ProjectionType, VgExprRef}; ...
export type VgEncodeChannel = | 'x' | 'x2' | 'xc' | 'width' | 'y' | 'y2' | 'yc' | 'height' | 'opacity' | 'fill' | 'fillOpacity' | 'stroke' | 'strokeWidth' | 'strokeCap' | 'strokeOpacity' | 'strokeDash' | 'strokeDashOffset' | 'strokeMiterLimit' | 'strokeJoin' | 'strokeOffset' ...
{ if (!isArray(domain)) { return 'field' in domain && 'data' in domain; } return false; }
identifier_body
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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 2 of the License, or (at your option) # any later version. # # ...
(self): QWidget.__init__(self) self.ui = Ui_KeyboardWidget() self.ui.setupUi(self) index = 0 # comboBox.addItem doesn't increase the currentIndex self.default_layout_index = None locales = sorted([(country, data) for country, data in yali.localedata.locales.items()]) ...
__init__
identifier_name
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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 2 of the License, or (at your option) # any later version. # # ...
def execute(self): ctx.interface.informationWindow.hide() ctx.logger.debug("Selected keymap is : %s" % ctx.installData.keyData["name"]) return True
index = self.ui.keyboard_list.currentIndex() keymap = self.ui.keyboard_list.itemData(index)#.toMap() # Gökmen's converter keymap = dict(map(lambda x: (str(x[0]), unicode(x[1])), keymap.iteritems())) ctx.installData.keyData = keymap ctx.interface.informationWindow.hide() i...
identifier_body
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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 2 of the License, or (at your option) # any later version. # # ...
index += 1 self.ui.keyboard_list.setCurrentIndex(self.default_layout_index) self.ui.keyboard_list.currentIndexChanged[int].connect(self.slotLayoutChanged) def shown(self): self.slotLayoutChanged() def slotLayoutChanged(self): index = self.ui.keyboard_list.curren...
self.default_layout_index = index
conditional_block
ScrKeyboard.py
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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 2 of the License, or (at your option) # any later version. # # ...
_d["consolekeymap"] = data["consolekeymap"][i] self.ui.keyboard_list.addItem(_d["name"], QVariant(_d)) i += 1 else: self.ui.keyboard_list.addItem(data["name"], QVariant(data)) if ctx.consts.lang == country: ...
_d["xkbvariant"] = variant[0] _d["name"] = variant[1]
random_line_split
OptionSchemas.ts
/** * Individual option schema within a menu. */ export type OptionSchema = | ActionSchema | BooleanSchema | MultiSelectSchema | NumberSchema | SelectSchema | StringSchema; /** * Type of an option schema. */ export enum OptionType { /** * Simple triggerable action. */ Acti...
*/ String = "string", } /** * Basic details for option schemas. */ export interface BasicSchema { /** * Displayed title of the option. */ title: string; /** * Type of the option. */ type: OptionType; } /** * Option that just calls an action. */ export interface Action...
Select = "select", /** * Any string value.
random_line_split
all.js
'use strict';
description: 'A KanBan system for FogBugz using MeanJS', keywords: 'KanBan, FogBugz, MeanJS' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstra...
module.exports = { app: { title: 'FrogBan',
random_line_split
main.rs
4rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::...
&ServerError::IoError(ref e) => e.fmt(f), &ServerError::DownstreamError(ref e) => e.fmt(f), &ServerError::StoreError(ref e) => write!(f, "{}", e), } } } impl Error for ServerError { fn description(&self) -> &str { match self { &ServerError::CapnpError(ref e) => e.description(), ...
random_line_split
main.rs
rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::E...
(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match self.protocol.try_lock() { Ok(ref proto) => write!(fmt, "DownStream{{ protocol: {:?} }}", &**proto), Err(_) => write!(fmt, "DownStream{{ protocol: <locked> }}"), } } } impl<S> Clone for DownStream<S> wher...
fmt
identifier_name
main.rs
rs; extern crate rusqlite; extern crate byteorder; #[cfg(test)] extern crate quickcheck; #[cfg(test)] extern crate rand; use std::default::Default; use std::net::{TcpListener, TcpStream}; use std::thread; use std::io::{self,Read,Write}; use std::fmt; use std::sync::{Arc,Mutex}; use std::clone::Clone; use std::error::E...
fn write(&self, seq: SeqNo, space: &str, key: &[u8], val: &[u8]) -> Result<Response, ServerError> { trace!("{}/{:?}: write:{:?} -> {:?}", self.id, space, key, val); try_box!(self.store.write(space, key, val)); Ok(Response::Okay(seq)) } fn subscribe(&mut self, seq: SeqNo, space: &str) -> Result<(), S...
{ let val = try_box!(self.store.read(space, key)); trace!("{}/{:?}: read:{:?}: -> {:?}", self.id, space, key, val); let data = val.iter().map(|c| Datum { key: Vec::new(), content: c.clone() }).collect(); Ok(Response::OkayData(seq, data)) }
identifier_body
signup.component.ts
import { Component, OnInit } from "@angular/core"; import { Router } from '@angular/router' import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; import { AuthService } from '../../services/authServices/auth.service'; @Component({ moduleId: module.id, selector: 'signup', templat...
onSignup() { var signupInfo = { email: this.email, password: this.password, password_confirmation: this.password_confirmation }; this._AuthService.signUp(signupInfo).subscribe( response => { console.log("Success Response "...
this.email = ''; this.password = ''; this.password_confirmation = ''; }
random_line_split
signup.component.ts
import { Component, OnInit } from "@angular/core"; import { Router } from '@angular/router' import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; import { AuthService } from '../../services/authServices/auth.service'; @Component({ moduleId: module.id, selector: 'signup', templat...
() { var signupInfo = { email: this.email, password: this.password, password_confirmation: this.password_confirmation }; this._AuthService.signUp(signupInfo).subscribe( response => { console.log("Success Response " + response);...
onSignup
identifier_name
signup.component.ts
import { Component, OnInit } from "@angular/core"; import { Router } from '@angular/router' import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms"; import { AuthService } from '../../services/authServices/auth.service'; @Component({ moduleId: module.id, selector: 'signup', templat...
ngOnInit(): void { } }
{ var signupInfo = { email: this.email, password: this.password, password_confirmation: this.password_confirmation }; this._AuthService.signUp(signupInfo).subscribe( response => { console.log("Success Response " + response); ...
identifier_body
Position.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @provides...
(left, top) { this.left = left; this.top = top; } Position.prototype.destructor = function() { this.left = null; this.top = null; }; PooledClass.addPoolingTo(Position, twoArgumentPooler); module.exports = Position;
Position
identifier_name
Position.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @provides...
Position.prototype.destructor = function() { this.left = null; this.top = null; }; PooledClass.addPoolingTo(Position, twoArgumentPooler); module.exports = Position;
{ this.left = left; this.top = top; }
identifier_body
Position.js
/**
* of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Position */ 'use strict'; var PooledClass = require('react/lib/PooledClass'); var twoArgumentPooler = PooledClass.twoArgumentPooler; /** * Position does not expose methods for construction via an `HTMLDOMElement`, *...
* Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant
random_line_split
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class WikiModel(): def __init_...
string_data.append(' '.join(parsed)) count_data = self.vectorizer.transform(string_data) # classify the documents probs = self.classifier.predict_proba(count_data) return probs
if (word in self.english_words and word not in self.stop_words and word in self.vocabulary): parsed.append(word)
conditional_block
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class WikiModel(): def __init_...
def load_training_data(self): # make some dictionaries to preprocess the words english_words = set() with open(PATH + "american-english.txt") as english_dictionary: english_words = set( word.strip().lower() for word in english_dictionary) stop_words = s...
self.vocabulary = set() self.stop_words = set() self.english_words = set() self.label_map = {} self.reverse_label_map = {} self.count_data = [] self.labels = [] self.vectorizer = None self.classifier = None self.load_training_data()
identifier_body
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class
(): def __init__(self): self.vocabulary = set() self.stop_words = set() self.english_words = set() self.label_map = {} self.reverse_label_map = {} self.count_data = [] self.labels = [] self.vectorizer = None self.classifier = None self...
WikiModel
identifier_name
wiki_model.py
import numpy from wiki_scraper import ( parse_html_simple, crawl_page) import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import os.path from parallel_webscrape import scrape_wikipedia PATH = 'wikimodel/' class WikiModel(): def __init_...
parsed.append(word) categories[k][inner_k] = parsed # aggregate all of the documents into one big data set while # transforming them into counts self.vocabulary = set(all_words) self.vectorizer = CountVectorizer(vocabulary=self.vocabulary) ...
for word in words: if word in english_words and word not in stop_words: all_words.add(word)
random_line_split
__init__.py
from functools import reduce def vartype(var): if var.is_discrete: return 1 elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(i...
except AttributeError: if arg: return arg[0] if kwarg: return kwarg["default"] raise def getHtmlCompatibleString(strVal): return strVal.replace("<=", "&#8804;").replace(">=","&#8805;").replace("<", "&#60;").replace(">","&#62;").replace("=\\=", "&#8800;")
if isinstance(obj, dict): return obj.get(attr) try: return reduce(getattr, attr.split("."), obj)
random_line_split
__init__.py
from functools import reduce def vartype(var): if var.is_discrete: return 1 elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(i...
(strVal): return strVal.replace("<=", "&#8804;").replace(">=","&#8805;").replace("<", "&#60;").replace(">","&#62;").replace("=\\=", "&#8800;")
getHtmlCompatibleString
identifier_name
__init__.py
from functools import reduce def vartype(var): if var.is_discrete: return 1 elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(i...
def getHtmlCompatibleString(strVal): return strVal.replace("<=", "&#8804;").replace(">=","&#8805;").replace("<", "&#60;").replace(">","&#62;").replace("=\\=", "&#8800;")
if isinstance(obj, dict): return obj.get(attr) try: return reduce(getattr, attr.split("."), obj) except AttributeError: if arg: return arg[0] if kwarg: return kwarg["default"] raise
identifier_body
__init__.py
from functools import reduce def vartype(var): if var.is_discrete:
elif var.is_continuous: return 2 elif var.is_string: return 3 else: return 0 def progress_bar_milestones(count, iterations=100): return set([int(i*count/float(iterations)) for i in range(iterations)]) def getdeepattr(obj, attr, *arg, **kwarg): if isinstance(obj, dict): ...
return 1
conditional_block
list-link-handler.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
/** * Check if the handler is enabled on a site level. * * @return {boolean} Whether or not the handler is enabled on a site level. */ isEnabled(): boolean { return this.assignProvider.isPluginEnabled(); } }
{ super(linkHelper, translate, 'AddonModAssign', 'assign'); }
identifier_body
list-link-handler.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
constructor(linkHelper: CoreContentLinksHelperProvider, translate: TranslateService, protected assignProvider: AddonModAssignProvider) { super(linkHelper, translate, 'AddonModAssign', 'assign'); } /** * Check if the handler is enabled on a site level. * * @return {boolea...
*/ @Injectable() export class AddonModAssignListLinkHandler extends CoreContentLinksModuleListHandler { name = 'AddonModAssignListLinkHandler';
random_line_split
list-link-handler.ts
// (C) Copyright 2015 Martin Dougiamas // // 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 agre...
(): boolean { return this.assignProvider.isPluginEnabled(); } }
isEnabled
identifier_name
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; impo...
set vLength(vLength: number) { mustBeInteger('vLength', vLength); throw new Error(readOnly('vLength').message); } public vertexTransform(transform: Transform): void { const iLen = this.vertices.length; for (let i = 0; i < iLen; i++) { const vertex = this.vertice...
{ return numPostsForFence(this._vSegments, this._vClosed); }
identifier_body
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; impo...
} /** * Derived classes must override. */ vertex(i: number, j: number): Vertex { mustBeInteger('i', i); mustBeInteger('j', j); throw new Error(notSupported('vertex').message); } }
{ const vertex = this.vertices[i]; const u = vertex.coords.getComponent(0); const v = vertex.coords.getComponent(1); transform.exec(vertex, u, v, this.uLength, this.vLength); }
conditional_block
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; impo...
(transform: Transform): void { const iLen = this.vertices.length; for (let i = 0; i < iLen; i++) { const vertex = this.vertices[i]; const u = vertex.coords.getComponent(0); const v = vertex.coords.getComponent(1); transform.exec(vertex, u, v, this.uLength,...
vertexTransform
identifier_name
GridPrimitive.ts
import { mustBeInteger } from '../checks/mustBeInteger'; import { BeginMode } from '../core/BeginMode'; import { notSupported } from '../i18n/notSupported'; import { readOnly } from '../i18n/readOnly'; import { numPostsForFence } from './numPostsForFence'; import { numVerticesForGrid } from './numVerticesForGrid'; impo...
* Derived classes must override. */ vertex(i: number, j: number): Vertex { mustBeInteger('i', i); mustBeInteger('j', j); throw new Error(notSupported('vertex').message); } }
/**
random_line_split
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, Inc. # # 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 applicabl...
# We cannot do /os-services?host=X as cinder returns a hostname of # X@lvm for cinder-volume binary r = s.get('%s/os-services' % VOLUME_ENDPOINT, verify=False, timeout=5) except (exc.ConnectionError, exc.HTTPError, exc.Timeout) as e: metric_bool('client_succes...
random_line_split
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, Inc. # # 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 applicabl...
(auth_ref, args): keystone = get_keystone_client(auth_ref) auth_token = keystone.auth_token VOLUME_ENDPOINT = ( '{protocol}://{hostname}:8776/v1/{tenant}'.format( protocol=args.protocol, hostname=args.hostname, tenant=keystone.tenant_id) ) s = requests.S...
check
identifier_name
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, Inc. # # 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 applicabl...
except (exc.ConnectionError, exc.HTTPError, exc.Timeout) as e: metric_bool('client_success', False, m_name='maas_cinder') status_err(str(e), m_name='maas_cinder') if not r.ok: metric_bool('client_success', False, m_name='maas_cinder') status_err( ...
keystone = get_keystone_client(auth_ref) auth_token = keystone.auth_token VOLUME_ENDPOINT = ( '{protocol}://{hostname}:8776/v1/{tenant}'.format( protocol=args.protocol, hostname=args.hostname, tenant=keystone.tenant_id) ) s = requests.Session() s.header...
identifier_body
cinder_service_check.py
#!/usr/bin/env python # Copyright 2014, Rackspace US, Inc. # # 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 applicabl...
metric_bool(name, service_is_up) else: for service in services: service_is_up = True if service['status'] == 'enabled' and service['state'] != 'up': service_is_up = False name = '%s_on_host_%s' % (service['binary'], service['host']) ...
[host, backend] = service['host'].split('@') name = '%s-%s_status' % (service['binary'], backend)
conditional_block
lib.rs
#![crate_name = "r6"] //! r6.rs is an attempt to implement R6RS Scheme in Rust language #![feature(slice_patterns)] #![feature(io)] // This line should be at the top of the extern link list, // because some weird compiler bug lets log imported from rustc, not crates.io log #[macro_use] extern crate log; #[macro_use]...
pub mod cast; /// Macro implementations pub mod syntax;
random_line_split
sentiment-satisfied-outlined.js
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("circle", {
cy: "9.5", r: "1.5" }), h("circle", { cx: "8.5", cy: "9.5", r: "1.5" }), h("path", { d: "M12 16c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2zm-.01-14C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8...
cx: "15.5",
random_line_split
royal-american.js
var cheerio = require('cheerio') , request = require('request') , url = 'http://theroyalamerican.com/schedule/' , shows = [] , months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Augus...
} shows.push(show) }) done(null, shows) }) } module.exports = royalamerican function normalizeDate(date, year) { var newDate = [] date = date.split(' ') var day = date.pop() if(day.length < 2) day = '0'+day var month = date.pop() month = (months.indexOf(month)+1).toString() if(mont...
url: $$('.details').first().find('a').attr('href'), date: date
random_line_split
royal-american.js
var cheerio = require('cheerio') , request = require('request') , url = 'http://theroyalamerican.com/schedule/' , shows = [] , months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Augus...
price: price, url: $$('.details').first().find('a').attr('href'), date: date } shows.push(show) }) done(null, shows) }) } module.exports = royalamerican function normalizeDate(date, year) { var newDate = [] date = date.split(' ') var day = date.pop() if(day.lengt...
{ request(url, function(err, response, body) { var $ = cheerio.load(body) $('.gig').each(function(i, elem) { var price, time var $$ = cheerio.load(elem) var title = $$('.title').text().trim() if($$('.with').text().trim()) title += $$('.with').text().trim() var date = $$('.date')....
identifier_body
royal-american.js
var cheerio = require('cheerio') , request = require('request') , url = 'http://theroyalamerican.com/schedule/' , shows = [] , months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Augus...
(date, year) { var newDate = [] date = date.split(' ') var day = date.pop() if(day.length < 2) day = '0'+day var month = date.pop() month = (months.indexOf(month)+1).toString() if(month.length < 2) month = '0'+month year = year.split('_')[1] newDate.push(year) newDate.push(month) newDate.push(da...
normalizeDate
identifier_name
index.debug.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueBootfy"] = factory(); else root["Vue...
/******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling h...
{ /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l...
identifier_body
index.debug.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueBootfy"] = factory(); else root["Vue...
(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /*...
__webpack_require__
identifier_name
index.debug.js
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["VueBootfy"] = factory(); else root["Vue...
/******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /****...
/******/ get: getter /******/ }); /******/ } /******/ }; /******/
random_line_split
errors.py
""" The MIT License (MIT) Copyright (c) 2014 Chris Wimbrow Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge...
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN...
random_line_split
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub us...
/// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names); /// /// Ok(()) /// }); /// /// // Even though we returned `Ok`, the transaction wasn't committed. /// let all_names = users.select(name).load::<String>(&conn)?; /// assert_eq!(vec!["Sean", "Tess"], all_names); /// # ...
/// /// let all_names = users.select(name).load::<String>(&conn)?;
random_line_split
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub us...
} } /// Creates a transaction that will never be committed. This is useful for /// tests. Panics if called while inside of a transaction. fn begin_test_transaction(&self) -> QueryResult<()> where Self: Sized, { let transaction_manager = self.transaction_manager(); ...
{ transaction_manager.rollback_transaction(self)?; Err(e) }
conditional_block
mod.rs
//! Types related to database connections mod statement_cache; mod transaction_manager; use std::fmt::Debug; use crate::backend::Backend; use crate::deserialize::FromSqlRow; use crate::expression::QueryMetadata; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::result::*; #[doc(hidden)] pub us...
(&self) -> &dyn std::any::Any { self } } impl<DB: Backend> dyn BoxableConnection<DB> { /// Downcast the current connection to a specific connection /// type. /// /// This will return `None` if the underlying /// connection does not match the corresponding /// type, otherwise a refer...
as_any
identifier_name