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
viewsets.py
from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permis...
serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None):...
random_line_split
viewsets.py
from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permis...
permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES
identifier_body
viewsets.py
from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permis...
(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, r...
export
identifier_name
importnews.py
# -*- coding:utf-8 -*- """ author comger@gmail.com news spider """ import tornado import urllib from kpages import set_default_encoding from pyquery import PyQuery as pyq from tornado import httpclient def main(): url = 'http://taiwan.huanqiu.com/news/' #url = 'http://world.huanqiu.com/observation/' ...
def callback(res): print 'ok' tornado.ioloop.IOLoop.instance().stop() http_client = httpclient.AsyncHTTPClient() http_client.fetch('http://www.sos360.com:8888/news/create',callback,method='POST',body=body) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': set_def...
labels = '测试', ) body = urllib.urlencode(params)
random_line_split
importnews.py
# -*- coding:utf-8 -*- """ author comger@gmail.com news spider """ import tornado import urllib from kpages import set_default_encoding from pyquery import PyQuery as pyq from tornado import httpclient def main(): url = 'http://taiwan.huanqiu.com/news/' #url = 'http://world.huanqiu.com/observation/' ...
default_encoding() main()
conditional_block
importnews.py
# -*- coding:utf-8 -*- """ author comger@gmail.com news spider """ import tornado import urllib from kpages import set_default_encoding from pyquery import PyQuery as pyq from tornado import httpclient def main(): url = 'http://taiwan.huanqiu.com/news/' #url = 'http://world.huanqiu.com/observation/' ...
http_client = httpclient.AsyncHTTPClient() http_client.fetch('http://www.sos360.com:8888/news/create',callback,method='POST',body=body) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': set_default_encoding() main()
t 'ok' tornado.ioloop.IOLoop.instance().stop()
identifier_body
importnews.py
# -*- coding:utf-8 -*- """ author comger@gmail.com news spider """ import tornado import urllib from kpages import set_default_encoding from pyquery import PyQuery as pyq from tornado import httpclient def main(): url = 'http://taiwan.huanqiu.com/news/' #url = 'http://world.huanqiu.com/observation/' ...
(url): doc = pyq(url=url) params = dict( title = doc('h1').text(), author = '52847ffb1a7f5a7d80fd1ff7', category = 'policy', city = '51d28ace931e334378000001', body = doc('#text').html(), labels = '测试', ) body = urllib.urlencode(params) def c...
get_info
identifier_name
util.ts
'path'; import { Readable } from 'stream'; import * as fs from 'fs'; import * as byline from 'byline'; export function log(...args: any[]): void { console.log.apply(console, ['git:', ...args]); } export interface IDisposable { dispose(): void; } export function dispose<T extends IDisposable>(disposables: T[]): T[...
export function done<T>(promise: Promise<T>): Promise<void> { return promise.then<void>(() => void 0); } export function onceEvent<T>(event: Event<T>): Event<T> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { result.dispose(); return listener.call(thisArgs, e); }, null...
{ return (listener, thisArgs = null, disposables?) => { const result = combinedDisposable(events.map(event => event(i => listener.call(thisArgs, i)))); if (disposables) { disposables.push(result); } return result; }; }
identifier_body
util.ts
'path'; import { Readable } from 'stream'; import * as fs from 'fs'; import * as byline from 'byline'; export function log(...args: any[]): void { console.log.apply(console, ['git:', ...args]); } export interface IDisposable { dispose(): void; } export function dispose<T extends IDisposable>(disposables: T[]): T[...
if (b0 === 0xFE && b1 === 0xFF) { return Encoding.UTF16be; } if (b0 === 0xFF && b1 === 0xFE) { return Encoding.UTF16le; } if (buffer.length < 3) { return null; } const b2 = buffer.readUInt8(2); if (b0 === 0xEF && b1 === 0xBB && b2 === 0xBF) { return Encoding.UTF8; } return null; } function isWin...
random_line_split
util.ts
'path'; import { Readable } from 'stream'; import * as fs from 'fs'; import * as byline from 'byline'; export function log(...args: any[]): void { console.log.apply(console, ['git:', ...args]); } export interface IDisposable { dispose(): void; } export function dispose<T extends IDisposable>(disposables: T[]): T[...
}); stream.on('error', (e: Error) => { if (!done) { done = true; error(e); } }); stream.on('close', () => { if (!done) { done = true; complete(buffer.slice(0, bytesRead)); } }); }); } export const enum Encoding { UTF8 = 'utf8', UTF16be = 'utf16be', UTF16le = 'utf16le' } ex...
{ (stream as any).destroy(); // Will trigger the close event eventually }
conditional_block
util.ts
'path'; import { Readable } from 'stream'; import * as fs from 'fs'; import * as byline from 'byline'; export function log(...args: any[]): void { console.log.apply(console, ['git:', ...args]); } export interface IDisposable { dispose(): void; } export function dispose<T extends IDisposable>(disposables: T[]): T[...
<I, O>(event: Event<I>, map: (i: I) => O): Event<O> { return (listener, thisArgs = null, disposables?) => event(i => listener.call(thisArgs, map(i)), null, disposables); } export function filterEvent<T>(event: Event<T>, filter: (e: T) => boolean): Event<T> { return (listener, thisArgs = null, disposables?) => event(...
mapEvent
identifier_name
test_response_whois_biz_status_available.py
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.biz/status_available # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse as t...
def test_nameservers(self): eq_(self.record.nameservers.__class__.__name__, 'list') eq_(self.record.nameservers, []) def test_admin_contacts(self): eq_(self.record.admin_contacts.__class__.__name__, 'list') eq_(self.record.admin_contacts, []) def test_registered(self): ...
eq_(self.record.domain, "u34jedzcq.biz")
identifier_body
test_response_whois_biz_status_available.py
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.biz/status_available # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse as t...
(self): eq_(self.record.domain_id, None) def test_expires_on(self): eq_(self.record.expires_on, None)
test_domain_id
identifier_name
test_response_whois_biz_status_available.py
# This file is autogenerated. Do not edit it manually. # If you want change the content of this file, edit # # spec/fixtures/responses/whois.biz/status_available # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse as ti...
def test_updated_on(self): eq_(self.record.updated_on, None) def test_domain_id(self): eq_(self.record.domain_id, None) def test_expires_on(self): eq_(self.record.expires_on, None)
eq_(self.record.technical_contacts.__class__.__name__, 'list') eq_(self.record.technical_contacts, [])
random_line_split
utils.py
. original_bytes = string.encode('utf-8', 'surrogateescape') return original_bytes.decode('utf-8', 'replace') # Helpers def formataddr(pair, charset='utf-8'): """The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable ...
return address def getaddresses(fieldvalues): """Return a list of (REALNAME, EMAIL) for each fieldvalue.""" all = COMMASPACE.join(fieldvalues) a = _AddressList(all) return a.addresslist ecre = re.compile(r''' =\? # literal =? (?P<charset>[^?]*?) # non-gr...
quotes = '' if specialsre.search(name): quotes = '"' name = escapesre.sub(r'\\\g<0>', name) return '%s%s%s <%s>' % (quotes, name, quotes, address)
conditional_block
utils.py
. original_bytes = string.encode('utf-8', 'surrogateescape') return original_bytes.decode('utf-8', 'replace') # Helpers def formataddr(pair, charset='utf-8'): """The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable ...
(str): """Remove quotes from a string.""" if len(str) > 1: if str.startswith('"') and str.endswith('"'): return str[1:-1].replace('\\\\', '\\').replace('\\"', '"') if str.startswith('<') and str.endswith('>'): return str[1:-1] return str # RFC2231-relate...
unquote
identifier_name
utils.py
. original_bytes = string.encode('utf-8', 'surrogateescape') return original_bytes.decode('utf-8', 'replace') # Helpers def formataddr(pair, charset='utf-8'): """The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable ...
Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead o...
random_line_split
utils.py
. original_bytes = string.encode('utf-8', 'surrogateescape') return original_bytes.decode('utf-8', 'replace') # Helpers def formataddr(pair, charset='utf-8'): """The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable ...
rfc2231_continuation = re.compile(r'^(?P<name>\w+)\*((?P<num>[0-9]+)\*?)?$', re.ASCII) def decode_params(params): """Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). """ # Copy params so we don't mess with the origi...
"""Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. """ s = urllib.parse.quote(s, safe='', encoding=charset or 'ascii') if charset is ...
identifier_body
team_groups_new.py
from __future__ import absolute_import from datetime import timedelta from django.utils import timezone from rest_framework.response import Response from sentry.api.base import Endpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.models import Group, GroupSt...
(self, request, team_id): """ Return a list of the newest groups for a given team. The resulting query will find groups which have been seen since the cutoff date, and then sort those by score, returning the highest scoring groups first. """ team = Team.objects.g...
get
identifier_name
team_groups_new.py
from __future__ import absolute_import from datetime import timedelta from django.utils import timezone from rest_framework.response import Response from sentry.api.base import Endpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.models import Group, GroupSt...
cutoff = timedelta(minutes=minutes) cutoff_dt = timezone.now() - cutoff group_list = list(Group.objects.filter( project__in=project_dict.keys(), status=GroupStatus.UNRESOLVED, active_at__gte=cutoff_dt, ).extra( select={'sort_value': 'score...
""" Return a list of the newest groups for a given team. The resulting query will find groups which have been seen since the cutoff date, and then sort those by score, returning the highest scoring groups first. """ team = Team.objects.get_from_cache( id=team...
identifier_body
team_groups_new.py
from __future__ import absolute_import from datetime import timedelta from django.utils import timezone from rest_framework.response import Response from sentry.api.base import Endpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.models import Group, GroupSt...
return Response(serialize(group_list, request.user))
group._project_cache = project_dict.get(group.project_id)
conditional_block
team_groups_new.py
from __future__ import absolute_import from datetime import timedelta from django.utils import timezone from rest_framework.response import Response from sentry.api.base import Endpoint from sentry.api.permissions import assert_perm from sentry.api.serializers import serialize from sentry.models import Group, GroupSt...
cutoff = timedelta(minutes=minutes) cutoff_dt = timezone.now() - cutoff group_list = list(Group.objects.filter( project__in=project_dict.keys(), status=GroupStatus.UNRESOLVED, active_at__gte=cutoff_dt, ).extra( select={'sort_value': 'scor...
project_list = Project.objects.get_for_user(user=request.user, team=team) project_dict = dict((p.id, p) for p in project_list)
random_line_split
debug.rs
use core::str; use core::sync::atomic::Ordering; use spin::Once; use context; use scheme::*; use sync::WaitQueue; use syscall::flag::EVENT_READ; use syscall::scheme::Scheme; pub static DEBUG_SCHEME_ID: AtomicSchemeId = ATOMIC_SCHEMEID_INIT; /// Input queue static INPUT: Once<WaitQueue<u8>> = Once::new(); /// Initia...
fn dup(&self, _file: usize, _buf: &[u8]) -> Result<usize> { Ok(0) } /// Read the file `number` into the `buffer` /// /// Returns the number of bytes read fn read(&self, _file: usize, buf: &mut [u8]) -> Result<usize> { Ok(INPUT.call_once(init_input).receive_into(buf, true)) ...
{ Ok(0) }
identifier_body
debug.rs
use core::str; use core::sync::atomic::Ordering; use spin::Once; use context; use scheme::*; use sync::WaitQueue; use syscall::flag::EVENT_READ; use syscall::scheme::Scheme; pub static DEBUG_SCHEME_ID: AtomicSchemeId = ATOMIC_SCHEMEID_INIT; /// Input queue static INPUT: Once<WaitQueue<u8>> = Once::new(); /// Initia...
fn read(&self, _file: usize, buf: &mut [u8]) -> Result<usize> { Ok(INPUT.call_once(init_input).receive_into(buf, true)) } /// Write the `buffer` to the `file` /// /// Returns the number of bytes written fn write(&self, _file: usize, buffer: &[u8]) -> Result<usize> { //TODO: Writ...
/// Read the file `number` into the `buffer` /// /// Returns the number of bytes read
random_line_split
debug.rs
use core::str; use core::sync::atomic::Ordering; use spin::Once; use context; use scheme::*; use sync::WaitQueue; use syscall::flag::EVENT_READ; use syscall::scheme::Scheme; pub static DEBUG_SCHEME_ID: AtomicSchemeId = ATOMIC_SCHEMEID_INIT; /// Input queue static INPUT: Once<WaitQueue<u8>> = Once::new(); /// Initia...
(b: u8) { let len = INPUT.call_once(init_input).send(b); context::event::trigger(DEBUG_SCHEME_ID.load(Ordering::SeqCst), 0, EVENT_READ, len); } pub struct DebugScheme; impl DebugScheme { pub fn new(scheme_id: SchemeId) -> DebugScheme { DEBUG_SCHEME_ID.store(scheme_id, Ordering::SeqCst); D...
debug_input
identifier_name
graphicsRequestBroker.py
#! /usr/bin/env python """ ############################################################################## ## ## ## @Name : graphicsRequestBroker.py ## ## ## @author : Nicholas Lemay ## ## @since : 2007-06-28, last updated on 2008-04-23 ## ## ## @license : MetPX Copyright (C) 2004-2006 Environment Canada ## ...
else:#other reply = "images=;error=" + _("Cannot execute query.Unknown plotter.Plotter was %s") %plotter returnToQueriersLocationWithReply( querier , reply ) #---------------------------------------------------- except Exception,inst: #---------------- reply = "images=;er...
queryBroker.getParametersFromForm( form ) error = queryBroker.searchForParameterErrors() if error == "" : queryBroker.prepareQuery( ) queryBroker.executeQuery( ) reply = queryBroker.getReplyToSendToquerier() returnToQueriersLocationWithReply( quer...
conditional_block
graphicsRequestBroker.py
#! /usr/bin/env python """ ############################################################################## ## ## ## @Name : graphicsRequestBroker.py ## ## ## @author : Nicholas Lemay ## ## @since : 2007-06-28, last updated on 2008-04-23 ## ## ## @license : MetPX Copyright (C) 2004-2006 Environment Canada ## ...
def handlePlotRequest( form, language ): """ @param form: form wich contains the parameters to use for the query. @param language : language of the querier. @precondition: global _ translator m...
""" @param form : Form with whom this programm was called. @return : Returns the queriers location. """ try: querier = form["querier"] except: querier = "" return querier
identifier_body
graphicsRequestBroker.py
#! /usr/bin/env python """ ############################################################################## ## ## ## @Name : graphicsRequestBroker.py ## ## ## @author : Nicholas Lemay ## ## @since : 2007-06-28, last updated on 2008-04-23 ## ## ## @license : MetPX Copyright (C) 2004-2006 Environment Canada ## ...
returnToQueriersLocationWithReply( querier , reply ) else: #An error was located within the call. queryBroker.replyParameters.error = error reply = queryBroker.getReplyToSendToquerier() returnToQueriersLocationWithReply( querier , reply ) els...
reply = queryBroker.getReplyToSendToquerier()
random_line_split
graphicsRequestBroker.py
#! /usr/bin/env python """ ############################################################################## ## ## ## @Name : graphicsRequestBroker.py ## ## ## @author : Nicholas Lemay ## ## @since : 2007-06-28, last updated on 2008-04-23 ## ## ## @license : MetPX Copyright (C) 2004-2006 Environment Canada ## ...
( form ): """ @param form : Form with whom this programm was called. @return : Returns the plotter type. """ #---------------------------------------------------------------------- try: if ( form["preDeterminedSpan"] == _("daily") ) : plotter = "gnuplot"...
getPlotterType
identifier_name
Square.js
import React, { Component, PropTypes } from 'react'; import { Text, View, StyleSheet, TouchableWithoutFeedback } from 'react-native'; export default class Board extends Component { static propTypes = { size: PropTypes.number.isRequired, showNotation: PropTypes.bool, rowIndex: PropTypes.number.isRequired,...
else if (inCheck) { backgroundColor = '#C51B16'; } return ( <TouchableWithoutFeedback onPress={this.onSelected} disabled={!canMoveHere} > <View style={[ styles.container, { backgroundColor, width: size, ...
{ backgroundColor = '#CDD26B'; }
conditional_block
Square.js
import React, { Component, PropTypes } from 'react'; import { Text, View, StyleSheet, TouchableWithoutFeedback } from 'react-native'; export default class Board extends Component { static propTypes = { size: PropTypes.number.isRequired, showNotation: PropTypes.bool, rowIndex: PropTypes.number.isRequired,...
() { const { size, rowIndex, columnIndex, selected, lastMove, inCheck, canMoveHere, } = this.props; const isBlack = (rowIndex + columnIndex) % 2 === 0; let backgroundColor = isBlack ? '#F0D9B5' : '#B58863'; if (selected) { backgroundColor = '#656E41';...
render
identifier_name
Square.js
import React, { Component, PropTypes } from 'react'; import { Text, View, StyleSheet, TouchableWithoutFeedback } from 'react-native'; export default class Board extends Component { static propTypes = { size: PropTypes.number.isRequired, showNotation: PropTypes.bool, rowIndex: PropTypes.number.isRequired,...
key={'row_notations'} style={[ styles.notation, { color: isBlack ? '#B58863' : '#F0D9B5', top: 0, right: 0, transform, }, ]} > {dimension - rowIndex} ...
{ const { showNotation, rowIndex, columnIndex, columnName, dimension, reverseBoard, } = this.props; const notations = []; const transform = [ { rotate: reverseBoard ? '180deg' : '0deg', }, ]; if (showNotation) { if (columnIndex + 1 =...
identifier_body
Square.js
import React, { Component, PropTypes } from 'react'; import { Text, View, StyleSheet, TouchableWithoutFeedback } from 'react-native'; export default class Board extends Component { static propTypes = { size: PropTypes.number.isRequired, showNotation: PropTypes.bool, rowIndex: PropTypes.number.isRequired,...
// verify if square is update before authorize new renderer shouldComponentUpdate(nextProps, nextState) { // check props dependencies square renderer const {selected, lastMove, canMoveHere, inCheck, reverseBoard} = nextProps; return ( selected !== this.props.selected || lastMove !== this....
}
random_line_split
stats.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() { assert!(Histogram::new(slice_into![], 1).is_none()); } }
none_when_too_few_data
identifier_name
stats.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
counts[bucket] += 1; corpus_i += 1; } // Initialized to size bucket_number + 1 above; iterates up to bucket_number; subscript is in range; qed bucket_bounds[bucket + 1] = bucket_end; bucket_end = bucket_end + bucket_size; } Some(Histogram { bucket_bounds: bucket_bounds, counts: counts }) } } ...
{ if corpus.len() < 1 { return None; } let corpus_end = corpus.last().expect("there is at least 1 element; qed").clone(); let corpus_start = corpus.first().expect("there is at least 1 element; qed").clone(); trace!(target: "stats", "Computing histogram from {} to {} with {} buckets.", corpus_start, corpus_end, ...
identifier_body
stats.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
let corpus_end = corpus.last().expect("there is at least 1 element; qed").clone(); let corpus_start = corpus.first().expect("there is at least 1 element; qed").clone(); trace!(target: "stats", "Computing histogram from {} to {} with {} buckets.", corpus_start, corpus_end, bucket_number); // Bucket needs to be ...
{ return None; }
conditional_block
stats.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
); } #[test] fn data_range_is_not_multiple_of_bucket_range() { assert_eq!( Histogram::new(slice_into![1, 2, 5], 2), Some(Histogram { bucket_bounds: vec_into![1, 4, 7], counts: vec![2, 1] }) ); } #[test] fn data_range_is_multiple_of_bucket_range() { assert_eq!( Histogram::new(slice_into![1, 2, 6...
fn smaller_data_range_than_bucket_range() { assert_eq!( Histogram::new(slice_into![1, 2, 2], 3), Some(Histogram { bucket_bounds: vec_into![1, 2, 3, 4], counts: vec![1, 2, 0] })
random_line_split
glfw_windowing.rs
QuitWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent}; use windowing::RefreshWindowEvent; use windowing::{Forward, Back}; use alert::{Alert, AlertMethods}; use extra::time::Timespec; use extra::time; use std::libc::c_int; use std::local_data; use geom::point::Point2D; use geom::si...
Loading => { self.glfw_window.set_title("Loading — Servo") } PerformingLayout => { self.glfw_window.set_title("Performing Layout — Servo") } FinishedLoading => { match self.render_state { Rend...
}
random_line_split
glfw_windowing.rs
QuitWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent}; use windowing::RefreshWindowEvent; use windowing::{Forward, Back}; use alert::{Alert, AlertMethods}; use extra::time::Timespec; use extra::time; use std::libc::c_int; use std::local_data; use geom::point::Point2D; use geom::si...
self.last_title_set_time = now; match self.ready_state { Blank => { self.glfw_window.set_title("blank — Servo") } Loading => { self.glfw_window.set_title("Loading — Servo") } PerformingLayout => { ...
{ return }
conditional_block
glfw_windowing.rs
QuitWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent}; use windowing::RefreshWindowEvent; use windowing::{Forward, Back}; use alert::{Alert, AlertMethods}; use extra::time::Timespec; use extra::time; use std::libc::c_int; use std::local_data; use geom::point::Point2D; use geom::si...
{ glfw_window: glfw::Window, event_queue: @mut ~[WindowEvent], drag_origin: Point2D<c_int>, mouse_down_button: @mut Option<glfw::MouseButton>, mouse_down_point: @mut Point2D<c_int>, ready_state: ReadyState, render_state: RenderState, last_title_set_time: Timespec, } impl WindowMet...
Window
identifier_name
glfw_windowing.rs
QuitWindowEvent, MouseWindowClickEvent, MouseWindowMouseDownEvent, MouseWindowMouseUpEvent}; use windowing::RefreshWindowEvent; use windowing::{Forward, Back}; use alert::{Alert, AlertMethods}; use extra::time::Timespec; use extra::time; use std::libc::c_int; use std::local_data; use geom::point::Point2D; use geom::si...
/// Sets the ready state. fn set_ready_state(@mut self, ready_state: ReadyState) { self.ready_state = ready_state; self.update_window_title() } /// Sets the render state. fn set_render_state(@mut self, render_state: RenderState) { if self.ready_state == FinishedLoading && ...
{ if !self.event_queue.is_empty() { return self.event_queue.shift() } glfw::poll_events(); if self.glfw_window.should_close() { QuitWindowEvent } else if !self.event_queue.is_empty() { self.event_queue.shift() } else { Idle...
identifier_body
dto.rs
use game_status::PlayerName; use card::Card; use card::Suit; use card::dto::CardDto; use deal::Deal; use deal::DealCard; use error::Error; use error::Result; use std::convert::TryFrom; use std::str::FromStr; #[derive(Serialize, Deserialize, Debug)] pub struct DealDto { #[serde(rename = "DealNumber")] deal_num...
impl TryFrom<DealCardDto> for DealCard { type Error = Error; fn try_from(dto: DealCardDto) -> Result<DealCard> { Ok(DealCard { player_name: dto.team_name.clone(), card: Card::try_from(dto.card)?, }) } } impl<'a> From<&'a DealCard> for DealCardDto { fn from(deal_c...
card: CardDto, }
random_line_split
dto.rs
use game_status::PlayerName; use card::Card; use card::Suit; use card::dto::CardDto; use deal::Deal; use deal::DealCard; use error::Error; use error::Result; use std::convert::TryFrom; use std::str::FromStr; #[derive(Serialize, Deserialize, Debug)] pub struct DealDto { #[serde(rename = "DealNumber")] deal_num...
(dto: DealDto) -> Result<Deal> { let deal_cards = dto.deal_cards .into_iter() .map(DealCard::try_from) .collect::<Result<Vec<DealCard>>>()?; let suit = Suit::from_str(&dto.suit_type)?; Ok(Deal { deal_number: dto.deal_number, initiator: ...
try_from
identifier_name
dto.rs
use game_status::PlayerName; use card::Card; use card::Suit; use card::dto::CardDto; use deal::Deal; use deal::DealCard; use error::Error; use error::Result; use std::convert::TryFrom; use std::str::FromStr; #[derive(Serialize, Deserialize, Debug)] pub struct DealDto { #[serde(rename = "DealNumber")] deal_num...
} #[derive(Serialize, Deserialize, Debug)] pub struct DealCardDto { #[serde(rename = "TeamName")] team_name: PlayerName, #[serde(rename = "Card")] card: CardDto, } impl TryFrom<DealCardDto> for DealCard { type Error = Error; fn try_from(dto: DealCardDto) -> Result<DealCard> { Ok(DealC...
{ DealDto { deal_number: deal.deal_number, initiator: deal.initiator.clone(), suit_type: deal.suit.unwrap_or(Suit::Club).into(), deal_cards: deal.deal_cards.iter().map(DealCardDto::from).collect(), deal_winner: deal.deal_winner.clone(), } }
identifier_body
dto.rs
use game_status::PlayerName; use card::Card; use card::Suit; use card::dto::CardDto; use deal::Deal; use deal::DealCard; use error::Error; use error::Result; use std::convert::TryFrom; use std::str::FromStr; #[derive(Serialize, Deserialize, Debug)] pub struct DealDto { #[serde(rename = "DealNumber")] deal_num...
, deal_cards: deal_cards, deal_winner: dto.deal_winner, }) } } impl<'a> From<&'a Deal> for DealDto { fn from(deal: &'a Deal) -> DealDto { DealDto { deal_number: deal.deal_number, initiator: deal.initiator.clone(), suit_type: deal.suit....
{ Some(suit) }
conditional_block
mod.rs
pub mod specialized; pub mod term; // Miscellaneous types required by queries go here // Enums /// Minimum should match - used in numerous queries /// TODO: should go somewhere specific #[derive(Debug)] pub struct CombinationMinimumShouldMatch { first: MinimumShouldMatch, second: MinimumShouldMatch, } impl ...
{ Auto, LevenshteinDistance(i64), Proportionate(f64), } from!(i64, Fuzziness, LevenshteinDistance); from!(f64, Fuzziness, Proportionate); impl Serialize for Fuzziness { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { use self::Fuzziness:...
Fuzziness
identifier_name
mod.rs
Can't convert {:?} to String", self), } } } impl Serialize for MinimumShouldMatch { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { MinimumShouldMatch::Integer(val) => val.serialize(serializer), Minimum...
impl Query { pub fn build_match_all() -> MatchAllQuery { MatchAllQuery::default() }
random_line_split
form_group_name.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core...
} } export const formArrayNameProvider: any = { provide: ControlContainer, useExisting: forwardRef(() => FormArrayName) }; /** * Syncs an existing form array to a DOM element. * * This directive can only be used as a child of {@link FormGroupDirective}. * * ```typescript * @Component({ * selector: 'my...
{ ReactiveErrors.groupParentException(); }
conditional_block
form_group_name.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core...
(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); } private _checkParentType(): void { if (_hasInvalidParent(this._parent)) { ReactiveErrors.arrayParentException(); } } } function _hasInvalidParent(parent: ControlContainer): boolean { return !(parent instanceof FormGroup...
asyncValidator
identifier_name
form_group_name.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core...
/** @internal */ _checkParentType(): void { if (_hasInvalidParent(this._parent)) { ReactiveErrors.groupParentException(); } } } export const formArrayNameProvider: any = { provide: ControlContainer, useExisting: forwardRef(() => FormArrayName) }; /** * Syncs an existing form array to a DOM ...
{ super(); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; }
identifier_body
form_group_name.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core...
constructor( @Optional() @Host() @SkipSelf() parent: ControlContainer, @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { super(); this._parent = parent; this._validators = validators; this._asyncV...
@Directive({selector: '[formGroupName]', providers: [formGroupNameProvider]}) export class FormGroupName extends AbstractFormGroupDirective implements OnInit, OnDestroy { @Input('formGroupName') name: string;
random_line_split
creatPredictdata.py
import glob import os
class CTD(object): """docstring for CTD""" def __init__(self): self.format_l = [] self.td_l = [] self.iternum = 0 self.formatname = "" def feature(self,index): format_l = self.format_l feature = ((float(format_l[index+1][1])-float(format_l[index+3][1]))/float...
import pandas as pd
random_line_split
creatPredictdata.py
import glob import os import pandas as pd class
(object): """docstring for CTD""" def __init__(self): self.format_l = [] self.td_l = [] self.iternum = 0 self.formatname = "" def feature(self,index): format_l = self.format_l feature = ((float(format_l[index+1][1])-float(format_l[index+3][1]))/float(format_l...
CTD
identifier_name
creatPredictdata.py
import glob import os import pandas as pd class CTD(object): """docstring for CTD""" def __init__(self): self.format_l = [] self.td_l = [] self.iternum = 0 self.formatname = "" def feature(self,index): format_l = self.format_l feature = ((float(format_l[inde...
def main(): ctd = CTD() ctd.run() if __name__ == '__main__' : main()
print(index) self.format_l = [] self.td_l = [] self.format(path) self.trainData() path = path.split('/') pathname = path[2] self.storage_txt(pathname) print os.popen("./bin/svm-scale -s predict_scale_model ./predict/data/...
conditional_block
creatPredictdata.py
import glob import os import pandas as pd class CTD(object): """docstring for CTD""" def __init__(self): self.format_l = [] self.td_l = [] self.iternum = 0 self.formatname = "" def feature(self,index): format_l = self.format_l feature = ((float(format_l[inde...
def storage_csv(self): rowname=['classify','feature','1-open','1-high','1-low','1-close','1-volume','1-adj close','2-open','2-high','2-low','2-close','2-volume','2-adj close','3-open','3-high','3-low','3-close','3-volume','3-adj close'] df = pd.DataFrame(self.td_l,columns=rowname) with ope...
for index in range(self.iternum): try: format_l = self.format_l classify = (float(format_l[index][3])-float(format_l[index+1][3]))/float(format_l[index+1][3])*100 feature = self.feature(index) a = ['0']+format_l[index+1]+format...
identifier_body
settings.py
# -*- coding: utf-8 -*- import sys, xbmc, xbmcaddon sys.argv[0] = 'plugin.video.filmix.net.dev'#PLUGIN_ID import os, xbmcup.app, xbmcup.system, xbmcup.db, xbmcup.gui from core.defines import * from core.auth import Auth import core.cover # log = open(xbmcup.system.fs('sandbox://myprog.log').decode('utf-8'), "a") #...
Auth().reset_auth(True) show_message(32004) openAddonSettings(PLUGIN_ID, 1, 0) if(sys.argv[1] == 'apply_list_settings'): clear_cache_db() show_message(32005) openAddonSettings(PLUGIN_ID, 1, 0)
show_message(32003) openAddonSettings(PLUGIN_ID, 1, 0) if(sys.argv[1] == 'logout'):
random_line_split
settings.py
# -*- coding: utf-8 -*- import sys, xbmc, xbmcaddon sys.argv[0] = 'plugin.video.filmix.net.dev'#PLUGIN_ID import os, xbmcup.app, xbmcup.system, xbmcup.db, xbmcup.gui from core.defines import * from core.auth import Auth import core.cover # log = open(xbmcup.system.fs('sandbox://myprog.log').decode('utf-8'), "a") #...
if(sys.argv[1] == 'apply_list_settings'): clear_cache_db() show_message(32005) openAddonSettings(PLUGIN_ID, 1, 0)
Auth().reset_auth(True) show_message(32004) openAddonSettings(PLUGIN_ID, 1, 0)
conditional_block
settings.py
# -*- coding: utf-8 -*- import sys, xbmc, xbmcaddon sys.argv[0] = 'plugin.video.filmix.net.dev'#PLUGIN_ID import os, xbmcup.app, xbmcup.system, xbmcup.db, xbmcup.gui from core.defines import * from core.auth import Auth import core.cover # log = open(xbmcup.system.fs('sandbox://myprog.log').decode('utf-8'), "a") #...
(addonId, id1=None, id2=None): xbmc.executebuiltin('Addon.OpenSettings(%s)' % addonId) if id1 != None: xbmc.executebuiltin('SetFocus(%i)' % (id1 + 200)) if id2 != None: xbmc.executebuiltin('SetFocus(%i)' % (id2 + 100)) if(sys.argv[1] == 'clear_cache'): clear_cache_db() show_message(...
openAddonSettings
identifier_name
settings.py
# -*- coding: utf-8 -*- import sys, xbmc, xbmcaddon sys.argv[0] = 'plugin.video.filmix.net.dev'#PLUGIN_ID import os, xbmcup.app, xbmcup.system, xbmcup.db, xbmcup.gui from core.defines import * from core.auth import Auth import core.cover # log = open(xbmcup.system.fs('sandbox://myprog.log').decode('utf-8'), "a") #...
def show_message(key): xbmcup.gui.message( xbmcup.app.lang[key].encode('utf-8') ) def openAddonSettings(addonId, id1=None, id2=None): xbmc.executebuiltin('Addon.OpenSettings(%s)' % addonId) if id1 != None: xbmc.executebuiltin('SetFocus(%i)' % (id1 + 200)) if id2 != None: xbmc.execut...
CACHE = xbmcup.db.Cache(xbmcup.system.fs('sandbox://'+CACHE_DATABASE)) CACHE.flush() SQL = xbmcup.db.SQL(xbmcup.system.fs('sandbox://'+CACHE_DATABASE)) try: SQL.set('DELETE FROM search') except: pass
identifier_body
subreddits.py
import os, sys, re, json from praw2 import Reddit reload(sys) try: from xbmc import log except: def log(msg): print(msg) sys.setdefaultencoding("utf-8") CLIENT_ID = 'J_0zNv7dXM1n3Q' CLIENT_SECRET = 'sfiPkzKDd8LZl3Ie1WLAvpCICH4' USER_AGENT = 'sparkle streams 1.0' class SubRedditEvents(object): as...
@staticmethod def collapse(entries): """ Collapse oure list of acestream entries to pick only one with the best quality text """ results = [] prev = None # Sort the entries by our priority logic, then iterate for entry in sorted(entries, key=lamb...
return (entry, 2)
conditional_block
subreddits.py
import os, sys, re, json from praw2 import Reddit reload(sys) try: from xbmc import log except: def log(msg): print(msg) sys.setdefaultencoding("utf-8") CLIENT_ID = 'J_0zNv7dXM1n3Q' CLIENT_SECRET = 'sfiPkzKDd8LZl3Ie1WLAvpCICH4' USER_AGENT = 'sparkle streams 1.0' class SubRedditEvents(object): as...
@staticmethod def priority(entry): """ For cases where we have multiple entries for the same acestream link, prioritize based on the quality text to get the best text possible """ if not entry[0]: return (entry, 3) elif re.search('.*\[.*\].*', entry[...
""" For each acestream link, return a tuple of acestream link, and link quality """ links = [] for entry in body.split('\n'): res = re.findall('(.*)(acestream://[a-z0-9]+)\s*(.*)', entry) if res: pre, acelink, post = res[0] ...
identifier_body
subreddits.py
import os, sys, re, json from praw2 import Reddit reload(sys) try:
except: def log(msg): print(msg) sys.setdefaultencoding("utf-8") CLIENT_ID = 'J_0zNv7dXM1n3Q' CLIENT_SECRET = 'sfiPkzKDd8LZl3Ie1WLAvpCICH4' USER_AGENT = 'sparkle streams 1.0' class SubRedditEvents(object): as_regex_str = r'(acestream://[^$\s]+)' def __init__(self, username=None, password=None, c...
from xbmc import log
random_line_split
subreddits.py
import os, sys, re, json from praw2 import Reddit reload(sys) try: from xbmc import log except: def log(msg): print(msg) sys.setdefaultencoding("utf-8") CLIENT_ID = 'J_0zNv7dXM1n3Q' CLIENT_SECRET = 'sfiPkzKDd8LZl3Ie1WLAvpCICH4' USER_AGENT = 'sparkle streams 1.0' class SubRedditEvents(object): as...
(entry): """ For cases where we have multiple entries for the same acestream link, prioritize based on the quality text to get the best text possible """ if not entry[0]: return (entry, 3) elif re.search('.*\[.*\].*', entry[0]): return (entry, 1) ...
priority
identifier_name
stratus_detach_volume.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Created as part of the StratusLab project (http://stratuslab.eu), # co-funded by the European Commission under the Grant Agreement # INFSO-RI-261552." # # Copyright (c) 2011, Centre National de la Recherche Scientifique (CNRS) # # Licensed under the Apache License, Vers...
(self): super(MainProgram, self).__init__() def parse(self): self.parser.usage = '%prog [options] volume-uuid ...' self.parser.description = ''' Detach one or more persistent volumes (disks) that were dynamically attached to a running virtual machine. The volume-uuid arguments are the uniq...
__init__
identifier_name
stratus_detach_volume.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Created as part of the StratusLab project (http://stratuslab.eu), # co-funded by the European Commission under the Grant Agreement # INFSO-RI-261552." # # Copyright (c) 2011, Centre National de la Recherche Scientifique (CNRS) # # Licensed under the Apache License, Vers...
from stratuslab.ConfigHolder import ConfigHolder from stratuslab.Authn import AuthnFactory from stratuslab.Exceptions import OneException # initialize console logging import stratuslab.api.LogUtil as LogUtil LogUtil.get_console_logger() class MainProgram(AuthnCommand, StorageCommand): """A command-line program ...
from stratuslab.CloudConnectorFactory import CloudConnectorFactory from stratuslab.Util import printError from stratuslab.commandbase.StorageCommand import StorageCommand from stratuslab.volume_manager.volume_manager_factory import VolumeManagerFactory
random_line_split
stratus_detach_volume.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Created as part of the StratusLab project (http://stratuslab.eu), # co-funded by the European Commission under the Grant Agreement # INFSO-RI-261552." # # Copyright (c) 2011, Centre National de la Recherche Scientifique (CNRS) # # Licensed under the Apache License, Vers...
def checkOptions(self): super(MainProgram, self).checkOptions() if not self.uuids: printError('Please provide at least one persistent disk UUID to detach') if self.options.instance < 0: printError('Please provide a VM ID on which to detach disk') try: ...
self.parser.usage = '%prog [options] volume-uuid ...' self.parser.description = ''' Detach one or more persistent volumes (disks) that were dynamically attached to a running virtual machine. The volume-uuid arguments are the unique identifiers of volumes to detach. ''' self.parser.add_option('-i', '--...
identifier_body
stratus_detach_volume.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Created as part of the StratusLab project (http://stratuslab.eu), # co-funded by the European Commission under the Grant Agreement # INFSO-RI-261552." # # Copyright (c) 2011, Centre National de la Recherche Scientifique (CNRS) # # Licensed under the Apache License, Vers...
try: self._retrieveVmNode() except OneException, e: printError(e) def _retrieveVmNode(self): credentials = AuthnFactory.getCredentials(self.options) self.options.cloud = CloudConnectorFactory.getCloud(credentials) self.options.cloud.setEndpoint(self....
printError('Please provide a VM ID on which to detach disk')
conditional_block
lib.rs
//! A crate to custom derive `Position` and `Advance` for any type that has a field named `vector` extern crate proc_macro; use crate::proc_macro::TokenStream; use quote::quote; use syn; #[proc_macro_derive(Advance)] pub fn advance_derive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::pars...
let name = &ast.ident; let gen = quote! { impl Position for #name { fn x(&self) -> f32 { self.vector.position.x } fn y(&self) -> f32 { self.vector.position.y } fn x_mut(&mut self) -> &mut f32 { &mut self.vector.position.x } fn y_mut(&mut self) -> &mut f32...
random_line_split
lib.rs
//! A crate to custom derive `Position` and `Advance` for any type that has a field named `vector` extern crate proc_macro; use crate::proc_macro::TokenStream; use quote::quote; use syn; #[proc_macro_derive(Advance)] pub fn advance_derive(input: TokenStream) -> TokenStream
#[proc_macro_derive(Position)] pub fn position_derive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; let gen = quote! { impl Position for #name { fn x(&self) -> f32 { self.vector.position.x } fn y(&self) ...
{ let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; let gen = quote! { impl Advance for #name { fn direction(&self) -> f32 { self.vector.direction } fn direction_mut(&mut self) -> &mut f32 { &mut self....
identifier_body
lib.rs
//! A crate to custom derive `Position` and `Advance` for any type that has a field named `vector` extern crate proc_macro; use crate::proc_macro::TokenStream; use quote::quote; use syn; #[proc_macro_derive(Advance)] pub fn advance_derive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::pars...
(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; let gen = quote! { impl Position for #name { fn x(&self) -> f32 { self.vector.position.x } fn y(&self) -> f32 { self.vector.position.y } fn x_mut(...
position_derive
identifier_name
component.d.ts
// Type definitions for ag-grid v4.1.5 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ceolter/> // Definitions: https://github.com/borisyankov/DefinitelyTyped import { IEventEmitter } from "../interfaces/iEventEmitter"; export declare class
implements IEventEmitter { private eGui; private destroyFunctions; private localEventService; private childComponents; constructor(template?: string); setTemplate(template: string): void; addEventListener(eventType: string, listener: Function): void; removeEventListener(eventType: strin...
Component
identifier_name
component.d.ts
// Type definitions for ag-grid v4.1.5 // Project: http://www.ag-grid.com/
// Definitions: https://github.com/borisyankov/DefinitelyTyped import { IEventEmitter } from "../interfaces/iEventEmitter"; export declare class Component implements IEventEmitter { private eGui; private destroyFunctions; private localEventService; private childComponents; constructor(template?: str...
// Definitions by: Niall Crosby <https://github.com/ceolter/>
random_line_split
missing-doc.rs
#![warn(clippy::missing_docs_in_private_items)] // When denying at the crate level, be sure to not get random warnings from the // injected intrinsics by the compiler. #![allow(dead_code)] #![feature(global_asm)] //! Some garbage docs for the crate here #![doc = "More garbage"] type Typedef = String; pub type PubTyped...
enum Baz { BazA { a: isize, b: isize }, BarB, } pub enum PubBaz { PubBazA { a: isize }, } /// dox pub enum PubBaz2 { /// dox PubBaz2A { /// dox a: isize, }, } #[allow(clippy::missing_docs_in_private_items)] pub enum PubBaz3 { PubBaz3A { b: isize }, } #[doc(hidden)] pub fn...
} }
random_line_split
missing-doc.rs
#![warn(clippy::missing_docs_in_private_items)] // When denying at the crate level, be sure to not get random warnings from the // injected intrinsics by the compiler. #![allow(dead_code)] #![feature(global_asm)] //! Some garbage docs for the crate here #![doc = "More garbage"] type Typedef = String; pub type PubTyped...
{ /// dox PubBaz2A { /// dox a: isize, }, } #[allow(clippy::missing_docs_in_private_items)] pub enum PubBaz3 { PubBaz3A { b: isize }, } #[doc(hidden)] pub fn baz() {} const FOO: u32 = 0; /// dox pub const FOO1: u32 = 0; #[allow(clippy::missing_docs_in_private_items)] pub const FOO2: ...
PubBaz2
identifier_name
capability_list.rs
// Copyright (c) 2017 David Renshaw and contributors // // 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...
marker: PhantomData<T>, reader: ListReader<'a> } impl <'a, T> Clone for Reader<'a, T> where T: FromClientHook { fn clone(&self) -> Reader<'a, T> { Reader { marker : self.marker, reader : self.reader } } } impl <'a, T> Copy for Reader<'a, T> where T: FromClientHook {} impl <'a, T> Reader<'a, T>...
type Builder = Builder<'a, T>; } pub struct Reader<'a, T> where T: FromClientHook {
random_line_split
capability_list.rs
// Copyright (c) 2017 David Renshaw and contributors // // 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...
pub fn len(&self) -> u32 { self.reader.len() } pub fn iter(self) -> ListIter<Reader<'a, T>, Result<T>> { ListIter::new(self, self.len()) } } impl <'a, T> Reader<'a, T> where T: FromClientHook { pub fn reborrow<'b>(&'b self) -> Reader<'b, T> { Reader { reader: self.reader, marker: P...
{ Reader::<'b, T> { reader : reader, marker : PhantomData } }
identifier_body
capability_list.rs
// Copyright (c) 2017 David Renshaw and contributors // // 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...
(builder : ListBuilder<'a>) -> Builder<'a, T> { Builder { builder: builder, marker: PhantomData } } pub fn len(&self) -> u32 { self.builder.len() } #[deprecated(since="0.9.2", note="use into_reader()")] pub fn as_reader(self) -> Reader<'a, T> { self.into_reader() } pub fn into...
new
identifier_name
mod.rs
// SPDX-License-Identifier: Unlicense mod device; mod handler; mod pager; const UPPER_VA_BITS: usize = 39; // 512 GB, avoids 1 level const LOWER_VA_BITS: usize = 48; // 256 TB /// Live hardware abstraction layer for integration tests and releases. #[cfg(not(test))] mod hal; /// Mock hardware abstraction layer for u...
pub use hal_test::core_id; pub use pager::PageBlockDescriptor; pub use pager::PageDirectory; #[cfg(test)] mod tests { use super::*; #[test] fn test_use() { assert_eq!(LOWER_VA_BITS, 48) } }
#[cfg(not(test))] pub use hal::core_id; #[cfg(test)]
random_line_split
mod.rs
// SPDX-License-Identifier: Unlicense mod device; mod handler; mod pager; const UPPER_VA_BITS: usize = 39; // 512 GB, avoids 1 level const LOWER_VA_BITS: usize = 48; // 256 TB /// Live hardware abstraction layer for integration tests and releases. #[cfg(not(test))] mod hal; /// Mock hardware abstraction layer for u...
() -> impl super::PageDirectory { pager::new_page_directory() } #[cfg(not(test))] pub use hal::core_id; #[cfg(test)] pub use hal_test::core_id; pub use pager::PageBlockDescriptor; pub use pager::PageDirectory; #[cfg(test)] mod tests { use super::*; #[test] fn test_use() { assert_eq!(LOWER_V...
new_page_directory
identifier_name
Main.ts
/// <reference path="common.d.ts" /> import common from "./Common"; let app = { Init: function () { //art dialog配置 (function (config) { config.lock = true; config.opacity = 0.2; config.resize = true; config.path = `${XCLCMSPageGlobalConfig.RootURL}R...
window.alert = art.dialog.alert; //init common.Init(); } }; export default app;
}); //重写全局的alert
random_line_split
config.local.js
const path = require('path'); const ip = require('ip'); module.exports = app => { const exports = {}; exports.view = { cache: false }; exports.static = { maxAge: 0 // maxAge 缓存,默认 1 年 }; exports.development = { watchDirs: [], // 指定监视的目录(包括子目录),当目录下的文件变化的时候自动重载应用,路径从项目根目录开始写 ignoreDirs: ['...
const localIP = ip.address(); const domainWhiteList = []; [7001, 9000, 9001].forEach(port => { domainWhiteList.push(`http://localhost:${port}`); domainWhiteList.push(`http://127.0.0.1:${port}`); domainWhiteList.push(`http://${localIP}:${port}`); }); exports.security = { domainWhiteList }; retu...
};
random_line_split
slicks-multiparts.js
/*** * Created by steve Samson <stevee.samson@gmail.com> on 2/16/14. */ var Busboy = require('busboy'), path = require('path'), os = require('os'), qs = require('querystring') fs = require('fs'); module.exports = function (options) { options = options || {}; return function (req, res, next) ...
return decodeChunks(); } var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { var saveTo = options.uploadDir ? path.join(BASE_DIR, options.uploadDir, path.basenam...
{ return next(); }
conditional_block
slicks-multiparts.js
/*** * Created by steve Samson <stevee.samson@gmail.com> on 2/16/14. */ var Busboy = require('busboy'), path = require('path'), os = require('os'), qs = require('querystring') fs = require('fs'); module.exports = function (options) { options = options || {}; return function (req, res, next) ...
}); busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated) { body[fieldname] = val; }); busboy.on('finish', function () { req.body = utils.extend(req.body || {}, body); req.files = files; next(); }); ...
};
random_line_split
type-params-in-different-spaces-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
std::io::println(A::test((&7306634593706211700, 8))); }
fn main() {
random_line_split
type-params-in-different-spaces-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<U>(u: U) -> Self { Tr::op(u) //~ ERROR expected Tr<U>, but found Tr<T> } } impl<T> Tr<T> for T { fn op(t: T) -> T { t } } impl<T> A for T {} fn main() { std::io::println(A::test((&7306634593706211700, 8))); }
test
identifier_name
type-params-in-different-spaces-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl<T> A for T {} fn main() { std::io::println(A::test((&7306634593706211700, 8))); }
{ t }
identifier_body
config.rs
pub use crate::tracker::TrackerMode; use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize)] pub struct UDPConfig { bind_address: String, announce_interval: u32, } impl UDPConfig { pub fn get_address(&self) -> &str { self.bind_address.as_str() } pub fn get_announce_i...
(&self) -> &Option<String> { &self.log_level } pub fn get_http_config(&self) -> Option<&HTTPConfig> { self.http.as_ref() } pub fn get_db_path(&self) -> &Option<String> { &self.db_path } pub fn get_cleanup_interval(&self) -> Option<u64> { self.cleanup_interval ...
get_log_level
identifier_name
config.rs
pub use crate::tracker::TrackerMode; use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize)] pub struct UDPConfig { bind_address: String, announce_interval: u32, } impl UDPConfig { pub fn get_address(&self) -> &str { self.bind_address.as_str() } pub fn get_announce_i...
} #[derive(Deserialize)] pub struct HTTPConfig { bind_address: String, access_tokens: HashMap<String, String>, } impl HTTPConfig { pub fn get_address(&self) -> &str { self.bind_address.as_str() } pub fn get_access_tokens(&self) -> &HashMap<String, String> { &self.access_tokens ...
}
random_line_split
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2019 Budget Insight # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the ...
return self.browser.iter_documents(subscription) def get_document(self, _id): subid = _id.rsplit('_', 1)[0] subscription = self.get_subscription(subid) return find_object(self.iter_documents(subscription), id=_id, error=DocumentNotFound) def download_document(self, document): ...
cription = self.get_subscription(subscription)
conditional_block
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2019 Budget Insight # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the ...
def iter_subscription(self): return self.browser.iter_subscriptions() def get_subscription(self, _id): return find_object(self.iter_subscription(), id=_id, error=SubscriptionNotFound) def iter_documents(self, subscription): if not isinstance(subscription, Subscription): s...
rn self.create_browser(self.config['login'].get(), self.config['password'].get(), self.config['lastname'].get())
identifier_body
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2019 Budget Insight # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the ...
f, document): if not isinstance(document, Document): document = self.get_document(document) return self.browser.download_document(document)
load_document(sel
identifier_name
module.py
# -*- coding: utf-8 -*- # Copyright(C) 2019 Budget Insight # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the ...
from weboob.capabilities.base import find_object from weboob.capabilities.bill import CapDocument, Document, SubscriptionNotFound, Subscription, DocumentNotFound from weboob.tools.value import Value, ValueBackendPassword from .browser import BouyguesBrowser __all__ = ['BouyguesModule'] class BouyguesModule(Module,...
random_line_split
jwplayer.utils.mediaparser.js
/** * Parser for the JW Player. * * @author zach * @version 5.4 */ (function(jwplayer) { jwplayer.utils.mediaparser = function() {}; var elementAttributes = { element: { width: 'width', height: 'height', id: 'id', 'class': 'className', name: 'name' }, media: { src: 'file', preload...
} }; parsers.media = parseMediaElement; parsers.audio = parseMediaElement; parsers.source = parseSourceElement; parsers.video = parseVideoElement; })(jwplayer);
random_line_split
jwplayer.utils.mediaparser.js
/** * Parser for the JW Player. * * @author zach * @version 5.4 */ (function(jwplayer) { jwplayer.utils.mediaparser = function() {}; var elementAttributes = { element: { width: 'width', height: 'height', id: 'id', 'class': 'className', name: 'name' }, media: { src: 'file', preload...
(elementType, attributes) { if (attributes === undefined) { attributes = elementAttributes[elementType]; } else { jwplayer.utils.extend(attributes, elementAttributes[elementType]); } return attributes; } function parseElement(domElement, attributes) { if (parsers[domElement.tagName.toLowerCase()] &&...
getAttributeList
identifier_name
jwplayer.utils.mediaparser.js
/** * Parser for the JW Player. * * @author zach * @version 5.4 */ (function(jwplayer) { jwplayer.utils.mediaparser = function() {}; var elementAttributes = { element: { width: 'width', height: 'height', id: 'id', 'class': 'className', name: 'name' }, media: { src: 'file', preload...
function parseVideoElement(domElement, attributes) { attributes = getAttributeList('video', attributes); var result = parseMediaElement(domElement, attributes); return result; } /** For IE browsers, replacing a media element's contents isn't possible, since only the start tag * is matched by document.g...
{ attributes = getAttributeList('source', attributes); var result = parseElement(domElement, attributes); result.width = result.width ? result.width : 0; result.bitrate = result.bitrate ? result.bitrate : 0; return result; }
identifier_body
jwplayer.utils.mediaparser.js
/** * Parser for the JW Player. * * @author zach * @version 5.4 */ (function(jwplayer) { jwplayer.utils.mediaparser = function() {}; var elementAttributes = { element: { width: 'width', height: 'height', id: 'id', 'class': 'className', name: 'name' }, media: { src: 'file', preload...
} // TODO: This is not required to fix [ticket:1094], but we may want to do it anyway // jwplayer.utils.setOuterHTML(toReplace, html); toReplace.outerHTML = html; } }; parsers.media = parseMediaElement; parsers.audio = parseMediaElement; parsers.source = parseSourceElement; parsers.video = par...
{ var element = siblings.pop(); element.parentNode.removeChild(element); }
conditional_block
execution_server.rs
use std::collections::VecDeque; use std::fmt::Debug; use std::iter::FromIterator; use std::ops::Deref; use std::sync::{Arc, Mutex}; use bazel_protos; use grpcio; use protobuf; #[derive(Clone, Debug)] pub struct MockExecution { name: String, execute_request: bazel_protos::remote_execution::ExecuteRequest, operat...
None => { sink.fail(grpcio::RpcStatus::new( grpcio::RpcStatusCode::InvalidArgument, Some("Did not expect this request".to_string()), )); } } } } impl bazel_protos::remote_execution_grpc::Execution for MockResponder { fn execute( &self, _: grpcio::RpcCont...
{ sink.success(op.clone()); }
conditional_block
execution_server.rs
use std::collections::VecDeque; use std::fmt::Debug; use std::iter::FromIterator; use std::ops::Deref; use std::sync::{Arc, Mutex}; use bazel_protos; use grpcio; use protobuf; #[derive(Clone, Debug)] pub struct MockExecution { name: String, execute_request: bazel_protos::remote_execution::ExecuteRequest, operat...
(mock_execution: MockExecution) -> TestServer { let mock_responder = MockResponder::new(mock_execution); let env = Arc::new(grpcio::Environment::new(1)); let mut server_transport = grpcio::ServerBuilder::new(env) .register_service(bazel_protos::remote_execution_grpc::create_execution( mock_re...
new
identifier_name
execution_server.rs
use std::collections::VecDeque; use std::fmt::Debug; use std::iter::FromIterator; use std::ops::Deref;
#[derive(Clone, Debug)] pub struct MockExecution { name: String, execute_request: bazel_protos::remote_execution::ExecuteRequest, operation_responses: Arc<Mutex<VecDeque<bazel_protos::operations::Operation>>>, } impl MockExecution { /// /// # Arguments: /// * `name` - The name of the operation. It is ass...
use std::sync::{Arc, Mutex}; use bazel_protos; use grpcio; use protobuf;
random_line_split
order.service.ts
/* Importing core module */ import {Injectable} from 'angular2/core'; import {Response} from 'angular2/http'; import {Observable} from 'rxjs/Observable'; import {HttpClient} from './http-client.service'; /* Importing model */ import {OrderModel} from '../model/order.model'; i...
* Make the following request to the server: [GET][/orders/:id]: fetch all order's details */ getOrderDetails (id) { return this._httpClient.get(this._actionUrl + id) .map(res => <OrderDetailsModel> res.json().order) .catch(this.handleError); } ...
.map(res => <OrderModel[]> res.json().order) .catch(this.handleError); } /**
random_line_split