file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
luhn_test.rs
// Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers struct Digits { m: u64 } impl Iterator for Digits { type Item = u64; fn next(&mut self) -> Option<u64> { match self.m { 0 => None, n => { let ret = n % 10; self.m = n / 10; Some(ret) } } } } #[derive(Copy, Clone)] enum LuhnState { Even, Odd, } fn digits(n: u64) -> Digits { Digits{m: n} } fn luhn_test(n: u64) -> bool { let odd_even = [LuhnState::Odd, LuhnState::Even]; let numbers = digits(n).zip(odd_even.iter().cycle().map(|&s| s)); let sum = numbers.fold(0u64, |s, n| { s + match n { (n, LuhnState::Odd) => n, (n, LuhnState::Even) => digits(n * 2).fold(0, |s, n| s + n), } }); sum % 10 == 0 } #[cfg(not(test))] fn main() { let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670]; for n in &nos { if luhn_test(*n) { println!("{} passes." , n); } else { println!("{} fails." , n); } } } #[test] fn test_inputs()
{ assert!(luhn_test(49927398716)); assert!(!luhn_test(49927398717)); assert!(!luhn_test(1234567812345678)); assert!(luhn_test(1234567812345670)); }
identifier_body
luhn_test.rs
// Implements http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers struct Digits { m: u64 } impl Iterator for Digits { type Item = u64; fn next(&mut self) -> Option<u64> { match self.m { 0 => None, n => { let ret = n % 10; self.m = n / 10; Some(ret) } } } } #[derive(Copy, Clone)] enum LuhnState { Even, Odd, } fn digits(n: u64) -> Digits { Digits{m: n} } fn luhn_test(n: u64) -> bool { let odd_even = [LuhnState::Odd, LuhnState::Even]; let numbers = digits(n).zip(odd_even.iter().cycle().map(|&s| s)); let sum = numbers.fold(0u64, |s, n| { s + match n { (n, LuhnState::Odd) => n, (n, LuhnState::Even) => digits(n * 2).fold(0, |s, n| s + n), } }); sum % 10 == 0 } #[cfg(not(test))] fn main() { let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670]; for n in &nos { if luhn_test(*n) { println!("{} passes." , n); } else { println!("{} fails." , n); } } } #[test]
assert!(!luhn_test(49927398717)); assert!(!luhn_test(1234567812345678)); assert!(luhn_test(1234567812345670)); }
fn test_inputs() { assert!(luhn_test(49927398716));
random_line_split
Route.tsx
/** * Taken from @taion as per example of how they actually use found-relay and * have default setup for each route. */ import { RouteSpinner } from "Artsy/Relay/renderWithLoadProgress" import { HttpError } from "found" import BaseRoute from "found/Route" import React from "react" type FetchIndicator = "spinner" | "overlay" interface CreateRenderProps { fetchIndicator?: FetchIndicator render?: (props) => React.ReactNode } interface RenderArgProps { Component: React.ComponentType props?: object error?: Error } function createRender({ fetchIndicator = "overlay", render, }: CreateRenderProps) { return (renderArgs: RenderArgProps) => { const { Component, props, error } = renderArgs if (error) { if (error instanceof HttpError) { throw error } console.error( "[Artsy/Router/Route] Non HttpError rendering route:", error ) return null } if (render)
if (Component === undefined) { return undefined } // This should only ever show when doing client-side routing. if (!props) { if (fetchIndicator === "spinner") { return <RouteSpinner /> // TODO: At some point we might want to make this a little fancier. If // undefined is returned here, then we defer to `RenderStatus` component. } else if (fetchIndicator === "overlay") { /* In attempting to avoid the use of <StaticContainer> in RenderStatus.tsx, which freezes the component tree with `shouldComponentUpdate = false`, we stored the previously-rendered component and props in a variable and instead of returning undefined here, we returned <PrevComponent {...prevProps} />. However, when the component is rendered by react, it errors out because the data in prevProps has seemingly been garbage collected. Relay has the ability to `retain` data in the store. We should investigate, which would give us greater control over our component tree when top-level route transitions occur. See: https://graphql.slack.com/archives/C0BEXJLKG/p1561741782163900 export const setLocal = (query: GraphQLTaggedNode, localData: object) => { const request = getRequest(query); const operation = createOperationDescriptor(request, {}); env.commitPayload(operation, localData); env.retain(operation.root); // <== here @en_js magic :wink: }; */ /** * Its an odd requirement, but the way in which one triggers RenderStatus * component updates is to return undefined. */ return undefined // If for some reason something else is passed, fall back to the spinner } else { return <RouteSpinner /> } } return <Component {...props} /> } } export class Route extends BaseRoute { constructor(props) { if (!(props.query || props.getQuery)) { super(props) return } super({ ...props, render: createRender(props), }) } }
{ return render(renderArgs) }
conditional_block
Route.tsx
/** * Taken from @taion as per example of how they actually use found-relay and * have default setup for each route. */ import { RouteSpinner } from "Artsy/Relay/renderWithLoadProgress" import { HttpError } from "found" import BaseRoute from "found/Route" import React from "react" type FetchIndicator = "spinner" | "overlay" interface CreateRenderProps { fetchIndicator?: FetchIndicator render?: (props) => React.ReactNode } interface RenderArgProps { Component: React.ComponentType props?: object error?: Error } function createRender({ fetchIndicator = "overlay", render, }: CreateRenderProps) { return (renderArgs: RenderArgProps) => { const { Component, props, error } = renderArgs if (error) { if (error instanceof HttpError) { throw error } console.error( "[Artsy/Router/Route] Non HttpError rendering route:", error ) return null } if (render) { return render(renderArgs) } if (Component === undefined) { return undefined } // This should only ever show when doing client-side routing. if (!props) { if (fetchIndicator === "spinner") { return <RouteSpinner /> // TODO: At some point we might want to make this a little fancier. If // undefined is returned here, then we defer to `RenderStatus` component. } else if (fetchIndicator === "overlay") { /* In attempting to avoid the use of <StaticContainer> in RenderStatus.tsx, which freezes the component tree with `shouldComponentUpdate = false`, we stored the previously-rendered component and props in a variable and instead of returning undefined here, we returned <PrevComponent {...prevProps} />. However, when the component is rendered by react, it errors out because the data in prevProps has seemingly been garbage collected. Relay has the ability to `retain` data in the store. We should investigate, which would give us greater control over our component tree when top-level route transitions occur. See: https://graphql.slack.com/archives/C0BEXJLKG/p1561741782163900 export const setLocal = (query: GraphQLTaggedNode, localData: object) => { const request = getRequest(query); const operation = createOperationDescriptor(request, {}); env.commitPayload(operation, localData); env.retain(operation.root); // <== here @en_js magic :wink: }; */ /** * Its an odd requirement, but the way in which one triggers RenderStatus * component updates is to return undefined. */ return undefined // If for some reason something else is passed, fall back to the spinner } else { return <RouteSpinner /> } } return <Component {...props} /> } } export class Route extends BaseRoute { constructor(props)
}
{ if (!(props.query || props.getQuery)) { super(props) return } super({ ...props, render: createRender(props), }) }
identifier_body
Route.tsx
/** * Taken from @taion as per example of how they actually use found-relay and * have default setup for each route. */ import { RouteSpinner } from "Artsy/Relay/renderWithLoadProgress" import { HttpError } from "found" import BaseRoute from "found/Route" import React from "react" type FetchIndicator = "spinner" | "overlay" interface CreateRenderProps { fetchIndicator?: FetchIndicator render?: (props) => React.ReactNode } interface RenderArgProps { Component: React.ComponentType props?: object error?: Error } function createRender({ fetchIndicator = "overlay", render, }: CreateRenderProps) { return (renderArgs: RenderArgProps) => { const { Component, props, error } = renderArgs if (error) { if (error instanceof HttpError) { throw error } console.error( "[Artsy/Router/Route] Non HttpError rendering route:", error ) return null } if (render) { return render(renderArgs) } if (Component === undefined) { return undefined } // This should only ever show when doing client-side routing. if (!props) { if (fetchIndicator === "spinner") { return <RouteSpinner /> // TODO: At some point we might want to make this a little fancier. If // undefined is returned here, then we defer to `RenderStatus` component. } else if (fetchIndicator === "overlay") { /* In attempting to avoid the use of <StaticContainer> in RenderStatus.tsx, which freezes the component tree with `shouldComponentUpdate = false`, we stored the previously-rendered component and props in a variable and instead of returning undefined here, we returned <PrevComponent {...prevProps} />. However, when the component is rendered by react, it errors out because the data in prevProps has seemingly been garbage collected. Relay has the ability to `retain` data in the store. We should investigate, which would give us greater control over our component tree when top-level route transitions occur. See: https://graphql.slack.com/archives/C0BEXJLKG/p1561741782163900 export const setLocal = (query: GraphQLTaggedNode, localData: object) => { const request = getRequest(query); const operation = createOperationDescriptor(request, {}); env.commitPayload(operation, localData); env.retain(operation.root); // <== here @en_js magic :wink: }; */ /** * Its an odd requirement, but the way in which one triggers RenderStatus * component updates is to return undefined. */ return undefined // If for some reason something else is passed, fall back to the spinner } else { return <RouteSpinner /> } } return <Component {...props} /> } } export class
extends BaseRoute { constructor(props) { if (!(props.query || props.getQuery)) { super(props) return } super({ ...props, render: createRender(props), }) } }
Route
identifier_name
Route.tsx
/**
import { HttpError } from "found" import BaseRoute from "found/Route" import React from "react" type FetchIndicator = "spinner" | "overlay" interface CreateRenderProps { fetchIndicator?: FetchIndicator render?: (props) => React.ReactNode } interface RenderArgProps { Component: React.ComponentType props?: object error?: Error } function createRender({ fetchIndicator = "overlay", render, }: CreateRenderProps) { return (renderArgs: RenderArgProps) => { const { Component, props, error } = renderArgs if (error) { if (error instanceof HttpError) { throw error } console.error( "[Artsy/Router/Route] Non HttpError rendering route:", error ) return null } if (render) { return render(renderArgs) } if (Component === undefined) { return undefined } // This should only ever show when doing client-side routing. if (!props) { if (fetchIndicator === "spinner") { return <RouteSpinner /> // TODO: At some point we might want to make this a little fancier. If // undefined is returned here, then we defer to `RenderStatus` component. } else if (fetchIndicator === "overlay") { /* In attempting to avoid the use of <StaticContainer> in RenderStatus.tsx, which freezes the component tree with `shouldComponentUpdate = false`, we stored the previously-rendered component and props in a variable and instead of returning undefined here, we returned <PrevComponent {...prevProps} />. However, when the component is rendered by react, it errors out because the data in prevProps has seemingly been garbage collected. Relay has the ability to `retain` data in the store. We should investigate, which would give us greater control over our component tree when top-level route transitions occur. See: https://graphql.slack.com/archives/C0BEXJLKG/p1561741782163900 export const setLocal = (query: GraphQLTaggedNode, localData: object) => { const request = getRequest(query); const operation = createOperationDescriptor(request, {}); env.commitPayload(operation, localData); env.retain(operation.root); // <== here @en_js magic :wink: }; */ /** * Its an odd requirement, but the way in which one triggers RenderStatus * component updates is to return undefined. */ return undefined // If for some reason something else is passed, fall back to the spinner } else { return <RouteSpinner /> } } return <Component {...props} /> } } export class Route extends BaseRoute { constructor(props) { if (!(props.query || props.getQuery)) { super(props) return } super({ ...props, render: createRender(props), }) } }
* Taken from @taion as per example of how they actually use found-relay and * have default setup for each route. */ import { RouteSpinner } from "Artsy/Relay/renderWithLoadProgress"
random_line_split
mapUtils.test.js
import deepFreeze from 'deep-freeze'; import { arrayToMap, mapKeysToArray } from './mapUtils'; describe('arrayToMap', () => { it('should create map from 2D array', () => { const a = [ ['key1', 'value1'], ['key2', 'value2'] ]; deepFreeze(a); const result = arrayToMap(a); expect(result.size).toBe(2); expect(result.get('key1')).toBe('value1'); expect(result.get('key2')).toBe('value2'); }); it('should create empty map from empty array', () => { const result = arrayToMap([]); expect(result.size).toBe(0); }); }); describe('mapKeysToArray', () => { it('should create array from map keys in order', () => { const map = new Map(); map.set('a', 'value1'); map.set('c', 'value2'); map.set('1', 'value3'); map.set('b', 'value4'); map.set('2', 'value5'); const result = mapKeysToArray(map); expect(result).toEqual(['a', 'c', '1', 'b', '2']); }); it('should create empty array from new map', () => {
const map = new Map(); const result = mapKeysToArray(map); expect(result).toEqual([]); }); });
random_line_split
counted-cache.ts
export interface CacheItem<T> { count: number data: T } export class
<T = any> { private caches: { [key: string]: CacheItem<T> } = {} private count = 0 get length(): number { return this.count } // return Array<[key, {count: number, data: T}]> getAll(): Array<[string, CacheItem<T>]> { return Object.keys(this.caches).map( key => [key, this.caches[key]] as [string, CacheItem<T>], ) } clear(): void { this.caches = {} } has(key: string): boolean { return key in this.caches } set(key: string, value: T): void { const item = this.caches[key] if (item) { item.count++ item.data = value } else { this.caches[key] = { count: 1, data: value, } this.count++ } } get(key: string): T | null { const item = this.caches[key] if (item) { item.count++ return item.data } return null } remove(key: string): void { if (key in this.caches) { delete this.caches[key] this.count-- } } }
CountedCache
identifier_name
counted-cache.ts
export interface CacheItem<T> { count: number data: T } export class CountedCache<T = any> { private caches: { [key: string]: CacheItem<T> } = {} private count = 0 get length(): number { return this.count } // return Array<[key, {count: number, data: T}]> getAll(): Array<[string, CacheItem<T>]> { return Object.keys(this.caches).map( key => [key, this.caches[key]] as [string, CacheItem<T>], ) } clear(): void { this.caches = {} } has(key: string): boolean { return key in this.caches } set(key: string, value: T): void { const item = this.caches[key] if (item) { item.count++
count: 1, data: value, } this.count++ } } get(key: string): T | null { const item = this.caches[key] if (item) { item.count++ return item.data } return null } remove(key: string): void { if (key in this.caches) { delete this.caches[key] this.count-- } } }
item.data = value } else { this.caches[key] = {
random_line_split
counted-cache.ts
export interface CacheItem<T> { count: number data: T } export class CountedCache<T = any> { private caches: { [key: string]: CacheItem<T> } = {} private count = 0 get length(): number { return this.count } // return Array<[key, {count: number, data: T}]> getAll(): Array<[string, CacheItem<T>]> { return Object.keys(this.caches).map( key => [key, this.caches[key]] as [string, CacheItem<T>], ) } clear(): void { this.caches = {} } has(key: string): boolean { return key in this.caches } set(key: string, value: T): void { const item = this.caches[key] if (item) { item.count++ item.data = value } else { this.caches[key] = { count: 1, data: value, } this.count++ } } get(key: string): T | null { const item = this.caches[key] if (item)
return null } remove(key: string): void { if (key in this.caches) { delete this.caches[key] this.count-- } } }
{ item.count++ return item.data }
conditional_block
counted-cache.ts
export interface CacheItem<T> { count: number data: T } export class CountedCache<T = any> { private caches: { [key: string]: CacheItem<T> } = {} private count = 0 get length(): number { return this.count } // return Array<[key, {count: number, data: T}]> getAll(): Array<[string, CacheItem<T>]> { return Object.keys(this.caches).map( key => [key, this.caches[key]] as [string, CacheItem<T>], ) } clear(): void { this.caches = {} } has(key: string): boolean { return key in this.caches } set(key: string, value: T): void { const item = this.caches[key] if (item) { item.count++ item.data = value } else { this.caches[key] = { count: 1, data: value, } this.count++ } } get(key: string): T | null
remove(key: string): void { if (key in this.caches) { delete this.caches[key] this.count-- } } }
{ const item = this.caches[key] if (item) { item.count++ return item.data } return null }
identifier_body
default.py
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,sys import shutil import urllib2,urllib import re import extract import time import downloader import plugintools import zipfile import ntpath USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' base='' ADDON=xbmcaddon.Addon(id='plugin.video.mykodibuildwizard') dialog = xbmcgui.Dialog() VERSION = "1.0.1" PATH = "mykodibuildwizard" def CATEGORIES(): link = OPEN_URL('https://raw.githubusercontent.com/GhostTV/plugin.video.mykodibuildwizard/master/wizard.html').replace('\n','').replace('\r','') match = re.compile('name="(.+?)".+?rl="(.+?)".+?mg="(.+?)".+?anart="(.+?)".+?escription="(.+?)"').findall(link) for name,url,iconimage,fanart,description in match: addDir(name,url,1,iconimage,fanart,description) setView('movies', 'MAIN') def OPEN_URL(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') response = urllib2.urlopen(req) link=response.read() response.close() return link def wizard(name,url,description): path = xbmc.translatePath(os.path.join('special://home/addons','packages')) dp = xbmcgui.DialogProgress() dp.create("Husham Wizard","Downloading ",'', 'Please Wait') lib=os.path.join(path, name+'.zip') try: os.remove(lib) except: pass downloader.download(url, lib, dp) addonfolder = xbmc.translatePath(os.path.join('special://','home')) time.sleep(2) dp.update(0,"", "Extracting Zip Please Wait") print '=======================================' print addonfolder print '=======================================' extract.all(lib,addonfolder,dp) dialog = xbmcgui.Dialog() dialog.ok("DOWNLOAD COMPLETE", 'Unfortunately the only way to get the new changes to stick is', 'to force close kodi. Click ok to force Kodi to close,', 'DO NOT use the quit/exit options in Kodi., If the Force close does not close for some reason please Restart Device or kill task manaully') killxbmc() def killxbmc(): choice = xbmcgui.Dialog().yesno('Force Close Kodi', 'You are about to close Kodi', 'Would you like to continue?', nolabel='No, Cancel',yeslabel='Yes, Close') if choice == 0: return elif choice == 1: pass myplatform = platform() print "Platform: " + str(myplatform) if myplatform == 'osx': # OSX print "############ try osx force close #################" try: os.system('killall -9 XBMC') except: pass try: os.system('killall -9 Kodi') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'linux': #Linux print "############ try linux force close #################" try: os.system('killall XBMC') except: pass try: os.system('killall Kodi') except: pass try: os.system('killall -9 xbmc.bin') except: pass try: os.system('killall -9 kodi.bin') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'android': # Android print "############ try android force close #################" try: os.system('adb shell am force-stop org.xbmc.kodi') except: pass try: os.system('adb shell am force-stop org.kodi') except: pass try: os.system('adb shell am force-stop org.xbmc.xbmc') except: pass try: os.system('adb shell am force-stop org.xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "Your system has been detected as Android, you ", "[COLOR=yellow][B]MUST[/COLOR][/B] force close XBMC/Kodi. [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Either close using Task Manager (If unsure pull the plug).") elif myplatform == 'windows': # Windows print "############ try windows force close #################" try: os.system('@ECHO off') os.system('tskill XBMC.exe') except: pass try: os.system('@ECHO off') os.system('tskill Kodi.exe') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im Kodi.exe /f') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im XBMC.exe /f') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Use task manager and NOT ALT F4") else: #ATV print "############ try atv force close #################" try: os.system('killall AppleTV') except: pass print "############ try raspbmc force close #################" #OSMC / Raspbmc try: os.system('sudo initctl stop kodi') except: pass try: os.system('sudo initctl stop xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit via the menu.","Your platform could not be detected so just pull the power cable.") def platform(): if xbmc.getCondVisibility('system.platform.android'): return 'android' elif xbmc.getCondVisibility('system.platform.linux'): return 'linux' elif xbmc.getCondVisibility('system.platform.windows'): return 'windows' elif xbmc.getCondVisibility('system.platform.osx'): return 'osx' elif xbmc.getCondVisibility('system.platform.atv2'): return 'atv2' elif xbmc.getCondVisibility('system.platform.ios'): return 'ios' def addDir(name,url,mode,iconimage,fanart,description): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&fanart="+urllib.quote_plus(fanart)+"&description="+urllib.quote_plus(description) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description } ) liz.setProperty( "Fanart_Image", fanart ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False) return ok def get_params():
params=get_params() url=None name=None mode=None iconimage=None fanart=None description=None try: url=urllib.unquote_plus(params["url"]) except: pass try: name=urllib.unquote_plus(params["name"]) except: pass try: iconimage=urllib.unquote_plus(params["iconimage"]) except: pass try: mode=int(params["mode"]) except: pass try: fanart=urllib.unquote_plus(params["fanart"]) except: pass try: description=urllib.unquote_plus(params["description"]) except: pass print str(PATH)+': '+str(VERSION) print "Mode: "+str(mode) print "URL: "+str(url) print "Name: "+str(name) print "IconImage: "+str(iconimage) def setView(content, viewType): # set content type so library shows more views and info if content: xbmcplugin.setContent(int(sys.argv[1]), content) if ADDON.getSetting('auto-view')=='true': xbmc.executebuiltin("Container.SetViewMode(%s)" % ADDON.getSetting(viewType) ) if mode==None or url==None or len(url)<1: CATEGORIES() elif mode==1: wizard(name,url,description) xbmcplugin.endOfDirectory(int(sys.argv[1]))
param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=sys.argv[2] cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param
identifier_body
default.py
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,sys import shutil import urllib2,urllib import re import extract import time import downloader import plugintools import zipfile import ntpath USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' base='' ADDON=xbmcaddon.Addon(id='plugin.video.mykodibuildwizard') dialog = xbmcgui.Dialog() VERSION = "1.0.1" PATH = "mykodibuildwizard" def CATEGORIES(): link = OPEN_URL('https://raw.githubusercontent.com/GhostTV/plugin.video.mykodibuildwizard/master/wizard.html').replace('\n','').replace('\r','') match = re.compile('name="(.+?)".+?rl="(.+?)".+?mg="(.+?)".+?anart="(.+?)".+?escription="(.+?)"').findall(link) for name,url,iconimage,fanart,description in match: addDir(name,url,1,iconimage,fanart,description) setView('movies', 'MAIN') def OPEN_URL(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') response = urllib2.urlopen(req) link=response.read() response.close() return link def wizard(name,url,description): path = xbmc.translatePath(os.path.join('special://home/addons','packages')) dp = xbmcgui.DialogProgress() dp.create("Husham Wizard","Downloading ",'', 'Please Wait') lib=os.path.join(path, name+'.zip') try: os.remove(lib) except: pass downloader.download(url, lib, dp) addonfolder = xbmc.translatePath(os.path.join('special://','home')) time.sleep(2) dp.update(0,"", "Extracting Zip Please Wait") print '=======================================' print addonfolder print '=======================================' extract.all(lib,addonfolder,dp) dialog = xbmcgui.Dialog() dialog.ok("DOWNLOAD COMPLETE", 'Unfortunately the only way to get the new changes to stick is', 'to force close kodi. Click ok to force Kodi to close,', 'DO NOT use the quit/exit options in Kodi., If the Force close does not close for some reason please Restart Device or kill task manaully') killxbmc() def killxbmc(): choice = xbmcgui.Dialog().yesno('Force Close Kodi', 'You are about to close Kodi', 'Would you like to continue?', nolabel='No, Cancel',yeslabel='Yes, Close') if choice == 0: return elif choice == 1: pass myplatform = platform() print "Platform: " + str(myplatform) if myplatform == 'osx': # OSX print "############ try osx force close #################" try: os.system('killall -9 XBMC') except: pass try: os.system('killall -9 Kodi') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'linux': #Linux print "############ try linux force close #################" try: os.system('killall XBMC') except: pass try: os.system('killall Kodi') except: pass try: os.system('killall -9 xbmc.bin') except: pass try: os.system('killall -9 kodi.bin') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'android': # Android print "############ try android force close #################" try: os.system('adb shell am force-stop org.xbmc.kodi') except: pass try: os.system('adb shell am force-stop org.kodi') except: pass try: os.system('adb shell am force-stop org.xbmc.xbmc') except: pass try: os.system('adb shell am force-stop org.xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "Your system has been detected as Android, you ", "[COLOR=yellow][B]MUST[/COLOR][/B] force close XBMC/Kodi. [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Either close using Task Manager (If unsure pull the plug).") elif myplatform == 'windows': # Windows print "############ try windows force close #################" try: os.system('@ECHO off') os.system('tskill XBMC.exe') except: pass try: os.system('@ECHO off') os.system('tskill Kodi.exe') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im Kodi.exe /f') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im XBMC.exe /f') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Use task manager and NOT ALT F4") else: #ATV print "############ try atv force close #################" try: os.system('killall AppleTV') except: pass print "############ try raspbmc force close #################" #OSMC / Raspbmc try: os.system('sudo initctl stop kodi') except: pass try: os.system('sudo initctl stop xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit via the menu.","Your platform could not be detected so just pull the power cable.") def platform(): if xbmc.getCondVisibility('system.platform.android'): return 'android' elif xbmc.getCondVisibility('system.platform.linux'): return 'linux' elif xbmc.getCondVisibility('system.platform.windows'): return 'windows' elif xbmc.getCondVisibility('system.platform.osx'): return 'osx' elif xbmc.getCondVisibility('system.platform.atv2'): return 'atv2' elif xbmc.getCondVisibility('system.platform.ios'):
def addDir(name,url,mode,iconimage,fanart,description): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&fanart="+urllib.quote_plus(fanart)+"&description="+urllib.quote_plus(description) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description } ) liz.setProperty( "Fanart_Image", fanart ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False) return ok def get_params(): param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=sys.argv[2] cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param params=get_params() url=None name=None mode=None iconimage=None fanart=None description=None try: url=urllib.unquote_plus(params["url"]) except: pass try: name=urllib.unquote_plus(params["name"]) except: pass try: iconimage=urllib.unquote_plus(params["iconimage"]) except: pass try: mode=int(params["mode"]) except: pass try: fanart=urllib.unquote_plus(params["fanart"]) except: pass try: description=urllib.unquote_plus(params["description"]) except: pass print str(PATH)+': '+str(VERSION) print "Mode: "+str(mode) print "URL: "+str(url) print "Name: "+str(name) print "IconImage: "+str(iconimage) def setView(content, viewType): # set content type so library shows more views and info if content: xbmcplugin.setContent(int(sys.argv[1]), content) if ADDON.getSetting('auto-view')=='true': xbmc.executebuiltin("Container.SetViewMode(%s)" % ADDON.getSetting(viewType) ) if mode==None or url==None or len(url)<1: CATEGORIES() elif mode==1: wizard(name,url,description) xbmcplugin.endOfDirectory(int(sys.argv[1]))
return 'ios'
conditional_block
default.py
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,sys import shutil import urllib2,urllib import re import extract import time import downloader import plugintools import zipfile import ntpath USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' base='' ADDON=xbmcaddon.Addon(id='plugin.video.mykodibuildwizard') dialog = xbmcgui.Dialog() VERSION = "1.0.1" PATH = "mykodibuildwizard" def CATEGORIES(): link = OPEN_URL('https://raw.githubusercontent.com/GhostTV/plugin.video.mykodibuildwizard/master/wizard.html').replace('\n','').replace('\r','') match = re.compile('name="(.+?)".+?rl="(.+?)".+?mg="(.+?)".+?anart="(.+?)".+?escription="(.+?)"').findall(link) for name,url,iconimage,fanart,description in match: addDir(name,url,1,iconimage,fanart,description) setView('movies', 'MAIN') def OPEN_URL(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') response = urllib2.urlopen(req) link=response.read() response.close() return link def wizard(name,url,description): path = xbmc.translatePath(os.path.join('special://home/addons','packages')) dp = xbmcgui.DialogProgress() dp.create("Husham Wizard","Downloading ",'', 'Please Wait') lib=os.path.join(path, name+'.zip') try: os.remove(lib) except: pass downloader.download(url, lib, dp) addonfolder = xbmc.translatePath(os.path.join('special://','home')) time.sleep(2) dp.update(0,"", "Extracting Zip Please Wait") print '=======================================' print addonfolder print '=======================================' extract.all(lib,addonfolder,dp) dialog = xbmcgui.Dialog() dialog.ok("DOWNLOAD COMPLETE", 'Unfortunately the only way to get the new changes to stick is', 'to force close kodi. Click ok to force Kodi to close,', 'DO NOT use the quit/exit options in Kodi., If the Force close does not close for some reason please Restart Device or kill task manaully') killxbmc() def killxbmc(): choice = xbmcgui.Dialog().yesno('Force Close Kodi', 'You are about to close Kodi', 'Would you like to continue?', nolabel='No, Cancel',yeslabel='Yes, Close') if choice == 0: return elif choice == 1: pass myplatform = platform() print "Platform: " + str(myplatform) if myplatform == 'osx': # OSX print "############ try osx force close #################" try: os.system('killall -9 XBMC') except: pass try: os.system('killall -9 Kodi') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'linux': #Linux print "############ try linux force close #################" try: os.system('killall XBMC') except: pass try: os.system('killall Kodi') except: pass try: os.system('killall -9 xbmc.bin') except: pass try: os.system('killall -9 kodi.bin') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'android': # Android print "############ try android force close #################" try: os.system('adb shell am force-stop org.xbmc.kodi') except: pass try: os.system('adb shell am force-stop org.kodi') except: pass try: os.system('adb shell am force-stop org.xbmc.xbmc') except: pass try: os.system('adb shell am force-stop org.xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "Your system has been detected as Android, you ", "[COLOR=yellow][B]MUST[/COLOR][/B] force close XBMC/Kodi. [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Either close using Task Manager (If unsure pull the plug).") elif myplatform == 'windows': # Windows print "############ try windows force close #################" try: os.system('@ECHO off') os.system('tskill XBMC.exe') except: pass try: os.system('@ECHO off') os.system('tskill Kodi.exe') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im Kodi.exe /f') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im XBMC.exe /f') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Use task manager and NOT ALT F4") else: #ATV print "############ try atv force close #################" try: os.system('killall AppleTV') except: pass print "############ try raspbmc force close #################" #OSMC / Raspbmc try: os.system('sudo initctl stop kodi') except: pass try: os.system('sudo initctl stop xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit via the menu.","Your platform could not be detected so just pull the power cable.") def platform(): if xbmc.getCondVisibility('system.platform.android'): return 'android' elif xbmc.getCondVisibility('system.platform.linux'): return 'linux' elif xbmc.getCondVisibility('system.platform.windows'): return 'windows' elif xbmc.getCondVisibility('system.platform.osx'): return 'osx' elif xbmc.getCondVisibility('system.platform.atv2'): return 'atv2' elif xbmc.getCondVisibility('system.platform.ios'): return 'ios' def addDir(name,url,mode,iconimage,fanart,description): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&fanart="+urllib.quote_plus(fanart)+"&description="+urllib.quote_plus(description) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description } ) liz.setProperty( "Fanart_Image", fanart ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False) return ok def
(): param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=sys.argv[2] cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param params=get_params() url=None name=None mode=None iconimage=None fanart=None description=None try: url=urllib.unquote_plus(params["url"]) except: pass try: name=urllib.unquote_plus(params["name"]) except: pass try: iconimage=urllib.unquote_plus(params["iconimage"]) except: pass try: mode=int(params["mode"]) except: pass try: fanart=urllib.unquote_plus(params["fanart"]) except: pass try: description=urllib.unquote_plus(params["description"]) except: pass print str(PATH)+': '+str(VERSION) print "Mode: "+str(mode) print "URL: "+str(url) print "Name: "+str(name) print "IconImage: "+str(iconimage) def setView(content, viewType): # set content type so library shows more views and info if content: xbmcplugin.setContent(int(sys.argv[1]), content) if ADDON.getSetting('auto-view')=='true': xbmc.executebuiltin("Container.SetViewMode(%s)" % ADDON.getSetting(viewType) ) if mode==None or url==None or len(url)<1: CATEGORIES() elif mode==1: wizard(name,url,description) xbmcplugin.endOfDirectory(int(sys.argv[1]))
get_params
identifier_name
default.py
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,sys import shutil import urllib2,urllib import re import extract import time import downloader import plugintools import zipfile import ntpath USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' base='' ADDON=xbmcaddon.Addon(id='plugin.video.mykodibuildwizard') dialog = xbmcgui.Dialog() VERSION = "1.0.1" PATH = "mykodibuildwizard" def CATEGORIES(): link = OPEN_URL('https://raw.githubusercontent.com/GhostTV/plugin.video.mykodibuildwizard/master/wizard.html').replace('\n','').replace('\r','') match = re.compile('name="(.+?)".+?rl="(.+?)".+?mg="(.+?)".+?anart="(.+?)".+?escription="(.+?)"').findall(link) for name,url,iconimage,fanart,description in match: addDir(name,url,1,iconimage,fanart,description) setView('movies', 'MAIN') def OPEN_URL(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') response = urllib2.urlopen(req) link=response.read() response.close() return link def wizard(name,url,description): path = xbmc.translatePath(os.path.join('special://home/addons','packages')) dp = xbmcgui.DialogProgress() dp.create("Husham Wizard","Downloading ",'', 'Please Wait') lib=os.path.join(path, name+'.zip') try: os.remove(lib) except: pass downloader.download(url, lib, dp) addonfolder = xbmc.translatePath(os.path.join('special://','home')) time.sleep(2) dp.update(0,"", "Extracting Zip Please Wait") print '=======================================' print addonfolder print '=======================================' extract.all(lib,addonfolder,dp) dialog = xbmcgui.Dialog() dialog.ok("DOWNLOAD COMPLETE", 'Unfortunately the only way to get the new changes to stick is', 'to force close kodi. Click ok to force Kodi to close,', 'DO NOT use the quit/exit options in Kodi., If the Force close does not close for some reason please Restart Device or kill task manaully') killxbmc() def killxbmc(): choice = xbmcgui.Dialog().yesno('Force Close Kodi', 'You are about to close Kodi', 'Would you like to continue?', nolabel='No, Cancel',yeslabel='Yes, Close') if choice == 0: return elif choice == 1: pass myplatform = platform() print "Platform: " + str(myplatform) if myplatform == 'osx': # OSX print "############ try osx force close #################" try: os.system('killall -9 XBMC') except: pass try: os.system('killall -9 Kodi') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'linux': #Linux print "############ try linux force close #################" try: os.system('killall XBMC') except: pass try: os.system('killall Kodi') except: pass try: os.system('killall -9 xbmc.bin') except: pass try: os.system('killall -9 kodi.bin') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.",'') elif myplatform == 'android': # Android print "############ try android force close #################" try: os.system('adb shell am force-stop org.xbmc.kodi') except: pass try: os.system('adb shell am force-stop org.kodi') except: pass try: os.system('adb shell am force-stop org.xbmc.xbmc') except: pass try: os.system('adb shell am force-stop org.xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "Your system has been detected as Android, you ", "[COLOR=yellow][B]MUST[/COLOR][/B] force close XBMC/Kodi. [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Either close using Task Manager (If unsure pull the plug).") elif myplatform == 'windows': # Windows print "############ try windows force close #################" try: os.system('@ECHO off') os.system('tskill XBMC.exe') except: pass try: os.system('@ECHO off') os.system('tskill Kodi.exe') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im Kodi.exe /f') except: pass try: os.system('@ECHO off') os.system('TASKKILL /im XBMC.exe /f') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit cleanly via the menu.","Use task manager and NOT ALT F4") else: #ATV print "############ try atv force close #################" try: os.system('killall AppleTV') except: pass print "############ try raspbmc force close #################" #OSMC / Raspbmc try: os.system('sudo initctl stop kodi') except: pass try: os.system('sudo initctl stop xbmc') except: pass dialog.ok("[COLOR=red][B]WARNING !!![/COLOR][/B]", "If you\'re seeing this message it means the force close", "was unsuccessful. Please force close XBMC/Kodi [COLOR=lime]DO NOT[/COLOR] exit via the menu.","Your platform could not be detected so just pull the power cable.") def platform(): if xbmc.getCondVisibility('system.platform.android'): return 'android' elif xbmc.getCondVisibility('system.platform.linux'): return 'linux' elif xbmc.getCondVisibility('system.platform.windows'): return 'windows' elif xbmc.getCondVisibility('system.platform.osx'): return 'osx' elif xbmc.getCondVisibility('system.platform.atv2'): return 'atv2' elif xbmc.getCondVisibility('system.platform.ios'): return 'ios' def addDir(name,url,mode,iconimage,fanart,description): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&fanart="+urllib.quote_plus(fanart)+"&description="+urllib.quote_plus(description) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description } ) liz.setProperty( "Fanart_Image", fanart ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False) return ok def get_params():
cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param params=get_params() url=None name=None mode=None iconimage=None fanart=None description=None try: url=urllib.unquote_plus(params["url"]) except: pass try: name=urllib.unquote_plus(params["name"]) except: pass try: iconimage=urllib.unquote_plus(params["iconimage"]) except: pass try: mode=int(params["mode"]) except: pass try: fanart=urllib.unquote_plus(params["fanart"]) except: pass try: description=urllib.unquote_plus(params["description"]) except: pass print str(PATH)+': '+str(VERSION) print "Mode: "+str(mode) print "URL: "+str(url) print "Name: "+str(name) print "IconImage: "+str(iconimage) def setView(content, viewType): # set content type so library shows more views and info if content: xbmcplugin.setContent(int(sys.argv[1]), content) if ADDON.getSetting('auto-view')=='true': xbmc.executebuiltin("Container.SetViewMode(%s)" % ADDON.getSetting(viewType) ) if mode==None or url==None or len(url)<1: CATEGORIES() elif mode==1: wizard(name,url,description) xbmcplugin.endOfDirectory(int(sys.argv[1]))
param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=sys.argv[2]
random_line_split
BranchAnalysisList-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { subDays } from 'date-fns'; import { shallow } from 'enzyme'; import * as React from 'react'; import { getProjectActivity } from '../../../../api/projectActivity'; import { toShortNotSoISOString } from '../../../../helpers/dates'; import { mockAnalysis, mockAnalysisEvent } from '../../../../helpers/testMocks'; import { waitAndUpdate } from '../../../../helpers/testUtils'; import BranchAnalysisList from '../BranchAnalysisList'; jest.mock('date-fns', () => { const actual = jest.requireActual('date-fns'); return { ...actual, startOfDay: jest.fn(() => ({ getTime: () => '1488322800000' // 2017-03-02 })) }; }); jest.mock('../../../../helpers/dates', () => ({ parseDate: jest.fn().mockReturnValue('2017-03-02'), toShortNotSoISOString: jest.fn().mockReturnValue('2017-03-02') })); jest.mock('../../../../api/projectActivity', () => ({ getProjectActivity: jest.fn().mockResolvedValue({ analyses: [] }) })); beforeEach(() => { jest.clearAllMocks(); }); it('should render correctly', async () => { (getProjectActivity as jest.Mock).mockResolvedValue({ analyses: [ mockAnalysis({ key: '4', date: '2017-03-02T10:36:01', projectVersion: '4.2' }), mockAnalysis({ key: '3', date: '2017-03-02T09:36:01', events: [mockAnalysisEvent()], projectVersion: '4.2' }), mockAnalysis({ key: '2', date: '2017-03-02T08:36:01', events: [ mockAnalysisEvent(), mockAnalysisEvent({ category: 'VERSION', qualityGate: undefined }) ], projectVersion: '4.1' }), mockAnalysis({ key: '1', projectVersion: '4.1' }) ] }); const wrapper = shallowRender(); await waitAndUpdate(wrapper); expect(getProjectActivity).toBeCalled(); expect(wrapper.state().analyses).toHaveLength(4); }); it('should reload analyses after range change', () => { const wrapper = shallowRender(); wrapper.instance().handleRangeChange({ value: 30 }); expect(getProjectActivity).toBeCalledWith({ branch: 'master', project: 'project1', from: toShortNotSoISOString(subDays(new Date(), 30)) }); }); it('should register the badge nodes', () => { const wrapper = shallowRender(); const element = document.createElement('div'); wrapper.instance().registerBadgeNode('4.3')(element); expect(element.getAttribute('originOffsetTop')).not.toBeNull(); }); it('should handle scroll', () => { const wrapper = shallowRender(); wrapper.instance().handleScroll({ currentTarget: { scrollTop: 12 } } as any); expect(wrapper.state('scroll')).toBe(12); }); describe('shouldStick', () => { const wrapper = shallowRender(); wrapper.instance().badges['10.5'] = mockBadge('43'); wrapper.instance().badges['12.2'] = mockBadge('85'); it('should handle no badge', () => { expect(wrapper.instance().shouldStick('unknown version')).toBe(false); }); it('should return the correct result', () => { wrapper.setState({ scroll: 36 }); // => 46 with STICKY_BADGE_SCROLL_OFFSET = 10 expect(wrapper.instance().shouldStick('10.5')).toBe(true); expect(wrapper.instance().shouldStick('12.2')).toBe(false); }); }); function shallowRender(props: Partial<BranchAnalysisList['props']> = {})
function mockBadge(offsetTop: string) { const element = document.createElement('div'); element.setAttribute('originOffsetTop', offsetTop); return element; }
{ return shallow<BranchAnalysisList>( <BranchAnalysisList analysis="analysis1" branch="master" component="project1" onSelectAnalysis={jest.fn()} {...props} /> ); }
identifier_body
BranchAnalysisList-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { subDays } from 'date-fns'; import { shallow } from 'enzyme'; import * as React from 'react'; import { getProjectActivity } from '../../../../api/projectActivity'; import { toShortNotSoISOString } from '../../../../helpers/dates'; import { mockAnalysis, mockAnalysisEvent } from '../../../../helpers/testMocks'; import { waitAndUpdate } from '../../../../helpers/testUtils'; import BranchAnalysisList from '../BranchAnalysisList'; jest.mock('date-fns', () => { const actual = jest.requireActual('date-fns'); return { ...actual, startOfDay: jest.fn(() => ({ getTime: () => '1488322800000' // 2017-03-02 })) }; }); jest.mock('../../../../helpers/dates', () => ({ parseDate: jest.fn().mockReturnValue('2017-03-02'), toShortNotSoISOString: jest.fn().mockReturnValue('2017-03-02') })); jest.mock('../../../../api/projectActivity', () => ({ getProjectActivity: jest.fn().mockResolvedValue({ analyses: [] }) })); beforeEach(() => { jest.clearAllMocks(); }); it('should render correctly', async () => { (getProjectActivity as jest.Mock).mockResolvedValue({ analyses: [ mockAnalysis({ key: '4', date: '2017-03-02T10:36:01', projectVersion: '4.2' }), mockAnalysis({ key: '3', date: '2017-03-02T09:36:01', events: [mockAnalysisEvent()], projectVersion: '4.2' }), mockAnalysis({ key: '2', date: '2017-03-02T08:36:01', events: [ mockAnalysisEvent(), mockAnalysisEvent({ category: 'VERSION', qualityGate: undefined }) ], projectVersion: '4.1' }), mockAnalysis({ key: '1', projectVersion: '4.1' }) ] }); const wrapper = shallowRender(); await waitAndUpdate(wrapper); expect(getProjectActivity).toBeCalled(); expect(wrapper.state().analyses).toHaveLength(4); }); it('should reload analyses after range change', () => { const wrapper = shallowRender(); wrapper.instance().handleRangeChange({ value: 30 }); expect(getProjectActivity).toBeCalledWith({ branch: 'master', project: 'project1', from: toShortNotSoISOString(subDays(new Date(), 30)) }); }); it('should register the badge nodes', () => { const wrapper = shallowRender(); const element = document.createElement('div'); wrapper.instance().registerBadgeNode('4.3')(element); expect(element.getAttribute('originOffsetTop')).not.toBeNull(); }); it('should handle scroll', () => { const wrapper = shallowRender(); wrapper.instance().handleScroll({ currentTarget: { scrollTop: 12 } } as any); expect(wrapper.state('scroll')).toBe(12); }); describe('shouldStick', () => { const wrapper = shallowRender(); wrapper.instance().badges['10.5'] = mockBadge('43'); wrapper.instance().badges['12.2'] = mockBadge('85'); it('should handle no badge', () => { expect(wrapper.instance().shouldStick('unknown version')).toBe(false); }); it('should return the correct result', () => { wrapper.setState({ scroll: 36 }); // => 46 with STICKY_BADGE_SCROLL_OFFSET = 10 expect(wrapper.instance().shouldStick('10.5')).toBe(true); expect(wrapper.instance().shouldStick('12.2')).toBe(false); }); }); function shallowRender(props: Partial<BranchAnalysisList['props']> = {}) { return shallow<BranchAnalysisList>( <BranchAnalysisList analysis="analysis1" branch="master" component="project1" onSelectAnalysis={jest.fn()} {...props} /> ); } function
(offsetTop: string) { const element = document.createElement('div'); element.setAttribute('originOffsetTop', offsetTop); return element; }
mockBadge
identifier_name
BranchAnalysisList-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { subDays } from 'date-fns'; import { shallow } from 'enzyme'; import * as React from 'react'; import { getProjectActivity } from '../../../../api/projectActivity'; import { toShortNotSoISOString } from '../../../../helpers/dates'; import { mockAnalysis, mockAnalysisEvent } from '../../../../helpers/testMocks'; import { waitAndUpdate } from '../../../../helpers/testUtils'; import BranchAnalysisList from '../BranchAnalysisList'; jest.mock('date-fns', () => { const actual = jest.requireActual('date-fns'); return { ...actual, startOfDay: jest.fn(() => ({ getTime: () => '1488322800000' // 2017-03-02 })) }; }); jest.mock('../../../../helpers/dates', () => ({ parseDate: jest.fn().mockReturnValue('2017-03-02'), toShortNotSoISOString: jest.fn().mockReturnValue('2017-03-02') })); jest.mock('../../../../api/projectActivity', () => ({ getProjectActivity: jest.fn().mockResolvedValue({ analyses: [] }) })); beforeEach(() => { jest.clearAllMocks(); }); it('should render correctly', async () => { (getProjectActivity as jest.Mock).mockResolvedValue({ analyses: [ mockAnalysis({ key: '4', date: '2017-03-02T10:36:01', projectVersion: '4.2' }), mockAnalysis({ key: '3', date: '2017-03-02T09:36:01', events: [mockAnalysisEvent()], projectVersion: '4.2' }), mockAnalysis({ key: '2', date: '2017-03-02T08:36:01', events: [ mockAnalysisEvent(), mockAnalysisEvent({ category: 'VERSION', qualityGate: undefined }) ], projectVersion: '4.1' }), mockAnalysis({ key: '1', projectVersion: '4.1' }) ] }); const wrapper = shallowRender();
expect(wrapper.state().analyses).toHaveLength(4); }); it('should reload analyses after range change', () => { const wrapper = shallowRender(); wrapper.instance().handleRangeChange({ value: 30 }); expect(getProjectActivity).toBeCalledWith({ branch: 'master', project: 'project1', from: toShortNotSoISOString(subDays(new Date(), 30)) }); }); it('should register the badge nodes', () => { const wrapper = shallowRender(); const element = document.createElement('div'); wrapper.instance().registerBadgeNode('4.3')(element); expect(element.getAttribute('originOffsetTop')).not.toBeNull(); }); it('should handle scroll', () => { const wrapper = shallowRender(); wrapper.instance().handleScroll({ currentTarget: { scrollTop: 12 } } as any); expect(wrapper.state('scroll')).toBe(12); }); describe('shouldStick', () => { const wrapper = shallowRender(); wrapper.instance().badges['10.5'] = mockBadge('43'); wrapper.instance().badges['12.2'] = mockBadge('85'); it('should handle no badge', () => { expect(wrapper.instance().shouldStick('unknown version')).toBe(false); }); it('should return the correct result', () => { wrapper.setState({ scroll: 36 }); // => 46 with STICKY_BADGE_SCROLL_OFFSET = 10 expect(wrapper.instance().shouldStick('10.5')).toBe(true); expect(wrapper.instance().shouldStick('12.2')).toBe(false); }); }); function shallowRender(props: Partial<BranchAnalysisList['props']> = {}) { return shallow<BranchAnalysisList>( <BranchAnalysisList analysis="analysis1" branch="master" component="project1" onSelectAnalysis={jest.fn()} {...props} /> ); } function mockBadge(offsetTop: string) { const element = document.createElement('div'); element.setAttribute('originOffsetTop', offsetTop); return element; }
await waitAndUpdate(wrapper); expect(getProjectActivity).toBeCalled();
random_line_split
FileTransformsUtility.ts
import tl = require('azure-pipelines-task-lib/task'); import { parse } from './ParameterParserUtility'; import { PackageType } from '../webdeployment-common/packageUtility'; var deployUtility = require('../webdeployment-common/utility.js'); var generateWebConfigUtil = require('../webdeployment-common/webconfigutil.js'); export class FileTransformsUtility { private static rootDirectoryPath: string = "D:\\home\\site\\wwwroot"; public static async applyTransformations(webPackage: string, parameters: string, packageType: PackageType): Promise<string> { tl.debug("WebConfigParameters is "+ parameters); if (parameters)
else { tl.debug('File Tranformation not enabled'); } return webPackage; } }
{ var isFolderBasedDeployment: boolean = tl.stats(webPackage).isDirectory(); var folderPath = await deployUtility.generateTemporaryFolderForDeployment(isFolderBasedDeployment, webPackage, packageType); if (parameters) { tl.debug('parsing web.config parameters'); var webConfigParameters = parse(parameters); generateWebConfigUtil.addWebConfigFile(folderPath, webConfigParameters, this.rootDirectoryPath); } var output = await deployUtility.archiveFolderForDeployment(isFolderBasedDeployment, folderPath); webPackage = output.webDeployPkg; }
conditional_block
FileTransformsUtility.ts
import tl = require('azure-pipelines-task-lib/task'); import { parse } from './ParameterParserUtility'; import { PackageType } from '../webdeployment-common/packageUtility'; var deployUtility = require('../webdeployment-common/utility.js'); var generateWebConfigUtil = require('../webdeployment-common/webconfigutil.js'); export class FileTransformsUtility {
private static rootDirectoryPath: string = "D:\\home\\site\\wwwroot"; public static async applyTransformations(webPackage: string, parameters: string, packageType: PackageType): Promise<string> { tl.debug("WebConfigParameters is "+ parameters); if (parameters) { var isFolderBasedDeployment: boolean = tl.stats(webPackage).isDirectory(); var folderPath = await deployUtility.generateTemporaryFolderForDeployment(isFolderBasedDeployment, webPackage, packageType); if (parameters) { tl.debug('parsing web.config parameters'); var webConfigParameters = parse(parameters); generateWebConfigUtil.addWebConfigFile(folderPath, webConfigParameters, this.rootDirectoryPath); } var output = await deployUtility.archiveFolderForDeployment(isFolderBasedDeployment, folderPath); webPackage = output.webDeployPkg; } else { tl.debug('File Tranformation not enabled'); } return webPackage; } }
random_line_split
FileTransformsUtility.ts
import tl = require('azure-pipelines-task-lib/task'); import { parse } from './ParameterParserUtility'; import { PackageType } from '../webdeployment-common/packageUtility'; var deployUtility = require('../webdeployment-common/utility.js'); var generateWebConfigUtil = require('../webdeployment-common/webconfigutil.js'); export class
{ private static rootDirectoryPath: string = "D:\\home\\site\\wwwroot"; public static async applyTransformations(webPackage: string, parameters: string, packageType: PackageType): Promise<string> { tl.debug("WebConfigParameters is "+ parameters); if (parameters) { var isFolderBasedDeployment: boolean = tl.stats(webPackage).isDirectory(); var folderPath = await deployUtility.generateTemporaryFolderForDeployment(isFolderBasedDeployment, webPackage, packageType); if (parameters) { tl.debug('parsing web.config parameters'); var webConfigParameters = parse(parameters); generateWebConfigUtil.addWebConfigFile(folderPath, webConfigParameters, this.rootDirectoryPath); } var output = await deployUtility.archiveFolderForDeployment(isFolderBasedDeployment, folderPath); webPackage = output.webDeployPkg; } else { tl.debug('File Tranformation not enabled'); } return webPackage; } }
FileTransformsUtility
identifier_name
Security.ts
/** * @module Security * @preferred * @description Module for security related stuff */ /** */ // tslint:disable:naming-convention
/** * Provides metadata about permission level. */ export enum PermissionLevel { AllowedOrDenied, Allowed, Denied } /** * Type to provide an Object with the permission information that has to be set. */ export class PermissionRequestBody { public identity: string; public localOnly?: boolean; public RestrictedPreview?: PermissionValues; public PreviewWithoutWatermakr?: PermissionValues; public PreviewWithoutRedaction?: PermissionValues; public Open?: PermissionValues; public OpenMinor?: PermissionValues; public Save?: PermissionValues; public Publish?: PermissionValues; public ForceUndoCheckout?: PermissionValues; public AddNew?: PermissionValues; public Approve?: PermissionValues; public Delete?: PermissionValues; public RecallOldVersion?: PermissionValues; public DeleteOldVersion?: PermissionValues; public SeePermissions?: PermissionValues; public SetPermissions?: PermissionValues; public RunApplication?: PermissionValues; public ManageListsAndWorkspaces?: PermissionValues; public TakeOwnership?: PermissionValues; public Custom01?: PermissionValues; public Custom02?: PermissionValues; public Custom03?: PermissionValues; public Custom04?: PermissionValues; public Custom05?: PermissionValues; public Custom06?: PermissionValues; public Custom07?: PermissionValues; public Custom08?: PermissionValues; public Custom09?: PermissionValues; public Custom10?: PermissionValues; public Custom11?: PermissionValues; public Custom12?: PermissionValues; public Custom13?: PermissionValues; public Custom14?: PermissionValues; } /** * Provides metadata about permission values. */ export enum PermissionValues { undefined = 0, allow = 1, deny = 2 } /** * Provides metadata about permission inheritance. */ export enum Inheritance { 'break', 'unbreak' }
/** * Provides metadata about identity kind. */ export enum IdentityKind { All, Users, Groups, OrganizationalUnits, UsersAndGroups, UsersAndOrganizationalUnits, GroupsAndOrganizationalUnits }
random_line_split
Security.ts
/** * @module Security * @preferred * @description Module for security related stuff */ /** */ // tslint:disable:naming-convention /** * Provides metadata about identity kind. */ export enum IdentityKind { All, Users, Groups, OrganizationalUnits, UsersAndGroups, UsersAndOrganizationalUnits, GroupsAndOrganizationalUnits } /** * Provides metadata about permission level. */ export enum PermissionLevel { AllowedOrDenied, Allowed, Denied } /** * Type to provide an Object with the permission information that has to be set. */ export class
{ public identity: string; public localOnly?: boolean; public RestrictedPreview?: PermissionValues; public PreviewWithoutWatermakr?: PermissionValues; public PreviewWithoutRedaction?: PermissionValues; public Open?: PermissionValues; public OpenMinor?: PermissionValues; public Save?: PermissionValues; public Publish?: PermissionValues; public ForceUndoCheckout?: PermissionValues; public AddNew?: PermissionValues; public Approve?: PermissionValues; public Delete?: PermissionValues; public RecallOldVersion?: PermissionValues; public DeleteOldVersion?: PermissionValues; public SeePermissions?: PermissionValues; public SetPermissions?: PermissionValues; public RunApplication?: PermissionValues; public ManageListsAndWorkspaces?: PermissionValues; public TakeOwnership?: PermissionValues; public Custom01?: PermissionValues; public Custom02?: PermissionValues; public Custom03?: PermissionValues; public Custom04?: PermissionValues; public Custom05?: PermissionValues; public Custom06?: PermissionValues; public Custom07?: PermissionValues; public Custom08?: PermissionValues; public Custom09?: PermissionValues; public Custom10?: PermissionValues; public Custom11?: PermissionValues; public Custom12?: PermissionValues; public Custom13?: PermissionValues; public Custom14?: PermissionValues; } /** * Provides metadata about permission values. */ export enum PermissionValues { undefined = 0, allow = 1, deny = 2 } /** * Provides metadata about permission inheritance. */ export enum Inheritance { 'break', 'unbreak' }
PermissionRequestBody
identifier_name
CheckoutButton.tsx
import { PAYMENT_METHOD_TYPE, PAYMENT_METHOD_TYPES } from '@proton/shared/lib/constants'; import { c } from 'ttag'; import { SubscriptionCheckResponse } from '@proton/shared/lib/interfaces'; import { PrimaryButton, StyledPayPalButton } from '@proton/components'; import { SignupPayPal } from './interfaces'; interface Props { className?: string; paypal: SignupPayPal; canPay: boolean; loading: boolean; method?: PAYMENT_METHOD_TYPE; checkResult?: SubscriptionCheckResponse; } const CheckoutButton = ({ className, paypal, canPay, loading, method, checkResult }: Props) => { if (method === PAYMENT_METHOD_TYPES.PAYPAL) { return ( <StyledPayPalButton paypal={paypal} flow="signup" className={className} amount={checkResult ? checkResult.AmountDue : 0} /> ); } if (checkResult && !checkResult.AmountDue) { return (
<PrimaryButton className={className} loading={loading} disabled={!canPay} type="submit">{c('Action') .t`Confirm`}</PrimaryButton> ); } return ( <PrimaryButton className={className} loading={loading} disabled={!canPay} type="submit">{c('Action') .t`Pay`}</PrimaryButton> ); }; export default CheckoutButton;
random_line_split
mod.rs
//! Collectors will receive events from the contextual shard, check if the //! filter lets them pass, and collects if the receive, collect, or time limits //! are not reached yet. use std::sync::Arc; mod error; pub use error::Error as CollectorError; #[cfg(feature = "unstable_discord_api")] pub mod component_interaction_collector; pub mod event_collector; pub mod message_collector; pub mod reaction_collector; #[cfg(feature = "unstable_discord_api")] pub use component_interaction_collector::*; pub use event_collector::*; pub use message_collector::*; pub use reaction_collector::*; /// Wraps a &T and clones the value into an Arc<T> lazily. Used with collectors to allow inspecting
pub(crate) struct LazyArc<'a, T> { value: &'a T, arc: Option<Arc<T>>, } impl<'a, T: Clone> LazyArc<'a, T> { pub fn new(value: &'a T) -> Self { LazyArc { value, arc: None, } } pub fn as_arc(&mut self) -> Arc<T> { let value = self.value; self.arc.get_or_insert_with(|| Arc::new(value.clone())).clone() } } impl<'a, T> std::ops::Deref for LazyArc<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.value } }
/// the value in filters while only cloning values that actually match. #[derive(Debug)]
random_line_split
mod.rs
//! Collectors will receive events from the contextual shard, check if the //! filter lets them pass, and collects if the receive, collect, or time limits //! are not reached yet. use std::sync::Arc; mod error; pub use error::Error as CollectorError; #[cfg(feature = "unstable_discord_api")] pub mod component_interaction_collector; pub mod event_collector; pub mod message_collector; pub mod reaction_collector; #[cfg(feature = "unstable_discord_api")] pub use component_interaction_collector::*; pub use event_collector::*; pub use message_collector::*; pub use reaction_collector::*; /// Wraps a &T and clones the value into an Arc<T> lazily. Used with collectors to allow inspecting /// the value in filters while only cloning values that actually match. #[derive(Debug)] pub(crate) struct LazyArc<'a, T> { value: &'a T, arc: Option<Arc<T>>, } impl<'a, T: Clone> LazyArc<'a, T> { pub fn new(value: &'a T) -> Self { LazyArc { value, arc: None, } } pub fn as_arc(&mut self) -> Arc<T> { let value = self.value; self.arc.get_or_insert_with(|| Arc::new(value.clone())).clone() } } impl<'a, T> std::ops::Deref for LazyArc<'a, T> { type Target = T; fn deref(&self) -> &Self::Target
}
{ self.value }
identifier_body
mod.rs
//! Collectors will receive events from the contextual shard, check if the //! filter lets them pass, and collects if the receive, collect, or time limits //! are not reached yet. use std::sync::Arc; mod error; pub use error::Error as CollectorError; #[cfg(feature = "unstable_discord_api")] pub mod component_interaction_collector; pub mod event_collector; pub mod message_collector; pub mod reaction_collector; #[cfg(feature = "unstable_discord_api")] pub use component_interaction_collector::*; pub use event_collector::*; pub use message_collector::*; pub use reaction_collector::*; /// Wraps a &T and clones the value into an Arc<T> lazily. Used with collectors to allow inspecting /// the value in filters while only cloning values that actually match. #[derive(Debug)] pub(crate) struct LazyArc<'a, T> { value: &'a T, arc: Option<Arc<T>>, } impl<'a, T: Clone> LazyArc<'a, T> { pub fn new(value: &'a T) -> Self { LazyArc { value, arc: None, } } pub fn
(&mut self) -> Arc<T> { let value = self.value; self.arc.get_or_insert_with(|| Arc::new(value.clone())).clone() } } impl<'a, T> std::ops::Deref for LazyArc<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.value } }
as_arc
identifier_name
rgb-effect.js
function
() { this.canvas = new MEDIA.Canvas(); this.name = 'RGBEffect'; this.controls = { RedThreshold: { value: 128, min: 0, max: 255, step: 2 } }; } RGBEffect.prototype = { draw: function () { var canvas = this.canvas; var redThreshold = this.controls.RedThreshold.value; APP.drawImage(canvas); var img = canvas.getImageData(); var data = img.data; // Pixel data here // 0 red : 1st pixel (0 - 255) // 1 green : 1st pixel // 2 blue : 1st pixel // 3 alpha : 1st pixel // 4 red : 2nd pixel // 5 green : 2nd pixel // 6 blue : 2nd pixel // 7 alpha : 2nd pixel for (var i = 0, len = data.length; i < len; i += 4) { var r = data[i]; // data[i] = r > redThreshold ? r : 0; if (r > redThreshold) { data[i] = r; } else { data[i] = 0; } } canvas.putImageData(img); } };
RGBEffect
identifier_name
rgb-effect.js
function RGBEffect() { this.canvas = new MEDIA.Canvas(); this.name = 'RGBEffect'; this.controls = { RedThreshold: { value: 128, min: 0, max: 255, step: 2 } }; } RGBEffect.prototype = { draw: function () { var canvas = this.canvas; var redThreshold = this.controls.RedThreshold.value; APP.drawImage(canvas); var img = canvas.getImageData(); var data = img.data; // Pixel data here // 0 red : 1st pixel (0 - 255) // 1 green : 1st pixel // 2 blue : 1st pixel // 3 alpha : 1st pixel // 4 red : 2nd pixel // 5 green : 2nd pixel // 6 blue : 2nd pixel // 7 alpha : 2nd pixel for (var i = 0, len = data.length; i < len; i += 4) { var r = data[i]; // data[i] = r > redThreshold ? r : 0; if (r > redThreshold)
else { data[i] = 0; } } canvas.putImageData(img); } };
{ data[i] = r; }
conditional_block
rgb-effect.js
function RGBEffect() { this.canvas = new MEDIA.Canvas(); this.name = 'RGBEffect'; this.controls = { RedThreshold: { value: 128, min: 0, max: 255, step: 2 } }; } RGBEffect.prototype = { draw: function () { var canvas = this.canvas;
var img = canvas.getImageData(); var data = img.data; // Pixel data here // 0 red : 1st pixel (0 - 255) // 1 green : 1st pixel // 2 blue : 1st pixel // 3 alpha : 1st pixel // 4 red : 2nd pixel // 5 green : 2nd pixel // 6 blue : 2nd pixel // 7 alpha : 2nd pixel for (var i = 0, len = data.length; i < len; i += 4) { var r = data[i]; // data[i] = r > redThreshold ? r : 0; if (r > redThreshold) { data[i] = r; } else { data[i] = 0; } } canvas.putImageData(img); } };
var redThreshold = this.controls.RedThreshold.value; APP.drawImage(canvas);
random_line_split
rgb-effect.js
function RGBEffect()
RGBEffect.prototype = { draw: function () { var canvas = this.canvas; var redThreshold = this.controls.RedThreshold.value; APP.drawImage(canvas); var img = canvas.getImageData(); var data = img.data; // Pixel data here // 0 red : 1st pixel (0 - 255) // 1 green : 1st pixel // 2 blue : 1st pixel // 3 alpha : 1st pixel // 4 red : 2nd pixel // 5 green : 2nd pixel // 6 blue : 2nd pixel // 7 alpha : 2nd pixel for (var i = 0, len = data.length; i < len; i += 4) { var r = data[i]; // data[i] = r > redThreshold ? r : 0; if (r > redThreshold) { data[i] = r; } else { data[i] = 0; } } canvas.putImageData(img); } };
{ this.canvas = new MEDIA.Canvas(); this.name = 'RGBEffect'; this.controls = { RedThreshold: { value: 128, min: 0, max: 255, step: 2 } }; }
identifier_body
character-select.js
import {Buttons} from '../game/input'; import {Menu, MenuPage, ButtonMenuItem, LabelMenuItem} from './menu'; import {DummyInputTarget, ProxyInputTarget} from '../player'; import StageSelectMenuPage from './stage-selection'; import React from 'react'; import {BabylonJS} from '../react-babylonjs'; import BABYLON from 'babylonjs'; import {render} from 'react-dom'; import MenuCamera from '../game/menuCamera'; export const heroesContext = require.context('../game/heroes', false, /\.js$/); export const heroKeys = heroesContext.keys().filter(key => key !== './baseHero.js'); const styles = { viewBlock: { display: 'flex', flexDirection: 'row', }, playerViewFullBlock: { margin: '20px', }, playerViewBlock: { border: '3px solid black', backgroundColor: '#fefefe', height: '220px', width: '220px', }, playerViewBlockText: { fontSize: '1.2em', fontWeight: '700', padding: '10px 5px 10px 5px', backgroundColor: '#fefefe', border: '4px solid black', }, lockedInText: { fontSize: '1.5em', fontWeight: '800', padding: '10px 5px 10px 5px', backgroundColor: '#66ff66', border: '4px solid black', }, }; class StageMenuPlayer extends React.Component { constructor(props) { super(props); this.state = { active: false, lockedIn: false, characterIndex: 0, }; this.props.input.setTarget(Object.assign(new DummyInputTarget(), { buttonDown: button => { if (this.state.active) { switch (button) { case Buttons.A: this.setState({ lockedIn: true, }); break; case Buttons.B: if (this.state.lockedIn) { this.setState({ lockedIn: false, }); } else { this.setState({ active: false, }); } } if (!this.state.lockedIn) { let changeHeroNumber = 0; switch (button) { case Buttons.JoyLeft: changeHeroNumber = -1; break; case Buttons.JoyRight: changeHeroNumber = 1; break; } if (changeHeroNumber != 0) { let newCharacterindex = (this.state.characterIndex + changeHeroNumber) % heroKeys.length; if (newCharacterindex < 0) { newCharacterindex = heroKeys.length - 1; } this.setState({ characterIndex: newCharacterindex, }); //console.log(this.state.character) this.loadDiffScene(); } } } else { // If not active switch (button) { case Buttons.A: this.setState({ active: true, }); break; case Buttons.B: this.props.wantsBack(); break; } } }, })); } componentDidUpdate() { this.props.stateChanged(); } get active() { return this.state.active; } get characterIndex() { return this.state.characterIndex; } get lockedIn() { return this.state.lockedIn; } doRenderLoop() { this.scene.render(); } loadDiffScene() { if (this.mesh) { this.mesh.dispose(); } //loadMenuScene(this, 1); require(`../../models/heroes/${heroesContext(heroKeys[this.state.characterIndex]).heroName}.blend`).ImportMesh(BABYLON.SceneLoader, null, this.scene, loadedMeshes => { this.mesh = loadedMeshes[0];//.clone(this.name); this.mesh.position.y -= 3; console.log('props', this.props); let id = this.props.player.index; console.log(id); let material = new BABYLON.StandardMaterial(id + 'playermaterialscene', this.scene); let colId = function (id, mult) { return Math.abs(((id * mult) % 255) / 255); } let color = new BABYLON.Color3(colId(id + .1, 50), colId(id + .2, -100), colId(id + 1, 200)); console.log(color); material.diffuseColor = color; material.specularColor = new BABYLON.Color3(1, 1, 1); this.mesh.material = material; let idleAnimation = this.mesh.skeleton.getAnimationRange('idle'); this.scene.beginAnimation(this.mesh.skeleton, idleAnimation.from+1, idleAnimation.to, true, 1); }); } onEngineCreated(engine) { this.engine = engine; engine.runRenderLoop(this.handleRenderLoop = () => this.doRenderLoop()); this.scene = new BABYLON.Scene(this.engine); let camera = new MenuCamera(this, {min:7, max:9}); let dirLight = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(1, -.7, 0), this.scene); let dirLightStrength = 1; dirLight.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLight.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLightStrength = .8; let dirLight2 = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(-1, -.3, .4), this.scene); dirLight2.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLight2.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); this.scene.clearColor = new BABYLON.Color3(.7, .7, .7); this.loadDiffScene(); } onEngineAbandoned() { this.engine.stopRenderLoop(this.handleRenderLoop); this.handleRenderLoop = null; this.engine = null; } render() { if (this.state.active) { return <div style={styles.playerViewFullBlock}> <p style={styles.playerViewBlockText}> {this.props.player.name} </p> <div style={styles.playerViewBlock}> <BabylonJS onEngineCreated={engine => this.onEngineCreated(engine)} onEngineAbandoned={engine => this.onEngineAbandoned(engine)}/> <p style={styles.playerViewBlockText}> {heroesContext(heroKeys[this.state.characterIndex]).heroName} </p> {this.state.lockedIn && <p style={styles.lockedInText}> LOCKED IN </p> } </div> </div>; } return <div> <p style={styles.playerViewBlockText}>{this.props.player.name} <br/>Press [attack1] to join.</p> </div> } } export default class CharacterSelectMenuPage extends React.Component { constructor(props) { super(props); this.state = { players: [], }; this.playerRefs = []; } playerAskedForBack() { // Only go back out of this menu if all players are inactive. console.log(this); if (this.playerRefs.find(p => p.active)) { return; } this.props.menu.popMenuPage(); } playerStateChanged() { console.log('Player state changed'); if (!this.playerRefs.find(p => p.active && !p.lockedIn) && this.playerRefs.find(p => p.active && p.lockedIn)) { console.log('Start Game'); console.log(this.playerRefs); const playerInfo = this.playerRefs.reduce((acc, val, i) => { if (val.active) { acc[i] = { characterIndex: val.characterIndex, }; }
componentDidMount() { this.props.players.setInputTargetFinder((i, player) => { const proxy = new ProxyInputTarget(new DummyInputTarget()); // setState is not synchronous. To mutate an array in it multiple // times before it applies the state update to this.state, must // use the callback pattern: http://stackoverflow.com/a/41445812 this.setState(state => { console.log(JSON.stringify(state.newPlayers)); const newPlayers = state.players.slice(); newPlayers[i] = <StageMenuPlayer key={i} player={player} input={proxy} ref={playerRef => this.playerRefs[i] = playerRef} wantsBack={() => this.playerAskedForBack()} stateChanged={() => this.playerStateChanged()} />; return { players: newPlayers, }; }); return proxy; }); } render() { return <div className="menu-page" style={styles.viewBlock}> {this.state.players.filter(player => player)} </div>; } }
return acc; }, {}); this.props.menu.pushMenuPage(<StageSelectMenuPage game={this.props.game} playerInfo={playerInfo}/>); } }
random_line_split
character-select.js
import {Buttons} from '../game/input'; import {Menu, MenuPage, ButtonMenuItem, LabelMenuItem} from './menu'; import {DummyInputTarget, ProxyInputTarget} from '../player'; import StageSelectMenuPage from './stage-selection'; import React from 'react'; import {BabylonJS} from '../react-babylonjs'; import BABYLON from 'babylonjs'; import {render} from 'react-dom'; import MenuCamera from '../game/menuCamera'; export const heroesContext = require.context('../game/heroes', false, /\.js$/); export const heroKeys = heroesContext.keys().filter(key => key !== './baseHero.js'); const styles = { viewBlock: { display: 'flex', flexDirection: 'row', }, playerViewFullBlock: { margin: '20px', }, playerViewBlock: { border: '3px solid black', backgroundColor: '#fefefe', height: '220px', width: '220px', }, playerViewBlockText: { fontSize: '1.2em', fontWeight: '700', padding: '10px 5px 10px 5px', backgroundColor: '#fefefe', border: '4px solid black', }, lockedInText: { fontSize: '1.5em', fontWeight: '800', padding: '10px 5px 10px 5px', backgroundColor: '#66ff66', border: '4px solid black', }, }; class StageMenuPlayer extends React.Component { constructor(props) { super(props); this.state = { active: false, lockedIn: false, characterIndex: 0, }; this.props.input.setTarget(Object.assign(new DummyInputTarget(), { buttonDown: button => { if (this.state.active) { switch (button) { case Buttons.A: this.setState({ lockedIn: true, }); break; case Buttons.B: if (this.state.lockedIn) { this.setState({ lockedIn: false, }); } else { this.setState({ active: false, }); } } if (!this.state.lockedIn) { let changeHeroNumber = 0; switch (button) { case Buttons.JoyLeft: changeHeroNumber = -1; break; case Buttons.JoyRight: changeHeroNumber = 1; break; } if (changeHeroNumber != 0) { let newCharacterindex = (this.state.characterIndex + changeHeroNumber) % heroKeys.length; if (newCharacterindex < 0) { newCharacterindex = heroKeys.length - 1; } this.setState({ characterIndex: newCharacterindex, }); //console.log(this.state.character) this.loadDiffScene(); } } } else { // If not active switch (button) { case Buttons.A: this.setState({ active: true, }); break; case Buttons.B: this.props.wantsBack(); break; } } }, })); } componentDidUpdate() { this.props.stateChanged(); } get active() { return this.state.active; } get characterIndex() { return this.state.characterIndex; } get lockedIn() { return this.state.lockedIn; } doRenderLoop() { this.scene.render(); } loadDiffScene() { if (this.mesh) { this.mesh.dispose(); } //loadMenuScene(this, 1); require(`../../models/heroes/${heroesContext(heroKeys[this.state.characterIndex]).heroName}.blend`).ImportMesh(BABYLON.SceneLoader, null, this.scene, loadedMeshes => { this.mesh = loadedMeshes[0];//.clone(this.name); this.mesh.position.y -= 3; console.log('props', this.props); let id = this.props.player.index; console.log(id); let material = new BABYLON.StandardMaterial(id + 'playermaterialscene', this.scene); let colId = function (id, mult) { return Math.abs(((id * mult) % 255) / 255); } let color = new BABYLON.Color3(colId(id + .1, 50), colId(id + .2, -100), colId(id + 1, 200)); console.log(color); material.diffuseColor = color; material.specularColor = new BABYLON.Color3(1, 1, 1); this.mesh.material = material; let idleAnimation = this.mesh.skeleton.getAnimationRange('idle'); this.scene.beginAnimation(this.mesh.skeleton, idleAnimation.from+1, idleAnimation.to, true, 1); }); } onEngineCreated(engine) { this.engine = engine; engine.runRenderLoop(this.handleRenderLoop = () => this.doRenderLoop()); this.scene = new BABYLON.Scene(this.engine); let camera = new MenuCamera(this, {min:7, max:9}); let dirLight = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(1, -.7, 0), this.scene); let dirLightStrength = 1; dirLight.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLight.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLightStrength = .8; let dirLight2 = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(-1, -.3, .4), this.scene); dirLight2.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLight2.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); this.scene.clearColor = new BABYLON.Color3(.7, .7, .7); this.loadDiffScene(); } onEngineAbandoned() { this.engine.stopRenderLoop(this.handleRenderLoop); this.handleRenderLoop = null; this.engine = null; } render() { if (this.state.active) { return <div style={styles.playerViewFullBlock}> <p style={styles.playerViewBlockText}> {this.props.player.name} </p> <div style={styles.playerViewBlock}> <BabylonJS onEngineCreated={engine => this.onEngineCreated(engine)} onEngineAbandoned={engine => this.onEngineAbandoned(engine)}/> <p style={styles.playerViewBlockText}> {heroesContext(heroKeys[this.state.characterIndex]).heroName} </p> {this.state.lockedIn && <p style={styles.lockedInText}> LOCKED IN </p> } </div> </div>; } return <div> <p style={styles.playerViewBlockText}>{this.props.player.name} <br/>Press [attack1] to join.</p> </div> } } export default class CharacterSelectMenuPage extends React.Component {
(props) { super(props); this.state = { players: [], }; this.playerRefs = []; } playerAskedForBack() { // Only go back out of this menu if all players are inactive. console.log(this); if (this.playerRefs.find(p => p.active)) { return; } this.props.menu.popMenuPage(); } playerStateChanged() { console.log('Player state changed'); if (!this.playerRefs.find(p => p.active && !p.lockedIn) && this.playerRefs.find(p => p.active && p.lockedIn)) { console.log('Start Game'); console.log(this.playerRefs); const playerInfo = this.playerRefs.reduce((acc, val, i) => { if (val.active) { acc[i] = { characterIndex: val.characterIndex, }; } return acc; }, {}); this.props.menu.pushMenuPage(<StageSelectMenuPage game={this.props.game} playerInfo={playerInfo}/>); } } componentDidMount() { this.props.players.setInputTargetFinder((i, player) => { const proxy = new ProxyInputTarget(new DummyInputTarget()); // setState is not synchronous. To mutate an array in it multiple // times before it applies the state update to this.state, must // use the callback pattern: http://stackoverflow.com/a/41445812 this.setState(state => { console.log(JSON.stringify(state.newPlayers)); const newPlayers = state.players.slice(); newPlayers[i] = <StageMenuPlayer key={i} player={player} input={proxy} ref={playerRef => this.playerRefs[i] = playerRef} wantsBack={() => this.playerAskedForBack()} stateChanged={() => this.playerStateChanged()} />; return { players: newPlayers, }; }); return proxy; }); } render() { return <div className="menu-page" style={styles.viewBlock}> {this.state.players.filter(player => player)} </div>; } }
constructor
identifier_name
character-select.js
import {Buttons} from '../game/input'; import {Menu, MenuPage, ButtonMenuItem, LabelMenuItem} from './menu'; import {DummyInputTarget, ProxyInputTarget} from '../player'; import StageSelectMenuPage from './stage-selection'; import React from 'react'; import {BabylonJS} from '../react-babylonjs'; import BABYLON from 'babylonjs'; import {render} from 'react-dom'; import MenuCamera from '../game/menuCamera'; export const heroesContext = require.context('../game/heroes', false, /\.js$/); export const heroKeys = heroesContext.keys().filter(key => key !== './baseHero.js'); const styles = { viewBlock: { display: 'flex', flexDirection: 'row', }, playerViewFullBlock: { margin: '20px', }, playerViewBlock: { border: '3px solid black', backgroundColor: '#fefefe', height: '220px', width: '220px', }, playerViewBlockText: { fontSize: '1.2em', fontWeight: '700', padding: '10px 5px 10px 5px', backgroundColor: '#fefefe', border: '4px solid black', }, lockedInText: { fontSize: '1.5em', fontWeight: '800', padding: '10px 5px 10px 5px', backgroundColor: '#66ff66', border: '4px solid black', }, }; class StageMenuPlayer extends React.Component { constructor(props) { super(props); this.state = { active: false, lockedIn: false, characterIndex: 0, }; this.props.input.setTarget(Object.assign(new DummyInputTarget(), { buttonDown: button => { if (this.state.active) { switch (button) { case Buttons.A: this.setState({ lockedIn: true, }); break; case Buttons.B: if (this.state.lockedIn) { this.setState({ lockedIn: false, }); } else { this.setState({ active: false, }); } } if (!this.state.lockedIn) { let changeHeroNumber = 0; switch (button) { case Buttons.JoyLeft: changeHeroNumber = -1; break; case Buttons.JoyRight: changeHeroNumber = 1; break; } if (changeHeroNumber != 0) { let newCharacterindex = (this.state.characterIndex + changeHeroNumber) % heroKeys.length; if (newCharacterindex < 0) { newCharacterindex = heroKeys.length - 1; } this.setState({ characterIndex: newCharacterindex, }); //console.log(this.state.character) this.loadDiffScene(); } } } else { // If not active switch (button) { case Buttons.A: this.setState({ active: true, }); break; case Buttons.B: this.props.wantsBack(); break; } } }, })); } componentDidUpdate() { this.props.stateChanged(); } get active() { return this.state.active; } get characterIndex() { return this.state.characterIndex; } get lockedIn() { return this.state.lockedIn; } doRenderLoop() { this.scene.render(); } loadDiffScene() { if (this.mesh) { this.mesh.dispose(); } //loadMenuScene(this, 1); require(`../../models/heroes/${heroesContext(heroKeys[this.state.characterIndex]).heroName}.blend`).ImportMesh(BABYLON.SceneLoader, null, this.scene, loadedMeshes => { this.mesh = loadedMeshes[0];//.clone(this.name); this.mesh.position.y -= 3; console.log('props', this.props); let id = this.props.player.index; console.log(id); let material = new BABYLON.StandardMaterial(id + 'playermaterialscene', this.scene); let colId = function (id, mult) { return Math.abs(((id * mult) % 255) / 255); } let color = new BABYLON.Color3(colId(id + .1, 50), colId(id + .2, -100), colId(id + 1, 200)); console.log(color); material.diffuseColor = color; material.specularColor = new BABYLON.Color3(1, 1, 1); this.mesh.material = material; let idleAnimation = this.mesh.skeleton.getAnimationRange('idle'); this.scene.beginAnimation(this.mesh.skeleton, idleAnimation.from+1, idleAnimation.to, true, 1); }); } onEngineCreated(engine) { this.engine = engine; engine.runRenderLoop(this.handleRenderLoop = () => this.doRenderLoop()); this.scene = new BABYLON.Scene(this.engine); let camera = new MenuCamera(this, {min:7, max:9}); let dirLight = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(1, -.7, 0), this.scene); let dirLightStrength = 1; dirLight.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLight.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLightStrength = .8; let dirLight2 = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(-1, -.3, .4), this.scene); dirLight2.diffuse = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); dirLight2.specular = new BABYLON.Color3(dirLightStrength,dirLightStrength,dirLightStrength); this.scene.clearColor = new BABYLON.Color3(.7, .7, .7); this.loadDiffScene(); } onEngineAbandoned() { this.engine.stopRenderLoop(this.handleRenderLoop); this.handleRenderLoop = null; this.engine = null; } render() { if (this.state.active) { return <div style={styles.playerViewFullBlock}> <p style={styles.playerViewBlockText}> {this.props.player.name} </p> <div style={styles.playerViewBlock}> <BabylonJS onEngineCreated={engine => this.onEngineCreated(engine)} onEngineAbandoned={engine => this.onEngineAbandoned(engine)}/> <p style={styles.playerViewBlockText}> {heroesContext(heroKeys[this.state.characterIndex]).heroName} </p> {this.state.lockedIn && <p style={styles.lockedInText}> LOCKED IN </p> } </div> </div>; } return <div> <p style={styles.playerViewBlockText}>{this.props.player.name} <br/>Press [attack1] to join.</p> </div> } } export default class CharacterSelectMenuPage extends React.Component { constructor(props) { super(props); this.state = { players: [], }; this.playerRefs = []; } playerAskedForBack() { // Only go back out of this menu if all players are inactive. console.log(this); if (this.playerRefs.find(p => p.active)) { return; } this.props.menu.popMenuPage(); } playerStateChanged() { console.log('Player state changed'); if (!this.playerRefs.find(p => p.active && !p.lockedIn) && this.playerRefs.find(p => p.active && p.lockedIn)) { console.log('Start Game'); console.log(this.playerRefs); const playerInfo = this.playerRefs.reduce((acc, val, i) => { if (val.active) { acc[i] = { characterIndex: val.characterIndex, }; } return acc; }, {}); this.props.menu.pushMenuPage(<StageSelectMenuPage game={this.props.game} playerInfo={playerInfo}/>); } } componentDidMount()
render() { return <div className="menu-page" style={styles.viewBlock}> {this.state.players.filter(player => player)} </div>; } }
{ this.props.players.setInputTargetFinder((i, player) => { const proxy = new ProxyInputTarget(new DummyInputTarget()); // setState is not synchronous. To mutate an array in it multiple // times before it applies the state update to this.state, must // use the callback pattern: http://stackoverflow.com/a/41445812 this.setState(state => { console.log(JSON.stringify(state.newPlayers)); const newPlayers = state.players.slice(); newPlayers[i] = <StageMenuPlayer key={i} player={player} input={proxy} ref={playerRef => this.playerRefs[i] = playerRef} wantsBack={() => this.playerAskedForBack()} stateChanged={() => this.playerStateChanged()} />; return { players: newPlayers, }; }); return proxy; }); }
identifier_body
printer.py
# coding=utf-8 __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' from flask import request, jsonify, make_response import re from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, restricted_access, NO_CONTENT from octoprint.server.api import api import octoprint.util as util #~~ Printer @api.route("/printer", methods=["GET"]) def printerState(): if not printer.isOperational(): return make_response("Printer is not operational", 409) # process excludes excludes = [] if "exclude" in request.values: excludeStr = request.values["exclude"] if len(excludeStr.strip()) > 0: excludes = filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(","))) result = {} # add temperature information if not "temperature" in excludes: result.update({"temperature": _getTemperatureData(lambda x: x)}) # add sd information if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]): result.update({"sd": {"ready": printer.isSdReady()}}) # add state information if not "state" in excludes: state = printer.getCurrentData()["state"] result.update({"state": state}) return jsonify(result) #~~ Tool @api.route("/printer/tool", methods=["POST"]) @restricted_access def printerToolCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "select": ["tool"], "target": ["targets"], "offset": ["offsets"], "extrude": ["amount"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response validation_regex = re.compile("tool\d+") ##~~ tool selection if command == "select": tool = data["tool"] if re.match(validation_regex, tool) is None: return make_response("Invalid tool: %s" % tool, 400) if not tool.startswith("tool"): return make_response("Invalid tool for selection: %s" % tool, 400) printer.changeTool(tool) ##~~ temperature elif command == "target": targets = data["targets"] # make sure the targets are valid and the values are numbers validated_values = {} for tool, value in targets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) validated_values[tool] = value # perform the actual temperature commands for tool in validated_values.keys(): printer.setTemperature(tool, validated_values[tool]) ##~~ temperature offset elif command == "offset": offsets = data["offsets"] # make sure the targets are valid, the values are numbers and in the range [-50, 50] validated_values = {} for tool, value in offsets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) if not -50 <= value <= 50: return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400) validated_values[tool] = value # set the offsets printer.setTemperatureOffset(validated_values) ##~~ extrusion elif command == "extrude": if printer.isPrinting(): # do not extrude when a print job is running return make_response("Printer is currently printing", 409) amount = data["amount"] if not isinstance(amount, (int, long, float)): return make_response("Not a number for extrusion amount: %r" % amount, 400) printer.extrude(amount) return NO_CONTENT @api.route("/printer/tool", methods=["GET"]) def printerToolState(): def deleteBed(x): data = dict(x) if "bed" in data.keys(): del data["bed"] return data return jsonify(_getTemperatureData(deleteBed)) ##~~ Heated bed @api.route("/printer/bed", methods=["POST"]) @restricted_access def printerBedCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "target": ["target"], "offset": ["offset"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response ##~~ temperature if command == "target": target = data["target"] # make sure the target is a number if not isinstance(target, (int, long, float)): return make_response("Not a number: %r" % target, 400) # perform the actual temperature command printer.setTemperature("bed", target) ##~~ temperature offset elif command == "offset": of
return NO_CONTENT @api.route("/printer/bed", methods=["GET"]) def printerBedState(): def deleteTools(x): data = dict(x) for k in data.keys(): if k.startswith("tool"): del data[k] return data return jsonify(_getTemperatureData(deleteTools)) ##~~ Print head @api.route("/printer/printhead", methods=["POST"]) @restricted_access def printerPrintheadCommand(): if not printer.isOperational() or printer.isPrinting(): # do not jog when a print job is running or we don't have a connection return make_response("Printer is not operational or currently printing", 409) valid_commands = { "jog": [], "home": ["axes"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response valid_axes = ["x", "y", "z"] ##~~ jog command if command == "jog": # validate all jog instructions, make sure that the values are numbers validated_values = {} for axis in valid_axes: if axis in data: value = data[axis] if not isinstance(value, (int, long, float)): return make_response("Not a number for axis %s: %r" % (axis, value), 400) validated_values[axis] = value # execute the jog commands for axis, value in validated_values.iteritems(): printer.jog(axis, value) ##~~ home command elif command == "home": validated_values = [] axes = data["axes"] for axis in axes: if not axis in valid_axes: return make_response("Invalid axis: %s" % axis, 400) validated_values.append(axis) # execute the home command printer.home(validated_values) return NO_CONTENT ##~~ SD Card @api.route("/printer/sd", methods=["POST"]) @restricted_access def printerSdCommand(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) if not printer.isOperational() or printer.isPrinting() or printer.isPaused(): return make_response("Printer is not operational or currently busy", 409) valid_commands = { "init": [], "refresh": [], "release": [] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response if command == "init": printer.initSdCard() elif command == "refresh": printer.refreshSdFiles() elif command == "release": printer.releaseSdCard() return NO_CONTENT @api.route("/printer/sd", methods=["GET"]) def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) return jsonify(ready=printer.isSdReady()) ##~~ Commands @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): # TODO: document me if not printer.isOperational(): return make_response("Printer is not operational", 409) if not "application/json" in request.headers["Content-Type"]: return make_response("Expected content type JSON", 400) data = request.json parameters = {} if "parameters" in data.keys(): parameters = data["parameters"] commands = [] if "command" in data.keys(): commands = [data["command"]] elif "commands" in data.keys(): commands = data["commands"] commandsToSend = [] for command in commands: commandToSend = command if len(parameters) > 0: commandToSend = command % parameters commandsToSend.append(commandToSend) printer.commands(commandsToSend) return NO_CONTENT @api.route("/printer/command/custom", methods=["GET"]) def getCustomControls(): # TODO: document me customControls = settings().get(["controls"]) return jsonify(controls=customControls) def _getTemperatureData(filter): if not printer.isOperational(): return make_response("Printer is not operational", 409) tempData = printer.getCurrentTemperatures() result = { "temps": filter(tempData) } if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues: tempHistory = printer.getTemperatureHistory() limit = 300 if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric(): limit = int(request.values["limit"]) history = list(tempHistory) limit = min(limit, len(history)) result.update({ "history": map(lambda x: filter(x), history[-limit:]) }) return result
fset = data["offset"] # make sure the offset is valid if not isinstance(offset, (int, long, float)): return make_response("Not a number: %r" % offset, 400) if not -50 <= offset <= 50: return make_response("Offset not in range [-50, 50]: %f" % offset, 400) # set the offsets printer.setTemperatureOffset({"bed": offset})
conditional_block
printer.py
# coding=utf-8 __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' from flask import request, jsonify, make_response import re from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, restricted_access, NO_CONTENT from octoprint.server.api import api import octoprint.util as util #~~ Printer @api.route("/printer", methods=["GET"]) def printerState(): if not printer.isOperational(): return make_response("Printer is not operational", 409) # process excludes excludes = [] if "exclude" in request.values: excludeStr = request.values["exclude"] if len(excludeStr.strip()) > 0: excludes = filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(","))) result = {} # add temperature information if not "temperature" in excludes: result.update({"temperature": _getTemperatureData(lambda x: x)}) # add sd information if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]): result.update({"sd": {"ready": printer.isSdReady()}}) # add state information if not "state" in excludes: state = printer.getCurrentData()["state"] result.update({"state": state}) return jsonify(result) #~~ Tool @api.route("/printer/tool", methods=["POST"]) @restricted_access def printerToolCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "select": ["tool"], "target": ["targets"], "offset": ["offsets"], "extrude": ["amount"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response validation_regex = re.compile("tool\d+") ##~~ tool selection if command == "select": tool = data["tool"] if re.match(validation_regex, tool) is None: return make_response("Invalid tool: %s" % tool, 400) if not tool.startswith("tool"): return make_response("Invalid tool for selection: %s" % tool, 400) printer.changeTool(tool) ##~~ temperature elif command == "target": targets = data["targets"] # make sure the targets are valid and the values are numbers validated_values = {} for tool, value in targets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) validated_values[tool] = value # perform the actual temperature commands for tool in validated_values.keys(): printer.setTemperature(tool, validated_values[tool]) ##~~ temperature offset elif command == "offset": offsets = data["offsets"] # make sure the targets are valid, the values are numbers and in the range [-50, 50] validated_values = {} for tool, value in offsets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) if not -50 <= value <= 50: return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400) validated_values[tool] = value # set the offsets printer.setTemperatureOffset(validated_values) ##~~ extrusion elif command == "extrude": if printer.isPrinting(): # do not extrude when a print job is running return make_response("Printer is currently printing", 409) amount = data["amount"] if not isinstance(amount, (int, long, float)): return make_response("Not a number for extrusion amount: %r" % amount, 400) printer.extrude(amount) return NO_CONTENT @api.route("/printer/tool", methods=["GET"]) def printerToolState(): def deleteBed(x): data = dict(x) if "bed" in data.keys(): del data["bed"] return data return jsonify(_getTemperatureData(deleteBed)) ##~~ Heated bed @api.route("/printer/bed", methods=["POST"]) @restricted_access def printerBedCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "target": ["target"], "offset": ["offset"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response ##~~ temperature if command == "target": target = data["target"] # make sure the target is a number if not isinstance(target, (int, long, float)): return make_response("Not a number: %r" % target, 400) # perform the actual temperature command printer.setTemperature("bed", target) ##~~ temperature offset elif command == "offset": offset = data["offset"] # make sure the offset is valid if not isinstance(offset, (int, long, float)): return make_response("Not a number: %r" % offset, 400) if not -50 <= offset <= 50: return make_response("Offset not in range [-50, 50]: %f" % offset, 400) # set the offsets printer.setTemperatureOffset({"bed": offset}) return NO_CONTENT @api.route("/printer/bed", methods=["GET"]) def printerBedState(): def de
): data = dict(x) for k in data.keys(): if k.startswith("tool"): del data[k] return data return jsonify(_getTemperatureData(deleteTools)) ##~~ Print head @api.route("/printer/printhead", methods=["POST"]) @restricted_access def printerPrintheadCommand(): if not printer.isOperational() or printer.isPrinting(): # do not jog when a print job is running or we don't have a connection return make_response("Printer is not operational or currently printing", 409) valid_commands = { "jog": [], "home": ["axes"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response valid_axes = ["x", "y", "z"] ##~~ jog command if command == "jog": # validate all jog instructions, make sure that the values are numbers validated_values = {} for axis in valid_axes: if axis in data: value = data[axis] if not isinstance(value, (int, long, float)): return make_response("Not a number for axis %s: %r" % (axis, value), 400) validated_values[axis] = value # execute the jog commands for axis, value in validated_values.iteritems(): printer.jog(axis, value) ##~~ home command elif command == "home": validated_values = [] axes = data["axes"] for axis in axes: if not axis in valid_axes: return make_response("Invalid axis: %s" % axis, 400) validated_values.append(axis) # execute the home command printer.home(validated_values) return NO_CONTENT ##~~ SD Card @api.route("/printer/sd", methods=["POST"]) @restricted_access def printerSdCommand(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) if not printer.isOperational() or printer.isPrinting() or printer.isPaused(): return make_response("Printer is not operational or currently busy", 409) valid_commands = { "init": [], "refresh": [], "release": [] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response if command == "init": printer.initSdCard() elif command == "refresh": printer.refreshSdFiles() elif command == "release": printer.releaseSdCard() return NO_CONTENT @api.route("/printer/sd", methods=["GET"]) def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) return jsonify(ready=printer.isSdReady()) ##~~ Commands @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): # TODO: document me if not printer.isOperational(): return make_response("Printer is not operational", 409) if not "application/json" in request.headers["Content-Type"]: return make_response("Expected content type JSON", 400) data = request.json parameters = {} if "parameters" in data.keys(): parameters = data["parameters"] commands = [] if "command" in data.keys(): commands = [data["command"]] elif "commands" in data.keys(): commands = data["commands"] commandsToSend = [] for command in commands: commandToSend = command if len(parameters) > 0: commandToSend = command % parameters commandsToSend.append(commandToSend) printer.commands(commandsToSend) return NO_CONTENT @api.route("/printer/command/custom", methods=["GET"]) def getCustomControls(): # TODO: document me customControls = settings().get(["controls"]) return jsonify(controls=customControls) def _getTemperatureData(filter): if not printer.isOperational(): return make_response("Printer is not operational", 409) tempData = printer.getCurrentTemperatures() result = { "temps": filter(tempData) } if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues: tempHistory = printer.getTemperatureHistory() limit = 300 if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric(): limit = int(request.values["limit"]) history = list(tempHistory) limit = min(limit, len(history)) result.update({ "history": map(lambda x: filter(x), history[-limit:]) }) return result
leteTools(x
identifier_name
printer.py
# coding=utf-8 __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' from flask import request, jsonify, make_response import re from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, restricted_access, NO_CONTENT from octoprint.server.api import api import octoprint.util as util #~~ Printer @api.route("/printer", methods=["GET"]) def printerState(): if not printer.isOperational(): return make_response("Printer is not operational", 409) # process excludes excludes = [] if "exclude" in request.values: excludeStr = request.values["exclude"] if len(excludeStr.strip()) > 0: excludes = filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(","))) result = {} # add temperature information if not "temperature" in excludes: result.update({"temperature": _getTemperatureData(lambda x: x)}) # add sd information if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]): result.update({"sd": {"ready": printer.isSdReady()}}) # add state information if not "state" in excludes: state = printer.getCurrentData()["state"] result.update({"state": state}) return jsonify(result) #~~ Tool @api.route("/printer/tool", methods=["POST"]) @restricted_access def printerToolCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "select": ["tool"], "target": ["targets"], "offset": ["offsets"], "extrude": ["amount"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response validation_regex = re.compile("tool\d+") ##~~ tool selection if command == "select": tool = data["tool"] if re.match(validation_regex, tool) is None: return make_response("Invalid tool: %s" % tool, 400) if not tool.startswith("tool"): return make_response("Invalid tool for selection: %s" % tool, 400) printer.changeTool(tool) ##~~ temperature elif command == "target": targets = data["targets"] # make sure the targets are valid and the values are numbers validated_values = {} for tool, value in targets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) validated_values[tool] = value
elif command == "offset": offsets = data["offsets"] # make sure the targets are valid, the values are numbers and in the range [-50, 50] validated_values = {} for tool, value in offsets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) if not -50 <= value <= 50: return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400) validated_values[tool] = value # set the offsets printer.setTemperatureOffset(validated_values) ##~~ extrusion elif command == "extrude": if printer.isPrinting(): # do not extrude when a print job is running return make_response("Printer is currently printing", 409) amount = data["amount"] if not isinstance(amount, (int, long, float)): return make_response("Not a number for extrusion amount: %r" % amount, 400) printer.extrude(amount) return NO_CONTENT @api.route("/printer/tool", methods=["GET"]) def printerToolState(): def deleteBed(x): data = dict(x) if "bed" in data.keys(): del data["bed"] return data return jsonify(_getTemperatureData(deleteBed)) ##~~ Heated bed @api.route("/printer/bed", methods=["POST"]) @restricted_access def printerBedCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "target": ["target"], "offset": ["offset"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response ##~~ temperature if command == "target": target = data["target"] # make sure the target is a number if not isinstance(target, (int, long, float)): return make_response("Not a number: %r" % target, 400) # perform the actual temperature command printer.setTemperature("bed", target) ##~~ temperature offset elif command == "offset": offset = data["offset"] # make sure the offset is valid if not isinstance(offset, (int, long, float)): return make_response("Not a number: %r" % offset, 400) if not -50 <= offset <= 50: return make_response("Offset not in range [-50, 50]: %f" % offset, 400) # set the offsets printer.setTemperatureOffset({"bed": offset}) return NO_CONTENT @api.route("/printer/bed", methods=["GET"]) def printerBedState(): def deleteTools(x): data = dict(x) for k in data.keys(): if k.startswith("tool"): del data[k] return data return jsonify(_getTemperatureData(deleteTools)) ##~~ Print head @api.route("/printer/printhead", methods=["POST"]) @restricted_access def printerPrintheadCommand(): if not printer.isOperational() or printer.isPrinting(): # do not jog when a print job is running or we don't have a connection return make_response("Printer is not operational or currently printing", 409) valid_commands = { "jog": [], "home": ["axes"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response valid_axes = ["x", "y", "z"] ##~~ jog command if command == "jog": # validate all jog instructions, make sure that the values are numbers validated_values = {} for axis in valid_axes: if axis in data: value = data[axis] if not isinstance(value, (int, long, float)): return make_response("Not a number for axis %s: %r" % (axis, value), 400) validated_values[axis] = value # execute the jog commands for axis, value in validated_values.iteritems(): printer.jog(axis, value) ##~~ home command elif command == "home": validated_values = [] axes = data["axes"] for axis in axes: if not axis in valid_axes: return make_response("Invalid axis: %s" % axis, 400) validated_values.append(axis) # execute the home command printer.home(validated_values) return NO_CONTENT ##~~ SD Card @api.route("/printer/sd", methods=["POST"]) @restricted_access def printerSdCommand(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) if not printer.isOperational() or printer.isPrinting() or printer.isPaused(): return make_response("Printer is not operational or currently busy", 409) valid_commands = { "init": [], "refresh": [], "release": [] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response if command == "init": printer.initSdCard() elif command == "refresh": printer.refreshSdFiles() elif command == "release": printer.releaseSdCard() return NO_CONTENT @api.route("/printer/sd", methods=["GET"]) def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) return jsonify(ready=printer.isSdReady()) ##~~ Commands @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): # TODO: document me if not printer.isOperational(): return make_response("Printer is not operational", 409) if not "application/json" in request.headers["Content-Type"]: return make_response("Expected content type JSON", 400) data = request.json parameters = {} if "parameters" in data.keys(): parameters = data["parameters"] commands = [] if "command" in data.keys(): commands = [data["command"]] elif "commands" in data.keys(): commands = data["commands"] commandsToSend = [] for command in commands: commandToSend = command if len(parameters) > 0: commandToSend = command % parameters commandsToSend.append(commandToSend) printer.commands(commandsToSend) return NO_CONTENT @api.route("/printer/command/custom", methods=["GET"]) def getCustomControls(): # TODO: document me customControls = settings().get(["controls"]) return jsonify(controls=customControls) def _getTemperatureData(filter): if not printer.isOperational(): return make_response("Printer is not operational", 409) tempData = printer.getCurrentTemperatures() result = { "temps": filter(tempData) } if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues: tempHistory = printer.getTemperatureHistory() limit = 300 if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric(): limit = int(request.values["limit"]) history = list(tempHistory) limit = min(limit, len(history)) result.update({ "history": map(lambda x: filter(x), history[-limit:]) }) return result
# perform the actual temperature commands for tool in validated_values.keys(): printer.setTemperature(tool, validated_values[tool]) ##~~ temperature offset
random_line_split
printer.py
# coding=utf-8 __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' from flask import request, jsonify, make_response import re from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, restricted_access, NO_CONTENT from octoprint.server.api import api import octoprint.util as util #~~ Printer @api.route("/printer", methods=["GET"]) def printerState(): if not printer.isOperational(): return make_response("Printer is not operational", 409) # process excludes excludes = [] if "exclude" in request.values: excludeStr = request.values["exclude"] if len(excludeStr.strip()) > 0: excludes = filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(","))) result = {} # add temperature information if not "temperature" in excludes: result.update({"temperature": _getTemperatureData(lambda x: x)}) # add sd information if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]): result.update({"sd": {"ready": printer.isSdReady()}}) # add state information if not "state" in excludes: state = printer.getCurrentData()["state"] result.update({"state": state}) return jsonify(result) #~~ Tool @api.route("/printer/tool", methods=["POST"]) @restricted_access def printerToolCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "select": ["tool"], "target": ["targets"], "offset": ["offsets"], "extrude": ["amount"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response validation_regex = re.compile("tool\d+") ##~~ tool selection if command == "select": tool = data["tool"] if re.match(validation_regex, tool) is None: return make_response("Invalid tool: %s" % tool, 400) if not tool.startswith("tool"): return make_response("Invalid tool for selection: %s" % tool, 400) printer.changeTool(tool) ##~~ temperature elif command == "target": targets = data["targets"] # make sure the targets are valid and the values are numbers validated_values = {} for tool, value in targets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) validated_values[tool] = value # perform the actual temperature commands for tool in validated_values.keys(): printer.setTemperature(tool, validated_values[tool]) ##~~ temperature offset elif command == "offset": offsets = data["offsets"] # make sure the targets are valid, the values are numbers and in the range [-50, 50] validated_values = {} for tool, value in offsets.iteritems(): if re.match(validation_regex, tool) is None: return make_response("Invalid target for setting temperature: %s" % tool, 400) if not isinstance(value, (int, long, float)): return make_response("Not a number for %s: %r" % (tool, value), 400) if not -50 <= value <= 50: return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400) validated_values[tool] = value # set the offsets printer.setTemperatureOffset(validated_values) ##~~ extrusion elif command == "extrude": if printer.isPrinting(): # do not extrude when a print job is running return make_response("Printer is currently printing", 409) amount = data["amount"] if not isinstance(amount, (int, long, float)): return make_response("Not a number for extrusion amount: %r" % amount, 400) printer.extrude(amount) return NO_CONTENT @api.route("/printer/tool", methods=["GET"]) def printerToolState(): def deleteBed(x): data = dict(x) if "bed" in data.keys(): del data["bed"] return data return jsonify(_getTemperatureData(deleteBed)) ##~~ Heated bed @api.route("/printer/bed", methods=["POST"]) @restricted_access def printerBedCommand(): if not printer.isOperational(): return make_response("Printer is not operational", 409) valid_commands = { "target": ["target"], "offset": ["offset"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response ##~~ temperature if command == "target": target = data["target"] # make sure the target is a number if not isinstance(target, (int, long, float)): return make_response("Not a number: %r" % target, 400) # perform the actual temperature command printer.setTemperature("bed", target) ##~~ temperature offset elif command == "offset": offset = data["offset"] # make sure the offset is valid if not isinstance(offset, (int, long, float)): return make_response("Not a number: %r" % offset, 400) if not -50 <= offset <= 50: return make_response("Offset not in range [-50, 50]: %f" % offset, 400) # set the offsets printer.setTemperatureOffset({"bed": offset}) return NO_CONTENT @api.route("/printer/bed", methods=["GET"]) def printerBedState(): def deleteTools(x): data = dict(x) for k in data.keys(): if k.startswith("tool"): del data[k] return data return jsonify(_getTemperatureData(deleteTools)) ##~~ Print head @api.route("/printer/printhead", methods=["POST"]) @restricted_access def printerPrintheadCommand(): if not printer.isOperational() or printer.isPrinting(): # do not jog when a print job is running or we don't have a connection return make_response("Printer is not operational or currently printing", 409) valid_commands = { "jog": [], "home": ["axes"] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response valid_axes = ["x", "y", "z"] ##~~ jog command if command == "jog": # validate all jog instructions, make sure that the values are numbers validated_values = {} for axis in valid_axes: if axis in data: value = data[axis] if not isinstance(value, (int, long, float)): return make_response("Not a number for axis %s: %r" % (axis, value), 400) validated_values[axis] = value # execute the jog commands for axis, value in validated_values.iteritems(): printer.jog(axis, value) ##~~ home command elif command == "home": validated_values = [] axes = data["axes"] for axis in axes: if not axis in valid_axes: return make_response("Invalid axis: %s" % axis, 400) validated_values.append(axis) # execute the home command printer.home(validated_values) return NO_CONTENT ##~~ SD Card @api.route("/printer/sd", methods=["POST"]) @restricted_access def printerSdCommand(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) if not printer.isOperational() or printer.isPrinting() or printer.isPaused(): return make_response("Printer is not operational or currently busy", 409) valid_commands = { "init": [], "refresh": [], "release": [] } command, data, response = util.getJsonCommandFromRequest(request, valid_commands) if response is not None: return response if command == "init": printer.initSdCard() elif command == "refresh": printer.refreshSdFiles() elif command == "release": printer.releaseSdCard() return NO_CONTENT @api.route("/printer/sd", methods=["GET"]) def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) return jsonify(ready=printer.isSdReady()) ##~~ Commands @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): # TODO: document me if not printer.isOperational(): return make_response("Printer is not operational", 409) if not "application/json" in request.headers["Content-Type"]: return make_response("Expected content type JSON", 400) data = request.json parameters = {} if "parameters" in data.keys(): parameters = data["parameters"] commands = [] if "command" in data.keys(): commands = [data["command"]] elif "commands" in data.keys(): commands = data["commands"] commandsToSend = [] for command in commands: commandToSend = command if len(parameters) > 0: commandToSend = command % parameters commandsToSend.append(commandToSend) printer.commands(commandsToSend) return NO_CONTENT @api.route("/printer/command/custom", methods=["GET"]) def getCustomControls(): # TODO: document me customControls = settings().get(["controls"]) return jsonify(controls=customControls) def _getTemperatureData(filter): if
not printer.isOperational(): return make_response("Printer is not operational", 409) tempData = printer.getCurrentTemperatures() result = { "temps": filter(tempData) } if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues: tempHistory = printer.getTemperatureHistory() limit = 300 if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric(): limit = int(request.values["limit"]) history = list(tempHistory) limit = min(limit, len(history)) result.update({ "history": map(lambda x: filter(x), history[-limit:]) }) return result
identifier_body
bibauthorid_prob_matrix.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. import bibauthorid_config as bconfig from bibauthorid_comparison import compare_bibrefrecs from bibauthorid_comparison import clear_all_caches as clear_comparison_caches from bibauthorid_backinterface import bib_matrix from bibauthorid_backinterface import get_sql_time from bibauthorid_backinterface import filter_modified_record_ids from bibauthorid_general_utils import update_status \ , update_status_final if bconfig.DEBUG_CHECKS: def _debug_is_eq(v1, v2): eps = 1e-2 return v1 + eps > v2 and v2 + eps > v1 def _debug_is_eq_v(vl1, vl2): if isinstance(vl1, str) and isinstance(vl2, str): return vl1 == vl2 if isinstance(vl1, tuple) and isinstance(vl2, tuple): return _debug_is_eq(vl1[0], vl2[0]) and _debug_is_eq(vl1[1], vl2[1]) return False class probability_matrix: ''' This class contains and maintains the comparison between all virtual authors. It is able to write and read from the database and update the results. ''' def
(self, cluster_set, use_cache=False, save_cache=False): ''' Constructs probability matrix. If use_cache is true, it will try to load old computations from the database. If save cache is true it will save the current results into the database. @param cluster_set: A cluster set object, used to initialize the matrix. ''' def check_for_cleaning(cur_calc): if cur_calc % 10000000 == 0: clear_comparison_caches() self._bib_matrix = bib_matrix(cluster_set) old_matrix = bib_matrix() ncl = sum(len(cl.bibs) for cl in cluster_set.clusters) expected = ((ncl * (ncl - 1)) / 2) if expected == 0: expected = 1 if use_cache and old_matrix.load(cluster_set.last_name): cached_bibs = set(filter_modified_record_ids( old_matrix.get_keys(), old_matrix.creation_time)) else: cached_bibs = set() if save_cache: creation_time = get_sql_time() cur_calc, opti = 0, 0 for cl1 in cluster_set.clusters: update_status((float(opti) + cur_calc) / expected, "Prob matrix: calc %d, opti %d." % (cur_calc, opti)) for cl2 in cluster_set.clusters: if id(cl1) < id(cl2) and not cl1.hates(cl2): for bib1 in cl1.bibs: for bib2 in cl2.bibs: if bib1 in cached_bibs and bib2 in cached_bibs: val = old_matrix[bib1, bib2] if not val: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) else: opti += 1 if bconfig.DEBUG_CHECKS: assert _debug_is_eq_v(val, compare_bibrefrecs(bib1, bib2)) else: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) self._bib_matrix[bib1, bib2] = val clear_comparison_caches() if save_cache: update_status(1., "saving...") self._bib_matrix.store(cluster_set.last_name, creation_time) update_status_final("Matrix done. %d calc, %d opt." % (cur_calc, opti)) def __getitem__(self, bibs): return self._bib_matrix[bibs[0], bibs[1]]
__init__
identifier_name
bibauthorid_prob_matrix.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. import bibauthorid_config as bconfig from bibauthorid_comparison import compare_bibrefrecs from bibauthorid_comparison import clear_all_caches as clear_comparison_caches from bibauthorid_backinterface import bib_matrix from bibauthorid_backinterface import get_sql_time from bibauthorid_backinterface import filter_modified_record_ids from bibauthorid_general_utils import update_status \ , update_status_final if bconfig.DEBUG_CHECKS: def _debug_is_eq(v1, v2): eps = 1e-2 return v1 + eps > v2 and v2 + eps > v1 def _debug_is_eq_v(vl1, vl2): if isinstance(vl1, str) and isinstance(vl2, str): return vl1 == vl2 if isinstance(vl1, tuple) and isinstance(vl2, tuple): return _debug_is_eq(vl1[0], vl2[0]) and _debug_is_eq(vl1[1], vl2[1]) return False class probability_matrix: ''' This class contains and maintains the comparison between all virtual authors. It is able to write and read from the database and update the results. ''' def __init__(self, cluster_set, use_cache=False, save_cache=False):
def __getitem__(self, bibs): return self._bib_matrix[bibs[0], bibs[1]]
''' Constructs probability matrix. If use_cache is true, it will try to load old computations from the database. If save cache is true it will save the current results into the database. @param cluster_set: A cluster set object, used to initialize the matrix. ''' def check_for_cleaning(cur_calc): if cur_calc % 10000000 == 0: clear_comparison_caches() self._bib_matrix = bib_matrix(cluster_set) old_matrix = bib_matrix() ncl = sum(len(cl.bibs) for cl in cluster_set.clusters) expected = ((ncl * (ncl - 1)) / 2) if expected == 0: expected = 1 if use_cache and old_matrix.load(cluster_set.last_name): cached_bibs = set(filter_modified_record_ids( old_matrix.get_keys(), old_matrix.creation_time)) else: cached_bibs = set() if save_cache: creation_time = get_sql_time() cur_calc, opti = 0, 0 for cl1 in cluster_set.clusters: update_status((float(opti) + cur_calc) / expected, "Prob matrix: calc %d, opti %d." % (cur_calc, opti)) for cl2 in cluster_set.clusters: if id(cl1) < id(cl2) and not cl1.hates(cl2): for bib1 in cl1.bibs: for bib2 in cl2.bibs: if bib1 in cached_bibs and bib2 in cached_bibs: val = old_matrix[bib1, bib2] if not val: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) else: opti += 1 if bconfig.DEBUG_CHECKS: assert _debug_is_eq_v(val, compare_bibrefrecs(bib1, bib2)) else: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) self._bib_matrix[bib1, bib2] = val clear_comparison_caches() if save_cache: update_status(1., "saving...") self._bib_matrix.store(cluster_set.last_name, creation_time) update_status_final("Matrix done. %d calc, %d opt." % (cur_calc, opti))
identifier_body
bibauthorid_prob_matrix.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. import bibauthorid_config as bconfig from bibauthorid_comparison import compare_bibrefrecs from bibauthorid_comparison import clear_all_caches as clear_comparison_caches from bibauthorid_backinterface import bib_matrix from bibauthorid_backinterface import get_sql_time from bibauthorid_backinterface import filter_modified_record_ids from bibauthorid_general_utils import update_status \ , update_status_final if bconfig.DEBUG_CHECKS: def _debug_is_eq(v1, v2): eps = 1e-2 return v1 + eps > v2 and v2 + eps > v1 def _debug_is_eq_v(vl1, vl2): if isinstance(vl1, str) and isinstance(vl2, str): return vl1 == vl2 if isinstance(vl1, tuple) and isinstance(vl2, tuple): return _debug_is_eq(vl1[0], vl2[0]) and _debug_is_eq(vl1[1], vl2[1]) return False class probability_matrix: ''' This class contains and maintains the comparison between all virtual authors. It is able to write and read from the database and update the results. ''' def __init__(self, cluster_set, use_cache=False, save_cache=False): ''' Constructs probability matrix. If use_cache is true, it will try to load old computations from the database. If save cache is true it will save the current results into the database. @param cluster_set: A cluster set object, used to initialize the matrix. ''' def check_for_cleaning(cur_calc): if cur_calc % 10000000 == 0: clear_comparison_caches() self._bib_matrix = bib_matrix(cluster_set) old_matrix = bib_matrix() ncl = sum(len(cl.bibs) for cl in cluster_set.clusters) expected = ((ncl * (ncl - 1)) / 2) if expected == 0: expected = 1 if use_cache and old_matrix.load(cluster_set.last_name): cached_bibs = set(filter_modified_record_ids( old_matrix.get_keys(), old_matrix.creation_time)) else: cached_bibs = set() if save_cache: creation_time = get_sql_time() cur_calc, opti = 0, 0 for cl1 in cluster_set.clusters: update_status((float(opti) + cur_calc) / expected, "Prob matrix: calc %d, opti %d." % (cur_calc, opti))
for cl2 in cluster_set.clusters: if id(cl1) < id(cl2) and not cl1.hates(cl2): for bib1 in cl1.bibs: for bib2 in cl2.bibs: if bib1 in cached_bibs and bib2 in cached_bibs: val = old_matrix[bib1, bib2] if not val: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) else: opti += 1 if bconfig.DEBUG_CHECKS: assert _debug_is_eq_v(val, compare_bibrefrecs(bib1, bib2)) else: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) self._bib_matrix[bib1, bib2] = val clear_comparison_caches() if save_cache: update_status(1., "saving...") self._bib_matrix.store(cluster_set.last_name, creation_time) update_status_final("Matrix done. %d calc, %d opt." % (cur_calc, opti)) def __getitem__(self, bibs): return self._bib_matrix[bibs[0], bibs[1]]
random_line_split
bibauthorid_prob_matrix.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. import bibauthorid_config as bconfig from bibauthorid_comparison import compare_bibrefrecs from bibauthorid_comparison import clear_all_caches as clear_comparison_caches from bibauthorid_backinterface import bib_matrix from bibauthorid_backinterface import get_sql_time from bibauthorid_backinterface import filter_modified_record_ids from bibauthorid_general_utils import update_status \ , update_status_final if bconfig.DEBUG_CHECKS: def _debug_is_eq(v1, v2): eps = 1e-2 return v1 + eps > v2 and v2 + eps > v1 def _debug_is_eq_v(vl1, vl2): if isinstance(vl1, str) and isinstance(vl2, str): return vl1 == vl2 if isinstance(vl1, tuple) and isinstance(vl2, tuple): return _debug_is_eq(vl1[0], vl2[0]) and _debug_is_eq(vl1[1], vl2[1]) return False class probability_matrix: ''' This class contains and maintains the comparison between all virtual authors. It is able to write and read from the database and update the results. ''' def __init__(self, cluster_set, use_cache=False, save_cache=False): ''' Constructs probability matrix. If use_cache is true, it will try to load old computations from the database. If save cache is true it will save the current results into the database. @param cluster_set: A cluster set object, used to initialize the matrix. ''' def check_for_cleaning(cur_calc): if cur_calc % 10000000 == 0: clear_comparison_caches() self._bib_matrix = bib_matrix(cluster_set) old_matrix = bib_matrix() ncl = sum(len(cl.bibs) for cl in cluster_set.clusters) expected = ((ncl * (ncl - 1)) / 2) if expected == 0: expected = 1 if use_cache and old_matrix.load(cluster_set.last_name): cached_bibs = set(filter_modified_record_ids( old_matrix.get_keys(), old_matrix.creation_time)) else:
if save_cache: creation_time = get_sql_time() cur_calc, opti = 0, 0 for cl1 in cluster_set.clusters: update_status((float(opti) + cur_calc) / expected, "Prob matrix: calc %d, opti %d." % (cur_calc, opti)) for cl2 in cluster_set.clusters: if id(cl1) < id(cl2) and not cl1.hates(cl2): for bib1 in cl1.bibs: for bib2 in cl2.bibs: if bib1 in cached_bibs and bib2 in cached_bibs: val = old_matrix[bib1, bib2] if not val: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) else: opti += 1 if bconfig.DEBUG_CHECKS: assert _debug_is_eq_v(val, compare_bibrefrecs(bib1, bib2)) else: cur_calc += 1 check_for_cleaning(cur_calc) val = compare_bibrefrecs(bib1, bib2) self._bib_matrix[bib1, bib2] = val clear_comparison_caches() if save_cache: update_status(1., "saving...") self._bib_matrix.store(cluster_set.last_name, creation_time) update_status_final("Matrix done. %d calc, %d opt." % (cur_calc, opti)) def __getitem__(self, bibs): return self._bib_matrix[bibs[0], bibs[1]]
cached_bibs = set()
conditional_block
window_event.rs
#![allow(missing_docs)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Serialize, Deserialize)] pub enum WindowEvent { Pos(i32, i32), Size(u32, u32), Close, Refresh, Focus(bool), Iconify(bool), FramebufferSize(u32, u32), MouseButton(MouseButton, Action, Modifiers), CursorPos(f64, f64, Modifiers), CursorEnter(bool), Scroll(f64, f64, Modifiers), Key(Key, Action, Modifiers), Char(char), CharModifiers(char, Modifiers), Touch(u64, f64, f64, TouchAction, Modifiers), } use WindowEvent::*; impl WindowEvent { /// Tests if this event is related to the keyboard. pub fn is_keyboard_event(&self) -> bool { matches!(self, Key(..) | Char(..) | CharModifiers(..)) } /// Tests if this event is related to the mouse. pub fn
(&self) -> bool { matches!( self, MouseButton(..) | CursorPos(..) | CursorEnter(..) | Scroll(..) ) } /// Tests if this event is related to the touch. pub fn is_touch_event(&self) -> bool { matches!(self, Touch(..)) } } // NOTE: list of keys inspired from glutin. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum Key { Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9, Key0, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, Snapshot, Scroll, Pause, Insert, Home, Delete, End, PageDown, PageUp, Left, Up, Right, Down, Back, Return, Space, Compose, Caret, Numlock, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, AbntC1, AbntC2, Add, Apostrophe, Apps, At, Ax, Backslash, Calculator, Capital, Colon, Comma, Convert, Decimal, Divide, Equals, Grave, Kana, Kanji, LAlt, LBracket, LControl, LShift, LWin, Mail, MediaSelect, MediaStop, Minus, Multiply, Mute, MyComputer, NavigateForward, NavigateBackward, NextTrack, NoConvert, NumpadComma, NumpadEnter, NumpadEquals, OEM102, Period, PlayPause, Power, PrevTrack, RAlt, RBracket, RControl, RShift, RWin, Semicolon, Slash, Sleep, Stop, Subtract, Sysrq, Tab, Underline, Unlabeled, VolumeDown, VolumeUp, Wake, WebBack, WebFavorites, WebForward, WebHome, WebRefresh, WebSearch, WebStop, Yen, Copy, Paste, Cut, Unknown, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum MouseButton { Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum Action { Release, Press, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum TouchAction { Start, End, Move, Cancel, } bitflags! { #[doc = "Key modifiers"] #[derive(Serialize, Deserialize)] pub struct Modifiers: i32 { const Shift = 0b0001; const Control = 0b0010; const Alt = 0b0100; const Super = 0b1000; } }
is_mouse_event
identifier_name
window_event.rs
#![allow(missing_docs)] #[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Serialize, Deserialize)] pub enum WindowEvent { Pos(i32, i32), Size(u32, u32), Close, Refresh, Focus(bool), Iconify(bool), FramebufferSize(u32, u32), MouseButton(MouseButton, Action, Modifiers), CursorPos(f64, f64, Modifiers), CursorEnter(bool), Scroll(f64, f64, Modifiers), Key(Key, Action, Modifiers), Char(char),
} use WindowEvent::*; impl WindowEvent { /// Tests if this event is related to the keyboard. pub fn is_keyboard_event(&self) -> bool { matches!(self, Key(..) | Char(..) | CharModifiers(..)) } /// Tests if this event is related to the mouse. pub fn is_mouse_event(&self) -> bool { matches!( self, MouseButton(..) | CursorPos(..) | CursorEnter(..) | Scroll(..) ) } /// Tests if this event is related to the touch. pub fn is_touch_event(&self) -> bool { matches!(self, Touch(..)) } } // NOTE: list of keys inspired from glutin. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum Key { Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9, Key0, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24, Snapshot, Scroll, Pause, Insert, Home, Delete, End, PageDown, PageUp, Left, Up, Right, Down, Back, Return, Space, Compose, Caret, Numlock, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, AbntC1, AbntC2, Add, Apostrophe, Apps, At, Ax, Backslash, Calculator, Capital, Colon, Comma, Convert, Decimal, Divide, Equals, Grave, Kana, Kanji, LAlt, LBracket, LControl, LShift, LWin, Mail, MediaSelect, MediaStop, Minus, Multiply, Mute, MyComputer, NavigateForward, NavigateBackward, NextTrack, NoConvert, NumpadComma, NumpadEnter, NumpadEquals, OEM102, Period, PlayPause, Power, PrevTrack, RAlt, RBracket, RControl, RShift, RWin, Semicolon, Slash, Sleep, Stop, Subtract, Sysrq, Tab, Underline, Unlabeled, VolumeDown, VolumeUp, Wake, WebBack, WebFavorites, WebForward, WebHome, WebRefresh, WebSearch, WebStop, Yen, Copy, Paste, Cut, Unknown, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum MouseButton { Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum Action { Release, Press, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub enum TouchAction { Start, End, Move, Cancel, } bitflags! { #[doc = "Key modifiers"] #[derive(Serialize, Deserialize)] pub struct Modifiers: i32 { const Shift = 0b0001; const Control = 0b0010; const Alt = 0b0100; const Super = 0b1000; } }
CharModifiers(char, Modifiers), Touch(u64, f64, f64, TouchAction, Modifiers),
random_line_split
test_hgnc_client.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.databases import hgnc_client from indra.util import unicode_strs from nose.plugins.attrib import attr def test_get_uniprot_id(): hgnc_id = '6840' uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) assert uniprot_id == 'Q02750' assert unicode_strs(uniprot_id) def test_get_uniprot_id_none(): # This HGNC entry doesn't have a UniProt ID hgnc_id = '37187' uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) assert uniprot_id is None, uniprot_id def test_get_hgnc_name(): hgnc_id = '3236' hgnc_name = hgnc_client.get_hgnc_name(hgnc_id) assert hgnc_name == 'EGFR' assert unicode_strs(hgnc_name) @attr('webservice') def
(): hgnc_id = '123456' hgnc_name = hgnc_client.get_hgnc_name(hgnc_id) assert hgnc_name is None assert unicode_strs(hgnc_name) def test_entrez_hgnc(): entrez_id = '653509' hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id) assert hgnc_id == '10798' def test_entrez_hgnc_none(): entrez_id = 'xxx' hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id) assert hgnc_id is None def test_ensembl_hgnc(): ensembl_id = 'ENSG00000006071' hgnc_id = hgnc_client.get_hgnc_from_ensembl(ensembl_id) assert hgnc_id == '59', hgnc_id assert hgnc_client.get_ensembl_id(hgnc_id) == ensembl_id def test_mouse_map(): hgnc_id1 = hgnc_client.get_hgnc_from_mouse('109599') hgnc_id2 = hgnc_client.get_hgnc_from_mouse('MGI:109599') assert hgnc_id1 == '4820' assert hgnc_id2 == '4820' hgnc_id = hgnc_client.get_hgnc_from_mouse('xxx') assert hgnc_id is None def test_rat_map(): hgnc_id1 = hgnc_client.get_hgnc_from_rat('6496784') hgnc_id2 = hgnc_client.get_hgnc_from_rat('RGD:6496784') assert hgnc_id1 == '44155' assert hgnc_id2 == '44155' hgnc_id = hgnc_client.get_hgnc_from_rat('xxx') assert hgnc_id is None def test_is_category(): assert hgnc_client.is_kinase('MAPK1') assert not hgnc_client.is_kinase('EGF') assert hgnc_client.is_phosphatase('PTEN') assert not hgnc_client.is_phosphatase('KRAS') assert hgnc_client.is_transcription_factor('FOXO3') assert not hgnc_client.is_transcription_factor('AKT1') def test_get_current_id(): # Current symbol assert hgnc_client.get_current_hgnc_id('BRAF') == '1097' # Outdated symbol, one ID assert hgnc_client.get_current_hgnc_id('SEPT7') == '1717' # Outdated symbol, multiple IDs ids = hgnc_client.get_current_hgnc_id('HOX1') assert len(ids) == 10 assert '5101' in ids def test_gene_type(): assert hgnc_client.get_gene_type('1097') == 'gene with protein product' assert hgnc_client.get_gene_type('31547') == 'RNA, micro'
test_get_hgnc_name_nonexistent
identifier_name
test_hgnc_client.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.databases import hgnc_client from indra.util import unicode_strs from nose.plugins.attrib import attr def test_get_uniprot_id(): hgnc_id = '6840' uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) assert uniprot_id == 'Q02750' assert unicode_strs(uniprot_id) def test_get_uniprot_id_none(): # This HGNC entry doesn't have a UniProt ID hgnc_id = '37187' uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) assert uniprot_id is None, uniprot_id def test_get_hgnc_name(): hgnc_id = '3236' hgnc_name = hgnc_client.get_hgnc_name(hgnc_id) assert hgnc_name == 'EGFR' assert unicode_strs(hgnc_name) @attr('webservice') def test_get_hgnc_name_nonexistent(): hgnc_id = '123456' hgnc_name = hgnc_client.get_hgnc_name(hgnc_id) assert hgnc_name is None assert unicode_strs(hgnc_name) def test_entrez_hgnc(): entrez_id = '653509' hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id) assert hgnc_id == '10798' def test_entrez_hgnc_none(): entrez_id = 'xxx' hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id) assert hgnc_id is None def test_ensembl_hgnc(): ensembl_id = 'ENSG00000006071' hgnc_id = hgnc_client.get_hgnc_from_ensembl(ensembl_id) assert hgnc_id == '59', hgnc_id assert hgnc_client.get_ensembl_id(hgnc_id) == ensembl_id def test_mouse_map(): hgnc_id1 = hgnc_client.get_hgnc_from_mouse('109599') hgnc_id2 = hgnc_client.get_hgnc_from_mouse('MGI:109599') assert hgnc_id1 == '4820' assert hgnc_id2 == '4820' hgnc_id = hgnc_client.get_hgnc_from_mouse('xxx') assert hgnc_id is None def test_rat_map(): hgnc_id1 = hgnc_client.get_hgnc_from_rat('6496784') hgnc_id2 = hgnc_client.get_hgnc_from_rat('RGD:6496784') assert hgnc_id1 == '44155' assert hgnc_id2 == '44155' hgnc_id = hgnc_client.get_hgnc_from_rat('xxx') assert hgnc_id is None
assert hgnc_client.is_transcription_factor('FOXO3') assert not hgnc_client.is_transcription_factor('AKT1') def test_get_current_id(): # Current symbol assert hgnc_client.get_current_hgnc_id('BRAF') == '1097' # Outdated symbol, one ID assert hgnc_client.get_current_hgnc_id('SEPT7') == '1717' # Outdated symbol, multiple IDs ids = hgnc_client.get_current_hgnc_id('HOX1') assert len(ids) == 10 assert '5101' in ids def test_gene_type(): assert hgnc_client.get_gene_type('1097') == 'gene with protein product' assert hgnc_client.get_gene_type('31547') == 'RNA, micro'
def test_is_category(): assert hgnc_client.is_kinase('MAPK1') assert not hgnc_client.is_kinase('EGF') assert hgnc_client.is_phosphatase('PTEN') assert not hgnc_client.is_phosphatase('KRAS')
random_line_split
test_hgnc_client.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.databases import hgnc_client from indra.util import unicode_strs from nose.plugins.attrib import attr def test_get_uniprot_id(): hgnc_id = '6840' uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) assert uniprot_id == 'Q02750' assert unicode_strs(uniprot_id) def test_get_uniprot_id_none(): # This HGNC entry doesn't have a UniProt ID hgnc_id = '37187' uniprot_id = hgnc_client.get_uniprot_id(hgnc_id) assert uniprot_id is None, uniprot_id def test_get_hgnc_name(): hgnc_id = '3236' hgnc_name = hgnc_client.get_hgnc_name(hgnc_id) assert hgnc_name == 'EGFR' assert unicode_strs(hgnc_name) @attr('webservice') def test_get_hgnc_name_nonexistent(): hgnc_id = '123456' hgnc_name = hgnc_client.get_hgnc_name(hgnc_id) assert hgnc_name is None assert unicode_strs(hgnc_name) def test_entrez_hgnc(): entrez_id = '653509' hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id) assert hgnc_id == '10798' def test_entrez_hgnc_none(): entrez_id = 'xxx' hgnc_id = hgnc_client.get_hgnc_from_entrez(entrez_id) assert hgnc_id is None def test_ensembl_hgnc(): ensembl_id = 'ENSG00000006071' hgnc_id = hgnc_client.get_hgnc_from_ensembl(ensembl_id) assert hgnc_id == '59', hgnc_id assert hgnc_client.get_ensembl_id(hgnc_id) == ensembl_id def test_mouse_map(): hgnc_id1 = hgnc_client.get_hgnc_from_mouse('109599') hgnc_id2 = hgnc_client.get_hgnc_from_mouse('MGI:109599') assert hgnc_id1 == '4820' assert hgnc_id2 == '4820' hgnc_id = hgnc_client.get_hgnc_from_mouse('xxx') assert hgnc_id is None def test_rat_map():
def test_is_category(): assert hgnc_client.is_kinase('MAPK1') assert not hgnc_client.is_kinase('EGF') assert hgnc_client.is_phosphatase('PTEN') assert not hgnc_client.is_phosphatase('KRAS') assert hgnc_client.is_transcription_factor('FOXO3') assert not hgnc_client.is_transcription_factor('AKT1') def test_get_current_id(): # Current symbol assert hgnc_client.get_current_hgnc_id('BRAF') == '1097' # Outdated symbol, one ID assert hgnc_client.get_current_hgnc_id('SEPT7') == '1717' # Outdated symbol, multiple IDs ids = hgnc_client.get_current_hgnc_id('HOX1') assert len(ids) == 10 assert '5101' in ids def test_gene_type(): assert hgnc_client.get_gene_type('1097') == 'gene with protein product' assert hgnc_client.get_gene_type('31547') == 'RNA, micro'
hgnc_id1 = hgnc_client.get_hgnc_from_rat('6496784') hgnc_id2 = hgnc_client.get_hgnc_from_rat('RGD:6496784') assert hgnc_id1 == '44155' assert hgnc_id2 == '44155' hgnc_id = hgnc_client.get_hgnc_from_rat('xxx') assert hgnc_id is None
identifier_body
8646922c8a04_change_default_pool_slots_to_1.py
# # 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 not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Change default pool_slots to 1 Revision ID: 8646922c8a04 Revises: 449b4072c2da Create Date: 2021-02-23 23:19:22.409973 """ import dill import sqlalchemy as sa from alembic import op from sqlalchemy import Column, Float, Integer, PickleType, String # revision identifiers, used by Alembic. from sqlalchemy.ext.declarative import declarative_base from airflow.models.base import COLLATION_ARGS from airflow.utils.sqlalchemy import UtcDateTime revision = '8646922c8a04' down_revision = '449b4072c2da' branch_labels = None depends_on = None Base = declarative_base() BATCH_SIZE = 5000 ID_LEN = 250 class TaskInstance(Base): # type: ignore """Task instance class.""" __tablename__ = "task_instance" task_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True) dag_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True) execution_date = Column(UtcDateTime, primary_key=True) start_date = Column(UtcDateTime) end_date = Column(UtcDateTime) duration = Column(Float) state = Column(String(20)) _try_number = Column('try_number', Integer, default=0) max_tries = Column(Integer) hostname = Column(String(1000)) unixname = Column(String(1000)) job_id = Column(Integer) pool = Column(String(50), nullable=False) pool_slots = Column(Integer, default=1) queue = Column(String(256)) priority_weight = Column(Integer) operator = Column(String(1000)) queued_dttm = Column(UtcDateTime) queued_by_job_id = Column(Integer) pid = Column(Integer) executor_config = Column(PickleType(pickler=dill)) external_executor_id = Column(String(ID_LEN, **COLLATION_ARGS)) def
(): """Change default pool_slots to 1 and make pool_slots not nullable""" connection = op.get_bind() sessionmaker = sa.orm.sessionmaker() session = sessionmaker(bind=connection) session.query(TaskInstance).filter(TaskInstance.pool_slots.is_(None)).update( {TaskInstance.pool_slots: 1}, synchronize_session=False ) session.commit() with op.batch_alter_table("task_instance", schema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=False) def downgrade(): """Unapply Change default pool_slots to 1""" with op.batch_alter_table("task_instance", schema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=True)
upgrade
identifier_name
8646922c8a04_change_default_pool_slots_to_1.py
# # 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 not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Change default pool_slots to 1 Revision ID: 8646922c8a04 Revises: 449b4072c2da Create Date: 2021-02-23 23:19:22.409973 """ import dill import sqlalchemy as sa from alembic import op from sqlalchemy import Column, Float, Integer, PickleType, String # revision identifiers, used by Alembic. from sqlalchemy.ext.declarative import declarative_base from airflow.models.base import COLLATION_ARGS from airflow.utils.sqlalchemy import UtcDateTime revision = '8646922c8a04' down_revision = '449b4072c2da' branch_labels = None depends_on = None Base = declarative_base() BATCH_SIZE = 5000 ID_LEN = 250 class TaskInstance(Base): # type: ignore """Task instance class.""" __tablename__ = "task_instance" task_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True) dag_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True) execution_date = Column(UtcDateTime, primary_key=True) start_date = Column(UtcDateTime) end_date = Column(UtcDateTime) duration = Column(Float) state = Column(String(20)) _try_number = Column('try_number', Integer, default=0) max_tries = Column(Integer) hostname = Column(String(1000)) unixname = Column(String(1000)) job_id = Column(Integer) pool = Column(String(50), nullable=False) pool_slots = Column(Integer, default=1) queue = Column(String(256)) priority_weight = Column(Integer) operator = Column(String(1000)) queued_dttm = Column(UtcDateTime) queued_by_job_id = Column(Integer) pid = Column(Integer) executor_config = Column(PickleType(pickler=dill)) external_executor_id = Column(String(ID_LEN, **COLLATION_ARGS)) def upgrade(): """Change default pool_slots to 1 and make pool_slots not nullable""" connection = op.get_bind() sessionmaker = sa.orm.sessionmaker() session = sessionmaker(bind=connection) session.query(TaskInstance).filter(TaskInstance.pool_slots.is_(None)).update( {TaskInstance.pool_slots: 1}, synchronize_session=False ) session.commit() with op.batch_alter_table("task_instance", schema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=False)
def downgrade(): """Unapply Change default pool_slots to 1""" with op.batch_alter_table("task_instance", schema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=True)
random_line_split
8646922c8a04_change_default_pool_slots_to_1.py
# # 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 not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Change default pool_slots to 1 Revision ID: 8646922c8a04 Revises: 449b4072c2da Create Date: 2021-02-23 23:19:22.409973 """ import dill import sqlalchemy as sa from alembic import op from sqlalchemy import Column, Float, Integer, PickleType, String # revision identifiers, used by Alembic. from sqlalchemy.ext.declarative import declarative_base from airflow.models.base import COLLATION_ARGS from airflow.utils.sqlalchemy import UtcDateTime revision = '8646922c8a04' down_revision = '449b4072c2da' branch_labels = None depends_on = None Base = declarative_base() BATCH_SIZE = 5000 ID_LEN = 250 class TaskInstance(Base): # type: ignore """Task instance class.""" __tablename__ = "task_instance" task_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True) dag_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True) execution_date = Column(UtcDateTime, primary_key=True) start_date = Column(UtcDateTime) end_date = Column(UtcDateTime) duration = Column(Float) state = Column(String(20)) _try_number = Column('try_number', Integer, default=0) max_tries = Column(Integer) hostname = Column(String(1000)) unixname = Column(String(1000)) job_id = Column(Integer) pool = Column(String(50), nullable=False) pool_slots = Column(Integer, default=1) queue = Column(String(256)) priority_weight = Column(Integer) operator = Column(String(1000)) queued_dttm = Column(UtcDateTime) queued_by_job_id = Column(Integer) pid = Column(Integer) executor_config = Column(PickleType(pickler=dill)) external_executor_id = Column(String(ID_LEN, **COLLATION_ARGS)) def upgrade(): """Change default pool_slots to 1 and make pool_slots not nullable""" connection = op.get_bind() sessionmaker = sa.orm.sessionmaker() session = sessionmaker(bind=connection) session.query(TaskInstance).filter(TaskInstance.pool_slots.is_(None)).update( {TaskInstance.pool_slots: 1}, synchronize_session=False ) session.commit() with op.batch_alter_table("task_instance", schema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=False) def downgrade():
"""Unapply Change default pool_slots to 1""" with op.batch_alter_table("task_instance", schema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=True)
identifier_body
AEtestNodeATemplate.py
""" To create an Attribute Editor template using python, do the following: 1. create a subclass of `uitypes.AETemplate` 2. set its ``_nodeType`` class attribute to the name of the desired node type, or name the class using the convention ``AE<nodeType>Template`` 3. import the module AETemplates which do not meet one of the two requirements listed in step 2 will be ignored. To ensure that your Template's node type is being detected correctly, use the ``AETemplate.nodeType()`` class method:: import AETemplates AETemplates.AEmib_amb_occlusionTemplate.nodeType() As a convenience, when pymel is imported it will automatically import the module ``AETemplates``, if it exists, thereby causing any AETemplates within it or its sub-modules to be registered. Be sure to import pymel or modules containing your ``AETemplate`` classes before opening the Atrribute Editor for the node types in question. To check which python templates are loaded:: from pymel.core.uitypes import AELoader print AELoader.loadedTemplates() The example below demonstrates the simplest case, which is the first. It provides a layout for the mib_amb_occlusion mental ray shader. """ import pymel.core as pm import mymagicbox.AETemplateBase as AETemplateBase import mymagicbox.log as log class
(AETemplateBase.mmbTemplateBase): def buildBody(self, nodeName): log.debug("building AETemplate for node: %s", nodeName) self.AEswatchDisplay(nodeName) self.beginLayout("Common Material Attributes",collapse=0) self.addControl("attribute0") self.endLayout() self.beginLayout("Version",collapse=0) self.addControl("mmbversion") self.endLayout() pm.mel.AEdependNodeTemplate(self.nodeName) self.addExtraControls()
AEtestNodeATemplate
identifier_name
AEtestNodeATemplate.py
""" To create an Attribute Editor template using python, do the following: 1. create a subclass of `uitypes.AETemplate` 2. set its ``_nodeType`` class attribute to the name of the desired node type, or name the class using the convention ``AE<nodeType>Template`` 3. import the module AETemplates which do not meet one of the two requirements listed in step 2 will be ignored. To ensure that your Template's node type is being detected correctly, use the ``AETemplate.nodeType()`` class method:: import AETemplates AETemplates.AEmib_amb_occlusionTemplate.nodeType() As a convenience, when pymel is imported it will automatically import the module ``AETemplates``, if it exists, thereby causing any AETemplates within it or its sub-modules to be registered. Be sure to import pymel or modules containing your ``AETemplate`` classes before opening the Atrribute Editor for the node types in question. To check which python templates are loaded:: from pymel.core.uitypes import AELoader print AELoader.loadedTemplates() The example below demonstrates the simplest case, which is the first. It provides a layout for the mib_amb_occlusion mental ray shader. """ import pymel.core as pm
class AEtestNodeATemplate(AETemplateBase.mmbTemplateBase): def buildBody(self, nodeName): log.debug("building AETemplate for node: %s", nodeName) self.AEswatchDisplay(nodeName) self.beginLayout("Common Material Attributes",collapse=0) self.addControl("attribute0") self.endLayout() self.beginLayout("Version",collapse=0) self.addControl("mmbversion") self.endLayout() pm.mel.AEdependNodeTemplate(self.nodeName) self.addExtraControls()
import mymagicbox.AETemplateBase as AETemplateBase import mymagicbox.log as log
random_line_split
AEtestNodeATemplate.py
""" To create an Attribute Editor template using python, do the following: 1. create a subclass of `uitypes.AETemplate` 2. set its ``_nodeType`` class attribute to the name of the desired node type, or name the class using the convention ``AE<nodeType>Template`` 3. import the module AETemplates which do not meet one of the two requirements listed in step 2 will be ignored. To ensure that your Template's node type is being detected correctly, use the ``AETemplate.nodeType()`` class method:: import AETemplates AETemplates.AEmib_amb_occlusionTemplate.nodeType() As a convenience, when pymel is imported it will automatically import the module ``AETemplates``, if it exists, thereby causing any AETemplates within it or its sub-modules to be registered. Be sure to import pymel or modules containing your ``AETemplate`` classes before opening the Atrribute Editor for the node types in question. To check which python templates are loaded:: from pymel.core.uitypes import AELoader print AELoader.loadedTemplates() The example below demonstrates the simplest case, which is the first. It provides a layout for the mib_amb_occlusion mental ray shader. """ import pymel.core as pm import mymagicbox.AETemplateBase as AETemplateBase import mymagicbox.log as log class AEtestNodeATemplate(AETemplateBase.mmbTemplateBase): def buildBody(self, nodeName):
log.debug("building AETemplate for node: %s", nodeName) self.AEswatchDisplay(nodeName) self.beginLayout("Common Material Attributes",collapse=0) self.addControl("attribute0") self.endLayout() self.beginLayout("Version",collapse=0) self.addControl("mmbversion") self.endLayout() pm.mel.AEdependNodeTemplate(self.nodeName) self.addExtraControls()
identifier_body
HeadsetMicTwoTone.js
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M5 17c0 .55.45 1 1 1h1v-4H5v3zm12-3h2v4h-2z", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "M12 1c-4.97 0-9 4.03-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2c0-3.87 3.13-7 7-7s7 3.13 7 7v2h-4v8h4v1h-7v2h6c1.66 0 3-1.34 3-3V10c0-4.97-4.03-9-9-9zM7 14v4H6c-.55 0-1-.45-1-1v-3h2zm12 4h-2v-4h2v4z"
}, "1")], 'HeadsetMicTwoTone');
random_line_split
mocks.ts
import { MenuItem } from './menu-item-model'; //importo la classe MenuItem così posso usarla qui dentro export const MENUITEMS: MenuItem[] = [ //esporto un oggetto costante di tipo MenuItem[] che si chiama MENUITEM che contiene { //tutte le proprietà degli item del menu di navigazione. name: "Home", description: "An overview page of my webapp", path: "home" }, { name: "Trends", description: "Some graphs about various things", path: "trends" }, { name: "Controller", description: "The button room", path: "controller"
description: "This is where is represented the schema of the Water Treatement Plant; with heating, distributing, ecc.", path: "waterplant" }, { name: "Docs", description: "Home Docs Here!", path: "docs" } ]
}, { name: "Water Plant",
random_line_split
InputErrorSuffix.js
import React from 'react'; import PropTypes from 'prop-types'; import Tooltip from '../Tooltip'; import SvgExclamation from '../svg/Exclamation.js'; import styles from './Input.scss'; class InputErrorSuffix extends React.Component {
() { return ( <Tooltip dataHook="input-tooltip" disabled={this.props.errorMessage.length === 0} placement="top" alignment="center" textAlign="left" content={this.props.errorMessage} overlay="" theme="dark" maxWidth="230px" hideDelay={150} > <div className={styles.exclamation}><SvgExclamation width={2} height={11}/></div> </Tooltip> ); } } InputErrorSuffix.propTypes = { theme: PropTypes.oneOf(['normal', 'paneltitle', 'material', 'amaterial']), errorMessage: PropTypes.string.isRequired, focused: PropTypes.bool }; export default InputErrorSuffix;
render
identifier_name
InputErrorSuffix.js
import React from 'react'; import PropTypes from 'prop-types'; import Tooltip from '../Tooltip'; import SvgExclamation from '../svg/Exclamation.js'; import styles from './Input.scss'; class InputErrorSuffix extends React.Component { render()
} InputErrorSuffix.propTypes = { theme: PropTypes.oneOf(['normal', 'paneltitle', 'material', 'amaterial']), errorMessage: PropTypes.string.isRequired, focused: PropTypes.bool }; export default InputErrorSuffix;
{ return ( <Tooltip dataHook="input-tooltip" disabled={this.props.errorMessage.length === 0} placement="top" alignment="center" textAlign="left" content={this.props.errorMessage} overlay="" theme="dark" maxWidth="230px" hideDelay={150} > <div className={styles.exclamation}><SvgExclamation width={2} height={11}/></div> </Tooltip> ); }
identifier_body
InputErrorSuffix.js
import React from 'react'; import PropTypes from 'prop-types'; import Tooltip from '../Tooltip'; import SvgExclamation from '../svg/Exclamation.js'; import styles from './Input.scss'; class InputErrorSuffix extends React.Component { render() {
placement="top" alignment="center" textAlign="left" content={this.props.errorMessage} overlay="" theme="dark" maxWidth="230px" hideDelay={150} > <div className={styles.exclamation}><SvgExclamation width={2} height={11}/></div> </Tooltip> ); } } InputErrorSuffix.propTypes = { theme: PropTypes.oneOf(['normal', 'paneltitle', 'material', 'amaterial']), errorMessage: PropTypes.string.isRequired, focused: PropTypes.bool }; export default InputErrorSuffix;
return ( <Tooltip dataHook="input-tooltip" disabled={this.props.errorMessage.length === 0}
random_line_split
matplotFF.py
import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.interpolate from PIL import Image matplotlib.use('Qt5Agg') class matplotFF(): """A class for plotting far-field measurements of lasers. It requires the 'x z signal' format, but supports stitched measurements — the data can be simply added at the end of a file """ def __init__(self, fig, BaseFilename, title='', xLen=0, zLen=0, stitch=True, distance=None, angular_direction=None, output_filename=None): self.BaseFilename = BaseFilename if output_filename is None: self.output_filename = BaseFilename else: self.output_filename = output_filename self.title = title self.fig = fig self.rawData = np.loadtxt(self.BaseFilename) self.zRaw = self.rawData[:,0] self.xRaw = self.rawData[:,1] self.sigRaw = self.rawData[:,2] self.xlim = (None, None) self.zlim = (None, None) z_pixdim = (self.zRaw.max() - self.zRaw.min()) / len(self.zRaw) x_pixdim = (self.xRaw.max() - self.xRaw.min()) / len(self.xRaw) self.pixdim = (x_pixdim, z_pixdim) self.distance = distance self.angular_direction = angular_direction if distance is not None: if angular_direction == 'x': self.xRaw = 180/(2*np.pi)*np.arctan(self.xRaw/distance) elif angular_direction == 'z': self.zRaw = 180/(2*np.pi)*np.arctan(self.zRaw/distance) # figure out the number of steps for Z and X stage_tolerance = 0.05 # stages don't always move to the same # place, so numerical positions might differ slightly if xLen == 0 and zLen == 0: z_unique_vals = [self.zRaw[0]] x_unique_vals = [self.xRaw[0]] # count unique values of Z/X values in the data file # (allows for non-rectangular data, i.e. for stiching together # patches) for i in range(len(self.zRaw)): if sum(abs(z_unique_vals-self.zRaw[i]) > stage_tolerance) == len(z_unique_vals): z_unique_vals.append(self.zRaw[i]) for i in range(len(self.xRaw)): if sum(abs(x_unique_vals-self.xRaw[i]) > stage_tolerance) == len(x_unique_vals): x_unique_vals.append(self.xRaw[i]) self.xLen = len(x_unique_vals) self.zLen = len(z_unique_vals) else: self.xLen = xLen self.zLen = zLen # fill in zeros if we are plotting a stitched far field if stitch: self.x = np.ndarray((self.zLen,self.xLen)) self.z = np.ndarray((self.zLen,self.xLen)) self.signal = np.zeros((self.zLen, self.xLen)) for iz, z in enumerate(sorted(z_unique_vals)): for ix, x in enumerate(sorted(x_unique_vals)): self.x[iz][ix] = x self.z[iz][ix] = z for i in zip(self.xRaw, self.zRaw, self.sigRaw): if (abs(i[0]-x) < stage_tolerance) and (abs(i[1]-z) < stage_tolerance): self.signal[iz][ix] = i[2] break else: self.x = self.xRaw.reshape((self.zLen,self.xLen)) self.z = self.zRaw.reshape((self.zLen,self.xLen)) self.signal = self.sigRaw.reshape((self.zLen,self.xLen)) # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def trim(self, xmin=None, xmax=None, zmin=None, zmax=None): self.x = self.x[zmin:zmax,xmin:xmax] self.z = self.z[zmin:zmax,xmin:xmax] self.signal = self.signal[zmin:zmax,xmin:xmax] # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def plotLine(self): '''plots the cross section of far-field (averaged all points at a set z position)''' av = [np.mean(row) for row in self.signal] zLine = [z[0] for z in self.z] plt.plot(av, zLine, color='#1b9e77') def plotLineAngle(self, distance=0, phaseShift=0, mean=True, angleData=False, color='#1b9e77', label=''): """plots the cross section of far-field (averaged all points at a set z position) Args: distance: distance of the detector in mm (for conversion into theta) phaseShift: angle in radians. Sometimes we want to shift the farfield by pi to get the plot on the other side of the polar coordinate system angleData: if True, it means that the data were collected with a rotation stage and therefore do not have to be converted into angle """ if mean: intens = np.mean(self.signal, axis=0) else: intens = self.signal[-5] intens = np.mean(self.signal) if angleData: theta = self.x[0]*np.pi/180 else: theta = [np.arctan(z[0]/distance)+phaseShift for z in self.z] # normalize values to [0,1] intens -= np.min(intens) intens /= np.max(intens) self.ax1 = self.fig.add_subplot(111, polar=True) self.ax1.plot(theta, intens, color=color, linewidth=2.0, label=label) #self.ax1.set_theta_offset(-np.pi/2) self.ax1.get_yaxis().set_visible(False) def plot(self, rotate=False): self.ax1 = self.fig.add_subplot(111) self.ax1.margins(x=0) self.ax1.set_xlim(self.x.min(), self.x.max()) plt.pcolormesh(self.x,self.z,self.signal, edgecolors='face') self.fig.suptitle(self.title, y=0.98, weight='bold') self.fig.subplots_adjust(top=0.86) self.ax1.tick_params(labelright=True, labeltop=True) return self.fig def crosssection_plot(self, axis=0, subplot=None): cs = np.mean(self.signal, axis=axis) cs /= np.max(cs) self.ax_cutline[axis] = self.fig.add_subplot(subplot) ax = self.ax_cutline[axis] xlim = self.ax1.get_xlim() ylim = self.ax1.get_ylim() ratio = abs(xlim[1]-xlim[0])/abs(ylim[1]-ylim[0]) if axis == 0: ax.plot(self.x[0, :], cs) ax.set_aspect(ratio*7) ax.set_xlim(xlim) ax.set_ylim([0, 1.05]) ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') ax.set_xlabel(r"$\theta$ / degrees") ax.set_ylabel("intensity / arb. u.", fontsize=7) self.ax1.xaxis.label.set_visible(False) elif axis == 1: ax.plot(cs, self.z[:, 0]) ax.set_xlim([1.05, 0]) ax.set_ylim(ylim) ax.set_aspect(ratio/7) if self.distance is not None and self.angular_direction == 'z': ax.set_ylabel("$\phi$ / degrees") else: ax.set_ylabel("Z / mm") ax.set_xlabel("intensity / arb. u.", fontsize=7) self.ax1.yaxis.label.set_visible(False) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. def plotInterpolate(self, xPoints, zPoints, rotate=False, origin='lower', cutlines=False): if not cutlines: self.ax1 = self.fig.add_subplot(111) else: #self.gs1 = gridspec.GridSpec(2, 2) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. self.ax1 = self.fig.add_subplot(224) self.ax_cutline = [None, None] self.ax1.tick_params(labelright=True, labelbottom=True, labelleft=False, bottom=True, right=True, left=False) self.ax1.set_xlabel(r"$\theta$ / degrees") if self.distance is not None and self.angular_direction == 'z': self.ax1.set_ylabel("$\phi$ / degrees") else: self.ax1.set_ylabel("Z / mm") xi, zi = np.linspace(self.x.min(), self.x.max(), xPoints), np.linspace(self.z.min(), self.z.max(), zPoints) xi, zi = np.meshgrid(xi, zi) rbf = scipy.interpolate.Rbf(self.x, self.z, self.signal, function='linear') sigi = rbf(xi, zi) # normalise again after interpolation — just so the colorbar # extends from 0 to 1 sigi /= np.max(sigi) if rotate: sigi = np.rot90(sigi) sigi[-1, -1] = 0 pltmesh = plt.imshow(sigi, extent=[self.x.min(), self.x.max(), self.z.min(), self.z.max()], origin=origin, aspect='auto') self.ax1.set_facecolor(pltmesh.cmap(0.0)) cb = self.fig.colorbar(pltmesh, ticks=[0, 1]) cb.set_label('light intensity / arb. u.') if cutlines: self.crosssection_plot(axis=0, subplot=222) self.crosssection_plot(axis=1, subplot=223) self.fig.subplots_adjust(hspace=-0.1, wspace=-0.2) #self.fig.suptitle(self.title, y=0.98, weight='bold') #self.fig.subplots_adjust(top=0.12, left=0.7) #self.ax1.tick_params(labelright=True, labeltop=True) def insert_laser_orientation(self, orientation_image_path, x, y): # https://stackoverflow.com/questions/3609585/how-to-insert-a-small-image-on-the-corner-of-a-plot-with-matplotlib im = Image.open(orientation_image_path) height = im.size[1] im = np.array(im).astype(np.float) / 255 self.fig.figimage(im, x, self.fig.bbox.ymax - height - y) def show
f): plt.savefig(self.output_filename + '.pdf') plt.savefig(self.output_filename + '.svg') plt.savefig(self.output_filename + '.png', transparent=True) plt.show()
(sel
identifier_name
matplotFF.py
import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.interpolate from PIL import Image matplotlib.use('Qt5Agg') class matplotFF(): """A class for plotting far-field measurements of lasers. It requires the 'x z signal' format, but supports stitched measurements — the data can be simply added at the end of a file """ def __init__(self, fig, BaseFilename, title='', xLen=0, zLen=0, stitch=True, distance=None, angular_direction=None, output_filename=None): self.BaseFilename = BaseFilename if output_filename is None: self.output_filename = BaseFilename else: self.output_filename = output_filename self.title = title self.fig = fig self.rawData = np.loadtxt(self.BaseFilename) self.zRaw = self.rawData[:,0] self.xRaw = self.rawData[:,1] self.sigRaw = self.rawData[:,2] self.xlim = (None, None) self.zlim = (None, None) z_pixdim = (self.zRaw.max() - self.zRaw.min()) / len(self.zRaw) x_pixdim = (self.xRaw.max() - self.xRaw.min()) / len(self.xRaw) self.pixdim = (x_pixdim, z_pixdim) self.distance = distance self.angular_direction = angular_direction if distance is not None: if angular_direction == 'x': self.xRaw = 180/(2*np.pi)*np.arctan(self.xRaw/distance) elif angular_direction == 'z': se
# figure out the number of steps for Z and X stage_tolerance = 0.05 # stages don't always move to the same # place, so numerical positions might differ slightly if xLen == 0 and zLen == 0: z_unique_vals = [self.zRaw[0]] x_unique_vals = [self.xRaw[0]] # count unique values of Z/X values in the data file # (allows for non-rectangular data, i.e. for stiching together # patches) for i in range(len(self.zRaw)): if sum(abs(z_unique_vals-self.zRaw[i]) > stage_tolerance) == len(z_unique_vals): z_unique_vals.append(self.zRaw[i]) for i in range(len(self.xRaw)): if sum(abs(x_unique_vals-self.xRaw[i]) > stage_tolerance) == len(x_unique_vals): x_unique_vals.append(self.xRaw[i]) self.xLen = len(x_unique_vals) self.zLen = len(z_unique_vals) else: self.xLen = xLen self.zLen = zLen # fill in zeros if we are plotting a stitched far field if stitch: self.x = np.ndarray((self.zLen,self.xLen)) self.z = np.ndarray((self.zLen,self.xLen)) self.signal = np.zeros((self.zLen, self.xLen)) for iz, z in enumerate(sorted(z_unique_vals)): for ix, x in enumerate(sorted(x_unique_vals)): self.x[iz][ix] = x self.z[iz][ix] = z for i in zip(self.xRaw, self.zRaw, self.sigRaw): if (abs(i[0]-x) < stage_tolerance) and (abs(i[1]-z) < stage_tolerance): self.signal[iz][ix] = i[2] break else: self.x = self.xRaw.reshape((self.zLen,self.xLen)) self.z = self.zRaw.reshape((self.zLen,self.xLen)) self.signal = self.sigRaw.reshape((self.zLen,self.xLen)) # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def trim(self, xmin=None, xmax=None, zmin=None, zmax=None): self.x = self.x[zmin:zmax,xmin:xmax] self.z = self.z[zmin:zmax,xmin:xmax] self.signal = self.signal[zmin:zmax,xmin:xmax] # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def plotLine(self): '''plots the cross section of far-field (averaged all points at a set z position)''' av = [np.mean(row) for row in self.signal] zLine = [z[0] for z in self.z] plt.plot(av, zLine, color='#1b9e77') def plotLineAngle(self, distance=0, phaseShift=0, mean=True, angleData=False, color='#1b9e77', label=''): """plots the cross section of far-field (averaged all points at a set z position) Args: distance: distance of the detector in mm (for conversion into theta) phaseShift: angle in radians. Sometimes we want to shift the farfield by pi to get the plot on the other side of the polar coordinate system angleData: if True, it means that the data were collected with a rotation stage and therefore do not have to be converted into angle """ if mean: intens = np.mean(self.signal, axis=0) else: intens = self.signal[-5] intens = np.mean(self.signal) if angleData: theta = self.x[0]*np.pi/180 else: theta = [np.arctan(z[0]/distance)+phaseShift for z in self.z] # normalize values to [0,1] intens -= np.min(intens) intens /= np.max(intens) self.ax1 = self.fig.add_subplot(111, polar=True) self.ax1.plot(theta, intens, color=color, linewidth=2.0, label=label) #self.ax1.set_theta_offset(-np.pi/2) self.ax1.get_yaxis().set_visible(False) def plot(self, rotate=False): self.ax1 = self.fig.add_subplot(111) self.ax1.margins(x=0) self.ax1.set_xlim(self.x.min(), self.x.max()) plt.pcolormesh(self.x,self.z,self.signal, edgecolors='face') self.fig.suptitle(self.title, y=0.98, weight='bold') self.fig.subplots_adjust(top=0.86) self.ax1.tick_params(labelright=True, labeltop=True) return self.fig def crosssection_plot(self, axis=0, subplot=None): cs = np.mean(self.signal, axis=axis) cs /= np.max(cs) self.ax_cutline[axis] = self.fig.add_subplot(subplot) ax = self.ax_cutline[axis] xlim = self.ax1.get_xlim() ylim = self.ax1.get_ylim() ratio = abs(xlim[1]-xlim[0])/abs(ylim[1]-ylim[0]) if axis == 0: ax.plot(self.x[0, :], cs) ax.set_aspect(ratio*7) ax.set_xlim(xlim) ax.set_ylim([0, 1.05]) ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') ax.set_xlabel(r"$\theta$ / degrees") ax.set_ylabel("intensity / arb. u.", fontsize=7) self.ax1.xaxis.label.set_visible(False) elif axis == 1: ax.plot(cs, self.z[:, 0]) ax.set_xlim([1.05, 0]) ax.set_ylim(ylim) ax.set_aspect(ratio/7) if self.distance is not None and self.angular_direction == 'z': ax.set_ylabel("$\phi$ / degrees") else: ax.set_ylabel("Z / mm") ax.set_xlabel("intensity / arb. u.", fontsize=7) self.ax1.yaxis.label.set_visible(False) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. def plotInterpolate(self, xPoints, zPoints, rotate=False, origin='lower', cutlines=False): if not cutlines: self.ax1 = self.fig.add_subplot(111) else: #self.gs1 = gridspec.GridSpec(2, 2) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. self.ax1 = self.fig.add_subplot(224) self.ax_cutline = [None, None] self.ax1.tick_params(labelright=True, labelbottom=True, labelleft=False, bottom=True, right=True, left=False) self.ax1.set_xlabel(r"$\theta$ / degrees") if self.distance is not None and self.angular_direction == 'z': self.ax1.set_ylabel("$\phi$ / degrees") else: self.ax1.set_ylabel("Z / mm") xi, zi = np.linspace(self.x.min(), self.x.max(), xPoints), np.linspace(self.z.min(), self.z.max(), zPoints) xi, zi = np.meshgrid(xi, zi) rbf = scipy.interpolate.Rbf(self.x, self.z, self.signal, function='linear') sigi = rbf(xi, zi) # normalise again after interpolation — just so the colorbar # extends from 0 to 1 sigi /= np.max(sigi) if rotate: sigi = np.rot90(sigi) sigi[-1, -1] = 0 pltmesh = plt.imshow(sigi, extent=[self.x.min(), self.x.max(), self.z.min(), self.z.max()], origin=origin, aspect='auto') self.ax1.set_facecolor(pltmesh.cmap(0.0)) cb = self.fig.colorbar(pltmesh, ticks=[0, 1]) cb.set_label('light intensity / arb. u.') if cutlines: self.crosssection_plot(axis=0, subplot=222) self.crosssection_plot(axis=1, subplot=223) self.fig.subplots_adjust(hspace=-0.1, wspace=-0.2) #self.fig.suptitle(self.title, y=0.98, weight='bold') #self.fig.subplots_adjust(top=0.12, left=0.7) #self.ax1.tick_params(labelright=True, labeltop=True) def insert_laser_orientation(self, orientation_image_path, x, y): # https://stackoverflow.com/questions/3609585/how-to-insert-a-small-image-on-the-corner-of-a-plot-with-matplotlib im = Image.open(orientation_image_path) height = im.size[1] im = np.array(im).astype(np.float) / 255 self.fig.figimage(im, x, self.fig.bbox.ymax - height - y) def show(self): plt.savefig(self.output_filename + '.pdf') plt.savefig(self.output_filename + '.svg') plt.savefig(self.output_filename + '.png', transparent=True) plt.show()
lf.zRaw = 180/(2*np.pi)*np.arctan(self.zRaw/distance)
conditional_block
matplotFF.py
import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.interpolate from PIL import Image matplotlib.use('Qt5Agg') class matplotFF(): """A class for plotting far-field measurements of lasers. It requires the 'x z signal' format, but supports stitched measurements — the data can be simply added at the end of a file """
else: self.output_filename = output_filename self.title = title self.fig = fig self.rawData = np.loadtxt(self.BaseFilename) self.zRaw = self.rawData[:,0] self.xRaw = self.rawData[:,1] self.sigRaw = self.rawData[:,2] self.xlim = (None, None) self.zlim = (None, None) z_pixdim = (self.zRaw.max() - self.zRaw.min()) / len(self.zRaw) x_pixdim = (self.xRaw.max() - self.xRaw.min()) / len(self.xRaw) self.pixdim = (x_pixdim, z_pixdim) self.distance = distance self.angular_direction = angular_direction if distance is not None: if angular_direction == 'x': self.xRaw = 180/(2*np.pi)*np.arctan(self.xRaw/distance) elif angular_direction == 'z': self.zRaw = 180/(2*np.pi)*np.arctan(self.zRaw/distance) # figure out the number of steps for Z and X stage_tolerance = 0.05 # stages don't always move to the same # place, so numerical positions might differ slightly if xLen == 0 and zLen == 0: z_unique_vals = [self.zRaw[0]] x_unique_vals = [self.xRaw[0]] # count unique values of Z/X values in the data file # (allows for non-rectangular data, i.e. for stiching together # patches) for i in range(len(self.zRaw)): if sum(abs(z_unique_vals-self.zRaw[i]) > stage_tolerance) == len(z_unique_vals): z_unique_vals.append(self.zRaw[i]) for i in range(len(self.xRaw)): if sum(abs(x_unique_vals-self.xRaw[i]) > stage_tolerance) == len(x_unique_vals): x_unique_vals.append(self.xRaw[i]) self.xLen = len(x_unique_vals) self.zLen = len(z_unique_vals) else: self.xLen = xLen self.zLen = zLen # fill in zeros if we are plotting a stitched far field if stitch: self.x = np.ndarray((self.zLen,self.xLen)) self.z = np.ndarray((self.zLen,self.xLen)) self.signal = np.zeros((self.zLen, self.xLen)) for iz, z in enumerate(sorted(z_unique_vals)): for ix, x in enumerate(sorted(x_unique_vals)): self.x[iz][ix] = x self.z[iz][ix] = z for i in zip(self.xRaw, self.zRaw, self.sigRaw): if (abs(i[0]-x) < stage_tolerance) and (abs(i[1]-z) < stage_tolerance): self.signal[iz][ix] = i[2] break else: self.x = self.xRaw.reshape((self.zLen,self.xLen)) self.z = self.zRaw.reshape((self.zLen,self.xLen)) self.signal = self.sigRaw.reshape((self.zLen,self.xLen)) # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def trim(self, xmin=None, xmax=None, zmin=None, zmax=None): self.x = self.x[zmin:zmax,xmin:xmax] self.z = self.z[zmin:zmax,xmin:xmax] self.signal = self.signal[zmin:zmax,xmin:xmax] # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def plotLine(self): '''plots the cross section of far-field (averaged all points at a set z position)''' av = [np.mean(row) for row in self.signal] zLine = [z[0] for z in self.z] plt.plot(av, zLine, color='#1b9e77') def plotLineAngle(self, distance=0, phaseShift=0, mean=True, angleData=False, color='#1b9e77', label=''): """plots the cross section of far-field (averaged all points at a set z position) Args: distance: distance of the detector in mm (for conversion into theta) phaseShift: angle in radians. Sometimes we want to shift the farfield by pi to get the plot on the other side of the polar coordinate system angleData: if True, it means that the data were collected with a rotation stage and therefore do not have to be converted into angle """ if mean: intens = np.mean(self.signal, axis=0) else: intens = self.signal[-5] intens = np.mean(self.signal) if angleData: theta = self.x[0]*np.pi/180 else: theta = [np.arctan(z[0]/distance)+phaseShift for z in self.z] # normalize values to [0,1] intens -= np.min(intens) intens /= np.max(intens) self.ax1 = self.fig.add_subplot(111, polar=True) self.ax1.plot(theta, intens, color=color, linewidth=2.0, label=label) #self.ax1.set_theta_offset(-np.pi/2) self.ax1.get_yaxis().set_visible(False) def plot(self, rotate=False): self.ax1 = self.fig.add_subplot(111) self.ax1.margins(x=0) self.ax1.set_xlim(self.x.min(), self.x.max()) plt.pcolormesh(self.x,self.z,self.signal, edgecolors='face') self.fig.suptitle(self.title, y=0.98, weight='bold') self.fig.subplots_adjust(top=0.86) self.ax1.tick_params(labelright=True, labeltop=True) return self.fig def crosssection_plot(self, axis=0, subplot=None): cs = np.mean(self.signal, axis=axis) cs /= np.max(cs) self.ax_cutline[axis] = self.fig.add_subplot(subplot) ax = self.ax_cutline[axis] xlim = self.ax1.get_xlim() ylim = self.ax1.get_ylim() ratio = abs(xlim[1]-xlim[0])/abs(ylim[1]-ylim[0]) if axis == 0: ax.plot(self.x[0, :], cs) ax.set_aspect(ratio*7) ax.set_xlim(xlim) ax.set_ylim([0, 1.05]) ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') ax.set_xlabel(r"$\theta$ / degrees") ax.set_ylabel("intensity / arb. u.", fontsize=7) self.ax1.xaxis.label.set_visible(False) elif axis == 1: ax.plot(cs, self.z[:, 0]) ax.set_xlim([1.05, 0]) ax.set_ylim(ylim) ax.set_aspect(ratio/7) if self.distance is not None and self.angular_direction == 'z': ax.set_ylabel("$\phi$ / degrees") else: ax.set_ylabel("Z / mm") ax.set_xlabel("intensity / arb. u.", fontsize=7) self.ax1.yaxis.label.set_visible(False) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. def plotInterpolate(self, xPoints, zPoints, rotate=False, origin='lower', cutlines=False): if not cutlines: self.ax1 = self.fig.add_subplot(111) else: #self.gs1 = gridspec.GridSpec(2, 2) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. self.ax1 = self.fig.add_subplot(224) self.ax_cutline = [None, None] self.ax1.tick_params(labelright=True, labelbottom=True, labelleft=False, bottom=True, right=True, left=False) self.ax1.set_xlabel(r"$\theta$ / degrees") if self.distance is not None and self.angular_direction == 'z': self.ax1.set_ylabel("$\phi$ / degrees") else: self.ax1.set_ylabel("Z / mm") xi, zi = np.linspace(self.x.min(), self.x.max(), xPoints), np.linspace(self.z.min(), self.z.max(), zPoints) xi, zi = np.meshgrid(xi, zi) rbf = scipy.interpolate.Rbf(self.x, self.z, self.signal, function='linear') sigi = rbf(xi, zi) # normalise again after interpolation — just so the colorbar # extends from 0 to 1 sigi /= np.max(sigi) if rotate: sigi = np.rot90(sigi) sigi[-1, -1] = 0 pltmesh = plt.imshow(sigi, extent=[self.x.min(), self.x.max(), self.z.min(), self.z.max()], origin=origin, aspect='auto') self.ax1.set_facecolor(pltmesh.cmap(0.0)) cb = self.fig.colorbar(pltmesh, ticks=[0, 1]) cb.set_label('light intensity / arb. u.') if cutlines: self.crosssection_plot(axis=0, subplot=222) self.crosssection_plot(axis=1, subplot=223) self.fig.subplots_adjust(hspace=-0.1, wspace=-0.2) #self.fig.suptitle(self.title, y=0.98, weight='bold') #self.fig.subplots_adjust(top=0.12, left=0.7) #self.ax1.tick_params(labelright=True, labeltop=True) def insert_laser_orientation(self, orientation_image_path, x, y): # https://stackoverflow.com/questions/3609585/how-to-insert-a-small-image-on-the-corner-of-a-plot-with-matplotlib im = Image.open(orientation_image_path) height = im.size[1] im = np.array(im).astype(np.float) / 255 self.fig.figimage(im, x, self.fig.bbox.ymax - height - y) def show(self): plt.savefig(self.output_filename + '.pdf') plt.savefig(self.output_filename + '.svg') plt.savefig(self.output_filename + '.png', transparent=True) plt.show()
def __init__(self, fig, BaseFilename, title='', xLen=0, zLen=0, stitch=True, distance=None, angular_direction=None, output_filename=None): self.BaseFilename = BaseFilename if output_filename is None: self.output_filename = BaseFilename
random_line_split
matplotFF.py
import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.interpolate from PIL import Image matplotlib.use('Qt5Agg') class matplotFF(): """A class for plotting far-field measurements of lasers. It requires the 'x z signal' format, but supports stitched measurements — the data can be simply added at the end of a file """ def __init__(self, fig, BaseFilename, title='', xLen=0, zLen=0, stitch=True, distance=None, angular_direction=None, output_filename=None): self.BaseFilename = BaseFilename if output_filename is None: self.output_filename = BaseFilename else: self.output_filename = output_filename self.title = title self.fig = fig self.rawData = np.loadtxt(self.BaseFilename) self.zRaw = self.rawData[:,0] self.xRaw = self.rawData[:,1] self.sigRaw = self.rawData[:,2] self.xlim = (None, None) self.zlim = (None, None) z_pixdim = (self.zRaw.max() - self.zRaw.min()) / len(self.zRaw) x_pixdim = (self.xRaw.max() - self.xRaw.min()) / len(self.xRaw) self.pixdim = (x_pixdim, z_pixdim) self.distance = distance self.angular_direction = angular_direction if distance is not None: if angular_direction == 'x': self.xRaw = 180/(2*np.pi)*np.arctan(self.xRaw/distance) elif angular_direction == 'z': self.zRaw = 180/(2*np.pi)*np.arctan(self.zRaw/distance) # figure out the number of steps for Z and X stage_tolerance = 0.05 # stages don't always move to the same # place, so numerical positions might differ slightly if xLen == 0 and zLen == 0: z_unique_vals = [self.zRaw[0]] x_unique_vals = [self.xRaw[0]] # count unique values of Z/X values in the data file # (allows for non-rectangular data, i.e. for stiching together # patches) for i in range(len(self.zRaw)): if sum(abs(z_unique_vals-self.zRaw[i]) > stage_tolerance) == len(z_unique_vals): z_unique_vals.append(self.zRaw[i]) for i in range(len(self.xRaw)): if sum(abs(x_unique_vals-self.xRaw[i]) > stage_tolerance) == len(x_unique_vals): x_unique_vals.append(self.xRaw[i]) self.xLen = len(x_unique_vals) self.zLen = len(z_unique_vals) else: self.xLen = xLen self.zLen = zLen # fill in zeros if we are plotting a stitched far field if stitch: self.x = np.ndarray((self.zLen,self.xLen)) self.z = np.ndarray((self.zLen,self.xLen)) self.signal = np.zeros((self.zLen, self.xLen)) for iz, z in enumerate(sorted(z_unique_vals)): for ix, x in enumerate(sorted(x_unique_vals)): self.x[iz][ix] = x self.z[iz][ix] = z for i in zip(self.xRaw, self.zRaw, self.sigRaw): if (abs(i[0]-x) < stage_tolerance) and (abs(i[1]-z) < stage_tolerance): self.signal[iz][ix] = i[2] break else: self.x = self.xRaw.reshape((self.zLen,self.xLen)) self.z = self.zRaw.reshape((self.zLen,self.xLen)) self.signal = self.sigRaw.reshape((self.zLen,self.xLen)) # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def trim(self, xmin=None, xmax=None, zmin=None, zmax=None): self.x = self.x[zmin:zmax,xmin:xmax] self.z = self.z[zmin:zmax,xmin:xmax] self.signal = self.signal[zmin:zmax,xmin:xmax] # normalise the signal to [0, 1] self.signal -= np.min(self.signal) self.signal /= np.max(self.signal) def plotLine(self): '''plots the cross section of far-field (averaged all points at a set z position)''' av = [np.mean(row) for row in self.signal] zLine = [z[0] for z in self.z] plt.plot(av, zLine, color='#1b9e77') def plotLineAngle(self, distance=0, phaseShift=0, mean=True, angleData=False, color='#1b9e77', label=''): """plots the cross section of far-field (averaged all points at a set z position) Args: distance: distance of the detector in mm (for conversion into theta) phaseShift: angle in radians. Sometimes we want to shift the farfield by pi to get the plot on the other side of the polar coordinate system angleData: if True, it means that the data were collected with a rotation stage and therefore do not have to be converted into angle """ if mean: intens = np.mean(self.signal, axis=0) else: intens = self.signal[-5] intens = np.mean(self.signal) if angleData: theta = self.x[0]*np.pi/180 else: theta = [np.arctan(z[0]/distance)+phaseShift for z in self.z] # normalize values to [0,1] intens -= np.min(intens) intens /= np.max(intens) self.ax1 = self.fig.add_subplot(111, polar=True) self.ax1.plot(theta, intens, color=color, linewidth=2.0, label=label) #self.ax1.set_theta_offset(-np.pi/2) self.ax1.get_yaxis().set_visible(False) def plot(self, rotate=False): self.ax1 = self.fig.add_subplot(111) self.ax1.margins(x=0) self.ax1.set_xlim(self.x.min(), self.x.max()) plt.pcolormesh(self.x,self.z,self.signal, edgecolors='face') self.fig.suptitle(self.title, y=0.98, weight='bold') self.fig.subplots_adjust(top=0.86) self.ax1.tick_params(labelright=True, labeltop=True) return self.fig def crosssection_plot(self, axis=0, subplot=None): cs = np.mean(self.signal, axis=axis) cs /= np.max(cs) self.ax_cutline[axis] = self.fig.add_subplot(subplot) ax = self.ax_cutline[axis] xlim = self.ax1.get_xlim() ylim = self.ax1.get_ylim() ratio = abs(xlim[1]-xlim[0])/abs(ylim[1]-ylim[0]) if axis == 0: ax.plot(self.x[0, :], cs) ax.set_aspect(ratio*7) ax.set_xlim(xlim) ax.set_ylim([0, 1.05]) ax.xaxis.set_label_position('top') ax.xaxis.set_ticks_position('top') ax.set_xlabel(r"$\theta$ / degrees") ax.set_ylabel("intensity / arb. u.", fontsize=7) self.ax1.xaxis.label.set_visible(False) elif axis == 1: ax.plot(cs, self.z[:, 0]) ax.set_xlim([1.05, 0]) ax.set_ylim(ylim) ax.set_aspect(ratio/7) if self.distance is not None and self.angular_direction == 'z': ax.set_ylabel("$\phi$ / degrees") else: ax.set_ylabel("Z / mm") ax.set_xlabel("intensity / arb. u.", fontsize=7) self.ax1.yaxis.label.set_visible(False) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. def plotInterpolate(self, xPoints, zPoints, rotate=False, origin='lower', cutlines=False): if not cutlines: self.ax1 = self.fig.add_subplot(111) else: #self.gs1 = gridspec.GridSpec(2, 2) #self.gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes. self.ax1 = self.fig.add_subplot(224) self.ax_cutline = [None, None] self.ax1.tick_params(labelright=True, labelbottom=True, labelleft=False, bottom=True, right=True, left=False) self.ax1.set_xlabel(r"$\theta$ / degrees") if self.distance is not None and self.angular_direction == 'z': self.ax1.set_ylabel("$\phi$ / degrees") else: self.ax1.set_ylabel("Z / mm") xi, zi = np.linspace(self.x.min(), self.x.max(), xPoints), np.linspace(self.z.min(), self.z.max(), zPoints) xi, zi = np.meshgrid(xi, zi) rbf = scipy.interpolate.Rbf(self.x, self.z, self.signal, function='linear') sigi = rbf(xi, zi) # normalise again after interpolation — just so the colorbar # extends from 0 to 1 sigi /= np.max(sigi) if rotate: sigi = np.rot90(sigi) sigi[-1, -1] = 0 pltmesh = plt.imshow(sigi, extent=[self.x.min(), self.x.max(), self.z.min(), self.z.max()], origin=origin, aspect='auto') self.ax1.set_facecolor(pltmesh.cmap(0.0)) cb = self.fig.colorbar(pltmesh, ticks=[0, 1]) cb.set_label('light intensity / arb. u.') if cutlines: self.crosssection_plot(axis=0, subplot=222) self.crosssection_plot(axis=1, subplot=223) self.fig.subplots_adjust(hspace=-0.1, wspace=-0.2) #self.fig.suptitle(self.title, y=0.98, weight='bold') #self.fig.subplots_adjust(top=0.12, left=0.7) #self.ax1.tick_params(labelright=True, labeltop=True) def insert_laser_orientation(self, orientation_image_path, x, y): # https://stackoverflow.com/questions/3609585/how-to-insert-a-small-image-on-the-corner-of-a-plot-with-matplotlib im =
def show(self): plt.savefig(self.output_filename + '.pdf') plt.savefig(self.output_filename + '.svg') plt.savefig(self.output_filename + '.png', transparent=True) plt.show()
Image.open(orientation_image_path) height = im.size[1] im = np.array(im).astype(np.float) / 255 self.fig.figimage(im, x, self.fig.bbox.ymax - height - y)
identifier_body
page.py
# encoding: utf-8 """ Paging capabilities for IPython.core Authors: * Brian Granger * Fernando Perez Notes ----- For now this uses ipapi, so it can't be in IPython.utils. If we can get rid of that dependency, we could move it there. ----- """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function import os import re import sys import tempfile from io import UnsupportedOperation from IPython import get_ipython from IPython.core.error import TryNext from IPython.utils.data import chop from IPython.utils import io from IPython.utils.process import system from IPython.utils.terminal import get_terminal_size from IPython.utils import py3compat #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- esc_re = re.compile(r"(\x1b[^m]+m)") def page_dumb(strng, start=0, screen_lines=25): """Very dumb 'pager' in Python, for when nothing else works. Only moves forward, same interface as page(), except for pager_cmd and mode.""" out_ln = strng.splitlines()[start:] screens = chop(out_ln, screen_lines - 1) if len(screens) == 1: print(os.linesep.join(screens[0]), file=io.stdout) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) print(last_escape + hunk, file=io.stdout) if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] print(last_escape + os.linesep.join(screens[-1]), file=io.stdout) def _detect_screen_size(screen_lines_def): """Attempt to work out the number of lines on the screen. This is called by page(). It can raise an error (e.g. when run in the test suite), so it's separated out so it can easily be called in a try block. """ TERM = os.environ.get('TERM', None) if not((TERM == 'xterm' or TERM == 'xterm-color') and sys.platform != 'sunos5'): # curses causes problems on many terminals other than xterm, and # some termios calls lock up on Sun OS5. return screen_lines_def try: import termios import curses except ImportError: return screen_lines_def # There is a bug in curses, where *sometimes* it fails to properly # initialize, and then after the endwin() call is made, the # terminal is left in an unusable state. Rather than trying to # check everytime for this (by requesting and comparing termios # flags each time), we just save the initial terminal state and # unconditionally reset it every time. It's cheaper than making # the checks. term_flags = termios.tcgetattr(sys.stdout) # Curses modifies the stdout buffer size by default, which messes # up Python's normal stdout buffering. This would manifest itself # to IPython users as delayed printing on stdout after having used # the pager. # # We can prevent this by manually setting the NCURSES_NO_SETBUF # environment variable. For more details, see: # http://bugs.python.org/issue10144 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None) os.environ['NCURSES_NO_SETBUF'] = '' # Proceed with curses initialization try: scr = curses.initscr() except AttributeError: # Curses on Solaris may not be complete, so we can't use it there return screen_lines_def screen_lines_real, screen_cols = scr.getmaxyx() curses.endwin() # Restore environment if NCURSES_NO_SETBUF is None: del os.environ['NCURSES_NO_SETBUF'] else: os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF # Restore terminal state in case endwin() didn't. termios.tcsetattr(sys.stdout, termios.TCSANOW, term_flags) # Now we have what we needed: the screen size in rows/columns return screen_lines_real # print '***Screen size:',screen_lines_real,'lines x',\ # screen_cols,'columns.' # dbg def page(strng, start=0, screen_lines=0, pager_cmd=None): """Display a string, piping through a pager after a certain length. strng can be a mime-bundle dict, supplying multiple representations, keyed by mime-type. The screen_lines parameter specifies the number of *usable* lines of your terminal screen (total lines minus lines you need to reserve to show other information). If you set screen_lines to a number <=0, page() will try to auto-determine your screen size and will only use up to (screen_size+screen_lines) for printing, paging after that. That is, if you want auto-detection but need to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for auto-detection without any lines reserved simply use screen_lines = 0. If a string won't fit in the allowed lines, it is sent through the specified pager command. If none given, look for PAGER in the environment, and ultimately default to less. If no system pager works, the string is sent through a 'dumb pager' written in python, very simplistic. """ # for compatibility with mime-bundle form: if isinstance(strng, dict): strng = strng['text/plain'] # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) # first, try the hook ip = get_ipython() if ip: try: ip.hooks.show_in_pager(strng) return except TryNext: pass # Ugly kludge, but calling curses.initscr() flat out crashes in emacs TERM = os.environ.get('TERM', 'dumb') if TERM in ['dumb', 'emacs'] and os.name != 'nt': print(strng) return # chop off the topmost part of the string we don't want to see str_lines = strng.splitlines()[start:] str_toprint = os.linesep.join(str_lines) num_newlines = len(str_lines) len_str = len(str_toprint) # Dumb heuristics to guesstimate number of on-screen lines the string # takes. Very basic, but good enough for docstrings in reasonable # terminals. If someone later feels like refining it, it's not hard. numlines = max(num_newlines, int(len_str / 80) + 1) screen_lines_def = get_terminal_size()[1] # auto-determine screen size if screen_lines <= 0: try: screen_lines += _detect_screen_size(screen_lines_def) except (TypeError, UnsupportedOperation): print(str_toprint, file=io.stdout) return # print 'numlines',numlines,'screenlines',screen_lines # dbg if numlines <= screen_lines: # print '*** normal print' # dbg print(str_toprint, file=io.stdout) else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return # value of a failed system command. If any intermediate attempt # sets retval to 1, at the end we resort to our own page_dumb() pager. pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) if os.name == 'nt': if pager_cmd.startswith('type'): # The default WinXP 'type' command is failing on complex # strings. retval = 1 else: fd, tmpname = tempfile.mkstemp('.txt') try: os.close(fd) with open(tmpname, 'wt') as tmpfile: tmpfile.write(strng) cmd = "%s < %s" % (pager_cmd, tmpname) # tmpfile needs to be closed for windows if os.system(cmd): retval = 1 else: retval = None finally: os.remove(tmpname) else: try: retval = None # if I use popen4, things hang. No idea why. #pager,shell_out = os.popen4(pager_cmd) pager = os.popen(pager_cmd, 'w') try: pager_encoding = pager.encoding or sys.stdout.encoding pager.write(py3compat.cast_bytes_py2( strng, encoding=pager_encoding)) finally: retval = pager.close() except IOError as msg: # broken pipe when user quits if msg.args == (32, 'Broken pipe'): retval = None else: retval = 1 except OSError: # Other strange problems, sometimes seen in Win2k/cygwin retval = 1 if retval is not None: page_dumb(strng, screen_lines=screen_lines) def
(fname, start=0, pager_cmd=None): """Page a file, using an optional pager command and starting line. """ pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) try: if os.environ['TERM'] in ['emacs', 'dumb']: raise EnvironmentError system(pager_cmd + ' ' + fname) except: try: if start > 0: start -= 1 page(open(fname).read(), start) except: print('Unable to show file', repr(fname)) def get_pager_cmd(pager_cmd=None): """Return a pager command. Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': default_pager_cmd = 'less -r' # -r for color control sequences elif os.name in ['nt', 'dos']: default_pager_cmd = 'type' if pager_cmd is None: try: pager_cmd = os.environ['PAGER'] except: pager_cmd = default_pager_cmd return pager_cmd def get_pager_start(pager, start): """Return the string for paging files with an offset. This is the '+N' argument which less and more (under Unix) accept. """ if pager in ['less', 'more']: if start: start_string = '+' + str(start) else: start_string = '' else: start_string = '' return start_string # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch() if os.name == 'nt' and os.environ.get('TERM', 'dumb') != 'emacs': import msvcrt def page_more(): """ Smart pausing between pages @return: True if need print more lines, False if quit """ io.stdout.write('---Return to continue, q to quit--- ') ans = msvcrt.getwch() if ans in ("q", "Q"): result = False else: result = True io.stdout.write("\b" * 37 + " " * 37 + "\b" * 37) return result else: def page_more(): ans = py3compat.input('---Return to continue, q to quit--- ') if ans.lower().startswith('q'): return False else: return True def snip_print(str, width=75, print_full=0, header=''): """Print a string snipping the midsection to fit in width. print_full: mode control: - 0: only snip long strings - 1: send to page() directly. - 2: snip long strings and ask for full length viewing with page() Return 1 if snipping was necessary, 0 otherwise.""" if print_full == 1: page(header + str) return 0 print(header, end=' ') if len(str) < width: print(str) snip = 0 else: whalf = int((width - 5) / 2) print(str[:whalf] + ' <...> ' + str[-whalf:]) snip = 1 if snip and print_full == 2: if py3compat.input(header + ' Snipped. View (y/n)? [N]').lower() == 'y': page(str) return snip
page_file
identifier_name
page.py
# encoding: utf-8 """ Paging capabilities for IPython.core Authors: * Brian Granger * Fernando Perez Notes ----- For now this uses ipapi, so it can't be in IPython.utils. If we can get rid of that dependency, we could move it there. ----- """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function import os import re import sys import tempfile from io import UnsupportedOperation from IPython import get_ipython from IPython.core.error import TryNext from IPython.utils.data import chop from IPython.utils import io from IPython.utils.process import system from IPython.utils.terminal import get_terminal_size from IPython.utils import py3compat #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- esc_re = re.compile(r"(\x1b[^m]+m)") def page_dumb(strng, start=0, screen_lines=25): """Very dumb 'pager' in Python, for when nothing else works. Only moves forward, same interface as page(), except for pager_cmd and mode.""" out_ln = strng.splitlines()[start:] screens = chop(out_ln, screen_lines - 1) if len(screens) == 1: print(os.linesep.join(screens[0]), file=io.stdout) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) print(last_escape + hunk, file=io.stdout) if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] print(last_escape + os.linesep.join(screens[-1]), file=io.stdout) def _detect_screen_size(screen_lines_def): """Attempt to work out the number of lines on the screen. This is called by page(). It can raise an error (e.g. when run in the test suite), so it's separated out so it can easily be called in a try block. """ TERM = os.environ.get('TERM', None) if not((TERM == 'xterm' or TERM == 'xterm-color') and sys.platform != 'sunos5'): # curses causes problems on many terminals other than xterm, and # some termios calls lock up on Sun OS5. return screen_lines_def try: import termios import curses except ImportError: return screen_lines_def # There is a bug in curses, where *sometimes* it fails to properly # initialize, and then after the endwin() call is made, the # terminal is left in an unusable state. Rather than trying to # check everytime for this (by requesting and comparing termios # flags each time), we just save the initial terminal state and # unconditionally reset it every time. It's cheaper than making # the checks. term_flags = termios.tcgetattr(sys.stdout) # Curses modifies the stdout buffer size by default, which messes # up Python's normal stdout buffering. This would manifest itself # to IPython users as delayed printing on stdout after having used # the pager. # # We can prevent this by manually setting the NCURSES_NO_SETBUF # environment variable. For more details, see: # http://bugs.python.org/issue10144 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None) os.environ['NCURSES_NO_SETBUF'] = '' # Proceed with curses initialization try: scr = curses.initscr() except AttributeError: # Curses on Solaris may not be complete, so we can't use it there return screen_lines_def screen_lines_real, screen_cols = scr.getmaxyx() curses.endwin() # Restore environment if NCURSES_NO_SETBUF is None: del os.environ['NCURSES_NO_SETBUF'] else: os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF # Restore terminal state in case endwin() didn't. termios.tcsetattr(sys.stdout, termios.TCSANOW, term_flags) # Now we have what we needed: the screen size in rows/columns return screen_lines_real # print '***Screen size:',screen_lines_real,'lines x',\ # screen_cols,'columns.' # dbg def page(strng, start=0, screen_lines=0, pager_cmd=None): """Display a string, piping through a pager after a certain length. strng can be a mime-bundle dict, supplying multiple representations, keyed by mime-type. The screen_lines parameter specifies the number of *usable* lines of your terminal screen (total lines minus lines you need to reserve to show other information). If you set screen_lines to a number <=0, page() will try to auto-determine your screen size and will only use up to (screen_size+screen_lines) for printing, paging after that. That is, if you want auto-detection but need to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for auto-detection without any lines reserved simply use screen_lines = 0. If a string won't fit in the allowed lines, it is sent through the specified pager command. If none given, look for PAGER in the environment, and ultimately default to less. If no system pager works, the string is sent through a 'dumb pager' written in python, very simplistic. """ # for compatibility with mime-bundle form: if isinstance(strng, dict): strng = strng['text/plain'] # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) # first, try the hook ip = get_ipython() if ip: try: ip.hooks.show_in_pager(strng) return except TryNext: pass # Ugly kludge, but calling curses.initscr() flat out crashes in emacs TERM = os.environ.get('TERM', 'dumb') if TERM in ['dumb', 'emacs'] and os.name != 'nt': print(strng) return # chop off the topmost part of the string we don't want to see str_lines = strng.splitlines()[start:] str_toprint = os.linesep.join(str_lines) num_newlines = len(str_lines) len_str = len(str_toprint) # Dumb heuristics to guesstimate number of on-screen lines the string # takes. Very basic, but good enough for docstrings in reasonable # terminals. If someone later feels like refining it, it's not hard. numlines = max(num_newlines, int(len_str / 80) + 1) screen_lines_def = get_terminal_size()[1] # auto-determine screen size if screen_lines <= 0:
# print 'numlines',numlines,'screenlines',screen_lines # dbg if numlines <= screen_lines: # print '*** normal print' # dbg print(str_toprint, file=io.stdout) else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return # value of a failed system command. If any intermediate attempt # sets retval to 1, at the end we resort to our own page_dumb() pager. pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) if os.name == 'nt': if pager_cmd.startswith('type'): # The default WinXP 'type' command is failing on complex # strings. retval = 1 else: fd, tmpname = tempfile.mkstemp('.txt') try: os.close(fd) with open(tmpname, 'wt') as tmpfile: tmpfile.write(strng) cmd = "%s < %s" % (pager_cmd, tmpname) # tmpfile needs to be closed for windows if os.system(cmd): retval = 1 else: retval = None finally: os.remove(tmpname) else: try: retval = None # if I use popen4, things hang. No idea why. #pager,shell_out = os.popen4(pager_cmd) pager = os.popen(pager_cmd, 'w') try: pager_encoding = pager.encoding or sys.stdout.encoding pager.write(py3compat.cast_bytes_py2( strng, encoding=pager_encoding)) finally: retval = pager.close() except IOError as msg: # broken pipe when user quits if msg.args == (32, 'Broken pipe'): retval = None else: retval = 1 except OSError: # Other strange problems, sometimes seen in Win2k/cygwin retval = 1 if retval is not None: page_dumb(strng, screen_lines=screen_lines) def page_file(fname, start=0, pager_cmd=None): """Page a file, using an optional pager command and starting line. """ pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) try: if os.environ['TERM'] in ['emacs', 'dumb']: raise EnvironmentError system(pager_cmd + ' ' + fname) except: try: if start > 0: start -= 1 page(open(fname).read(), start) except: print('Unable to show file', repr(fname)) def get_pager_cmd(pager_cmd=None): """Return a pager command. Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': default_pager_cmd = 'less -r' # -r for color control sequences elif os.name in ['nt', 'dos']: default_pager_cmd = 'type' if pager_cmd is None: try: pager_cmd = os.environ['PAGER'] except: pager_cmd = default_pager_cmd return pager_cmd def get_pager_start(pager, start): """Return the string for paging files with an offset. This is the '+N' argument which less and more (under Unix) accept. """ if pager in ['less', 'more']: if start: start_string = '+' + str(start) else: start_string = '' else: start_string = '' return start_string # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch() if os.name == 'nt' and os.environ.get('TERM', 'dumb') != 'emacs': import msvcrt def page_more(): """ Smart pausing between pages @return: True if need print more lines, False if quit """ io.stdout.write('---Return to continue, q to quit--- ') ans = msvcrt.getwch() if ans in ("q", "Q"): result = False else: result = True io.stdout.write("\b" * 37 + " " * 37 + "\b" * 37) return result else: def page_more(): ans = py3compat.input('---Return to continue, q to quit--- ') if ans.lower().startswith('q'): return False else: return True def snip_print(str, width=75, print_full=0, header=''): """Print a string snipping the midsection to fit in width. print_full: mode control: - 0: only snip long strings - 1: send to page() directly. - 2: snip long strings and ask for full length viewing with page() Return 1 if snipping was necessary, 0 otherwise.""" if print_full == 1: page(header + str) return 0 print(header, end=' ') if len(str) < width: print(str) snip = 0 else: whalf = int((width - 5) / 2) print(str[:whalf] + ' <...> ' + str[-whalf:]) snip = 1 if snip and print_full == 2: if py3compat.input(header + ' Snipped. View (y/n)? [N]').lower() == 'y': page(str) return snip
try: screen_lines += _detect_screen_size(screen_lines_def) except (TypeError, UnsupportedOperation): print(str_toprint, file=io.stdout) return
conditional_block
page.py
# encoding: utf-8 """ Paging capabilities for IPython.core Authors: * Brian Granger * Fernando Perez Notes ----- For now this uses ipapi, so it can't be in IPython.utils. If we can get rid of that dependency, we could move it there. ----- """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function import os import re import sys import tempfile from io import UnsupportedOperation from IPython import get_ipython from IPython.core.error import TryNext from IPython.utils.data import chop from IPython.utils import io from IPython.utils.process import system from IPython.utils.terminal import get_terminal_size from IPython.utils import py3compat #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- esc_re = re.compile(r"(\x1b[^m]+m)") def page_dumb(strng, start=0, screen_lines=25): """Very dumb 'pager' in Python, for when nothing else works. Only moves forward, same interface as page(), except for pager_cmd and mode.""" out_ln = strng.splitlines()[start:] screens = chop(out_ln, screen_lines - 1) if len(screens) == 1: print(os.linesep.join(screens[0]), file=io.stdout) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) print(last_escape + hunk, file=io.stdout) if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] print(last_escape + os.linesep.join(screens[-1]), file=io.stdout) def _detect_screen_size(screen_lines_def): """Attempt to work out the number of lines on the screen. This is called by page(). It can raise an error (e.g. when run in the test suite), so it's separated out so it can easily be called in a try block. """ TERM = os.environ.get('TERM', None) if not((TERM == 'xterm' or TERM == 'xterm-color') and sys.platform != 'sunos5'): # curses causes problems on many terminals other than xterm, and # some termios calls lock up on Sun OS5. return screen_lines_def try: import termios import curses except ImportError: return screen_lines_def # There is a bug in curses, where *sometimes* it fails to properly # initialize, and then after the endwin() call is made, the # terminal is left in an unusable state. Rather than trying to # check everytime for this (by requesting and comparing termios # flags each time), we just save the initial terminal state and # unconditionally reset it every time. It's cheaper than making # the checks. term_flags = termios.tcgetattr(sys.stdout) # Curses modifies the stdout buffer size by default, which messes # up Python's normal stdout buffering. This would manifest itself # to IPython users as delayed printing on stdout after having used # the pager. # # We can prevent this by manually setting the NCURSES_NO_SETBUF # environment variable. For more details, see: # http://bugs.python.org/issue10144 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None) os.environ['NCURSES_NO_SETBUF'] = '' # Proceed with curses initialization try: scr = curses.initscr() except AttributeError: # Curses on Solaris may not be complete, so we can't use it there return screen_lines_def screen_lines_real, screen_cols = scr.getmaxyx() curses.endwin() # Restore environment if NCURSES_NO_SETBUF is None: del os.environ['NCURSES_NO_SETBUF'] else: os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF # Restore terminal state in case endwin() didn't. termios.tcsetattr(sys.stdout, termios.TCSANOW, term_flags) # Now we have what we needed: the screen size in rows/columns return screen_lines_real # print '***Screen size:',screen_lines_real,'lines x',\ # screen_cols,'columns.' # dbg def page(strng, start=0, screen_lines=0, pager_cmd=None): """Display a string, piping through a pager after a certain length. strng can be a mime-bundle dict, supplying multiple representations, keyed by mime-type. The screen_lines parameter specifies the number of *usable* lines of your terminal screen (total lines minus lines you need to reserve to show other information). If you set screen_lines to a number <=0, page() will try to auto-determine your screen size and will only use up to (screen_size+screen_lines) for printing, paging after that. That is, if you want auto-detection but need to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for auto-detection without any lines reserved simply use screen_lines = 0. If a string won't fit in the allowed lines, it is sent through the specified pager command. If none given, look for PAGER in the environment, and ultimately default to less. If no system pager works, the string is sent through a 'dumb pager' written in python, very simplistic. """ # for compatibility with mime-bundle form: if isinstance(strng, dict): strng = strng['text/plain'] # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) # first, try the hook ip = get_ipython() if ip: try: ip.hooks.show_in_pager(strng) return except TryNext: pass # Ugly kludge, but calling curses.initscr() flat out crashes in emacs TERM = os.environ.get('TERM', 'dumb') if TERM in ['dumb', 'emacs'] and os.name != 'nt': print(strng) return # chop off the topmost part of the string we don't want to see str_lines = strng.splitlines()[start:] str_toprint = os.linesep.join(str_lines) num_newlines = len(str_lines) len_str = len(str_toprint) # Dumb heuristics to guesstimate number of on-screen lines the string # takes. Very basic, but good enough for docstrings in reasonable # terminals. If someone later feels like refining it, it's not hard. numlines = max(num_newlines, int(len_str / 80) + 1) screen_lines_def = get_terminal_size()[1] # auto-determine screen size if screen_lines <= 0: try: screen_lines += _detect_screen_size(screen_lines_def) except (TypeError, UnsupportedOperation): print(str_toprint, file=io.stdout) return # print 'numlines',numlines,'screenlines',screen_lines # dbg if numlines <= screen_lines: # print '*** normal print' # dbg print(str_toprint, file=io.stdout) else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return # value of a failed system command. If any intermediate attempt # sets retval to 1, at the end we resort to our own page_dumb() pager. pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) if os.name == 'nt': if pager_cmd.startswith('type'): # The default WinXP 'type' command is failing on complex # strings. retval = 1 else: fd, tmpname = tempfile.mkstemp('.txt') try: os.close(fd) with open(tmpname, 'wt') as tmpfile: tmpfile.write(strng) cmd = "%s < %s" % (pager_cmd, tmpname) # tmpfile needs to be closed for windows if os.system(cmd): retval = 1 else: retval = None finally: os.remove(tmpname) else: try: retval = None # if I use popen4, things hang. No idea why. #pager,shell_out = os.popen4(pager_cmd) pager = os.popen(pager_cmd, 'w') try: pager_encoding = pager.encoding or sys.stdout.encoding pager.write(py3compat.cast_bytes_py2( strng, encoding=pager_encoding)) finally: retval = pager.close() except IOError as msg: # broken pipe when user quits if msg.args == (32, 'Broken pipe'): retval = None else: retval = 1 except OSError: # Other strange problems, sometimes seen in Win2k/cygwin retval = 1 if retval is not None: page_dumb(strng, screen_lines=screen_lines) def page_file(fname, start=0, pager_cmd=None): """Page a file, using an optional pager command and starting line. """ pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) try: if os.environ['TERM'] in ['emacs', 'dumb']: raise EnvironmentError system(pager_cmd + ' ' + fname) except: try: if start > 0: start -= 1 page(open(fname).read(), start) except: print('Unable to show file', repr(fname)) def get_pager_cmd(pager_cmd=None): """Return a pager command. Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': default_pager_cmd = 'less -r' # -r for color control sequences elif os.name in ['nt', 'dos']: default_pager_cmd = 'type' if pager_cmd is None: try: pager_cmd = os.environ['PAGER'] except: pager_cmd = default_pager_cmd return pager_cmd def get_pager_start(pager, start): """Return the string for paging files with an offset. This is the '+N' argument which less and more (under Unix) accept. """ if pager in ['less', 'more']: if start: start_string = '+' + str(start) else: start_string = '' else: start_string = '' return start_string # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch() if os.name == 'nt' and os.environ.get('TERM', 'dumb') != 'emacs': import msvcrt def page_more(): """ Smart pausing between pages @return: True if need print more lines, False if quit """ io.stdout.write('---Return to continue, q to quit--- ')
result = True io.stdout.write("\b" * 37 + " " * 37 + "\b" * 37) return result else: def page_more(): ans = py3compat.input('---Return to continue, q to quit--- ') if ans.lower().startswith('q'): return False else: return True def snip_print(str, width=75, print_full=0, header=''): """Print a string snipping the midsection to fit in width. print_full: mode control: - 0: only snip long strings - 1: send to page() directly. - 2: snip long strings and ask for full length viewing with page() Return 1 if snipping was necessary, 0 otherwise.""" if print_full == 1: page(header + str) return 0 print(header, end=' ') if len(str) < width: print(str) snip = 0 else: whalf = int((width - 5) / 2) print(str[:whalf] + ' <...> ' + str[-whalf:]) snip = 1 if snip and print_full == 2: if py3compat.input(header + ' Snipped. View (y/n)? [N]').lower() == 'y': page(str) return snip
ans = msvcrt.getwch() if ans in ("q", "Q"): result = False else:
random_line_split
page.py
# encoding: utf-8 """ Paging capabilities for IPython.core Authors: * Brian Granger * Fernando Perez Notes ----- For now this uses ipapi, so it can't be in IPython.utils. If we can get rid of that dependency, we could move it there. ----- """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function import os import re import sys import tempfile from io import UnsupportedOperation from IPython import get_ipython from IPython.core.error import TryNext from IPython.utils.data import chop from IPython.utils import io from IPython.utils.process import system from IPython.utils.terminal import get_terminal_size from IPython.utils import py3compat #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- esc_re = re.compile(r"(\x1b[^m]+m)") def page_dumb(strng, start=0, screen_lines=25): """Very dumb 'pager' in Python, for when nothing else works. Only moves forward, same interface as page(), except for pager_cmd and mode.""" out_ln = strng.splitlines()[start:] screens = chop(out_ln, screen_lines - 1) if len(screens) == 1: print(os.linesep.join(screens[0]), file=io.stdout) else: last_escape = "" for scr in screens[0:-1]: hunk = os.linesep.join(scr) print(last_escape + hunk, file=io.stdout) if not page_more(): return esc_list = esc_re.findall(hunk) if len(esc_list) > 0: last_escape = esc_list[-1] print(last_escape + os.linesep.join(screens[-1]), file=io.stdout) def _detect_screen_size(screen_lines_def): """Attempt to work out the number of lines on the screen. This is called by page(). It can raise an error (e.g. when run in the test suite), so it's separated out so it can easily be called in a try block. """ TERM = os.environ.get('TERM', None) if not((TERM == 'xterm' or TERM == 'xterm-color') and sys.platform != 'sunos5'): # curses causes problems on many terminals other than xterm, and # some termios calls lock up on Sun OS5. return screen_lines_def try: import termios import curses except ImportError: return screen_lines_def # There is a bug in curses, where *sometimes* it fails to properly # initialize, and then after the endwin() call is made, the # terminal is left in an unusable state. Rather than trying to # check everytime for this (by requesting and comparing termios # flags each time), we just save the initial terminal state and # unconditionally reset it every time. It's cheaper than making # the checks. term_flags = termios.tcgetattr(sys.stdout) # Curses modifies the stdout buffer size by default, which messes # up Python's normal stdout buffering. This would manifest itself # to IPython users as delayed printing on stdout after having used # the pager. # # We can prevent this by manually setting the NCURSES_NO_SETBUF # environment variable. For more details, see: # http://bugs.python.org/issue10144 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None) os.environ['NCURSES_NO_SETBUF'] = '' # Proceed with curses initialization try: scr = curses.initscr() except AttributeError: # Curses on Solaris may not be complete, so we can't use it there return screen_lines_def screen_lines_real, screen_cols = scr.getmaxyx() curses.endwin() # Restore environment if NCURSES_NO_SETBUF is None: del os.environ['NCURSES_NO_SETBUF'] else: os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF # Restore terminal state in case endwin() didn't. termios.tcsetattr(sys.stdout, termios.TCSANOW, term_flags) # Now we have what we needed: the screen size in rows/columns return screen_lines_real # print '***Screen size:',screen_lines_real,'lines x',\ # screen_cols,'columns.' # dbg def page(strng, start=0, screen_lines=0, pager_cmd=None):
def page_file(fname, start=0, pager_cmd=None): """Page a file, using an optional pager command and starting line. """ pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) try: if os.environ['TERM'] in ['emacs', 'dumb']: raise EnvironmentError system(pager_cmd + ' ' + fname) except: try: if start > 0: start -= 1 page(open(fname).read(), start) except: print('Unable to show file', repr(fname)) def get_pager_cmd(pager_cmd=None): """Return a pager command. Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': default_pager_cmd = 'less -r' # -r for color control sequences elif os.name in ['nt', 'dos']: default_pager_cmd = 'type' if pager_cmd is None: try: pager_cmd = os.environ['PAGER'] except: pager_cmd = default_pager_cmd return pager_cmd def get_pager_start(pager, start): """Return the string for paging files with an offset. This is the '+N' argument which less and more (under Unix) accept. """ if pager in ['less', 'more']: if start: start_string = '+' + str(start) else: start_string = '' else: start_string = '' return start_string # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch() if os.name == 'nt' and os.environ.get('TERM', 'dumb') != 'emacs': import msvcrt def page_more(): """ Smart pausing between pages @return: True if need print more lines, False if quit """ io.stdout.write('---Return to continue, q to quit--- ') ans = msvcrt.getwch() if ans in ("q", "Q"): result = False else: result = True io.stdout.write("\b" * 37 + " " * 37 + "\b" * 37) return result else: def page_more(): ans = py3compat.input('---Return to continue, q to quit--- ') if ans.lower().startswith('q'): return False else: return True def snip_print(str, width=75, print_full=0, header=''): """Print a string snipping the midsection to fit in width. print_full: mode control: - 0: only snip long strings - 1: send to page() directly. - 2: snip long strings and ask for full length viewing with page() Return 1 if snipping was necessary, 0 otherwise.""" if print_full == 1: page(header + str) return 0 print(header, end=' ') if len(str) < width: print(str) snip = 0 else: whalf = int((width - 5) / 2) print(str[:whalf] + ' <...> ' + str[-whalf:]) snip = 1 if snip and print_full == 2: if py3compat.input(header + ' Snipped. View (y/n)? [N]').lower() == 'y': page(str) return snip
"""Display a string, piping through a pager after a certain length. strng can be a mime-bundle dict, supplying multiple representations, keyed by mime-type. The screen_lines parameter specifies the number of *usable* lines of your terminal screen (total lines minus lines you need to reserve to show other information). If you set screen_lines to a number <=0, page() will try to auto-determine your screen size and will only use up to (screen_size+screen_lines) for printing, paging after that. That is, if you want auto-detection but need to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for auto-detection without any lines reserved simply use screen_lines = 0. If a string won't fit in the allowed lines, it is sent through the specified pager command. If none given, look for PAGER in the environment, and ultimately default to less. If no system pager works, the string is sent through a 'dumb pager' written in python, very simplistic. """ # for compatibility with mime-bundle form: if isinstance(strng, dict): strng = strng['text/plain'] # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) # first, try the hook ip = get_ipython() if ip: try: ip.hooks.show_in_pager(strng) return except TryNext: pass # Ugly kludge, but calling curses.initscr() flat out crashes in emacs TERM = os.environ.get('TERM', 'dumb') if TERM in ['dumb', 'emacs'] and os.name != 'nt': print(strng) return # chop off the topmost part of the string we don't want to see str_lines = strng.splitlines()[start:] str_toprint = os.linesep.join(str_lines) num_newlines = len(str_lines) len_str = len(str_toprint) # Dumb heuristics to guesstimate number of on-screen lines the string # takes. Very basic, but good enough for docstrings in reasonable # terminals. If someone later feels like refining it, it's not hard. numlines = max(num_newlines, int(len_str / 80) + 1) screen_lines_def = get_terminal_size()[1] # auto-determine screen size if screen_lines <= 0: try: screen_lines += _detect_screen_size(screen_lines_def) except (TypeError, UnsupportedOperation): print(str_toprint, file=io.stdout) return # print 'numlines',numlines,'screenlines',screen_lines # dbg if numlines <= screen_lines: # print '*** normal print' # dbg print(str_toprint, file=io.stdout) else: # Try to open pager and default to internal one if that fails. # All failure modes are tagged as 'retval=1', to match the return # value of a failed system command. If any intermediate attempt # sets retval to 1, at the end we resort to our own page_dumb() pager. pager_cmd = get_pager_cmd(pager_cmd) pager_cmd += ' ' + get_pager_start(pager_cmd, start) if os.name == 'nt': if pager_cmd.startswith('type'): # The default WinXP 'type' command is failing on complex # strings. retval = 1 else: fd, tmpname = tempfile.mkstemp('.txt') try: os.close(fd) with open(tmpname, 'wt') as tmpfile: tmpfile.write(strng) cmd = "%s < %s" % (pager_cmd, tmpname) # tmpfile needs to be closed for windows if os.system(cmd): retval = 1 else: retval = None finally: os.remove(tmpname) else: try: retval = None # if I use popen4, things hang. No idea why. #pager,shell_out = os.popen4(pager_cmd) pager = os.popen(pager_cmd, 'w') try: pager_encoding = pager.encoding or sys.stdout.encoding pager.write(py3compat.cast_bytes_py2( strng, encoding=pager_encoding)) finally: retval = pager.close() except IOError as msg: # broken pipe when user quits if msg.args == (32, 'Broken pipe'): retval = None else: retval = 1 except OSError: # Other strange problems, sometimes seen in Win2k/cygwin retval = 1 if retval is not None: page_dumb(strng, screen_lines=screen_lines)
identifier_body
domparser.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 crate::document_loader::DocumentLoader; use crate::dom::bindings::codegen::Bindings::DOMParserBinding; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::DocumentSource; use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::servoparser::ServoParser; use crate::dom::window::Window; use dom_struct::dom_struct; use script_traits::DocumentActivity; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: Dom<Window>, // XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: &Window) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: Dom::from_ref(window), } } pub fn new(window: &Window) -> DomRoot<DOMParser> { reflect_dom_object( Box::new(DOMParser::new_inherited(window)), window, DOMParserBinding::Wrap, ) } pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>> { Ok(DOMParser::new(window)) } } impl DOMParserMethods for DOMParser { // https://w3c.github.io/DOM-Parsing/#the-domparser-interface fn ParseFromString( &self, s: DOMString, ty: DOMParserBinding::SupportedType, ) -> Fallible<DomRoot<Document>> { let url = self.window.get_url(); let content_type = ty .as_str() .parse() .expect("Supported type is not a MIME type"); let doc = self.window.Document(); let loader = DocumentLoader::new(&*doc.loader()); match ty { Text_html => { let document = Document::new( &self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_html_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) }, Text_xml | Application_xml | Application_xhtml_xml =>
, } } }
{ let document = Document::new( &self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::NonHTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_xml_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) }
conditional_block
domparser.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 crate::document_loader::DocumentLoader; use crate::dom::bindings::codegen::Bindings::DOMParserBinding; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::DocumentSource; use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::servoparser::ServoParser; use crate::dom::window::Window; use dom_struct::dom_struct; use script_traits::DocumentActivity; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: Dom<Window>, // XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: &Window) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: Dom::from_ref(window), } } pub fn new(window: &Window) -> DomRoot<DOMParser> { reflect_dom_object( Box::new(DOMParser::new_inherited(window)), window, DOMParserBinding::Wrap, ) } pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>> { Ok(DOMParser::new(window)) } } impl DOMParserMethods for DOMParser { // https://w3c.github.io/DOM-Parsing/#the-domparser-interface fn ParseFromString( &self, s: DOMString, ty: DOMParserBinding::SupportedType, ) -> Fallible<DomRoot<Document>> { let url = self.window.get_url(); let content_type = ty .as_str() .parse() .expect("Supported type is not a MIME type"); let doc = self.window.Document(); let loader = DocumentLoader::new(&*doc.loader()); match ty { Text_html => { let document = Document::new( &self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_html_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) },
&self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::NonHTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_xml_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) }, } } }
Text_xml | Application_xml | Application_xhtml_xml => { let document = Document::new(
random_line_split
domparser.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 crate::document_loader::DocumentLoader; use crate::dom::bindings::codegen::Bindings::DOMParserBinding; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::DocumentSource; use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::servoparser::ServoParser; use crate::dom::window::Window; use dom_struct::dom_struct; use script_traits::DocumentActivity; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: Dom<Window>, // XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: &Window) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: Dom::from_ref(window), } } pub fn new(window: &Window) -> DomRoot<DOMParser> { reflect_dom_object( Box::new(DOMParser::new_inherited(window)), window, DOMParserBinding::Wrap, ) } pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>>
} impl DOMParserMethods for DOMParser { // https://w3c.github.io/DOM-Parsing/#the-domparser-interface fn ParseFromString( &self, s: DOMString, ty: DOMParserBinding::SupportedType, ) -> Fallible<DomRoot<Document>> { let url = self.window.get_url(); let content_type = ty .as_str() .parse() .expect("Supported type is not a MIME type"); let doc = self.window.Document(); let loader = DocumentLoader::new(&*doc.loader()); match ty { Text_html => { let document = Document::new( &self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_html_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) }, Text_xml | Application_xml | Application_xhtml_xml => { let document = Document::new( &self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::NonHTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_xml_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) }, } } }
{ Ok(DOMParser::new(window)) }
identifier_body
domparser.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 crate::document_loader::DocumentLoader; use crate::dom::bindings::codegen::Bindings::DOMParserBinding; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html; use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::document::DocumentSource; use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use crate::dom::servoparser::ServoParser; use crate::dom::window::Window; use dom_struct::dom_struct; use script_traits::DocumentActivity; #[dom_struct] pub struct DOMParser { reflector_: Reflector, window: Dom<Window>, // XXXjdm Document instead? } impl DOMParser { fn new_inherited(window: &Window) -> DOMParser { DOMParser { reflector_: Reflector::new(), window: Dom::from_ref(window), } } pub fn new(window: &Window) -> DomRoot<DOMParser> { reflect_dom_object( Box::new(DOMParser::new_inherited(window)), window, DOMParserBinding::Wrap, ) } pub fn
(window: &Window) -> Fallible<DomRoot<DOMParser>> { Ok(DOMParser::new(window)) } } impl DOMParserMethods for DOMParser { // https://w3c.github.io/DOM-Parsing/#the-domparser-interface fn ParseFromString( &self, s: DOMString, ty: DOMParserBinding::SupportedType, ) -> Fallible<DomRoot<Document>> { let url = self.window.get_url(); let content_type = ty .as_str() .parse() .expect("Supported type is not a MIME type"); let doc = self.window.Document(); let loader = DocumentLoader::new(&*doc.loader()); match ty { Text_html => { let document = Document::new( &self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::HTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_html_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) }, Text_xml | Application_xml | Application_xhtml_xml => { let document = Document::new( &self.window, HasBrowsingContext::No, Some(url.clone()), doc.origin().clone(), IsHTMLDocument::NonHTMLDocument, Some(content_type), None, DocumentActivity::Inactive, DocumentSource::FromParser, loader, None, None, Default::default(), ); ServoParser::parse_xml_document(&document, s, url); document.set_ready_state(DocumentReadyState::Complete); Ok(document) }, } } }
Constructor
identifier_name
graphicalgauge.py
import kivy kivy.require('1.9.1') from utils import kvFind from kivy.core.window import Window from kivy.properties import NumericProperty from autosportlabs.racecapture.views.dashboard.widgets.gauge import CustomizableGauge class GraphicalGauge(CustomizableGauge): _gaugeView = None gauge_size = NumericProperty(0) def _update_gauge_size(self, size):
def __init__(self, **kwargs): super(GraphicalGauge, self).__init__(**kwargs) def on_size(self, instance, value): width = value[0] height = value[1] size = width if width < height else height self._update_gauge_size(size) @property def graphView(self): if not self._gaugeView: self._gaugeView = kvFind(self, 'rcid', 'gauge') return self._gaugeView
self.gauge_size = size
identifier_body
graphicalgauge.py
import kivy kivy.require('1.9.1') from utils import kvFind from kivy.core.window import Window from kivy.properties import NumericProperty from autosportlabs.racecapture.views.dashboard.widgets.gauge import CustomizableGauge class GraphicalGauge(CustomizableGauge): _gaugeView = None gauge_size = NumericProperty(0) def _update_gauge_size(self, size): self.gauge_size = size def __init__(self, **kwargs): super(GraphicalGauge, self).__init__(**kwargs)
size = width if width < height else height self._update_gauge_size(size) @property def graphView(self): if not self._gaugeView: self._gaugeView = kvFind(self, 'rcid', 'gauge') return self._gaugeView
def on_size(self, instance, value): width = value[0] height = value[1]
random_line_split
graphicalgauge.py
import kivy kivy.require('1.9.1') from utils import kvFind from kivy.core.window import Window from kivy.properties import NumericProperty from autosportlabs.racecapture.views.dashboard.widgets.gauge import CustomizableGauge class GraphicalGauge(CustomizableGauge): _gaugeView = None gauge_size = NumericProperty(0) def _update_gauge_size(self, size): self.gauge_size = size def __init__(self, **kwargs): super(GraphicalGauge, self).__init__(**kwargs) def on_size(self, instance, value): width = value[0] height = value[1] size = width if width < height else height self._update_gauge_size(size) @property def graphView(self): if not self._gaugeView:
return self._gaugeView
self._gaugeView = kvFind(self, 'rcid', 'gauge')
conditional_block
graphicalgauge.py
import kivy kivy.require('1.9.1') from utils import kvFind from kivy.core.window import Window from kivy.properties import NumericProperty from autosportlabs.racecapture.views.dashboard.widgets.gauge import CustomizableGauge class GraphicalGauge(CustomizableGauge): _gaugeView = None gauge_size = NumericProperty(0) def
(self, size): self.gauge_size = size def __init__(self, **kwargs): super(GraphicalGauge, self).__init__(**kwargs) def on_size(self, instance, value): width = value[0] height = value[1] size = width if width < height else height self._update_gauge_size(size) @property def graphView(self): if not self._gaugeView: self._gaugeView = kvFind(self, 'rcid', 'gauge') return self._gaugeView
_update_gauge_size
identifier_name
complete_starter_form.js
var instanceURL = gs.getProperty("glide.servlet.uri"); var overrideURL = gs.getProperty("glide.email.override.url"); if (overrideURL)
else{ instanceURL = instanceURL; } var url = instanceURL + 'com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=299dbe0b0a0a3c4501c8951df102a2ae&manager_request=' + current.sys_id + '&first_name=' + current.u_first_name + '&last_name=' + current.u_last_name + '&known_as=' + current.u_known_as + '&job_title=' + current.u_job_title + '&grade=' + current.u_grade + '&region=' + current.u_region + '&sector=' + current.u_sector + '&service_line=' + current.u_service_line + '&employee_id=' + current.u_employee_id + '&manager_name=' + current.u_manager_name + '&start_date=' + current.u_start_date + '&contrator=' + current.u_contractor + '&end_date=' + current.u_end_date + '&hr_comments=' + current.u_hr_comments; gs.log(url); action.setRedirectURL(url); //condition current.u_request_id == '' && current.u_request_type == 'Starter' && current.u_assigned_to == gs.userID() || current.u_request_id == '' && current.u_request_type == 'Starter' && current.u_manager_name == gs.userID()
{ instanceURL = overrideURL; }
conditional_block
complete_starter_form.js
var instanceURL = gs.getProperty("glide.servlet.uri"); var overrideURL = gs.getProperty("glide.email.override.url"); if (overrideURL){ instanceURL = overrideURL; } else{ instanceURL = instanceURL; } var url = instanceURL + 'com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=299dbe0b0a0a3c4501c8951df102a2ae&manager_request=' + current.sys_id + '&first_name=' + current.u_first_name + '&last_name=' + current.u_last_name + '&known_as=' + current.u_known_as + '&job_title=' + current.u_job_title + '&grade=' + current.u_grade + '&region=' + current.u_region + '&sector=' + current.u_sector + '&service_line=' + current.u_service_line + '&employee_id=' + current.u_employee_id + '&manager_name=' + current.u_manager_name + '&start_date=' + current.u_start_date + '&contrator=' + current.u_contractor + '&end_date=' + current.u_end_date + '&hr_comments=' + current.u_hr_comments; gs.log(url); action.setRedirectURL(url);
//condition current.u_request_id == '' && current.u_request_type == 'Starter' && current.u_assigned_to == gs.userID() || current.u_request_id == '' && current.u_request_type == 'Starter' && current.u_manager_name == gs.userID()
random_line_split
builtins.rs
use crate::state::InterpState; use enum_iterator::IntoEnumIterator; /// Represents a builtin function #[derive(Debug, Clone, PartialEq, IntoEnumIterator)] pub enum Builtin { Dot, Plus, Minus, Star, Slash, Abs, And, Or, Xor, LShift, RShift, Equals, NotEquals, LessThan, GreaterThan, LessEqual, GreaterEqual, Emit, Dup, Swap, Over, Rot, Tuck, Drop, Fetch, Store, Here, Comma, Depth, Allot, } impl Builtin { pub fn
(&self) -> &'static str { match *self { Builtin::Dot => ".", Builtin::Plus => "+", Builtin::Minus => "-", Builtin::Star => "*", Builtin::Slash => "/", Builtin::Abs => "abs", Builtin::And => "and", Builtin::Or => "or", Builtin::Xor => "xor", Builtin::LShift => "lshift", Builtin::RShift => "rshift", Builtin::Equals => "=", Builtin::NotEquals => "<>", Builtin::LessThan => "<", Builtin::GreaterThan => ">", Builtin::LessEqual => "<=", Builtin::GreaterEqual => ">=", Builtin::Emit => "emit", Builtin::Dup => "dup", Builtin::Swap => "swap", Builtin::Over => "over", Builtin::Rot => "rot", Builtin::Tuck => "tuck", Builtin::Drop => "drop", Builtin::Here => "here", Builtin::Fetch => "@", Builtin::Store => "!", Builtin::Comma => ",", Builtin::Depth => "depth", Builtin::Allot => "allot", } } pub fn call(&self, state: &mut InterpState) { let stack = &mut state.stack; /// Allows defining a builtin using closure-like syntax. Note that the /// arguments are in reverse order, as that is how the stack is laid out. macro_rules! stackexpr { ( | $($aname:ident : $atype:ty),+ | $($value:expr),+ ) => { { $( let $aname: $atype = stack.pop(); )+ $( stack.push($value); )+ } } } use self::Builtin::*; match *self { Dot => print!("{}", stack.pop::<i32>()), Plus => stackexpr!(|n2: i32, n1: i32| n1 + n2), Minus => stackexpr!(|n2: i32, n1: i32| n1 - n2), Star => stackexpr!(|n2: i32, n1: i32| n1 * n2), Slash => stackexpr!(|n2: i32, n1: i32| n1 / n2), Abs => stackexpr!(|n: i32| n.abs()), And => stackexpr!(|n2: i32, n1: i32| n1 & n2), Or => stackexpr!(|n2: i32, n1: i32| n1 | n2), Xor => stackexpr!(|n2: i32, n1: i32| n1 ^ n2), LShift => stackexpr!(|u: i32, n: i32| n << u), RShift => stackexpr!(|u: i32, n: i32| n >> u), Equals => stackexpr!(|n2: i32, n1: i32| n1 == n2), NotEquals => stackexpr!(|n2: i32, n1: i32| n1 != n2), LessThan => stackexpr!(|n2: i32, n1: i32| n1 < n2), GreaterThan => stackexpr!(|n2: i32, n1: i32| n1 > n2), LessEqual => stackexpr!(|n2: i32, n1: i32| n1 <= n2), GreaterEqual => stackexpr!(|n2: i32, n1: i32| n1 >= n2), Emit => print!("{}", stack.pop::<char>()), Dup => { let n: i32 = stack.peak(); stack.push(n); } Swap => stackexpr!(|n2: i32, n1: i32| n2, n1), Over => stackexpr!(|n2: i32, n1: i32| n1, n2, n1), Rot => stackexpr!(|n3: i32, n2: i32, n1: i32| n2, n3, n1), Tuck => stackexpr!(|n2: i32, n1: i32| n2, n1, n2), Drop => { stack.pop::<i32>(); } Fetch => stackexpr!(|addr: i32| state.memory.get::<i32>(addr)), Store => { let addr: i32 = stack.pop(); let n: i32 = stack.pop(); state.memory.set(addr, n); } Here => stack.push(state.memory.here()), Comma => { state.memory.new(stack.pop::<i32>()); } Depth => { let len = stack.len(); stack.push(len); } Allot => { let n = stack.pop(); if n < 0 { // TODO Free memory } else { for _ in 0..n { state.memory.new(0); } } } } } }
word
identifier_name
builtins.rs
use crate::state::InterpState; use enum_iterator::IntoEnumIterator; /// Represents a builtin function #[derive(Debug, Clone, PartialEq, IntoEnumIterator)] pub enum Builtin { Dot, Plus, Minus, Star, Slash, Abs, And, Or, Xor, LShift, RShift, Equals, NotEquals, LessThan, GreaterThan, LessEqual, GreaterEqual, Emit, Dup, Swap, Over, Rot, Tuck, Drop, Fetch, Store, Here, Comma, Depth, Allot, } impl Builtin { pub fn word(&self) -> &'static str { match *self { Builtin::Dot => ".", Builtin::Plus => "+", Builtin::Minus => "-", Builtin::Star => "*", Builtin::Slash => "/", Builtin::Abs => "abs", Builtin::And => "and", Builtin::Or => "or", Builtin::Xor => "xor", Builtin::LShift => "lshift", Builtin::RShift => "rshift", Builtin::Equals => "=", Builtin::NotEquals => "<>", Builtin::LessThan => "<", Builtin::GreaterThan => ">", Builtin::LessEqual => "<=", Builtin::GreaterEqual => ">=", Builtin::Emit => "emit", Builtin::Dup => "dup", Builtin::Swap => "swap", Builtin::Over => "over", Builtin::Rot => "rot", Builtin::Tuck => "tuck", Builtin::Drop => "drop", Builtin::Here => "here", Builtin::Fetch => "@", Builtin::Store => "!", Builtin::Comma => ",", Builtin::Depth => "depth", Builtin::Allot => "allot", } } pub fn call(&self, state: &mut InterpState) { let stack = &mut state.stack; /// Allows defining a builtin using closure-like syntax. Note that the /// arguments are in reverse order, as that is how the stack is laid out. macro_rules! stackexpr { ( | $($aname:ident : $atype:ty),+ | $($value:expr),+ ) => { { $( let $aname: $atype = stack.pop(); )+ $( stack.push($value); )+ } } } use self::Builtin::*; match *self { Dot => print!("{}", stack.pop::<i32>()), Plus => stackexpr!(|n2: i32, n1: i32| n1 + n2), Minus => stackexpr!(|n2: i32, n1: i32| n1 - n2), Star => stackexpr!(|n2: i32, n1: i32| n1 * n2), Slash => stackexpr!(|n2: i32, n1: i32| n1 / n2), Abs => stackexpr!(|n: i32| n.abs()), And => stackexpr!(|n2: i32, n1: i32| n1 & n2), Or => stackexpr!(|n2: i32, n1: i32| n1 | n2), Xor => stackexpr!(|n2: i32, n1: i32| n1 ^ n2), LShift => stackexpr!(|u: i32, n: i32| n << u),
LessEqual => stackexpr!(|n2: i32, n1: i32| n1 <= n2), GreaterEqual => stackexpr!(|n2: i32, n1: i32| n1 >= n2), Emit => print!("{}", stack.pop::<char>()), Dup => { let n: i32 = stack.peak(); stack.push(n); } Swap => stackexpr!(|n2: i32, n1: i32| n2, n1), Over => stackexpr!(|n2: i32, n1: i32| n1, n2, n1), Rot => stackexpr!(|n3: i32, n2: i32, n1: i32| n2, n3, n1), Tuck => stackexpr!(|n2: i32, n1: i32| n2, n1, n2), Drop => { stack.pop::<i32>(); } Fetch => stackexpr!(|addr: i32| state.memory.get::<i32>(addr)), Store => { let addr: i32 = stack.pop(); let n: i32 = stack.pop(); state.memory.set(addr, n); } Here => stack.push(state.memory.here()), Comma => { state.memory.new(stack.pop::<i32>()); } Depth => { let len = stack.len(); stack.push(len); } Allot => { let n = stack.pop(); if n < 0 { // TODO Free memory } else { for _ in 0..n { state.memory.new(0); } } } } } }
RShift => stackexpr!(|u: i32, n: i32| n >> u), Equals => stackexpr!(|n2: i32, n1: i32| n1 == n2), NotEquals => stackexpr!(|n2: i32, n1: i32| n1 != n2), LessThan => stackexpr!(|n2: i32, n1: i32| n1 < n2), GreaterThan => stackexpr!(|n2: i32, n1: i32| n1 > n2),
random_line_split
builtins.rs
use crate::state::InterpState; use enum_iterator::IntoEnumIterator; /// Represents a builtin function #[derive(Debug, Clone, PartialEq, IntoEnumIterator)] pub enum Builtin { Dot, Plus, Minus, Star, Slash, Abs, And, Or, Xor, LShift, RShift, Equals, NotEquals, LessThan, GreaterThan, LessEqual, GreaterEqual, Emit, Dup, Swap, Over, Rot, Tuck, Drop, Fetch, Store, Here, Comma, Depth, Allot, } impl Builtin { pub fn word(&self) -> &'static str { match *self { Builtin::Dot => ".", Builtin::Plus => "+", Builtin::Minus => "-", Builtin::Star => "*", Builtin::Slash => "/", Builtin::Abs => "abs", Builtin::And => "and", Builtin::Or => "or", Builtin::Xor => "xor", Builtin::LShift => "lshift", Builtin::RShift => "rshift", Builtin::Equals => "=", Builtin::NotEquals => "<>", Builtin::LessThan => "<", Builtin::GreaterThan => ">", Builtin::LessEqual => "<=", Builtin::GreaterEqual => ">=", Builtin::Emit => "emit", Builtin::Dup => "dup", Builtin::Swap => "swap", Builtin::Over => "over", Builtin::Rot => "rot", Builtin::Tuck => "tuck", Builtin::Drop => "drop", Builtin::Here => "here", Builtin::Fetch => "@", Builtin::Store => "!", Builtin::Comma => ",", Builtin::Depth => "depth", Builtin::Allot => "allot", } } pub fn call(&self, state: &mut InterpState)
}
{ let stack = &mut state.stack; /// Allows defining a builtin using closure-like syntax. Note that the /// arguments are in reverse order, as that is how the stack is laid out. macro_rules! stackexpr { ( | $($aname:ident : $atype:ty),+ | $($value:expr),+ ) => { { $( let $aname: $atype = stack.pop(); )+ $( stack.push($value); )+ } } } use self::Builtin::*; match *self { Dot => print!("{}", stack.pop::<i32>()), Plus => stackexpr!(|n2: i32, n1: i32| n1 + n2), Minus => stackexpr!(|n2: i32, n1: i32| n1 - n2), Star => stackexpr!(|n2: i32, n1: i32| n1 * n2), Slash => stackexpr!(|n2: i32, n1: i32| n1 / n2), Abs => stackexpr!(|n: i32| n.abs()), And => stackexpr!(|n2: i32, n1: i32| n1 & n2), Or => stackexpr!(|n2: i32, n1: i32| n1 | n2), Xor => stackexpr!(|n2: i32, n1: i32| n1 ^ n2), LShift => stackexpr!(|u: i32, n: i32| n << u), RShift => stackexpr!(|u: i32, n: i32| n >> u), Equals => stackexpr!(|n2: i32, n1: i32| n1 == n2), NotEquals => stackexpr!(|n2: i32, n1: i32| n1 != n2), LessThan => stackexpr!(|n2: i32, n1: i32| n1 < n2), GreaterThan => stackexpr!(|n2: i32, n1: i32| n1 > n2), LessEqual => stackexpr!(|n2: i32, n1: i32| n1 <= n2), GreaterEqual => stackexpr!(|n2: i32, n1: i32| n1 >= n2), Emit => print!("{}", stack.pop::<char>()), Dup => { let n: i32 = stack.peak(); stack.push(n); } Swap => stackexpr!(|n2: i32, n1: i32| n2, n1), Over => stackexpr!(|n2: i32, n1: i32| n1, n2, n1), Rot => stackexpr!(|n3: i32, n2: i32, n1: i32| n2, n3, n1), Tuck => stackexpr!(|n2: i32, n1: i32| n2, n1, n2), Drop => { stack.pop::<i32>(); } Fetch => stackexpr!(|addr: i32| state.memory.get::<i32>(addr)), Store => { let addr: i32 = stack.pop(); let n: i32 = stack.pop(); state.memory.set(addr, n); } Here => stack.push(state.memory.here()), Comma => { state.memory.new(stack.pop::<i32>()); } Depth => { let len = stack.len(); stack.push(len); } Allot => { let n = stack.pop(); if n < 0 { // TODO Free memory } else { for _ in 0..n { state.memory.new(0); } } } } }
identifier_body
index.js
describe('Loading Nuora', function () { //using nuora as a module var colors = require('colors'), Nuora = require('../'), nuora, zuora, tests; it('has opts property', function () { expect(Nuora).to.have.property('opts'); }); Nuora.opts.option('--reporter [value]', ''); Nuora.opts.option('-r [value]', ''); it('builds Nuora', function () { nuora = Nuora.build(); zuora = nuora.zuora; describe('Nuora build', function () { it('has zuora property', function () { expect(nuora).to.have.property('zuora'); }); it('has zuora.soap property', function () { expect(zuora).to.have.property('soap'); }); }); tests = function () { describe('Perform a query', function () { this.timeout(10000); it('should return an array of no more than two elements', function (done) { var sql = "select id from account limit 1", i = 0, callback = function (err, data) { describe('Query ResultObject', function () { it('should have property id', function () { assert(data.result.records.hasOwnProperty('Id')); }); }); done(err); }; zuora.query(sql, callback, true); }); }); }; }); describe('Logging in', function () {
done(); tests(); }); }); }); });
it('connected to the server', function (done) { zuora.on('loggedin', function () {
random_line_split
write.ts
"use strict"; import {WriteCommand, IWriteCommandArguments} from '../commands/write'; import {Scanner} from '../scanner'; export function parseWriteCommandArgs(args : string) : WriteCommand { if (!args) { return new WriteCommand({}); } var scannedArgs : IWriteCommandArguments = {}; var scanner = new Scanner(args); while (true) { scanner.skipWhiteSpace(); if (scanner.isAtEof)
let c = scanner.next(); switch (c) { case '!': if (scanner.start > 0) { // :write !cmd scanner.ignore(); while (!scanner.isAtEof) { scanner.next(); } // vim ignores silently if no command after :w ! scannedArgs.cmd = scanner.emit().trim() || undefined; continue; } // :write! scannedArgs.bang = true; scanner.ignore(); continue; case '+': // :write ++opt=value scanner.expect('+'); scanner.ignore(); scanner.expectOneOf(['bin', 'nobin', 'ff', 'enc']); scannedArgs.opt = scanner.emit(); scanner.expect('='); scanner.ignore(); while (!scanner.isAtEof) { let c = scanner.next(); if (c !== ' ' && c !== '\t') { continue; } scanner.backup(); continue; } let value = scanner.emit(); if (!value) { throw new Error("Expected value for option."); } scannedArgs.optValue = value; continue; default: throw new Error("Not implemented"); } } // TODO: actually parse arguments. // ++bin ++nobin ++ff ++enc =VALUE return new WriteCommand(scannedArgs); }
{ break; }
conditional_block
write.ts
"use strict"; import {WriteCommand, IWriteCommandArguments} from '../commands/write'; import {Scanner} from '../scanner'; export function parseWriteCommandArgs(args : string) : WriteCommand { if (!args) { return new WriteCommand({});
if (scanner.isAtEof) { break; } let c = scanner.next(); switch (c) { case '!': if (scanner.start > 0) { // :write !cmd scanner.ignore(); while (!scanner.isAtEof) { scanner.next(); } // vim ignores silently if no command after :w ! scannedArgs.cmd = scanner.emit().trim() || undefined; continue; } // :write! scannedArgs.bang = true; scanner.ignore(); continue; case '+': // :write ++opt=value scanner.expect('+'); scanner.ignore(); scanner.expectOneOf(['bin', 'nobin', 'ff', 'enc']); scannedArgs.opt = scanner.emit(); scanner.expect('='); scanner.ignore(); while (!scanner.isAtEof) { let c = scanner.next(); if (c !== ' ' && c !== '\t') { continue; } scanner.backup(); continue; } let value = scanner.emit(); if (!value) { throw new Error("Expected value for option."); } scannedArgs.optValue = value; continue; default: throw new Error("Not implemented"); } } // TODO: actually parse arguments. // ++bin ++nobin ++ff ++enc =VALUE return new WriteCommand(scannedArgs); }
} var scannedArgs : IWriteCommandArguments = {}; var scanner = new Scanner(args); while (true) { scanner.skipWhiteSpace();
random_line_split
write.ts
"use strict"; import {WriteCommand, IWriteCommandArguments} from '../commands/write'; import {Scanner} from '../scanner'; export function
(args : string) : WriteCommand { if (!args) { return new WriteCommand({}); } var scannedArgs : IWriteCommandArguments = {}; var scanner = new Scanner(args); while (true) { scanner.skipWhiteSpace(); if (scanner.isAtEof) { break; } let c = scanner.next(); switch (c) { case '!': if (scanner.start > 0) { // :write !cmd scanner.ignore(); while (!scanner.isAtEof) { scanner.next(); } // vim ignores silently if no command after :w ! scannedArgs.cmd = scanner.emit().trim() || undefined; continue; } // :write! scannedArgs.bang = true; scanner.ignore(); continue; case '+': // :write ++opt=value scanner.expect('+'); scanner.ignore(); scanner.expectOneOf(['bin', 'nobin', 'ff', 'enc']); scannedArgs.opt = scanner.emit(); scanner.expect('='); scanner.ignore(); while (!scanner.isAtEof) { let c = scanner.next(); if (c !== ' ' && c !== '\t') { continue; } scanner.backup(); continue; } let value = scanner.emit(); if (!value) { throw new Error("Expected value for option."); } scannedArgs.optValue = value; continue; default: throw new Error("Not implemented"); } } // TODO: actually parse arguments. // ++bin ++nobin ++ff ++enc =VALUE return new WriteCommand(scannedArgs); }
parseWriteCommandArgs
identifier_name
write.ts
"use strict"; import {WriteCommand, IWriteCommandArguments} from '../commands/write'; import {Scanner} from '../scanner'; export function parseWriteCommandArgs(args : string) : WriteCommand
{ if (!args) { return new WriteCommand({}); } var scannedArgs : IWriteCommandArguments = {}; var scanner = new Scanner(args); while (true) { scanner.skipWhiteSpace(); if (scanner.isAtEof) { break; } let c = scanner.next(); switch (c) { case '!': if (scanner.start > 0) { // :write !cmd scanner.ignore(); while (!scanner.isAtEof) { scanner.next(); } // vim ignores silently if no command after :w ! scannedArgs.cmd = scanner.emit().trim() || undefined; continue; } // :write! scannedArgs.bang = true; scanner.ignore(); continue; case '+': // :write ++opt=value scanner.expect('+'); scanner.ignore(); scanner.expectOneOf(['bin', 'nobin', 'ff', 'enc']); scannedArgs.opt = scanner.emit(); scanner.expect('='); scanner.ignore(); while (!scanner.isAtEof) { let c = scanner.next(); if (c !== ' ' && c !== '\t') { continue; } scanner.backup(); continue; } let value = scanner.emit(); if (!value) { throw new Error("Expected value for option."); } scannedArgs.optValue = value; continue; default: throw new Error("Not implemented"); } } // TODO: actually parse arguments. // ++bin ++nobin ++ff ++enc =VALUE return new WriteCommand(scannedArgs); }
identifier_body
index-plain.js
var plain = require('./workers/plain.js'); var NodeMover = require('./modules/NodeMover').NodeMover; var PixiGraphics = require('./modules/PixiGraphics').PixiGraphics; module.exports.main = function () {
var _layoutIterations = 1000; var _layoutStepsPerMessage = 25; //--simple frame-rate display for renders vs layouts var _counts = {renders: 0, layouts: 0, renderRate: 0, layoutRate: 0}; var $info = $('<div>').appendTo('body'); var startTime = new Date(); var _updateInfo = function () { var endTime = new Date(); var timeDiff = (endTime - startTime) / 1000; if (_counts.layouts < _layoutIterations) { _counts.layoutRate = _counts.layouts / timeDiff; } _counts.renderRate = _counts.renders / timeDiff; $info.text('Renders: ' + _counts.renders + ' (' + Math.round(_counts.renderRate) + ') | Layouts: ' + _counts.layouts + ' (' + Math.round(_counts.layoutRate) + ')'); }; var _nodeMovers = {}; $.getJSON('data/graph.json', function (jsonData) { jsonData.nodes.forEach(function (node, i) { var nodeMover = new NodeMover(); nodeMover.data('id', node.id); _nodeMovers[node.id] = nodeMover; }); var _layoutPositions = {}; function updatePos(ev) { _layoutPositions = ev.data; _counts.layouts = _layoutPositions.i; }; plain(jsonData); var graphics = new PixiGraphics(0.75, jsonData, function () { $.each(_nodeMovers, function (id, nodeMover) { if (_layoutPositions.nodePositions) { nodeMover.position(_layoutPositions.nodePositions[id]); nodeMover.animate(); } }); return _nodeMovers; }); function renderFrame() { plain.step(updatePos); graphics.renderFrame(); _counts.renders++; _updateInfo(); requestAnimFrame(renderFrame); } // begin animation loop: renderFrame(); }); };
random_line_split
index-plain.js
var plain = require('./workers/plain.js'); var NodeMover = require('./modules/NodeMover').NodeMover; var PixiGraphics = require('./modules/PixiGraphics').PixiGraphics; module.exports.main = function () { var _layoutIterations = 1000; var _layoutStepsPerMessage = 25; //--simple frame-rate display for renders vs layouts var _counts = {renders: 0, layouts: 0, renderRate: 0, layoutRate: 0}; var $info = $('<div>').appendTo('body'); var startTime = new Date(); var _updateInfo = function () { var endTime = new Date(); var timeDiff = (endTime - startTime) / 1000; if (_counts.layouts < _layoutIterations) { _counts.layoutRate = _counts.layouts / timeDiff; } _counts.renderRate = _counts.renders / timeDiff; $info.text('Renders: ' + _counts.renders + ' (' + Math.round(_counts.renderRate) + ') | Layouts: ' + _counts.layouts + ' (' + Math.round(_counts.layoutRate) + ')'); }; var _nodeMovers = {}; $.getJSON('data/graph.json', function (jsonData) { jsonData.nodes.forEach(function (node, i) { var nodeMover = new NodeMover(); nodeMover.data('id', node.id); _nodeMovers[node.id] = nodeMover; }); var _layoutPositions = {}; function updatePos(ev) { _layoutPositions = ev.data; _counts.layouts = _layoutPositions.i; }; plain(jsonData); var graphics = new PixiGraphics(0.75, jsonData, function () { $.each(_nodeMovers, function (id, nodeMover) { if (_layoutPositions.nodePositions)
}); return _nodeMovers; }); function renderFrame() { plain.step(updatePos); graphics.renderFrame(); _counts.renders++; _updateInfo(); requestAnimFrame(renderFrame); } // begin animation loop: renderFrame(); }); };
{ nodeMover.position(_layoutPositions.nodePositions[id]); nodeMover.animate(); }
conditional_block
index-plain.js
var plain = require('./workers/plain.js'); var NodeMover = require('./modules/NodeMover').NodeMover; var PixiGraphics = require('./modules/PixiGraphics').PixiGraphics; module.exports.main = function () { var _layoutIterations = 1000; var _layoutStepsPerMessage = 25; //--simple frame-rate display for renders vs layouts var _counts = {renders: 0, layouts: 0, renderRate: 0, layoutRate: 0}; var $info = $('<div>').appendTo('body'); var startTime = new Date(); var _updateInfo = function () { var endTime = new Date(); var timeDiff = (endTime - startTime) / 1000; if (_counts.layouts < _layoutIterations) { _counts.layoutRate = _counts.layouts / timeDiff; } _counts.renderRate = _counts.renders / timeDiff; $info.text('Renders: ' + _counts.renders + ' (' + Math.round(_counts.renderRate) + ') | Layouts: ' + _counts.layouts + ' (' + Math.round(_counts.layoutRate) + ')'); }; var _nodeMovers = {}; $.getJSON('data/graph.json', function (jsonData) { jsonData.nodes.forEach(function (node, i) { var nodeMover = new NodeMover(); nodeMover.data('id', node.id); _nodeMovers[node.id] = nodeMover; }); var _layoutPositions = {}; function
(ev) { _layoutPositions = ev.data; _counts.layouts = _layoutPositions.i; }; plain(jsonData); var graphics = new PixiGraphics(0.75, jsonData, function () { $.each(_nodeMovers, function (id, nodeMover) { if (_layoutPositions.nodePositions) { nodeMover.position(_layoutPositions.nodePositions[id]); nodeMover.animate(); } }); return _nodeMovers; }); function renderFrame() { plain.step(updatePos); graphics.renderFrame(); _counts.renders++; _updateInfo(); requestAnimFrame(renderFrame); } // begin animation loop: renderFrame(); }); };
updatePos
identifier_name
index-plain.js
var plain = require('./workers/plain.js'); var NodeMover = require('./modules/NodeMover').NodeMover; var PixiGraphics = require('./modules/PixiGraphics').PixiGraphics; module.exports.main = function () { var _layoutIterations = 1000; var _layoutStepsPerMessage = 25; //--simple frame-rate display for renders vs layouts var _counts = {renders: 0, layouts: 0, renderRate: 0, layoutRate: 0}; var $info = $('<div>').appendTo('body'); var startTime = new Date(); var _updateInfo = function () { var endTime = new Date(); var timeDiff = (endTime - startTime) / 1000; if (_counts.layouts < _layoutIterations) { _counts.layoutRate = _counts.layouts / timeDiff; } _counts.renderRate = _counts.renders / timeDiff; $info.text('Renders: ' + _counts.renders + ' (' + Math.round(_counts.renderRate) + ') | Layouts: ' + _counts.layouts + ' (' + Math.round(_counts.layoutRate) + ')'); }; var _nodeMovers = {}; $.getJSON('data/graph.json', function (jsonData) { jsonData.nodes.forEach(function (node, i) { var nodeMover = new NodeMover(); nodeMover.data('id', node.id); _nodeMovers[node.id] = nodeMover; }); var _layoutPositions = {}; function updatePos(ev)
; plain(jsonData); var graphics = new PixiGraphics(0.75, jsonData, function () { $.each(_nodeMovers, function (id, nodeMover) { if (_layoutPositions.nodePositions) { nodeMover.position(_layoutPositions.nodePositions[id]); nodeMover.animate(); } }); return _nodeMovers; }); function renderFrame() { plain.step(updatePos); graphics.renderFrame(); _counts.renders++; _updateInfo(); requestAnimFrame(renderFrame); } // begin animation loop: renderFrame(); }); };
{ _layoutPositions = ev.data; _counts.layouts = _layoutPositions.i; }
identifier_body
lib.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/. */ #![crate_name = "js"] #![crate_type = "rlib"] #![feature(core_intrinsics)] #![feature(link_args)] #![feature(str_utf16)] #![feature(unsafe_no_drop_flag)] #![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, improper_ctypes, raw_pointer_derive)] extern crate libc; #[macro_use] extern crate log;
pub mod jsapi; pub mod linkhack; pub mod rust; pub mod glue; pub mod jsval; use jsapi::{JSContext, JSProtoKey, Heap}; use jsval::JSVal; use rust::GCMethods; use libc::c_uint; use heapsize::HeapSizeOf; pub const default_heapsize: u32 = 32_u32 * 1024_u32 * 1024_u32; pub const default_stacksize: usize = 8192; pub const JSID_TYPE_STRING: i64 = 0; pub const JSID_TYPE_INT: i64 = 1; pub const JSID_TYPE_VOID: i64 = 2; pub const JSID_TYPE_OBJECT: i64 = 4; pub const JSID_TYPE_DEFAULT_XML_NAMESPACE: i64 = 6; pub const JSID_TYPE_MASK: i64 = 7; pub const JSFUN_CONSTRUCTOR: u32 = 0x400; /* native that can be called as a ctor */ pub const JSPROP_ENUMERATE: c_uint = 0x01; pub const JSPROP_READONLY: c_uint = 0x02; pub const JSPROP_PERMANENT: c_uint = 0x04; pub const JSPROP_GETTER: c_uint = 0x10; pub const JSPROP_SETTER: c_uint = 0x20; pub const JSPROP_SHARED: c_uint = 0x40; pub const JSPROP_NATIVE_ACCESSORS: c_uint = 0x08; pub const JSCLASS_RESERVED_SLOTS_SHIFT: c_uint = 8; pub const JSCLASS_RESERVED_SLOTS_WIDTH: c_uint = 8; pub const JSCLASS_RESERVED_SLOTS_MASK: c_uint = ((1 << JSCLASS_RESERVED_SLOTS_WIDTH) - 1) as c_uint; pub const JSCLASS_HIGH_FLAGS_SHIFT: c_uint = JSCLASS_RESERVED_SLOTS_SHIFT + JSCLASS_RESERVED_SLOTS_WIDTH; pub const JSCLASS_IS_GLOBAL: c_uint = 1 << (JSCLASS_HIGH_FLAGS_SHIFT + 1); pub const JSCLASS_GLOBAL_APPLICATION_SLOTS: c_uint = 4; pub const JSCLASS_GLOBAL_SLOT_COUNT: c_uint = JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProtoKey::JSProto_LIMIT as u32 * 3 + 31; pub const JSCLASS_IS_DOMJSCLASS: u32 = 1 << 4; pub const JSCLASS_IMPLEMENTS_BARRIERS: u32 = 1 << 5; pub const JSCLASS_USERBIT1: u32 = 1 << 7; pub const JSCLASS_IS_PROXY: u32 = 1 << (JSCLASS_HIGH_FLAGS_SHIFT+4); pub const JSSLOT_PROXY_PRIVATE: u32 = 1; pub const JS_DEFAULT_ZEAL_FREQ: u32 = 100; pub const JSTrue: u8 = 1; pub const JSFalse: u8 = 0; #[link(name = "jsglue")] extern { } #[cfg(target_os = "android")] #[link(name = "stdc++")] extern { } #[cfg(target_os = "android")] #[link(name = "gcc")] extern { } #[inline(always)] pub unsafe fn JS_ARGV(_cx: *mut JSContext, vp: *mut JSVal) -> *mut JSVal { vp.offset(2) } #[inline(always)] pub unsafe fn JS_CALLEE(_cx: *mut JSContext, vp: *mut JSVal) -> JSVal { *vp } // This is measured properly by the heap measurement implemented in SpiderMonkey. impl<T: Copy + GCMethods<T>> HeapSizeOf for Heap<T> { fn heap_size_of_children(&self) -> usize { 0 } } known_heap_size!(0, JSVal);
#[macro_use] extern crate heapsize; extern crate rustc_serialize as serialize;
random_line_split
lib.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/. */ #![crate_name = "js"] #![crate_type = "rlib"] #![feature(core_intrinsics)] #![feature(link_args)] #![feature(str_utf16)] #![feature(unsafe_no_drop_flag)] #![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, improper_ctypes, raw_pointer_derive)] extern crate libc; #[macro_use] extern crate log; #[macro_use] extern crate heapsize; extern crate rustc_serialize as serialize; pub mod jsapi; pub mod linkhack; pub mod rust; pub mod glue; pub mod jsval; use jsapi::{JSContext, JSProtoKey, Heap}; use jsval::JSVal; use rust::GCMethods; use libc::c_uint; use heapsize::HeapSizeOf; pub const default_heapsize: u32 = 32_u32 * 1024_u32 * 1024_u32; pub const default_stacksize: usize = 8192; pub const JSID_TYPE_STRING: i64 = 0; pub const JSID_TYPE_INT: i64 = 1; pub const JSID_TYPE_VOID: i64 = 2; pub const JSID_TYPE_OBJECT: i64 = 4; pub const JSID_TYPE_DEFAULT_XML_NAMESPACE: i64 = 6; pub const JSID_TYPE_MASK: i64 = 7; pub const JSFUN_CONSTRUCTOR: u32 = 0x400; /* native that can be called as a ctor */ pub const JSPROP_ENUMERATE: c_uint = 0x01; pub const JSPROP_READONLY: c_uint = 0x02; pub const JSPROP_PERMANENT: c_uint = 0x04; pub const JSPROP_GETTER: c_uint = 0x10; pub const JSPROP_SETTER: c_uint = 0x20; pub const JSPROP_SHARED: c_uint = 0x40; pub const JSPROP_NATIVE_ACCESSORS: c_uint = 0x08; pub const JSCLASS_RESERVED_SLOTS_SHIFT: c_uint = 8; pub const JSCLASS_RESERVED_SLOTS_WIDTH: c_uint = 8; pub const JSCLASS_RESERVED_SLOTS_MASK: c_uint = ((1 << JSCLASS_RESERVED_SLOTS_WIDTH) - 1) as c_uint; pub const JSCLASS_HIGH_FLAGS_SHIFT: c_uint = JSCLASS_RESERVED_SLOTS_SHIFT + JSCLASS_RESERVED_SLOTS_WIDTH; pub const JSCLASS_IS_GLOBAL: c_uint = 1 << (JSCLASS_HIGH_FLAGS_SHIFT + 1); pub const JSCLASS_GLOBAL_APPLICATION_SLOTS: c_uint = 4; pub const JSCLASS_GLOBAL_SLOT_COUNT: c_uint = JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProtoKey::JSProto_LIMIT as u32 * 3 + 31; pub const JSCLASS_IS_DOMJSCLASS: u32 = 1 << 4; pub const JSCLASS_IMPLEMENTS_BARRIERS: u32 = 1 << 5; pub const JSCLASS_USERBIT1: u32 = 1 << 7; pub const JSCLASS_IS_PROXY: u32 = 1 << (JSCLASS_HIGH_FLAGS_SHIFT+4); pub const JSSLOT_PROXY_PRIVATE: u32 = 1; pub const JS_DEFAULT_ZEAL_FREQ: u32 = 100; pub const JSTrue: u8 = 1; pub const JSFalse: u8 = 0; #[link(name = "jsglue")] extern { } #[cfg(target_os = "android")] #[link(name = "stdc++")] extern { } #[cfg(target_os = "android")] #[link(name = "gcc")] extern { } #[inline(always)] pub unsafe fn JS_ARGV(_cx: *mut JSContext, vp: *mut JSVal) -> *mut JSVal { vp.offset(2) } #[inline(always)] pub unsafe fn JS_CALLEE(_cx: *mut JSContext, vp: *mut JSVal) -> JSVal
// This is measured properly by the heap measurement implemented in SpiderMonkey. impl<T: Copy + GCMethods<T>> HeapSizeOf for Heap<T> { fn heap_size_of_children(&self) -> usize { 0 } } known_heap_size!(0, JSVal);
{ *vp }
identifier_body
lib.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/. */ #![crate_name = "js"] #![crate_type = "rlib"] #![feature(core_intrinsics)] #![feature(link_args)] #![feature(str_utf16)] #![feature(unsafe_no_drop_flag)] #![allow(non_upper_case_globals, non_camel_case_types, non_snake_case, improper_ctypes, raw_pointer_derive)] extern crate libc; #[macro_use] extern crate log; #[macro_use] extern crate heapsize; extern crate rustc_serialize as serialize; pub mod jsapi; pub mod linkhack; pub mod rust; pub mod glue; pub mod jsval; use jsapi::{JSContext, JSProtoKey, Heap}; use jsval::JSVal; use rust::GCMethods; use libc::c_uint; use heapsize::HeapSizeOf; pub const default_heapsize: u32 = 32_u32 * 1024_u32 * 1024_u32; pub const default_stacksize: usize = 8192; pub const JSID_TYPE_STRING: i64 = 0; pub const JSID_TYPE_INT: i64 = 1; pub const JSID_TYPE_VOID: i64 = 2; pub const JSID_TYPE_OBJECT: i64 = 4; pub const JSID_TYPE_DEFAULT_XML_NAMESPACE: i64 = 6; pub const JSID_TYPE_MASK: i64 = 7; pub const JSFUN_CONSTRUCTOR: u32 = 0x400; /* native that can be called as a ctor */ pub const JSPROP_ENUMERATE: c_uint = 0x01; pub const JSPROP_READONLY: c_uint = 0x02; pub const JSPROP_PERMANENT: c_uint = 0x04; pub const JSPROP_GETTER: c_uint = 0x10; pub const JSPROP_SETTER: c_uint = 0x20; pub const JSPROP_SHARED: c_uint = 0x40; pub const JSPROP_NATIVE_ACCESSORS: c_uint = 0x08; pub const JSCLASS_RESERVED_SLOTS_SHIFT: c_uint = 8; pub const JSCLASS_RESERVED_SLOTS_WIDTH: c_uint = 8; pub const JSCLASS_RESERVED_SLOTS_MASK: c_uint = ((1 << JSCLASS_RESERVED_SLOTS_WIDTH) - 1) as c_uint; pub const JSCLASS_HIGH_FLAGS_SHIFT: c_uint = JSCLASS_RESERVED_SLOTS_SHIFT + JSCLASS_RESERVED_SLOTS_WIDTH; pub const JSCLASS_IS_GLOBAL: c_uint = 1 << (JSCLASS_HIGH_FLAGS_SHIFT + 1); pub const JSCLASS_GLOBAL_APPLICATION_SLOTS: c_uint = 4; pub const JSCLASS_GLOBAL_SLOT_COUNT: c_uint = JSCLASS_GLOBAL_APPLICATION_SLOTS + JSProtoKey::JSProto_LIMIT as u32 * 3 + 31; pub const JSCLASS_IS_DOMJSCLASS: u32 = 1 << 4; pub const JSCLASS_IMPLEMENTS_BARRIERS: u32 = 1 << 5; pub const JSCLASS_USERBIT1: u32 = 1 << 7; pub const JSCLASS_IS_PROXY: u32 = 1 << (JSCLASS_HIGH_FLAGS_SHIFT+4); pub const JSSLOT_PROXY_PRIVATE: u32 = 1; pub const JS_DEFAULT_ZEAL_FREQ: u32 = 100; pub const JSTrue: u8 = 1; pub const JSFalse: u8 = 0; #[link(name = "jsglue")] extern { } #[cfg(target_os = "android")] #[link(name = "stdc++")] extern { } #[cfg(target_os = "android")] #[link(name = "gcc")] extern { } #[inline(always)] pub unsafe fn JS_ARGV(_cx: *mut JSContext, vp: *mut JSVal) -> *mut JSVal { vp.offset(2) } #[inline(always)] pub unsafe fn JS_CALLEE(_cx: *mut JSContext, vp: *mut JSVal) -> JSVal { *vp } // This is measured properly by the heap measurement implemented in SpiderMonkey. impl<T: Copy + GCMethods<T>> HeapSizeOf for Heap<T> { fn
(&self) -> usize { 0 } } known_heap_size!(0, JSVal);
heap_size_of_children
identifier_name
test.js
var config = require('./lib/config'); var FaceRec = require('./lib/facerec').FaceRec; var hfr = new FaceRec(config); // constant var threshold = 20; var prevX; var prevY; setInterval(function() { var result = hfr.detect(); console.log('result:' + JSON.stringify(result)); if (result && result.pos_x && result.pos_y) { var newX = result.pos_x; var newY = result.pos_y; var deltaX = newX - prevX; var deltaY = newY - prevY; if (Math.abs(deltaX) > threshold) { var direction = deltaX > 0 ? "right" : "left"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaX)); } if (Math.abs(deltaY) > threshold)
console.log('updating x and y'); prevX = newX; prevY = newY; } }, 5000);
{ var direction = deltaY > 0 ? "down" : "up"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaY)); }
conditional_block
test.js
var config = require('./lib/config'); var FaceRec = require('./lib/facerec').FaceRec; var hfr = new FaceRec(config); // constant var threshold = 20; var prevX; var prevY;
setInterval(function() { var result = hfr.detect(); console.log('result:' + JSON.stringify(result)); if (result && result.pos_x && result.pos_y) { var newX = result.pos_x; var newY = result.pos_y; var deltaX = newX - prevX; var deltaY = newY - prevY; if (Math.abs(deltaX) > threshold) { var direction = deltaX > 0 ? "right" : "left"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaX)); } if (Math.abs(deltaY) > threshold) { var direction = deltaY > 0 ? "down" : "up"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaY)); } console.log('updating x and y'); prevX = newX; prevY = newY; } }, 5000);
random_line_split
wicked.py
# -*- coding: utf-8 -*- ############################################################################################### # # MediaPortal for Dreambox OS # # Coded by MediaPortal Team (c) 2013-2017 # # This plugin is open source but it is NOT free software. # # This plugin may only be distributed to and executed on hardware which # is licensed by Dream Property GmbH. This includes commercial distribution. # In other words: # It's NOT allowed to distribute any parts of this plugin or its source code in ANY way # to hardware which is NOT licensed by Dream Property GmbH. # It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way # on hardware which is NOT licensed by Dream Property GmbH. # # This applies to the source code as a whole as well as to parts of it, unless # explicitely stated otherwise. # # If you want to use or modify the code or parts of it, # you have to keep OUR license and inform us about the modifications, but it may NOT be # commercially distributed other than under the conditions noted above. # # As an exception regarding execution on hardware, you are permitted to execute this plugin on VU+ hardware # which is licensed by satco europe GmbH, if the VTi image is used on that hardware. # # As an exception regarding modifcations, you are NOT permitted to remove # any copy protections implemented in this plugin or change them for means of disabling # or working around the copy protections, unless the change has been explicitly permitted # by the original authors. Also decompiling and modification of the closed source # parts is NOT permitted. # # Advertising with this plugin is NOT allowed. # For other uses, permission from the authors is necessary. # ############################################################################################### from Plugins.Extensions.MediaPortal.plugin import _ from Plugins.Extensions.MediaPortal.resources.imports import * from Plugins.Extensions.MediaPortal.resources.choiceboxext import ChoiceBoxExt myagent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0' BASE_NAME = "WickedPictures.com" class wickedGenreScreen(MPScreen): def __init__(self, session): MPScreen.__init__(self, session, skin='MP_Plugin') self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "cancel" : self.keyCancel }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre:") self.genreliste = [] self.suchString = '' self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.genreliste.insert(0, ("Exclusive Girls", 'http://www.wicked.com/tour/pornstars/exclusive/', None)) self.genreliste.insert(0, ("Most Active Girls", 'http://www.wicked.com/tour/pornstars/mostactive/', None)) self.genreliste.insert(0, ("Most Liked Girls", 'http://www.wicked.com/tour/pornstars/mostliked/', None)) self.genreliste.insert(0, ("Most Recent Girls", 'http://www.wicked.com/tour/pornstars/mostrecent/', None)) self.genreliste.insert(0, ("Most Viewed Movies", 'http://www.wicked.com/tour/movies/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Movies", 'http://www.wicked.com/tour/movies/toprated/', None)) self.genreliste.insert(0, ("Latest Movies", 'http://www.wicked.com/tour/movies/latest/', None)) self.genreliste.insert(0, ("Most Viewed Scenes", 'http://www.wicked.com/tour/videos/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Scenes", 'http://www.wicked.com/tour/videos/toprated/', None)) self.genreliste.insert(0, ("Latest Scenes", 'http://www.wicked.com/tour/videos/latest/', None)) self.genreliste.insert(0, ("--- Search ---", "callSuchen", None)) self.ml.setList(map(self._defaultlistcenter, self.genreliste)) self.showInfos() def keyOK(self): if
def SuchenCallback(self, callback = None, entry = None): if callback is not None and len(callback): self.suchString = callback Name = "--- Search ---" Link = self.suchString.replace(' ', '-') self.session.open(wickedFilmScreen, Link, Name) class wickedGirlsScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 1 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def loadData(self, data): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') parse = re.search('class="showcase-models(.*?)</section>', data, re.S) Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-models.*?img\ssrc="(.*?)"\stitle="(.*?)".*?scenes">(\d+)\sScenes', parse.group(1), re.S) if Movies: for (Url, Image, Title, Scenes) in Movies: Url = "http://www.wicked.com" + Url Title = Title + " - %s Scenes" % Scenes self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No pornstars found!'), None, None)) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1] if Link: rangelist = [['Scenes', 'videos/'], ['Movies', 'movies/']] self.session.openWithCallback(self.keyOK2, ChoiceBoxExt, title=_('Select Action'), list = rangelist) def keyOK2(self, result): if result: Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] Link = Link + result[1] self.session.open(wickedFilmScreen, Link, Name) class wickedFilmScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 9 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] if re.match(".*?Search", self.Name): url = "http://www.wicked.com/tour/search/videos/%s/%s/" % (self.Link, str(self.page)) else: url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def loadData(self, data): if re.match(".*?Search", self.Name): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') elif re.match(".*?/tour/pornstar", self.Link): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') else: self['page'].setText(str(self.page) + ' / ' + str(self.lastpage)) parse = re.search('lass="showcase-movies">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-movies.*?img\ssrc="(.*?)"\salt=".*?"\stitle="(.*?)"', parse.group(1), re.S) else: parse = re.search('class="showcase-scenes">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-scenes.*?img\ssrc="(.*?)"\stitle=".*?"\salt="(.*?)"', parse.group(1), re.S) if Movies: for (Url, Image, Title) in Movies: Image = Image.replace('_2.jpg','_1.jpg') Url = "http://www.wicked.com" + Url self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No videos found!'), '', None, '')) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1] get_stream_link(self.session).check_link(Link, self.play) def play(self, url): title = self['liste'].getCurrent()[0][0] self.session.open(SimplePlayer, [(title, url.replace('%2F','%252F').replace('%3D','%253D').replace('%2B','%252B'))], showPlaylist=False, ltype='wicked')
not config.mediaportal.premiumize_use.value: message = self.session.open(MessageBoxExt, _("%s only works with enabled MP premiumize.me option (MP Setup)!" % BASE_NAME), MessageBoxExt.TYPE_INFO, timeout=10) return Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] if Name == "--- Search ---": self.suchen() elif re.match(".*?Girls", Name): self.session.open(wickedGirlsScreen, Link, Name) else: self.session.open(wickedFilmScreen, Link, Name)
identifier_body
wicked.py
# -*- coding: utf-8 -*- ############################################################################################### # # MediaPortal for Dreambox OS # # Coded by MediaPortal Team (c) 2013-2017 # # This plugin is open source but it is NOT free software. # # This plugin may only be distributed to and executed on hardware which # is licensed by Dream Property GmbH. This includes commercial distribution. # In other words: # It's NOT allowed to distribute any parts of this plugin or its source code in ANY way # to hardware which is NOT licensed by Dream Property GmbH. # It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way # on hardware which is NOT licensed by Dream Property GmbH. # # This applies to the source code as a whole as well as to parts of it, unless # explicitely stated otherwise. # # If you want to use or modify the code or parts of it, # you have to keep OUR license and inform us about the modifications, but it may NOT be # commercially distributed other than under the conditions noted above. # # As an exception regarding execution on hardware, you are permitted to execute this plugin on VU+ hardware # which is licensed by satco europe GmbH, if the VTi image is used on that hardware. # # As an exception regarding modifcations, you are NOT permitted to remove # any copy protections implemented in this plugin or change them for means of disabling # or working around the copy protections, unless the change has been explicitly permitted # by the original authors. Also decompiling and modification of the closed source # parts is NOT permitted. # # Advertising with this plugin is NOT allowed. # For other uses, permission from the authors is necessary. # ############################################################################################### from Plugins.Extensions.MediaPortal.plugin import _ from Plugins.Extensions.MediaPortal.resources.imports import * from Plugins.Extensions.MediaPortal.resources.choiceboxext import ChoiceBoxExt myagent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0' BASE_NAME = "WickedPictures.com" class wickedGenreScreen(MPScreen): def __init__(self, session): MPScreen.__init__(self, session, skin='MP_Plugin') self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "cancel" : self.keyCancel }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre:") self.genreliste = [] self.suchString = '' self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.genreliste.insert(0, ("Exclusive Girls", 'http://www.wicked.com/tour/pornstars/exclusive/', None)) self.genreliste.insert(0, ("Most Active Girls", 'http://www.wicked.com/tour/pornstars/mostactive/', None)) self.genreliste.insert(0, ("Most Liked Girls", 'http://www.wicked.com/tour/pornstars/mostliked/', None)) self.genreliste.insert(0, ("Most Recent Girls", 'http://www.wicked.com/tour/pornstars/mostrecent/', None)) self.genreliste.insert(0, ("Most Viewed Movies", 'http://www.wicked.com/tour/movies/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Movies", 'http://www.wicked.com/tour/movies/toprated/', None)) self.genreliste.insert(0, ("Latest Movies", 'http://www.wicked.com/tour/movies/latest/', None)) self.genreliste.insert(0, ("Most Viewed Scenes", 'http://www.wicked.com/tour/videos/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Scenes", 'http://www.wicked.com/tour/videos/toprated/', None)) self.genreliste.insert(0, ("Latest Scenes", 'http://www.wicked.com/tour/videos/latest/', None)) self.genreliste.insert(0, ("--- Search ---", "callSuchen", None)) self.ml.setList(map(self._defaultlistcenter, self.genreliste)) self.showInfos() def keyOK(self): if not config.mediaportal.premiumize_use.value: message = self.session.open(MessageBoxExt, _("%s only works with enabled MP premiumize.me option (MP Setup)!" % BASE_NAME), MessageBoxExt.TYPE_INFO, timeout=10) return Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] if Name == "--- Search ---": self.suchen() elif re.match(".*?Girls", Name): self.session.open(wickedGirlsScreen, Link, Name) else: self.session.open(wickedFilmScreen, Link, Name) def SuchenCallback(self, callback = None, entry = None): if callback is not None and len(callback): self.suchString = callback Name = "--- Search ---" Link = self.suchString.replace(' ', '-') self.session.open(wickedFilmScreen, Link, Name) class wickedGirlsScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 1 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def loadData(self, data): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') parse = re.search('class="showcase-models(.*?)</section>', data, re.S) Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-models.*?img\ssrc="(.*?)"\stitle="(.*?)".*?scenes">(\d+)\sScenes', parse.group(1), re.S) if Movies: for (Url, Image, Title, Scenes) in Movies: Url = "http://www.wicked.com" + Url Title = Title + " - %s Scenes" % Scenes self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No pornstars found!'), None, None)) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1] if Link: rangelist = [['Scenes', 'videos/'], ['Movies', 'movies/']] self.session.openWithCallback(self.keyOK2, ChoiceBoxExt, title=_('Select Action'), list = rangelist) def keyOK2(self, result): if result: Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] Link = Link + result[1] self.session.open(wickedFilmScreen, Link, Name) class wickedFilmScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 9 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] if re.match(".*?Search", self.Name): url = "http://www.wicked.com/tour/search/videos/%s/%s/" % (self.Link, str(self.page)) else: url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def loadData(self, data): if re.match(".*?Search", self.Name): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') elif re.match(".*?/tour/pornstar", self.Link): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') else: self['page'].setText(str(self.page) + ' / ' + str(self.lastpage)) parse = re.search('lass="showcase-movies">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-movies.*?img\ssrc="(.*?)"\salt=".*?"\stitle="(.*?)"', parse.group(1), re.S) else: parse = re.search('class="showcase-scenes">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-scenes.*?img\ssrc="(.*?)"\stitle=".*?"\salt="(.*?)"', parse.group(1), re.S) if Movies: for (Url, Image, Title) in Movies: Image = Image.replace('_2.jpg','_1.jpg') Url = "http://www.wicked.com" + Url self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No videos found!'), '', None, '')) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1]
get_stream_link(self.session).check_link(Link, self.play) def play(self, url): title = self['liste'].getCurrent()[0][0] self.session.open(SimplePlayer, [(title, url.replace('%2F','%252F').replace('%3D','%253D').replace('%2B','%252B'))], showPlaylist=False, ltype='wicked')
random_line_split
wicked.py
# -*- coding: utf-8 -*- ############################################################################################### # # MediaPortal for Dreambox OS # # Coded by MediaPortal Team (c) 2013-2017 # # This plugin is open source but it is NOT free software. # # This plugin may only be distributed to and executed on hardware which # is licensed by Dream Property GmbH. This includes commercial distribution. # In other words: # It's NOT allowed to distribute any parts of this plugin or its source code in ANY way # to hardware which is NOT licensed by Dream Property GmbH. # It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way # on hardware which is NOT licensed by Dream Property GmbH. # # This applies to the source code as a whole as well as to parts of it, unless # explicitely stated otherwise. # # If you want to use or modify the code or parts of it, # you have to keep OUR license and inform us about the modifications, but it may NOT be # commercially distributed other than under the conditions noted above. # # As an exception regarding execution on hardware, you are permitted to execute this plugin on VU+ hardware # which is licensed by satco europe GmbH, if the VTi image is used on that hardware. # # As an exception regarding modifcations, you are NOT permitted to remove # any copy protections implemented in this plugin or change them for means of disabling # or working around the copy protections, unless the change has been explicitly permitted # by the original authors. Also decompiling and modification of the closed source # parts is NOT permitted. # # Advertising with this plugin is NOT allowed. # For other uses, permission from the authors is necessary. # ############################################################################################### from Plugins.Extensions.MediaPortal.plugin import _ from Plugins.Extensions.MediaPortal.resources.imports import * from Plugins.Extensions.MediaPortal.resources.choiceboxext import ChoiceBoxExt myagent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0' BASE_NAME = "WickedPictures.com" class wickedGenreScreen(MPScreen): def __init__(self, session): MPScreen.__init__(self, session, skin='MP_Plugin') self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "cancel" : self.keyCancel }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre:") self.genreliste = [] self.suchString = '' self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.genreliste.insert(0, ("Exclusive Girls", 'http://www.wicked.com/tour/pornstars/exclusive/', None)) self.genreliste.insert(0, ("Most Active Girls", 'http://www.wicked.com/tour/pornstars/mostactive/', None)) self.genreliste.insert(0, ("Most Liked Girls", 'http://www.wicked.com/tour/pornstars/mostliked/', None)) self.genreliste.insert(0, ("Most Recent Girls", 'http://www.wicked.com/tour/pornstars/mostrecent/', None)) self.genreliste.insert(0, ("Most Viewed Movies", 'http://www.wicked.com/tour/movies/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Movies", 'http://www.wicked.com/tour/movies/toprated/', None)) self.genreliste.insert(0, ("Latest Movies", 'http://www.wicked.com/tour/movies/latest/', None)) self.genreliste.insert(0, ("Most Viewed Scenes", 'http://www.wicked.com/tour/videos/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Scenes", 'http://www.wicked.com/tour/videos/toprated/', None)) self.genreliste.insert(0, ("Latest Scenes", 'http://www.wicked.com/tour/videos/latest/', None)) self.genreliste.insert(0, ("--- Search ---", "callSuchen", None)) self.ml.setList(map(self._defaultlistcenter, self.genreliste)) self.showInfos() def keyOK(self): if not config.mediaportal.premiumize_use.value: message = self.session.open(MessageBoxExt, _("%s only works with enabled MP premiumize.me option (MP Setup)!" % BASE_NAME), MessageBoxExt.TYPE_INFO, timeout=10) return Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] if Name == "--- Search ---": self.suchen() elif re.match(".*?Girls", Name): self.session.open(wickedGirlsScreen, Link, Name) else: self.session.open(wickedFilmScreen, Link, Name) def SuchenCallback(self, callback = None, entry = None): if callback is not None and len(callback): self.suchString = callback Name = "--- Search ---" Link = self.suchString.replace(' ', '-') self.session.open(wickedFilmScreen, Link, Name) class wickedGirlsScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 1 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def loadData(self, data): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') parse = re.search('class="showcase-models(.*?)</section>', data, re.S) Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-models.*?img\ssrc="(.*?)"\stitle="(.*?)".*?scenes">(\d+)\sScenes', parse.group(1), re.S) if Movies: for (Url, Image, Title, Scenes) in Movies: Url = "http://www.wicked.com" + Url Title = Title + " - %s Scenes" % Scenes self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No pornstars found!'), None, None)) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1] if Link: rangelist = [['Scenes', 'videos/'], ['Movies', 'movies/']] self.session.openWithCallback(self.keyOK2, ChoiceBoxExt, title=_('Select Action'), list = rangelist) def keyOK2(self, result): if result: Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] Link = Link + result[1] self.session.open(wickedFilmScreen, Link, Name) class wickedFilmScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 9 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] if re.match(".*?Search", self.Name): url = "http://www.wicked.com/tour/search/videos/%s/%s/" % (self.Link, str(self.page)) else: url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def loadData(self, data): if re.match(".*?Search", self.Name): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') elif re.match(".*?/tour/pornstar", self.Link): se
else: self['page'].setText(str(self.page) + ' / ' + str(self.lastpage)) parse = re.search('lass="showcase-movies">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-movies.*?img\ssrc="(.*?)"\salt=".*?"\stitle="(.*?)"', parse.group(1), re.S) else: parse = re.search('class="showcase-scenes">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-scenes.*?img\ssrc="(.*?)"\stitle=".*?"\salt="(.*?)"', parse.group(1), re.S) if Movies: for (Url, Image, Title) in Movies: Image = Image.replace('_2.jpg','_1.jpg') Url = "http://www.wicked.com" + Url self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No videos found!'), '', None, '')) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1] get_stream_link(self.session).check_link(Link, self.play) def play(self, url): title = self['liste'].getCurrent()[0][0] self.session.open(SimplePlayer, [(title, url.replace('%2F','%252F').replace('%3D','%253D').replace('%2B','%252B'))], showPlaylist=False, ltype='wicked')
lf.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)')
conditional_block
wicked.py
# -*- coding: utf-8 -*- ############################################################################################### # # MediaPortal for Dreambox OS # # Coded by MediaPortal Team (c) 2013-2017 # # This plugin is open source but it is NOT free software. # # This plugin may only be distributed to and executed on hardware which # is licensed by Dream Property GmbH. This includes commercial distribution. # In other words: # It's NOT allowed to distribute any parts of this plugin or its source code in ANY way # to hardware which is NOT licensed by Dream Property GmbH. # It's NOT allowed to execute this plugin and its source code or even parts of it in ANY way # on hardware which is NOT licensed by Dream Property GmbH. # # This applies to the source code as a whole as well as to parts of it, unless # explicitely stated otherwise. # # If you want to use or modify the code or parts of it, # you have to keep OUR license and inform us about the modifications, but it may NOT be # commercially distributed other than under the conditions noted above. # # As an exception regarding execution on hardware, you are permitted to execute this plugin on VU+ hardware # which is licensed by satco europe GmbH, if the VTi image is used on that hardware. # # As an exception regarding modifcations, you are NOT permitted to remove # any copy protections implemented in this plugin or change them for means of disabling # or working around the copy protections, unless the change has been explicitly permitted # by the original authors. Also decompiling and modification of the closed source # parts is NOT permitted. # # Advertising with this plugin is NOT allowed. # For other uses, permission from the authors is necessary. # ############################################################################################### from Plugins.Extensions.MediaPortal.plugin import _ from Plugins.Extensions.MediaPortal.resources.imports import * from Plugins.Extensions.MediaPortal.resources.choiceboxext import ChoiceBoxExt myagent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0' BASE_NAME = "WickedPictures.com" class wickedGenreScreen(MPScreen): def __init__(self, session): MPScreen.__init__(self, session, skin='MP_Plugin') self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "cancel" : self.keyCancel }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre:") self.genreliste = [] self.suchString = '' self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.genreliste.insert(0, ("Exclusive Girls", 'http://www.wicked.com/tour/pornstars/exclusive/', None)) self.genreliste.insert(0, ("Most Active Girls", 'http://www.wicked.com/tour/pornstars/mostactive/', None)) self.genreliste.insert(0, ("Most Liked Girls", 'http://www.wicked.com/tour/pornstars/mostliked/', None)) self.genreliste.insert(0, ("Most Recent Girls", 'http://www.wicked.com/tour/pornstars/mostrecent/', None)) self.genreliste.insert(0, ("Most Viewed Movies", 'http://www.wicked.com/tour/movies/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Movies", 'http://www.wicked.com/tour/movies/toprated/', None)) self.genreliste.insert(0, ("Latest Movies", 'http://www.wicked.com/tour/movies/latest/', None)) self.genreliste.insert(0, ("Most Viewed Scenes", 'http://www.wicked.com/tour/videos/mostviewed/', None)) self.genreliste.insert(0, ("Top Rated Scenes", 'http://www.wicked.com/tour/videos/toprated/', None)) self.genreliste.insert(0, ("Latest Scenes", 'http://www.wicked.com/tour/videos/latest/', None)) self.genreliste.insert(0, ("--- Search ---", "callSuchen", None)) self.ml.setList(map(self._defaultlistcenter, self.genreliste)) self.showInfos() def keyOK(self): if not config.mediaportal.premiumize_use.value: message = self.session.open(MessageBoxExt, _("%s only works with enabled MP premiumize.me option (MP Setup)!" % BASE_NAME), MessageBoxExt.TYPE_INFO, timeout=10) return Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] if Name == "--- Search ---": self.suchen() elif re.match(".*?Girls", Name): self.session.open(wickedGirlsScreen, Link, Name) else: self.session.open(wickedFilmScreen, Link, Name) def SuchenCallback(self, callback = None, entry = None): if callback is not None and len(callback): self.suchString = callback Name = "--- Search ---" Link = self.suchString.replace(' ', '-') self.session.open(wickedFilmScreen, Link, Name) class wickedGirlsScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 1 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def lo
elf, data): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') parse = re.search('class="showcase-models(.*?)</section>', data, re.S) Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-models.*?img\ssrc="(.*?)"\stitle="(.*?)".*?scenes">(\d+)\sScenes', parse.group(1), re.S) if Movies: for (Url, Image, Title, Scenes) in Movies: Url = "http://www.wicked.com" + Url Title = Title + " - %s Scenes" % Scenes self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No pornstars found!'), None, None)) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1] if Link: rangelist = [['Scenes', 'videos/'], ['Movies', 'movies/']] self.session.openWithCallback(self.keyOK2, ChoiceBoxExt, title=_('Select Action'), list = rangelist) def keyOK2(self, result): if result: Name = self['liste'].getCurrent()[0][0] Link = self['liste'].getCurrent()[0][1] Link = Link + result[1] self.session.open(wickedFilmScreen, Link, Name) class wickedFilmScreen(MPScreen, ThumbsHelper): def __init__(self, session, Link, Name): self.Link = Link self.Name = Name MPScreen.__init__(self, session, skin='MP_Plugin') ThumbsHelper.__init__(self) self["actions"] = ActionMap(["MP_Actions"], { "ok" : self.keyOK, "0" : self.closeAll, "cancel" : self.keyCancel, "5" : self.keyShowThumb, "up" : self.keyUp, "down" : self.keyDown, "right" : self.keyRight, "left" : self.keyLeft, "nextBouquet" : self.keyPageUp, "prevBouquet" : self.keyPageDown, "green" : self.keyPageNumber }, -1) self['title'] = Label(BASE_NAME) self['ContentTitle'] = Label("Genre: %s" % self.Name) self['F2'] = Label(_("Page")) self['Page'] = Label(_("Page:")) self.keyLocked = True self.page = 1 self.lastpage = 9 self.filmliste = [] self.ml = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent) self['liste'] = self.ml self.onLayoutFinish.append(self.loadPage) def loadPage(self): self.keyLocked = True self['name'].setText(_('Please wait...')) self.filmliste = [] if re.match(".*?Search", self.Name): url = "http://www.wicked.com/tour/search/videos/%s/%s/" % (self.Link, str(self.page)) else: url = "%s%s/" % (self.Link, str(self.page)) getPage(url, agent=myagent).addCallback(self.loadData).addErrback(self.dataError) def loadData(self, data): if re.match(".*?Search", self.Name): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') elif re.match(".*?/tour/pornstar", self.Link): self.getLastPage(data, 'class="paginationui-container(.*?)</ul>', '.*(?:\/|>)(\d+)') else: self['page'].setText(str(self.page) + ' / ' + str(self.lastpage)) parse = re.search('lass="showcase-movies">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-movies.*?img\ssrc="(.*?)"\salt=".*?"\stitle="(.*?)"', parse.group(1), re.S) else: parse = re.search('class="showcase-scenes">(.*?)</section>', data, re.S) if parse: Movies = re.findall('<a\shref="(.*?)"\sclass="showcase-scenes.*?img\ssrc="(.*?)"\stitle=".*?"\salt="(.*?)"', parse.group(1), re.S) if Movies: for (Url, Image, Title) in Movies: Image = Image.replace('_2.jpg','_1.jpg') Url = "http://www.wicked.com" + Url self.filmliste.append((decodeHtml(Title), Url, Image)) if len(self.filmliste) == 0: self.filmliste.append((_('No videos found!'), '', None, '')) self.ml.setList(map(self._defaultlistleft, self.filmliste)) self.ml.moveToIndex(0) self.keyLocked = False self.th_ThumbsQuery(self.filmliste, 0, 1, 2, None, None, self.page, int(self.lastpage), mode=1) self.showInfos() def showInfos(self): title = self['liste'].getCurrent()[0][0] pic = self['liste'].getCurrent()[0][2] self['name'].setText(title) CoverHelper(self['coverArt']).getCover(pic) def keyOK(self): if self.keyLocked: return Link = self['liste'].getCurrent()[0][1] get_stream_link(self.session).check_link(Link, self.play) def play(self, url): title = self['liste'].getCurrent()[0][0] self.session.open(SimplePlayer, [(title, url.replace('%2F','%252F').replace('%3D','%253D').replace('%2B','%252B'))], showPlaylist=False, ltype='wicked')
adData(s
identifier_name
config.py
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import re import json import inflection from os.path import exists, isfile from requests import RequestException from mycroft.util.json_helper import load_commented_json, merge_dict from mycroft.util.log import LOG from .locations import (DEFAULT_CONFIG, SYSTEM_CONFIG, USER_CONFIG, WEB_CONFIG_CACHE) def is_remote_list(values): ''' check if this list corresponds to a backend formatted collection of dictionaries ''' for v in values: if not isinstance(v, dict): return False if "@type" not in v.keys(): return False return True def translate_remote(config, setting): """ Translate config names from server to equivalents usable in mycroft-core. Args: config: base config to populate settings: remote settings to be translated """ IGNORED_SETTINGS = ["uuid", "@type", "active", "user", "device"] for k, v in setting.items(): if k not in IGNORED_SETTINGS: # Translate the CamelCase values stored remotely into the # Python-style names used within mycroft-core. key = inflection.underscore(re.sub(r"Setting(s)?", "", k)) if isinstance(v, dict): config[key] = config.get(key, {}) translate_remote(config[key], v) elif isinstance(v, list): if is_remote_list(v): if key not in config: config[key] = {} translate_list(config[key], v) else: config[key] = v else: config[key] = v def translate_list(config, values): """ Translate list formated by mycroft server. Args: config (dict): target config values (list): list from mycroft server config """ for v in values: module = v["@type"] if v.get("active"): config["module"] = module config[module] = config.get(module, {}) translate_remote(config[module], v) class LocalConf(dict): """ Config dict from file. """ def __init__(self, path): super(LocalConf, self).__init__() if path: self.path = path self.load_local(path) def load_local(self, path): """ Load local json file into self. Args: path (str): file to load """ if exists(path) and isfile(path): try: config = load_commented_json(path) for key in config: self.__setitem__(key, config[key]) LOG.debug("Configuration {} loaded".format(path)) except Exception as e: LOG.error("Error loading configuration '{}'".format(path)) LOG.error(repr(e)) else: LOG.debug("Configuration '{}' not defined, skipping".format(path)) def store(self, path=None):
def merge(self, conf): merge_dict(self, conf) class RemoteConf(LocalConf): """ Config dict fetched from mycroft.ai """ def __init__(self, cache=None): super(RemoteConf, self).__init__(None) cache = cache or WEB_CONFIG_CACHE from mycroft.api import is_paired if not is_paired(): self.load_local(cache) return try: # Here to avoid cyclic import from mycroft.api import DeviceApi api = DeviceApi() setting = api.get_settings() try: location = api.get_location() except RequestException as e: LOG.error("RequestException fetching remote location: {}" .format(str(e))) if exists(cache) and isfile(cache): location = load_commented_json(cache).get('location') if location: setting["location"] = location # Remove server specific entries config = {} translate_remote(config, setting) for key in config: self.__setitem__(key, config[key]) self.store(cache) except RequestException as e: LOG.error("RequestException fetching remote configuration: {}" .format(str(e))) self.load_local(cache) except Exception as e: LOG.error("Failed to fetch remote configuration: %s" % repr(e), exc_info=True) self.load_local(cache) class Configuration: __config = {} # Cached config __patch = {} # Patch config that skills can update to override config @staticmethod def get(configs=None, cache=True): """ Get configuration, returns cached instance if available otherwise builds a new configuration dict. Args: configs (list): List of configuration dicts cache (boolean): True if the result should be cached """ if Configuration.__config: return Configuration.__config else: return Configuration.load_config_stack(configs, cache) @staticmethod def load_config_stack(configs=None, cache=False): """ load a stack of config dicts into a single dict Args: configs (list): list of dicts to load cache (boolean): True if result should be cached Returns: merged dict of all configuration files """ if not configs: configs = [LocalConf(DEFAULT_CONFIG), RemoteConf(), LocalConf(SYSTEM_CONFIG), LocalConf(USER_CONFIG), Configuration.__patch] else: # Handle strings in stack for index, item in enumerate(configs): if isinstance(item, str): configs[index] = LocalConf(item) # Merge all configs into one base = {} for c in configs: merge_dict(base, c) # copy into cache if cache: Configuration.__config.clear() for key in base: Configuration.__config[key] = base[key] return Configuration.__config else: return base @staticmethod def set_config_update_handlers(bus): """Setup websocket handlers to update config. Args: bus: Message bus client instance """ bus.on("configuration.updated", Configuration.updated) bus.on("configuration.patch", Configuration.patch) @staticmethod def updated(message): """ handler for configuration.updated, triggers an update of cached config. """ Configuration.load_config_stack(cache=True) @staticmethod def patch(message): """ patch the volatile dict usable by skills Args: message: Messagebus message should contain a config in the data payload. """ config = message.data.get("config", {}) merge_dict(Configuration.__patch, config) Configuration.load_config_stack(cache=True)
""" Cache the received settings locally. The cache will be used if the remote is unreachable to load settings that are as close to the user's as possible """ path = path or self.path with open(path, 'w') as f: json.dump(self, f, indent=2)
identifier_body
config.py
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import re import json import inflection from os.path import exists, isfile from requests import RequestException from mycroft.util.json_helper import load_commented_json, merge_dict from mycroft.util.log import LOG from .locations import (DEFAULT_CONFIG, SYSTEM_CONFIG, USER_CONFIG, WEB_CONFIG_CACHE) def is_remote_list(values): ''' check if this list corresponds to a backend formatted collection of dictionaries ''' for v in values: if not isinstance(v, dict): return False if "@type" not in v.keys(): return False return True def translate_remote(config, setting): """ Translate config names from server to equivalents usable in mycroft-core. Args: config: base config to populate settings: remote settings to be translated """ IGNORED_SETTINGS = ["uuid", "@type", "active", "user", "device"] for k, v in setting.items(): if k not in IGNORED_SETTINGS: # Translate the CamelCase values stored remotely into the # Python-style names used within mycroft-core. key = inflection.underscore(re.sub(r"Setting(s)?", "", k)) if isinstance(v, dict): config[key] = config.get(key, {}) translate_remote(config[key], v) elif isinstance(v, list): if is_remote_list(v): if key not in config: config[key] = {} translate_list(config[key], v) else: config[key] = v else: config[key] = v def translate_list(config, values): """ Translate list formated by mycroft server. Args: config (dict): target config values (list): list from mycroft server config """ for v in values: module = v["@type"] if v.get("active"): config["module"] = module config[module] = config.get(module, {}) translate_remote(config[module], v) class LocalConf(dict): """ Config dict from file. """ def __init__(self, path): super(LocalConf, self).__init__() if path: self.path = path self.load_local(path) def load_local(self, path): """ Load local json file into self. Args: path (str): file to load """ if exists(path) and isfile(path): try: config = load_commented_json(path) for key in config: self.__setitem__(key, config[key]) LOG.debug("Configuration {} loaded".format(path)) except Exception as e: LOG.error("Error loading configuration '{}'".format(path)) LOG.error(repr(e)) else: LOG.debug("Configuration '{}' not defined, skipping".format(path)) def store(self, path=None): """ Cache the received settings locally. The cache will be used if the remote is unreachable to load settings that are as close to the user's as possible """ path = path or self.path with open(path, 'w') as f: json.dump(self, f, indent=2) def merge(self, conf): merge_dict(self, conf) class RemoteConf(LocalConf): """ Config dict fetched from mycroft.ai """ def __init__(self, cache=None): super(RemoteConf, self).__init__(None) cache = cache or WEB_CONFIG_CACHE from mycroft.api import is_paired if not is_paired(): self.load_local(cache) return try: # Here to avoid cyclic import from mycroft.api import DeviceApi api = DeviceApi() setting = api.get_settings() try: location = api.get_location() except RequestException as e: LOG.error("RequestException fetching remote location: {}" .format(str(e))) if exists(cache) and isfile(cache): location = load_commented_json(cache).get('location') if location: setting["location"] = location # Remove server specific entries config = {} translate_remote(config, setting) for key in config: self.__setitem__(key, config[key]) self.store(cache) except RequestException as e: LOG.error("RequestException fetching remote configuration: {}" .format(str(e))) self.load_local(cache) except Exception as e: LOG.error("Failed to fetch remote configuration: %s" % repr(e), exc_info=True) self.load_local(cache) class Configuration: __config = {} # Cached config
__patch = {} # Patch config that skills can update to override config @staticmethod def get(configs=None, cache=True): """ Get configuration, returns cached instance if available otherwise builds a new configuration dict. Args: configs (list): List of configuration dicts cache (boolean): True if the result should be cached """ if Configuration.__config: return Configuration.__config else: return Configuration.load_config_stack(configs, cache) @staticmethod def load_config_stack(configs=None, cache=False): """ load a stack of config dicts into a single dict Args: configs (list): list of dicts to load cache (boolean): True if result should be cached Returns: merged dict of all configuration files """ if not configs: configs = [LocalConf(DEFAULT_CONFIG), RemoteConf(), LocalConf(SYSTEM_CONFIG), LocalConf(USER_CONFIG), Configuration.__patch] else: # Handle strings in stack for index, item in enumerate(configs): if isinstance(item, str): configs[index] = LocalConf(item) # Merge all configs into one base = {} for c in configs: merge_dict(base, c) # copy into cache if cache: Configuration.__config.clear() for key in base: Configuration.__config[key] = base[key] return Configuration.__config else: return base @staticmethod def set_config_update_handlers(bus): """Setup websocket handlers to update config. Args: bus: Message bus client instance """ bus.on("configuration.updated", Configuration.updated) bus.on("configuration.patch", Configuration.patch) @staticmethod def updated(message): """ handler for configuration.updated, triggers an update of cached config. """ Configuration.load_config_stack(cache=True) @staticmethod def patch(message): """ patch the volatile dict usable by skills Args: message: Messagebus message should contain a config in the data payload. """ config = message.data.get("config", {}) merge_dict(Configuration.__patch, config) Configuration.load_config_stack(cache=True)
random_line_split
config.py
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import re import json import inflection from os.path import exists, isfile from requests import RequestException from mycroft.util.json_helper import load_commented_json, merge_dict from mycroft.util.log import LOG from .locations import (DEFAULT_CONFIG, SYSTEM_CONFIG, USER_CONFIG, WEB_CONFIG_CACHE) def is_remote_list(values): ''' check if this list corresponds to a backend formatted collection of dictionaries ''' for v in values: if not isinstance(v, dict): return False if "@type" not in v.keys(): return False return True def translate_remote(config, setting): """ Translate config names from server to equivalents usable in mycroft-core. Args: config: base config to populate settings: remote settings to be translated """ IGNORED_SETTINGS = ["uuid", "@type", "active", "user", "device"] for k, v in setting.items(): if k not in IGNORED_SETTINGS: # Translate the CamelCase values stored remotely into the # Python-style names used within mycroft-core. key = inflection.underscore(re.sub(r"Setting(s)?", "", k)) if isinstance(v, dict): config[key] = config.get(key, {}) translate_remote(config[key], v) elif isinstance(v, list): if is_remote_list(v): if key not in config: config[key] = {} translate_list(config[key], v) else: config[key] = v else: config[key] = v def translate_list(config, values): """ Translate list formated by mycroft server. Args: config (dict): target config values (list): list from mycroft server config """ for v in values: module = v["@type"] if v.get("active"): config["module"] = module config[module] = config.get(module, {}) translate_remote(config[module], v) class LocalConf(dict): """ Config dict from file. """ def __init__(self, path): super(LocalConf, self).__init__() if path: self.path = path self.load_local(path) def load_local(self, path): """ Load local json file into self. Args: path (str): file to load """ if exists(path) and isfile(path): try: config = load_commented_json(path) for key in config: self.__setitem__(key, config[key]) LOG.debug("Configuration {} loaded".format(path)) except Exception as e: LOG.error("Error loading configuration '{}'".format(path)) LOG.error(repr(e)) else: LOG.debug("Configuration '{}' not defined, skipping".format(path)) def store(self, path=None): """ Cache the received settings locally. The cache will be used if the remote is unreachable to load settings that are as close to the user's as possible """ path = path or self.path with open(path, 'w') as f: json.dump(self, f, indent=2) def merge(self, conf): merge_dict(self, conf) class RemoteConf(LocalConf): """ Config dict fetched from mycroft.ai """ def __init__(self, cache=None): super(RemoteConf, self).__init__(None) cache = cache or WEB_CONFIG_CACHE from mycroft.api import is_paired if not is_paired(): self.load_local(cache) return try: # Here to avoid cyclic import from mycroft.api import DeviceApi api = DeviceApi() setting = api.get_settings() try: location = api.get_location() except RequestException as e: LOG.error("RequestException fetching remote location: {}" .format(str(e))) if exists(cache) and isfile(cache):
if location: setting["location"] = location # Remove server specific entries config = {} translate_remote(config, setting) for key in config: self.__setitem__(key, config[key]) self.store(cache) except RequestException as e: LOG.error("RequestException fetching remote configuration: {}" .format(str(e))) self.load_local(cache) except Exception as e: LOG.error("Failed to fetch remote configuration: %s" % repr(e), exc_info=True) self.load_local(cache) class Configuration: __config = {} # Cached config __patch = {} # Patch config that skills can update to override config @staticmethod def get(configs=None, cache=True): """ Get configuration, returns cached instance if available otherwise builds a new configuration dict. Args: configs (list): List of configuration dicts cache (boolean): True if the result should be cached """ if Configuration.__config: return Configuration.__config else: return Configuration.load_config_stack(configs, cache) @staticmethod def load_config_stack(configs=None, cache=False): """ load a stack of config dicts into a single dict Args: configs (list): list of dicts to load cache (boolean): True if result should be cached Returns: merged dict of all configuration files """ if not configs: configs = [LocalConf(DEFAULT_CONFIG), RemoteConf(), LocalConf(SYSTEM_CONFIG), LocalConf(USER_CONFIG), Configuration.__patch] else: # Handle strings in stack for index, item in enumerate(configs): if isinstance(item, str): configs[index] = LocalConf(item) # Merge all configs into one base = {} for c in configs: merge_dict(base, c) # copy into cache if cache: Configuration.__config.clear() for key in base: Configuration.__config[key] = base[key] return Configuration.__config else: return base @staticmethod def set_config_update_handlers(bus): """Setup websocket handlers to update config. Args: bus: Message bus client instance """ bus.on("configuration.updated", Configuration.updated) bus.on("configuration.patch", Configuration.patch) @staticmethod def updated(message): """ handler for configuration.updated, triggers an update of cached config. """ Configuration.load_config_stack(cache=True) @staticmethod def patch(message): """ patch the volatile dict usable by skills Args: message: Messagebus message should contain a config in the data payload. """ config = message.data.get("config", {}) merge_dict(Configuration.__patch, config) Configuration.load_config_stack(cache=True)
location = load_commented_json(cache).get('location')
conditional_block