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
lrslayer.py
# -*- coding: utf-8 -*- """ /*************************************************************************** LrsPlugin A QGIS plugin Linear reference system builder and editor ------------------- begin : 2017-5-29 copyright ...
self, progressFunction=None): #debug("load %s %s" % (self.layer.name(), self.routeFieldName)) self.reset() if not self.routeFieldName: return total = self.layer.featureCount() count = 0 for feature in self.layer.getFeatures(): # sleep(1) # progres...
oad(
identifier_name
lrslayer.py
# -*- coding: utf-8 -*- """ /*************************************************************************** LrsPlugin A QGIS plugin Linear reference system builder and editor ------------------- begin : 2017-5-29 copyright ...
f not self.layer or not self.routeFieldName: return [] ids = set() for feature in self.layer.getFeatures(): ids.add(feature[self.routeFieldName]) ids = list(ids) ids.sort() return ids
identifier_body
lrslayer.py
# -*- coding: utf-8 -*- """ /*************************************************************************** LrsPlugin A QGIS plugin Linear reference system builder and editor ------------------- begin : 2017-5-29 copyright ...
def getRouteIds(self): #debug("getRouteIds routeFieldName = %s" % self.routeFieldName) if not self.layer or not self.routeFieldName: return [] ids = set() for feature in self.layer.getFeatures(): ids.add(feature[self.routeFieldName]) ids = list(ids) ...
self.routes[normalId] = LrsLayerRoute(routeId, parallelMode='error') return self.routes[normalId]
random_line_split
websockets.py
import json from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from .base import Binding from ..generic.websockets import WebsocketDemultiplexer from ..sessions import enforce_ordering class WebsocketBinding(Binding): """ Websocket-specific outgoing binding subcla...
data = super(WebsocketBindingWithMembers, self).serialize_data(instance) member_data = {} for m in self.send_members: member = instance for s in m.split('.'): member = getattr(member, s) if callable(member): member_data[m.replace('.', '...
identifier_body
websockets.py
import json from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from .base import Binding from ..generic.websockets import WebsocketDemultiplexer from ..sessions import enforce_ordering class WebsocketBinding(Binding): """ Websocket-specific outgoing binding subcla...
(self, instance, action): payload = { "action": action, "pk": instance.pk, "data": self.serialize_data(instance), "model": self.model_label, } return payload def serialize_data(self, instance): """ Serializes model data into JS...
serialize
identifier_name
websockets.py
import json from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from .base import Binding from ..generic.websockets import WebsocketDemultiplexer from ..sessions import enforce_ordering class WebsocketBinding(Binding): """ Websocket-specific outgoing binding subcla...
if callable(member): member_data[m.replace('.', '__')] = member() else: member_data[m.replace('.', '__')] = member member_data = json.loads(self.encoder.encode(member_data)) # the update never overwrites any value from data, # because an o...
member = getattr(member, s)
conditional_block
websockets.py
import json from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from .base import Binding from ..generic.websockets import WebsocketDemultiplexer from ..sessions import enforce_ordering class WebsocketBinding(Binding): """ Websocket-specific outgoing binding subcla...
return WebsocketDemultiplexer.encode(stream, payload) def serialize(self, instance, action): payload = { "action": action, "pk": instance.pk, "data": self.serialize_data(instance), "model": self.model_label, } return payload def s...
def encode(cls, stream, payload):
random_line_split
event.js
import Ember from 'ember'; import DS from 'ember-data'; const secondsInDay = 86400; const days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', ]; export default DS.Model.extend(Ember.Copyable, { temp: DS.attr('number', { defaultValue: 18, }), // Seconds since...
() { return days[this.get('day')]; }, set(key, dayLabel) { this.set('day', days.indexOf(dayLabel)); return dayLabel; }, }), secondsToday: Ember.computed('seconds', 'day', { get() { const dayOffset = this.get('day') * secondsInDay; const secondsToday = this.get('se...
get
identifier_name
event.js
import Ember from 'ember'; import DS from 'ember-data'; const secondsInDay = 86400; const days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', ]; export default DS.Model.extend(Ember.Copyable, { temp: DS.attr('number', { defaultValue: 18, }), // Seconds since...
const newDayOffset = day * secondsInDay; const oldDayOffset = this.get('day') * secondsInDay; const secondsRemaining = this.get('seconds') - oldDayOffset; this.set('seconds', newDayOffset + secondsRemaining); return day; }, }), dayLabel: Ember.computed('day', { get...
{ day += days.length; }
conditional_block
event.js
import Ember from 'ember'; import DS from 'ember-data'; const secondsInDay = 86400; const days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', ]; export default DS.Model.extend(Ember.Copyable, { temp: DS.attr('number', { defaultValue: 18, }), // Seconds since...
, set(key, time) { const duration = moment.duration(time); this.set('secondsToday', duration.asSeconds()); return time; }, }), copy() { return this.store.createRecord('event', { temp: this.get('temp'), seconds: this.get('seconds'), }); } });
{ const time = moment({ hours: 0 }).seconds(this.get('secondsToday')); return time.format('HH:mm'); }
identifier_body
event.js
import Ember from 'ember'; import DS from 'ember-data'; const secondsInDay = 86400; const days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', ]; export default DS.Model.extend(Ember.Copyable, { temp: DS.attr('number', { defaultValue: 18, }), // Seconds since...
});
random_line_split
active_object.rs
acode.org/wiki/Active_object #![feature(std_misc)] extern crate time; extern crate num; extern crate schedule_recv; use num::traits::Zero; use num::Float; use std::f64::consts::PI; use std::sync::{Arc, Mutex}; use std::time::duration::Duration; use std::thread::{self, spawn}; use std::sync::mpsc::{channel, Sender, Se...
// Rust supports both shared-memory and actor models of concurrency, and the Integrator utilizes // both. We use a Sender (actor model) to send the Integrator new functions, while we use a Mutex // (shared-memory concurrency) to hold the result of the integration. // // Note that these are not the only options here--...
random_line_split
active_object.rs
acode.org/wiki/Active_object #![feature(std_misc)] extern crate time; extern crate num; extern crate schedule_recv; use num::traits::Zero; use num::Float; use std::f64::consts::PI; use std::sync::{Arc, Mutex}; use std::time::duration::Duration; use std::thread::{self, spawn}; use std::sync::mpsc::{channel, Sender, Se...
// Rust, timers can yield Receivers that are periodically notified with an empty // message (where the period is the frequency). This is useful because it lets us wait // on either a tick or another type of message (in this case, a request to change the // function we ar...
{ // We create a pipe allowing functions to be sent from tx (the sending end) to input (the // receiving end). In order to change the function we are integrating from the task in // which the Integrator lives, we simply send the function through tx. let (tx, input) = channel(); ...
identifier_body
active_object.rs
ode.org/wiki/Active_object #![feature(std_misc)] extern crate time; extern crate num; extern crate schedule_recv; use num::traits::Zero; use num::Float; use std::f64::consts::PI; use std::sync::{Arc, Mutex}; use std::time::duration::Duration; use std::thread::{self, spawn}; use std::sync::mpsc::{channel, Sender, Send...
() -> f64 { let object = Integrator::new(10); object.input(Box::new(|t: u32| { let f = 1. / Duration::seconds(2).num_milliseconds() as f64; (2. * PI * f * t as f64).sin() })).ok().expect("Failed to set input"); thread::sleep_ms(2000); object.input(Box::new(|_| 0.)).ok().expect("Faile...
integrate
identifier_name
munge.ts
/** * Turn a list of plain-text files into a single JSON document. */ let fs = require('fs'); let path = require('path'); const FRONT_MATTER_MARKER = /---\n/; const KEY_VALUE_PAIR = /(\w+): (.*)$/; function read_string(filename: string) { let data = fs.readFileSync(filename); return data.toString(); }
let index = s.search(FRONT_MATTER_MARKER); if (index === -1) { return ['', s.trim()]; } else { let back = s.slice(index); let nlindex = back.indexOf("\n"); if (nlindex != -1) { back = back.slice(nlindex); } return [s.slice(0, index).trim(), back.trim()]; } } type StringMap = { [ k...
function split_front_matter(s: string): [string, string] {
random_line_split
munge.ts
/** * Turn a list of plain-text files into a single JSON document. */ let fs = require('fs'); let path = require('path'); const FRONT_MATTER_MARKER = /---\n/; const KEY_VALUE_PAIR = /(\w+): (.*)$/; function read_string(filename: string) { let data = fs.readFileSync(filename); return data.toString(); } functio...
return [s.slice(0, index).trim(), back.trim()]; } } type StringMap = { [ key: string]: string }; function parse_front_matter(s: string): StringMap { let out: StringMap = {}; for (let line of s.split(/\n/)) { let res = line.match(KEY_VALUE_PAIR); if (res) { out[res[1]] = res[2]; } } ret...
{ back = back.slice(nlindex); }
conditional_block
munge.ts
/** * Turn a list of plain-text files into a single JSON document. */ let fs = require('fs'); let path = require('path'); const FRONT_MATTER_MARKER = /---\n/; const KEY_VALUE_PAIR = /(\w+): (.*)$/; function read_string(filename: string) { let data = fs.readFileSync(filename); return data.toString(); } functio...
(s: string): [string, string] { let index = s.search(FRONT_MATTER_MARKER); if (index === -1) { return ['', s.trim()]; } else { let back = s.slice(index); let nlindex = back.indexOf("\n"); if (nlindex != -1) { back = back.slice(nlindex); } return [s.slice(0, index).trim(), back.trim()...
split_front_matter
identifier_name
munge.ts
/** * Turn a list of plain-text files into a single JSON document. */ let fs = require('fs'); let path = require('path'); const FRONT_MATTER_MARKER = /---\n/; const KEY_VALUE_PAIR = /(\w+): (.*)$/; function read_string(filename: string) { let data = fs.readFileSync(filename); return data.toString(); } functio...
main();
{ let args = process.argv.slice(2); let out: StringMap[] = []; for (let fn of args) { let s = read_string(fn); let [front, back] = split_front_matter(s); let values = parse_front_matter(front); values['body'] = back; values['name'] = path.basename(fn).split('.')[0]; out.push(values); } ...
identifier_body
MicroBlogPost.tsx
import * as React from 'react'; import { MicroPost } from 'src/microblog/type/MicroPost'; import MicroblogForm from 'src/components/molecules/MicroblogForm'; import { connect } from 'react-redux'; import { GlobalStore } from 'src/type/GlobalStore'; import { Dispatch } from 'redux'; import { deletePost, editPost, reply...
<span className="MicroBlogPost__Author__Created">{post.Created}</span> </div> {showTitle && <div className="MicroBlogPost__Title">{post.Title}</div>} <div className="MicroBlogPost__Content"><ReactMarkdown escapeHtml={false} source={post.Content}></Reac...
<button className="MicroBlogPost__VoteArrow" onClick={() => votePost ? votePost(post.ID, -1) : null}>⇩</button> </div> <div className="MicroBlogPost__Post"> <div className="MicroBlogPost__Author"> <strong className="MicroBlogPost__Author__Name"...
random_line_split
MicroBlogPost.tsx
import * as React from 'react'; import { MicroPost } from 'src/microblog/type/MicroPost'; import MicroblogForm from 'src/components/molecules/MicroblogForm'; import { connect } from 'react-redux'; import { GlobalStore } from 'src/type/GlobalStore'; import { Dispatch } from 'redux'; import { deletePost, editPost, reply...
} return ( <div className={post.ID == editId ? "MicroBlogPost MicroBlogPost--edited" : "MicroBlogPost"}> <div className="MicroBlogPost__Profile"> <span className="MicroBlogPost__Avatar"></span> <button className="MicroBlogPost__VoteArrow" onClick={() => vote...
{ onDelete ? onDelete(post.ID) : null; }
conditional_block
sw.js
var CACHE_NAME = 'morpheus'; var CACHED_FILES = [ 'css/morpheus-latest.min.css', 'fonts/FontAwesome.otf', 'fonts/fontawesome-webfont.eot', 'fonts/fontawesome-webfont.svg', 'fonts/fontawesome-webfont.ttf', 'fonts/fontawesome-webfont.woff', 'fonts/fontawesome-webfont.woff2', 'js/morpheus-external-latest.min.js', ...
else { return fetch(event.request).then(function (response) { return response; }); } }).catch(function (error) { // This catch() will handle exceptions that arise from the match() or fetch() operations. // Note that a HTTP error response (e.g. 404) will NOT trigger an exception. // I...
{ // try to get an updated version return fetch(event.request.clone()).then(function (response) { cache.put(event.request, response.clone()); return response; }).catch(function () { return cachedResponse; }) }
conditional_block
sw.js
var CACHE_NAME = 'morpheus'; var CACHED_FILES = [ 'css/morpheus-latest.min.css', 'fonts/FontAwesome.otf', 'fonts/fontawesome-webfont.eot', 'fonts/fontawesome-webfont.svg', 'fonts/fontawesome-webfont.ttf', 'fonts/fontawesome-webfont.woff', 'fonts/fontawesome-webfont.woff2', 'js/morpheus-external-latest.min.js', ...
}) ); });
random_line_split
auth-guard.service.ts
// ============================= // Email: info@ebenmonney.com // www.ebenmonney.com/templates // ============================= import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild, CanLoad, Route } from '@angular/router'; import { Auth...
this.authService.loginRedirectUrl = url; this.router.navigate(['/login']); return false; } }
{ return true; }
conditional_block
auth-guard.service.ts
// ============================= // Email: info@ebenmonney.com // www.ebenmonney.com/templates // ============================= import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild, CanLoad, Route } from '@angular/router'; import { Auth...
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { const url: string = state.url; return this.checkLogin(url); } canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return this.canActivate(route, state); } canLoad(route: Route)...
{ }
identifier_body
auth-guard.service.ts
// ============================= // Email: info@ebenmonney.com // www.ebenmonney.com/templates // ============================= import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild, CanLoad, Route } from '@angular/router'; import { Auth...
(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return this.canActivate(route, state); } canLoad(route: Route): boolean { const url = `/${route.path}`; return this.checkLogin(url); } checkLogin(url: string): boolean { if (this.authService.isLoggedIn) { return tru...
canActivateChild
identifier_name
auth-guard.service.ts
// ============================= // Email: info@ebenmonney.com // www.ebenmonney.com/templates // ============================= import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild, CanLoad, Route } from '@angular/router'; import { Auth...
return false; } }
} this.authService.loginRedirectUrl = url; this.router.navigate(['/login']);
random_line_split
session.js
(function(w, undefined) { var lifetime = 1800, //in seconds
domain = undefined, secure = undefined, sid = 'JSSESSID'; /** * Check for a PHPSESSID. If found unpack it from the cookie * If not found, create it then pack everything in $_SESSION * into a cookie. */ w.session_start = function() { var cookie = w.getcookie(sid); if(!cookie || cookie == "n...
path = undefined,
random_line_split
session.js
(function(w, undefined) { var lifetime = 1800, //in seconds path = undefined, domain = undefined, secure = undefined, sid = 'JSSESSID'; /** * Check for a PHPSESSID. If found unpack it from the cookie * If not found, create it then pack everything in $_SESSION * into a cookie. */ w.session_...
var r = [name + '=' + w.urlencode(value)], s = {}, i = ''; s = {expires: expires, path: path, domain: domain}; for (i in s) { if (s.hasOwnProperty(i)) { // Exclude items on Object.prototype s[i] && r.push(i + '=' + s[i]); } } return secure && r.push('secure'), w.document.cookie = r....
{ expires = (new Date((new Date).getTime() + expires * 3600)).toGMTString(); }
conditional_block
helperFunctions.js
// checks if the URL is the user's profile page // 'thisPath' = the requested url path following the protocol and hostname function isProfilePage(thisPath) { let userProfileLocation = '/user'; let bool = undefined; thisPath === userProfileLocation ? bool = true : bool = false; return bool; } // checks if the...
export { isProfilePage, isExerciseDetailPage, isWorkoutLogPage };
random_line_split
helperFunctions.js
// checks if the URL is the user's profile page // 'thisPath' = the requested url path following the protocol and hostname function isProfilePage(thisPath)
// checks if the URL is the the page to display an exercise's history // 'thisPath' = the requested url path following the protocol and hostname function isExerciseDetailPage(thisPath) { let exerciseDetailLocation = '/exercise/detail'; let bool = undefined; // remove the exerciseID from the path requested le...
{ let userProfileLocation = '/user'; let bool = undefined; thisPath === userProfileLocation ? bool = true : bool = false; return bool; }
identifier_body
helperFunctions.js
// checks if the URL is the user's profile page // 'thisPath' = the requested url path following the protocol and hostname function isProfilePage(thisPath) { let userProfileLocation = '/user'; let bool = undefined; thisPath === userProfileLocation ? bool = true : bool = false; return bool; } // checks if the...
(thisPath) { let exerciseDetailLocation = '/exercise/detail'; let bool = undefined; // remove the exerciseID from the path requested let pathArray = thisPath.split('/'); pathArray.pop(); let path = pathArray.join('/'); path === exerciseDetailLocation ? bool = true : bool = false; return bool; } // c...
isExerciseDetailPage
identifier_name
camera.js
/** * controls what is shown on the canvas * @class Camera */ var Camera = Shade.extend({ /** * @member {string} Camera.prototype.name - the unique name necessary for proto's inheritance */ _protosName: 'camera', _zoom: 1, /** * @member {boolean} Camera.prototype.scrolling - use to ...
});
player.y(0); } else if (player.y() + player.height() > this.height()) { player.y(this.height() - player.height()); } }
random_line_split
camera.js
/** * controls what is shown on the canvas * @class Camera */ var Camera = Shade.extend({ /** * @member {string} Camera.prototype.name - the unique name necessary for proto's inheritance */ _protosName: 'camera', _zoom: 1, /** * @member {boolean} Camera.prototype.scrolling - use to ...
if (trigger.vx() > 0 && trigger.x() + trigger.width() > regions.right && base.x() > this.width() - base.width()) { this.vx( (trigger.vx()) ); } if (trigger.vy() < 0 && trigger.y() < regions.top && base.y() < 0) { this...
{ this.vx( (trigger.vx()) ); }
conditional_block
temp.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 12 22:25:38 2017 @author: sitibanc """ import math import numpy as np def entropy(p1, n1): # postive, negative if p1 == 0 and n1 == 0: return 1 value = 0 pp = p1 / (p1 + n1) pn = n1 / (p1 + n1) if pp > 0: ...
def buildDT(feature, target, positive, negative): ### node structure (dictionary) # node.leaf = 0/1 # node.selectf = feature index # node.threshold = some value (regards feature value) # node.child = index of childs (leaft, right) ### # root node node = dict() node['data'] ...
total = p1 + n1 + p2 + n2 s1 = p1 + n1 s2 = p2 + n2 return entropy(p1 + p2, n1 + n2) - s1 / total * entropy(p1, n1) - s2 / total * entropy(p2, n2)
identifier_body
temp.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 12 22:25:38 2017 @author: sitibanc """ import math import numpy as np def entropy(p1, n1): # postive, negative if p1 == 0 and n1 == 0: return 1 value = 0 pp = p1 / (p1 + n1) pn = n1 / (p1 + n1) if pp > 0: ...
node = dict() node['data'] = range(len(target)) Tree = []; Tree.append(node) t = 0 while(t<len(Tree)): idx = Tree[t]['data'] if(sum(target[idx])==0): print(idx) Tree[t]['leaf']=1 Tree[t]['decision']=0 elif(sum(target[idx])==len(idx)): ...
['decision'] = positive else: tree[i]['decision'] = negative i += 1 return tree data = np.loadtxt('PlayTennis.txt',usecols=range(5),dtype=int) feature = data[:,0:4] target = data[:,4]-1 def DT(feature, target):
conditional_block
temp.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 12 22:25:38 2017 @author: sitibanc """ import math import numpy as np def
(p1, n1): # postive, negative if p1 == 0 and n1 == 0: return 1 value = 0 pp = p1 / (p1 + n1) pn = n1 / (p1 + n1) if pp > 0: value -= pp * math.log2(pp) if pn > 0: value -= pn * math.log2(pn) return value def infoGain(p1, n1, p2, n2): total = p1 + n1 + p2 +...
entropy
identifier_name
temp.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 12 22:25:38 2017 @author: sitibanc """ import math import numpy as np def entropy(p1, n1): # postive, negative if p1 == 0 and n1 == 0: return 1 value = 0 pp = p1 / (p1 + n1) pn = n1 / (p1 + n1) if pp > 0: ...
Tree[t]['decision']=1 else: bestIG = 0 for i in range(feature.shape[1]): pool = list(set(feature[idx,i])) for j in range(len(pool)-1): thres = (pool[j]+pool[j+1])/2 G1 = [] G2 = [] ...
print(idx) Tree[t]['leaf']=1
random_line_split
nav.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { TranslateService } from 'ng2-translate/ng2-translate'; import * as _ from 'lodash';
import { Language } from '../models'; @Component({ selector: 'yt-nav', templateUrl: 'nav.component.html', styleUrls: [ 'nav.component.scss' ] }) export class NavComponent implements OnInit { siteLangs: Language[]; constructor( public authService: AuthService, private translateService: TranslateServ...
import { AuthService } from '../auth.service';
random_line_split
nav.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { TranslateService } from 'ng2-translate/ng2-translate'; import * as _ from 'lodash'; import { AuthService } from '../auth.service'; import { Language } from '../models'; @Component({ selector: 'yt-nav', t...
() { this.route.data.forEach((data: { siteLanguages: Language[] }) => { this.siteLangs = data.siteLanguages; }); } logout() { this.authService.logout(true); } changeLanguage(code: string) { // TODO: do a better global check for site languages here if (_.chain(this.siteLangs).map('cod...
ngOnInit
identifier_name
nav.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { TranslateService } from 'ng2-translate/ng2-translate'; import * as _ from 'lodash'; import { AuthService } from '../auth.service'; import { Language } from '../models'; @Component({ selector: 'yt-nav', t...
} }
{ localStorage.setItem('siteLang', code); this.translateService.use(code); }
conditional_block
nav.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { TranslateService } from 'ng2-translate/ng2-translate'; import * as _ from 'lodash'; import { AuthService } from '../auth.service'; import { Language } from '../models'; @Component({ selector: 'yt-nav', t...
changeLanguage(code: string) { // TODO: do a better global check for site languages here if (_.chain(this.siteLangs).map('code').includes(code).value()) { localStorage.setItem('siteLang', code); this.translateService.use(code); } } }
{ this.authService.logout(true); }
identifier_body
android-devices.test.ts
/* 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 false }) // androidDevice.on(messageType.outputError, event => { // debug('OUTPUT_ERROR:', event) // }) // androidDevice.on(messageType.outputLog, event => { // debug('OUTPUT_LOG:', event) // }) await androidDevice.run({ id: firstDevice.id, applicationId:...
{ firstDevice = info return true }
conditional_block
android-devices.test.ts
/* 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...
import { messageType } from '@weex-cli/utils/lib/process/process.js' jest.setTimeout(90000) import AndroidDevice from './android-devices' describe('Test android', () => { const androidDevice = new AndroidDevice() const deviceList = androidDevice.getList() debug('deviceList', deviceList) // TODO mock test(...
const path = require('path') const debug = require('debug')('device') import 'jest'
random_line_split
application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat...
//= require wishlists //= require base //= require reverse_geocoder // =require current_location //= require mapper //= require map_bounds //= require map
//= require airports
random_line_split
typedstring.d.ts
declare module goog.string$ { /** * Wrapper for strings that conform to a data type or language. * * Implementations of this interface are wrappers for strings, and typically * associate a type contract with the wrapped string. Concrete implementations * of this interface may choose to im...
* implements this interface. All implementations of this interface set this * property to {@code true}. * @type {boolean} */ implementsGoogStringTypedString: boolean; /** * Retrieves this wrapped string's value. * @return {!string} The wrap...
random_line_split
tcp.rs
use traits::*; use rotor::mio::tcp::TcpStream as MioTcpStream; use rotor::mio::tcp::Shutdown; use netbuf::Buf; use std::io; pub struct TcpStream { stream: MioTcpStream, read_buffer: Buf, } impl Transport for TcpStream { type Buffer = MioTcpStream; /// Returns a buffer object that will write data to t...
}
{ debug!("writable tcp stream"); }
identifier_body
tcp.rs
use traits::*; use rotor::mio::tcp::TcpStream as MioTcpStream; use rotor::mio::tcp::Shutdown; use netbuf::Buf; use std::io; pub struct TcpStream { stream: MioTcpStream, read_buffer: Buf, } impl Transport for TcpStream { type Buffer = MioTcpStream; /// Returns a buffer object that will write data to t...
, _ => { return Err(e) }, } }, } } } /// Tells transport that "bytes" number of bytes have been read fn consume(&mut self, bytes: usize) { self.read_buffer.consume(byt...
{}
conditional_block
tcp.rs
use traits::*; use rotor::mio::tcp::TcpStream as MioTcpStream; use rotor::mio::tcp::Shutdown; use netbuf::Buf; use std::io; pub struct TcpStream { stream: MioTcpStream, read_buffer: Buf, } impl Transport for TcpStream { type Buffer = MioTcpStream; /// Returns a buffer object that will write data to t...
fn read(&mut self) -> io::Result<&[u8]> { use std::io::ErrorKind::*; let stream = &mut self.stream; let buf = &mut self.read_buffer; loop { match buf.read_from(stream) { Ok(_) => {}, Err(e) => { match e.kind() { ...
random_line_split
tcp.rs
use traits::*; use rotor::mio::tcp::TcpStream as MioTcpStream; use rotor::mio::tcp::Shutdown; use netbuf::Buf; use std::io; pub struct
{ stream: MioTcpStream, read_buffer: Buf, } impl Transport for TcpStream { type Buffer = MioTcpStream; /// Returns a buffer object that will write data to the underlying socket. This is used by the /// Codecs in order to efficiently write data without copying. fn buffer(&mut self) -> &mut Sel...
TcpStream
identifier_name
qrcode.d.ts
//--------------------------------------------------------------------- // // QR Code Generator for JavaScript - TypeScript Declaration File // // Copyright (c) 2016 Kazuhiko Arase // // URL: http://www.d-project.com/ // // Licensed under the MIT license: // http://www.opensource.org/licenses/mit-license.php // // The...
isDark(row: number, col: number) : boolean; createImgTag(cellSize?: number, margin?: number) : string; createSvgTag(cellSize?: number, margin?: number) : string; createDataURL(cellSize?: number, margin?: number) : string; createTableTag(cellSize?: number, margin?: number) : string; createASCII(cellSize?: nu...
interface QRCode { addData(data: string, mode?: Mode) : void; make() : void; getModuleCount() : number;
random_line_split
15.4.4.17-3-22.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright an...
{ var callbackfnAccessed = false; var toStringAccessed = false; var valueOfAccessed = false; function callbackfn(val, idx, obj) { callbackfnAccessed = true; return val > 10; } var obj = { 0: 11, 1: 12, lengt...
stcase()
identifier_name
15.4.4.17-3-22.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright an...
}, toString: function () { toStringAccessed = true; return {}; } } }; try { Array.prototype.some.call(obj, callbackfn); return false; } catch (ex) { return (ex...
return {};
random_line_split
15.4.4.17-3-22.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright an...
toStringAccessed = true; return {}; } } }; try { Array.prototype.some.call(obj, callbackfn); return false; } catch (ex) { return (ex instanceof TypeError) && toStringAccessed && valueOfAccess...
var callbackfnAccessed = false; var toStringAccessed = false; var valueOfAccessed = false; function callbackfn(val, idx, obj) { callbackfnAccessed = true; return val > 10; } var obj = { 0: 11, 1: 12, length: ...
identifier_body
cov.py
from bacpypes.apdu import SubscribeCOVRequest, SimpleAckPDU, RejectPDU, AbortPDU from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.pdu import Address from bacpypes.object import get_object_class, get_datatype from bacpypes.constructeddata import Array from bacpypes.primitivedata import Tag...
(self, address, objectID, confirmed=None, lifetime=None, callback=None): self.address = address self.subscriberProcessIdentifier = SubscriptionContext.next_proc_id SubscriptionContext.next_proc_id += 1 self.monitoredObjectIdentifier = objectID self.issueConfirmedNotifications = c...
__init__
identifier_name
cov.py
from bacpypes.apdu import SubscribeCOVRequest, SimpleAckPDU, RejectPDU, AbortPDU from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.pdu import Address from bacpypes.object import get_object_class, get_datatype from bacpypes.constructeddata import Array from bacpypes.primitivedata import Tag...
def subscription_acknowledged(self, iocb): if iocb.ioResponse: self._log.info("Subscription success") if iocb.ioError: self._log.error("Subscription failed. {}".format(iocb.ioError)) def cov(self, address, objectID, confirmed=True, lifetime=0, callback=None): ...
self._log.debug("Request : {}".format(request)) iocb = IOCB(request) self._log.debug("IOCB : {}".format(iocb)) iocb.add_callback(self.subscription_acknowledged) # pass to the BACnet stack deferred(self.this_application.request_io, iocb)
identifier_body
cov.py
from bacpypes.apdu import SubscribeCOVRequest, SimpleAckPDU, RejectPDU, AbortPDU from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.pdu import Address from bacpypes.object import get_object_class, get_datatype from bacpypes.constructeddata import Array from bacpypes.primitivedata import Tag...
request.lifetime = context.lifetime return request # def context_callback(self, elements, callback=None): def context_callback(self, elements): self._log.info("Received COV Notification for {}".format(elements)) # if callback: # callback() for device in s...
random_line_split
cov.py
from bacpypes.apdu import SubscribeCOVRequest, SimpleAckPDU, RejectPDU, AbortPDU from bacpypes.iocb import IOCB from bacpypes.core import deferred from bacpypes.pdu import Address from bacpypes.object import get_object_class, get_datatype from bacpypes.constructeddata import Array from bacpypes.primitivedata import Tag...
device[elements["object_changed"]].cov_registered = True for prop, value in elements["properties"].items(): if prop == "presentValue": device[elements["object_changed"]]._trend(value) else: device[elements["object_ch...
conditional_block
ief.py
IefDataTypes(object): """Enum for the different data types within the Ief class. Use these for easy access of the Ief class. """ HEADER, DETAILS, IED_DATA, SNAPSHOTS, DESCRIPTION = range(5) class Ief(object): """Contains the details in the in the IEF file. Class data and a methods for acces...
if not self.snapshots is None and not self.snapshots == []: snapshot_paths = [snap['file'] for snap in self.snapshots] paths_dict['snapshots'] = snapshot_paths else: paths_dict['snapshots'] = [] return paths_dict def getValue(self, key): """Get...
paths_dict['ieds'] = []
conditional_block
ief.py
IefDataTypes(object): """Enum for the different data types within the Ief class. Use these for easy access of the Ief class. """ HEADER, DETAILS, IED_DATA, SNAPSHOTS, DESCRIPTION = range(5) class Ief(object): """Contains the details in the in the IEF file. Class data and a methods for acces...
def _findVarInDictionary(self, the_dict, key): """Returns the variable in a dictionary. Tests to see if a variables exists under the given key in the given dictionary. If it does it will return it. Args: the_dict (Dict): Dictionary in which to check the keys existence. ...
raise ValueError('time is not a numeric value') self.snapshots.append({'time': time, 'file': snapshot_path})
random_line_split
ief.py
IefDataTypes(object): """Enum for the different data types within the Ief class. Use these for easy access of the Ief class. """ HEADER, DETAILS, IED_DATA, SNAPSHOTS, DESCRIPTION = range(5) class Ief(object): """Contains the details in the in the IEF file. Class data and a methods for acces...
(self): """Returns the description component of the ief.""" return self.description def setValue(self, key, value): """Set the value of one of dictionary entries in the ief. Args: key(str): The key of the value to update. value(str(: the value to update. ...
getDescription
identifier_name
ief.py
class IefDataTypes(object): """Enum for the different data types within the Ief class. Use these for easy access of the Ief class. """ HEADER, DETAILS, IED_DATA, SNAPSHOTS, DESCRIPTION = range(5) class Ief(object): """Contains the details in the in the IEF file. Class data and a methods for ...
try: paths_dict['Results'] = self._findVarInDictionary(self.event_header, 'Results') except: paths_dict['Results'] = None try: paths_dict['InitialConditions'] = self._findVarInDictionary(self.event_details, 'InitialConditions') except: path...
"""Returns all the file paths that occur in the ief file. Most paths are extracted from the head and details data, when they exist, and are added to paths_dict. If any ied data or snapshot data exists it will be added as a list to the dictionary. If a particular path is not found the ...
identifier_body
ps.js
var q = require("./quasi"); exports.ps = function (opt) { opt = opt || {}; var strokeWidth = opt.strokeWidth || "0.015"; if (opt.color) console.error("The ps module does not support the `color` option."); // PS header var ret = [ "%%!PS-Adobe-1.0 " , "%%%%BoundingBox: -1 -1 766...
} , setFillGrey: function (colour) { ret.push(colour + " sg"); ret.push("fill"); } , setStrokeGrey: function (colour) { ret.push(colour + " sg"); ret.push("a"); } // we don't take these ...
, endGroup: function () { ret.push("h");
random_line_split
persistent_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A persistent, thread-safe singly-linked list. use std::sync::Arc; pub struct PersistentList<T> { head: P...
} } } pub struct PersistentListIterator<'a, T> where T: 'a + Send + Sync { entry: Option<&'a PersistentListEntry<T>>, } impl<'a, T> Iterator for PersistentListIterator<'a, T> where T: Send + Sync + 'static { type Item = &'a T; #[inline] fn next(&mut self) -> Option<&'a T> { let en...
// This establishes the persistent nature of this list: we can clone a list by just cloning // its head. PersistentList { head: self.head.clone(), length: self.length,
random_line_split
persistent_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A persistent, thread-safe singly-linked list. use std::sync::Arc; pub struct PersistentList<T> { head: P...
(&self) -> PersistentListIterator<T> { // This could clone (and would not need the lifetime if it did), but then it would incur // atomic operations on every call to `.next()`. Bad. PersistentListIterator { entry: self.head.as_ref().map(|head| &**head), } } } impl<T> Clo...
iter
identifier_name
platform-data.ts
import { Architectures } from "common/butlerd/messages"; interface PlatformData { icon: string; platform: string; emoji: string; } interface PlatformDataMap {
osx: PlatformData; [key: string]: PlatformData; } const data: PlatformDataMap = { windows: { icon: "windows8", platform: "windows", emoji: "🏁" }, linux: { icon: "tux", platform: "linux", emoji: "🐧" }, osx: { icon: "apple", platform: "osx", emoji: "🍎" }, }; export default data; export type PlatformHolder ...
windows: PlatformData; linux: PlatformData;
random_line_split
platform-data.ts
import { Architectures } from "common/butlerd/messages"; interface PlatformData { icon: string; platform: string; emoji: string; } interface PlatformDataMap { windows: PlatformData; linux: PlatformData; osx: PlatformData; [key: string]: PlatformData; } const data: PlatformDataMap = { windows: { icon:...
PlatformHolder): boolean { for (const key of Object.keys(data)) { if ((target.platforms as { [key: string]: Architectures })[key]) { return true; } } if (target.type === "html") { return true; } return false; }
rms(target:
identifier_name
platform-data.ts
import { Architectures } from "common/butlerd/messages"; interface PlatformData { icon: string; platform: string; emoji: string; } interface PlatformDataMap { windows: PlatformData; linux: PlatformData; osx: PlatformData; [key: string]: PlatformData; } const data: PlatformDataMap = { windows: { icon:...
false; }
urn true; } return
conditional_block
platform-data.ts
import { Architectures } from "common/butlerd/messages"; interface PlatformData { icon: string; platform: string; emoji: string; } interface PlatformDataMap { windows: PlatformData; linux: PlatformData; osx: PlatformData; [key: string]: PlatformData; } const data: PlatformDataMap = { windows: { icon:...
const key of Object.keys(data)) { if ((target.platforms as { [key: string]: Architectures })[key]) { return true; } } if (target.type === "html") { return true; } return false; }
identifier_body
NSpicard.py
['linear_algebra_backend'] = 'PETSc' for xx in xrange(1,m): print xx nn = 2**(xx) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn mesh = RectangleMesh(-1, -1, 1, 1, nn, nn,'right') # tic() parameters['reorder_dofs_serial'] = False V = VectorFunctionSpace(mesh, ...
if case == 1: u0 = Expression(("20*x[0]*pow(x[1],3)","5*pow(x[0],4)-5*pow(x[1],4)")) p0 = Expression("60*pow(x[0],2)*x[1]-20*pow(x[1],3)") elif case == 2: Su0 = Expression(("pow(x[1],2)-x[1]","pow(x[0],2)-x[0]")) p0 = Expression("x[1]+x[0]-1") elif case == 3: u0 = E...
return on_boundary
identifier_body
NSpicard.py
['linear_algebra_backend'] = 'PETSc' for xx in xrange(1,m): print xx nn = 2**(xx) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn mesh = RectangleMesh(-1, -1, 1, 1, nn, nn,'right') # tic() parameters['reorder_dofs_serial'] = False V = VectorFunctionSpace(mesh, ...
elif case == 3: f = -Expression(("8*pi*pi*cos(2*pi*x[1])*sin(2*pi*x[0]) + 2*pi*cos(2*pi*x[0])*sin(2*pi*x[1])","2*pi*cos(2*pi*x[0])*sin(2*pi*x[1]) - 8*pi*pi*cos(2*pi*x[0])*sin(2*pi*x[1])")) u_k = Function(V) mu = Constant(1e0) u_k.vector()[:] = u_k.vector()[:]*0 n = FacetNormal(mesh) h...
f = -Expression(("-1","-1"))
conditional_block
NSpicard.py
parameters['linear_algebra_backend'] = 'PETSc' for xx in xrange(1,m): print xx nn = 2**(xx) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn mesh = RectangleMesh(-1, -1, 1, 1, nn, nn,'right') # tic() parameters['reorder_dofs_serial'] = False V = VectorFunctionSp...
iter = 0 # iteration counter maxiter = 100 # max no of iterations allowed while eps > tol and iter < maxiter: iter += 1 x = Function(W) uu = Function(W) tic() AA, bb = assemble_system(a, L1, bcs) A = as_backend_type(...
eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance
random_line_split
NSpicard.py
['linear_algebra_backend'] = 'PETSc' for xx in xrange(1,m): print xx nn = 2**(xx) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn mesh = RectangleMesh(-1, -1, 1, 1, nn, nn,'right') # tic() parameters['reorder_dofs_serial'] = False V = VectorFunctionSpace(mesh, ...
(x, on_boundary): return on_boundary if case == 1: u0 = Expression(("20*x[0]*pow(x[1],3)","5*pow(x[0],4)-5*pow(x[1],4)")) p0 = Expression("60*pow(x[0],2)*x[1]-20*pow(x[1],3)") elif case == 2: Su0 = Expression(("pow(x[1],2)-x[1]","pow(x[0],2)-x[0]")) p0 = Expression("x[1]...
boundary
identifier_name
index.js
module.exports = importGTFS const async = require('async') const path = require('path') const load = require('require-all')({ dirname: __dirname, filter: /import.(.+)\.js$/, excludeDirs: /^\.(git|svn)$/ }) const importOrder = [ 'agency', 'calendar_dates', 'calendar', 'stops', 'routes', 'trips', '...
(source, callback) { const transit = this const status = { imported: {} } async.eachSeries(importOrder, function (what, cb) { const importer = load[what] importer(path.join(source, what + '.txt'), transit, function (err) { if (err && err.code === 'ENOENT') { if (err && importer.opt...
importGTFS
identifier_name
index.js
module.exports = importGTFS const async = require('async') const path = require('path') const load = require('require-all')({ dirname: __dirname, filter: /import.(.+)\.js$/, excludeDirs: /^\.(git|svn)$/ }) const importOrder = [ 'agency', 'calendar_dates', 'calendar', 'stops', 'routes', 'trips', '...
// file is optional, so omit 'file not found' error err = null } } status.imported[what] = true cb(err) }) }, callback) }
{ const transit = this const status = { imported: {} } async.eachSeries(importOrder, function (what, cb) { const importer = load[what] importer(path.join(source, what + '.txt'), transit, function (err) { if (err && err.code === 'ENOENT') { if (err && importer.optional === true) { ...
identifier_body
index.js
module.exports = importGTFS const async = require('async') const path = require('path') const load = require('require-all')({ dirname: __dirname, filter: /import.(.+)\.js$/, excludeDirs: /^\.(git|svn)$/ }) const importOrder = [ 'agency', 'calendar_dates', 'calendar', 'stops', 'routes', 'trips', '...
} status.imported[what] = true cb(err) }) }, callback) }
{ // file is optional, so omit 'file not found' error err = null }
conditional_block
index.js
module.exports = importGTFS const async = require('async') const path = require('path') const load = require('require-all')({ dirname: __dirname, filter: /import.(.+)\.js$/, excludeDirs: /^\.(git|svn)$/ }) const importOrder = [ 'agency', 'calendar_dates', 'calendar', 'stops', 'routes', 'trips', '...
importer(path.join(source, what + '.txt'), transit, function (err) { if (err && err.code === 'ENOENT') { if (err && importer.optional === true) { // file is optional, so omit 'file not found' error err = null } if (err && typeof importer.optional === 'fu...
} async.eachSeries(importOrder, function (what, cb) { const importer = load[what]
random_line_split
IRLS_tf_v2.py
# python 3 # tensorflow 2.0 from __future__ import print_function, division, absolute_import import os import argparse import random import numpy as np import datetime # from numpy import linalg import os.path as osp import sys cur_dir = osp.dirname(osp.abspath(__file__)) sys.path.insert(1, osp.join(cur_dir, '.')) fr...
(X, y, w): p = prob(X, w) y_pred = tf.cast(tf.argmax(p, axis=1), tf.float32) y = tf.cast(tf.squeeze(y), tf.float32) acc = tf.reduce_mean(tf.cast(tf.equal(y, y_pred), tf.float32)) return acc def update(w_old, X, y, L2_param=0): """ w_new = w_old - w_update w_update = (X'RX+lambda*I)^(-1) (X...
compute_acc
identifier_name
IRLS_tf_v2.py
# python 3 # tensorflow 2.0 from __future__ import print_function, division, absolute_import import os import argparse import random import numpy as np import datetime # from numpy import linalg import os.path as osp import sys cur_dir = osp.dirname(osp.abspath(__file__)) sys.path.insert(1, osp.join(cur_dir, '.')) fr...
lambda_ = 20 # 0 train_IRLS(X_train, y_train, X_test, y_test, L2_param=lambda_, max_iter=100) from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() classifier.fit(X_train, y_train.reshape(N_train,)) y_pred_train = classifier.predict(X_train) train_acc = np.sum(y...
conditional_block
IRLS_tf_v2.py
# python 3 # tensorflow 2.0 from __future__ import print_function, division, absolute_import import os import argparse import random import numpy as np import datetime # from numpy import linalg import os.path as osp import sys cur_dir = osp.dirname(osp.abspath(__file__)) sys.path.insert(1, osp.join(cur_dir, '.')) fr...
def compute_acc(X, y, w): p = prob(X, w) y_pred = tf.cast(tf.argmax(p, axis=1), tf.float32) y = tf.cast(tf.squeeze(y), tf.float32) acc = tf.reduce_mean(tf.cast(tf.equal(y, y_pred), tf.float32)) return acc def update(w_old, X, y, L2_param=0): """ w_new = w_old - w_update w_update = (X'RX...
""" X: Nxd w: dx1 --- prob: N x num_classes(2)""" y = tf.constant(np.array([0.0, 1.0]), dtype=tf.float32) prob = tf.exp(tf.matmul(X, w) * y) / (1 + tf.exp(tf.matmul(X, w))) return prob
identifier_body
IRLS_tf_v2.py
# python 3 # tensorflow 2.0 from __future__ import print_function, division, absolute_import import os import argparse import random import numpy as np import datetime
cur_dir = osp.dirname(osp.abspath(__file__)) sys.path.insert(1, osp.join(cur_dir, '.')) from sklearn.datasets import load_svmlight_file from scipy.sparse import csr_matrix # from scipy.sparse import linalg import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import tensorflow as tf from tf_utils im...
# from numpy import linalg import os.path as osp import sys
random_line_split
test_tag_tagvis.py
import pytest from cfme.cloud.provider.azure import AzureProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.networks.views import BalancerView from cfme.networks.views import CloudNetworkView from cfme.networks.views import FloatingIpView from cfme.networks.views import NetworkPortView f...
@pytest.fixture(params=network_collections, scope='module') def entity(request, appliance): collection_name = request.param item_collection = getattr(appliance.collections, collection_name) items = item_collection.all() if items: return items[0] else: pytest.skip("No content found...
""" Polarion: assignee: anikifor initialEstimate: 1/8h casecomponent: Tagging """ collection = appliance.collections.network_providers.filter({'provider': provider}) network_provider = collection.all()[0] network_provider.add_tag(tag=tag) request.addfinalizer(lambda: net...
identifier_body
test_tag_tagvis.py
import pytest from cfme.cloud.provider.azure import AzureProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.networks.views import BalancerView from cfme.networks.views import CloudNetworkView from cfme.networks.views import FloatingIpView from cfme.networks.views import NetworkPortView f...
else: assert relationship_view.entities.entity_ids actual_visibility = True except AssertionError: actual_visibility = False return actual_visibility @pytest.mark.parametrize("relationship,view", network_test_items, ids=[rel[0] for rel in network_...
assert relationship_view.entities.entity_names
conditional_block
test_tag_tagvis.py
import pytest from cfme.cloud.provider.azure import AzureProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.networks.views import BalancerView from cfme.networks.views import CloudNetworkView from cfme.networks.views import FloatingIpView from cfme.networks.views import NetworkPortView f...
pytest.mark.usefixtures('setup_provider'), pytest.mark.provider([AzureProvider], selector=ONE_PER_CATEGORY, scope='module') ] network_collections = [ 'network_providers', 'cloud_networks', 'network_subnets', 'network_ports', 'network_security_groups', 'network_routers', 'network_flo...
pytestmark = [
random_line_split
test_tag_tagvis.py
import pytest from cfme.cloud.provider.azure import AzureProvider from cfme.markers.env_markers.provider import ONE_PER_CATEGORY from cfme.networks.views import BalancerView from cfme.networks.views import CloudNetworkView from cfme.networks.views import FloatingIpView from cfme.networks.views import NetworkPortView f...
(appliance, network_provider, relationship, view): network_provider_view = navigate_to(network_provider, 'Details') if network_provider_view.entities.relationships.get_text_of(relationship) == "0": pytest.skip("There are no relationships for {}".format(relationship)) network_provider_view.entities.r...
child_visibility
identifier_name
icu_tools.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import icu def all_glyphs(prop): return [c.encode('utf-16', 'surrogatepass').decode('utf-16') for c in icu.UnicodeSetIterator(icu.UnicodeSet(r'[:{}:]'.format(prop)))] def all_cps(prop): return list(map(glyph_cp, all_glyphs(prop))) def glyph_name(glyph, default=...
raise TypeError('glyph must be a string with length of 1') elif len(glyph) == 0: return default else: return icu.Char.charName(glyph) def cp_glyph(cp, default=''): try: return chr(int(cp, 16)) except ValueError: return default def cp_name(cp, default=''): re...
random_line_split
icu_tools.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import icu def all_glyphs(prop): return [c.encode('utf-16', 'surrogatepass').decode('utf-16') for c in icu.UnicodeSetIterator(icu.UnicodeSet(r'[:{}:]'.format(prop)))] def all_cps(prop): return list(map(glyph_cp, all_glyphs(prop))) def glyph_name(glyph, default=...
elif len(glyph) == 0: return default else: return icu.Char.charName(glyph) def cp_glyph(cp, default=''): try: return chr(int(cp, 16)) except ValueError: return default def cp_name(cp, default=''): return glyph_name(cp_glyph(cp), default) def glyph_cp(glyph): r...
raise TypeError('glyph must be a string with length of 1')
conditional_block
icu_tools.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import icu def all_glyphs(prop): return [c.encode('utf-16', 'surrogatepass').decode('utf-16') for c in icu.UnicodeSetIterator(icu.UnicodeSet(r'[:{}:]'.format(prop)))] def
(prop): return list(map(glyph_cp, all_glyphs(prop))) def glyph_name(glyph, default=''): if len(glyph) > 1: raise TypeError('glyph must be a string with length of 1') elif len(glyph) == 0: return default else: return icu.Char.charName(glyph) def cp_glyph(cp, default=''): try...
all_cps
identifier_name
icu_tools.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import icu def all_glyphs(prop): return [c.encode('utf-16', 'surrogatepass').decode('utf-16') for c in icu.UnicodeSetIterator(icu.UnicodeSet(r'[:{}:]'.format(prop)))] def all_cps(prop):
def glyph_name(glyph, default=''): if len(glyph) > 1: raise TypeError('glyph must be a string with length of 1') elif len(glyph) == 0: return default else: return icu.Char.charName(glyph) def cp_glyph(cp, default=''): try: return chr(int(cp, 16)) except ValueError:...
return list(map(glyph_cp, all_glyphs(prop)))
identifier_body
emf_export.py
space lengths.""" pyemf._EMR._EXTCREATEPEN.__init__(self) self.style = style self.penwidth = width self.color = pyemf._normalizeColor(color) self.brushstyle = 0x0 # solid if style & pyemf.PS_STYLE_MASK != pyemf.PS_USERSTYLE: styleentries = [] self...
(self, pt, textitem): """Convert text to a path and draw it. """ # print "text", pt, textitem.text() path = qt.QPainterPath() path.addText(pt, textitem.font(), textitem.text()) fill = self.emf.CreateSolidBrush(self.pencolor) self.emf.SelectObject(fill) se...
drawTextItem
identifier_name
emf_export.py
"ellipse" args = ( int(rect.left()*scale), int(rect.top()*scale), int(rect.right()*scale), int(rect.bottom()*scale), int(rect.left()*scale), int(rect.top()*scale), int(rect.left()*scale), int(rect.top()*scale), ) self.emf.Pie(*args) sel...
self.emf.BeginPath() self.emf.MoveTo(0,0) w = int(self.width*self.dpi*scale) h = int(self.height*self.dpi*scale) self.emf.LineTo(w, 0) self.emf.LineTo(w, h) self.emf.LineTo(0, h) self.emf.CloseFigure() self.emf.EndPath() ...
conditional_block
emf_export.py
0, 0) self.brush = self.emf.GetStockObject(pyemf.NULL_BRUSH) self.paintdevice = paintdevice return True def drawLines(self, lines): """Draw lines to emf output.""" for line in lines: self.emf.Polyline( [ (int(line.x1()*scale), int(line.y1()*sca...
"""Update to selected brush.""" style = brush.style() qc = brush.color() color = (qc.red(), qc.green(), qc.blue()) # print "brush", color if style == qt.Qt.SolidPattern: newbrush = self.emf.CreateSolidBrush(color) elif style == qt.Qt.NoBrush: newb...
identifier_body
emf_export.py
) self.brush = self.emf.GetStockObject(pyemf.NULL_BRUSH) self.paintdevice = paintdevice return True def drawLines(self, lines): """Draw lines to emf output.""" for line in lines: self.emf.Polyline( [ (int(line.x1()*scale), int(line.y1()*scale))...
qt.Qt.DiagCrossPattern: pyemf.HS_DIAGCROSS }[brush.style()] except KeyError:
random_line_split
lib.rs
pub new_pipeline_id: PipelineId, /// Id of the new frame associated with this pipeline. pub subpage_id: SubpageId, /// Network request data which will be initiated by the script thread. pub load_data: LoadData, /// The paint channel, cast to `OptionalOpaqueIpcSender`. This is really an /// `...
/// Data needed to construct a script thread. /// /// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you /// do! Use IPC senders and receivers instead. pub struct InitialScriptState { /// The ID of the pipeline with which this script thread is associated. pub id: Pi...
{ Length::new(time::precise_time_ns()) }
identifier_body
lib.rs
. pub new_pipeline_id: PipelineId, /// Id of the new frame associated with this pipeline. pub subpage_id: SubpageId, /// Network request data which will be initiated by the script thread. pub load_data: LoadData, /// The paint channel, cast to `OptionalOpaqueIpcSender`. This is really an ///...
(pub IpcSender<TimerEvent>, pub TimerSource, pub TimerEventId, pub MsDuration); /// Notifies the script thread to fire due timers. /// TimerSource must be FromWindow when dispatched to ScriptThread and /// must be FromWorker when di...
TimerEventRequest
identifier_name
lib.rs
Event { /// The window was resized. ResizeEvent(WindowSizeData), /// A mouse button state changed. MouseButtonEvent(MouseEventType, MouseButton, Point2D<f32>), /// The mouse was moved over a point (or was moved out of the recognizable region). MouseMoveEvent(Option<Point2D<f32>>), /// A touc...
Error, /// Sent when the favicon of a browser `<iframe>` changes.
random_line_split
index.rs
use std::collections::HashMap; use std::io::prelude::*; use std::fs::File; use std::path::Path; use rustc_serialize::json; use core::dependency::{Dependency, DependencyInner, Kind}; use core::{SourceId, Summary, PackageId, Registry}; use sources::registry::{RegistryPackage, RegistryDependency, INDEX_LOCK};
pub struct RegistryIndex<'cfg> { source_id: SourceId, path: Filesystem, cache: HashMap<String, Vec<(Summary, bool)>>, hashes: HashMap<(String, String), String>, // (name, vers) => cksum config: &'cfg Config, locked: bool, } impl<'cfg> RegistryIndex<'cfg> { pub fn new(id: &SourceId, ...
use util::{CargoResult, ChainError, internal, Filesystem, Config};
random_line_split
index.rs
use std::collections::HashMap; use std::io::prelude::*; use std::fs::File; use std::path::Path; use rustc_serialize::json; use core::dependency::{Dependency, DependencyInner, Kind}; use core::{SourceId, Summary, PackageId, Registry}; use sources::registry::{RegistryPackage, RegistryDependency, INDEX_LOCK}; use util::...
(&mut self, name: &str) -> CargoResult<&Vec<(Summary, bool)>> { if self.cache.contains_key(name) { return Ok(self.cache.get(name).unwrap()); } let summaries = self.load_summaries(name)?; let summaries = summaries.into_iter().filter(|summary| { summary.0.package_id...
summaries
identifier_name
index.rs
use std::collections::HashMap; use std::io::prelude::*; use std::fs::File; use std::path::Path; use rustc_serialize::json; use core::dependency::{Dependency, DependencyInner, Kind}; use core::{SourceId, Summary, PackageId, Registry}; use sources::registry::{RegistryPackage, RegistryDependency, INDEX_LOCK}; use util::...
let path = match fs_name.len() { 1 => path.join("1").join(&fs_name), 2 => path.join("2").join(&fs_name), 3 => path.join("3").join(&fs_name[..1]).join(&fs_name), _ => path.join(&fs_name[0..2]) .join(&fs_name[2..4]) .join(&f...
{ let (path, _lock) = if self.locked { let lock = self.path.open_ro(Path::new(INDEX_LOCK), self.config, "the registry index"); match lock { Ok(lock) => { (lock.path().par...
identifier_body
string_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use libc::{c_int}; use std::slice; use string::cef_string_utf16_set; use types::{cef_string_list_t,cef_string_t}; ...
#[no_mangle] pub extern "C" fn cef_string_list_size(lt: *mut cef_string_list_t) -> c_int { unsafe { if lt.is_null() { return 0; } (*lt).len() as c_int } } #[no_mangle] pub extern "C" fn cef_string_list_append(lt: *mut cef_string_list_t, value: *const cef_string_t) { unsafe { if lt...
{ Box::into_raw(box vec!()) }
identifier_body
string_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use libc::{c_int}; use std::slice; use string::cef_string_utf16_set; use types::{cef_string_list_t,cef_string_t}; ...
(lt: *mut cef_string_list_t) -> *mut cef_string_list_t { unsafe { if lt.is_null() { return 0 as *mut cef_string_list_t; } let copy = (*lt).clone(); Box::into_raw(box copy) } }
cef_string_list_copy
identifier_name